Thursday, August 27, 2015

How to add a Global.asax.cs to a website

Global.asax is the asp.net application file. It is an optional file that handles events raised by ASP.NET or by HttpModules. It is used to handle server aoplication-level and session-level events.Fo example, used for application and session start/end events and for global error handling. When used, it should be in the root of the website. Only one Global.asax can be found in any project/website.

When creating a web application project, you have a Global.asax and its corresponding Global.asax.cs. However, in a web application the class (Global.asax.cs) cannot be created.

The created Global.asax starts with
<%@ Application  Language="C#" %>
And looks like the following image

To add Global.asax.cs
Choose your solution=> Add => Class
Save it as Global.asax.cs,
It must be saved in App_Code to be compiled correctly.

Even if you didn't save it to App_code, you will get the following warning:


Next cut code (without the tags, just c# code) from Global.asax and paste it to Global.asax.cs, as follows:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       
    }
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occur
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started.
    }
}

And in Global.asax leave only this line:
<%@ Application Codebehind="Global.asax.cs" Inherits="Global" Language="C#" %>


Thanks,
Nerdy Geeky J!

Server Time Vs. Local Time

I had this problem that my web applications were hosted in a server abroad. This meant  time zone difference.  I needed to save the data with an absolute value and when displaying it, I display it according to client preferences.

To do this I saved the DateTime value in UTC standard  (Coordinated Universal Time). More about it here
As in the following code in C#  :

                                DateTime timeUtc = System.DateTime.UtcNow;
        
When retrieving data, i converted the DateTime value into the desired TimeZone as follows: 


TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
        DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);



Thanks,
Nerdy Geeky J!