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

Thursday, 29 November 2012

read and write data into xml using gridview


//creation of gridview

<table width="900px">
                <tr>
                    <td style="background-color: Silver; width: 900">
                        <asp:GridView ID="gvClientTestimonials" runat="server" AutoGenerateColumns="false"
                            OnRowDataBound="gvClientTestimonials_RowDataBound">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <p>
                                            <img src="images/open-quotes.gif" width="19" height="12" hspace="5" vspace="5" align="bottom"><asp:Label
                                                ID="lblTestimonial" runat="server">
                                            </asp:Label>
                                            <img src="images/close-quotes1.gif" width="19" height="12" hspace="5" vspace="5"
                                                align="middle"></p>
                                        <div align="right">
                                            <strong>--<asp:Label ID="lblClientName" runat="server"></asp:Label></strong></div>
                                        <br />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </table>

//in.cs file


protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataSet ds = new DataSet("Testimonials");
                //finding xml file is exist or not

                if (File.Exists(Server.MapPath("Testimonials.xml")) == false)
                {                  
                    ds.Tables.Add("Testimonials");
                    ds.Tables[0].Columns.Add("Id");
                    ds.Tables[0].Columns.Add("Testimonial");
                    ds.Tables[0].Columns.Add("Client");
                    ds.Tables[0].Columns.Add("DateTime");
                   // ds.Tables[0].Rows.Add(txtClientTestimonials.Text, txtClientName.Text, DateTime.Now.ToString());
                    ds.Tables[0].Rows.Add(0, "Working with the some is a great pleasure!", "ram", DateTime.Now.ToString());
                    ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    ds.Clear();
                    ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    gvClientTestimonials.DataSource = ds;
                    gvClientTestimonials.DataBind();
                }
                else
                {
                    ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    gvClientTestimonials.DataSource = ds;
                    gvClientTestimonials.DataBind();
                }
               
            }
           
        }
        protected void gvClientTestimonials_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblTestimonial = (Label)e.Row.FindControl("lblTestimonial");
                Label lblClientName = (Label)e.Row.FindControl("lblClientName");
                DataRowView drv = (DataRowView)e.Row.DataItem;
                lblTestimonial.Text = drv["Testimonial"].ToString();
                lblClientName.Text = drv["Client"].ToString();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet("Testimonials");
            if (File.Exists(Server.MapPath("ClientTestimonials/Testimonials.xml")) == false)
            {
                ds.Tables.Add("Testimonials");
                ds.Tables[0].Columns.Add("Id");
                ds.Tables[0].Columns.Add("Testimonial");
                ds.Tables[0].Columns.Add("Client");
                ds.Tables[0].Columns.Add("DateTime");              
                ds.Tables[0].Rows.Add(0,"Working with the Roopasoft is a great pleasure!","James",DateTime.Now.ToString());
                ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
            }
            else
            {
                ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                ds.Tables[0].Rows.Add(ds.Tables[0].Rows.Count+1,txtClientTestimonials.Text, txtClientName.Text, DateTime.Now.ToString());
                ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
            }
            gvClientTestimonials.DataSource = ds;
            gvClientTestimonials.DataBind();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtClientName.Text = "";
            txtClientTestimonials.Text = "";

        }

Sunday, 18 November 2012

create binary image converstion and stores in database


//on button click(browse button)

private void btnProductVariantBrowse_Click(object sender, EventArgs e)
        {
  //it stores the file name in textbox
            txtProductImage.Text = BrowseFile();
         
        }

//it open window and return the file name

public string BrowseFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return ofd.FileName;
            }
            return "";
        }
//picture details


 if (File.Exists(txtProductImage.Text))
            {
                FileInfo fi = new FileInfo(txtProductImage.Text);
                pvDetails.picture = new Picture();
                pvDetails.picture.PictureBinary = DbHelper.FileToByteArray(txtProductImage.Text);
                pvDetails .picture .MimeType="Image/" + fi.Extension.Substring(1, fi.Extension.Length - 1);
                pvDetails .picture.IsNew =true;       
               

            }
           

//file to byte array class


 public static byte[] FileToByteArray(string _FileName)
        {
            byte[] bytArrData = null;
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
                // read entire file into buffer
                bytArrData = _BinaryReader.ReadBytes((Int32)_TotalBytes);

                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }
            catch (Exception ex)
            {
                // Error
                //Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }
            return bytArrData;
        }



