Friday, February 20, 2009

Show Header for GridView For NULL DataSource


We have to desing the gridview header in the Table and put it inside the
EmptyDataTemplate of the gridview as given below.


<asp:GridView ID="GridView2" runat="server" CssClass="th">
<EmptyDataTemplate>
<table>
<tbody>
<tr>
<td>
<b>Name</b></td>
</tr>
</tbody>
</table>
</EmptyDataTemplate>
</asp:GridView>


GridView Create THeader and TBody

protected void Page_Load(object sender, EventArgs e)
{
//Add data to the GridView
GridView1.DataSource = SQLHelper.ExecuteDataset("Data Source=SERVER;Initial
Catalog=DBName; Uid=sa; PWD=12345678; Connect Timeout=360; pooling=true;
Max PoolSize
=200; ", CommandType.Text, "Select * from TblName");
GridView1.DataBind();

MakeAccessible(GridView1);

}

private void MakeAccessible(GridView grid)
{
//HtmlTextWriterStyle style = new HtmlTextWriterStyle();
//TableRow tr = new TableRow();
////tr.Style.Add(HtmlTextWriterStyle
//tr.Style.Add(style ,
if (grid.Rows.Count > 0)
{
//This replaces with and adds the scope attribute
grid.UseAccessibleHeader = true;

//This will add the and elements
grid.HeaderRow.TableSection = TableRowSection.TableHeader;
//grid.HeaderStyle.AddAttributesToRender(


//This adds the element. Remove if you don't have a footer row
grid.FooterRow.TableSection = TableRowSection.TableFooter;
}
}


Another Way/

Form Authentication

Login Through Cookies
Detecting ASP.NET Session Timeouts

            
                
                
            
        

We have to set the value to the attribute path="/" in forms tag. Then only a common authentication works for both the browsers (Internet Explorer and Firefox.)
I.e. we logged in IE and open the page in Firefox it once again ask to logon. To over come this gives the path.

The place the cookies are stored in windows XP.
The default location for Internet Explorer
C:\Documents and Settings\\Cookies

If you set form authentication it give the user name that you gave in Login control other wise it took as windows authentication and gave windows user name.
string webUsername = HttpContext.Current.User.Identity.Name;

    protected void LoginAuthenticate(object sender, AuthenticateEventArgs e)
    {
        //if username and password given by the enduser is available in the
        //database then we can authenticate the user by providing

        e.Authenticated = true;
        AuthenticateUser("UserName");
    }

    protected void AuthenticateUser(string userName)
    {
        /*Providing the FormsAuthenticationTicket "Ticket" to the authenticated
        user which contains version, username, entry datetime and expire date time,
        userdata and cookie path*/
        FormsAuthentication.Initialize();
        FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket
        (1, userName.Trim(), DateTime.Now, DateTime.Now.AddMinutes(90),
        true, userName.Trim() + "," + Page.ClientID,
        FormsAuthentication.FormsCookiePath);

        //encrypt the ticket and assign it into the string variable "hash"
        string hash = FormsAuthentication.Encrypt(Ticket);

        /*FormsAuthentication.FormsCookieName --> This is the name
        that we gave in web.config file*/

        HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
        Response.Cookies.Clear();

        /*checking whether the cookie is constant,
        If constant then expires the cookie based on the expiration
        time of user specified in ticket
        */
        if (Ticket.IsPersistent)
        {
            Cookie.Expires = Ticket.Expiration;
            Response.Cookies.Add(Cookie);
        }
    }

    //When writing a cookie, use Response but reading may depend on your situation. 
    //Normally, you read from Request but if your application is attempting 
    //to get a cookie that has just been written or updated and the round trip 
    //to the browser has not occured, you may need to read it form Response.

    public void WriteCookie(string name, string value)
    {
        HttpCookie cookie = new HttpCookie(name, value);
        HttpContext.Current.Response.Cookies.Set(cookie);
    }

    public string ReadCookie(string name)
    {
        string[] CookiesKeys = HttpContext.Current.Response.Cookies.AllKeys;
        if (((IList)CookiesKeys).Contains(name))
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[name];
            if (cookie != null) return cookie[name];
        }

        CookiesKeys = HttpContext.Current.Request.Cookies.AllKeys;
        if (((IList)CookiesKeys).Contains(name))
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie != null) return cookie[name];
        }
        return null;
    }

    //Update Cookie 
    private void UpdateCookie()
    {
        // If the request cookie exists, copy it to the response.
        // Otherwise create a response cookie.
        HttpCookie cookie = Request.Cookies["theCookie"];
        if (cookie == null)
        {
            Response.Cookies.Set(new HttpCookie("theCookie", "SomeValue"));
        }
        else
        {
            Response.Cookies.Set(cookie);
            // Add the expiration date. 
            cookie.Expires = DateTime.Now.AddYears(30);
            // Change the cookie's value 
            cookie.Value = "NewValue";
        }
    }

    private string GetCurrentCookieValue()
    {
        string currentCookieValue = null;
        // Response.Cookies always has the latest values
        if (Request.Browser.Cookies)
        {
            HttpCookie cookie = Request.Cookies["theCookie"];
            if (cookie != null) currentCookieValue = cookie.Value;
        }
        return currentCookieValue;
    }

    protected void ibtnLogedOut_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Session.Clear();
        //Removes the FormsAuthentication ticket from the server
        FormsAuthentication.SignOut();

        #region Removers Cookie When User Log Off
        //Clear cookie when user Logout 
        Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
        #endregion

        ibtnLogin.Visible = true;
        ibtnLogOut.Visible = false;

        Response.Redirect("~/Home.aspx");
    }
