Thursday, 26 December 2013

Class in Javascript

3 ways to define a JavaScript class

September 29th, 2006. Tagged: JavaScript

Introduction

JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.
It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.

1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.
function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}
 
// anti-pattern! keep reading...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}
To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:
var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

1.1. Methods defined internally

In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:
function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}
Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

1.2. Methods added to the prototype

A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.
function Apple (type) {
    this.type = type;
    this.color = "red";
}
 
Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};
Again, you can use the new objects exactly the same way as in 1. and 1.1.

2. Using object literals

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:
var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}
In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
apple.color = "reddish";
alert(apple.getInfo());
Such an object is also sometimes called singleton. It "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.

3. Singleton using a function

Again with the singleton, eh? :)
The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:
var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}
So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.
apple.color = "reddish";
alert(apple.getInfo());
new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.

Tuesday, 24 December 2013

Views in Sql server

Different Types of SQL Server Views

Posted By : Shailendra Chauhan, 10 Mar 2011
Updated On : 18 Dec 2012
  Version Support : SQL Server 2005,2008,2012
Keywords : Types of Sql View pdf, Simple View, Complex View, Sql Server View, Modify View, Advantage of Views, Use of Views
Views are virtual tables that are compiled at run time. The data associated with views are not physically stored in the view, but it is stored in the base tables of the view. A view can be made over one or more database tables. Generally we put those columns in view that we need to retrieve/query again and again. Once you have created the view, you can query view like as table. We can make index, trigger on view.
In Sql Server we make views for security purpose since it restricts the user to view some columns/fields of the table(s). Views show only those columns that are present in the query which is used to make view.One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table.
Syntax for View
  1. CREATE VIEW view_name
  2. AS
  3. select_statement[]

Types of Views

