23 May 2013

Count the Number of Online Visitors of an ASP.NET Web Site

Steps 1:

Create a web site for which you want to count online visitors.

Steps 2:

Add global.asax file into our website .Here is steps to add global.asax file into your website
  • Write Click on your website say Add new items

    Asp.net1.gif
     
  • In the item window select Global Application Class

    Asp.net2.gif
     
  • Click on Add Button

Note: Don't change Global.asax file name.

Step 3:


Write this code into the Global.asax file:

Which look like:
<%@ Application Language="C#" %>
<script runat="server">     void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup        Application["OnlineUsers"] = 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["OnlineUsers"] = (int)Application["OnlineUsers"] + 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();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
        Application.UnLock();
    }
</script>
This will allow us to, whenever a distant web visitor opens our website in his browser,
create a new session for him by incrementing our "OnlineUsers" variable in the global HttpApplicationState class instance.

Also when the user closes his browser or does not click on any links in our website, the session expires,
and our "OnlineUsers" global variable is decreased.

NOTE: we are using the Application.Lock and Application.Unlock methods to prevent multiple threads from changing this variable at the same time.

By calling Application.Lock we are receiving exclusive right to change the values in Application state.

But we must not forget to call Application.Unlock() afterwards.

Step 4:

In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):
        <system.web>
        <
sessionState mode="InProc" cookieless="false" timeout="20" />
        </
system.web>

In-process mode stores session state values and variables in memory on the local Web server.

It is the only mode that supports the Session_OnEnd event that we used previously.

A timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words here we set how long our users can be inactive before considered Offline.

In this example the timeout is set to 20 minutes, so while our visitors click on some links in our website at least once in a 20 minute period, they are considered online.

If they do not open any pages on our website during 20 minutes, they are considered offline, and their session is destroyed, so our online visitor counter is decreased by 1.

Note: You can change the Session State time by using a timeout property. The default time for a session is 20 minutes.

Step 5:

To show the number of online visitors/users on your ASPX page you can use this code:
Online Visitors: <%= Application["OnlineUsers"].ToString() %>

Next you can put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and
use a Timer to refresh it in regular intervals without refreshing the whole page or you can write the following line inside a HTML body tag. It will refresh your Page every 5 minutes.
<meta http-equiv="Refresh" content="300">

Step 6: Run the web site.

20 May 2013

export gridview to excel,word,pdf and print in asp.net with c#

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <br />
    <center>    <asp:Button ID="btn1" runat="server" Text="Export to Excel" OnClick="btn1_Click" />
        <asp:Button ID="Button1" runat="server" Text="Export to Word"
            onclick="Button1_Click"/>
        <asp:Button ID="Button2" runat="server" Text="Export to PDF"
            onclick="Button2_Click"/>
        <input id="Submit1" onclick="window.print()" type="submit" value="Print" /><br />
    <br />
 
    <asp:GridView ID="gv1" runat="server">
    </asp:GridView>
    </center>

</asp:Content>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        string sql = "select * from Employee_Details";
        SqlCommand cmd = new SqlCommand(sql, con);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        da.Fill(ds);
        gv1.DataSource = ds;
        gv1.DataBind();
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment; filename=Expport.xls");
        Response.ContentType = "application/ms-excel";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment; filename=Expport.doc");
        Response.ContentType = "application/ms-word";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        Response.AddHeader("content-disposition", "attachment; filename=Expport.pdf");
        Response.ContentType = "application/pdf";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
        
    }
}

web.config

<connectionStrings>
<add name="con" connectionString="Data Source=.;Initial Catalog=exp;Integrated Security=true;"/>
</connectionStrings>

Output







nested gridview in asp.net c#

Create Database:

create database nestedgridview


USE [nestedgridview]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Branch](
[id] [int] IDENTITY(100,1) NOT NULL,
[Branch] [varchar](200) NULL,
[sem] [varchar](200) NULL,
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 ANSI_PADDING OFF
GO

USE [nestedgridview]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[teacher](
[id] [int] IDENTITY(100,1) NOT NULL,
[branch] [int] NULL,
[name] [varchar](200) NULL,
[cell] [varchar](200) NULL,
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 ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[teacher]  WITH CHECK ADD FOREIGN KEY([branch])
REFERENCES [dbo].[Branch] ([id])
GO

Create Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
        <center>
            <asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false" CellPadding="4"
                CellSpacing="2" OnRowDataBound="gv1_RowDataBound" DataKeyNames="id">
                <Columns>
                    <asp:TemplateField HeaderText="Nested Gridview">
                        <ItemTemplate>
                            <%# Eval("id")%>---
                            <%# Eval("Branch")%>
                            ---
                            <%# Eval("sem")%>
                            <asp:GridView ID="gv2" runat="server" Width="100%" EnableViewState="false">
                            </asp:GridView>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </center>
    </div>
    </form>
</body>
</html>

Create Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    SqlCommand cmd = new SqlCommand();
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter();
    protected void Page_Load(object sender, EventArgs e)
    {
        string sql = "select * from Branch";
        con.Open();
        cmd = new SqlCommand(sql, con);
        da.SelectCommand = cmd;
        da.Fill(ds);
        con.Close();
        gv1.DataSource = ds;
        gv1.DataBind();
    }
    protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow) return;
        GridView gv2 = (GridView)e.Row.FindControl("gv2");
        int fid = int.Parse(gv1.DataKeys[e.Row.RowIndex].Value.ToString());
       // DataTable table = new DataTable();
        DataSet ds1 = new DataSet();
        SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        using (con1)
        {
           // con.Open();
            string sql1 = "select * from teacher where branch=@fid";
            using (SqlCommand cmd1 = new SqlCommand(sql1, con1))
            {
                using (SqlDataAdapter da1=new SqlDataAdapter(cmd1))
                {
                    cmd1.Parameters.AddWithValue("@fid", fid);
                    da1.Fill(ds1);
                }
            }
        }
        gv2.DataSource = ds1;
        gv2.DataBind();
       // con.Close();
       // ds1.Clear();
    }
    
    
}