web editor in windows form


        private void frmPrdouctVariant_Load(object sender, EventArgs e)
        {
            _objMdiMalta = (mdiAMalta)this.MdiParent;

            ClearProductDetails();
            wbFullDescription.Navigate(Path.GetDirectoryName(Application.ExecutablePath).Replace("\\bin\\Debug", string.Empty) + "\\tinymce\\examples\\HtmlEditor.html");

        }
        public string HtmlFullDescription
        {
            get
            {
                string content = string.Empty;
                if (wbFullDescription.Document != null)
                {
                    object html = wbFullDescription.Document.InvokeScript("GetContent");
                    content = html as string;
                }
                return content;
            }
            set
            {
                if (wbFullDescription.Document != null)
                {
                    wbFullDescription.Document.InvokeScript("SetContent", new object[] { value });
                    // wbFullDescription.DocumentText = wbFullDescription.DocumentText.Replace("@@content@@", value);
                }
            }
        }

      public void CreateHtmlEditor(String strContent)
        {
            // String strFilePath = AppDomain.CurrentDomain.BaseDirectory + "tinymce\\examples\\index.html";
            String strBasePath = Path.GetDirectoryName(Application.ExecutablePath).Replace("\\bin\\Debug", string.Empty);
            String strFilePath = strBasePath + "\\tinymce\\examples\\index.html";
            if (File.Exists(strFilePath))
            {
                String strFileContent = File.ReadAllText(strFilePath);

                strFileContent = strFileContent.Replace("@@content@@", strContent);
                if (File.Exists(strBasePath + "\\tinymce\\examples\\HtmlEditor.html"))
                {
                    File.Delete(strBasePath + "\\tinymce\\examples\\HtmlEditor.html");
                }
                File.WriteAllText(strBasePath + "\\tinymce\\examples\\HtmlEditor.html", strFileContent);
            }
        }

Add two gridview column deatils to one gridview column


 <div style="background-color: White; height: 600px; overflow-y: scroll;">
                <asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
                    Width="200px" Height="90%"
                    OnPageIndexChanging="gvSuppliers_PageIndexChanging1"
                    onrowdatabound="gvCategory_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="Category names">
                            <ItemTemplate>
                                <asp:LinkButton ID="lbtnCategory" runat="server"  CommandArgument='<%#Eval("CategoryID") %>'
                                    OnClick="lbtnCategory_Click"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <PagerSettings Mode="NumericFirstLast" />
                </asp:GridView>
            </div>


  protected void lbtnCategory_Click(object sender, EventArgs e)
         {
             LinkButton lbtnSupplier = (LinkButton)sender;
             int categoryid = int.Parse(lbtnSupplier.CommandArgument);
             int intSupplierID = Convert.ToInt32(Session["intSupplierID"]);
             BindProductGrid(intSupplierID, categoryid);
          }

          protected void gvCategory_RowDataBound(object sender, GridViewRowEventArgs e)
          {
              if (e.Row.RowType == DataControlRowType.DataRow)
              {
                LinkButton lbtn= (LinkButton) e.Row.FindControl("lbtnCategory");
                //Text='"<%#Eval("Name")"+"("+Eval("ProductCount")%>+")"'
                DataRow rowView = ((DataRowView)e.Row.DataItem).Row;
               
                if (lbtn != null)
                {
                    lbtn.Text = rowView["Name"] + " (" +  rowView["ProductCount"] + ")";
                }
              }
          }
     

Saturday, 29 September 2012

Test Credit Card Account Numbers


Test Credit Card Account Numbers

Credit Card Type
Credit Card Number
American Express
378282246310005
American Express
371449635398431
American Express Corporate
378734493671000
Australian BankCard
5610591081018250
Diners Club
30569309025904
Diners Club
38520000023237
Discover
6011111111111117
Discover
6011000990139424
JCB
3530111333300000
JCB
3566002020360505
MasterCard
5555555555554444
MasterCard
5105105105105100
Visa
4111111111111111
Visa
4012888888881881
Visa
4222222222222
Note : Even though this number has a different character count than the other test numbers, it is the correct and functional number.
Processor-specific Cards
Dankort (PBS)
76009244561
Dankort (PBS)
5019717010103742
Switch/Solo (Paymentech)
6331101999990016