In Sql Server we have two types of views.
  1. System Defined Views

    System defined Views are predefined Views that already exist in the Master database of Sql Server. These are also used as template Views for all newly created databases. These system Views will be automatically attached to any user defined database.

    We have following types of system defined views.
    1. Information Schema View

      In Sql Server we have twenty different schema views. These are used to display information of a database, like as tables and columns. This type of view starts with INFORMATION_SCHEMA and after this view name.
      1. --Create a table
      2. create table Employee_Test
      3. (
      4. Emp_ID int identity,
      5. Emp_Name varchar(55),
      6. Emp_Technology varchar(55),
      7. Emp_Sal decimal (10,2),
      8. Emp_Designation varchar(20)
      9. )
      10. --To view detailed information of the columns of table Employee_Test
      11. SELECT * FROM INFORMATION_SCHEMA.COLUMNS
      12. where TABLE_NAME='Employee_Test'
    2. Catalog View

      Catalog Views were introduced with SQL Server 2005. These are used to show database self describing information.
      1. select * from sys.tables
    3. Dynamic Management View

      Dynamic Management Views were introduced in SQL Server 2005. These Views give the administrator information of the database about the current state of the SQL Server machine. These values help the administrator to analyze problems and tune the server for optimal performance. These are of two types
      1. Server-scoped Dynamic Management View

        These are stored only in the Master database.
      2. Database-scoped Dynamic Management View

        These are stored in each database.
      1. --To see all SQL Server connections
      2. SELECT connection_id,session_id,client_net_address,auth_scheme
      3. FROM sys.dm_exec_connections
  2. User Defined Views

    These types of view are defined by users. We have two types of user defined views.
    1. Simple View

      When we create a view on a single table, it is called simple view.
      1. --Now Insert data to table Employee_Test
      2. Insert into Employee_Test values ('Amit','PHP',12000,'SE');
      3. Insert into Employee_Test values ('Mohan','ASP.NET',15000,'TL');
      4. Insert into Employee_Test values ('Avin','C#',14000,'SE');
      5. Insert into Employee_Test values ('Manoj','JAVA',22000,'SSE');
      6. Insert into Employee_Test values ('Riyaz','VB',18000,'TH');
      7. -- Now create view on single table Employee_Test
      8. create VIEW vw_Employee_Test
      9. AS
      10. Select Emp_ID ,Emp_Name ,Emp_Designation
      11. From Employee_Test
      1. -- Query view like as table
      2. Select * from vw_Employee_Test
      In simple view we can insert, update, delete data. We can only insert data in simple view if we have primary key and all not null fields in the view.
      1. -- Insert data to view vw_Employee_Test
      2. insert into vw_Employee_Test(Emp_Name, Emp_Designation) values ('Shailu','SSE')
      3. -- Now see the affected view
      4. Select * from vw_Employee_Test
      1. -- Update data to view vw_Employee_Test
      2. Update vw_Employee_Test set Emp_Name = 'Pawan' where Emp_ID = 6
      3. -- Now see the affected view
      4. Select * from vw_Employee_Test
      1. -- Delete data from view vw_Employee_Test
      2. delete from vw_Employee_Test where Emp_ID = 6
      3. -- Now see the affected view
      4. Select * from vw_Employee_Test
    2. Complex View

      When we create a view on more than one table, it is called complex view.
      1. --Create another table
      2. create table Personal_Info
      3. (
      4. Emp_Name varchar(55),
      5. FName varchar(55),
      6. DOB varchar(55),
      7. Address varchar(55),
      8. Mobile int,
      9. State varchar(55)
      10. )
      11. -- Now Insert data
      12. Insert into Personal_Info values ('G.Chaudary','22-10-1985','Ghaziabad',96548922,'UP');
      13. Insert into Personal_Info values ('B.S.Chauhan','02-07-1986','Haridwar',96548200,'UK');
      14. Insert into Personal_Info values ('A.Panwar','30-04-1987','Noida',97437821,'UP');
      15. Insert into Personal_Info values ('H.C.Patak','20-07-1986','Rampur',80109747,'UP');
      16. Insert into Personal_Info values ('M.Shekh','21-10-1985','Delhi',96547954,'Delhi');
      17. -- Now create view on two tables Employee_Test and Personal_Info
      18. Create VIEW vw_Employee_Personal_Info
      19. As
      20. Select e.Emp_ID, e.Emp_Name,e.Emp_Designation,p.DOB,p.Mobile
      21. From Employee_Test e INNER JOIN Personal_Info p
      22. On e.Emp_Name = p. Emp_Name
      1. -- Now Query view like as table
      2. Select * from vw_Employee_Personal_Info
      We can only update data in complex view.We can't insert,update data in complex view.
      1. --Update view
      2. update vw_Employee_Personal_Info set Emp_Designation = 'SSE' where Emp_ID = 3
      3. -- See affected view
      4. Select * from vw_Employee_Personal_Info

Note

  1. We make views for security purpose since it restricts the user to view some columns/fields of the table(s).
  2. One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table
Summary
In this article I try to explain the view in sql server with example. I hope after reading this article your sql views concepts will be strong. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Friday, 22 November 2013

Asp.net Page life cycle

Introduction

In this article, we will try to understand what the different events are which take place right from the time the user sends a request, until the time the request is rendered on the browser. So we will first try to understand the two broader steps of an ASP.NET request and then we will move into different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page object. As we move in this event journey, we will try to understand what kind of logic should go in each and every one of these events.
This is a small Ebook for all my .NET friends which covers topics like WCF, WPF, WWF, Ajax, Core .NET, SQL, etc. You can download the same from here or else you can catch me on my daily free training here.

The Two Step Process

From 30,000 feet level, ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:
  • ASP.NET creates an environment which can process the request. In other words, it creates the application object, request, response and context objects to process the request.
  • Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let's name this step as MHPM (Module, handler, page and Module event), we will come to details later.

In the coming sections, we will understand both these main steps in more detail.

Creation of ASP.NET Environment

Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.
Note: For more details, read this.

The below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.

Process Request using MHPM Events Fired

Once ‘HttpApplication’ is created, it starts processing requests. It goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections, it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead, let's understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:
  • If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.
  • If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.
You can read more about the differences from here.
Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below:

Step 1(M: HttpModule): Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET HttpModule emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.

Step 2 (H: ‘HttpHandler’): Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project.

