Image cropping using Jcrop in ASP.NET MVC Application

What is Image cropping?

  • Image cropping refer to removal of some part of image
  • Uses to improve framing and size
  • Applied in photograph to resize image

Application overview
In this project, I will show image cropping of an employee phot when employee information saved and modified. Full crud operation applied in the application with image cropping.
Let’s have a look on the implementation of the project.

Tools and Technology used

I used following tools and technology to develop the project –

  1. Visual Studio 2015
  2. Visual C#
  3. ASP.NET MVC
  4. Entity Framework 5
  5. Razor view engine
  6. JCrop

Step 1: Create a ASP.net MVC Project
File -> New project and select the project template Visual C# -> ASP.NET Web Application (.NET Framework) -> Console application (.NET Core).

0108_01

Select MVC as a Template as ASP.NET Template and click OK

0108_02

Step 2: Change or Add Connection String
Change or Add connection string in Web.config as follows

  
    
  
  

Step 3: Install JCrop Nuget Package
Go to Tools -> NuGet Package Manager -> Manages NuGet Package Manager for the solution -> Search Jcrop and install jquery.jcrop.js

0108_02_B

Step 4: Create model class

Create model class “Employee” as follows.

Employee Class

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace JCropMVC.Models
{
    public class Employee
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Display(Name = "Full Name")]
        [Required(ErrorMessage = "Name cannot be empty")]
        public string Name { get; set; }

        [Display(Name = "Father Name")]
        public string FatherName { get; set; }

        [Display(Name = "Designation")]
        public string Designation { get; set; }

        [Display(Name = "Mobile No")]
        public string Mobile { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Display(Name = "Image URL")]
        public string PhotoURL { get; set; }
    }
}

Step 5: Modify Context class
Modify ApplicationDbContext in IdentityModel Class

    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet Employees { get; set; }
    }

Step 6: Create Controller and Views
Create Employees Controller and Views
Click Right button on Controller Folder->Add Controller. Now choose scaffolding template as MVC Controllers with views using Entity Framework and then Click Add.

0108_03

Now select Model class as Employee and Data Context Class as ApplicationDbContext as follows. Then click OK.

0108_04

Step 7: Modify the controller
Modify EmployeesController as follows. Here method ProcessImage(string croppedImage) is used to process and save image. An extra parameter added for Create and Edit action.

using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using JCropMVC.Models;
using System.IO;

namespace JCropMVC.Controllers
{
    public class EmployeesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Employees
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: Employees/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,FatherName,Designation,Mobile,Email,PhotoURL")] Employee employee, string avatarCropped)
        {
            string filePath = ProcessImage(avatarCropped);
            employee.PhotoURL = filePath;

            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        /// 
        /// Process image and save in predefined path
        /// 
        /// 
        /// 
        private string ProcessImage(string croppedImage)
        {
            string filePath = String.Empty;
            try
            {
                string base64 = croppedImage;
                byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
                filePath = "/Images/Photo/Emp-" + Guid.NewGuid() + ".png";
                using (FileStream stream = new FileStream(Server.MapPath(filePath), FileMode.Create))
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                }
            }
            catch (Exception ex)
            {
                string st = ex.Message;
            }

            return filePath;
        }

        // GET: Employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,FatherName,Designation,Mobile,Email,PhotoURL")] Employee employee, string avatarCropped)
        {
            string filePath = ProcessImage(avatarCropped);
            employee.PhotoURL = filePath;

            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        //[Authorize(Users ="sumon")]
        // GET: Employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Step 8: Modify the views for Employee

Create.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Create";
}



@using (Html.BeginForm("Create", "Employees", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "" }) @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "Enter employee full name...", type = "text" }) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.FatherName, new { @class = "" }) @Html.TextBoxFor(model => model.FatherName, new { @class = "form-control", placeholder = "Enter father name...", type = "text" }) @Html.ValidationMessageFor(model => model.FatherName)
@Html.LabelFor(model => model.Designation, new { @class = "" }) @Html.TextBoxFor(model => model.Designation, new { @class = "form-control", placeholder = "Enter designation name...", type = "text" }) @Html.ValidationMessageFor(model => model.Designation)
@Html.LabelFor(model => model.Mobile, new { @class = "" }) @Html.TextBoxFor(model => model.Mobile, new { @class = "form-control", placeholder = "Enter mobile number...", type = "text" }) @Html.ValidationMessageFor(model => model.Mobile)
@Html.LabelFor(model => model.Email, new { @class = "" }) @Html.TextBoxFor(model => model.Email, new { @class = "form-control", placeholder = "Enter email address...", type = "text" }) @Html.ValidationMessageFor(model => model.Email)
@Html.LabelFor(model => model.PhotoURL, new { @class = "" })
Width:   Height: Crop Image
Employee Image

}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Edit.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @*
*@

Employee


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "" }) @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@*
@Html.LabelFor(model => model.PhotoURL, htmlAttributes: new { @class = "" })
@Html.EditorFor(model => model.PhotoURL, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PhotoURL, "", new { @class = "text-danger" })
*@
@Html.LabelFor(model => model.PhotoURL, new { @class = "" })
Width:   Height: Crop Image
Employee Image

@*
*@ }
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.FatherName) @Html.DisplayNameFor(model => model.Designation) @Html.DisplayNameFor(model => model.Mobile) @Html.DisplayNameFor(model => model.Email) @Html.DisplayNameFor(model => model.PhotoURL)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.FatherName) @Html.DisplayFor(modelItem => item.Designation) @Html.DisplayFor(modelItem => item.Mobile) @Html.DisplayFor(modelItem => item.Email) @**@ @*@Html.DisplayFor(modelItem => item.PhotoURL)*@ @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Delete.cshtml

@model JCropMVC.Models.Employee

@{
    ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this?

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Mobile)
@Html.DisplayFor(model => model.Mobile)
@Html.DisplayNameFor(model => model.Email)
@Html.DisplayFor(model => model.Email)
@Html.DisplayNameFor(model => model.PhotoURL)
@Html.DisplayFor(model => model.PhotoURL)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Step 9: Add image folders
Add Image folders and sub folders (Deafult and Photo) as follows. Add blank photo in the Default folder to show blank photo for the employee.

0108_05

Step 10: Add Employee link
Add Employee link in the nav bar of _Layout page as follows.

                

Step 11: Run the application
Now run the application. Click Employee link in the nav bar. You can View, add, modify and delete employee information. If you go to the create or edit page, you have an option to upload photo and have option to crop the image and then save the image with employee information. Yes! You are done. Let’s cheers!

0108_06

Properties a short explanation using C#

What Are Properties?

  • Properties are methods that protect access to class members.
  • Properties are class members that provide access to elements of an object or class.
  • Protect access to the state of object.
  •  It likes fields, but they operate much like methods.
  • The get and set statements are called accessors.
  • Fields can’t be used in Interfaces so properties are the solution.

Syntax:

        private double balance;
        public double Balance
        {
            get
            {
                return balance;
            }
            set
            {
                balance = value;
            }
        }

