Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Thursday, July 24, 2014

FileUpload control and its errors in Asp.NET

This is a tutorial in asp.net for working with FileUpload control.
  1. How to upload a file using FileUpload control in asp.net
  2. Possible errors while uploading files into the  Webserver(IIS)
File upload controls can be used to upload any kind of file into a webserver or a desired location using ASP.NET

This is pretty very easy one.
Let me make it simple for you.

First, Create an ASP.NET application and keep a FileUpload control on it. let us say the name as FileUploadDocuments.
Now place a button let say UPLOAD FILE near the FileUpload control
Now on the UploadFile_Click event write the code below
protected void UploadFileButton_Click(object sender, EventArgs e)
{
  FileUploadDocuments.SaveAs(@"C:\user\" + FileUploadDocuments.

Now, run your application. Select a file from your local machine. Click on the Upload button and that's it. Done!!

Go to the physical location and you can find the Uploaded file there. "C:\user\".

How, simple is it right?

Normally, I start like this. So, its easy for others to understand FileUploading. Now, you know which code actually uploads the file.

Now, We need to know much more things about the control to exactly upload the file with no errors or saving it from uploading virus scripts or anything.

So, what all things should be checked here. Let us say, I want my file size restricted to 10MB, only images, pdf, doc files should be uploaded, Whether the file is present in the physical location etc etc. So, how can I achieve this?


1) I want to upload the Files into a folder inside my website


Its always better to upload files into the same website subfolders since all the files will be available for you. But, there are cases like if its a big application you cannot go with this approach since there might be too much files getting uploaded. So, you can use a network path or a physical path to an external HDD etc.

Now, here we are talking about how to upload into a sub folder inside my website itself.
So, First create a folder inside your solution from Solution explorer.
steps:-
Right click on Solution->Add->NewFolder (in Visual Studio 2013)
Right Click on Solution->NewFolder (in Visual Studio 2010)
Let us say the name given to that folder is "UPLOADS"

Now I want to save the files into my uploads folder.
So, First i want to get the physical path of my Uploads folder. The physical path can be some thing like "C:\inetpub\wwwroot\website\uploads\"
But we don't know in the webserver where we are going to place the webiste. So, the location should be mapped dynamically into the website.
For getting the physical path of a website folder you can use the statement Server.MapPath.
So, change the fileUpload controls code to
 FileUploadDocuments.SaveAs(Server.MapPath("~/Uploads/") + FileUploadDocuments.FileName);

Here Server.MapPath("~/Uploads/") will get the physical path of the upload folder and allows the file to be uploaded into that particular folder.

2) Check whether the file is available in the physical location.


Why should we need this? I'm selecting a file from physical location right?
Yes, You are selecting a file from Physical location. But what if after your selection the file got removed and then you tried to upload the file?

So, we need to avoid this issue.
This can be cross checked by HasFile attribute of the FileUpload Control like

if (FileUploadDocuments.HasFile)
{
 FileUploadDocuments.SaveAs(@"C:\user\" + FileUploadDocuments.FileName);
}
else
{
 ErrorMessage.Text="The file does not exist in the physical path";

}

This ensures the file you are about to upload is physically present in the drive.

3) I want to restrict my file size to 10MB


Why should I check this?
If you doesn't check this your webserver or the location to which you are uploading will be soon filled with files. What if someone tries to upload files of 100MB each.

So, We need to make use of all the available options given by FileUpload control in asp.net
How can we achieve this?
We can achieve this easily with the help of properly called ContentLength. Content length will return the no of bytes of the file you are trying to upload. You can write the code like this.

if (FileUploadDocuments.PostedFile.ContentLength < ((1024 * 10) * 1024))
{
FileUploadDocuments.SaveAs(@"C:\user\" + FileUploadDocuments.FileName);
}
else
{
ErrorMessage.Text="Your file is more than 10MB";
}
I have done the calculation like (1024 * 10) * 1024) because 10MB means the value will be 10485760 bytes. So, when you don't know exact value you think like this. 1MB=1024KB, 1KB=1024bytes.

So above you restricted the user to upload files below 10 MB. So, when a user tries to upload a file above 10 MB you can show an error message

4) I want to upload only files with a specific type(PDF/JPG/DOCX)


Why you need this?
This is needed since your purpose will be a job application and no one should upload a Video as his CV. :-)
Definition is as simple as that.