Wednesday, 26 September 2012

Ajax model pop up


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="samplemodel.aspx.cs" Inherits="vScreenSite.pages.samplemodel" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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">

.ModalPopupBG
{
    background-color: #666699;
    filter: alpha(opacity=50);
    opacity: 0.7;
}

.HellowWorldPopup
{
    min-width:200px;
    min-height:150px;
    background:white;
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
 <cc1:ToolkitScriptManager ID="tlkt1" runat="server">
                </cc1:ToolkitScriptManager>
<%--<asp:button id="Button1" runat="server" text="Button" />--%>

<%--<cc1:modalpopupextender id="ModalPopupExtender1" runat="server"
cancelcontrolid="btnCancel" okcontrolid="btnOkay"
targetcontrolid="Button1" popupcontrolid="Panel1"
popupdraghandlecontrolid="PopupHeader" drag="true"
backgroundcssclass="ModalPopupBG">
</cc1:modalpopupextender>--%>



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnLogin1" runat="server" Text="Already have an account? Log in." OnClick="btnLogin1_Click" />
        <asp:Button ID="BtnTarget" runat="server" Text="Target" Style="display: none" />
       
        <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="BtnTarget"
            PopupControlID="Panel1">
        </cc1:ModalPopupExtender>
        <asp:Panel ID="Panel1" runat="server" BackColor="WhiteSmoke" Width="300px" Height="200px">
            <asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
                <ContentTemplate>
                <table>
                <tr>
                <td>
                    <asp:Label ID="lblEmail" runat="server" Text="enter id value"></asp:Label>
                </td>
                <td>
                 <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                </td>
                 
                </tr>
                <tr>
                <td><asp:Label ID="lblPassword" runat="server" Text="enter pass value"></asp:Label>
             
                </td>
                <td><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
                </td>
                </tr>
                </table>
                <asp:Label ID="lbl" runat="server" ></asp:Label>
               
                    <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnLogin" EventName="Click" />
                </Triggers>
            </asp:UpdatePanel>
        </asp:Panel>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnLogin1" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>
    </form>
</body>
</html>

codebehind file code

    protected void btnLogin1_Click(object sender, EventArgs e)
        {
            ModalPopupExtender1.Show();
            txtEmail.Text = "sai";
            txtPassword.Text = "babu";
     
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtEmail.Text == "sai" && txtPassword.Text == "babu")
            {
                Response.Redirect("child_login.aspx");
            }
            else
            {
                ModalPopupExtender1.Show();
                lbl.Text = txtEmail.Text;
            }
          //  Response.Write(TextBox1.Text+" and "+TextBox2.Text);
          //  Response.Redirect("child_login.aspx");
        }
    }



Monday, 24 September 2012

facebook share


 <script>
        function fbs_click()
         {
            u = location.href;
            t = document.title;
         window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }</script>
    <style>
        html .fb_share_link
        {
            padding: 2px 0 0 20px;
            height: 16px;
            background: url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top left;
        }
    </style>
    <a rel="nofollow" href="http://www.facebook.com/share.php?u=>" onclick="return fbs_click()"
        target="_blank" class="fb_share_link">Share on Facebook</a>

Thursday, 20 September 2012

twitter share code

<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.domain.com/gfgf+11/" runat="server"  data-count="none" data-via="AnGe7s" data-lang="fr">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>






Properties which can be used by all types of the Tweet Button

The properties in this table can be used by the Javascript, IFRAME and build your own Tweet Buttons. Each property is a query string parameter for the https://twitter.com/share URL.

Query String Parameter   Description
url                                  URL of the page to share
via                                 Screen name of the user to attribute the Tweet to
text                                 Default Tweet text
related                         Related accounts
count                        Count box position
lang                               The language for the Tweet Button
counturl                       URL to which your shared URL resolves
hashtags                      Comma separated hashtags appended to tweet text
size                               The size of the rendered button
dnt                                See this section for information
Properties which can be used by the Javascript Tweet Button

The properties in this table can only be used by the Javascript Tweet Button. When used they provide additional places the Tweet Button can look for information on what to pre fill the Tweet with. The Tweet Button looks for property values in the priority order given in the table. For example when looking for the URL to use, the Tweet Button will: