Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

How to enable CORS in web API2

In this post I am going to show you a very simple and useful tips that how to enable CORS in web API2.
What is CORS
Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from anotherdomain outside the domain from which the resource originated
How to enable in CORS in web API2
In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Cors
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
 public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

How To Change your ASP.Net controls at runtime

Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for SafeTextBox
///
public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = System.Web.HttpUtility.HtmlEncode(value);
        }
    }
}

Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

<pages> <tagMapping> <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/> </tagMapping> </pages>
After we add the following line of code in the web.config file all the TextBox control will be mapped to the TextBox.

How to change some text before it is sent to the client.

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           Hello World!
           <br />
           Hi
       </div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class InterceptHtml : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       Response.Filter = new ReplaceHTML(Response.Filter);


   }
   /// <summary>
   /// Second Method!!!!!!! overide the Render Method.
   /// </summary>
   /// <param name="writer"></param>
   protected override void Render(HtmlTextWriter writer)
   {


       StringWriter output = new StringWriter();
       base.Render(new HtmlTextWriter(output));
       writer.Write(output.ToString().Replace("Hi", "This is the replaced text!
Welcome to <a href=\"http://www.aspdotnetcodebook.blogspot.com\
">www.aspdotnetcodebook.blogspot.com</a>"));
   }
}
II nd Method
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// To intercept and get a reference to the HTML, we now need to create a
/// class to inherit System.IO.Stream. So, create a new class in
/// </summary>
public class ReplaceHTML : System.IO.Stream
{

    private System.IO.Stream Base;

    public ReplaceHTML(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }






    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.Base.Read(buffer, offset, count);
    }


    public override void SetLength(long value)
    {

    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        // Get HTML code 
        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);

        // Replace the text with something else 
        HTML = HTML.Replace("Hello World!", "I've replaced the Hello World example!");

        // Send output 
        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

    public override bool CanRead
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanSeek
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanWrite
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override void Flush()
    {
        HttpContext.Current.Response.Flush();

    }

    public override long Length
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override long Position
    {
        get
        {
            throw new Exception("The method or operation is not implemented.");
        }
        set
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

How to create custom config section in asp.net

You can extend ASP.NET configuration settings with XML configuration elements of
your own. To do this, you create a custom configuration section handler.
The handler must be a .NET Framework class that inherits from 
the System.Configuration.ConfigurationSection class. The section handler 
interprets and processes the settings that are defined in XML configuration 
elements in a specific section of a Web.config file. You can read and write 
these settings through the handler's properties.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
            {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

How to read namespace based xml using Linq

In this post,I will show you how to read xml with namespace.For this demo,I will use following xml

structure

<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="urn:account">
  <account>1001</account>
  <account>1002</account>
</accounts>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("accounts.xml");
            var query = from x in doc.Descendants("{urn:account}account")
                        select x;
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Natural Sorting in asp.net

In this post,I will show you how to implement natural sorting in asp.net.There are several ways to implement this,but in this post,I am going to use windows api.

Check out following link for more details

StrCmpLogicalW (shlwapi)

Let's start the implementation



Create a new class named FileList and add following code




Create a new class in App_Code folder and add following code




Here is complete source code

FileList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class FileList
{
    public FileList()
    {
    }
    public string Name { get; set; }
    public DateTime DateModified { get; set; }
    public string FileType { get; set; }
    public static List<FileList> List
    {
    get
        {
    return new List<FileList>
            {
    new FileList{Name="file11.txt",DateModified=DateTime.Now,FileType="Text"},
    new FileList{Name="file1.txt",DateModified=DateTime.Now,FileType="Text"},
    new FileList{Name="file21.exe",DateModified=DateTime.Now,FileType="Application"},
    new FileList{Name="file100.mp3",DateModified=DateTime.Now,FileType="MultiMedia"},
    new FileList{Name="file19011.jpg",DateModified=DateTime.Now,FileType="iamge"},
            };
        }
    }
}

NaturalSort.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security;
using System.Runtime.InteropServices;
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}
public sealed class NaturalFileComparer : IComparer<FileList>
{
    public int Compare(FileList x, FileList y)
    {
    return SafeNativeMethods.StrCmpLogicalW(x.Name, y.Name);
    }
}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    
    </div>
    <asp:Button ID="btnSort" runat="server" onclick="btnSort_Click" Text="Sort" />
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSort_Click(object sender, EventArgs e)
    {
    var list = FileList.List;
        list.Sort(new NaturalFileComparer());
        GridView1.DataSource = list;
        GridView1.DataBind();
    }
}


Calling cross domain wcf service using Jquery

In this post,I will show you how to call cross domain service using jquery.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;

namespace CorssDomainService
{
    [DataContract]
    public class Order
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
        [DataMember]
        public string Name { get; set; }

    }
    [ServiceContract]
    public interface IOrderService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/",
           ResponseFormat = WebMessageFormat.Json
   )]
        string ProcessOrder();

    }
    [ServiceBehavior]
    public class OrderService : IOrderService
    {
        [OperationBehavior]
        public string ProcessOrder()
        {
            Order order = new Order
            {
                ID = 1,
                OrderDate = DateTime.Now,
                Name = "Laptop"

            };

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Order));
            MemoryStream stream = new MemoryStream();
            json.WriteObject(stream, order);
            return Encoding.UTF8.GetString(stream.ToArray());

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(OrderService));
            host.Open();
            Console.WriteLine("Service is ready");
            Console.ReadLine();
        }
    }
}
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="CorssDomainService.OrderService" behaviorConfiguration="serviceBehave">
        <endpoint address="rest" bindingConfiguration="crossDomain"  behaviorConfiguration="enableScriptBehaviour"
                  binding="webHttpBinding"
                  contract="CorssDomainService.IOrderService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9090/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehave">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="mex"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="enableScriptBehaviour">
          <webHttp></webHttp>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
