Monday, May 14, 2012

Creating the Table dynamically and biding to the Grid view


In this article I am going to explain about how to create a table dynamically and how to add this to grid view.

What is dynamic table ?
Dynamic table is nothing but create a table dynamically and add rows and columns dynamically using c# programming.i.e. creating the table in the code behind is called Dynamic table.

How can we create the dynamic table?
To create the dynamic table we will use the “DataTable” class of the C#.net.For Adding new column we will use the “DataColumn” class and for adding new Row we will use the “DataRow” Class.

To create the Dynamic table letus create a new Aspx page with the following Code :


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Dynamic dtatTable creation</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDyndatatable" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>


Then add the following Name space to the code behind file :
using System.Data;

Then add the following code in the code behind .


protected void Page_Load(object sender, EventArgs e)
        {
            BindGvData();
        }

        private void BindGvData()
        {
            //Create a Datatable
            DataTable objDatatable = new DataTable();
            //Adding columns to the Data Table
            objDatatable.Columns.Add("Id", typeof(Int32));
            objDatatable.Columns.Add("StudentName", typeof(string));
            objDatatable.Columns.Add("Education", typeof(string));

            objDatatable = AddNewRow(1, "Prakash", "MCA", objDatatable);
            objDatatable = AddNewRow(2, "Pradeep", "MBA", objDatatable);
            objDatatable = AddNewRow(3, "Sathya", "BTECH", objDatatable);
            objDatatable = AddNewRow(4, "Sagar", "Degree", objDatatable);

            gvDyndatatable.DataSource = objDatatable;
            gvDyndatatable.DataBind();
        }

        public DataTable AddNewRow(int id, string name, string Education, DataTable objDatatable)
        {
            DataRow objDatatablerow = objDatatable.NewRow();
            objDatatablerow["Id"] = id;
            objDatatablerow["StudentName"] = name;
            objDatatablerow["Education"] = Education;
            objDatatable.Rows.Add(objDatatablerow);
            return objDatatable;

        }

Output:



Wednesday, May 9, 2012

Encrypting Query string value and pass to another Page and decrypt the query string value

In this post I am going to explain about how to encrypt the Query string value and how to decrepit the query string value from one page to another page.We know that the query string value will known to the user and user can simply chenge the Query string value and he may obtain the details of other user also.So I have Used this Encrypt/Decrepit in my recent application.For this I am using the MD5CryptoServiceProvider Class.
To do this first we write the two methods in one class with the following code.


  public class Encrypt
    {
        public static string EncryptString(string Message, string Passphrase)
        {

            byte[] Results;

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            //  1. We hash the passphrase using MD5

            // We use the MD5 hash generator as the result is a 128 bit byte array

            // which is a valid length for the TripleDES encoder we use below


             MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            //  2. Create a new TripleDESCryptoServiceProvider object

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            //  3. Setup the encoder

            TDESAlgorithm.Key = TDESKey;

            TDESAlgorithm.Mode = CipherMode.ECB;

            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            //  4. Convert the input string to a byte[]

            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            //  5. Attempt to encrypt the string

            try
            {

                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();

                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);

            }

            finally
            {

                // Clear the TripleDes and Hashprovider services of any sensitive information

                TDESAlgorithm.Clear();

                HashProvider.Clear();

            }


            //  6. Return the encrypted string as a base64 encoded string

            return Convert.ToBase64String(Results);

        }


        public static string DecryptString(string Message, string Passphrase)
        {

            byte[] Results;

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5

            // We use the MD5 hash generator as the result is a 128 bit byte array

            // which is a valid length for the TripleDES encoder we use below
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));



            // Step 2. Create a new TripleDESCryptoServiceProvider object

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();



            // Step 3. Setup the decoder

            TDESAlgorithm.Key = TDESKey;

            TDESAlgorithm.Mode = CipherMode.ECB;

            TDESAlgorithm.Padding = PaddingMode.PKCS7;



            // Step 4. Convert the input string to a byte[]

            byte[] DataToDecrypt = Convert.FromBase64String(Message);



            // Step 5. Attempt to decrypt the string

            try
            {

                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();

                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);

            }

            finally
            {

                // Clear the TripleDes and Hashprovider services of any sensitive information

                TDESAlgorithm.Clear();

                HashProvider.Clear();

            }


            // Step 6. Return the decrypted string in UTF8 format

            return UTF8.GetString(Results);

        }
    }

