Friday 3 June 2016

ASP.NET MVC - How To Show A Popup Warning Before Session Timeout - ASP.NET MVC

This article is basically for how to add a friendly 'Session Timeout' warning alert message to your ASP.NET MVC website using simple jquery code. This helps you to:

    Display a warning message before a user's session times out and
    Allow the end-user to continue the session or log them our automatically



Session Timeout

1) Session Timeout is a property that you can set in your web.config file to control when a user session should expire.

2) Unfortunately, your end-users don't know when their session will expire unless you notify them somehow.

Popup Warning

One of the best way to notify your end-users is using a popup warning dialog. You may have seen these types of popups on your bank's website.

Web.Config Form Authentication code:-



<system.web>
    <httpRuntime maxRequestLength="1048576" executionTimeout="36000" targetFramework="4.5" requestValidationMode="2.0" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Login/Login" timeout="3" slidingExpiration="true" />
    </authentication>
</system.web>


Layout Page:-

Alert message html added in layout page.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Crop Images", "CropImage", "Home")</li>
                    <li>@Html.ActionLink("Fb Like Crop Images", "CropImageLikeFb", "Home")</li>
                    <li>@Html.ActionLink("Croper Image", "CroperImage", "Home")</li>
                    <li>@Html.ActionLink("Demo Croper Image", "DemoCropper", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

 

<div id="divPopupTimeOut" style="display:none; text-align: left; margin-top:15px; width:280px !important; position:fixed; top:40px; right:0px; z-index:9999; height:165px;" class="alert alert-warning">
    <div class="row" style="margin-top:10px; margin-left:10px;">
        Your session is about to expire! 
        <br />
        <span id="CountDownHolder"></span>
        <br />
        Click OK to continue your session.
    </div>
    <div class="row">
        <div class="text-center button-block" style="text-align:center; margin-top:22px;">
            <button type="button" class="btn btn-default btn-sm" onclick="SessionTimeout.sendKeepAlive();">@ResourcesLang.OK</button>
            <button type="button" class="btn btn-default btn-sm" onclick="SessionTimeout.hidePopup();">@ResourcesLang.Cancel</button>
        </div>
    </div>
</div> 
 
@functions {
    public int PopupShowDelay
    {
        get
        {
            return 1000 * (Convert.ToInt32(FormsAuthentication.Timeout.TotalSeconds) - 130);
        }
    }
 } 
 


Jquery Code:-


<script type="text/javascript">
    var loginUrl='@Url.Action("Login", "Login")';
    var extendMethodUrl='@Url.Action("ExtendSession","Dashboard")';
    $(document).ready(function(){
            SessionTimeout.schedulePopup();
        });

    window.SessionTimeout = (function() {
            var _timeLeft, _popupTimer, _countDownTimer;
            var stopTimers = function() {
                window.clearTimeout(_popupTimer);
                window.clearTimeout(_countDownTimer);
            };
            var updateCountDown = function() {
                var min = Math.floor(_timeLeft / 60);
                var sec = _timeLeft % 60;
                if(sec < 10)
                    sec = "0" + sec;

                document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;

                if(_timeLeft > 0) {
                    _timeLeft--;
                    _countDownTimer = window.setTimeout(updateCountDown, 1000);
                } else  {
                    document.location = loginUrl;
                }
            };
            var showPopup = function() {
            $("#divPopupTimeOut").show();
                _timeLeft = 120;
                updateCountDown();
            };
            var schedulePopup = function() {
            $("#divPopupTimeOut").hide();
                stopTimers();
                _popupTimer = window.setTimeout(showPopup, @PopupShowDelay);
            };
            var hidePopup=function(){
            $("#divPopupTimeOut").hide();
            };
            var sendKeepAlive = function() {
                stopTimers();
                $("#divPopupTimeOut").hide();
                $.ajax({
                    type: "GET",
                    url: extendMethodUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function successFunc(response) {
                        SessionTimeout.schedulePopup();
                    },
                    error:function(){
                    }
                });
            };
            return {
                schedulePopup: schedulePopup,
                sendKeepAlive: sendKeepAlive,
                hidePopup:hidePopup,
                stopTimers:stopTimers,
            };

        })();

</script>


Controller Action method code:-

When you click on ok button in session warning message then below mentioned
method is called and it will extend the form authentication timeout time or session
time in your website.


[HttpGet]
 public ActionResult ExtendSession()
 {
    System.Web.Security.FormsAuthentication.SetAuthCookie(User.Identity.Name, false);
    var data = new { IsSuccess = true };
    return Json(data, JsonRequestBehavior.AllowGet);
 }

Wednesday 1 June 2016

How to add prefix of http and https in your url automatically when you enter text like (google.com) in your textbox.

You can add http or https in your url very easily in your textbox by using jquery. This is done by using the jquery blur method you can achieve this result easily.

Below is the jquery code:-

$(document).ready(function () {
 $(selector).blur(function () {
            unSavedChangesInPopup = true;
            var input = $(this);
            var val = input.val();
            if (val && !val.match(/^http([s]?):\/\/.*/)) {
                switch (val) {
                    case 'http':
                        input.val(val + '://www.');
                        break;
                    case 'http:':
                        input.val(val + '//www.');
                        break;
                    case 'http:/':
                        input.val(val + '/www.');
                        break;
                    case 'https':
                        input.val(val + '://www.');
                        break;
                    case 'https:':
                        input.val(val + '//www.');
                        break;
                    case 'https:/':
                        input.val(val + '/www.');
                        break;
                    case 'www':
                        input.val(val + '/www.');
                        input.val('http://' + val + '.');
                        break;
                    default:
                        input.val('http://www.' + val);
                        break;

                }
                
            }
        });
 });

Tuesday 31 May 2016

How to prevent cut, copy and paste by using jquery code.

You can prevent cut, copy and paste in your input type textboxe's or in textarea's by using jquery code very easily.

Below is the jquery code:-

$(document).on('cut copy paste', '.controlClass', function (e) {
        e.preventDefault();
    });

Wednesday 25 May 2016

How to remove or add placeholder in dynamically created textboxes through using jquery.

In this article, I am going to show you how to remove or add placeholder in dynamically created html  input type textboxes. By using jquery you can easily add or remove placeholder text.

Below is the jquery code:-

 $(document).on({
        'focus': function () {
            // something
            $(this).attr('placeholder', '');
        },
        'blur': function () {
            // something
            $(this).attr('placeholder', 'Your placeholder text here');
        }
    }, 'input.myClass');


Thursday 19 May 2016

How to map your Web Access Layer List type of model to Data Access model in ASP.NET MVC by using Automapper.

In this article, I am going to show you how to map your Web Access Layer list type of model to Data Access Layer model. For that you have to use Automapper class for mapping that model classes.


Step 1:- Model class

namespace WebAccessLayer.Models
{
    public class DropListModel
    {
    public int? Id { get; set; }
        public string Title { get; set; }
    }
}

namespace DataAccessLayer.Models
{
    public class DropListModel
    {
    public int? Id { get; set; }
        public string Title { get; set; }
    }
}



Step 2:- Controller Code:-

[HttpPost]
public ActionResult Test(DropListModel oModel)
{
    AutoMapper.Mapper.Map<WebAccessLayer.Models.DropListModel , DataAccessLayer.Models.DropListModel>(oModel);
    return View(oModel);
}  


Mapping List type of Model code:-

public ActionResult Test2(List<DropListModel> oModel)
{
    AutoMapper.Mapper.Map<List<WebAccessLayer.Models.DropListModel>, List<DataAccessLayer.Models.DropListModel>>(oModel);
    return View(oModel);
}

How to access asp.net mvc model fields values in jquery code.

You can access mvc model values in jquery by using Newtonsoft json serializer. It serialize your model object. And then you have to stringify that object by using JSON.stringify method of javascript and store that values in a vriable. After that you have to parses that stored value in a new variable by using JSON.parse method.

 Following are the javascript code how to access model fields value in javascript or in jquery.

 Model classes:-

namespace Demo.Models
{
    public class DropListModel
    {
    public int? Id { get; set; }
        public string Title { get; set; }
    }


    public class TestViewModel
    {
  
    private List<DropListModel> _DayList;
        public IEnumerable<SelectListItem> DayList
        {
            get
            {
                _DayList = new List<DropListModel>();
                _DayList.Add(new DropListModel() { Id = 0, Title = Resources.Select });
                for (int i = 1; i <= 31; i++)
                {
                    _DayList.Add(new DropListModel() { Id = i, Title = i.ToString() });
                }
                return new SelectList(_DayList, "Id", "Title");
            }
        }

    }

}


Controller Code here:-

public ActionResult AccessModelFiledValue(long id)
{
    TestViewModel oModel = new TestViewModel();
    return View(oModel);
}

AccessModelFiledValue.cshtml page code:-


@model Demo.Models.TestViewModel
@{
    ViewBag.Title = "Test";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
          
        </div>
</div>

//Javascript code here:-
<script type="text/javascript">

var serializedObject = JSON.stringify(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model.DayList)));

        var yourJsonData = JSON.parse(serializedObject );


