Image Resize with auto-crop

Task: Image resize, auto-crop and auto scale.

Description: Here is sample code for image resize with auto-crop while maintaining its ratio. below function we need to pass image path, maximum width and height for resizing. And then below code will resized to given width & height & crop the remaining part which not covered under given measurement. 



public void drawimage(string ThumbnailPath, int maxwidth, int maxheight)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
       
        if (maxheight == 0 || maxwidth == 0)
        {
            maxwidth = image.Width;
            maxheight = image.Height;
        }
        Size ThumbNailSize = setimagesize(maxwidth, maxheight, image.Width, image.Height);

        System.Drawing.Image ImgThnail;
        if (image.Width < maxwidth || image.Height < maxheight)
        {
            ImgThnail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
        }
        else
        {
            ImgThnail = new Bitmap(maxwidth, maxheight);
        }
       
        System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(ImgThnail);
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphics.CompositingQuality = CompositingQuality.HighQuality;

        if (image.Width < maxwidth || image.Height < maxheight)
        {
            graphics.DrawImage(image, 0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
        }
        else
        {
            int xcord = 0;
            int ycord = 0;
            {
                xcord = (ThumbNailSize.Width - maxwidth) / 2;
                ycord = (ThumbNailSize.Height - maxheight) / 2;
            }

            graphics.DrawImage(image, -xcord, -ycord, ThumbNailSize.Width, ThumbNailSize.Height);

        }


        ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

        string sExt = System.IO.Path.GetExtension(ThumbnailPath);

        if (sExt.ToString() == ".png")
        {
            Response.ContentType = "image/png";
            ImgThnail.Save(Response.OutputStream, image.RawFormat);
        }
        else
        {
            Response.ContentType = "image/jpeg";
            ImgThnail.Save(Response.OutputStream, info[1], encoderParameters);
        }
        image.Dispose();

    }




    // below code is my old one for calculating height and width with maintain image ratio.

public Size setimagesize(int maxwidth, int maxheight, int OriginalWidth, int OriginalHeight)
    {
        Size NewSize = new Size();
        if (OriginalHeight < maxheight && OriginalWidth < maxwidth)
        {
            NewSize = new Size(OriginalWidth, OriginalHeight);
            return NewSize;
        }
        int sNewWidth = OriginalWidth;
        int sNewHeight = OriginalHeight;
        int tempheight = 0;
        int tempwidht = 0;

        if (OriginalWidth >= OriginalHeight)
        {
            if (OriginalWidth >= maxwidth)
            {
                sNewWidth = maxwidth;
                sNewHeight = OriginalHeight * maxwidth / OriginalWidth;
            }
            if (sNewHeight < maxheight)
            {
                tempheight = sNewHeight;
                sNewHeight = maxheight;
                sNewWidth = sNewWidth * maxheight / tempheight;
            }
        }
        else
        {
            if (OriginalHeight >= maxheight)
            {
                sNewHeight = maxheight;
                sNewWidth = OriginalWidth * maxheight / OriginalHeight;
            }
            if (sNewWidth < maxwidth)
            {
                tempwidht = sNewWidth;
                sNewWidth = maxwidth;
                sNewHeight = sNewHeight * maxwidth / tempwidht;
            }
        }
        NewSize = new Size(sNewWidth, sNewHeight);
        return NewSize;
    }

WebService with JSON implementation

Task: WebService with JSON implementation in asp.net

Description: Here sample of WebService implementation in asp.net which returns only JSON format, default format of webservice is xml. But we have convert the xml response into JSON format here. As nowdays we need to JSON for IPHON and Android App. Also we can use WebApi which is latest technology. Which we will describe later. 



