Friday, 28 December 2012

get excel sheet data


     private void btnCompare_Click(object sender, EventArgs e)
        {
            string filename1 = FileTxt1.Text;
            string filename2 = FileTxt2.Text;

            string file1_sheet = GetExcelSheets(filename1);
            string file2_sheet = GetExcelSheets(filename2);

            //String sConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            //"Data Source=" + filename1 + ";" +
            //"Extended Properties=Excel 8.0;";

            //String sConnectionString2 = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            //"Data Source=" + filename2 + ";" +
            //"Extended Properties=Excel 8.0;";
            String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=" + filename1 + ";" +
            "Extended Properties=Excel 12.0;";

            String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=" + filename2 + ";" +
            "Extended Properties=Excel 12.0;";
            OleDbConnection objConn = new OleDbConnection(sConnectionString1);

            objConn.Open();
            OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + file1_sheet + "$]", objConn);
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
            objAdapter1.SelectCommand = objCmdSelect;
            DataSet objDataset1 = new DataSet();
            objAdapter1.Fill(objDataset1, "XLData");
            DataTable dt1 = objDataset1.Tables[0];
            objConn.Close();


            objConn = new OleDbConnection(sConnectionString2);
            objConn.Open();
            objCmdSelect = new OleDbCommand("SELECT * FROM [" + file2_sheet + "$]", objConn);
            objAdapter1 = new OleDbDataAdapter();
            objAdapter1.SelectCommand = objCmdSelect;
            objDataset1 = new DataSet();
            objAdapter1.Fill(objDataset1, "XLData");
            DataTable dt2 = objDataset1.Tables[0];
            objConn.Close();
            compareDataTables(dt1, dt2);

        }



   public string GetExcelSheets(string excelFileName)
        {
            Microsoft.Office.Interop.Excel.Application excelFileObject = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workBookObject = null;
            workBookObject = excelFileObject.Workbooks.Open(excelFileName, 0, true, 5, "", "", false,
            Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
            "",
            true,
            false,
            0,
            true,
            false,
            false);
            Excel.Sheets sheets = workBookObject.Worksheets;

            // get the first and only worksheet from the collection of worksheets
            Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
            //MessageBox.Show(worksheet.Name);
            return worksheet.Name;
        }

compare two datatables

 public DataTable CompareDataTables(DataTable first, DataTable second)
        {
            first.TableName = "FirstTable";
            second.TableName = "SecondTable";
            //Create Empty Table
            DataTable table = new DataTable("Difference");
            try
            {
                //Must use a Dataset to make use of a DataRelation object
                using (DataSet ds = new DataSet())
                {
                    //Add tables
                    ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });
                    //Get Columns for DataRelation
                    DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];
                    for (int i = 0; i < firstcolumns.Length; i++)
                    {
                        firstcolumns[i] = ds.Tables[0].Columns[i];
                    }
                    DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];
                    for (int i = 0; i < secondcolumns.Length; i++)
                    {
                        secondcolumns[i] = ds.Tables[1].Columns[i];
                    }
                    //Create DataRelation
                    DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
                    ds.Relations.Add(r);
                    //Create columns for return table
                    for (int i = 0; i < first.Columns.Count; i++)
                    {
                        table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
                    }
                    //If First Row not in Second, Add to return table.
                    table.BeginLoadData();
                    foreach (DataRow parentrow in ds.Tables[0].Rows)
                    {
                        DataRow[] childrows = parentrow.GetChildRows(r);
                        if (childrows == null || childrows.Length == 0)
                            table.LoadDataRow(parentrow.ItemArray, true);
                    }
                    table.EndLoadData();
                }
            }

        return table;
        }

Saturday, 15 December 2012