Step 3 (P: ASP.NET page): Once the HttpHandler logic executes, the ASP.NET page object is created. While the ASP.NET page object is created, many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages Init, Load, validate, event, render and unload. You can remember the word SILVER to remember the events S – Start (does not signify anything as such just forms the word) , I – (Init) , L (Load) , V (Validate), E (Event) and R (Render).

Step4 (M: HttpModule): Once the page object is executed and unloaded from memory, HttpModule provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
The below figure shows the same in a pictorial format.

In What Event Should We Do What?

The million dollar question is in which events should we do what? Below is the table which shows in which event what kind of logic or code can go.
Section Event Description
HttpModule BeginRequest This event signals a new request; it is guaranteed to be raised on each request.
HttpModule AuthenticateRequest This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule AuthorizeRequest This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule ResolveRequestCache In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.
HttpModule AcquireRequestState This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule PreRequestHandlerExecute This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler ProcessRequest Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
Page Init This event happens in the ASP.NET page and can be used for:
  • Creating controls dynamically, in case you have controls to be created on runtime.
  • Any setting initialization.
  • Master pages and the settings.
In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.
Page Load In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page Validate If you have valuators on your page, you would like to check the same here.

Render It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Page Unload Page object is unloaded from the memory.
HttpModule PostRequestHandlerExecute Any logic you would like to inject after the handlers are executed.
HttpModule ReleaserequestState If you would like to save update some state variables like session variables.
HttpModule UpdateRequestCache Before you end, if you want to update your cache.
HttpModule EndRequest This is the last stage before your output is sent to the client browser.

A Sample Code for Demonstration

With this article, we have attached a sample code which shows how the events actually fire. In this code, we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events, below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all events and adds it to a global collection.
public class clsHttpModule : IHttpModule
{
...... 
void OnUpdateRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnUpdateRequestCache");
}
void OnReleaseRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnReleaseRequestState");
}
void OnPostRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPostRequestHandlerExecute");
}
void OnPreRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPreRequestHandlerExecute");
}
void OnAcquireRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAcquireRequestState");
}
void OnResolveRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnResolveRequestCache");
}
void OnAuthorization(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAuthorization");
}
void OnAuthentication(object sender, EventArgs a)
{

objArrayList.Add("httpModule:AuthenticateRequest");
}
void OnBeginrequest(object sender, EventArgs a)
{

objArrayList.Add("httpModule:BeginRequest");
}
void OnEndRequest(object sender, EventArgs a)
{
objArrayList.Add("httpModule:EndRequest");
objArrayList.Add("<hr>");
foreach (string str in objArrayList)
{
httpApp.Context.Response.Write(str + "<br>") ;
}
} 
}
Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.
public class clsHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");
context.Response.Redirect("Default.aspx");
}
}
We are also tracking all the events from the ASP.NET page.
public partial class _Default : System.Web.UI.Page 
{
protected void Page_init(object sender, EventArgs e)
{

clsHttpModule.objArrayList.Add("Page:Init");
}
protected void Page_Load(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Load");
}
public override void Validate() 
{
clsHttpModule.objArrayList.Add("Page:Validate");
}
protected void Button1_Click(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Event");
}
protected override void Render(HtmlTextWriter output) 
{
clsHttpModule.objArrayList.Add("Page:Render");
base.Render(output);
}
protected void Page_Unload(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:UnLoad");
}}
Below is how the display looks like with all events as per the sequence discussed in the previous section.

Zooming ASP.NET Page Events

In the above section, we have seen the overall flow of events for an ASP.NET page request. One of the most important sections is the ASP.NET page, we have not discussed the same in detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this section.
Any ASP.NET page has 2 parts, one is the page which is displayed on the browser which has HTML tags, hidden values in form of viewstate and data on the HTML inputs. When the page is posted, these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code, you can execute and write your own login on the same and render the page back to the browser.

Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform, we need to put this logic appropriately in those events.
Note: Most of the developers directly use the page_load method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes, etc., everything happens on the page load. So if we can put logic in proper events as per the nature of the logic, that would really make your code clean.
Seq Events Controls Initialized View state
Available
Form data
Available
What Logic can be written here?
1 Init No No No Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.
2 Load view state Not guaranteed Yes Not guaranteed You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3 PostBackdata Not guaranteed Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4 Load Yes Yes Yes This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.
5 Validate Yes Yes Yes If your page has validators or you want to execute validation for your page, this is the right place to the same.
6 Event Yes Yes Yes If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7 Pre-render Yes Yes Yes If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8 Save view state Yes Yes Yes Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.
10 Unload Yes Yes Yes Any kind of clean up you would like to do here.

