Monday 14 April 2014

Asp.Net MVC 4.0 multiple images or files upload application

In  my previous article I have written step by step how to upload image or file. But only one image / file only can be uploaded at one time.

Here I am going to illustrate with sample application how to upload multiple images or files.

Step 1. Add one model class FileUpload as shown below

 public class FileUpload
    {
        public string FileName { get; set; }
        public string Location { get; set; }
        public HttpPostedFileBase File{ get; set; }

    }

Step 2. Add one controller FileUploadController with read write option.

[HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            HttpFileCollectionBase files = HttpContext.Request.Files;
            int fileCount = files.Count;
            try
            {
                for (int index = 0; index < fileCount; index++)
                {
                  HttpPostedFileBase file =   files.Get(index);
                  file.SaveAs("D:\\Test" + file.FileName.Substring(file.FileName.LastIndexOf("\\"),(file.FileName.Length-file.FileName.LastIndexOf("\\"))));
                }
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View(ex.Message);
            }
        }


Step 3.  Add view to the Create Get method in controller by right click and select add view. Select strongly type view and select or type complete path of model FileUpload class. Type the below code in view 



@using (Html.BeginForm("Create", "FileUpload", FormMethod.Post, new  { enctype="multipart/form-data"}))
{
        <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
         <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
     <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
}

Step 4. Create D:\\Test folder.Give permission and remove read only attribute.

Now run and select and save the files.

Saturday 12 April 2014

CoVariance and ContraVariance in CSharp

I am going to discuss about the Variance in csharp. But before that we have to know about some keyword

Subtyping: is a polymorphism rule in programming language which refers to how 2 complex types A (subtype or more specific type) can substitute or can be used where B(super type or generic type) is required.

Variance: refers to how subtyping between components of A and B are related depending on the subtyping relations between A and B.

Covariant: A is subtype of B. Then A can be used where B is required.
Contravariant: Reverse of above.
Bivariant: Both covariant and contravariant is applicable.
Invariant: None of the above


In this content I am going to discuss how Delegates uses co- and contraVariant.

Contravariant Delegates Arguments:

FamilyCar <: Car (FamilyCar is a derived class of Car.)

In the below example delegate CardetailDelegate expects an argument of type FamilyCar but it is assigned to a method with base class argument Car.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Variance
{
    class Program
    {
        delegate string CardetailDelegate(FamilyCar car);
        static void Main(string[] args)
        {
            FamilyCar fmCar = new FamilyCar();
            fmCar.EnginePower = "80";
            fmCar.EngineDisplacement = "1300";
            fmCar.Color = "RED";
            fmCar.Length = 4;
            fmCar.Price = 350000;
            fmCar.SeatingCapacity = 5;         

            CardetailDelegate cardetaildel = CarDetail; //delegate is assigned to a method with base class argument Car

            Console.WriteLine(cardetaildel(fmCar));
            Console.Read();
        }
        static string CarDetail(Car car)
        {
      
            return string.Format("I am a car with {0} BHP power and {1} cc displacement. I am {2} mt in length and {3} in color. {4} passengers can sit together.", car.EnginePower,

car.EngineDisplacement, car.Length, car.Color, car.SeatingCapacity);
       
   
        }
    }
}

public  class Car
{
    public string Color { get; set; }
    public virtual string EnginePower { get; set; }
    public virtual string EngineDisplacement { get; set; }
    public virtual int SeatingCapacity { get; set; }
    public  int Length { get; set; }
    public bool AC { get; set; }
    public decimal Price { get; set; }

   

}


public class FamilyCar : Car
{
    string enginePower;
    string engineDisplacement;
     int seatingCapacity;

    public override string EnginePower
    {
        get
        {
            return enginePower;
        }
        set
        {
            enginePower = value;
        }
    }

    public override string EngineDisplacement
    {
        get
        {
            return engineDisplacement;
        }
        set
        {
            engineDisplacement = value;
        }
    }

    public override int SeatingCapacity
    {
        get
        {
            return seatingCapacity;
        }
        set
        {
            seatingCapacity = value;
        }
    }

   
}
 


CoVariance delegates return type:

In the below example delegate NewCarDelegate returns type Car but it is assigned to a method with derived class return type FamilyCar.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Variance
{
    class Program
    {
       
       
        delegate Car NewCarDelegate();


        static void Main(string[] args)
        {
          

          
            NewCarDelegate newCar = GetNewCar; //contravariance GetNewCar return FamilyCar but NewCarDelegate has return type Car which base class of FamilyCar
           
            Console.WriteLine(CarDetail(newCar()));

            Console.Read();
        }
        static string CarDetail(Car car)
        {       
            return string.Format("I am a car with {0} BHP power and {1} cc displacement. I am {2} mt in length and {3} in color. {4} passengers can sit together.", car.EnginePower,

car.EngineDisplacement, car.Length, car.Color, car.SeatingCapacity);       
   
        }

        static FamilyCar GetNewCar()
        {
            FamilyCar fmCar = new FamilyCar();
            fmCar.EnginePower = "180";
            fmCar.EngineDisplacement = "3000";
            fmCar.Color = "White";
            fmCar.Length = 6;
            fmCar.Price = 1500000;
            fmCar.SeatingCapacity = 5;
            return fmCar;
        }
    }
}

