Monday, September 10, 2012

Upload Large Files in ASP.NET

ASP.Net have set the restrictions to upload the file to the server of only 4 MB by default. We can increase this setting in Web.Config through the <httpRuntime> tag.
To upload large files in asp.net, you need change some default parameters and add tags in your configuration file, i.e. Web.Config inside <System.Web> tag.
Check out the following configuration for web.config

<httpRuntime 
maxRequestLength="4096"  
shutdownTimeout="90" 
executionTimeout="110"  
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"  
minFreeThreads="8"  
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"           
enableKernelOutputCache="true" 
enableVersionHeader="true"
 requireRootedSaveAsPath="true"    
enable="true"  

delayNotificationTimeout="5"                
waitChangeNotification="0"  
maxWaitChangeNotification="0"
enableHeaderChecking="true"  
sendCacheControlHeader="true"  
apartmentThreading="false" />


To increase the default upload size, we need to increase the value of maxRequestLength property to whatever we want in KB. Default is 4096 KB(4MB).

To upload 100 MB, set
maxRequestLength="102400"


Now to upload the file we need FileUpload control in .aspx file
 
<asp:FileUpload ID="UploadCtrl" runat="server" />

In code behind,

Step 1: Add following namespace 

            using System.IO;

Step 2: Declare global variable 

            String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
            Boolean FileOK = false;   // TO CHECK THE FILE TYPE
            Boolean FileSaved = false;

 Step 3: Add Upload function

private string uploadImage(FileUpload Upload)
        {
            string imgpath = null;
            try
            {
                if (Upload.HasFile)
                {
                    Session["WorkingImage"] = Upload.FileName;

                    String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
                    String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (FileExtension == allowedExtensions[i])
                        {
                            FileOK = true;
                        }
                    }
                }
                if (FileOK)
                {
                    try
                    {
                        long str = System.DateTime.Now.ToBinary();
                        Session["WorkingImage"] = str.ToString() + Session["WorkingImage"];
                        Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                        FileSaved = true;
                    }
                    catch (Exception ex)
                    {
                        message.Visible = true;
                        message.Attributes.Add("style", "margin-bottom: 5px");
                        message.Attributes.Add("id", "message-red");
                        messageClass.Attributes.Add("class", "red-left");
                        messageIcon.Src = "images/table/icon_close_red.gif";
                        lblresult.Text = "File could not be uploaded." + ex.Message.ToString();
                        lblresult.Visible = true;
                        FileSaved = false;
                    }
                }
                else
                {
                    message.Visible = true;
                    message.Attributes.Add("style", "margin-bottom: 5px");
                    message.Attributes.Add("id", "message-red");
                    messageClass.Attributes.Add("class", "red-left");
                    messageIcon.Src = "images/table/icon_close_red.gif";
                    lblresult.Text = "Cannot accept files of this type.";
                    lblresult.Visible = true;
                }
                if (FileSaved)
                {
                    Upload.Visible = false;
                    //imgContent.ImageUrl = "../images/" + Session["WorkingImage"].ToString();
                }
               
                if (FileOK)
                {
                    imgpath = "../images/" + Session["WorkingImage"].ToString();
                }
            }
            catch (Exception ex)
            {
                message.Visible = true;
                lblresult.Text = ex.Message;
                message.Attributes.Add("style", "margin-bottom: 5px");
                messageIcon.Src = "images/table/icon_close_red.gif";
                messageClass.Attributes.Add("class", "red-left");
            }
            return imgpath;
        }


Step 4:  Call Upload function.

You just need to pass your File upload  control ID to the function.

protected void btnSubmit_Click(object sender, EventArgs e)
{
      string FileNamePath = uploadImage(UploadCtrl);
}





Friday, May 25, 2012

Microsoft Technology

Welcome to my Microsoft Technology – Programming Guide for Beginners Blog.

 

The basic for .Net  

Framework is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. 
The .NET Framework is Microsoft's Programming model for building applications that have visually stunning user experience, secure communication, and the ability to model a range of business processes.
    Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined API, yet they contain some key distinguishing features that separate them from normal libraries.

Frameworks have these distinguishing features that separate them from libraries or normal user applications:
   1. Inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.
   2. Default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
   3. Extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality
   4. Non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.

There are different versions of Framework like 2.0, 3.0, 3.5, 4.0. See Below image to understand more. Microsoft has added different functionality in various version of framework. This is just an overview of an new technology introduce in Framework versions.

DotNetFramework
Dot Net Frameworks
The .Net framework 4.0 also support backward compatibility. That means it also supports the older version of frameworks. The applications which are created in older version can continue in the same targeted version. See following image to check version 4.0 functions.
      
You can download .Net Framework 4.0 from Here

What is CLR ?
The Common Language Runtime is the Execution Engine for .Net Framework. It Provides number of services, including following.
  1. Code management (Loading & Execution).
  2. Application memory isolation.
  3. Verification of type safety.
  4. Conversion of IL (Intermediate Language) to native code.
  5. Access to metadata.
  6. Managing memory for managed object.
  7. Enforcement of CAS (code access security).
  8. Exception Handling including cross language exception.
  9. Inter operation between managed code, COM objects and pre existing DLLs ( Unmanaged code and data)
  10. Support for developer service like profiling, debugging, etc.
  11. Automation of object layout. 

.NET Framework Class Library

The .NET Framework class library is a library of classes, interfaces, and value types that provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.

The Base Class Library (BCL) includes a small subset of the entire class library and is the core set of classes that serve as the basic API of the Common LanguageRuntime.[9] The classes in mscorlib.dll and some of the classes in System.dll and System.core.dll are considered to be a part of the BCL. The BCL classes are available in both .NET Framework as well as its alternative implementations including .NET CompactFramework, Microsoft Silverlight and Mono.
The Framework ClassLibrary (FCL) is a superset of the BCL classes and refers to the entire class library that ships with .NET Framework. It includes an expanded set of libraries, including WinForms, ADO.NET, ASP.NET, LanguageIntegrated Query, WPF, WCF among others. The FCL is much larger in scope than standard libraries for languages like C++, and comparable in scope to the standard libraries ofJava.