Sunday, December 11, 2011

How to create self signed certificate using makecert

In this post,I will show you how to create self signed certificate for wcf application.For this,I will used the utility makecert.MakeCert.exe allows you to (for test/dev purposes) generate both a trusted root certificate and a certificate signed by that trusted root certificate for encryption purposes (also for signature purposes.


Open visual studio command prompt (Admin mode) and type following command 
    C:\cert>makecert -pe -n "CN=RootCA" -ss My -sr LocalMachine -a sha1 -sky signatu re -r "RootCA.cer"
  • -pe Marks the generated private key as exportable. This allows the private key to be included in the certificate.
  • -Specifies the subject's certificate name. This name must conform to the X.500 standard. The simplest method is to specify the name in double quotes, preceded by CN=; for example, "CN=myName".
  • -ss Specifies the subject's certificate store name that stores the output certificate.
  • sr >localmachine
  • -a Specifies the signature algorithm. Must be either 
  • -sky Specifies the subject's key type, which must be signatureexchange, or an integer that represents a provider type. By default, you can pass 1for an exchange key and 2 for a signature key.
  • -r Creates a self-signed certificate.


Above command will create a certificate named RootCA.cer in the cert directory ,and also placed this certificate into Person folder
After executing the above command do the following steps


  • Start/Run/MMC

  • File/Add-Remove Snap-In

  • Click Add


  • Select Certificates and click Add

  • Select Computer Account and hit Next

  • Select Local Computer

  • Click Close

  • Click OK
Go back to the certificates snap-in, right-click the "RootCA" certificate and copy it to the "Trusted Root Certification Authorities" node. Once done, if you expand this node, and then select certificates your newly created root cert should be present.

Now,It's time to create the server certificate.Type the following command and press enter
    C:\cert>makecert -pe -n "CN=santosh-pc" -ss My -sr LocalMachine -sky exchange -a

 sha1 -in "RootCA" -is My -ir LocalMachine -sy 12 santosh-pc.cer



Thursday, October 20, 2011

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>

Sunday, October 9, 2011

How to enable/disable dropdownlist through a checkbox selection

In this post,I will show you how to enable/disable dropdownlist control through checkbox selection in asp.net.

  • Create a new website 
  • Right click on the website,add a new webpage,and add following code into it



<%@ 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">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#chkEnable").click(function () {
                if (this.checked)
                    $('#ddlList').attr('disabled', 'disabled');
                else
                    $('#ddlList').removeAttr('disabled');
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="chkEnable" runat="server" Text="Enable/Disable" /><br />
        <asp:DropDownList ID="ddlList" runat="server">
            <asp:ListItem Text="Select" Value="-1">
            </asp:ListItem>
            <asp:ListItem Text="Option1" Value="1" />
            <asp:ListItem Text="Option2" Value="2" />
            <asp:ListItem Text="Option3" Value="3" />
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

{Click here for live demo}

Saturday, October 8, 2011

How to change default binding in WCF 4.0

With WCF 3.x, if you try to host a service without any configured endpoints, the ServiceHost instance will throw an exception informing you that you need to configure at least one endpoint. With WCF 4, this is no longer the case because the runtime automatically adds one or more “default endpoints” for you, thereby making the service usable without any configuration.
If you want to change default binding then open web.config and do following entry in <system.serviceModel>

<system.serviceModel>

<protocolMapping>

<add binding="basicHttpBinding" scheme="Http"/>

</protocolMapping>


</system.serviceModel>

How to upload/Download file from wcf service

In this post,I will show you how to stream (upload and download) data through wcfservice.


  • Create a new website
  • Right click on the website and add new wcf service named FileStream.svc
  • Open the IFileStream.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
[ServiceContract]
public interface IFileStream
{
    [OperationContract]
    string Upload(Stream inputStream);
    [OperationContract]
    Stream Download(string fileId);
    [OperationContract]
    string[] GetAvailableFiles();
}

Open FileStream.cs file and add following code inside it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class FileStream : IFileStream
{
    private const string FILEPATH = @"C:\temp\download";
    private string GetDirectoryPath()
    {
    return FILEPATH;
    }
    public string Upload(System.IO.Stream inputStream)
    {
    string fileID = string.Format(@"{0}\{1}.txt", GetDirectoryPath(), Guid.NewGuid().ToString());
        StreamReader reader = new StreamReader(inputStream);
    string contents = reader.ReadToEnd();
        File.WriteAllText(fileID, contents);
    return fileID;
    }
    public System.IO.Stream Download(string fileId)
    {
        MemoryStream stream = new MemoryStream();
    byte[] buffer = File.ReadAllBytes(fileId);
        stream.Write(buffer, 0, buffer.Length);
        stream.Position = 0;
    return stream;
    }
    public string[] GetAvailableFiles()
    {
    return new DirectoryInfo(GetDirectoryPath()).GetFiles().Select(x => x.FullName).ToArray();
    }
}

Now,It's time to configure the service.There are two way to configure the service.First through the code ,and second through the config file.I will followlatter approach.Open web.config and go to section and add following code

<?xml version="1.0"?>
<configuration>
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.serviceModel>
    <services>
    <service behaviorConfiguration="streamServiceBehaviour" name="FileStream">
    <endpoint address="" binding="basicHttpBinding" contract="IFileStream" bindingConfiguration="streamBindingConfig"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
    </services>
    <behaviors>
    <serviceBehaviors>
    <behavior name="streamServiceBehaviour">
    <serviceDebug includeExceptionDetailInFaults="true"/>
    <serviceMetadata httpGetEnabled="true"/>
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <bindings>
    <basicHttpBinding>
    <binding name="streamBindingConfig" transferMode="Streamed">
    </binding>
    </basicHttpBinding>
    </bindings>
    </system.serviceModel>
</configuration>

In the above configuration,I have used basicHttpBinding and transferMode is Streamed..

Let's consume the service.Right click on the project and add new page and add following code into it


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServiceExample.aspx.cs" Inherits="ServiceExample" %>
<!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:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
    </div>
    <asp:Button ID="btnDownload" runat="server" onclick="btnDownload_Click" 
    Text="Download" />
    <asp:TextBox ID="TextBox1" runat="server" Height="235px" Width="377px"></asp:TextBox>
    </form>
</body>
</html>
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class ServiceExample : System.Web.UI.Page
{
    StreamService.FileStreamClient client = new StreamService.FileStreamClient();
    string fileId = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
 
     fileId=client.Upload(new MemoryStream(FileUpload1.FileBytes));
     Session["fileID"] = fileId;
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        Stream stream = client.Download((String)Session["fileID"]);
        StreamReader reader = new StreamReader(stream);
        TextBox1.Text = reader.ReadToEnd();
    }
}

How to implement Adapter pattern in asp.net



In this post,I will show you how to implement Adapter patter in asp.net.Before going to implementation details let's dive into adapter pattern definitions.

What is  an Adapter Pattern?

The adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface


How’s it implemented?
1.     You want to use existing class,and its interface doe not match the one you need.

2.     You want to create a reusable class that cooperates with unrelated classes with incompatible interface

Problem:-

Many of us use the .net Cache class for storing objects into memory. Suppose later if we find that some other third party Cache management library that  is better than existing Cache class , then the project would not change just adapter internally would call the new Cache class.




1.     Here ICacheManager (Target) the interface that client wants to use
2.     HttpContext (Adaptee) An implementation that needs adapting
3.     CacheManager (Adapter) The class that implements the Target interface in terms of the Adaptee




Implementation

  • Let's start implementing the adapter patternRight click on the project and add a new class named ICacheManager and add following code inside it




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public interface ICacheManager
{
    void Add(string key, object data);
    void Remove(string key);
    T Get&lt;T&gt;(string key);
}

  • Right click on the project and add a new class CacheManager and add following code inside it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class CacheManager : ICacheManager
{
    public void Add(string key, object data)
    {
        //Implements third party caching here
        HttpContext.Current.Cache.Add(key, data);
    }

    public void Remove(string key)
    {
        if (HttpContext.Current.Cache["key"] != null)
            HttpContext.Current.Cache.Remove(key);
    }
    public T Get&lt;T&gt;(string key)
    {
        T itemStored = (T)HttpContext.Current.Cache.Get(key);
        if (itemStored == null)
            itemStored = default(T);
        return itemStored;

    }

  • Add a new page and add following code inside it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Adapter.aspx.cs" Inherits="Adapter" %>

<!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:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />
        <asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
        <asp:Button ID="btnGet" runat="server" OnClick="btnGet_Click" Text="Get Value from Cache" />
    </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 Adapter : System.Web.UI.Page
{
    CacheManager manager = new CacheManager();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        manager.Add("Key", DateTime.Now);
        
    }
    protected void btnGet_Click(object sender, EventArgs e)
    {
        Response.Write(manager.Get<DateTime>("Key").ToShortDateString());
    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        manager.Remove("Key");
    }
}
}

    Friday, October 7, 2011

    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}}

    Saturday, October 1, 2011

    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

    Wednesday, August 17, 2011

    How to compress and decompress data in c#

    In this post,I will show you how to compress and decompress data in c# using GzipStream class.Below is the code for the same

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.IO.Compression;
    namespace CompressDecompress
    {
        class Program
        {
        const string CompressFilePath = @"C:\temp\data.zip";
        const string Filename = @"C:\temp\data.txt";
        private const string DeCompressFilePath = @"C:\temp\data1.txt";
        static void Main(string[] args)
            {
                Compress(Filename);
                Decompress(CompressFilePath);
            }
        private static void Decompress(string compressFilePath)
            {
        using (FileStream inputStream = new FileStream(compressFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
        using (FileStream outputStream = new FileStream(DeCompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
        using (GZipStream gZipStream = new GZipStream(inputStream, CompressionMode.Decompress))
                        {
                            gZipStream.CopyTo(outputStream);
                        }
                    }
                }
            }
        private static void Compress(string filename)
            {
        using (FileStream inputStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    Console.WriteLine("Size Before Compression:{0} KB", inputStream.Length / 1024);
        using (FileStream outputStream = new FileStream(CompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
        using (GZipStream gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
                        {
                            inputStream.CopyTo(gZipStream);
                            Console.WriteLine("Size after Compression:{0} KB", outputStream.Length / 1024);
                        }
                    }
                }
            }
        }
    }
    

    Saturday, August 6, 2011

    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},
                           };
            }
        }
    }

    Thursday, August 4, 2011

    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 send output of console application to file

    In this example,I will show how to send console output to file in c#
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text;
    
    namespace SNIPPET_CS
    {
        class Program
        {
            static void Main(string[] args)
            {
                ConsoleOutput();
                Console.WriteLine("Console output saved successfully");
                Console.ReadLine();
            }
            private static void ConsoleOutput()
            {
                const string applicationPath = @"D:\Windows\System32\ipconfig.exe";
                //string ApplicationArguments = "-c -x";
    
                // Create a new process object
                Process processObj = new Process();
    
                // StartInfo contains the startup information of
                // the new process
                processObj.StartInfo.FileName = applicationPath;
                //ProcessObj.StartInfo.Arguments = ApplicationArguments;
    
                // These two optional flags ensure that no DOS window
                // appears
                processObj.StartInfo.UseShellExecute = false;
                processObj.StartInfo.CreateNoWindow = true;
    
                // If this option is set the DOS window appears again :-/
                // ProcessObj.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    
                // This ensures that you get the output from the DOS application
                processObj.StartInfo.RedirectStandardOutput = true;
    
                // Start the process
                processObj.Start();
    
                // Wait that the process exits
                processObj.WaitForExit();
    
                // Now read the output of the DOS application
                string result = processObj.StandardOutput.ReadToEnd();
                WriteToFile(result);
            }
            private static void WriteToFile(string result)
            {
                using (FileStream stream = new FileStream(@"C:\temp\a.txt", FileMode.OpenOrCreate, FileAccess.Write))
                {
    
                    byte[] buffer = Encoding.Default.GetBytes(result);
                    stream.Write(buffer, 0, buffer.Length);
                    stream.Close();
                }
            }
        }
    }
    

    Monday, July 25, 2011

    How to create an Enum value from the string

    This is a simple code for converting string representation to Enum
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Blog_CS
    {
        public enum State { New, Ready, Stop, Reset };
        class Program
        {
            private static void Main(string[] args)
            {
                const string state = "New";
                State currentState = (State)Enum.Parse(typeof(State), state);
    
                if (currentState == State.New)
                {
                    Console.WriteLine("Run state");
    
                }
            }
        }
    }

    Sunday, July 24, 2011

    How to add custom sorting for a class with IComparable interface

    Sometimes it necessary to sort your collection before showing it on UI.You can add custom sorting to you class just by inheriting it with  IComparable interface.IComparable interface contains one single method CompareTo.

    For this post I have created a class Employee which has four properties FirstName,LastName,Age and Title.This class implements IComparable interface,which means instance of the class can be compared with other instance of this class.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    namespace Blog_CS
    {
        public class Employee : IComparable<Employee>
        {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Title { get; set; }
        public static List<Employee> Employees
            {
                get
                {
        return new List<Employee>()
                               {
        new Employee(){FirstName = "F004",LastName = "L001",Age = 21,Title = "SE"},
        new Employee(){FirstName = "F002",LastName = "L002",Age = 41,Title = "SSE"},
        new Employee(){FirstName = "F001",LastName = "L003",Age = 21,Title = "JE"},
        new Employee(){FirstName = "F003",LastName = "L003",Age = 31,Title = "APM"},
                               };
                }
            }
        #region IComparable<Employee> Members
        public int CompareTo(Employee other)
            {
        return this.FirstName.CompareTo(other.FirstName);
            }
        #endregion
        }
        class Program
        {
        static void Main(string[] args)
            {
                List<Employee> employees = Employee.Employees;
                employees.Sort();
                Console.WriteLine("FirstName    LastName   Age    Title ");
        foreach (var employee in employees)
                {
        string combineddata = String.Format("{0}\t{1}\t{2}\t", employee.FirstName,
                                    employee.LastName, Convert.ToInt32(employee.Age), employee.Title);
                    Console.WriteLine(combineddata);
                }
            }
        }
    }