Add the below code in Global.asax
    //Code that runs on application startup
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity FID = (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket Ticket = FID.Ticket;

                    //Get the stored user-data, in this case, Page Client ID and UserName
                    string userData = Ticket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(FID, roles);
                }
            }
        }
    }
Set the cookie expiration time by giving the session time out
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool isPersistent = this.Login1.RememberMeSet;
        string username = this.Login1.UserName;
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
            (
                1,//Version
                username,
                DateTime.Now,// issueDate
                GetExpirationTime(),// expiration
                isPersistent,// isPersistent
                Guid.NewGuid().ToString("N"), //roles or userData
                FormsAuthentication.FormsCookiePath // cookiePath
            );

        // Encrypt the ticket.
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        // Create the cookie.
        this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));

        Session["UserName"] = username;

        // Redirect back to original URL.
        this.Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
    }

    private DateTime GetExpirationTime()
    {
        double minutes = 0;
        TimeSpan obj;
        minutes = ((System.Web.Configuration.AuthenticationSection)System.Configuration.ConfigurationManager.GetSection("system.web/authentication")).Forms.Timeout.Minutes;
        obj = TimeSpan.FromMinutes(minutes);
        return DateTime.Now.AddMinutes(obj.Minutes);
    }
Note
//Clear cookie when user Logout 
Response.Cookies.Remove(FormsAuthentication.FormsCookieName); 
//Removes the FormsAuthentication ticket from the server 
FormsAuthentication.SignOut(); 
//Note If you set form authentication it give the user name that you gave in Login control. 
//other wise it took as windows authentication and gave windows user name 
//string webUsername = HttpContext.Current.User.Identity.Name; 
//==================================================================== 
//Get Windowns userName 
string str = Request.ServerVariables["LOGON_USER"];
Brute force protect your websites

SQL SERVER Table and Index Architecture

Table and Index Architecture

Friday, January 23, 2009

Events in Global.asax or Gloabl.asax Events

Original Page

Another Link

Exploring the Global.asax file in ASP.NET

Have you ever felt the need of writing logic at the application level;
precisely a location or a file where you could handle events or errors
at the application level? Well if yes, then enter the Global.asax. Using
this file, you can define event handlers with application-wide or
session-wide scope. In this article, we will explore the application
and session level events exposed in the Global.asax file and how we can
utilize these events in our applications.
The Global.asax, also known as the ASP.NET application file, is located in
the root directory of an ASP.NET application. This file contains code that
is executed in response to application-level and session-level events raised
by ASP.NET or by HTTP modules. You can also define ‘objects’ with
application-wide or session-wide scope in the Global.asax file.
These events and objects declared in the Global.asax are applied to
all resources in that web application.
Note 1: The Global.asax is an optional file. Use it only when there
is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected.
External users cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET.
You can deploy this file as an assembly in the \bin directory of an
ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 > Create a new website > Go to the
Solution Explorer > Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events.
The first set which gets invoked on each request and the second set
which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request

Application Request to trigger events in the following order:

1. Application_BeginRequest
2. Application_AuthenticateRequest
3. Application_AuthorizeRequest
4. Application_ResolveRequestCache
5. Application_AcquireRequestState
6. Application_PreRequestHandlerExecute
7. Application_PreSendRequestHeaders
8. Application_PreSendRequestContent
9. Application_PostRequestHandlerExecute
10. Application_ReleaseRequestState
11. Application_UpdateRequestCache
12. Application_EndRequest

Application_BeginRequest() – fired when a request for the
web application comes in.
Application_AuthenticateRequest –fired just before
the user credentials are authenticated. You can specify
your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful
authentication of user’s credentials. You can use this
method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful
completion of an authorization request.
Application_AcquireRequestState() – fired just before the
session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework
begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has
executed the request.
Application_ReleaseRequestState() – fired before current state data kept
in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to
output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from
the web server and the web application starts.
Session_Start() – fired when session starts on each new user
requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch
unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file
(Right click project > Add New Item > Global.asax).
In the Application_Error() method, add the following code:

C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();

}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ".

Error Message:" & objErr.Message.ToString()

End Sub
Here we make use of the Application_Error() method to capture the error

using the Server.GetLastError().
Conclusion:
In this article, we learnt that Global.asax is a file used to declare
application-level events and objects. The file is responsible for handling
higher-level application events such as Application_Start, Application_End,
Session_Start, Session_End, and so on. I would encourage you to explore the
methods corresponding to the events and analyze the best possible methods
to use them in your application, if needed.

Saturday, January 10, 2009

Error: Connection string already added



Server Error in '/BabuTest' Application.



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: The entry 'SiteSqlServer' has already been added.

Source Error:





Line 23:       providerName="System.Data.SqlClient" />-->
Line 24: <!-- Connection String for SQL Server 2000/2005-->
Line 25: <add name="ConnectionString" connectionString="Server=(local);
Database=babu
uid=sa;pwd=sa12345678;" providerName="System.Data.SqlClient"/>
Line 26: </connectionStrings>
Line 27: <appSettings>


Source File: c:\inetpub\wwwroot\dnntest\web.config Line: 25





Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42



This is the config error i get. Has anyone experienced this problem?



// Moderator edit to reduce scroll



How to solve the Issue

The common cause for the error is the connecting string name
name="ConnectionString" already is present in
the machine.config file.

It is default in the machine.config file.

The best way of giving the name of the connection string is
project Name + ConnString

Or if the problem still exists.

<connectionstrings>
<clear>
<!-- OR -->
<remove name="SiteSqlServer">
<add name="SiteSqlServer" connectionstring="..."
providername="System.Data.SqlClient"></add>
</connectionstrings>