Now,create a website in visual studio,and paste following code into it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("http://localhost:9090/Rest?callback=?", null, function (data) {
                alert(data);
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

How to validate asp.net form using Jquery

In this post I will show you how to validate asp.net form using jqery. Create a new website,add a new js file ,and add following code inside it
function validateForm(e) {
    var formIsValid = true;
    // check that a valid email address has been entered
    var emailRegExp = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/;
    if (!emailRegExp.test(String($("#txtEmail").val()).toUpperCase())) {
        addError("txtEmail", "Please enter a valid email address.");
        formIsValid = false;
    } else {
        removeError("txtEmail");
    }

    // check that first name has one or more characters
    if ($("#txtFirstName").val() == '') {
        addError("txtFirstName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtFirstName");
    }
    // check that last name has one or more characters
    if ($("#txtLastName").val() == '') {
        addError("txtLastName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtLastName");
    }

    // check that a valid phone number is entered
    var phoneRegExp = /^\(?[1-9]\d{2}\)?\s?\-?\.?\d{3}\s?\-?\.?\d{4}$/;
    if (!phoneRegExp.test($("#txtPhone").val())) {
        addError("txtPhone", "Valid phone number required.");
        formIsValid = false;
    } else {
        removeError("txtPhone");
    }

    if (!formIsValid) {
        e.preventDefault();
    }
}

function addError(id, msg) {
    if ($("#" + id).parent().find("label[class=error]").attr("generated") == "true") {
        $("#" + id).parent().find("label[class=error]").css("display", "block");
    } else {
        $("#" + id).parent().append('<label for="' + id + '" generated="true" class="error">' + msg + '</label>').css("display", "block");
    }
}
function removeError(id) {
    $("#" + id).parent().find("label[class=error]").css("display", "none");
}
Add a new page.Then add reference of jquery and above js file
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="Scripts/Validation.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".submitForm").click(function (e) {
                validateForm(e);
            });
        });
    </script>
    <style type="text/css">
    .error{color:Red;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                FirstName
            </td>
            <td>
                <asp:TextBox ID="txtFirstName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                LastName
            </td>
            <td>
                <asp:TextBox ID="txtLastName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Phone Number
            </td>
            <td>
                <asp:TextBox ID="txtPhone"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Email
            </td>
            <td>
                <asp:TextBox ID="txtEmail"  runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>
    <div>
        <input type="button" id="btnSubmit" class="submitForm" value="Submit" />
    </div>
    </form>
</body>
</html>

How to remove duplicates elements from List using IEqualityComparer

In this post,I will show you how to remove duplicate record from List using IEqualityComparer.It has two methods to support the comparison of objects for equality.

Let us suppose that you have a Employee class that has four properties EmployeeID,FirstName,LastName and Age.

public class Employee
{
    public Employee()
    {
    }
    public string EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public List&lt;Employee&gt; Employees
    {
        get
        {
    return new List&lt;Employee&gt;()
            {
    new Employee(){EmployeeID="E001",FirstName="F001",LastName="L001",Age=21},
    new Employee(){EmployeeID="E002",FirstName="F002",LastName="L002",Age=25},
    new Employee(){EmployeeID="E003",FirstName="F003",LastName="L003",Age=26},
    new Employee(){EmployeeID="E001",FirstName="F001",LastName="L001",Age=21},
    new Employee(){EmployeeID="E001",FirstName="F001",LastName="L001",Age=21},
            };
        }
    }
}


In the above class I have added some dummy records which have duplicates elements.Now,let's remove the duplicate elements from the above class using IEqualityComparer interface.


For this right click on the project and add a new class named EmployeeEquality and inherit this class with IEqualityComparer and implement the interface method as shown below


public class EmployeeEquality : IEqualityComparer<Employee>
{
    public bool Equals(Employee x, Employee y)
    {
    if (x.EmployeeID == y.EmployeeID && x.FirstName == y.FirstName && x.LastName == y.LastName && x.Age == y.Age)
    return true;
    return false;
    }
    public int GetHashCode(Employee obj)
    {
    //For shake of simplicity
    return obj.FirstName.GetHashCode();
    }
}

Now,let's display the record on UI

Right click on the project and add new page,and add following code inside it

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Button ID="btnUnSorted" runat="server" OnClick="btnUnSorted_Click" Text="Duplicates" />
    <asp:Button ID="btnWDuplicate" runat="server" OnClick="btnWDuplicate_Click" Text="Without Duplicate" />
    </form>
</body>
</html>

In the code behind add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUnSorted_Click(object sender, EventArgs e)
    {
        Employee employee = new Employee();
        GridView1.DataSource = employee.Employees;
        GridView1.DataBind();
    }
    protected void btnWDuplicate_Click(object sender, EventArgs e)
    {
        Employee employee = new Employee();
        List<Employee> list = employee.Employees;
        var distinctEmployee = list.Distinct(new EmployeeEquality());
        GridView1.DataSource = distinctEmployee;
        GridView1.DataBind();
    }
}
{{Click here for live demo}}