Now, how can you achieve this.
You can achieve this in many ways. My way of achieving is with the help of FileInfo class from System.IO and the ContentType property of the FileUpload control itself.

The safest way is with the help of ContentType since no one can alter the file extension and upload a different file(Like an image with docx extension)

You can write the code like below.
if (FileUploadDocuments.PostedFile.ContentType.ToUpper() == "APPLICATION/PDF" || FileUploadDocuments.PostedFile.ContentType.ToUpper() == "IMAGE/JPG" )
{
FileUploadDocuments.SaveAs(@"C:\user\" + FileUploadDocuments.FileName);
}
else
{
ErrorMessage.Text = "Only PDF and JPG files are allowed";
}

The above code will allow only PDF, and JPG files to be uploaded into the application.

TIP: Try printing FileUploadDocuments.PostedFile.ContentType when you upload different type of files and you will get all the desired content types.

If you only want to check the extension of the file then go thorough this way
System.IO.FileInfo fi = new System.IO.FileInfo(FileUploadDocuments.FileName);
if (fi.Extension.ToUpper() == ".DOCX" || fi.Extension.ToUpper() == ".DOC")
{
  FileUploadDocuments.SaveAs(@"C:\user\" + FileUploadDocuments.FileName);
}
else
{
  ErrorMessage.Text = "Invalid document only DOC, DOCX files are allowed";
}
So, with the codes above you can upload a file in the safest way to your webserver.

Now, let us see how the final code looks like with all these validations.

protected void UploadFileButton_Click(object sender, EventArgs e)
 {
  System.IO.FileInfo fi = new System.IO.FileInfo(FileUploadDocuments.FileName);  
  if (FileUploadDocuments.HasFile)
  {
   if (FileUploadDocuments.PostedFile.ContentLength < ((1024 * 10) * 1024))
   {
    if (FileUploadDocuments.PostedFile.ContentType.ToUpper() == "APPLICATION/PDF" || FileUploadDocuments.PostedFile.ContentType.ToUpper() == "IMAGE/JPG" || fi.Extension.ToUpper() == ".DOCX" || fi.Extension.ToUpper() == ".DOC")
    {
     FileUploadDocuments.SaveAs(Server.MapPath("~/Uploads/") + FileUploadDocuments.FileName);
    }
    else
    {
     ErrorMessage.Text = "Only PDF/JPG/DOC/DOCX files are allowed";
    }
   }
   else
   {
    ErrorMessage.Text = "Your file is more than 10MB";
   }
  }
  else
  {
   ErrorMessage.Text = "The file does not exist in the physical path";
  }
}


Now, when you run this it will work smoothly until you put this into a real Webserver.

Handling Errors


What's going to happen when you put this into a webserver. If you are beginner and you are working with the file upload control it can make you crazy with the errors appearing in the webservers.
First one will be exception due to the permission level of the folder
Always make sure you have set the write permission of the folder to IIS_IUSRS of the webserver machine.

























This will make sure that IIS users are allowed to write the files into the Uploads Folder. You just need to set the permission only for Uploads folder.

Now, Another error which you might have to face is the Max Request length reached error.
Whenever you try to upload a file above 4MB using FileUpload control into the Webserver, It will raise an error saying Max Request Length reached. This is because by default the max request length of our IIS setting is set to 4MB. when you get this error you must have to override the maxRequestLenth from web.config.
This can be done by adding a line of code in the web.config in the system.web section.

  <httpRuntime targetFramework="4.5.1" maxRequestLength="1024000" />
In most cases the above code alone should handle the exception.
But in some cases even if you write the above code again you might get the same error. So, this time you will be worried thinking what happened. This is because in a minor case sometimes IIS will look into system.weberver section also.
So, you must override this in the system.webserver section too. If you don't have the system.webserver section you must add it into the web.config file.

<system.webServer>    
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="524288000"/>
      </requestFiltering>
    </security>
  </system.webServer>
Now, this must allow you to upload files upto 500MB of size.

So, have a great day. My next blog will be containing how to upload file into a network folder and what all thre problems that you will face in that. How to store files into a network folder with the help of Identity Impersonation, dynamic impersonation, Identity impersonation encryption etc.

If you are working with .NET Framework 4.0 sometimes even with all the above codes you might get an error "Page cannot be displayed".
So, if you face this error write the below code after the security section in System.webserver

<modules runAllManagedModulesForAllRequests="true"/>

Now, the website should work perfectly.


Thanks csharp-asp blog

Thursday, June 20, 2013

Structs in C#

               The C# struct is a lightweight alternative to a class. It can do almost the same as a class, but it's less "expensive" to use a struct rather than a class. The reason for this is a bit technical, but to sum up, new instances of a class is placed on the heap, where newly instantiated structs are placed on the stack. Furthermore, you are not dealing with references to structs, like with classes, but instead you are working directly with the struct instance. This also means that when you pass a struct to a function, it is by value, instead of as a reference. There is more about this in the chapter about function parameters. 

So, you should use structs when you wish to represent more simple data structures, and especially if you know that you will be instantiating lots of them. There are lots of examples in the .NET framework, where Microsoft has used structs instead of classes, for instance the Point, Rectangle and Color struct. 

First I would like to show you an example of using a struct, and then we will discuss some of the limitations of using them instead of classes:

class Program
{
    static void Main(string[] args)
    {
        Car car;

        car = new Car("Blue");
        Console.WriteLine(car.Describe());

        car = new Car("Red");
        Console.WriteLine(car.Describe());

        Console.ReadKey();
    }
}

struct Car
{
    private string color;

    public Car(string color)
    {
        this.color = color;
    }

    public string Describe()
    {
        return "This car is " + Color;
    }

    public string Color
    {
        get { return color; }
        set { color = value; }
    }
}
The observant reader will notice that this is the exact same example code as used in the introduction to classes, besides the change from a class to a struct. This goes to show how similar the two concepts are. But how do they differ, besides the technical details mention in the beginning of this chapter? 

First of all, fields can't have initializers, meaning that you can't declare a member like this:

private string color = "Blue";
If you declare a constructor, all fields must be assigned to before leaving the constructor. A struct does come with a default constructor, but as soon as you choose to define your own, you agree to initialize all fields in it. That also means that you can't declare your own paramaterless constructor - all struct constructors has to take at least one parameter. In our example above, we did in fact assign a value to the color field. If we hadn't done that, the compiler would complain. 

A struct can not inherit from other classes or structs, and classes can't inherit from structs. A struct does inherit from the Object class, but that's it for inheritance and structs. They do support interfaces though, meaning that your structs can implement custom interfaces.

Exception handling

          In every program, things go wrong sometimes. With C#, we're blessed with a good compiler, which will help us prevent some of the most common mistakes. Obviously it can't see every error that might happen, and in those cases, the .NET framework will throw an exception, to tell us that something went wrong. In an earlier chapter, about arrays, I described how we would get an exception if we tried to stuff too many items into an array. Let's bring the example:
using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[2];

            numbers[0] = 23;
            numbers[1] = 32;
            numbers[2] = 42;

            foreach(int i in numbers)
                Console.WriteLine(i);
            Console.ReadLine();
        }
    }
}
Okay, try running this example, and you will see what I'm talking about. Do you see what we're doing wrong? We have defined an array of integers with room for 2 items, yet we try to use 3 spaces in it. Obviously, this leads to an error, which you will see if you try to run this example. When run inside Visual C# Express, the IDE gives us some options for the exception, but if you try to execute the program by simply doubleclicking the EXE file, you will get a nasty error. If you know that an error might occur, you should handle it. This is where exceptions are used. Here is a slightly modified version of the code from above:
int[] numbers = new int[2];
try
{
    numbers[0] = 23;
    numbers[1] = 32;
    numbers[2] = 42;

    foreach(int i in numbers)
        Console.WriteLine(i);
}
catch
{
    Console.WriteLine("Something went wrong!");
}
Console.ReadLine();
Let me introduce to you your new best friend when it comes to error handling: the try..catch block. Try running the program now, and see the difference - instead of Visual C# Express/Windows telling us that a serious problem occured, we get to tell our own story. But wouldn't it be nice if we could tell what went wrong? No problem:
catch(Exception ex)
{
    Console.WriteLine("An error occured: " + ex.Message);
}
As you can see, we have added something to the catch statement. We now tell which exception we want caught, in this case the base of all exceptions, the Exception. By doing so, we get some information about the problem which caused the exception, and by outputting the Message property, we get an understandable description of the problem. 

