Tuesday 15 May 2012

Encrypt & Decrypt of Password in Asp.net



In .aspx page:-

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="" width="50%">
            <tr>
                <td colspan="2" style="font-family: 'Times New Roman', Times, serif; font-size: large;
                    font-weight: bold; text-decoration: underline; color: #800000">
                    Encryption and Decryption of Password.
                </td>
            </tr>
            <tr>
                <td align="right">
                    UserName :
                </td>
                <td>
                    <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ControlToValidate="txtUsername" ErrorMessage="Enter User Name">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Password :
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                        ControlToValidate="txtPassword" ErrorMessage="Enter Password">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Email Id :
                </td>
                <td>
                    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td />
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    </br></br>
    <table cellspacing="10" width="60%">
        <tr>
            <td align="center">
                Encrypted Password.
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="gvUsers" runat="server" CellPadding="4" BackColor="White" BorderColor="#CC9966"
                    BorderStyle="None" BorderWidth="1px" Width="480px">
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <SortedAscendingCellStyle BackColor="#FEFCEB" />
                    <SortedAscendingHeaderStyle BackColor="#AF0101" />
                    <SortedDescendingCellStyle BackColor="#F6F0C0" />
                    <SortedDescendingHeaderStyle BackColor="#7E0000" />
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td align="center">
                Decrypted Password.
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="gvdecryption" runat="server" BackColor="White" BorderColor="#CC9966"
                    BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowDataBound="gvdecryption_RowDataBound"
                    Width="480px">
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <SortedAscendingCellStyle BackColor="#FEFCEB" />
                    <SortedAscendingHeaderStyle BackColor="#AF0101" />
                    <SortedDescendingCellStyle BackColor="#F6F0C0" />
                    <SortedDescendingHeaderStyle BackColor="#7E0000" />
                </asp:GridView>
            </td>
        </tr>
    </table>
    </form>
</body>

In .aspx.Cs Page:-

SqlConnection ConnString = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    DataSet Ds;
    SqlDataAdapter Da;
    String SqlString = "SELECT * FROM [UserTable]";

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridBindEncryptedData();
            GridBindDecryptedData();
        }
    }

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string StrPwd = Encryptdata(txtPassword.Text);
        ConnString.Open();
        SqlCommand SqlCmd = new SqlCommand("INSERT INTO [UserTable]([Username],[Password],[EmailId])VALUES('" + txtUsername.Text + "','" + StrPwd + "','" + txtEmailId.Text + "')", ConnString );
        SqlCmd.ExecuteNonQuery();
        ConnString.Close();
        GridBindEncryptedData();
        GridBindDecryptedData();
    }

    #region " G R I D V i e w  D I S P L A Y "
    //Binding Encrypted data To GridView1
    protected void GridBindEncryptedData()
    {
        ConnString.Open();
        SqlCommand SqlCmd = new SqlCommand(SqlString, ConnString);
        Da = new SqlDataAdapter(SqlCmd);
        Ds = new DataSet();
        Da.Fill(Ds);
        gvUsers.DataSource = Ds;
        gvUsers.DataBind();
        ConnString.Close();
    }
    //Binding Decrypted data To GridView2
    protected void GridBindDecryptedData()
    {
        ConnString .Open();
        SqlCommand SqlCmd = new SqlCommand(SqlString, ConnString);
        Da = new SqlDataAdapter(SqlCmd);
        Ds = new DataSet();
        Da.Fill(Ds);
        gvdecryption.DataSource = Ds;
        gvdecryption.DataBind();
        ConnString .Close();
    }
    //RowDataBound event fires on binding the data to the row
    protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string decryptpassword = e.Row.Cells[1].Text;
            e.Row.Cells[1].Text = Decryptdata(decryptpassword);
        }
    }   
    #endregion
    #region " F U N C T I O N S "
    // Function is used to Encrypt the Password   
    private string Encryptdata(string Password)
    {
        string strPwd = string.Empty;
        byte[] toEncode = new byte[Password.Length];
        toEncode = System.Text.Encoding.UTF8.GetBytes(Password);
        strPwd = Convert.ToBase64String(toEncode);
        return strPwd;
    }
    // Function is used to Decrypt the Password   
    private string Decryptdata(string encryptpwd)
    {
        string strPwd = string.Empty;
        UTF8Encoding EncodePwd = new UTF8Encoding();
        System.Text.Decoder utf8Decode = EncodePwd.GetDecoder();
        byte[] toDecode = Convert.FromBase64String(encryptpwd);
        int StrCount = utf8Decode.GetCharCount(toDecode, 0, toDecode.Length);
        char[] decodedStr = new char[StrCount];
        utf8Decode.GetChars(toDecode, 0, toDecode.Length, decodedStr, 0);
        strPwd = new String(decodedStr);
        return strPwd;

    }
    #endregion

