Tuesday, 8 April 2014

Form Authentication in Asp.net

There are times when you want to validate users hitting a web site on your own rather than using Windows or Passport authentication. That requires forms based security. This article shows you how to implement Forms Based Authentication.
Hitting any web page on the site will automatically redirect to the login form. When the login form has authenticated the user, it will automatically redirect back to the originally requested page. Failure to log in will prohibit the user from hitting the originally requested page.
Each example below is shown in C#. Use the appropriate code for the language you are using.
In the web.config file in the root of the web site, insert this XML:
<authentication mode="Forms"> <forms name="login" loginUrl="login.aspx" /></authentication> <authorization> <allow roles="bigboss" /> <allow roles="wimpyuser" /> <allow users="admin" /> <deny users="*" /></authorization>
Change the rules to give permissions to the proper users and roles. You may create a different web.config and its authorization section in each subdirectory with different rules.
In the global.asax file, insert this code:
c#]
using System.Security.Principal;
using System.Web.Security;
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use 
if (!(HttpContext.Current.User == null))
{  
if (HttpContext.Current.User.Identity.IsAuthenticated)
{  
if (HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))  
{  
FormsIdentity fi = (FormsIdentity) HttpContext.Current.User.Identity;  
FormsAuthenticationTicket fat = fi.Ticket;  
String[] astrRoles = fat.UserData.Split('|'); 
HttpContext.Current.User = new GenericPrincipal(fi, astrRoles); } 
}
}
}
Create a Web Form named login.aspx, set the style to Flow Layout, and put this onto the page:
<table height="66%" width="100%">
<tr>
<td align="middle">
<table id="loginbox" width="300" class="itemstyle">
<tr>
<td id="login" align="middle" colspan="3">Login</td>
</tr>
<tr>
<td>Username:</td>
<td><asp:textbox id="txtUsername" tabindex="4" runat="server"
columns="12"></asp:textbox></td>
<td valign="center" align="middle" rowspan="2">
<asp:button id="btnLogin" runat="server" text="Login"
cssclass="button"></asp:button></td>
<tr>
<td>Password:</td>
<td><asp:textbox id="txtPassword" runat="server" columns="12"
textmode="Password"></asp:textbox></td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="2"><asp:label id="lblError" runat="server"
forecolor="Red" visible="False">Not a valid username or password.</asp:label>
</td>
</tr>
</table>
</td>
</tr>
</table>

In the CodeBehind for login.aspx, put this code:

[c#]
using System.Web.Security; private void btnLogin_Click(object sender, System.EventArgs e) { if (ValidateUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.Initialize(); String strRole = AssignRoles(txtUsername.Text); //The AddMinutes determines how long the user will be logged in after leaving //the site if he doesn't log off. FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat))); Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false)); } else lblError.Visible = true; } private Boolean ValidateUser(String strUsername, String strPassword) { //Return true if the username and password is valid, false if it isn't return ((strUsername == "admin") && (strPassword == "password")); } private String AssignRoles(String strUsername) { //Return a | separated list of roles this user is a member of if (txtUsername.Text == "admin") return "bigboss|wimpyuser"; else return String.Empty; }
Change the ValidateUser and AssignRoles to do lookups into a database or other data store instead of the hardcoded validation and role assignment shown.
On each page on the site, you will need a way to log out. Simply put a hyperlink to the logout page:
<asp:HyperLink id="hlLogout" runat="server"
NavigateUrl="logout.aspx">Logout</asp:HyperLink>

The logout.aspx page should have this on it:
<table width="100%">
<tr>
<td align="middle">
You have been logged out.
<asp:hyperlink id="hlLogin" runat="server"
navigateurl="default.aspx">Log back in.</asp:hyperlink>
</td>
</tr>
</table>

The CodeBehind for the logout page should include this:
[c#]
using System.Web.Security; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Session.Abandon(); FormsAuthentication.SignOut(); }
You can put things that are only allowable to certain roles on your web page by using code like this:
[c#]
hlAdmin.Visible = Page.User.IsInRole("bigboss");

Thursday, 27 March 2014

Passing the values between the windows forms - C#

In this article we are going to see , how to pass the value between the forms.First let we see how to pass the value from the child screen to the parent form,next parent form to child form. For transfer the data we have to use the Property.

Child form to Parent Form:
In this sample we are going to launch student form, in which the textbox is readonly we cant able to enter the value, the value should be calculate from the child form then it should fill the textbox in the parent form.

Parent Form:
public partial class ParentForm : Form
    {
        public ParentForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ChildForm cf = new ChildForm();
            cf.ShowDialog();
            textBox1.Text = cf.TotalVaue.ToString();
        }
    }



Child Form:

public partial class ChildForm : Form
    {
        public int TotalVaue { setget; }

        private int a;

        private int b;

        public ChildForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show(":Please fill the details to calculate the operation ");
            }
            else
            {
                try
                {
                    a = int.Parse(textBox1.Text);
                    b = int.Parse(textBox2.Text);
                    TotalVaue = a + b;
                    this.Close();
                }
                catch
                {
                    MessageBox.Show(":Please fill the details to calculate the operation ");
                }
            }
        }
    }

Output:


Parent Form to Child Form:
In this second sample we are going to pass the value to child form from parent form using property. So here in this sample Student name is pass from the parent form to child form.


Parent Form:

if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("Please fill the student name");
            }
            else
            {
                ChildForm cf = new ChildForm();
                cf.StudentName = textBox2.Text;
                cf.ShowDialog();
                textBox1.Text = cf.TotalVaue.ToString();
            }