dynamic ip change in c#



                 ManagementBaseObject inPar = null;
                 ManagementBaseObject outPar = null;
                 ManagementClass mc = new
                 ManagementClass("Win32_NetworkAdapterConfiguration");
                 ManagementObjectCollection moc = mc.GetInstances();
                 try
                 {
                     foreach (ManagementObject mo in moc)
                     {
                         if (!(bool)mo["IPEnabled"])
                             continue;

                         inPar = mo.GetMethodParameters("EnableStatic");
                         inPar["IPAddress"] = new string[] {"10.57.245.184" };
                         inPar["SubnetMask"] = new string[] {"255.255.0.0" };
                         outPar = mo.InvokeMethod("EnableStatic", inPar,null);
                         //MonIP.Text = "10.59.245.186";
                     }
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("Problème au changement d'IP (" +
                     ex.Message + ")", "erreur", MessageBoxButtons.OK,
                     MessageBoxIcon.Error);
                     return;
                 }

Thursday, 13 December 2012

Calender Control in asp.net


<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css"
        type="text/css" media="all" />
    <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css"
        type="text/css" media="all" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"
        type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%= txtFrom.ClientID  %>").datepicker();
            $("#<%= txtTo.ClientID  %>").datepicker();
        });
       
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">   
    <p>
        <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox></p>
    <p>
        <asp:TextBox ID="txtTo" runat="server"></asp:TextBox></p>

</asp:Content>

Modify the gridview row data in asp.net


 protected void gvOpenings_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                //int i=e.Row.RowIndex;
                for (int i = 0; i <8 ; i++)
                {
                    if (e.Row.Cells[i].Text.Length > 30)
                    {
                        string strStore = e.Row.Cells[i].Text;
                        e.Row.Cells[i].Text = strStore.Substring(0, 27) + "..";
                    }
                }
            }
        }

send mail with attachment


