Beispiel #1
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;
        }
Beispiel #2
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;
 }
Beispiel #3
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;
 }