In Web.Config:-

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=Manjeeth;Initial Catalog= Manjeeth;User ID=sa;Password=****" providerName="System.Data.SqlClient"/>
  </connectionStrings>


Database Script for a table UserTable:-

CREATE TABLE [dbo].[UserTable](
      [Username] [varchar](50) NOT NULL,
      [Password] [nvarchar](100) NULL,
      [EmailId] [varchar](50) NULL,
 CONSTRAINT [PK_UserTable] PRIMARY KEY CLUSTERED
(
      [Username] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Happy Programming.....





Friday 11 May 2012

ASP.NET Authentication and Authorization



Authentication Authentication is the process of attaining identification credentials such as username and password from a user and validating those credentials against some authority.  If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.


Authorization : The purpose of authorization is to determine whether an identity should be granted the requested type of access to a given resource.

There are three types of Authentication.They are
1. Forms Authentication
2. Windows Authentication
3. Passport Authentication

Forms Authentication is cookie based, as ASP.NET places a cookie in the client machine in order to track the user. If the user requests a secure page and has not logged in, then ASP.NET redirects user to the login page. Once the user is authenticated, then user will be allowed to access the requested page. 

Windows Authentication can be used only in an intranet environment where the administrator has full control over the users in the network. 

Passport Authentication Passport authentication is a centralized authentication service that uses Microsoft's Passport Service to authenticate the users of an application. It allows the users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. 


In this example, we are showing how authentication and authorization works. We are taking 3 Roles ADMIN, USER and SECURE USER. When Admin logins he has permissions to access all the modules. When user logins he can access all modules except ADMIN module. And when the secure user logins he can access only the Secure module.

In this example we have taken one XML file (UserInformation.xml) for Users Information and Roles. This xml file works as the database file. And every Authenticate Requests Fires from the browser is from Global.asax file.
This is the best example of Authentication and Authorization.


-- Happy Programming----------


Thursday 10 May 2012

Cascading DropDownList in ASP.NET using database



Description :


        Asp.Net Dropdownlist selection on client side using Web-service, Ajax call and database.



Database :

CREATE TABLE [dbo].[Country](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [Name] [varchar](50) NULL,   
      [ParentId] [int] NULL, 
 CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[Country] ON
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (1, N'India', NULL)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (2, N'AndhraPradesh', 1)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (3, N'Karnataka', 1)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (4, N'Tamilnadu', 1)

INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (5, N'USA', NULL)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (6, N'California', 5)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (7, N'Washington', 5)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (7, N'Florida', 5)


INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (8, N'Oman', NULL)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (9, N'Zufar', 8)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (10, N'Masqat', 8)
INSERT [dbo].[Country] ([Id], [Name], [ParentId]) VALUES (10, N'al-Batina', 8)

SET IDENTITY_INSERT [dbo].[Country] OFF


In .aspx Page:-

<head runat="server">
    <script src="../Javascript/jquery-1.6.4.min.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        var pageUrl = '<%=ResolveUrl("~/Cascadingddl.aspx")%>';
        function ProjectChanged() {
            $.ajax({
                type: "POST",
                url: pageUrl + '/GetCountrySummary',
                data: '{Id: ' + $('#<%=ddlCountry.ClientID%>').val() + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: CountryChangedCallBack
            });
        }
        function CountryChangedCallBack (response) {
            var CountryList = response.d;
            $("#<%=ddlState.ClientID%>").empty();
            $('#<%= ddlState.ClientID%>').append(new Option('--Select--', '0'));
            $.each(CountryList, function (index) {
                var Country = CountryList [index];
                $('#<%= ddlState.ClientID%>').append(new Option(Country.name, Country.id));
            });
        }

        function StateChanged() {
            debugger;
            var CountryName = $('#<%= ddlState.ClientID %> option:selected').text();
            alert("Country Name : " + CountryName + " and Id :" + $('#<%= ddlState.ClientID%>').val());

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                Select Country:
            </td>
            <td>
                <asp:DropDownList ID=" ddlCountry " onchange="CountryChanged();" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Select Product :
            </td>
            <td>
                <asp:DropDownList ID=" ddlState " runat="server" onchange=" StateChanged ();" />
            </td>
        </tr>
    </table>
    </form>
</body>

In .Cs Page:-

String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String strQuery = "Select Id,Name from Country Where Id is Null";
            // Fill The Country Dropdownlist in Form_Load
        }
    } 


    [System.Web.Services.WebMethod]

    public static System.Collections.ArrayList GetCountrySummary(int Id)
    {
        System.Collections.ArrayList list = new System.Collections.ArrayList();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        String strQuery = "Select Id,Name from Country Where Id="+Id;
        using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strConnString))
        {
            using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = strQuery;
                cmd.Connection = con;
                con.Open();
                System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    var Country = new
                    {
                        Cid = sdr["id"],
                        Cname = sdr["Name"]                        
                    };
                    list.Add(Country);
                }
                con.Close();
            }
        }
        return list;
    }