using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;
using System.Data;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Summary description for MyWebService
/// </summary>
[WebService(Namespace = "http://www.weburl.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService {
   
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void ShowUserDetail(string userid, string accesstoken)
    {
        MyUser myuser = new MyUser();
        List<MyUser> buser = new List<MyUser>();

        bool status = myuser.ShowProfile(userid, accesstoken);
        if (status)
        {
            Status = "Success";
            StatusMessage = "Success With Data";
            buser.Add(bringuser);
        }
        else
        {
            Status = "Failed";
            StatusMessage = "Authentication Failed";
        }

        var resp = new JSONEnvelope<MyUser>(buser, Status, StatusMessage);

        JavaScriptSerializer Machinejson = new JavaScriptSerializer();
        this.Context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
        this.Context.Response.ContentType = "application/json; charset=utf-8"; // to remove xml tag from response
        this.Context.Response.Write(Machinejson.Serialize(resp));
    }

}


Here is Class for getting Data from database . 


/// <summary>
/// Summary description for MyUser
/// </summary>
public class MyUser
{
      public int Id { get; set; }
      public string UserName { get; set; }
      public string firstName { get; set; }
      public string Email { get; set; }
      public string phone { get; set; }
      public string profile_pic_url { get; set; }
      public string shortdescrition { get; set; }

public bool ShowProfile(string userid, string accesstoken)
      {
          DataLayer dl = new DataLayer();
          DataTable dt = dl.GetProfile(useridaccesstoken ); // Return Datatable
          if (dt.Rows.Count > 0)
          {
              Id = Convert.ToInt32(dt.Rows[0]["id"]);
              UserName = dt.Rows[0]["username"].ToString();
              firstName = dt.Rows[0]["firstname"].ToString();
              Email = dt.Rows[0]["email"].ToString();
              phone = dt.Rows[0]["phone"].ToString();
              profile_pic_url = dt.Rows[0]["profile_pic_url"].ToString();
              shortdescrition = dt.Rows[0]["shortdescription"].ToString();
              return true;
          }
          return false;
      }
}
 


Here Class for generating a Envelope for JSON response. 


public class JSONEnvelope<T>
{
    public List<T> Data { get; private set; }
    public string Status { get; set; }
    public string StatusMessage { get; set; }

    public JSONEnvelope(IEnumerable<T> items, string status, string statusmessage)
    {
        Data = new List<T>(items);
        Status = status;
        StatusMessage = statusmessage;
    }
}

useful web config code asp.net

Task: Some useful web.config code. eg. URL Rewriting/ Remove Etag / Remove Server Header/ Enable Gzip and few more..


Description: Some Useful web-config code which used for URL Rewriting and do many more things.

1) Define database connection in web.config. the connectionStrings tag should be in <configuration> tag.
<connectionStrings>
<add name="ConnectNEw" connectionString="Data Source=APC\SQLEXPRESS;Initial Catalog=database_db;user id=user_8; pwd=Pass@L#7Mad87" providerName="System.Data.SqlClient"/>
</connectionStrings>


2) Define Execution timeout and max request length using <httpRuntime> tag. it should be in <system.web> tag. Here we can also define the session mode and its timeout value.
<system.web>
<httpRuntime enableVersionHeader="false"  executionTimeout="2400" maxRequestLength="20480" />
<sessionState mode="InProc" cookieless="false" timeout="80"></sessionState>
</system.web>



3) Etag and Server Header and other Redirect rule (Default page redirect, www redirect , https redirect)
<system.webServer>
    <rewrite>
      <outboundRules>
        <rule name="Remove ETag" >
          <match serverVariable="RESPONSE_ETag" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
        <rule name="Remove Server header">
          <match serverVariable="RESPONSE_Server" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
      </outboundRules>
      <rules>


 <!--<Redirect Without www to www> -->
        <rule name="Redirect to www" stopProcessing="true">
          <match url=".*" />
          <conditions trackAllCaptures="false">
            <add input="{HTTP_HOST}" pattern="^hemantrautela.blogspot.com$" />
          </conditions>
 <action type="Redirect" url="https://www.hemantrautela.blogspot.com/{R:0}" redirectType="Permanent"/>
        </rule>

 <!--<Redirect default.aspx to domain name> -->
        <rule name="default.aspx Redirect" stopProcessing="true">
          <match url="^(.*\/)*default\.aspx$"/>
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_METHOD}" negate="true" pattern="^POST$"/>
          </conditions>
          <action type="Redirect" url="{R:1}" redirectType="Permanent"/>
        </rule>

<!--<Redirect http to https - Non Secure to Secure page> -->
        <rule name="Redirect to https" stopProcessing="true" enabled="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>



4)Add MIME type (A List for various mime type : https://www.sitepoint.com/web-foundations/mime-types-complete-list/)
<system.webServer>
 <staticContent>
     <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
      <remove fileExtension=".kml" />
      <mimeMap fileExtension=".kml" mimeType="application/vnd.google-earth.kml+xml" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".eot" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
    </staticContent>
</system.webServer>



5) Security Headers - X-Content-Type: nosniff & Other

<system.webServer>
<httpProtocol>
      <customHeaders>
        <remove name="Vary"></remove>
        <add name="Vary" value="Accept-Encoding"></add>
          <remove name="X-Powered-By"></remove>
          <add name="X-Frame-Options" value="SAMEORIGIN"></add>
          <add name="X-XSS-Protection" value="1; mode=block"></add>
          <add name="X-Content-Type-Options" value="nosniff "></add>
      </customHeaders>
    </httpProtocol>
</system.webServer>
 



6) Gzip Compression

<system.webServer>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
      <dynamicTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
      </staticTypes>
    </httpCompression>

    <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>