Thursday, 5 January 2012

File upload problems and Solutions.



Giving ASP.NET Proper Permissions to Upload Files

You might receive errors when your end users upload files to your Web server through the FileUpload control in your application. These might occur because the destination folder on the server is not writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder's properties.


First, right-click on the folder where the ASP.NET files should be uploaded and select Properties from the provided menu. The Properties dialog for the selected folder opens. Click the Security tab to make sure the ASP.NET Machine Account is included in the list and has the proper permissions to write to disk. If it is enabled, you see something similar to what is presented in Figure 2.


Professional ASP.NET 2.0 Special Edition - Figure 2
Figure 2

If you don't see the ASP.NET Machine Account in the list of users allowed to access the folder, add ASP.NET by clicking the Add button and entering ASPNET (without the period) in the text area provided (see Figure 3).

Professional ASP.NET 2.0 Special Edition - Figure 3
Figure 3
Click OK, and you can then click the appropriate check boxes to provide the permissions needed for your application.

Understanding File Size Limitations

Your end users might never encounter an issue with the file upload process in your application, but you should be aware that some limitations exist. When users work through the process of uploading files, a size restriction is actually sent to the server for uploading. The default size limitation is 4MB (4096kb); the transfer fails if a user tries to upload a file that is larger than 4096kb.

A size restriction protects your application. You want to prevent malicious users from uploading numerous large files to your Web server in an attempt to tie up all the available processes on the server. Such an occurrence is called a denial of service attack. It ties up the Web server's resources so that legitimate users are denied responses from the server.

One of the great things about .NET, however, is that it usually provides a way around limitations. You can usually change the default settings that are in place. To change the limit on the allowable upload file size, you make some changes in either the web.config.comments (found in the ASP.NET 2.0 configuration folder at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) or in your application's web.config file.
In the web.config.comments file, find a node called <httpRuntime>. In this file, you see that the default allowable file size is dictated by the actual request size permitted to the Web server (4096KB). The <httpRuntime> section of the web.config.comments file is shown in Listing 2.

Listing 2: Changing the file-size limitation setting in the web.config file
<httpRuntime 
 executionTimeout="110" 
 maxRequestLength="4096" 
 requestLengthDiskThreshold="80" 
 useFullyQualifiedRedirectUrl="false" 
 minFreeThreads="8" 
 minLocalRequestFreeThreads="4" 
 appRequestQueueLimit="5000" 
 enableKernelOutputCache="true" 
 enableVersionHeader="true" 
 requireRootedSaveAsPath="true" 
 enable="true" 
 shutdownTimeout="90" 
 delayNotificationTimeout="5" 
 waitChangeNotification="0" 
 maxWaitChangeNotification="0" 
 enableHeaderChecking="true" 
 sendCacheControlHeader="true" 
 apartmentThreading="false" />
You can do a lot with the <httpRuntime> section of the web.config file, but two properties — themaxRequestLength and executionTimeout properties — are especially interesting.
The maxRequestLength property is the setting that dictates the size of the request made to the Web server. When you upload files, the file is included in the request; you alter the size allowed to be uploaded by changing the value of this property. The value presented is in kilobytes. To allow files larger than the default of 4MB, change the maxRequestLength property as in the following:

maxRequestLength="11000"

This example changes the maxRequestLength property's value to 11,000KB (around 10MB). With this setting in place, your end users can upload 10MB files to the server. When changing themaxRequestLength property, be aware of the setting provided for the executionTimeout property. This property sets the time (in seconds) for a request to attempt to execute to the server before ASP.NET shuts down the request (whether or not it is finished). The default setting is 90 seconds. The end user receives a timeout error notification in the browser if the time limit is exceeded. If you are going to permit larger requests, remember that they take longer to execute than smaller ones. If you increase the size of the maxRequestLength property, you should examine whether to increase theexecutionTimeout property as well.

If you are working with smaller files, it's advisable to reduce the size allotted for the request to the Web server by decreasing the value of the maxRequestLength property. This helps safeguard your application from a denial of service attack.

Making these changes in the web.config.comments file applies this setting to all the applications that are on the server. If you want to apply this only to the application you are working with, apply the<httpRuntime> node to the web.config file of your application, overriding any setting that is in theweb.config.comments file. Make sure this node resides between the <system.web> nodes in the configuration file.

Uploading Multiple Files from the Same Page

So far, you have seen some good examples of how to upload a file to the server without much hassle. Now, take a look at how to upload multiple files to the server from a single page.
No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. With a little work, however, you can easily accomplish this task just as you would have in the past using .NET 1.x.
The trick is to import the System.IO class into your ASP.NET page and then to use theHttpFileCollection class to capture all the files that are sent in with the Request object. This approach enables you to upload as many files as you want from a single page.
If you wanted to, you could simply handle each and every FileUpload control on the page individually as shown in in Listing 3.
Listing 3: Handling each FileUpload control individuallyVB
If FileUpload1.HasFile Then
   ' Handle file
End If
If FileUpload2.HasFile Then
   ' Handle file
End If
C#
if (FileUpload1.HasFile) {
   // Handle file
}
if (FileUpload2.HasFile) {
   // Handle file
}
If you are working with a limited number of file upload boxes, this approach works; but at the same time you may, in certain cases, want to handle the files using the HttpFileCollection class. This is especially true if you are working with a dynamically generated list of server controls on your ASP.NET page.
For an example of this, you can build an ASP.NET page that has three FileUpload controls and one Submit button (using the Button control). After the user clicks the Submit button and the files are posted to the server, the code behind takes the files and saves them to a specific location on the server. After the files are saved, the file information that was posted is displayed in the ASP.NET page (see Listing 4).

