Friday, September 2, 2011

Encode Decode QueryString

EncodeQuery.cs
-----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace QueryString
{
    public class EncodeQuery
    {
        private static byte[] key = { };
        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        private static string EncryptionKey = "!#853g`de";
       
        public string Encrypt(string Input)
        {
          try
           {
                key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] inputByteArray = Encoding.UTF8.GetBytes(Input);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
          }
         catch (Exception ex)
         {
           return "";
         }
       }
    }
}
DecodeQuery.cs
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace QueryString
{
    public class DecodeQuery
    {
        private static byte[] key = { };
        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        private static string EncryptionKey = "!#853g`de";
        public string Decrypt(string Input)
        {
            Byte[] inputByteArray = new Byte[Input.Length];
            try
            {
                key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(Input);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                return "";
            }
        }
    }
}




Default.aspx
--------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QueryString._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 style="height: 138px">
    
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Redirect" />
    
    </div>
    </form>
</body>
</html>
Default.aspx.cs
---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace QueryString
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            EncodeQuery eq = new EncodeQuery();
            Response.Redirect("WebForm1.aspx?" + "Name=" + eq.Encrypt("muruga") +"&LastName=" + eq.Encrypt("S")); 
        }
    }
}
WebForm1.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="QueryString.WebForm1" %>
<!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>
    </form>
</body>
</html>
WebForm1.aspx.cs
-------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace QueryString
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DecodeQuery eq = new DecodeQuery();
            string str1 = eq.Decrypt(Request.QueryString["Name"]);
            string str2 = eq.Decrypt(Request.QueryString["LastName"]);
            Response.Write(str1+" ");
            Response.Write(str2);
        }
    }
}




button1



button2

Sunday, August 28, 2011

Persisting CheckBox State While Paging in GridView Control

grid

Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxPersistGridView.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView ID="gvCustomers" PageSize="3" AllowPaging="true" OnPageIndexChanging="gvCustomersPageChanging" runat="server" AutoGenerateColumns="false">
    
    <Columns>
    
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="First Name">
    <ItemTemplate>
    <%# Eval("CatID") %>
    </ItemTemplate>
    </asp:TemplateField>
    
     <asp:TemplateField HeaderText="Last Name">
    <ItemTemplate>
    <%# Eval("CatName") %>
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="RowIndex">
    <ItemTemplate>
    <%# Container.DisplayIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
      <asp:TemplateField HeaderText="DataItemIndex">
    <ItemTemplate>
    <%# Container.DataItemIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
    </Columns>
    
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Default.aspx.cs
--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace CheckBoxPersistGridView
{
    public partial class Default : System.Web.UI.Page
    {
        public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex"; 
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                BindData();
            }
        }
        private void BindData()
        {
            SqlConnection conn = new SqlConnection(@"Data Source=truefaster\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select CatID,CatName from Category",conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Category");
            gvCustomers.DataSource = ds.Tables["Category"];
            gvCustomers.DataBind();
            //using(var db = new  NorthwindDataContext())
            //{
                
            //    gvCustomers.DataSource = from c in db.Categories
            //                             select c; 
            //    gvCustomers.DataBind();
            //}
            RePopulateCheckBoxes(); 
        }
        private void RePopulateCheckBoxes()
        {
            foreach (GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
                if (SelectedCustomersIndex != null)
                {
                    if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
                    {
                        chkBox.Checked = true;
                    }
                }
            }
        }
        protected void gvCustomersPageChanging(object sender, GridViewPageEventArgs e)
        {
            foreach(GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer) chkBox.NamingContainer; 
                if(chkBox.Checked)
                {
                    PersistRowIndex(container.DataItemIndex); 
                }
                else
                {
                    RemoveRowIndex(container.DataItemIndex);
                }
            }
            gvCustomers.PageIndex = e.NewPageIndex;
            BindData(); 
        }
        private List<Int32> SelectedCustomersIndex
        {
            get
            {
                if(ViewState[SELECTED_CUSTOMERS_INDEX] == null)
                {
                    ViewState[SELECTED_CUSTOMERS_INDEX] = new List<Int32>(); 
                }
                return (List<Int32>) ViewState[SELECTED_CUSTOMERS_INDEX]; 
            }
        }
        private void RemoveRowIndex(int index)
        {
            SelectedCustomersIndex.Remove(index); 
        }
        
        private void PersistRowIndex(int index)
        {
            if(!SelectedCustomersIndex.Exists(i => i == index))
            {
                SelectedCustomersIndex.Add(index);
            }
        }
    }
}