As I said, Exception is the most general type of exception. The rules of exception handling tells us that we should always use the least general type of exception, and in this case, we actually know the exact type of exception generated by our code. How? Because Visual Studio told us when we didn't handle it. If you're in doubt, the documentation usually describes which exception(s) a method may throw. Another way of finding out is using the Exception class to tell us - change the output line to this:

Console.WriteLine("An error occured: " + ex.GetType().ToString());
The result is, as expected, IndexOutOfRangeException. We should therefore handle this exception, but nothing prevents us from handling more than one exception. In some situations you might wish to do different things, depending on which exception was thrown. Simply change our catch block to the following:
catch(IndexOutOfRangeException ex)
{
    Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
    Console.WriteLine("Some sort of error occured: " + ex.Message);
}
As you can see, we look for the IndexOutOfRangeException first. If we did it the other way around, the catch block with the Exception class would get it, because all exceptions derive from it. So in other words, you should use the most specific exceptions first. 

One more thing you should know about concerning exceptions is the finally block. The finally block can be added to a set of catch blocks, or be used exclusively, depending on your needs. The code within the finally block is always run - exception or no exception. It's a good place if you need to close file references or dispose objects you won't need anymore. Since our examples have been pretty simple so far, we haven't really been in need of any cleanup, since the garbage collector handles that. But since will likely run into situations where you need the finally block, here is an extended version of our example:
int[] numbers = new int[2];
try
{
    numbers[0] = 23;
    numbers[1] = 32;
    numbers[2] = 42;

    foreach(int i in numbers)
        Console.WriteLine(i);
}
catch(IndexOutOfRangeException ex)
{
    Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
    Console.WriteLine("Some sort of error occured: " + ex.Message);
}
finally
{
    Console.WriteLine("It's the end of our try block. Time to clean up!");
}
Console.ReadLine();
If you run the code, you will see that both the first exception block and the finally block is executed. If you remove the line that adds the number 42 to the array, you will see that only the finally block is reached. 

