Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

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





Wednesday 8 January 2014

Entity Framework 5 new features

Some of the important features of Entity Framework 5.0 

Introduction:

EF 5.0 can be used in Visual Studio 2010 and Visual Studio 2012. It is used with .NET 4.0 and .NET 4.5. With .NET 4.5, this release introduces some new features 
                     
§  Enum support:
§  Spatial Data Types 
§  Performance Enhancement
Ø  Repeat Execution Time
Ø  automatic compilation
Ø  End to end performance
§  CF will detect if you have localDB available for creating new database
§  CF will add tables to existing db
§  Table Valued functions


Enum Support:

 Entity framework 5 provides support for Enum datatype. Now a property or field in a class can be declared as a Enum Type. Entity framework will successfully save the entity in DB and will display it back. But it will not store Enum type as static data in table rather will store the enum type as int value type.
e.g.
Public  enum  Color {
White,
Black,
Red,
Yellow
}

Public  Class Car
{
                Public  Color BodyColor{get;set;}
                Public  decimal Price {get;set;} 
               Public string BrandName {get;set;}
}









If we create an instance of Car and save into the database table.

    Car mycar = new Car();
mycar. BodyColor = Color.Red;
mycar.Price = 800000.00;
mycar.BrandName = “DZX”;

Table will have the data BodyColor as 2. (base value). There will not be any static table with records as White, Black, Red and Yellow.

Spatial Data type:

Entity framework 5.0 is now equipped with DbGeometry datatype which is equivalent to Geometry datatype in SQLServer.
Now we can use DbGeometry datatype for location / Geographical coordinate storing and manipulation.
e.g.
                Public class Office {
                               Public string Name{get;set;}
                              Public DbGeometry Location{get;set;}
             }
            Office Myoffice = new Office();
            Myoffice.Name = “XYZ”;
           Myoffice.Location = DbGeometry.FromText("POINT(40.644047 -73.782291)");

 The same will get persist into the database table as Geometry datatype in SQLServer.