How to sum the value of gridview column using jquery

In this post I will show how to sum the value of gridview column on selection of checkbox .Let us suppose that you have a gridview which has three column named Name,Quantity and Price.Now your requirement is to sum the value of price filed on selection of checkbox.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
    var total;
    //Column index value of price field (Column index start from 1)
    var columnIndexValue = 4;
    var checked = $('input:checkbox').click(function (e) {
    var total = 0.0;
                $("tr:has(:checkbox:checked) td:nth-child(" + columnIndexValue + ")").each(function () {
                    total += parseFloat($(this).text());
                });
                $('#Sum').text("your total is:" + total.toFixed(2));
            });
        });
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkItem" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>
    <asp:Label ID="label2" Text='<%#Eval("Name") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Quantity">
    <ItemTemplate>
    <asp:Label ID="Label1" Text='<%#Eval("Quantity") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Price">
    <ItemTemplate>
    <asp:Label ID="Label2" Text='<%#Eval("Price") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    <div id="Sum">
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        grdItems.DataSource = new Item().Items;
        grdItems.DataBind();
    }
}
public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public List<Item> Items
    {
        get
        {
    return new List<Item>()
                       {
    new Item(){Name = "Item01",Quantity = 10,Price = 180M},
    new Item(){Name = "Item01",Quantity = 11,Price = 184M},
    new Item(){Name = "Item01",Quantity = 12,Price = 190M},
    new Item(){Name = "Item01",Quantity = 13,Price = 110M},
                       };
        }
    }
}

Click here for live Demo

How to read pdf document properties in asp.net

In this post, I will show you how to read the pdf document properties in asp.net.As we know that there is no- such  in-built class in .net framework that read the pdf document.So,for this demo,I will used third-party library iTextSharp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PdfPropertiesReader.aspx.cs"
    Inherits="PdfPropertiesReader" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="pdfProperties" runat="server">
        </div>
    </div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Read Pdf Properties" />
    </form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;

public partial class PdfPropertiesReader : System.Web.UI.Page
{
    private const string FileNmae = @"C:\\temp\\asp.pdf";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder stringBuilder = new StringBuilder();
            // create a reader (constructor overloaded for path to local file or URL)
            PdfReader reader = new PdfReader(FileNmae);
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
            // file properties
            Hashtable infodict = reader.Info;
            foreach (DictionaryEntry kvp in infodict)
            {
                stringBuilder.Append(kvp.Key + "=>" + kvp.Value + "</br>");
            }

            pdfProperties.InnerHtml = stringBuilder.ToString();
        }
        catch (Exception exception)
        {

            Response.Write(exception.Message);
        }
    }
}

How to convert IEnumerable to Html table in asp.net