Another important part you should know about exceptions, is how they impact the method in which the exceptions occur. Not all unhandled exceptions are fatal for your application, but when they aren't, you should not expect the remaining code of the method to be executed. On the other hand, if you do handle the exception, only the lines after the try block will be executed. In our example, the loop that outputs the values of the array is never reached, because the try block goes straight to the catch/finally block(s) once an exception is thrown. However, the last line, where we read from the console to prevent the application from exiting immediately, is reached. You should always have this in mind when you construct try blocks.

Enumerations

          Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace. 

Here is an example of a simple enumeration to show what they are all about.

public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
All of these possible values correspond to a number. If we don't set them specifically, the first value is equal to 0, the next one to 1, and so on. The following piece of code will prove this, as well as show how we use one of the possible values from the enum:
using System;

namespace ConsoleApplication1
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.ReadLine();
        }
    }
}
The output will be zero, because the Monday value maps directly to the number zero. Obviously we can change that - change the line to something like this:
public enum Days { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
If you run our code again, you will see that the Monday now equals 1 instead of 0. All of the other values will be one number higher as well as a result. You can assign other numbers to the other values as well. Because of the direct mapping to a number, you can use numbers to get a corresponding value from the enumeration as well, like this:
Days day = (Days)5;
Console.WriteLine(day);
Console.ReadLine();
Another cool feature of enumerations is the fact that you can a string representation of the values as well. Change the above example to something like this:
static void Main(string[] args)
{
    string[] values = Enum.GetNames(typeof(Days));
    foreach(string s in values)
        Console.WriteLine(s);
    
    Console.ReadLine();
}
The Enum class contains a bunch of useful methods for working with enumerations.

Abstract classes

        Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. 

To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing. 

In this example, we will create a base class for four legged animals and then create a Dog class, which inherits from it, like this:

namespace AbstractClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            Console.WriteLine(dog.Describe());
            Console.ReadKey();
        }
    }

    abstract class FourLeggedAnimal
    {
        public virtual string Describe()
        {
            return "Not much is known about this four legged animal!";
        }
    }

    class Dog : FourLeggedAnimal
    {

    }
}
If you compare it with the examples in the chapter about inheritance, you won't see a big difference. In fact, the abstract keyword in front of the FourLeggedAnimal definition is the biggest difference. As you can see, we create a new instance of the Dog class and then call the inherited Describe() method from the FourLeggedAnimal class. Now try creating an instance of the FourLeggedAnimal class instead:
FourLeggedAnimal someAnimal = new FourLeggedAnimal();
You will get this fine compiler error: 

