/// <summary>
 /// Copies the specified file path sources.
 /// </summary>
 /// <param name="filePathSources">The file path sources.</param>
 /// <param name="filePathDest">The file path dest.</param>
 /// <param name="move">if set to <c>true</c> [move].</param>
 /// <returns></returns>
 public static Dictionary<string, object> Cp( List<object> filePathSources, string filePathDest, bool move )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem cp" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string secPath = Main.PhysicalApplicationPath.Substring( 0, Main.PhysicalApplicationPath.Length - 1 );
     string path = "";
     string exSecMsg = "Access outside of physical site path not allowed";
     string strFtp = "ftp://";
     string strVSiteRoot = "~";
     string backSlash = "\\";
     try {
         using(Impersonation imp = new Impersonation()) {
             string dest = filePathDest.Replace("~", Main.PhysicalApplicationPath);
             foreach(string file in filePathSources as List<object>) {
                 if((!filePathDest.Contains(strFtp)) && (!file.Contains(strFtp))) {
                     /* if LOCAL to LOCAL */
                     string f = file.ToString().Replace(strVSiteRoot, Main.PhysicalApplicationPath);
                     /* both source and dest must be in the site */
                     if(Main.FileSystemAccess == FileSystemAccess.Site && ((!f.Contains(secPath) || !dest.Contains(secPath)))) {
                         Exception e = new Exception(exSecMsg);
                         throw e;
                     }
                     if(f.EndsWith(backSlash)) {
                         path = Path.GetDirectoryName(Path.GetDirectoryName(f));
                         string fName = Path.GetFileName(Path.GetDirectoryName(f));
                         string fDest = Path.Combine(dest, fName);
                         if(!move) {
                             if(!Directory.Exists(fDest)) {
                                 Directory.CreateDirectory(fDest);
                             }
                         }
                         RecursiveCopy(f, fDest, move);
                     } else {
                         path = Path.GetDirectoryName(f);
                         if(move) {
                             File.Move(f, Path.Combine(dest, Path.GetFileName(f)));
                         } else {
                             File.Copy(f, Path.Combine(dest, Path.GetFileName(f)));
                         }
                     }
                 }
             }
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     if( path.Length > 0 ) {
         Dictionary<string, object> l = Ls( path );
         return l;
     } else {
         return j;
     }
 }
Exemple #2
0
 /// <summary>
 /// Executes the image template.  This is a reciprecol function.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="imageTemplateId">The image template id.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public static System.Drawing.Bitmap ExecuteImageTemplate( System.Drawing.Bitmap image, string imageTemplateId, ref List<object> errors )
 {
     ( "FUNCTION /w SP,ADHOC executeImageTemplate" ).Debug( 10 );
     string commandText = @"select imagingTemplateDetailId, imagingTemplateId, name,
         description, script, language,filterOrder, enabled, template
         from imagingTemplateDetail
         where imagingTemplateId = @imagingTemplateId or imagingTemplateDetailId = @imagingTemplateId";
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand(commandText, cn)) {
                 cmd.Parameters.Add("@imagingTemplateId", SqlDbType.UniqueIdentifier).Value = new Guid(imageTemplateId.ToString());
                 using(SqlDataReader d = cmd.ExecuteReader()) {
                     if(d.HasRows) {
                         while(d.Read()) {
                             if(d.GetGuid(8) != Guid.Empty) {
                                 ExecuteImageTemplate(image, d.GetGuid(8).ToString(), ref errors);
                             } else {
                                 object[] args = { image };
                                 object obj = ExecuteScript(d.GetString(4), d.GetString(5), "script", "main", ref args, ref errors);
                                 if(errors.Count == 0) {
                                     if(obj.GetType() == typeof(System.Drawing.Bitmap)) {
                                         image = (System.Drawing.Bitmap)obj;
                                     } else {
                                         ("Error in template: " + d.GetGuid(1).ToString() +
                                         " Imaging script must return type System.Drawing.Bitmap.").Debug(1);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return image;
 }
Exemple #3
0
 /// <summary>
 /// Deletes an item image.
 /// </summary>
 /// <param name="args">{imageId}</param>
 /// <returns></returns>
 public static Dictionary<string, object> DeleteImage( Dictionary<string, object> args )
 {
     ( "FUNCTION /w SP,File System I/O,deleteImage" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string commandText = @"/* delete file list */
     select 'img\items\'+c.siteaddress+'\'+rtrim(itemNumber)+'\'+fileName from imagingDetail d  with (nolock)
     inner join site_configuration c with (nolock) on c.unique_siteID = d.unique_siteId
     where ImagingId = @imagingId
     union all
     select 'img\items\'+rtrim(itemNumber)+'\'+fileName from imaging with (nolock)
     /* remove records */
     delete from Imaging where imagingId = @imagingId;
     delete from ImagingDetail where imagingId = @imagingId;";
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand(commandText, cn)) {
                 cmd.Parameters.Add("@imagingId", SqlDbType.UniqueIdentifier).Value = new Guid(args["imagingId"].ToString());
                 using(SqlDataReader d = cmd.ExecuteReader()) {
                     while(d.Read()) {
                         string fileNameAndPath = Main.PhysicalApplicationPath + d.GetString(0);
                         if(File.Exists(fileNameAndPath)) {
                             File.Delete(fileNameAndPath);
                         }
                     }
                 }
             }
         }
     }
     /* return the new state of things */
     Dictionary<string, object> cmdargs = new Dictionary<string, object>();
     cmdargs.Add( "CommandText", "select imagingID,fileSize,fileName,thumbnail,thumbOrder,height,width from Imaging where itemnumber = \'' + instance.itemNumber + '\';" );
     return ( Dictionary<string, object> )Admin.GetSqlArray( cmdargs );
 }
Exemple #4
0
 /// <summary>
 /// Applies the imaging template.
 /// </summary>
 /// <param name="templateId">The template id.</param>
 /// <param name="img">The img.</param>
 /// <returns></returns>
 public static System.Drawing.Bitmap ApplyImageTemplate( string templateId, System.Drawing.Bitmap img )
 {
     ( "FUNCTION /w SP,binaryStream applyImageTemplate" ).Debug( 10 );
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand("select imagingTemplateDetailID,template from imagingTemplateDetail where enabled = 1 and imagingTemplateId = @imagingTemplateId order by filterOrder asc", cn)) {
                 cmd.Parameters.Add("@imagingTemplateId", SqlDbType.UniqueIdentifier).Value = new Guid(templateId.ToString());
                 using(SqlDataReader r = cmd.ExecuteReader()) {
                     if(r.HasRows) {
                         while(r.Read()) {
                             if(r.GetGuid(1) != Guid.Empty) {
                                 img = ApplyImageTemplate(r.GetGuid(1).ToString(), img);
                             } else {
                                 List<object> errors = new List<object>();
                                 img = ExecuteImageTemplate(img, r.GetGuid(0).ToString(), ref errors);
                                 if(errors.Count > 0) {
                                     foreach(Dictionary<string, object> d in errors) {
                                         String.Format(" --------------------------------------------------\n" +
                                         " Error:" + d["errorNumber"] + "\n" +
                                         " Description:" + d["errorText"] + "\n" +
                                         " Line:" + d["line"] + "\n" +
                                         " --------------------------------------------------").Debug(1);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 return img;
             }
         }
     }
 }
Exemple #5
0
 /// <summary>
 /// Adds an image from the specified path to the specified item.
 /// </summary>
 /// <param name="itemNumber">The item number.</param>
 /// <param name="pathToImage">The path to image.</param>
 /// <returns></returns>
 public static Dictionary<string, object> AddItemImage( string itemNumber, string pathToImage )
 {
     ( "FUNCTION /w SP,ADHOC,fileSystem addItemImage" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     using(Impersonation imp = new Impersonation()) {
         if(File.Exists(pathToImage)) {
             if(pathToImage.ToLower().EndsWith("jpg") || pathToImage.ToLower().EndsWith("gif") || pathToImage.ToLower().EndsWith("png")) {
                 /*
                     select
                     ImagingDetailID, ImagingID, unique_siteID, height, width, itemnumber, filename, locationType, VerCol
                     from ImagingDetail
                  *
                  */
                 /* copy the image to its final resting spot */
                 Guid imageId = Guid.NewGuid();
                 if(!Directory.Exists(Main.PhysicalApplicationPath + "img")) {
                     Directory.CreateDirectory(Main.PhysicalApplicationPath + "img");
                 }
                 if(!Directory.Exists(Main.PhysicalApplicationPath + "img\\items")) {
                     Directory.CreateDirectory(Main.PhysicalApplicationPath + "img\\items");
                 }
                 if(!Directory.Exists(Main.PhysicalApplicationPath + "img\\items\\" + itemNumber)) {
                     Directory.CreateDirectory(Main.PhysicalApplicationPath + "img\\items\\" + itemNumber);
                 }
                 string fileName = Path.GetFileName(pathToImage);
                 string fileExt = Path.GetExtension(fileName);
                 string newFileName = imageId.ToFileName() + fileExt;
                 string newFilePath = Main.PhysicalApplicationPath + "img\\items\\" + itemNumber + "\\" + newFileName;
                 File.Copy(pathToImage, newFilePath);
                 using(System.Drawing.Bitmap img = new System.Drawing.Bitmap(newFilePath)) {
                     FileInfo f = new FileInfo(newFilePath);
                     using(SqlConnection cn = Site.CreateConnection(true, true)) {
                         cn.Open();
                         /* insert record into 'master' table */
                         using(SqlCommand cmd = new SqlCommand("dbo.addItemImage @imagingID,@itemnumber,@filesize,@filename,@thumbnail,@width,@height,@thumborder", cn)) {
                             cmd.Parameters.Add("@imagingId", SqlDbType.UniqueIdentifier).Value = new Guid(imageId.ToString());
                             cmd.Parameters.Add("@itemnumber", SqlDbType.VarChar).Value = itemNumber;
                             cmd.Parameters.Add("@filesize", SqlDbType.BigInt).Value = f.Length;
                             cmd.Parameters.Add("@filename", SqlDbType.VarChar).Value = fileName;
                             cmd.Parameters.Add("@thumbnail", SqlDbType.Bit).Value = 1;
                             cmd.Parameters.Add("@width", SqlDbType.BigInt).Value = img.Height;
                             cmd.Parameters.Add("@height", SqlDbType.BigInt).Value = img.Width;
                             cmd.Parameters.Add("@thumborder", SqlDbType.Bit).Value = -1;
                             cmd.ExecuteNonQuery();
                         }
                     }
                 }
                 /* refresh */
                 Main.Site.ItemImages = new Commerce.ItemImages(Main.Site);
                 j = RefreshAllItemImages(itemNumber);
                 return j;
             } else {
                 j.Add("error", -2);
                 j.Add("description", "Only png, jpg, or gif images can be selected.");
             }
         } else {
             j.Add("error", -1);
             j.Add("description", "File does not exist");
         }
     }
     return j;
 }
Exemple #6
0
        /// <summary>
        /// Previews the gallery cropping.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="cropX">The crop X.</param>
        /// <param name="cropY">The crop Y.</param>
        /// <param name="cropW">The crop W.</param>
        /// <param name="cropH">The crop H.</param>
        /// <param name="imageX">The image X.</param>
        /// <param name="imageY">The image Y.</param>
        /// <param name="imageW">The image W.</param>
        /// <param name="imageH">The image H.</param>
        /// <param name="destW">The dest W.</param>
        /// <param name="destH">The dest H.</param>
        /// <returns></returns>
        public static string PreviewGalleryCropping( string sourcePath, Int64 cropX, Int64 cropY,
		Int64 cropW, Int64 cropH, Int64 imageX, Int64 imageY, Int64 imageW, Int64 imageH, Int64 destW, Int64 destH )
        {
            /* make sure the temp directory exists */
            if(!Directory.Exists(Main.PhysicalApplicationPath + "temp/")) {
                Directory.CreateDirectory(Main.PhysicalApplicationPath + "temp/");
            }
            string fileName = Guid.NewGuid().ToFileName();
            string fileExt = Path.GetExtension(sourcePath);
            string filePath = Main.PhysicalApplicationPath + "temp/" + fileName + fileExt;
            using(Impersonation imp = new Impersonation()) {
                /* set 10 mintue Timer then delete the preview generated */
                Timer deleteTimer = new Timer(10000);
                deleteTimer.elapsed += new EventHandler(delegate(object obj, EventArgs e) {
                    if(File.Exists(filePath)) {
                        File.Delete(filePath);
                    }
                });
                if(File.Exists(sourcePath)) {
                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(sourcePath);
                    bmp = GalleryCrop(bmp, cropX, cropY, cropW, cropH, imageX, imageY, imageW, imageH, destW, destH);
                    bmp.Save(filePath);
                }
            }
            return "temp/" + fileName + fileExt;
        }
 /// <summary>
 /// Recursively copy.
 /// </summary>
 /// <param name="sourceFolder">The source folder.</param>
 /// <param name="destFolder">The dest folder.</param>
 /// <param name="move">if set to <c>true</c> [move].</param>
 public static void RecursiveCopy( string sourceFolder, string destFolder, bool move )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem recursiveCopy" ).Debug( 10 );
     if(Main.FileSystemAccess == FileSystemAccess.Site &&
         (!sourceFolder.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
         Exception e = new Exception("Access outside of physical site path not allowed");
         throw e;
     }
     using(Impersonation imp = new Impersonation()) {
         if(move) {
             Directory.Move(sourceFolder, destFolder);
         } else {
             if(!Directory.Exists(destFolder))
                 Directory.CreateDirectory(destFolder);
             string[] files = Directory.GetFiles(sourceFolder);
             foreach(string file in files) {
                 string name = Path.GetFileName(file);
                 string dest = Path.Combine(destFolder, name);
                 File.Copy(file, dest);
             }
             string[] folders = Directory.GetDirectories(sourceFolder);
             foreach(string folder in folders) {
                 string name = Path.GetFileName(folder);
                 string dest = Path.Combine(destFolder, name);
                 RecursiveCopy(folder, dest, move);
             }
         }
     }
 }
Exemple #8
0
 /// <summary>
 /// Previews a single filter in a filter template.
 /// </summary>
 /// <param name="templateDetailId">The template detail id.</param>
 /// <param name="sampleImage">The sample image.</param>
 /// <param name="binaryOutput">if set to <c>true</c> [binary output].</param>
 /// <returns></returns>
 public static Dictionary<string, object> PreviewTemplateDetail( string templateDetailId, string sampleImage, bool binaryOutput )
 {
     ( "FUNCTION /w fileSystem previewTemplateDetail" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     // resrouce file in source path /js/admin/img/test_pattern.png
     byte[] buffer = getSampleImage();
     MemoryStream fms = new MemoryStream( buffer );
     System.Drawing.Bitmap img = ( System.Drawing.Bitmap )System.Drawing.Bitmap.FromStream( fms );
     List<object> errors = new List<object>();
     try {
         using(Impersonation imp = new Impersonation()) {
             img = ExecuteImageTemplate(img, templateDetailId, ref errors);
             if(errors.Count != 0) {
                 j.Add("error", -2);
                 j.Add("description", "One or more scripts generated errors.");
                 j.Add("errors", errors);
                 return j;
             }
         }
     } catch( Exception e ) {
         if( e.InnerException != null ) {
             j.Add( "description", "Internal server error: " + e.InnerException.Source + ": " + e.InnerException.Message );
         } else {
             j.Add( "description", "Internal server error: " + e.Source + ": " + e.Message );
         }
         return j;
     }
     Guid g = Guid.NewGuid();
     string tempFileName = "temp\\" + g.ToString() + ".jpg";
     if( !binaryOutput ) {
         using(Impersonation imp = new Impersonation()) {
             img.Save(Main.PhysicalApplicationPath + tempFileName);
         }
         Dictionary<string, object> ii = new Dictionary<string, object>();
         FileInfo f = new FileInfo( Main.PhysicalApplicationPath + tempFileName );
         ii.Add( "height", img.Height );
         ii.Add( "width", img.Width );
         ii.Add( "size", f.Length );
         j.Add( "imageInfo", ii );
         j.Add( "image", tempFileName.Replace( "\\", "/" ) );
         j.Add( "error", 0 );
         j.Add( "description", "" );
     } else {
         using( MemoryStream ms = new MemoryStream() ) {
             img.Save( ms, System.Drawing.Imaging.ImageFormat.Png );
             HttpContext.Current.Response.Clear();
             HttpContext.Current.Response.ContentType = "image/png";
             HttpContext.Current.Response.AddHeader( "Expires", "0" );/* RFC 2616 14.21 Content has already expired */
             HttpContext.Current.Response.AddHeader( "Cache-Control", "no-store" );/* RFC 2616 14.9.2 Don't ever cache */
             HttpContext.Current.Response.AddHeader( "Pragma", "no-store" );/* RFC 2616 14.32 Pragma - same as cache control */
             ms.WriteTo( HttpContext.Current.Response.OutputStream );
         }
         img.Dispose();
         HttpContext.Current.Response.Flush();
         HttpContext.Current.ApplicationInstance.CompleteRequest();
     }
     return j;
 }
 /// <summary>
 /// List recursivly the specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns>JSON Object</returns>
 public static Dictionary<string, object> LsRecursive( string path )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem ls_recursive" ).Debug( 10 );
     Dictionary<string, object> fd = new Dictionary<string, object>();
     try {
         if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
             Exception e = new Exception("Access outside of physical site path not allowed");
             throw e;
         }
         using(Impersonation imp = new Impersonation()) {
             string[] dirs = Directory.GetDirectories(path.Replace("~", Main.PhysicalApplicationPath));
             foreach(string dir in dirs) {
                 if(Main.FileSystemAccess == FileSystemAccess.Site && (!dir.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                     Exception e = new Exception("Access outside of physical site path not allowed");
                     throw e;
                 }
                 fd.Add("name", dir);
                 fd.Add("size", 0);
                 fd.Add("creationTime", File.GetCreationTime(dir).ToString("mm/dd/yy hh:mm:ss"));
                 fd.Add("lastAccessTime", File.GetLastAccessTime(dir).ToString("mm/dd/yy hh:mm:ss"));
                 fd.Add("lastWriteTime", File.GetLastWriteTime(dir).ToString("mm/dd/yy hh:mm:ss"));
                 fd.Add("objectType", "directory");
                 fd.Add("path", LsRecursive(dir));
             }
         }
     } catch( Exception e ) {
         if( e.GetType().FullName == "System.UnauthorizedAccessException" ) {
             fd.Add( "name", path + " <restricted>" );
             fd.Add( "size", 0 );
             fd.Add( "creationTime", DateTime.MinValue.ToString( "mm/dd/yy hh:mm:ss" ) );
             fd.Add( "lastAccessTime", DateTime.MinValue.ToString( "mm/dd/yy hh:mm:ss" ) );
             fd.Add( "lastWriteTime", DateTime.MinValue.ToString( "mm/dd/yy hh:mm:ss" ) );
             fd.Add( "objectType", "directory" );
         }
     }
     return fd;
 }
Exemple #10
0
 /// <summary>
 /// creates the specified new dir path.
 /// </summary>
 /// <param name="newDirPath">The new dir path.</param>
 /// <returns></returns>
 public static Dictionary<string, object> MkDir( string newDirPath )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem mkdir" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string path = "";
     try {
         using(Impersonation imp = new Impersonation()) {
             path = Path.GetFullPath(newDirPath.Replace("~", Main.PhysicalApplicationPath));
             if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                 Exception e = new Exception("Access outside of physical site path not allowed");
                 throw e;
             }
             if(!Directory.Exists(path)) {
                 Directory.CreateDirectory(path);
                 j.Add("description", "");
             } else {
                 j.Add("description", "Directory already exists.");
             }
             j.Add("error", 0);
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     if( path.Length > 0 ) {
         Dictionary<string, object> l = Ls( path );
         return l;
     }
     return j;
 }
Exemple #11
0
 /// <summary>
 /// List the specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 public static Dictionary<string, object> Ls( string path )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem ls" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     ArrayList dirs = new ArrayList();
     ArrayList files = new ArrayList();
     List<object> f = new List<object>();
     Dictionary<string, object> up = new Dictionary<string, object>();
     try {
         using(Impersonation imp = new Impersonation()) {
             if(path.Length == 0) {
                 string targetDirectory = Main.PhysicalApplicationPath;
                 if(Main.GetCurrentSession().UserId == -1) {
                     targetDirectory += "user\\public";
                     if(!Directory.Exists(targetDirectory)) {
                         Directory.CreateDirectory(targetDirectory);
                     }
                 } else {
                     targetDirectory += "user\\" + Convert.ToString(Main.GetCurrentSession().UserId);
                     if(!Directory.Exists(targetDirectory)) {
                         Directory.CreateDirectory(targetDirectory);
                     }
                 }
                 /*
                  * this seems like it woulbe be cool, but really it isn't
                  * so lets just put this here
                  * */
                 path = Main.PhysicalApplicationPath;
             }
             if(path.StartsWith("/")) {
                 path = path.TrimStart('/');
             }
             /* trim ending slash */
             if(path.EndsWith("\\")) {
                 path = path.Substring(0, path.Length - 1);
             }
             if(!path.Contains(":")) {
                 path = Main.PhysicalApplicationPath + path.Replace("/", "\\");
             }
             if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                 Exception e = new Exception("Access outside of physical site path not allowed");
                 throw e;
             }
             files.AddRange(Directory.GetFiles(path));
             dirs.AddRange(Directory.GetDirectories(path));
             if(path.Length > 3) {
                 up.Add("name", path + "\\..");
                 up.Add("size", 0);
                 up.Add("creationTime", "");
                 up.Add("lastAccessTime", "");
                 up.Add("lastWriteTime", "");
                 up.Add("objectType", "directory");
                 f.Add(up);
             }
             foreach(string dir in dirs) {
                 Dictionary<string, object> fd = new Dictionary<string, object>();
                 fd.Add("name", dir);
                 fd.Add("size", 0);
                 fd.Add("creationTime", File.GetCreationTime(dir));
                 fd.Add("lastAccessTime", File.GetLastAccessTime(dir));
                 fd.Add("lastWriteTime", File.GetLastWriteTime(dir));
                 fd.Add("objectType", "directory");
                 f.Add(fd);
             }
             foreach(string file in files) {
                 /* for some reason some files are listed that are not actually there
                  * for instance C:\WebDev.WebServer20.EXE shows in the list
                  * but is not in the directory.  */
                 try {
                     Dictionary<string, object> fd = new Dictionary<string, object>();
                     fd.Add("name", file);
                     FileInfo info = new FileInfo(file);
                     fd.Add("size", info.Length);
                     fd.Add("creationTime", info.CreationTime);
                     fd.Add("lastAccessTime", info.LastAccessTime);
                     fd.Add("lastWriteTime", info.LastWriteTime);
                     fd.Add("objectType", info.Extension);
                     f.Add(fd);
                 } catch{ }
             }
             j.Add("files", f);
             j.Add("error", 0);
             j.Add("description", "");
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     return j;
 }
Exemple #12
0
        /// <summary>
        /// Handles file uploads, supplies a progress meter using class ProgressInfo.
        /// </summary>
        public static void Iis6Upload()
        {
            ( "FUNCTION /w SP,ADHOC,fileSystem,binaryStream upload" ).Debug( 10 );
            Dictionary<string, object> j = new Dictionary<string, object>();
            string uploadId = HttpContext.Current.Request.QueryString[ "uploadId" ];
            string explicitTarget = HttpContext.Current.Request.QueryString[ "target" ];
            string targetDirectory = Main.PhysicalApplicationPath;
            string userRootDir = targetDirectory + "\\user\\";
            string userDir = targetDirectory + "\\user\\" + Convert.ToString( Session.CurrentSession.UserId );
            string publicDir = targetDirectory + "\\user\\public";
            string tempDir = targetDirectory + "\\temp";
            if( !Directory.Exists( userRootDir ) ) {
                Directory.CreateDirectory( userRootDir );
            }
            if( !Directory.Exists( tempDir ) ) {
                Directory.CreateDirectory( tempDir );
            }
            if(Session.CurrentSession.UserId == -1) {
                targetDirectory = publicDir;
                if( !Directory.Exists( publicDir ) ) {
                    Directory.CreateDirectory( publicDir );
                }
            } else {
                targetDirectory = userDir;
                if( !Directory.Exists( userDir ) ) {
                    Directory.CreateDirectory( userDir );
                }
            }
            if( explicitTarget.Length > 0 ) {
                if( Directory.Exists( explicitTarget ) ) {
                    targetDirectory = explicitTarget;
                }
            }
            const int BUFFER_SIZE = 16384;
            /* find the raw request */
            HttpWorkerRequest request = ( HttpWorkerRequest )HttpContext.Current.GetType().GetProperty( "WorkerRequest", ( BindingFlags )36 ).GetValue( HttpContext.Current, null );
            string contentType = HttpContext.Current.Request.ContentType;
            if( contentType.Contains( "multipart/form-data" ) ) {
                using(Impersonation imp = new Impersonation()) {
                    Guid id = new Guid(uploadId);
                    ProgressInfo u = new ProgressInfo(id);
                    if(!Main.ProgressInfos.ContainsKey(id)) {
                        Main.ProgressInfos.Add(id, u);
                    } else {
                        Main.ProgressInfos[id] = u;
                    }
                    string boundary = contentType.Substring(contentType.IndexOf("boundary=") + 9);
                    List<string> delList = new List<string>();
                    byte[] binBoundary = System.Text.Encoding.UTF8.GetBytes(boundary);
                    byte[] binFileNameProp = System.Text.Encoding.UTF8.GetBytes("filename=\"");
                    u.TotalItemSize = Convert.ToInt32(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
                    u.CurrentItemName = "multipart/form-data stream";
                    if(u.TotalItemSize < 0) {
                        u.Complete = true;
                        return;
                    }; /* over size */
                    u.CurrentSizeComplete = 0;
                    int bytes = BUFFER_SIZE;
                    byte[] buffer = new byte[BUFFER_SIZE];
                    Guid tempFileId = System.Guid.NewGuid();
                    buffer.Equals(buffer);
                    byte[] body = request.GetPreloadedEntityBody();
                    u.CurrentSizeComplete += body.Length;
                    string tempFile = Main.PhysicalApplicationPath + "\\temp\\temp_" + tempFileId.ToString() + ".tmp";
                    delList.Add(tempFile);
                    try {
                        long tickCount = Environment.TickCount;
                        long tickTimeout = 1000;
                        u.Started = DateTime.Now;
                        using(FileStream fs = File.Create(tempFile)) {
                            fs.Write(body, 0, body.Length);
                            if(!request.IsEntireEntityBodyIsPreloaded()) {
                                while((u.TotalItemSize - u.CurrentSizeComplete) >= bytes) {
                                    bytes = request.ReadEntityBody(buffer, buffer.Length);
                                    u.CurrentSizeComplete += bytes;
                                    u.Updated = DateTime.Now;
                                    fs.Write(buffer, 0, bytes);
                                    if(bytes > 0) {
                                        tickCount = Environment.TickCount;
                                    }
                                    if(Environment.TickCount - tickCount > tickTimeout) {
                                        ("HTTP client tick timedout during upload.").Debug(4);
                                        u.Complete = true;
                                        File.Delete(tempFile);
                                        return;
                                    }
                                }
                                bytes = request.ReadEntityBody(buffer, (u.TotalItemSize - u.CurrentSizeComplete));
                                fs.Write(buffer, 0, bytes);
                                u.CurrentSizeComplete += bytes;
                            }
                        }
                        /* file(s) downloaded now parse the request file */
                        List<long> boundaries = new List<long>();
                        List<long> fileNames = new List<long>();
                        long boundaryLength = binBoundary.Length;
                        long bufferSize = 10240;
                        using(FileStream fs = File.OpenRead(tempFile)) {
                            boundaries = fs.Find(binBoundary, 0);/*get all the boundraies in the upload*/
                            List<string> tmpFilePaths = new List<string>();
                            u.TotalItemSize = Convert.ToInt32(fs.Length);
                            for(var x = 0; boundaries.Count - 1 > x; x++) {
                                byte[] cBuffer = new byte[bufferSize];
                                string fileName = "";
                                long endAt = 0;
                                long headerEndsAt = 0;
                                string destFilePath = Main.PhysicalApplicationPath + "\\temp\\temp_" + tempFileId.ToString() + "___" + Convert.ToString(x) + ".tmp";
                                if(boundaries.Count - 1 == x) {
                                    endAt = fs.Length;
                                } else {
                                    endAt = boundaries[x + 1];
                                }
                                using(FileStream ds = File.Create(destFilePath)) {
                                    u.CurrentSizeComplete = Convert.ToInt32(boundaries[x]);
                                    fs.Position = boundaries[x];
                                    headerEndsAt = fs.FindFirst(new byte[4] { 13, 10, 13, 10 }, boundaries[x]) + 6;
                                    fs.Position = boundaries[x];
                                    byte[] headerBytes = new byte[headerEndsAt - boundaries[x]];
                                    bytes = fs.Read(headerBytes, 0, headerBytes.Length);
                                    string header = System.Text.Encoding.UTF8.GetString(headerBytes);
                                    int filenameStart = header.IndexOf("filename=\"") + 10;
                                    int filenameEnds = header.IndexOf("\"", filenameStart);
                                    fileName = header.Substring(filenameStart, (filenameEnds - filenameStart));
                                    u.CurrentItemName = fileName;
                                    /* move to the end of the header */
                                    fs.Position = headerEndsAt;
                                    /*copy the data from the sumission temp file into the finished temp file*/
                                    bytes = 1;
                                    long dataLength = endAt - headerEndsAt;
                                    long readIn = 0;
                                    int remainder = Convert.ToInt32(dataLength % cBuffer.Length);
                                    if(dataLength > cBuffer.Length) {
                                        while((readIn + cBuffer.Length) < dataLength) {
                                            bytes = fs.Read(cBuffer, 0, cBuffer.Length);
                                            ds.Write(cBuffer, 0, cBuffer.Length);
                                            readIn += cBuffer.Length;
                                        }
                                    } else {
                                        remainder = Convert.ToInt32(dataLength);
                                    }
                                    if(remainder > 0) {
                                        fs.Read(cBuffer, 0, remainder);
                                        ds.Write(cBuffer, 0, remainder);
                                    }
                                    if(fileName.Length > 0 && filenameStart > 9) {
                                        tmpFilePaths.Add(destFilePath + "|" + fileName);
                                    }
                                    delList.Add(destFilePath);
                                }
                            }
                            for(var y = 0; tmpFilePaths.Count > y; y++) {
                                string tempFileLocation = tmpFilePaths[y].Split('|')[0];
                                string orgFileNameWithExt = tmpFilePaths[y].Split('|')[1];
                                string orgFileExt = Path.GetExtension(orgFileNameWithExt);
                                string orgFileName = Path.GetFileNameWithoutExtension(orgFileNameWithExt);
                                string newFileName = orgFileName;
                                string newFileNameWithExt = orgFileName + orgFileExt;
                                int f = 0;
                                while(File.Exists(Path.Combine(targetDirectory, newFileNameWithExt))) {
                                    newFileNameWithExt = newFileName + "(" + Convert.ToString(f + 1) + ")" + orgFileExt;
                                    f++;
                                }
                                File.Move(tempFileLocation, Path.Combine(targetDirectory, newFileNameWithExt));
                                u.UploadedFiles.Add(Path.Combine(targetDirectory, newFileNameWithExt));
                            }
                        }
                        for(var y = 0; delList.Count > y; y++) {
                            File.Delete(delList[y]);
                        }
                        u.Complete = true;
                    } catch(Exception e) {
                        (e.Message).Debug(0);
                        u.Complete = true;
                        for(var y = 0; delList.Count > y; y++) {
                            File.Delete(delList[y]);
                        }
                    }
                }
            }
            try {
                HttpContext.Current.Response.Redirect( Main.AdminDirectory + "/js/blank.html" );
                request.FlushResponse( true );
                request.EndOfRequest();
                request.CloseConnection();
            } finally {

            }
            return;
        }
 /// <summary>
 /// Site startup.
 /// </summary>
 /// <param name="sender">The sender.</param>
 public void Init( HttpApplication sender )
 {
     HttpApplication _app = (HttpApplication)sender;
     /* set defaults for static properties
      * and subscribe to events
      */
     InitSetMainDefaults(_app);
     /* bind all HTTPModule event handlers
      * this should be done EVERYTIME the httpApplication fires init*/
     _app.BeginRequest += new EventHandler(BeginRequest);
     _app.EndRequest += new EventHandler(OnEndRequest);
     _app.Error += new EventHandler(OnAppError);
     /* if the site hasn't picked a thread to start on yet then THIS is the thread
      * this should be done once per httpApplication instance
      * init is called once per thread
      */
     if( State == SiteState.NotYetStarted ) {
         /* prevent addtional startups */
         State = SiteState.BeginingStartup;
         try {
             /* first thing load the site config to get impersonation info */
             TrustLevel = getCurrentTrustLevel();
             if(!(TrustLevel == AspNetHostingPermissionLevel.Unrestricted
             || TrustLevel == AspNetHostingPermissionLevel.High)) {
                 System.Security.SecurityException ex = new System.Security.SecurityException(
                 String.Format("Rendition.dll requires AspNetHostingPermissionLevel High or Full.  The current level is {0}",
                 TrustLevel.ToString()));
                 throw ex;
             }
             Site.SiteConfiguration baseConfig = Main.getBaseConfig();
             LoadConfig(baseConfig);
             /* start logging */
             using (Impersonation imp = new Impersonation()) {
                 if (debug == null) {
                     string logPath = Main.PhysicalApplicationPath + "log\\debug.txt";
                     /* try and move the old log file first */
                     if (File.Exists(logPath)) {
                         try {
                             File.Move(logPath, Path.GetDirectoryName(logPath) + "\\" + DateTime.Now.ToString("MM.dd.yyyy-HH.mm.ss") + ".txt");
                         } catch { }
                     }
                     debug = new Logger(logPath);
                 }
                 IISVersion = getIISVersion();
                 if (!Directory.Exists(Main.PhysicalApplicationPath + "log\\")) {
                     Directory.CreateDirectory(Main.PhysicalApplicationPath + "log\\");
                 }
             }
             /* allow for lookup of assemblies embedded into the dll */
             AppDomain.CurrentDomain.AssemblyResolve += resolveEmbeddedAssembiles;
             /* start the site if it hasn't started on any thread yet */
             if(Main.Site == null) {
                 Main.Site = new Site(baseConfig);
             }
             /* let all other threads in this process know the site has finished starting up */
             State = SiteState.Started;
             ("Waiting for connections...").Debug(8);
         } catch(Exception ex) {
             ex = getInnermostException(ex);
             State = SiteState.CannotStart;
             CannotStartException = ex;
             ("Cannot Start Site => " + ex.Message).Debug(0);
             ErrorPage(HttpContext.Current, 500, ex.Message);
         }
     }
 }
Exemple #14
0
 /// <summary>
 /// Gets an image from a path and streams the content to the current HttpContext
 /// </summary>
 /// <param name="imagePath">The image path.</param>
 /// <returns></returns>
 public static void GetImageStream( string imagePath )
 {
     using(Impersonation imp = new Impersonation()) {
         try {
             if(!File.Exists(imagePath)) {
                 // throw image exception
                 FileNotFoundException ex = new FileNotFoundException(String.Format("File was not found",imagePath));
                 throw ex;
             }
             using(System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(imagePath)) {
                 OutputPNGMemoryStream(bmp);
             }
         } catch(Exception e) {
             OutputPNGMemoryStream(imageExceptionPicture(e));
         }
     }
     HttpContext.Current.Response.Flush();
     HttpContext.Current.ApplicationInstance.CompleteRequest();
 }
Exemple #15
0
 /// <summary>
 /// deletes the specified file paths.
 /// </summary>
 /// <param name="filePaths">The file paths.</param>
 /// <returns></returns>
 public static Dictionary<string, object> Rm( List<object> filePaths )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem rm" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string path = "";
     bool isDirectory = false;
     string showPathWhenDone = "";
     try {
         using(Impersonation imp = new Impersonation()) {
             foreach(string file in filePaths as List<object>) {
                 isDirectory = Directory.Exists(file);
                 path = Path.GetDirectoryName(file.Replace("~", Main.PhysicalApplicationPath));
                 if(!isDirectory) {
                     showPathWhenDone = path;
                 } else {
                     DirectoryInfo di = new DirectoryInfo(path);
                     showPathWhenDone = di.Parent.FullName;
                 }
                 if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                     Exception e = new Exception("Access outside of physical site path not allowed");
                     throw e;
                 }
                 /* is this a file or directory ? */
                 if(isDirectory) {
                     /* delete this directory tree */
                     Directory.Delete(file, true);
                 } else {
                     /* delete this file */
                     File.Delete(file);
                 }
             }
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
         return j;
     }
     if( path.Length > 0 ) {
         Dictionary<string, object> l = Ls(showPathWhenDone);
         return l;
     }
     j.Add( "error", -2 );
     j.Add( "source", "unknown" );
     j.Add( "description", "an unknown error has occured" );
     return j;
 }
Exemple #16
0
 /// <summary>
 /// Previews a template.
 /// </summary>
 /// <param name="templateId">The template id.</param>
 /// <param name="sampleImage">Path to the sample image.</param>
 /// <param name="binaryOutput">if set to <c>true</c> [binary output].</param>
 /// <returns></returns>
 public static Dictionary<string, object> PreviewTemplate( string templateId, string sampleImage, bool binaryOutput )
 {
     ( "FUNCTION /w SP,binaryStream previewTemplate" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     using(Impersonation imp = new Impersonation()) {
         byte[] buffer = getSampleImage();
         MemoryStream fms = new MemoryStream(buffer);
         System.Drawing.Bitmap img = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(fms);
         try {
             img = ApplyImageTemplate(templateId, img);
         } catch(Exception e) {
             if(e.InnerException != null) {
                 j.Add("description", "Internal server error: " + e.InnerException.Source + ": " + e.InnerException.Message);
             } else {
                 j.Add("description", "Internal server error: " + e.Source + ": " + e.Message);
             }
             return j;
         }
         Guid g = Guid.NewGuid();
         string tempRootDir = Main.TempDirectory.Replace("~/", Main.PhysicalApplicationPath);
         if(!Directory.Exists(tempRootDir)) {
             Directory.CreateDirectory(tempRootDir);
         }
         string tempFileNameAndPath = tempRootDir + "\\" + g.ToString() + ".jpg";
         if(!binaryOutput) {
             using(Impersonation p = new Impersonation()) {
                 img.Save(tempFileNameAndPath);
             }
             Dictionary<string, object> ii = new Dictionary<string, object>();
             FileInfo f = new FileInfo(tempFileNameAndPath);
             ii.Add("height", img.Height);
             ii.Add("width", img.Width);
             ii.Add("size", f.Length);
             j.Add("imageInfo", ii);
             j.Add("image", Main.TempDirectory.Replace("~/", "") + "/" + Path.GetFileName(tempFileNameAndPath));
             j.Add("error", 0);
             j.Add("description", "");
         } else {
             using(MemoryStream ms = new MemoryStream()) {
                 img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                 HttpContext.Current.Response.Clear();
                 HttpContext.Current.Response.ContentType = "image/png";
                 HttpContext.Current.Response.AddHeader("Expires", "0");/* RFC 2616 14.21 Content has already expired */
                 HttpContext.Current.Response.AddHeader("Cache-Control", "no-store");/* RFC 2616 14.9.2 Don't ever cache */
                 HttpContext.Current.Response.AddHeader("Pragma", "no-store");/* RFC 2616 14.32 Pragma - same as cache control */
                 ms.WriteTo(HttpContext.Current.Response.OutputStream);
             }
             img.Dispose();
             HttpContext.Current.Response.Flush();
             HttpContext.Current.ApplicationInstance.CompleteRequest();
         }
     }
     return j;
 }
Exemple #17
0
 /// <summary>
 /// Renames the specified file name.
 /// </summary>
 /// <param name="oldName">Full path to the old name.</param>
 /// <param name="newName">Full path to the new name.</param>
 /// <returns>Dictionary the new names directory.</returns>
 public static Dictionary<string, object> Rn( string oldName, string newName )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem rn" ).Debug( 10 );
     int error = 0;
     try {
         if( Main.FileSystemAccess == FileSystemAccess.Site && ( !oldName.Contains( Main.PhysicalApplicationPath.Substring( 0, Main.PhysicalApplicationPath.Length - 1 ) ) ) ) {
             Exception e = new Exception( "Access outside of physical site path not allowed" );
             error = -1;
             throw e;
         }
         if( Main.FileSystemAccess == FileSystemAccess.Site && ( !newName.Contains( Main.PhysicalApplicationPath.Substring( 0, Main.PhysicalApplicationPath.Length - 1 ) ) ) ) {
             Exception e = new Exception( "Access outside of physical site path not allowed" );
             error = -2;
             throw e;
         }
         using(Impersonation imp = new Impersonation()) {
             if(File.Exists(oldName)) {
                 if(!File.Exists(newName)) {
                     File.Move(oldName, newName);
                 } else {
                     Exception e = new Exception("A file with that name already exists.");
                     error = -3;
                     throw e;
                 }
             } else {
                 Exception e = new Exception("Source file does not exist.");
                 error = -4;
                 throw e;
             }
         }
     } catch( Exception e ) {
         Dictionary<string, object> j = new Dictionary<string, object>();
         if( error == 0 ) { error = -5; };
         j.Add( "error", error );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     Dictionary<string, object> l = Ls( Path.GetDirectoryName( newName ) );
     return l;
 }
Exemple #18
0
        /// <summary>
        /// Refreshes the item images.
        /// </summary>
        /// <param name="itemNumber">The item number.</param>
        /// <param name="locationArray">The location array.</param>
        /// <param name="uniqueSiteId">The unique site id.</param>
        /// <param name="onlyRenderThisImageId">The only render this image id.  Render all when Guid.Empty.</param>
        /// <returns></returns>
        public static Dictionary<string, object> RefreshItemImages( string itemNumber, string[] locationArray,
		Guid uniqueSiteId, Guid onlyRenderThisImageId )
        {
            Dictionary<string, object> j = new Dictionary<string, object>();
            string[] als = { "m", "c", "f", "t", "a", "x", "y", "z", "b", "d" };
            string[] ls = new string[ ( int )Utilities.Iif( locationArray.Length == 0, als.Length, locationArray.Length ) ];
            if( locationArray.Length != 0 ) {
                locationArray.CopyTo( ls, 0 );
            } else {
                als.CopyTo( ls, 0 );
            }
            using(Impersonation imp = new Impersonation()) {
                foreach(SiteImagePlaceholder p in Main.Site.SiteImagePlaceholders.List) {
                    if(uniqueSiteId == p.SiteId || uniqueSiteId == Guid.Empty) {
                        List<Commerce.Image> current = Main.Site.ItemImages.List.FindAll(delegate(Commerce.Image img) {
                            return img.ItemNumber == itemNumber;
                        });
                        foreach(Commerce.Image r in current) {
                            if((onlyRenderThisImageId != Guid.Empty) && onlyRenderThisImageId != r.Id) {
                                continue;
                            }
                            string fileExt = Path.GetExtension(r.FileName);
                            string filePath = Main.PhysicalApplicationPath + "img\\items\\" + itemNumber + "\\" + r.Id.ToFileName() +
                            fileExt;
                            string oldStyleFilePath = "";
                            /* check for an older style file path */
                            if(!File.Exists(filePath)) {
                                oldStyleFilePath = Main.PhysicalApplicationPath + "img\\items\\" + itemNumber + "\\" + r.Id.ToString().Replace("-", "_") + r.FileName +
                                fileExt;
                            }
                            if(!File.Exists(filePath) && oldStyleFilePath == "") {
                                j.Add("error", -5);
                                j.Add("description", "Source file does not exist.");
                                return j;
                            }
                            if(oldStyleFilePath.Length != 0) {
                                filePath = oldStyleFilePath;
                            }
                            if(!File.Exists(filePath)) {
                                Exception ex = new Exception(
                                    String.Format("Source file is missing. Path: {0}, Item: {1}, ImageId: {2} ",
                                        filePath,
                                        itemNumber,
                                        r.Id
                                    )
                                );
                                throw ex;
                            }
                            System.Drawing.Bitmap img = new System.Drawing.Bitmap(filePath);
                            foreach(string l in ls) {
                                Guid templateId = p.ImageTypes[l];
                                Guid imagingDetailId = Guid.NewGuid();
                                Guid imagingId = r.Id;
                                System.Drawing.Bitmap target = (System.Drawing.Bitmap)img.Clone();
                                try {
                                    target = ApplyImageTemplate(templateId.ToString(), target);
                                } catch(Exception e) {
                                    j.Add("error", -2);
                                    j.Add("description", e.Message);
                                }
                                string targetFileName = imagingDetailId.ToFileName() + fileExt;
                                string targetPath = Main.PhysicalApplicationPath + "img\\items\\" + p.SiteAddress + "\\" + itemNumber;
                                if(!Directory.Exists(targetPath)) {
                                    Directory.CreateDirectory(targetPath);
                                }
                                if(fileExt == "png") {
                                    target.Save(targetPath + "\\" + targetFileName, System.Drawing.Imaging.ImageFormat.Png);
                                } else {
                                    target.SaveJpg(targetPath + "\\" + targetFileName, Main.Compression);
                                }
                                using(SqlConnection cn = Site.CreateConnection(true, true)) {
                                    cn.Open();
                                    using(SqlCommand cmd = new SqlCommand("dbo.insertItemImageDetail @imagingDetailId,@imagingId,@unique_siteId,@itemnumber,@width,@height,@fileName,@locationType", cn)) {
                                        cmd.Parameters.Add("@imagingDetailId", SqlDbType.UniqueIdentifier).Value = new Guid(imagingDetailId.ToString());
                                        cmd.Parameters.Add("@imagingId", SqlDbType.UniqueIdentifier).Value = new Guid(imagingId.ToString());
                                        cmd.Parameters.Add("@unique_siteId", SqlDbType.UniqueIdentifier).Value = new Guid(p.SiteId.ToString());
                                        cmd.Parameters.Add("@itemnumber", SqlDbType.VarChar).Value = itemNumber;
                                        cmd.Parameters.Add("@width", SqlDbType.BigInt).Value = target.Height;
                                        cmd.Parameters.Add("@height", SqlDbType.BigInt).Value = target.Width;
                                        cmd.Parameters.Add("@fileName", SqlDbType.VarChar).Value = targetFileName;
                                        cmd.Parameters.Add("@locationType", SqlDbType.VarChar).Value = l;
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                                target.Dispose();
                            }
                            /* load new images into the site's in-memory cache */
                            Main.Site.RenderedImages = new Commerce.RenderedImages(Main.Site);
                            Main.Site.ItemImages = new Commerce.ItemImages(Main.Site);
                            /* refresh lists loaded into this item. */
                            Main.Site.Items.GetItemByItemNumber(itemNumber).RefreshImages(Main.Site);
                        }
                    }
                }
            }
            j.Add( "error", 0 );
            j.Add( "description", "" );
            return j;
        }
Exemple #19
0
 /// <summary>
 /// Saves text of a file at the specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <param name="encoding">The encoding.</param>
 /// <param name="text">The text.</param>
 /// <param name="lastWriteTime">The last write time.</param>
 /// <param name="override_warning">if set to <c>true</c> [override_warning].</param>
 /// <returns>
 /// JSON Object
 /// </returns>
 public static Dictionary<string, object> SaveFileText(string path, string encoding, string text, string lastWriteTime, bool override_warning)
 {
     ("FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem SaveFileText").Debug(10);
     //convert virtual paths into real paths
     if(path.StartsWith("~/")) {
         path = HttpContext.Current.Request.MapPath(path);
     }
     Dictionary<string, object> fd = new Dictionary<string, object>();
     FileInfo info = new FileInfo(path);
     if(Main.FileSystemAccess == FileSystemAccess.Site && (!info.FullName.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
         Exception e = new Exception("Access outside of physical site path not allowed");
         throw e;
     }
     using(Impersonation imp = new Impersonation()) {
         File.WriteAllText(path, text);
     }
     fd.Add("creationTime", info.CreationTime.ToString("mm/dd/yy hh:mm:ss"));
     fd.Add("lastAccessTime", info.LastAccessTime.ToString("mm/dd/yy hh:mm:ss"));
     fd.Add("lastWriteTime", info.LastWriteTime.ToString("mm/dd/yy hh:mm:ss"));
     fd.Add("extension", info.Extension);
     fd.Add("fullName", info.FullName);
     fd.Add("name", info.Name);
     fd.Add("size", info.Length);
     fd.Add("directoryName", info.DirectoryName);
     fd.Add("error", "0");
     fd.Add("description", "");
     return fd;
 }
Exemple #20
0
 /// <summary>
 /// Renders the template images.  Updates an ProgressInfo matching progressInfoId parameter.
 /// </summary>
 /// <param name="templateId">The template id.</param>
 /// <param name="progressInfoId">The progress info id.</param>
 /// <returns></returns>
 public static List<object> RenderTemplateImages( string templateId, string progressInfoId )
 {
     Guid id = new Guid( progressInfoId );
     ProgressInfo u = new ProgressInfo( id );
     if( !Main.ProgressInfos.ContainsKey( id ) ) {
         Main.ProgressInfos.Add( id, u );
     } else {
         Main.ProgressInfos[ id ] = u;
     }
     u.CurrentItemName = "Starting";
     u.TotalItemCount = 0;
     u.Started = DateTime.Now;
     ( "FUNCTION /w SP renderTemplateImages" ).Debug( 10 );
     List<object> l = new List<object>();
     List<object> entries = new List<object>();
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand("getTemplateUsage @templateId", cn)) {
                 cmd.Parameters.Add("@templateId", SqlDbType.UniqueIdentifier).Value = new Guid(templateId.ToString());
                 using(SqlDataReader d = cmd.ExecuteReader()) {
                     if(d.HasRows) {
                         while(d.Read()) {
                             foreach(Commerce.Item i in Main.Site.Items.List) {
                                 u.TotalItemCount++;
                                 string[] ls = { d.GetString(1) };
                                 List<object> f = new List<object>();
                                 f.Add(i.ItemNumber);
                                 f.Add(ls);
                                 f.Add(d.GetGuid(0));
                                 entries.Add(f);
                             }
                         }
                     }
                 }
             }
         }
         foreach(List<object> entry in entries) {
             l.Add(RefreshItemImages(((string)entry[0]), ((string[])entry[1]), ((Guid)(entry[2])), Guid.Empty));
             u.CurrentItemCount++;
             u.Updated = DateTime.Now;
             u.CurrentItemName = ((string)entry[0]);
         }
     }
     u.Complete = true;
     return l;
 }
Exemple #21
0
 /// <summary>
 /// Renders the image gallery.
 /// </summary>
 /// <param name="_galleryId">The _gallery id.</param>
 /// <param name="progressInfoId">The progress info id.</param>
 /// <returns></returns>
 public static Dictionary<string, object> RenderImageGallery( string _galleryId, string progressInfoId )
 {
     ( "FUNCTION /w SP,fileSystem renderImageGallery" ).Debug( 10 );
     Guid id = new Guid( progressInfoId );
     ProgressInfo u = new ProgressInfo( id );
     if( !Main.ProgressInfos.ContainsKey( id ) ) {
         Main.ProgressInfos.Add( id, u );
     } else {
         Main.ProgressInfos[ id ] = u;
     }
     u.CurrentItemName = "Calculating work size please wait...";
     u.TotalItemCount = 0;
     u.Started = DateTime.Now;
     Dictionary<string, object> j = new Dictionary<string, object>();
     List<object> errors = new List<object>();
     j.Add( "error", 0 );
     j.Add( "description", "" );
     List<Dictionary<Int64, object>> entries = new List<Dictionary<Int64, object>>();
     try {
         using(Impersonation imp = new Impersonation()) {
             Guid galleryId = new Guid(_galleryId);
             using(SqlConnection cn = Site.CreateConnection(true, true)) {
                 cn.Open();
                 using(SqlCommand cmd = new SqlCommand("getRotatorCategory @imageRotatorCategoryId", cn)) {
                     cmd.Parameters.Add("@imageRotatorCategoryId", SqlDbType.UniqueIdentifier).Value = new Guid(galleryId.ToString());
                     using(SqlDataReader d = cmd.ExecuteReader()) {
                         while(d.Read()) {
                             Dictionary<Int64, object> i = new Dictionary<Int64, object>();
                             i.Add(1, d.GetString(1));
                             i.Add(2, (Int64)d.GetInt32(2));
                             i.Add(3, (Int64)d.GetInt32(3));
                             i.Add(5, d.GetGuid(5));
                             i.Add(6, d.GetGuid(6));
                             i.Add(7, d.GetGuid(7));
                             i.Add(8, d.GetGuid(8));
                             i.Add(9, d.GetGuid(9));
                             i.Add(15, d.GetString(15));
                             i.Add(14, d.GetGuid(14));
                             i.Add(18, (Int64)d.GetInt32(18));
                             i.Add(19, (Int64)d.GetInt32(19));
                             i.Add(20, (Int64)d.GetInt32(20));
                             i.Add(21, (Int64)d.GetInt32(21));
                             i.Add(22, (Int64)d.GetInt32(22));
                             i.Add(23, (Int64)d.GetInt32(23));
                             i.Add(24, (Int64)d.GetInt32(24));
                             i.Add(25, (Int64)d.GetInt32(25));
                             entries.Add(i);
                             u.CurrentItemName = String.Format("Adding item {0}", Path.GetFileName((string)i[15]));
                             u.TotalItemCount++;
                         }
                     }
                 }
             }
             u.CurrentItemCount = 0;
             foreach(Dictionary<Int64, object> i in entries) {
                 u.CurrentItemName = String.Format("Working on item {0}", Path.GetFileName((string)i[15]));
                 u.CurrentItemCount++;
                 string categoryDirectory = Main.PhysicalApplicationPath + "img\\gallery\\" + i[1];
                 string srcFilePath = (string)i[15];
                 string outputFileName = ((Guid)i[14]).ToFileName();
                 /* create gallery directory */
                 if(!Directory.Exists(categoryDirectory)) {
                     Directory.CreateDirectory(categoryDirectory);
                 }
                 /* get the input file */
                 using(System.Drawing.Bitmap srcImg = new System.Drawing.Bitmap(srcFilePath)) {
                     /* for each type of image create a file with a special suffix */
                     /* the rotator template is special, it gets the gallery method then the rotator template */
                     System.Drawing.Bitmap b;
                     using(b = (System.Drawing.Bitmap)srcImg.Clone()) {
                         b = Admin.GalleryCrop(b, (Int64)i[18], (Int64)i[19], (Int64)i[21], (Int64)i[20],
                         (Int64)i[22], (Int64)i[23], (Int64)i[25], (Int64)i[24], (Int64)i[3], (Int64)i[2]);
                         b = Admin.ExecuteImageTemplate(b, i[5].ToString(), ref errors);/*5=rotator template */
                         b.SaveJpg(categoryDirectory + "\\" + outputFileName + "r.jpg", 90L);
                     }
                     using(b = (System.Drawing.Bitmap)srcImg.Clone()) {
                         b = Admin.ExecuteImageTemplate(b, i[6].ToString(), ref errors);/*6=thumb template */
                         b.SaveJpg(categoryDirectory + "\\" + outputFileName + "t.jpg", 90L);
                     }
                     using(b = (System.Drawing.Bitmap)srcImg.Clone()) {
                         b = Admin.ExecuteImageTemplate(b, i[7].ToString(), ref errors);/*7=fullsize template */
                         b.SaveJpg(categoryDirectory + "\\" + outputFileName + "f.jpg", 90L);
                     }
                     using(b = (System.Drawing.Bitmap)srcImg.Clone()) {
                         b = Admin.ExecuteImageTemplate(b, i[8].ToString(), ref errors);/*8=portfolio template */
                         b.SaveJpg(categoryDirectory + "\\" + outputFileName + "p.jpg", 90L);
                     }
                     using(b = (System.Drawing.Bitmap)srcImg.Clone()) {
                         b = Admin.ExecuteImageTemplate(b, i[9].ToString(), ref errors);/*9=Blog template */
                         b.SaveJpg(categoryDirectory + "\\" + outputFileName + "b.jpg", 90L);
                     }
                 }
             }
             u.Complete = true;
         }
     } catch( Exception e ) {
         j[ "error" ] = -1;
         j[ "description" ] = e.Message;
     }
     if( errors.Count > 0 ) {
         j[ "error" ] = -2;
         j[ "description" ] = errors;
     }
     return j;
 }