Wednesday, 20 November 2013

Scheduled Tasks in ASP.NET



Scheduled Tasks in ASP.NET
Very often, there is a need to execute some code on certain date and time, or to repeat execution in regular time intervals. In case of ASP.NET web application, that could be sending of reminder e-mails, analyze traffic data, creating reports, maintenance tasks etc. ASP.NET doesn't provide some straightforward way to schedule tasks. Also, only what HTTP protocol can do is to return some output as a response after receives web request.
 

Fortunately, there are numerous solutions to solve this problem. Scheduled tasks methods could be divided in two groups:
- Pure ASP.NET methods, like using of timer, cache expiration or threads,
- Using of external application, like Windows Task Scheduler, Windows service, web hosting automation program etc.
In this tutorial, I will show three ways to simulate scheduled tasks using ASP.NET only. To learn more about options for scheduled tasks in ASP.NET using external application see Task Scheduler or Windows service in ASP.NET tutorial.
ASP.NET only methods are often an option if you have shared hosting, but they have some drawbacks.
Scheduled tasks using threading
Solution that uses threads is very simple. We'll use Application_Start procedure in Global.asax to initially start task. Then, in separate thread we'll call task again in regular time intervals. Code in Global.asax could look like this:
[ C# ]
<%@ Application Language="C#" %>
<%-- We need this namespace to work with threads --%>
<%@ Import Namespace="System.Threading" %>
  
   <script runat="server">
  
  
   void Application_Start(object sender, EventArgs e)
   {
   // On application start, create an start separate thread
   ThreadStart tsTask = new ThreadStart(TaskLoop);
   Thread MyTask = new Thread(tsTask);
   MyTask.Start();
  
   }
  
   static void TaskLoop()
   {
   // In this example, task will repeat in infinite loop
   // You can additional parameter if you want to have an option
   // to stop the task from some page
   while (true)
   {
   // Execute scheduled task
   ScheduledTask();
  
   // Wait for certain time interval
   System.Threading.Thread.Sleep(TimeSpan.FromHours(12));
   }
   }
  
   static void ScheduledTask()
   {
   // Task code which is executed periodically
  
   }
   </script>
[ VB.NET ]
<%@ Application Language="VB" %>
<%-- We need this namespace to work with threads --%>
<%@ Import Namespace="System.Threading" %>
<script runat="server">
  
   Protected Sub Application_Start(ByVal sender As Object, ByVal e As System.EventArgs)
   ' On application start, create an start separate thread
   Dim tsTask As ThreadStart = New ThreadStart(AddressOf TaskLoop)
   Dim MyTask As Thread = New Thread(tsTask)
   MyTask.Start()
   End Sub
  
   Shared Sub TaskLoop()
   ' In this example, task will repeat in infinite loop
   ' You can additional parameter if you want to have an option
   ' to stop the task from some page
   While (True)
  
   ' Execute scheduled task
   ScheduledTask()
  
   ' Wait for certain time interval
   System.Threading.Thread.Sleep(TimeSpan.FromHours(12))
   End While
   End Sub
  
   Shared Sub ScheduledTask()
   ' Task code which is executed periodically
  
   End Sub
 </script>
Scheduled tasks using timers
Very simple solution to perform scheduled tasks is by using timer. Again, we'll use Global.asax and Application_Start procedure. In Application_Start we'll create a Timer and use Elapsed event to execute task in regular time intervals. To make it so, write this code in Global.asax file:
[ C# ]
<%@ Application Language="C#" %>
  
   <script runat="server">
  
   // Code that runs on application startup
   void Application_Start(object sender, EventArgs e)
   {
   // Dynamically create new timer
   System.Timers.Timer timScheduledTask = new System.Timers.Timer();
  
   // Timer interval is set in miliseconds,
   // In this case, we'll run a task every minute
   timScheduledTask.Interval = 60 * 1000;
  
   timScheduledTask.Enabled = true;
  
   // Add handler for Elapsed event
   timScheduledTask.Elapsed +=
   new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
   }
  
   void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
   {
   // Execute some task
   FirstTask();
   }
  
   void FirstTask()
   {
   // Here is the code we need to execute periodically
  
   }
   </script>
[ VB.NET ]
<%@ Application Language="VB" %>
  
   <script runat="server">
   Protected Sub Application_Start(ByVal sender As Object, ByVal e As System.EventArgs)
   ' Dynamically create new timer
   Dim timScheduledTask As System.Timers.Timer = New System.Timers.Timer()
  
   ' Timer interval is set in miliseconds,
   ' In this case, we'll run a task every minute
   timScheduledTask.Interval = 60 * 1000
  
   timScheduledTask.Enabled = True
  
   ' Add handler for Elapsed event
   AddHandler timScheduledTask.Elapsed, AddressOf timScheduledTask_Elapsed Â
   End Sub
  
   Sub timScheduledTask_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
   ' Execute some task
   FirstTask()
   End Sub
  
   Sub FirstTask()
   ' Here is the code we need to execute periodically
  
   End Sub
   </script>
This solution looks very simple and neat, at least theoretically. In practice, timer is often unstable when used in web application. It is common that timer stops after 20-30 minutes, especially on shared hosting where hosting provider tries to save resources and recycle web application.
Scheduled tasks using cache expiration as a trigger
ASP.NET Cache expiration is one more method you can use to create scheduled tasks. In this method, it is not important what you put in the cache. In this example I added short string "1", but could be anything. Useful for scheduled tasks is the fact that cache expires after specified time interval and then executes selected function (scheduled task).
Here is example of Global.asax file that uses cache expiration to schedule tasks in ASP.NET application. First, Application_Start method calls ScheduleTask procedure that uses cache expiration to schedule when task will be executed. In this example, cache willl expire after one hour. Then, after cache expired, SetTimer() is called. SetTimer function calls DoTask() method which represents code of scheduled task, and also calls again ScheduleTask() function to plan next task execution.
[ C# ]
<%@ Application Language="C#" %>
  
   <script runat="server">
   void Application_Start(object sender, EventArgs e)
   {
   // Schedule task for the first time
   ScheduleTask();
   }
  
   static void ScheduleTask()
   {
   HttpRuntime.Cache.Add(
   // String that represents the name of the cache item,
   // could be any string
   "ScheduledTask",
   // Something to store in the cache
   "1",
   // No cache dependencies
   null,
   // Will not use absolute cache expiration
   Cache.NoAbsoluteExpiration,
   // Cache will expire after one hour
   // You can change this time interval according
   // to your requriements
   TimeSpan.FromHours(1),
   // Cache will not be removed before expired
   CacheItemPriority.NotRemovable,
   // SetTimer function will be called when cache expire
   new CacheItemRemovedCallback(SetTimer));
   }
  
   // This function si called when cache is expired
   static void SetTimer(string key, Object value, CacheItemRemovedReason reason)
   {
   // Call the task function
   DoTask();
   // Schedule new execution time
   ScheduleTask();
   }
  
   static void DoTask()
   {
   // Task code which is executed periodically
   // In this example, code will be executed every hour
   }
   </script>
[ VB.NET ]
<%@ Application Language="VB" %>
   <script runat="server">
   Protected Sub Application_Start(ByVal sender As Object, ByVal e As System.EventArgs)
   ' Schedule task for the first time
   ScheduleTask()
   End Sub
  
   Shared Sub ScheduleTask()
   ' Cache will expire after one hour
   ' You can change this time interval according
   ' to your requriements
   ' SetTimer function will be called when cache expire
   HttpRuntime.Cache.Add( _
   "ScheduledTask", _
   "1", _
   Nothing, _
   Cache.NoAbsoluteExpiration, _
   TimeSpan.FromHours(1), _
   CacheItemPriority.NotRemovable, _
   New CacheItemRemovedCallback(AddressOf SetTimer))
   End Sub
  
   ' This function si called when cache is expired
   Shared Sub SetTimer(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)
   ' Call the task function
   DoTask()
   ' Schedule new execution time
   ScheduleTask()
   End Sub
  
   Shared Sub DoTask()
   ' Task code which is executed periodically
   ' In this example, code will be executed every hour
   End Sub
   </script>
Conclusion
Scheduled task could be running of Windows application, script, web page, sending email etc. The problem with pure ASP.NET methods could be insufficient rights, since ASP.NET by default runs as NETWORK SERVICE or ASPNET account which are very limited.
Also, ASP.NET application could restart or even stop work because of numerous reasons. If ASP.NET application stops, scheduled tasks are not executed. If there is nobody on website (no web requests), server could stop application after short time. The possible workaround could be to keep web application alive using scheduled task that will use WebClient class to periodically (e.g. every ten minutes) make web requests to some page.
This doesn't help if ASP.NET application restarts. If task is time critical, consider more reliable options that use external application in Task Scheduler or Windows service in ASP.NET tutorial.
Using of external application is also recommended if you have long and heavy tasks that could hurt web application's performances. If visitors' experience will be bad because of some scheduled task, remove it from web application. In case that you are not able to use Windows service or Task Scheduler because your website is hosted on shared hosting, try to split long and heavy task into multiple short steps.
-------------------------------------------------------------------------------------------------------
Global.asax:-
 public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

            //if (HttpRuntime.Cache["CurrentDate"] != null && Convert.ToString(HttpRuntime.Cache["CurrentDate"]) == DateTime.Now.ToString("ddMMyyyy"))
            //    return;
            //else
            //{

            //    HttpRuntime.Cache["CurrentDate"] = DateTime.Now.ToString("ddMMyyyy");
            //}
            ScheduleTask();

        }

        static void ScheduleTask()
        {
            HttpRuntime.Cache.Add(
                // String that represents the name of the cache item,
                // could be any string
            "ScheduledTask",
                // Something to store in the cache
            "1",
                // No cache dependencies
            null,
                // Will not use absolute cache expiration
            Cache.NoAbsoluteExpiration,
                // Cache will expire after one hour
                // You can change this time interval according
                // to your requriements
            TimeSpan.FromMinutes(1),
                // Cache will not be removed before expired
            CacheItemPriority.NotRemovable,
                // SetTimer function will be called when cache expire
            new CacheItemRemovedCallback(SetTimer));
        }

        // This function si called when cache is expired
        static void SetTimer(string key, Object value, CacheItemRemovedReason reason)
        {
            // Call the task function
            DoTask();
            // Schedule new execution time
            ScheduleTask();
        }

        static void DoTask()
        {
            // Task code which is executed periodically
            // In this example, code will be executed every hour
            try
            {
                Notification notification = new Notification();
                List<BenefitStatus> dailyalertlst = notification.pendingBenefitStatuslst;
                List<BenefitStatus> lst = notification.pendingBenefitlst;
                List<ApprovedCampus> expireuserlst = notification.expireuserlst;
            }
            catch (Exception ex)
            { }
        }

        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

        }

        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.

        }

    }