web.config

  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.;Initial Catalog=nestedgridview;Integrated Security=true;"/>
  </connectionStrings>

Output:

Difference between interface and abstract class

Abstract Class: 
1) An abstract method is created by specifying the abstract type modifier. 
2) An abstract method contains no body. 
3) An abstract method is not implemented by the base class. 
4) An abstract method is automatically virtual. 
5) A derived class must override it. 
6) Abstract class can have modifiers for methods,properties etc., 
7) An abstract class can implement a property. 
8) The abstract modifier cannot be applied to static methods. 
9) Properties can also be abstract. 
10) A class containing abstract methods must be declared as abstract with the abstract specifier. 
11) There can be no objects of an abstract class. 
12) If a derived class doesn't implement all of the abstract methods in the base class, then the derived class must also be specified as abstract. 
13) An abstract class can inherit from a class and one or more interfaces. 
14) An abstract class can implement code with non-Abstract methods. 
15) Abstract class can have constant and fields. 
16) An abstract class can have constructors or destructor's. 
17) An abstract class cannot be inherited from by structures. 
18) An abstract class cannot support multiple inheritance. 
19) If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. 

Interface:
1) Interfaces cannot be instantiated directly. 
2) Interfaces can contain events, method, indexer and properties. 
3) An Interface can contain property definitions. 
4) Interfaces contain no implementation of methods. 
5) Classes and Structs can implement more than one interface. 
6) An Interface can be inherited from by structures. 
7) An interface itself can inherit from multiple interfaces (Interface can support multiple 
inheritance). 
8) An abstract class can implement a property. 
9) If we add a new method to an Interface then we have to track down all the implementations of 
the interface and define implementation for the new method.

Difference between array list and hash table


Array List:

1.Array List is a List 
2.In this we can only add items to the list 
3.Here we Can Add any datatype value,Every item in arraylist is treated as object 
4. ArrayList Key must be numeric.
5. Arraylist is a collection of objects(may be of different types).

Hash Table:

1.Hash Table is a map 
2.Here we can add data with the key 
3.Retrieving by key in Hashtable is faster than retrieving in Arraylist.
4. Hashtable Contain two parameter first is Key and other is Value and in case of Hash Table key may be numeric or Alpha.
5. Hashtable is also collection which takes a key corresponding to each values.

Difference between dll and exe in .net


.DLL
1.Its a Dynamic Link Library.
2.  It can be reused.
3. It can be versioned.
4. It is not self executable.
5. It doesn't have main function.
6.There are many entry points.
7.The system loads a DLL into the context of an existing thread.
8.DLL Can Occupy own memory space it self.
9.Many .dll files may exists in one application.
10.dll can be shared with other applications.

.EXE
1.Its a executable file.
2. It cannot be reused.
3.It cannot be versioned.
4.It is self executable.
5.It will have main.
6.There is only single main entry.
7.When a system launches new exe, a new process is created.
8.The entry thread is called in context of main thread of that process.
9.Only one .exe file exists per application.
10.Exe cannot be shared with other applications.

Differences between Stored Procedures and Functions


  1. Procedure can return zero or n values whereas function can return one value which is mandatory.
  2. Procedures can have input/output parameters for it whereas functions can have only input parameters.
  3. Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
  4. Functions can be called from procedure whereas procedures cannot be called from function.
  5. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
  6. We can go for transaction management in procedure whereas we can't go in function.
  7. Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.
  8. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  9. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  10. Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowsetoperations.

Stored Procedure

A Stored Procedure is a program (or procedure) which is physically stored within a database. They are usually written in a proprietary database language like PL/SQL for Oracle database or PL/PgSQL for PostgreSQL. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server. As such, it has direct access to the data it needs to manipulate and only needs to send its results back to the user, doing away with the overhead of communicating large amounts of data back and forth.

User-defined Function

A user-defined function is a routine that encapsulates useful logic for use in other queries. While views are limited to a single SELECT statement, user-defined functions can have multiple SELECT statements and provide more powerful logic than is possible with views.
User defined functions have three main categories:
  1. Scalar-valued function - returns a scalar value such as an integer or a timestamp. Can be used as column name in queries.
  2. Inline function - can contain a single SELECT statement.
  3. Table-valued function - can contain any number of statements that populate the table variable to be returned. They become handy when you need to return a set of rows, but you can't enclose the logic for getting this rowset in a single SELECT statement.