Listing 4: Uploading multiple files to the server

VB
Protected Sub Button1_Click(ByVal sender As Object, _
   ByVal e As System.EventArgs)
   Dim filepath As String = "C:\Uploads"
   Dim uploadedFiles As HttpFileCollection = Request.Files
   Dim i As Integer = 0
   Do Until i = uploadedFiles.Count
     Dim userPostedFile As HttpPostedFile = uploadedFiles(i)
     Try
        If (userPostedFile.ContentLength > 0) Then
           Label1.Text += "<u>File #" & (i + 1) & "</u><br>"
           Label1.Text += "File Content Type: " & _
              userPostedFile.ContentType & "<br>"
           Label1.Text += "File Size: " & _
              userPostedFile.ContentLength & "kb<br>"
           Label1.Text += "File Name: " & _
              userPostedFile.FileName & "<br>"
           userPostedFile.SaveAs(filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName))
           Label1.Text += "Location where saved: " & _
              filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName) & _
              "<p>"
        End If
     Catch ex As Exception
        Label1.Text += "Error:<br>" & ex.Message
     End Try
     i += 1
   Loop
End Sub
C#
protected void Button1_Click(object sender, EventArgs e)
{
   string filepath = "C:\\Uploads";
   HttpFileCollection uploadedFiles = Request.Files;
    
   for (int i = 0; i < uploadedFiles.Count; i++)
   {    
      HttpPostedFile userPostedFile = uploadedFiles[i];
    
      try
      {    
         if (userPostedFile.ContentLength > 0 )
         {
            Label1.Text += "<u>File #" + (i+1) + 
               "</u><br>";
            Label1.Text += "File Content Type: " + 
               userPostedFile.ContentType + "<br>";
            Label1.Text += "File Size: " + 
               userPostedFile.ContentLength + "kb<br>";
            Label1.Text += "File Name: " + 
               userPostedFile.FileName + "<br>";
    
            userPostedFile.SaveAs(filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName));
    
            Label1.Text += "Location where saved: " + 
               filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName) + 
               "<p>";
         }    
      } 
      catch (Exception Ex)
      {    
         Label1.Text += "Error: <br>" + Ex.Message;    
      }    
   }    
}
This ASP.NET page enables the end user to select up to three files and click the Upload Files button, which initializes the Button1_Click event. Using the HttpFileCollection class with theRequest.Files property lets you gain control over all the files that are uploaded from the page. When the files are in this state, you can do whatever you want with them. In this case, the files' properties are examined and written to the screen. In the end, the files are saved to the Uploads folder in the root directory of the server. The result of this action is illustrated in Figure 4.
Professional ASP.NET 2.0 Special Edition - Figure 4

Wednesday, 4 January 2012

Page Life Cycle in ASP.NET

An important article on the different methods and order they are executed during the load of an .aspx web page. ASP.NET.


In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.

When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.

The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page's life cycle in the order listed below.

MethodsDescription
Page_InitPage Initialization
LoadViewStateView State Loading
LoadPostDataPostback Data Processing
Page_LoadPage Loading
RaisePostDataChangedEventPostBack Change Notification
RaisePostBackEventPostBack Event Handling
Page_PreRenderPage Pre Rendering Phase
SaveViewStateView State Saving
Page_RenderPage Rendering
Page_UnloadPage Unloading
The first processed method is Page_Init(). Once the control tree has been created, the controls declared in the .aspx file are initialized. The controls can modify some of the settings set in this method to be used later in the page life cycle. Obviously no other information is available to be modified at this time.

The next processed method is LoadViewState(). The Viewstate contains stored information that is set by the page and controls of the page. This is carried to and from every aspx page request per visitor.
I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

The next processed method is LoadPostData(). These are values associated with the HTML form elements the visitor has typed, changed or selected. Now the control has access to this information which can update their stored information pulled from the Viewstate.

The next processed method is Page_Load(). This method should look familiar and is usually the most common used method on the server side application code for an .aspx file. All code inside of this method is executed once at the beginning of the page.

The next processed method is RaisePostDataChangedEvent(). When a visitor completes a form and presses the submit button, an event is triggered. This change in state signals the page to do something.
The next processed method is RaisePostBackEvent(). This method allows the page to know what event has been triggered and which method to call. If the visitor clicks Button1, then Button1_Click is usually called to perform its function.

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
The next processed method is Page_PreRender(). This method is the last chance for the Viewstate to be changed based on the PostBackEvent before the page is rendered.

The next processed method is SaveViewState(). This method saves the updated Viewstate to be processed on the next page. The final Viewstate is encoded to the _viewstate hidden field on the page during the page render.
The next processed method is Page_Render(). This method renders all of the application code to be outputted on the page. This action is done with the HtmlWriter object. Each control uses the render method and caches the HTML prior to outputting.

The last processed method is Page_Unload(). During this method, data can be released to free up resources on the server for other processes. Once this method is completed, the HTML is sent to the browser for client side processing.

Now you should have a little bit better understanding of the order of methods executed in the request of an .aspx file.