public  class Car
{
    public string Color { get; set; }
    public virtual string EnginePower { get; set; }
    public virtual string EngineDisplacement { get; set; }
    public virtual int SeatingCapacity { get; set; }
    public  int Length { get; set; }
    public bool AC { get; set; }
    public decimal Price { get; set; }

   

}


public class FamilyCar : Car
{
    string enginePower;
    string engineDisplacement;
     int seatingCapacity;

    public override string EnginePower
    {
        get
        {
            return enginePower;
        }
        set
        {
            enginePower = value;
        }
    }

    public override string EngineDisplacement
    {
        get
        {
            return engineDisplacement;
        }
        set
        {
            engineDisplacement = value;
        }
    }

    public override int SeatingCapacity
    {
        get
        {
            return seatingCapacity;
        }
        set
        {
            seatingCapacity = value;
        }
    }   
}



We will discuss more on this in coming blogs.

Tuesday 8 April 2014

ASP.Net MVC 4 Image Upload Application Step by Step

I am going to develop an image upload application step by step in Asp.Net MVC 4.0. It is sometimes required to upload image in application.

It is sample application and you can upload one image against an employee.

Step 1.  Open Visual Studio and click on the File à New Project. Select ASP.Net MVC 4.0 Web application as shown below.

Step 2.  Give the project name as ImageUploadProject.
Step 3. Select Internet Application template as shown below and click on the OK button.

Step 4.  Run the application you will see the below screen in the browser.


Step 6.  In the SQL Server create Database EmployeeDB and table Employee as shown below.
               
CREATE TABLE [dbo].[Employee](
      [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
      [FirstName] [nvarchar](50) NOT NULL,
      [LastName] [nvarchar](50) NOT NULL,
      [Address] [nvarchar](50) NULL,
      [ZipCode] [nvarchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
      [EmployeeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO



Step 7. Browse the solution and locate Model folder. Add Employee class as shown below


public class Employee    {
        public int EmployeeID { get; set; }
        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }
        [Required]
        [StringLength(50)]
        public string LastName { get; set; }
        public string Address { get; set; }
        public string ZipCode { get; set; }
        [NotMapped]
        public HttpPostedFileBase Image { get; set; }
        [NotMapped]
        [Display(Name = "Image")]
        public string ImageFile { get; set; }
    }


Step 8.  Add EmployeeDBContext class in the Model folder as shown below

public class EmployeeDBContext:DbContext
    {
        public DbSet<Employee> EmployeeCollection { get; set; }

        public EmployeeDBContext()
            : base("EmployeeConnection") {        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().Map(m =>
            {
                m.MapInheritedProperties();
                m.ToTable("Employee");

            })          
            .Property(m => m.EmployeeID).HasColumnName("EmployeeID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
        }      
    }

Step 9. Add Employee Controller as shown below


Step 10. : Add the  below methods in the Employee Controller.
         public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Employee empModel)
        {
            try
            {
             using (EmployeeDBContext edb = new EmployeeDBContext())
                {
                    edb.EmployeeCollection.Add(empModel);
                    edb.SaveChanges();
                    PictureUpload(empModel);
                }

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View();
            }
        }

Step 11. Right click on the Create method and select Add View method.


Step 12. Add the below tag to upload image in case if not auto generated in create.cshtml file.
<div class="editor-field">
                @Html.TextBoxFor(model => model.Image, new { type = "file" })
                @Html.ValidationMessageFor(model => model.Image)
        </div>
Step 12.  Add below 2 methods in the EmployeeController class
private void PictureUpload(Employee emp)
        {
            if (emp.Image.ContentLength > 0)
            {
               
                var filePath = Server.MapPath(@"/Content/Uploads");
                string savedFileName = Path.Combine(filePath, emp.EmployeeID.ToString()+".jpg");
                emp.Image.SaveAs(savedFileName);
               
            }
           
        }
        private void DownloadPetPicture(IList<Employee> empList)
        {
            foreach (var employee in empList)
            {
                var name = "/Content/Uploads/"+employee.EmployeeID.ToString() +".jpg";
                var picture = @UrlHelper.GenerateContentUrl( name,  this.HttpContext);
               
                employee.ImageFile = "<img src='" + picture + "'></img>";
            }
        }
Step 13. Update the Index method as shown below
public ActionResult Index()
        {
            List<Employee> employeeCollection = null;
            using (EmployeeDBContext emd = new EmployeeDBContext())
            {
              
                 employeeCollection =   emd.EmployeeCollection.ToList();
                 if (employeeCollection != null)
                     DownloadPetPicture(employeeCollection);
            }
            return View(employeeCollection);
        }
Step 14. Create one Uploads folder under Content folder in the solution. 
We can write code to auto generate the folder in case it is not available. But I have not coded that. Add strongly view with index method as shown in previous steps. 
Now build and type Employee/create you will see the below screen


Enter values and select image it will take you the index(or List) view as shown below