Example:

    public class Employee
    {
        private double salary;
        private double taxRate = 0.05;
        

        public string Name { get; set; }
        public double YearOfExp { get; set; }

        public double YearlyMedicalAllowance {get; private set;}

        public Employee()
        {
            this.YearlyMedicalAllowance = 30000;
        }

        public double Salary
        {
            get { return salary; }
            set {
                if (value > 200000)
                    salary = value - value * taxRate;
                else
                    salary = 5000;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee objEmployee = new Employee();
            objEmployee.Name = "Rafiqul Islam";
            objEmployee.YearOfExp = 7;
            objEmployee.Salary = 5000;
            
            Console.WriteLine(objEmployee.Name);
            Console.WriteLine("Salary: " + objEmployee.Salary);
            Console.WriteLine("Yearly Madical Allowance" + objEmployee.YearlyMedicalAllowance);

            Console.ReadLine();
        }
    }

Static Constructor and C# implementation

Static Constructor

  • Instance constructors are used to initialize an object
  • Static constructors are used to initialize a class
  • Will only ever be executed once
  • Run before the first object of that type is created.
  • Have no parameter
  • Do not take an access modifier
  • May co-exist with a class constructor

Syntax:

        class Lion
        {
            static Lion()
            {
                // class-specific initialization
            }
        }

Example:


class RandomNumberGenerator
{
private static Random randomNumber;
public static string AuthorName { get; set; }

public RandomNumberGenerator(String msg)
{
Console.WriteLine(msg);
//Constructor for object
}

//Static constructor
static RandomNumberGenerator()
{
AuthorName = “Mahedee Hasan”;
randomNumber = new Random();
}

public int Next()
{
return randomNumber.Next();
}
}

class Program
{
static void Main(string[] args)
{
RandomNumberGenerator randomNumber
= new RandomNumberGenerator(“Generate 10 Random Number”);

for (int i = 0; i < 10; i++) { Console.WriteLine(randomNumber.Next()); } Console.WriteLine(“Author Name: ” + RandomNumberGenerator.AuthorName); Console.ReadKey(); } } [/csharp]

How to remove special character from Unicode string

Here is the sample code to remove special character from Unicode string.
Sample Input: SG@%@sgs th? g#%@^@#$ chào^#^$#!abc35| _ sgs _35 hello world không gsg
Sample Output: SG%sgs th? g#%^#$ chào^#^$#!abc35 sgs 35 hello world không gsg

    class Program
    {
        static void Main(string[] args)
        {
            string inputString = "SG@%@sgs thể g#%@^@#$ chào^#^$#!abc35| _ sgs _35 hello world không gsg";

            string outputString = inputString.Replace("@", "").Replace("|", "").Replace("_", "");

            Console.WriteLine(inputString);
            Console.WriteLine(outputString);
            Console.ReadKey();
        }
    }

Factorial Calculator using C#

Factorial is a positive number is the product of all number less than or equal to the positive number.
For example:

0! = 1
1! = 1
2! = 2 * 1! = 2
3! = 3 * 2! = 6

n! = n * (n – 1)!

Here is the sample code to calculate Factorial using both loop and recursion using c#.


///

/// Author: Md. Mahedee Hasan
///

class Program
{
static void Main(string[] args)
{
int number = 0;
Console.WriteLine(“Enter an integer number to calculate factorial: “);
Int32.TryParse(Console.ReadLine(), out number);

Console.WriteLine(“Factorial of ” + number + ” is: ” + CalculateFactoial(number));
Console.WriteLine(“Factorial of ” + number + ” is: ” + Factorial(number));
Console.ReadLine();
}

//Calculate factorial using loop

private static int CalculateFactoial(int number)
{
int factorial = 1;
for (int counter = 1; counter <= number; counter++) { factorial = factorial * counter; } return factorial; } //Calculate factorial using recursion private static int Factorial(int number) { if (number == 0) return 1; else return number * Factorial(number – 1); } } [/csharp]

How to check Palindrome word using C#

Palindrome word can be read in both direction. Suppose “level” can be read in both direction, so it is palindrome word. To check palindrome word you can try like following code using C#.


    class Program
    {
        public static bool IsPalindrome(string word)
        {
            int minLength = 0;
            int maxLength = word.Length - 1;
            while (true)
            {
                if (minLength > maxLength)
                {
                    return true;
                }
                char a = word[minLength];
                char b = word[maxLength];
                if (char.ToLower(a) != char.ToLower(b))
                {
                    return false;
                }
                minLength++;
                maxLength--;
            }
        }

        static void Main()
        {
            string[] palindromeWord = {"aibohphobia","Dhaka","alula","cammac","Civic", "deified","deleveled",
                                 "detartrated","devoved","History","evitative","level","","mahedee"};

            foreach (string word in palindromeWord)
            {
                if (IsPalindrome(word))
                {
                    Console.WriteLine(word + " is a Palindrome");
                }
                else
                {
                    Console.WriteLine(word + " is not a Palindrome");
                }
            }
            Console.ReadKey();
        }
    }

How to find prime number between 1 to n


class Program
{
static void Main(string[] args)
{
//int n = 100000;
int n = 0;
Console.WriteLine(“Type an integer number to get prime number between 1 to n”);
Int32.TryParse(Console.ReadLine(), out n);
PrintPrimes(n);
}

public static void PrintPrimes(int n)
{
bool isPrime = false;
for (int i = 2; i < n; i++) { isPrime = true; for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) Console.Write(i + ” “); } Console.ReadKey(); } } [/csharp] [wpdm_file id=51]

Draw star pyramid using C#

Sample input: 5
Sample output:

code-01

Code:


/*Author: Md. Mahedee Hasan*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StarPyramid
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter a number to draw pyramid: “);
int nRow = 0;
nRow = Convert.ToInt32(Console.ReadLine());

for (int row = 1; row <= nRow; row++) { for (int leftSpace = row; leftSpace <= nRow; leftSpace++) { Console.Write(” “); } for (int star = 1; star <= 2 * row – 1; star++) { Console.Write(“*” + ” “); //Print star and space } Console.WriteLine(); } Console.ReadKey(); } } } [/csharp] [wpdm_file id=50]