string strSMTPServer = ConfigurationManager.AppSettings["SMTPServer"];
                string strFromAddress = ConfigurationManager.AppSettings["FromAddress"];
                string strUserName = ConfigurationManager.AppSettings["MailCredential_UserName"];
                string strPassword = ConfigurationManager.AppSettings["MailCredential_Password"];
                int intSMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(strSMTPServer);
                if (fileResume.HasFile == true)
                {
                    mail.Attachments.Add(new Attachment(fileResume.PostedFile.InputStream, fileResume.PostedFile.FileName));
                    mail.From = new MailAddress(strFromAddress);
                    mail.To.Add(ConfigurationManager.AppSettings["MailToAddress"]);
                    String strAppliedFor=Request.QueryString["jobid"]!=null?Request.QueryString["jobid"]:"General";
                    mail.Subject = "Applied For " + ddlApplyOne.SelectedValue;
                    mail.IsBodyHtml = true;
                    StringBuilder mailBody = new StringBuilder();
                    mailBody.AppendFormat("<div style='width:50px;backround-color:Green'><table border='10' bordercolor='red' cellpadding='10' cellspacing='10'  align='center'>");
                    mailBody.AppendFormat("<tr><td colspan='2' align='center'><h1>Application for the post of {0}</h1></td></tr>", ddlApply.SelectedValue);
                    mailBody.AppendFormat("<tr><td>Name of the Candidate:</td><td>{0}</td></tr>",txtName.Text);
                    mailBody.AppendFormat("<tr><td>EmailID:</td><td>{0}</td></tr>",txtEmail.Text);
                    mailBody.AppendFormat("<tr><td>Contact Ph:</td><td>{0}</td></tr>",txtContact.Text);
                    mailBody.AppendFormat("<tr><td>Educational Qualification:</td><td>{0}</td></tr>",txtEduQu.Text);
                    mailBody.AppendFormat("<tr><td>Technical Skils:</td><td>{0}</td></tr>",txtSkills.Text);
                    mailBody.AppendFormat("<tr><td>Work Experience:</td><td>{0}</td></tr>", ddlExp.SelectedValue);
                    mailBody.AppendFormat("<tr><td>Current Working Status:</td><td>{0}</td></tr>", txtWorkStat.Text);
                    mailBody.AppendFormat("</table></div>");
                    mail.Body = mailBody.ToString();
                    SmtpServer.Port = intSMTPPort;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(strUserName, strPassword);
                    SmtpServer.EnableSsl = true;
                    SmtpServer.Send(mail);
                    txtEmail.Text = "";
                    txtName.Text = "";
                    txtSkills.Text = "";
                    txtWorkStat.Text = "";
                    txtContact.Text="";
                    txtEduQu.Text="";
                    txtWorkStat.Text="";
                    ddlApply.SelectedIndex=0;
                    ddlExp.SelectedIndex=0;
                    lblError.Text = "";
                    ScriptManager.RegisterStartupScript(this,this.GetType(),"MessageBox","alert('Your details are updated to our system. We will get back to you soon..Thank you');",true);

Messagebox in asp.net page

 ScriptManager.RegisterStartupScript(this,this.GetType(),"MessageBox","alert('Your details are updated to our system. We will get back to you soon..Thank you');",true);

Tuesday, 11 December 2012

Mail Sending in C#


Mail Sending in C#


                    string strSMTPServer = ConfigurationManager.AppSettings["SMTPServer"];//smtp server url
                    string strFromAddress = ConfigurationManager.AppSettings["FromAddress"];
//From Address of Mail
                    string strUserName = ConfigurationManager.AppSettings["MailCredential_UserName"];
                    string strPassword = ConfigurationManager.AppSettings["MailCredential_Password"];
                    int intSMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient(strSMTPServer);
                    mail.From = new MailAddress(strFromAddress);
                    mail.To.Add(ConfigurationManager.AppSettings["ToAddress"]);
                    mail.Subject = "Subject of Mail here";
                    mail.Body = "Body of mail here" ;
                    SmtpServer.Port = intSMTPPort;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(strUserName, strPassword);
                    SmtpServer.EnableSsl = true;
                    SmtpServer.Send(mail);
                    lblLoginError.Text = "Password Sent Successfully";

Monday, 10 December 2012

IIS 7.5 error: Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list


IIS 7.5 error: Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list
Posted on August 12, 2010 by Maris
Today I installed Clean Windows Web Server 2008 R2 64-bit with IIS 7.5. To my surprise opening .NET 4.0 application I received the following error:
IIS 7.5 Detailed Error - 500.21 - Internal Server Error






As it turns out, some glitch caused this problem, and somehow .NET was not registered with IIS.
Running the following commands solved this issue:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Unique visitor counter in asp.net


In global.asax file 


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HitCounterControl.ascx.cs" Inherits="Rr.HitCounterControl" %>


<div style="padding-top: 15px; text-align: center">
    <span style="font-size:small">Visitor Count </span>
    <asp:Literal ID="ltlCounter" runat="server"></asp:Literal>
</div>





 void Session_Start(object sender, EventArgs e)
        {                    
         

//Get & increment visitor count
            int count = 0;
            DataSet tmpDs = new DataSet();
            HttpContext currentContext = HttpContext.Current;
            if (currentContext != null)
            {              
                try
                {
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    int i = 0;
                    String ipAddress = currentContext.Request.UserHostAddress;
                    Session["ipAddress"] = ipAddress;
                    while (tmpDs.Tables[0].Rows[i]["ipAddress"].ToString() != null)
                    {
                        if (ipAddress == tmpDs.Tables[0].Rows[i]["ipAddress"].ToString())
                        {
                            count++;
                        }
                        i++;
                    }
                }
                catch (System.IO.FileNotFoundException)
                {
                    throw;
                }
                catch
                {
                    //no need to throw exception for this
                }
            }
            if (currentContext != null && count==0)
            {
                try
                {
                    Session["Start"] = DateTime.Now;
                    //UserVisitCount();
                    // DataSet tmpDs = new DataSet();
                    //read hit count
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    tmpDs.Tables[0].Rows.Add(tmpDs.Tables[0].Rows.Count + 1, currentContext.Request.UserHostAddress, DateTime.Now.ToString(), currentContext.Session.SessionID);
                    tmpDs.WriteXml(Server.MapPath("~/HitCounter.xml"));
                    //set in Session                  
                }
                catch { }
            }


            Session["HitCount"] = tmpDs.Tables[0].Rows.Count;


}




In user control






using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;


namespace RR
{
    public partial class HitCounterControl : System.Web.UI.UserControl
    {
         int totalDigits = 6;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltlCounter.Text = FormatHTMLCounter(Session["HitCount"].ToString());
            }
        }

       /// <summary>
       /// Calculates and formats the vistor count number
       /// </summary>
       /// <param name="visitCount"></param>
       /// <returns></returns>
        private string FormatHTMLCounter(string visitCount)
        {
            int noOfDigits = visitCount.Length;
            int zeroesToPrefix = totalDigits - noOfDigits;
            StringBuilder strCounterHtml = new StringBuilder();
         
            strCounterHtml.Append(@"<table align=""center"" style=""width: 120px; background-color: Black; color: White; text-align: center; font-weight: bold;""><tr>");

            for (int i = 0; i < zeroesToPrefix; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append("0");
                strCounterHtml.Append("</td>");
            }

            char[] visitCountChar = visitCount.ToCharArray();
            for (int i = 0; i < visitCountChar.Length; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append(visitCountChar[i]);
                strCounterHtml.Append("</td>");
            }

            strCounterHtml.Append("</tr></table>");
            return strCounterHtml.ToString();
        }
    }
}

//Drag and drop this user control to required web page


Sunday, 9 December 2012

Display time in ASP.NET Application


    <script type="text/javascript" language="javascript">
                function updateTime() {
                    var label = document.getElementById('currentTime');
                    if (label) {
                        var time = (new Date()).localeFormat("T");
                        label.innerHTML = time;
                    }
                }
                updateTime();
                window.setInterval(updateTime, 1000);
        </script>
            <Ajax:ToolkitScriptManager runat="server" EnablePartialRendering="true" ID="ScriptManager1" />
            <asp:UpdatePanel runat="server" ID="UpdatePanel1">
                <ContentTemplate>
                    <div style="width: 180px; height: 100px;">
                        <asp:Panel ID="timer" runat="server" Width="200px" ForeColor="DarkBlue" Style="z-index: 500; border-radius: 15px;">
                            <div style="width: 100%; height: 100%; vertical-align: middle; text-align: center;">
                                <span id="currentTime" clientidmode="Static" runat="server" style="font-size: large;font-weight: bold; line-height: 40px; color: Black;" />
                            </div>
                        </asp:Panel>
                        <Ajax:AlwaysVisibleControlExtender ID="avce" runat="server" TargetControlID="timer"
                            VerticalSide="Top" VerticalOffset="10" HorizontalSide="Right" HorizontalOffset="10"
                            ScrollEffectDuration=".1" />
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>

Saturday, 8 December 2012

VB.net Encryption and Decyption pssword



Encrypt Process:

Public Function Encrypt(ByVal plainText As String) As String

        Dim passPhrase As String = "Pas5pr@se"
        Dim saltValue As String = "zKqffFs392WuxGMhFkfhYj/HtDDIjSiXnYqMlMMzrNc="

        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)


        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

        Dim memoryStream As New IO.MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function


Decrypt Process


Public Function Decrypt(ByVal cipherText As String, ByVal salt As String) As String

        Dim passPhrase As String = "Pas5pr@se"
        Dim saltValue As String = "zKqffFs392WuxGMhFkfhYj/HtDDIjSiXnYqMlMMzrNc="
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

        ' First, we must create a password, from which the key will be
        ' derived. This password will be generated from the specified
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)

        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()

        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC

        ' Generate decryptor from the existing key bytes and initialization
        ' vector. Key size will be defined based on the number of the key
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New IO.MemoryStream(cipherTextBytes)

        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)

        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
        ' Convert decrypted data into a string.
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        ' Return decrypted string.
        Return plainText
    End Function

C# decryption password




Decryption

    public string Decrypt(string cipherText,string salt)
    {
        string passPhrase = "Pas5pr@se";        // can be any string
        string saltValue = salt;        // can be any string
        string hashAlgorithm = "SHA1";             // can be "MD5"
        int passwordIterations = 2;                  // can be any number
        string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int keySize = 256;                // can be 192 or 128
        cipherText = cipherText.Replace(" ", "+");

        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        // First, we must create a password, from which the key will be
        // derived. This password will be generated from the specified
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate decryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes,
                                                         initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                      decryptor,
                                                      CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes,0,plainTextBytes.Length);

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert decrypted data into a string.
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes,0,decryptedByteCount);

        // Return decrypted string.  
        return plainText;
    }