Cannot create an instance of the abstract class or interface 'AbstractClasses.FourLeggedAnimal' 

Now, as you can see, we just inherited the Describe() method, but it isn't very useful in it's current form, for our Dog class. Let's override it:

class Dog : FourLeggedAnimal
{
    public override string Describe()
    {
        return "This four legged animal is a Dog!";
    }
}
In this case, we do a complete override, but in some cases, you might want to use the behavior from the base class in addition to new functionality. This can be done by using the base keyword, which refers to the class we inherit from:
abstract class FourLeggedAnimal
{
    public virtual string Describe()
    {
        return "This animal has four legs.";
    }
}


class Dog : FourLeggedAnimal
{
    public override string Describe()
    {
        string result = base.Describe();
        result += " In fact, it's a dog!";
        return result;
    }
}

Interfaces in C#

                we had a look at abstract classes. Interfaces are much like abstract classes and they share the fact that no instances of them can be created. However, interfaces are even more conceptual than abstract classes, since no method bodies are allowed at all. So an interface is kind of like an abstract class with nothing but abstract methods, and since there are no methods with actual code, there is no need for any fields. Properties are allowed though, as well as indexers and events. You can consider an interface as a contract - a class that implements it is required to implement all of the methods and properties. However, the most important difference is that while C# doesn't allow multiple inheritance, where classes inherit more than a single base class, it does in fact allow for implementation of multiple interfaces! 

So, how does all of this look in code? Here's a pretty complete example. Have a look, perhaps try it out on your own, and then read on for the full explanation: 

using System;
using System.Collections.Generic;

namespace Interfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Dog> dogs = new List<Dog>();
            dogs.Add(new Dog("Fido"));
            dogs.Add(new Dog("Bob"));
            dogs.Add(new Dog("Adam"));
            dogs.Sort();
            foreach(Dog dog in dogs)
                Console.WriteLine(dog.Describe());
            Console.ReadKey();
        }
    }

    interface IAnimal
    {
        string Describe();

        string Name
        {
            get;
            set;
        }
    }

    class Dog : IAnimal, IComparable
    {
        private string name;

        public Dog(string name)
        {
            this.Name = name;
        }

        public string Describe()
        {
            return "Hello, I'm a dog and my name is " + this.Name;
        }

        public int CompareTo(object obj)
        {
            if(obj is IAnimal)
                return this.Name.CompareTo((obj as IAnimal).Name);
            return 0;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

Let's start in the middle, where we declare the interface. As you can see, the only difference from a class declaration, is the keyword used - interface instead of class. Also, the name of the interface is prefixed with an I for Interface - this is simply a coding standard, and not a requirement. You can call your interfaces whatever you want, but since they are used like classes so much that you might have a hard time telling the difference in some parts of your code, the I prefix makes pretty good sense. 

Then we declare the Describe method, and afterwards, the Name property, which has both a get and a set keyword, making this a read and writable property. You will also notice the lack of access modifiers (public, private, protected etc.), and that's because they are not allowed in an interface - they are all public by default. 

Next up is our Dog class. Notice how it looks just like inheriting from another class, with the colon between the class name and the class/interface being subclassed/implemented. However, in this case, two interfaces are implemented for the same class, simply separated by a comma. You can implement as many interfaces as you want to, but in this case we only implement two - our own IAnimal interface, and the .NET IComparable interface, which is a shared interface for classes that can be sorted. Now as you can see, we have implemented both the method and the property from the IAnimal interface, as well as a CompareTo method from the IComparable interface. 

Now you might be thinking: If we have to do all the work our self, by implementing the entire methods and properties, why even bother? And a very good example of why it's worth your time, is given in the top of our example. Here, we add a bunch of Dog objects to a list, and then we sort the list. And how does the list know how to sort dogs? Because our Dog class has a CompareTo method that can tell how to compare two dogs. And how does the list know that our Dog object can do just that, and which method to call to get the dogs compared? Because we told it so, by implementing an interface that promises a CompareTo method! This is the real beauty of interfaces.