In this post I will show how to convert IEnumerable to string (Html table).Assume you have a customer class which has three properties named FirstName,LastName and Age.Now,you want to display customer collection on UI.
For this I have created following method which retrives propertyname and value dynamically (using reflection) and return result as string
public static string ToHtmlTable(IEnumerable list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .headerStyle
        {
            background-color: #abc;
        }
        .rowStyle
        {
            background-color: #def;
        }
        .alternateRowStyle
        {
            background-color: #aabbcc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="table" runat="server">
        </div>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        table.InnerHtml = ToHtmlTable(EmployeeDAL.Employees, "", "headerStyle", "rowStyle", "alternateRowStyle");
    }

    public static string ToHtmlTable<T>(IEnumerable<T> list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)
    {

        var result = new StringBuilder();
        if (String.IsNullOrEmpty(tableSyle))
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\">");
        }
        else
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\" class=\"" + tableSyle + "\">");
        }

        var propertyArray = typeof(T).GetProperties();
        foreach (var prop in propertyArray)
        {
            if (String.IsNullOrEmpty(headerStyle))
            {
                result.AppendFormat("<th>{0}</th>", prop.Name);
            }
            else
            {
                result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, prop.Name);
            }
        }

        for (int i = 0; i < list.Count(); i++)
        {
            if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle))
            {
                result.AppendFormat("<tr class=\"{0}\">", i % 2 == 0 ? rowStyle : alternateRowStyle);
            }
            else
            {
                result.AppendFormat("<tr>");
            }

            foreach (var prop in propertyArray)
            {
                object value = prop.GetValue(list.ElementAt(i), null);
                result.AppendFormat("<td>{0}</td>", value ?? String.Empty);
            }
            result.AppendLine("</tr>");
        }
        result.Append("</table>");
        return result.ToString();
    }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

}
public class EmployeeDAL
{
    public static List<Employee> Employees
    {
        get
        {
            return new List<Employee>()
                       {
                           new Employee(){FirstName = "F001",LastName = "L001",Age = 31},
                           new Employee(){FirstName = "F002",LastName = "L002",Age = 32},
                           new Employee(){FirstName = "F003",LastName = "L003",Age = 33},
                           new Employee(){FirstName = "F004",LastName = "L004",Age = 34},
                       };
        }
    }
}

How to fetch header info from given url

In this post I will show how to fetch header info from given url
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace SNIPPET_CS
{
    public class HeaderInfo
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public static List<HeaderInfo> GetHttpResponseHeaders(string url)
        {
            List<HeaderInfo> headerList = new List<HeaderInfo>();
            WebRequest webRequestObject = WebRequest.Create(url);
            WebResponse responseObject = webRequestObject.GetResponse();
            if (responseObject != null)
            {
                headerList.AddRange(from string headerKey in responseObject.Headers
                                    select new HeaderInfo()
                                               {
                                                   Key = headerKey,
                                                   Value = responseObject.Headers[headerKey]
                                               });
                responseObject.Close();
            }

            return headerList;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {

            // Retrieve headers:
            var headers = HeaderInfo.GetHttpResponseHeaders("http://www.google.com");

            // And output them:
            foreach (HeaderInfo headerKey in headers)
                Console.WriteLine("{0}: {1}", headerKey.Key, headerKey.Value);
        }
    }
}

How to encrypt/decrypt data in asp.net using Symmetric algorithm

In this post I am going to show you how to encrypt and decrypt data in asp.net using Symmetric algorithm.Before going to implementation details let discuss some security related terms before.

What is Hashing


Hashing is one-way algorithm, means once the data is hashed you can’t recovered it latter.
Hashing is a cryptographic function that is used to provide a secure fingerprint of data. A common usage you may have encountered is to check a file you have downloaded.

What is Encryption

If you want to secure your data, and latter you want to retrieve the original data. We used encryption because encryption is two-way processes. For encryption we requires following things


Key:Key is a piece of information that is used as an input parameter in encryption. The output of encryption is determined by the key.
Types of Encryption

are two main types of encryption and decryption algorithms, symmetric and asymmetric.

Symmetric:

In symmetric encryption we used same key for encryption and decryption( As the diagram shows the same key is used for encrypting and decrypting the message).DES, Triple DES, RC2 and AES or Rijndael are examples of symmetric algorithms




Asymmetric Encryption:

Asymmetric algorithms use a related key-pair to encrypt and decrypt data. One of the keys in the pair is typically called a public key while the other is called a private key. Data encrypted with a public key can only be decrypted with the private key, and vice-versa. PKI (public key infrastructure) is built based on asymmetric algorithm. RSA is a popular asymmetric algorithm.


What are the steps required for Encryption ?