-------------------------------------------------------------------------------------------------------
 public class Notification
    {
        /// <summary>
        /// Daily Alert
        /// </summary>
        public List<BenefitStatus> pendingBenefitStatuslst=new List<BenefitStatus>();
        /// <summary>
        /// Send Alert to every 15 Days from start date
        /// </summary>
        public List<BenefitStatus> pendingBenefitlst=new List<BenefitStatus>();
        /// <summary>
        /// Send Alert for User Expiry Notification
        /// </summary>
        public List<ApprovedCampus> expireuserlst = new List<ApprovedCampus>();


        public Notification()
        {           
            GetPendingBenefitlst();
            GetExpiryCampuslst();
        }

        private void GetExpiryCampuslst()
        {
            ApprovedCampus objApprovedCampus = new ApprovedCampus();
            List<ApprovedCampus> campuslst = objApprovedCampus.GetExpireUser();
            ApprovedCampus campus = null;
            foreach (var lst in campuslst)
            {
                Int16 datediff = Convert.ToInt16((lst.EndDate - DateTime.Now).TotalDays);
                //if (datediff =15)
                //{
                //    campus = new ApprovedCampus();
                //    campus.CampusName = lst.CampusName;
                //    campus.CampusID = lst.CampusID;
                //    expireuserlst.Add(campus);
                //}
            }
        }      

        private void GetPendingBenefitlst()
        {

            BenefitStatus objBenefitStatus = new BenefitStatus();
            List<BenefitStatus> benefitstatuslst = objBenefitStatus.GetBenefitStatus();
           // ApprovedCampus objApprovedCampus = new ApprovedCampus();
            BenefitStatus benefit = null;
                foreach (var lst in benefitstatuslst)
                {
                   
                    Int16 datediff =Convert.ToInt16( (lst.ExpiryDate - DateTime.Now).TotalDays);
                    //if Send Alert email after 4 week
                    if (lst.StartDate.AddDays(28) == DateTime.Now)
                    {
                        benefit = new BenefitStatus();
                        benefit.CampusName = lst.CampusName;
                        benefit.BenefitName = lst.BenefitName;
                        pendingBenefitStatuslst.Add(benefit);
                    }
                        //
                    else if (datediff == lst.NotificationDate)
                    {
                        benefit = new BenefitStatus();
                        benefit.CampusName = lst.CampusName;
                        benefit.BenefitName = lst.BenefitName;
                        pendingBenefitStatuslst.Add(benefit);
                    }
                        //if Send Alert email Frequency Before SLA expiration Date

                    else if (datediff < lst.NotificationDate)
                    {
                        //Check frequency to send Alert email, Daily or once after NotificationDate
                        if (lst.IsRepeated)
                        {
                            benefit = new BenefitStatus();
                            benefit.CampusName = lst.CampusName;
                            benefit.BenefitName = lst.BenefitName;
                            pendingBenefitStatuslst.Add(benefit);
                        }
                    }
                    //Send Alert email to every 15 Days from start date
                    else if (lst.StartDate.AddDays(15) == DateTime.Now)
                    {
                        benefit = new BenefitStatus();
                        benefit.CampusName = lst.CampusName;
                        benefit.BenefitName = lst.BenefitName;
                        pendingBenefitlst.Add(benefit);
                    }               
                }            
        }      
    }