</script>

Thursday 5 May 2016

How to upload, resize, crop and maintain aspect ratio of images in asp.net mvc with jquery.

   This article is basically for how to resize or cropping the images. How you can
   handle your images when you want to upload on website where the images
   container or dimensions are in fixed size. In this article  we will learn
  step by step how to resize images on the basis of heightwise and widthwise. First
  of all we need to find out the image orientation (It is a landscape
  image or portrait image) and then start resizing process.

    Note 1:- We need to calculate aspect ratio of origianl image.
    eg. original image Height=3456, Width=5184
       aspect ratio=1.5

    Note 2:- Calculate aspect ratio of fixed size whatever you mention.
    eg. height=160,width=255
        aspect ratio= 1.5
    Formula for clculate aspect ratio (double aspect = (double)srcWidth / (double)srcHeight;)


    How to crope image file?
    I have used Jquery.Jcrop.min.js file for cropping process.

    <link href="~/Content/cssNew/jquery.Jcrop.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="~/Scripts/jquery.Jcrop.min.js"></script> 





  Step 1:- Html 

    --------------------HTML for cropping image -------------
 
 
 
 
 
    
<div>
    <input class="ImageClassBanner" type="file" name="ImageClassBanner" id="HeaderBannerImageFile" />
    </div>

    <div id="divCropBannerImage" style="text-align:center; float:left;width:100%; display:none;">
                                            <img id="imgBannerForCrop" style="text-align:center; margin-

    top:20px;" />
                                            <p style="margin-top:10px;">

                                                <a id="pCropBannerImageButton" onclick="cropImage

    ('imgBannerForCrop');" class="btn btn-default btn-sm hide_element">Crop Image</a>

                                            </p>

                                        </div>

    <div>
    <img id="CroppedImage"/>
    </div>
