Friday, January 25, 2013

Remember password functionality in ASP.NET

In the Login button click write the below code

protected void btn_Login_Click(object sender, EventArgs e)  
{  
     if (cb_Remember.Checked)  
     {  
          HttpCookie prCookie = new HttpCookie("PRCOOKIE");  
          prCookie["EID"] = txt_EmpId.Text;  
          prCookie["PWD"] = txt_Password.Text;  
          Response.Cookies.Add(prCookie);  
          Response.Cookies["PRCOOKIE"].Expires = DateTime.Now.AddDays(30);  
     }  
     else  
     {  
          Response.Cookies["PRCOOKIE"].Expires = DateTime.Now.AddDays(-1);  
     }  
}  
Here,
cb_Remember is a CheckBox
txt_EmpId.Text is a Login Name TextBox
txt_Password.Tex is a Password TextBox


then in the Page_Load function add the below code

protected void Page_Load(object sender, EventArgs e)  
{  
     HttpCookie cookie = Request.Cookies["PRCOOKIE"];  
     if (cookie != null)  
     {  
          txt_EmpId.Text = Convert.ToString(cookie["EID"]);  
          txt_Password.Attributes["Value"] = Convert.ToString(cookie["PWD"]);  
     }  
}  

Thursday, January 24, 2013

How to Bind DataTable to ASP.NET Pie Chart


To Bind DataTable to ASP.NET Pie Chart, refer the below code.
 DataTable dt=new DataTable();  
   
 dt.Columns.Add("Name");  
 dt.Columns.Add("Percentage");  
   
 DataRow dr=dt.NewRow();  
 dr["Name"]="Name1";  
 dr["Percentage"]="80";  
 dt.Rows.Add(dr);  
   
 DataRow dr1=dt.NewRow();  
 dr1["Name"]="Name2";  
 dr1["Percentage"]="75";  
 dt.Rows.Add(dr1);  
   
 DataRow dr2=dt.NewRow();  
 dr2["Name"]="Name3";  
 dr2["Percentage"]="90";  
 dt.Rows.Add(dr2);  
   
 DataRow dr3=dt.NewRow();  
 dr3["Name"]="Name4";  
 dr3["Percentage"]="100";  
 dt.Rows.Add(dr3); 
   
 Dictionary<string, int> chartData = new Dictionary<string, int>();  
 foreach (DataRow r in dt.Rows)  
 {  
     string key = r["Name"].ToString();  
     int value = Convert.ToInt32(r["Percentage"]);  
     chartData.Add(key, value);  
 }  
   
 Chart1.Series["Series1"].Points.DataBind(chartData , "Key", "Value", string.Empty);  