-------------------------------------------------------------------------------------------------------
 public class BenefitStatus
    {
        public int CampusID { get; set; }     
        public int BenefitID { get; set; }
        public string BenefitName { get; set; }
        public string CampusName { get; set; }
        public bool IsDelivered { get; set; }
        public bool IsInProcess { get; set; }
        public bool IsPending { get; set; }
        public int NotificationDate { get; set; }
        public bool IsRepeated { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime ExpiryDate { get; set; }

        public List<BenefitStatus> GetBenefitStatus()
        {
            string Bstatus = string.Empty;
            List<BenefitStatus> BenefitStatuslst = new List<BenefitStatus>() {
                new BenefitStatus{CampusID=1,BenefitID=1,CampusName="ABC1",BenefitName="XYZ1",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(2),NotificationDate=2, IsRepeated=true},
                new BenefitStatus{CampusID=2,BenefitID=2,CampusName="ABC2",BenefitName="XYZ2",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(2),NotificationDate=5, IsRepeated=true },
                 new BenefitStatus{CampusID=3,BenefitID=3,CampusName="ABC3",BenefitName="XYZ3",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(2),NotificationDate=5, IsRepeated=true},
                new BenefitStatus{CampusID=4,BenefitID=4,CampusName="ABC4",BenefitName="XYZ4",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(2),NotificationDate=5, IsRepeated=true },               
                new BenefitStatus{CampusID=5,BenefitID=5,CampusName="ABC5",BenefitName="XYZ5",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(2),NotificationDate=5, IsRepeated=true},
                new BenefitStatus{CampusID=6,BenefitID=6,CampusName="ABC6",BenefitName="XYZ6",IsDelivered=false,IsInProcess=false,IsPending=false,StartDate=DateTime.Now, ExpiryDate=DateTime.Now.AddDays(5),NotificationDate=5, IsRepeated=false }};


            return BenefitStatuslst;
        }
    }