Follow these steps to encrypt data symmetrically:

  1. Choose an algorithm.
  2. Create or retrieve a key.
  3. Generate the IV.
  4. Convert the clear text data to an array of bytes.
  5. Encrypt the clear text byte array.
  6. Store the encrypted data and the IV.

What are the steps required for Decryption?

Following are the steps required for decrypting the data.


  1. Choose the same algorithm that was used to encrypt the data.
  2. Retrieve the key that was used.
  3. Retrieve the IV that was used.
  4. Retrieve the encrypted data.
  5. Decrypt the data.
  6. Convert the decrypted data back to its original format.
Implementation 

I am going to choose Triple DES algorithm for this demo.(Step#1)


 Let's first generate IV (initialization vector) and Key (Step #2).For this,create a separate console application and paste following code inside Main method



static void Main(string[] args)
 {
  DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  des.GenerateIV();
  des.GenerateKey();
  Console.WriteLine("Key={0}",String.Join(",",des.Key));
  Console.WriteLine("IV={0}", String.Join(",", des.IV));


 }


Run the application and note down the value of IV and Key.



Create a new class named EncryptionManager and add following code



public class EncryptionManager
{
private byte[] Key = {89,83,45,236,140,228,180,79,209,164,231,131,28,7,110,73,140,235,118,52,225,46,202,118
    };
private byte[] IV = { 161, 200, 187, 207, 22, 92, 119, 227 };
public string Encrypt(string inputString)
    {
//Step #4
byte[] buffer = Encoding.ASCII.GetBytes(inputString);
        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider()
        {
            Key = Key,
            IV = IV
        };
//Step #4,5,6
        ICryptoTransform ITransform = tripleDes.CreateEncryptor();
return Convert.ToBase64String(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
    }
public string Decrypt(string inputString)
    {
byte[] buffer = Convert.FromBase64String(inputString);
        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider()
        {
            Key = Key,
            IV = IV
        };
        ICryptoTransform ITransform = tripleDes.CreateDecryptor();
return Encoding.ASCII.GetString(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
    }
}
How to use
Create a new webpage and add following code inside it


 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EncryptDecrypt.aspx.cs" Inherits="EncryptDecrypt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:TextBox ID="txtData" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
<td>
<asp:TextBox runat="server" ID="txtEncrypt" TextMode="MultiLine"></asp:TextBox>
</td>
<td>
<asp:TextBox runat="server" ID="txtDecrypt" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnEncrypt" runat="server" OnClick="btnEncrypt_Click" Text="Encrypt" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" OnClick="btnDecrypt_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public partial class EncryptDecrypt : System.Web.UI.Page
{
    EncryptionManager manager = new EncryptionManager();
protected void Page_Load(object sender, EventArgs e)
    {
    }
protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        txtEncrypt.Text = manager.Encrypt(txtData.Text);
    }
protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        txtDecrypt.Text = manager.Decrypt(txtEncrypt.Text);
    }
}

How to compress response in asp.net

In this post I will show you how to compress http response in asp.net for improving performance. Before going into details let's create a simple website with single page Default.aspx and add following code into it Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdPerson" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grdPerson.DataSource = Person.Persons;
            grdPerson.DataBind();
        }
    }
}


[Serializable]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Phone { get; set; }
    public string Email { get; set; }
    public static List<Person> Persons
    {
        get
        {
            return new List<Person>()
                {
                    new Person(){FirstName="Santosh",LastName="Singh",Phone=1213123,Email="santosh@gmail.com"},
                    new Person(){FirstName="Ashok",LastName="Singh",Phone=1213123,Email="ashok@gmail.com"},
                    new Person(){FirstName="Bill",LastName="Gates",Phone=1213123,Email="bill@gmail.com"},
                };
        }

    }
    public override string ToString()
    {
        return string.Format(@"FirstName {0} & LastName {1} Phone {2} Email {3}", this.FirstName, this.LastName, this.Phone, this.Email);
    }
}
Now,press F5 and see the response result in FireBug.You will see the response result something like below
Note down the Content-Length size(in my case is 1720) Let's compress the response.For this right click on website ,and add Global.asax file.Inside this file add a method named
void Application_BeginRequest(object sender, EventArgs e)
{

}
Inside it paste the following code and see the result in FireBug
 void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext incoming = HttpContext.Current;
        string oldpath = incoming.Request.Path.ToLower();
        incoming.Response.Filter = new System.IO.Compression.GZipStream(incoming.Response.Filter, System.IO.Compression.CompressionMode.Compress);
        HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
        HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

    }
Check the Content-Length property after compression. Note:For compress/decompression I am using .net framework class GZipStream