How to count days between two dates except Saturday and Sunday in CSharp (C#)


To count days between two dates except Saturday and Sunday use the below C# code
public int CountDays(fromDate,toDate)  
{  
     int noOfDays = 0;  
     DateTime fDate = Convert.ToDateTime(fromDate);  
     DateTime tDate = Convert.ToDateTime(toDate);  
     while (DateTime.Compare(fDate, tDate) <= 0)  
     {  
          if (fDate.DayOfWeek != DayOfWeek.Saturday && fDate.DayOfWeek != DayOfWeek.Sunday)  
          {  
               noOfDays += 1;  
          }  

          fDate = fDate.AddDays(1);  
     }  
     
     return noOfDays;  
}  

Compare two date in CSharp (C#)

Some times you may have a situation to compare two dates for the date validation. You can do this easily using the DateTime.Compare method.
public bool ValidateDate(string from,string to)  
{  
     bool isValid = false;  
     if (from != string.Empty && to != string.Empty)  
     {  
          if (DateTime.Compare(Convert.ToDateTime(txt_From.Text), Convert.ToDateTime(txt_To.Text)) == 1)  
          {  
               isValid = false;  
          }  
          else  
          {  
               isValid = true;  
          } 
 
          if (DateTime.Compare(Convert.ToDateTime(to), DateTime.Now) > 0)  
          {  
          isValid = false;  
          }  
     } 
 
     return isValid;  
}  

Move ListBox selected Items to another ListBox in ASP.NET CSharp (C#)

Assume you have two  ListBoxes ListBox1 and ListBox2 in your ASP.NET application. You like to move selected items from ListBox1 to ListBox2. Usee the below code.
if (ListBox.Items.Count > 0 && ListBox.SelectedItem != null)  
{  
    while (ListBox.Items.Count > 0 && ListBox.SelectedItem != null)  
    {  
        ListItem selectedItem = new ListItem();  
        selectedItem = ListBox.SelectedItem;  
        selectedItem.Selected = false;  
        ListBox2.Items.Add(selectedItem);  
        ListBox1.Items.Remove(selectedItem);  
    }  
}  

you can move multiple items by selecting multiple items in list box. To do that you have to set the ListBox "SelectionMode" properties to "Multiple"

Display online users in in ASP.NET application

To display online users in ASP.NET application u need to add a Global.asax file. Global.ascx is the ASP.NET application file. It has some application level events raised by ASP.NET application. In the below code whenever a user log in to your application a count will increase in Application["CurrentUsers"] state. The count will decrease when he Log Out.
void Application_Start(object sender, EventArgs e)  
{  
    // Code that runs on application startup  
    Application["CurrentUsers"] = 0;  
}  

void Application_End(object sender, EventArgs e)  
{  
    // Code that runs on application shutdown  
}  

void Application_Error(object sender, EventArgs e)  
{  
    // Code that runs when an unhandled error occurs  
}  

void Session_Start(object sender, EventArgs e)  
{  
    // Code that runs when a new session is started  
    Application.Lock();  
    Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1;  
    Application.UnLock();  
}  

void Session_End(object sender, EventArgs e)  
{  
    // Code that runs when a session ends.  
    // Note: The Session_End event is raised only when the sessionstate mode  
    // is set to InProc in the Web.config file. If session mode is set to StateServer  
    // or SQLServer, the event is not raised.  
    Application.Lock();  

    if ((int)Application["CurrentUsers"] > 0)  
    {  
        Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1;  
    }  

    Application.UnLock();  
}  
Then in the Code behind add the below code
Label1.Text = Convert.ToString(Application["CurrentUsers"]);  

Add a new event to server control in asp.net

Server controls in asp.net may not have all required events. But we can add additional javaScript events. So here i have provided a example to add a "Double Click" event in ListBox control.
protected void Page_Load(object sender, EventArgs e)  
{  
    ListBox1.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(ListBox1, "doubleClickEvent"));  
    if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "doubleClickEvent")  
    {  
        //Write your code to handle the Double Click Event  
    }  
}  

Wednesday, January 23, 2013

Set up ASP.NET web application default page in IIS

It's essential to set the starting page of your ASP.net application in IIS. Here I have provided the solution to do that
  • Go to Start -> Run
  • Type "inetmgr" then press Enter
  • In the Default Web Site right click your web application then select Properties
  • Navigate to Documents tab
  • Add the page name with extension by clicking the add button
  • Press Apply

It will work now!

Expand or collapse displaying text in asp.net label using more/less link button

To Expand or collapse displaying text in asp.net label using more/less link button use the below code
 <script type="text/javascript">  
   $(document).ready(function () {  
     var showChar = 200;  
     var ellipsestext = "...";  
     var moretext = "more";  
     var lesstext = "less";  
     $('.more span').each(function () {  
       var content = $(this).html();  
       if (content.length > showChar) {  
         var c = content.substr(0, showChar);  
         var h = content.substr(showChar - 1, content.length - showChar);  
         var html = c + '<span class="moreelipses">' + ellipsestext + '</span>&nbsp;<span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';  
         $(this).html(html);  
       }  
     });  
     $(".morelink").click(function () {  
       if ($(this).hasClass("less")) {  
         $(this).removeClass("less");  
         $(this).html(moretext);  
       } else {  
         $(this).addClass("less");  
         $(this).html(lesstext);  
       }  
       $(this).parent().prev().toggle();  
       $(this).prev().toggle();  
       return false;  
     });  
   });  
 </script>  
  • Add the above code in asp.net page
  • Cover the label with div tags and use a class "more" like showing in below code

 <div class="more">  
 <asp:Label ID="Label1" runat="server" Text=""></asp:Label>  
 </div>  

The JavaScript code will search the more class in asp.net design page and apply the more / less functionality.

(Solved) Error: Unrecognized attribute 'targetFramework'.

Error:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

Source Error:
</controls>  
    </pages>  
    <compilation debug="true" targetFramework="4.0" />    
<authentication mode="Forms">  
Solution:
In IIS 5.1
  • Go to Start -> Run
  • Type "inetmgr" then press Enter
  • In the Default Web Site right click your web application then select Properties
  • Navigate to ASP.NET tab
  • Change the ASP.NET version to 4.0
  • Press Apply
  • It will work now

(Solved) Error: Invalid temp directory in chart handler configuration [c:\TempImageFiles\]

Solution for this error is,
  • Go the the Web.config file in your ASP.NET application
  • Navigate to the below line
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;">
</add>
  • Just remove the dir element from the add attribute like below
<add key="ChartImageHandler" value="storage=file;timeout=20;">
</add>
  • Publish your app.