Stored Procedure

Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called.

Function

Function is compiled and executed every time when it is called.

Difference:
  • Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  • Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  • Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
  • Functions can be called from Procedure whereas Procedures cannot be called from Function.
  • Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  • Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  • Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  • Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  • Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  • Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  • We can go for Transaction Management in Procedure whereas we can't go in Function.

Login code using Stored Procedure

login.aspx

    <asp:Panel ID="panel1" runat="server">
        <table>
            <tr>
                <td align="right">
                    <asp:Label ID="lblUid" runat="server" Text="UserName :"></asp:Label>
                </td>
                <td align="left">
                    <asp:TextBox ID="txtUid" runat="server" Height="25px" Width="275px" BorderColor="#666666"
                        BorderStyle="Solid" BorderWidth="1px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvlogin" runat="server" Display="Dynamic" ControlToValidate="txtUid"
                        Text="*" CssClass="err" ValidationGroup="l" />
                </td>
            </tr>
            <tr>
                <td align="right">
                    <asp:Label ID="lblpwd" runat="server" Text="Password :"></asp:Label>
                </td>
                <td align="left">
                    <asp:TextBox ID="txtpwd" runat="server" TextMode="Password" Height="25px" Width="275px"
                        BorderColor="#666666" BorderStyle="Solid" BorderWidth="1px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic"
                        ControlToValidate="txtpwd" CssClass="err" ValidationGroup="l" Text="*" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="left">
                    <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Sign In"
                        ValidationGroup="l" Height="30px" Width="90px" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="left">
                    Forgot Login Details?&nbsp;<asp:HyperLink ID="hlnkForgottenPassword" runat="server"
                        NavigateUrl="~/ForgotPassword.aspx">Click Here</asp:HyperLink>
                </td>
            </tr>
        </table>
    </asp:Panel>
    <br />
    <br />
    <asp:Label ID="ltrmsg" runat="server" ForeColor="Red" /></p>

login.asp.cs code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

public partial class Login : System.Web.UI.Page
{
    BAL bal = new BAL();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        try
        {
            if (txtUid.Text != null && txtpwd.Text != null)
            {
                if (bal.getUserLoginDetails(txtUid.Text, txtpwd.Text))
                {
                    FormsAuthentication.RedirectFromLoginPage(txtUid.Text, false);
                    Session["UserId"] = txtUid.Text;
                    Response.Redirect("~/User/Welcome.aspx");
                }              
                else
                    ltrmsg.Text = "Invalid Username (or) Password.";
            }
            else
                ltrmsg.Text = "Username & Password cann't be empty";
        }
        catch (Exception ex)
        {
            ltrmsg.Text = ex.Message;
        }
    }
}

BAL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
    DAL dal = new DAL();
    DataSet ds = new DataSet();

public BAL()
{
//
// TODO: Add constructor logic here
//
}

  public bool getUserLoginDetails(string Uid, string pwd)
    {
        try
        {
            string _sql = "Sp_UserLoginDetails";
            SqlParameter[] par = new SqlParameter[2];
            par[0] = new SqlParameter("@uid", Uid);
            par[1] = new SqlParameter("@pwd", pwd);
            if (dal.getLoginDetails(_sql, par))
                return true;
            else
                return false;
           // string _sql = "SELECT Username FROM TblUserRegistration where Username='" + Uid + "' AND Password='" + pwd + "'";
           // if (dal.getLoginDetails(_sql))
            //    return true;
          //  else
            //    return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  }
DAL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
   SqlConnection con;
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        SqlCommand cmd;
        string fname;

        public DAL()
        {
            con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["class"].ToString());
            fname = string.Empty;
        }

public bool getLoginDetails(string _sql, SqlParameter[] sqlparam)
        {
            try
            {
                string Uid;
                con.Open();
                cmd = new SqlCommand(_sql, con);
                cmd.CommandType = CommandType.StoredProcedure;

                foreach (SqlParameter p in sqlparam)
                {
                    cmd.Parameters.Add(p);
                }

                Uid = Convert.ToString(cmd.ExecuteScalar());
                if (Uid.Length > 0)
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
       }






15 May 2013

Difference between Primary Key & Unique Key



Primary Key:

i) Can be only one in a table
ii) It never allows null values
iii) Primary Key is unique key identifier and can not be null and must be unique.
iV) Primary key can be made foreign key into another table.
v) By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.

Unique Key:

i) Can be more than one unique key in one table.
ii) Unique key can have null values, accept only one null value.
iii) Unique key can be null and may not be unique.
iv) In SQL Server, Unique key can be made foreign key into another table.
v) By default, Unique key is a unique non-clustered index.


Define Primary key and Unique key

 CREATE TABLE Employee 
 (
 EmpID int PRIMARY KEY, --define primary key
 Name varchar (50) NOT NULL,
 MobileNo int UNIQUE, --define unique key
 Salary int NULL
 )