output:


Menu From Database

Menu Database2.html
Default3.aspx
--------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Debug="true" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .menuItem
{
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #000000;
	border: 1px solid #C8B678;
	color: #806000;
	background-color: #FFF7DD;
	padding: 4px 5px 4px 5px;
}
 .menuHover
{
	color: #EEEBE6;
	border: 1px Solid #C8B678;
	background-color: #A47E00;
	padding: 4px 5px 4px 5px;
	text-decoration: none;
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Menu Width="165px" ID="Menu1" StaticMenuItemStyle-CssClass="menuItem" StaticHoverStyle-CssClass="menuHover"
    DynamicHoverStyle-CssClass="menuHover" DynamicMenuItemStyle-CssClass="menuItem"
    runat="server">
    <StaticItemTemplate>
        <%# Eval("Text") %>
        <asp:Label runat="server" ID="lbItmCount">[<%#Eval("ChildItems.Count")%>]</asp:Label>
    </StaticItemTemplate>
</asp:Menu>
    </div>
    </form>
</body>
</html>
Default3.aspx.cs
------------------
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
partial class Default3 : System.Web.UI.Page
{
    public Default3()
    {
        Load += Page_Load;
    }
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindMenu();
        }
    }
    public void BindMenu()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlDataAdapter dadCategories = new SqlDataAdapter("SELECT CatId,CatName FROM Category order by CatName", con);
        SqlDataAdapter dadSubCat = new SqlDataAdapter("SELECT SubCatId,CatId,SubCatName FROM SubCategory order by SubCatName", con);
        // Add the DataTables to the DataSet
        DataSet dsCat = new DataSet();
        using (con)
        {
            con.Open();
            dadCategories.Fill(dsCat, "Category");
            dadSubCat.Fill(dsCat, "SubCategory");
        }
        // Add a DataRelation
        dsCat.Relations.Add("Children", dsCat.Tables["Category"].Columns["CatId"], dsCat.Tables["SubCategory"].Columns["CatId"]);
        // Add the Category nodes
        int count = 0;
        foreach (DataRow categoryRow in dsCat.Tables["Category"].Rows)
        {
            MenuItem mNode = new MenuItem(Convert.ToString(categoryRow["CatName"]), "", "", "~/DetailView.aspx?CatID=" + Convert.ToString(categoryRow["CatId"]), "_parent");
            Menu1.Items.Add(mNode);
            // Get matching Sub Category
            DataRow[] subCatRows = categoryRow.GetChildRows("Children");
            foreach (DataRow row in subCatRows)
            {
                string subCatName = Convert.ToString(row["SubCatName"]);
                MenuItem subCatItems = new MenuItem(subCatName, "", "", "~/DetailView.aspx?CatID=" + Convert.ToString(row["CatId"]) + "&SubCatID=" + Convert.ToString(row["SubCatId"]), "_parent");
                Menu1.Items[count].ChildItems.Add(subCatItems);
            }
            count = count + 1;
        }
    }
    
}


 



DetailView.aspx
------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailView.aspx.cs" Inherits="DetailView" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        You have selected
        <br />
        Category ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :&nbsp;
        <asp:Label ID="lbCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        Sub Category ID :&nbsp;
        <asp:Label ID="lbSubCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        <br />
        Back to the previous page <a href="Default.aspx">Default.aspx</a></div>
    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailView.aspx.cs" Inherits="DetailView" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        You have selected
        <br />
        Category ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :&nbsp;
        <asp:Label ID="lbCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        Sub Category ID :&nbsp;
        <asp:Label ID="lbSubCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        <br />
        Back to the previous page <a href="Default.aspx">Default.aspx</a></div>
    </form>
</body>
</html>
DetailView.aspx.cs
---------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public partial class DetailView : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if ((Request.QueryString["CatId"] != null))
        {
            lbCatID.Text = Request.QueryString["CatId"];
        }
        if ((Request.QueryString["SubCatId"] != null))
        {
            lbSubCatID.Text = Request.QueryString["SubCatId"];
        }
    }
    public DetailView()
    {
        Load += Page_Load;
    }
}


output:



Menu Database3_html_m4c6debb1