Then create the first aspx page with the following code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Redirect to Secondpage" />
   
    </div>
    </form>
</body>
</html>

Write the following Code in the Code behind Page under Button Click

protected void Button1_Click(object sender, EventArgs e)
        {
          

            string Password = "Query1";
            string Msg = "Prakash";
          

            string EncryptedString = Encrypt.EncryptString(Msg, Password);


            Response.Redirect("Default2.aspx?" + EncryptedString);
        }


Now design the Default2.aspx page with the following Code



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>


In the page load of Default2.aspx use the following code to read the query string value.


protected void Page_Load(object sender, EventArgs e)
        {
            string Password = "Query1";
            string URL =Request.Url.ToString().Trim() ;
           
           
            string EncodedQueryString = URL.Substring(URL.LastIndexOf('?')+1, (URL.Length-(URL.LastIndexOf('?')+1)));
                string QryString1  = Encrypt.DecryptString(EncodedQueryString, Password);
                Response.Write("Query String value is " + QryString1);
        }

Output :



Tuesday, May 8, 2012

Color Dialog

Author: Konjerla Suresh

Color dialog Control is Pallet of colors. This Control is used to select any color from available colors and also used to define the custom colors.  A typical color Dialog control is looks like below.


 The only purpose of color dialog control is to display the available colors and to create the custom colors and apply those colors to our application.

Creating a colorDialog Control:
 We can create a color dialog control in two ways, those are
1)      Using Forms Designer at design time
      2)      Using ColorDialog Control at run time.

Design Time:
To create a ColorDialog control at design-time, you simply drag and drop a ColorDialog control from Toolbox to a Form. 
Run time:

 To create a Color Dialog At run time, you simple create the instance for ColorDialog class. Call the ShowDialog method to display the color dialog
  Syntax: ColorDialog colordlg1 = new ColorDialog ();
Setting ColorDialog Properties:
Open the properties window by pressing F4 or right click on a control and select Properties menu item. It looks like below 



AllowFullOpen:
We can create custom define colors only when this property is true only. If this property is false, we can use only available colors.
When this property is true – define Custom colors option will be enabled where you can define your required color by selecting color form colors area or by setting RGB values. 




When this property is false - define Custom colors option will be disabled

Example program:
Create an application that changes form back  ground color and button fore ground color 


Steps:
1)      Open Windows application.
2)      Drag a button on form.
3)      Double click on the button and write following code in button1 _click event.
    private void button1_Click(object sender, EventArgs e)
     {
            ColorDialog clrDlg = new ColorDialog();
            clrDlg.ShowDialog();
            button1.ForeColor = clrDlg.Color;
            this.BackColor = clrDlg.Color;
    }

Output : 


Thursday, May 3, 2012

Abstract Classes in C#

In this post I am going to explain about the Abstract classes in the C#.An abstract class is one that cannot be directly instantiated. Instead derived classes must inherit from it and their constructors must be used.To declare a abstarect class we will use the keyword “ Abstract”.

An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.
Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition.
For example:
public abstract class A
{
    // Class members here.
}

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:

public abstract class A
{
    public abstract void DoWork(int i);
}

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The following program will explain you how to create a abstract class and how to use the abstract class in the derived class.


  abstract class Test
    {
        public int _a;
        
        public abstract void A();
    }

    class Example1 : Test
    {
        public override void A()
        {
            base._a = 10;
            Console.WriteLine("Example1.A");
            base._a++;
            Console.WriteLine("a value =" + base._a);
        }
    }

    class Example2 : Test
    {
        public override void A()
        {
            base._a = 5;
            Console.WriteLine("Example2.A");
            base._a--;

            Console.WriteLine("a value =" + base._a);
        }
    }

    class AbstractEx
    {
        static void Main()
        {
            // Reference Example1 through Test type.
            Test test1 = new Example1();
            test1.A();

            // Reference Example2 through Test type.
            Test test2 = new Example2();
            test2.A();
            Console.ReadKey();
        }
    }

Output :