Monday, May 28, 2012

[Sample of May 13th] Show file upload status in ASP.NET

[Sample of May 13th] Show file upload status in ASP.NET:

Homepage image
Sample of the Day RSS Feed
Sample Downloads: http://code.msdn.microsoft.com/CSASPNETFileUploadStatus-5ff0194f 
Today’s sample demostrate how to show the file upload status based on AJAX without a third part component like ActiveX control, Flash or Silverlight.  It's also a solution for big file uploading.
imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

Introduction

The project illustrates how to show the file upload status based on AJAX without a third part component like ActiveX control, Flash or Silverlight.  It's also a solution for big file uploading.

How it works

When a file is uploading, the server will get the request data like below.   (P.S. we can get this part when we upload a file by a tool like Fiddler.)
 
/*---------Sample reference Start------*/
POST http://jerrywengserver/UploadControls.aspx'>http://jerrywengserver/UploadControls.aspx HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml,
       image/gif, image/pjpeg, application/x-ms-xbap,
        application/x-shockwave-flash, */*
Referer: http://jerrywengserver/UploadControls.aspx'>http://jerrywengserver/UploadControls.aspx
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64;
            Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;
            .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8;
            .NET4.0C; .NET4.0E)
Content-Type: multipart/form-data; boundary=---------------------------7da106f207ba
Accept-Encoding: gzip, deflate
Host: jerrywengserver
Content-Length: 1488
Connection: Keep-Alive
Pragma: no-cache
 
-----------------------------7da106f207ba
Content-Disposition: form-data; name="__VIEWSTATE"
 
/wEPDwUKMTI3MTMxMTcxNw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkcrWP136t6D4d+g8BDfyR5WF+aP/yi4YARRyuOuRsO1M=
-----------------------------7da106f207ba
Content-Disposition: form-data; name="__EVENTVALIDATION"
 
/wEWAgL5mtyRBALt3oXMA9W4TniGaEKs/xcWf28H93S+wRcfLHr35wNo+N1v9gQ5
-----------------------------7da106f207ba
Content-Disposition: form-data; name="fuFile"; filename="C:\******\FileUploadTest.txt"
Content-Type: text/plain
 
*****This part is the content of the uploaed file!*****
-----------------------------7da106f207ba
Content-Disposition: form-data; name="btnUpload"
 
Upload
-----------------------------7da106f207ba--
/*---------Sample reference End-----*/
 
There are some useful information in the head part, for example,
  The content-Type of this request.
  The boundary which seperate the body part.
  The content-length of this request.
  Some request variables.
  The filename of the uploaded file and its content-type.
 
If we analyze the data, we can find some tips like below.
  1. All the request data is sperated by a boundary which is defined in the content-type of the head part.
  2. The name and the value of one parameter is seperated by a newline.
  3. If the parameter is a file, we can get the filename and content-type of the file
  4. The data of the file followed the content-type of the file.
 
So when the server has got all these data, the uploading will be finished. The prolem left here is how can we get to know that how much data the server had read and is there a way that we can control the length which the server read by one time.
 
For IIS and .Net Framework, we can control this by a HTTPModule.  Data reading will be started in BeginRequest event. And the HttpWorkerRequest class could control the reading process.
 
We can use HttpWorkerRequest.GetPreloadedEntityBody() to get the first part of the request data which the server read. If the data is too large, HttpWorkerRequest.IsEntireEntityBodyIsPreloaded will return false, we can use HttpWorkerRequest.ReadEntityBody() to read the left data. By this way, we can know how much data loaded and how much left. At last, we need to send the status back to the server, here I store the status to the Cache.
 
Another important issue is how the client side get the status from the server side without postback to the server. The answer is to use AJAX feature. Here we use ICallBackEventHandler, because it is easy to handle and clear enough for us to understand the process. We can learn how to use it from the reference at the bottom of this readme file. We can also use jQuery ajax to call back a web service or generic handler to get the status.
 

Running the Sample

Step 1. Build the website "WSFileUploadStatus".
 
Step 2. View the Default.aspx in the browser.
 
Step 3. Select a file which you want to test the sample.
 
Step 4. Click Upload button. And you will see the upload status in details.

Using the Code

Step 1.  Create a C# Code Project in Visual Studio 2010 or Visual Web Developer 2010. Name it as UploadStatus.
 
Step 2.  Add the two references into the project, System.Web.Extension and System.Web.
 
Step 3.  Copy the code from the UploadStatus.cs from the sample folder, "FileUploadStatus".
 
Step 4.  Add an ASP.NET Module and named it as UploadProcessModule.
 
Step 5.  Copy the code from the UploadProcessModule.cs in the sample folder, "FileUploadStatus".
 
Step 6.  Also create the files: BinaryHelper.cs, UploadFile.cs, UploadFileCollection.cs and FileUploadDataManager.cs, and copy the codes.
 
Step 7.  Save and Build the project.
[Caution] Be sure the project is released on "ANY CPU". We can't add this project reference which is x86 version to the website
deployed on an x64 system platform.
 
Step 8.  Add a new Empty ASP.NET WebSite into the solution, name it as WSFileUploadStatus.
 
Step 9.  Add the project reference, "UploadStatus", which we created at first.
 
Step 10.  Create a new Web User Control named as UploadStatusWindow.ascx. We will use this user control to hold a Popup window to show the status information. Copy the markups from the UploadStatusWindow.ascx in the sample folder, "WSFileUploadStatus".
 
Step 11. Create an ASP.NET web page named as UploadControls.aspx. Add one FileUpload web control and one Button web control into the page. Copy the markups from UploadControls.aspx in the sample folder, "WSFileUploadStatus".
 
Step 12. Create an ASP.NET web page named as Deafult.aspx. Add an iframe into the page. Set the src to "UploadControls.aspx". Copy the javascript function and markups from the Default.aspx in the sample folder, "WSFileUploadStatus".
 
Step 13. Copy the follow two folders in the sapmle folder into the website, "styles" and "scripts".
 
Step 14. Modify the web.config. Register the HttpModule. Set the maxRequestLength to 1048576, means max request data will be limited to 1GB. If we delpoy the website to IIS7, we need set the requestLimits in the system.webServer block.
 
Step 15. Make sure we have made the page same as the sample. Build the solution.
 
Step 16. Test the site.

More Information

MSDN: HttpModules
 http://msdn.microsoft.com/en-us/library/zec9k340(VS.71).aspx
 
MSDN: HttpWorkerRequest Class
 http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.aspx
 
MSDN: ICallBackEventHandler Interface
 http://msdn.microsoft.com/en-us/library/system.web.ui.icallbackeventhandler.aspx
 
MSDN: An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET
 http://msdn.microsoft.com/en-us/library/bb299886.aspx
 
MSDN: JavaScriptSerializer Class
 http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

[Sample of May 14th] Image slideshow in full screen mode

[Sample of May 14th] Image slideshow in full screen mode:

Homepage image
Sample of the Day RSS Feed
Sample Downloads: http://code.msdn.microsoft.com/CSImageFullScreenSlideShow-79e29568 
Today’s sample demonstrates how to display image slideshow in a Windows Forms application. It also shows how to enter the full screen mode to slide-show images. The sample was written by our sample writer: Jason Wang.
imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

Introduction

The sample demonstrates how to display image slideshow in a Windows Forms application.  It also shows how to enter the full screen mode to slide-show images.

Running the Sample

Step1. Build and run the sample project in Visual Studio 2010.
Step2. Prepare some image files.  Click the "Open Folder..." button and select the path which includes image files.
Step3. Click "Previous" button and "Next" button to make image files displayed in order.
 
Step4. Left-click the "Settings" button and select the internal between the displayed image files for Timer control in order to display them with a fixed interval time. Finally, left-click the "Start Slideshow" button to make the image files displayed one by one.
 
Step5. Left-click the "Full Screen" button to display images in the full screen mode.  Press the "ESC" key to leave the full screen mode.

Using the Code

1. When user selects the root folder of image files, the sample enumerates the image files in the folder using the stack-based iteration method demonstrated in this MSDN article: http://msdn.microsoft.com/en-us/library/bb513869.aspx
The sample does not use Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); to enumerate the files because it will abort when the user does not have access permissions for certain directories or files in the root folder.
public static string[] GetFiles(string path, string searchPattern)
        {
            string[] patterns = searchPattern.Split(';');
            List<string> files = new List<string>();
            foreach (string filter in patterns)
            {
                // Iterate through the directory tree and ignore the 
               // DirectoryNotFoundException or UnauthorizedAccessException 
               // exceptions. 
               // http://msdn.microsoft.com/en-us/library/bb513869.aspx'>http://msdn.microsoft.com/en-us/library/bb513869.aspx'>http://msdn.microsoft.com/en-us/library/bb513869.aspx'>http://msdn.microsoft.com/en-us/library/bb513869.aspx
 
               // Data structure to hold names of subfolders to be
                // examined for files.
                Stack<string> dirs = new Stack<string>(20);
 
               if (!Directory.Exists(path))
                {
                    throw new ArgumentException();
                }
                dirs.Push(path);
 
               while (dirs.Count > 0)
                {
                    string currentDir = dirs.Pop();
                    string[] subDirs;
                    try
                    {
                        subDirs = Directory.GetDirectories(currentDir);
                    }
                    // An UnauthorizedAccessException exception will be thrown 
                   // if we do not have discovery permission on a folder or 
                   // file. It may or may not be acceptable to ignore the 
                   // exception and continue enumerating the remaining files 
                   // and folders. It is also possible (but unlikely) that a 
                   // DirectoryNotFound exception will be raised. This will 
                   // happen if currentDir has been deleted by another 
                   // application or thread after our call to Directory.Exists. 
                   // The choice of which exceptions to catch depends entirely 
                   // on the specific task you are intending to perform and 
                   // also on how much you know with certainty about the 
                   // systems on which this code will run.
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }
                    catch (DirectoryNotFoundException)
                    {
                        continue;
                    }
 
                   try
                    {
                        files.AddRange(Directory.GetFiles(currentDir, filter));
                    }
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }
                    catch (DirectoryNotFoundException)
                    {
                        continue;
                    }
 
                   // Push the subdirectories onto the stack for traversal.
                    // This could also be done before handing the files.
                    foreach (string str in subDirs)
                    {
                        dirs.Push(str);
                    }
                }
            }
 
           return files.ToArray();
        }
 


2. The sample displays the images in a PictureBox.

/// <summary>
        /// Show the image in the PictureBox.
        /// </summary>
        public static void ShowImage(string path, PictureBox pct)
        {
            pct.ImageLocation = path;
        }
 
       /// <summary>
        /// Show the previous image.
        /// </summary>
        private void ShowPrevImage()
        {
            ShowImage(this.imageFiles[(--this.selected) % this.imageFiles.Length], this.pictureBox);
        }
 
       /// <summary>
        /// Show the next image.
        /// </summary>
        private void ShowNextImage()
        {
            ShowImage(this.imageFiles[(++this.selected) % this.imageFiles.Length], this.pictureBox);
        }
 


A timer is used to automatically slideshow the images.

/// <summary>
        /// Show the next image at every regular intervals.
        /// </summary>
        private void timer_Tick(object sender, EventArgs e)
        {
            ShowNextImage();
        }
 


2. To slide-show images in the full-screen mode, the sample provides a helper class 'FullScreen'. FullScreen.cs contains two public methods:

EnterFullScreen - used to make a Windows Form display in the full screen.

LeaveFullScreen - used to restore a Windows Form to its original state.

/// <summary>
        /// Maximize the window to the full screen.
        /// </summary>
        public void EnterFullScreen(Form targetForm)
        {
            if (!IsFullScreen)
            {
                Save(targetForm);  // Save the original form state.
 
               targetForm.WindowState = FormWindowState.Maximized;
                targetForm.FormBorderStyle = FormBorderStyle.None;
                targetForm.TopMost = true;
                targetForm.Bounds = Screen.GetBounds(targetForm);
 
               IsFullScreen = true;
            }
        }
 
       /// <summary>
        /// Leave the full screen mode and restore the original window state.
        /// </summary>
        public void LeaveFullScreen(Form targetForm)
        {
            if (IsFullScreen)
            {
                // Restore the original Window state.
                targetForm.WindowState = winState;
                targetForm.FormBorderStyle = brdStyle;
                targetForm.TopMost = topMost;
                targetForm.Bounds = bounds;
 
               IsFullScreen = false;
            }
        }
 


More Information


How to: Iterate Through a Directory Tree (C# Programming Guide)

 http://msdn.microsoft.com/en-us/library/bb513869.aspx

Screen.GetBounds Method

http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.getbounds.aspx

Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...