Child Form :
private void ChildForm_Load(object sender, EventArgs e)
        {
            label4.Text = StudentName;
        }



Output:




I hope from this article you can learn how to pass the data from the parent form to the child form.

Drag Drop GridView Rows With JQuery Asp.Net

This Example explains How To Implement Drag And Drop GridView Rows Functionality Using JQuery JavaScript In Asp.Net 2.0 3.5 4.0 To Rearrange Row On Client Side.

You need to download and add JQuery and TableDnD plugin in your application.

GridView is populated with Northwind database using SqlDataSource.





Add Script references and css style in head section of page.


   <style type="text/css">
       .highlight
         {
            color : White !important;
             background-color : Teal !important;
         }
   </style>
     <script src="jquery-1.7.1.js" type="text/javascript"/>
    <script src="jquery.tablednd.0.7.min.js" type="text/javascript"/>

Call tableDnD function of drag and drop plugin by passing Gridview Id.


    <script type="text/javascript" language="javascript">
     $(document).ready(function() 
     {
     $("#<%=GridView1.ClientID%>").tableDnD(
                 {
                     onDragClass: "highlight"
                 });
     });
     </script>
    </head>



     <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                   AutoGenerateColumns="False" DataKeyNames="OrderID" 
                   DataSourceID="SqlDataSource1">
     <Columns>
     <asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
     <asp:BoundField DataField="Freight" HeaderText="Freight"/>
     <asp:BoundField DataField="ShipName" HeaderText="ShipName"/>
     <asp:BoundField DataField="ShipCity" HeaderText="ShipCity"/>
     <asp:BoundField DataField="ShipCountry" HeaderText="ShipCountry"/>
    </Columns>
    </asp:GridView>


Build and run the code. 

Date Time Difference in Millisecond Using C#

  1. <%@ Page Language="C#" AutoEventWireup="true"%>  
  2.       
  3. <!DOCTYPE html>        
  4. <script runat="server">  
  5.     protected void Button1_Click(object sender, System.EventArgs e)  
  6.     {  
  7.         //initialize a datetime variable with current datetime  
  8.         DateTime now = DateTime.Now;  
  9.   
  10.         Label1.Text = "now : " + now.ToString();  
  11.   
  12.         //add 2 minutes to current time  
  13.         DateTime dateAfter2Minutes = now.AddMinutes(2);  
  14.   
  15.         TimeSpan ts = dateAfter2Minutes - now;  
  16.         //total milliseconds difference between two datetime object  
  17.         int milliseconds = (int)ts.TotalMilliseconds;  
  18.          
  19.         Label1.Text += "<br ><br />after two minutes: ";  
  20.         Label1.Text += dateAfter2Minutes.ToString();  
  21.   
  22.         Label1.Text += "<br ><br />smillieconds difference between to datetime object : ";  
  23.         Label1.Text += milliseconds;  
  24.     }  
  25. </script>        
  26.         
  27. <html xmlns="http://www.w3.org/1999/xhtml">        
  28. <head id="Head1" runat="server">        
  29.     <title>c# example - datetime difference in milliseconds</title>        
  30. </head>        
  31. <body>        
  32.     <form id="form1" runat="server">        
  33.     <div>        
  34.         <h2 style="color:MidnightBlue; font-style:italic;">        
  35.             c# example - datetime difference in milliseconds  
  36.         </h2>        
  37.         <hr width="550" align="left" color="Gainsboro" />        
  38.         <asp:Label         
  39.             ID="Label1"         
  40.             runat="server"        
  41.             Font-Size="Large"      
  42.             Font-Names="Comic Sans MS"  
  43.             >        
  44.         </asp:Label>        
  45.         <br /><br />      
  46.         <asp:Button         
  47.             ID="Button1"         
  48.             runat="server"         
  49.             Text="get milliseconds difference between two datetime"        
  50.             OnClick="Button1_Click"      
  51.             Height="40"        
  52.             Font-Bold="true"        
  53.             />        
  54.     </div>        
  55.     </form>        
  56. </body>        
  57. </html>