Step 2:- Upload image file by using the jquery code. In this code i have applied the validation check
         upload only(jpg,jpeg,png,gif,bmp) files. After 
         uploaded the file then applied jcrop functionality on
         recently upload image file.
 
 
 


-------- Jquery code for upload image file and applied validation check....

        <script type="text/javascript">

        $(document).on("change", ".ImageClassBanner", function (event) {
                var UploadImage = "/Home/Image";
                var flag = false;
                var file = getNameFromPath($(this).val());
                if (file != null) {
                    var extension = file.substr((file.lastIndexOf('.') + 1));
                    switch (extension.toLowerCase()) {
                        case 'jpg':
                        case 'jpeg':
                        case 'png':
                        case 'gif':
                        case 'bmp':
                            flag = true;
                            break;
                        default:
                           flag = false;
                    }
                }

                if (flag == false) {
                    alert(popupAlertUploadOnlyImage);
                    return false;
                }
                if (flag == true) {
                    files = event.target.files;
                    if (10 > (event.target.files[0].size / 1048576)) {
                        var reader = new FileReader();
                        //Read the contents of Image File.
                        reader.readAsDataURL(files[0]);
                        reader.onload = function (e) {
                            //Initiate the JavaScript Image object.
                            var image = new Image();
                            //Set the Base64 string return from FileReader as source.
                            image.src = e.target.result;
                            image.onload = function () {
                                //Determine the Height and Width.
                                var height = this.height;
                                var width = this.width;
                                var imageType = 2;
                                var contentType = "multipart/form-data";
                                var fd = new FormData();
                                var URL = UploadImage;
                                fd.append("Image", files[0]);
                                fd.append("ImageName", "");
                                fd.append("ImageType", imageType);
                                fd.append("ImageHeight", height);
                                fd.append("ImageWidth", width);
                                $.ajax({
                                   url: URL,
                                    type: "post",
                                    data: fd, processData: false, contentType: false,
                                    success: function (response) {
                                        if (response.IsSuccess) {
                                            $('#divCropBannerImage').show();

                                            // destroy Jcrop if it is existed
                                            if (typeof jcrop_api != 'undefined') {
                                                jcrop_api.destroy();
                                                jcrop_api = null;
                                                $('#imgBannerForCrop').attr({ 'src': 
    response.OriginalImagePath + response.ImagePath + "?t=" + new Date().getTime(), 'width': 
    response.ImageHeightWidth.Width, 'height': response.ImageHeightWidth.Height }).css({ 'height': 
    response.ImageHeightWidth.Height, 'width': response.ImageHeightWidth.Width })
                                            }
                                            else {
                                                $('#imgBannerForCrop').attr({ 'src': 
    response.OriginalImagePath + response.ImagePath + "?t=" + new Date().getTime(), 'width': 
    response.ImageHeightWidth.Width, 'height': response.ImageHeightWidth.Height }).css({ 'height': 
    response.ImageHeightWidth.Height, 'width': response.ImageHeightWidth.Width })
                                            }
     
                                            $('#imgBannerForCrop').attr('ImageName', response.ImagePath);
                                            $('#pCropBannerImageButton').show();
                                             initCrop('imgBannerForCrop',255, 160, 255, 160);
                                            //end Jcrop
                                        }
                                        else {
                                            alert(response.Message);
                                        }
                                    },
                                    error: function (data) {
                                    }
                                });
                            };
                        }
                    }
                    else {
                        alert(imageSizeAlertMessage);
                    }
                }
            });



        Step 3:- Below mentioned functions or variables are used for crop the image file.

        // Jquery croping variables and functions

        var imageCropWidth = 155;
            var imageCropHeight = 65;
            var cropPointX = 0;
            var cropPointY = 0;
            var jcrop_api;



        //initialize jcrop on selected image file.
        function initCrop(imageId,minWidth, minHeight, maxWidth, maxHeight) {
                $('#' + imageId).Jcrop({
                    setSelect: [0, 0, maxWidth, maxHeight],
                    onChange: setCoordsAndImgSize,
                    bgOpacity: .5,
                    sideHandles: false,
                    minSize: [minWidth, minHeight],
                    maxSize: [maxWidth, maxHeight]
                }, function () {
                    jcrop_api = this;
                });
            }

        function setCoordsAndImgSize(e) {
                cropPointX = e.x;
                cropPointY = e.y;
                imageCropWidth = e.w;
                imageCropHeight = e.h;

            }

        // This function is used to save the croped image file and display it on the page.
        function cropImage(imageId) {

                var cropImage = "/Home/CropImage";
                if (imageCropWidth == 0 && imageCropHeight == 0) {
                    alert("Please select crop area.");
                    return;
                }

                var data2 = JSON.stringify({
                    imageName: $("#" + imageId).attr("ImageName"), cropPointX: cropPointX, cropPointY: 
    cropPointY,
                    imageCropWidth: imageCropWidth, imageCropHeight: imageCropHeight
                });
                $.ajax({
                    url: cropImage,
                    type: 'POST',
                    data: data2,
                    contentType: 'application/json;charset=utf-8',
                    dataType: 'json',
                    success: function (data) {
                        //Saved and set article crop image
                            $('#divCropBannerImage').hide();
                            $('#CroppedImage').attr('src', data.photoPath + '?t=' + new Date().getTime
    ()).show();
                        //End article image upload
                    },
                    error: function (data) {
                    }
                });
            }

        </script>
 
 
   MVC action method code for save original image file 
   and resige image on the basis of height wise 
   and width wise.


[HttpPost]
            public ActionResult Image(HttpPostedFileWrapper Image, string ImageName,short ImageType, int 
    ImageHeight, int ImageWidth)
            {
                int imgHeight = 0, imgWidth = 0;
                int[] imageDimension;
                string logoImageBase64 = "", fileName = "";
                if (Image == null || Image.ContentLength == 0)
                {
                    return Json(new
                    {
                        Messsage = "No Image",
                        IsSuccess = false
                    }, JsonRequestBehavior.AllowGet);
                }
                fileName = String.Format("{0}.png", Guid.NewGuid().ToString());
                string TemplateImagesPath = "/Content/UploadedImages/";
            string TemplateImagesPathThumb="/Content/UploadedImages/Thumb";

                var templateImagesPath = Path.Combine(Server.MapPath(Url.Content(TemplateImagesPath)), 
    fileName);
                var templateThumbPath = Path.Combine(Server.MapPath(Url.Content(TemplateImagesPathThumb)), 
    fileName);

                Image i = Bitmap.FromStream(Image.InputStream);
                i.Save(templateImagesPath);

            //Get image dimensions on the basis of image orientation.
            imageDimension = Helper.ImageHelper.GetImageDimensions(i, ImageWidth, ImageHeight);
                        if (imageDimension.Length > 0)
                        {
                //Get calculated height and width of image file.
                            int[] heightWidth = Helper.ImageHelper.CalculateImageDimension(imageDimension[0], 
    imageDimension[1], 255, 160);
                            if (heightWidth.Length > 0)
                            {
                    // Resize the image file.
                                var newsletterContentTemplateImage = Helper.ImageHelper.FixedSize(i, 
    Convert.ToInt32(heightWidth[0]), Convert.ToInt32                (heightWidth[1]));
                                newsletterContentTemplateImage.Save(templateThumbPath);
                                imgWidth = Convert.ToInt32(heightWidth[0]);
                                imgHeight = Convert.ToInt32(heightWidth[1]);
                            }
                        }

                return Json(new
                {
                    BaseImagePath = TemplateImagesPath + "thumb/",
                    ImagePath = Url.Content(String.Format("{0}", fileName)),
                    IsSuccess = true,
                    OriginalImagePath = GetSiteRoot() + TemplateImagesPathThumb,
                    ImageHeightWidth = new { Height = imgHeight, Width = imgWidth },
                }, JsonRequestBehavior.AllowGet);
            }


        // This method is used for get the base path of the website.
         private string GetSiteRoot()
            {
                string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
                if (port == null || port == "80" || port == "443")
                    port = "";
                else
                    port = ":" + port;
                string protocol = System.Web.HttpContext.Current.Request.ServerVariables
    ["SERVER_PORT_SECURE"];
                if (protocol == null || protocol == "0")
                    protocol = "http://";
                else
                    protocol = "https://";
                string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables
    ["SERVER_NAME"] + port +         System.Web.HttpContext.Current.Request.ApplicationPath;
                if (sOut.EndsWith("/"))
                {
                    sOut = sOut.Substring(0, sOut.Length - 1);
                }

                return sOut;
            }
    --------------------------------End---------------------------------------------------
     
    -------------------------------Crope image file--------------------------------------------

     This action method is used for save the cropped image and return the cropped image file path result in 
    json format.

        [HttpPost]
            public ActionResult CropImage(string imageName, int? cropPointX, int? cropPointY, int? 
    imageCropWidth, int? imageCropHeight)
            {
                if (string.IsNullOrEmpty(imageName) || !cropPointX.HasValue || !cropPointY.HasValue || !
    imageCropWidth.HasValue || !imageCropHeight.HasValue)
                {
                    return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest);
                }

                byte[] imageBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/UploadedImages/" + 
    imageName));
                byte[] croppedImage = Helper.ImageHelper.CropImage(imageBytes, cropPointX.Value, 
    cropPointY.Value, imageCropWidth.Value, imageCropHeight.Value);

                string tempFolderName = Server.MapPath("~/Content/UploadedImages/CroppedImages/");
                string fileName = imageName;//Path.GetFileName(imagePath);
                try
                {
                    Helper.FileHelper.SaveFile(croppedImage, Path.Combine(tempFolderName, fileName));
                }
                catch (Exception ex)
                {
                    //Log an error     
                    return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                }
                string photoPath = string.Concat("/Content/UploadedImages/CroppedImages/", "/", fileName);
                return Json(new { photoPath = photoPath }, JsonRequestBehavior.AllowGet);
            }

    ------------------------------------------------------------------------

    ---------------------------Helper class--------------------------------

    namespace Application.Helper
    {
        public static class FileHelper
        {
            public static void SaveFile(byte[] content, string path)
            {
                string filePath = GetFileFullPath(path);
                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                }

                //Save file
                using (FileStream str = File.Create(filePath))
                {
                    str.Write(content, 0, content.Length);
                }
            }

            public static string GetFileFullPath(string path)
            {
                string relName = path.StartsWith("~") ? path : path.StartsWith("/") ? string.Concat("~", 
    path) : path;

                string filePath = relName.StartsWith("~") ? HostingEnvironment.MapPath(relName) : relName;

                return filePath;
            }
        }

        public static class ImageHelper
        {
            public static byte[] CropImage(byte[] content, int x, int y, int width, int height)
            {
                using (MemoryStream stream = new MemoryStream(content))
                {
                    return CropImage(stream, x, y, width, height);
                }
            }

            public static byte[] CropImage(Stream content, int x, int y, int width, int height)
            {
                //Parsing stream to bitmap
                using (Bitmap sourceBitmap = new Bitmap(content))
                {
                    //Get new dimensions
                    double sourceWidth = Convert.ToDouble(sourceBitmap.Size.Width);
                    double sourceHeight = Convert.ToDouble(sourceBitmap.Size.Height);
                    Rectangle cropRect = new Rectangle(x, y, width, height);

                    //Creating new bitmap with valid dimensions
                    using (Bitmap newBitMap = new Bitmap(cropRect.Width, cropRect.Height))
                    {
                        using (Graphics g = Graphics.FromImage(newBitMap))
                        {
                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                           g.SmoothingMode = SmoothingMode.HighQuality;
                            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            g.CompositingQuality = CompositingQuality.HighQuality;
                            g.DrawImage(sourceBitmap, new Rectangle(0, 0, newBitMap.Width, newBitMap.Height), 
    cropRect, GraphicsUnit.Pixel);

                            return GetBitmapBytes(newBitMap);
                        }
                    }
                }
            }

            public static byte[] GetBitmapBytes(Bitmap source)
            {
                //Settings to increase quality of the image
                ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4];
                EncoderParameters parameters = new EncoderParameters(1);
                parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

                //Temporary stream to save the bitmap
                using (MemoryStream tmpStream = new MemoryStream())
                {
                    source.Save(tmpStream, codec, parameters);
                    //Get image bytes from temporary stream
                    byte[] result = new byte[tmpStream.Length];
                    tmpStream.Seek(0, SeekOrigin.Begin);
                    tmpStream.Read(result, 0, (int)tmpStream.Length);
                    return result;
                }
            }

           This method is used for calcualte the aspect ratio of the original image file. Moreover it also 
           calculate the aspect ratio of  user defined dimensions (eg. maxWidth=255 and maxHeight=160) and calcuate 
           the expected height and width of the image and return that dimension back to the calling method.

            public static int[] CalculateImageDimension(int srcWidth, int srcHeight, int maxWidth, int 
    maxHeight)
            {
                double resizeWidth = 0.00, resizeHeight = 0.00;
                double maxAspect = (double)maxWidth / (double)maxHeight;
                double aspect = (double)srcWidth / (double)srcHeight;

                if (maxAspect > aspect && srcWidth > maxWidth)
                {
                    //Width is the bigger dimension relative to max bounds
                    resizeWidth = maxWidth;
                    resizeHeight = maxWidth / aspect;
                }
                else if (maxAspect <= aspect && srcHeight > maxHeight)
                {
                    //Height is the bigger dimension
                    resizeHeight = maxHeight;
                    resizeWidth = maxHeight * aspect;
                }
                else
                {
                    resizeHeight = maxHeight;
                    resizeWidth = maxWidth;
                }
                int[] heightWidth = new[] { Convert.ToInt32(resizeWidth), Convert.ToInt32(resizeHeight) };
                return heightWidth;
            }

        This method is used to get the orientation of the image.
        eg. You have taken image from your mobile and image orientation is landscape wise, portrait wise etc. 
        Sometimes if you upload very big size portrait image and you find the height of image convert it into 
        width and width into height in that situation you have to maintain original orientatio then use below 
        mentioned code. It will provide you the original orientation of image.


            public static int[] GetImageDimensions(Image imgPhoto, int Width, int Height)
            {
                #region Check Orientaion
                if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    var prop = imgPhoto.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value, 
    0);
                        if (orientationExif == 8)
                        {   //Swaping the Width with Height as Required
                            int var = Width;
                            Width = Height;
                            Height = var;
                        }
                        else if (orientationExif == 3)
                        {
                            //Swaping the Width with Height as Required
                            int var = Width;
                            Width = Height;
                            Height = var;
                        }
                        else if (orientationExif == 6)
                        {
                            //Swaping the Width with Height as Required
                            int temp = Width;
                            Width = Height;
                            Height = temp;
                        }
                    }
                }
                #endregion

                #region Return and Free Memory
                int[] heightWidth = new[] { Width, Height };
                return heightWidth;
                #endregion
            }

        This method is used to resize the image file. I have passed fixed size of image dimensions and this 
        method will resize the image on the basis of fixed height and width.

            public static Image FixedSize(Image imgPhoto, int Width, int Height)
            {

                #region Check Orientaion
                int isRorated = 0;
                if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    var prop = imgPhoto.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value, 
    0);
                        if (orientationExif == 8)
                        {   //Swaping the Width with Height as Required
                            isRorated = 8;
                            int var = Width;
                            Width = Height;
                            Height = var;
                        }
                        else if (orientationExif == 3)
                        {
                            //Swaping the Width with Height as Required
                            isRorated = 3;
                            int var = Width;
                            Width = Height;
                            Height = var;
                        }
                        else if (orientationExif == 6)
                        {
                            //Swaping the Width with Height as Required
                            isRorated = 6;
                            int temp = Width;
                            Width = Height;
                            Height = temp;
                        }
                    }
                }

                #endregion

                #region Generate Thumbnail
                int sourceWidth = imgPhoto.Width;
                int sourceHeight = imgPhoto.Height;
                int sourceX = 0;
                int sourceY = 0;
                int destX = 0;
                int destY = 0;
                float nPercent = 0;
                float nPercentW = 0;
                float nPercentH = 0;
                nPercentW = ((float)Width / (float)sourceWidth);
                nPercentH = ((float)Height / (float)sourceHeight);
                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentH;
                    destX = System.Convert.ToInt16((Width -
                                  (sourceWidth * nPercent)) / 2);
                }
                else
                {
                    nPercent = nPercentW;
                    destY = System.Convert.ToInt16((Height -
                                  (sourceHeight * nPercent)) / 2);
                }

                int destWidth = (int)(sourceWidth * nPercent);
                int destHeight = (int)(sourceHeight * nPercent);

                Bitmap bmPhoto = new Bitmap(Width, Height,
                                  PixelFormat.Format32bppArgb);
                bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                 imgPhoto.VerticalResolution);
                Graphics grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.Clear(System.Drawing.Color.Transparent);
                grPhoto.InterpolationMode =
                        InterpolationMode.HighQualityBicubic;
     
                grPhoto.DrawImage(imgPhoto,
                    new Rectangle(destX, destY, destWidth, destHeight),
                    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                    GraphicsUnit.Pixel);

                switch (isRorated)
                {
                    case 8:
                        bmPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        break;
                    case 6:
                        bmPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        break;
                    case 3:
                        bmPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        break;
                    default:
                        break;
                }
                #endregion
                #region Return and Free Memory
                grPhoto.Dispose();
                return bmPhoto;
                #endregion
            }
        }
    }
 
 
   This is the complete solution for resizing, cropping and
   upload images.
 
 
  Thanks.