Monday, August 18, 2014

Simple Task Scheduling in asp.net website in Global.asax file

Global.asax.cs

private static DateTime taskLastRun;

void Application_Start(object sender, EventArgs e)
{
    taskLastRun= DateTime.Now;
}
 
void Session_Start(object sender, EventArgs e)
{
  DoTask();
}

/*Private method implemented in Global.asax file.
* Example Task to run every time application runs
* In this, it will delete the one day old files stored in uploads directory. 
*/

static void DoTask()
{
  var aDayAgo = DateTime.Now.AddDays(-1);
  if (taskLastRun.IsGreaterThan(aDayAgo))
  {
    var path = HttpContext.Current.Server.MapPath("Uploads");
    var folder = new DirectoryInfo(path);
    FileInfo[] files = folder.GetFiles();
    foreach (var file in files)
    {
      if(file.CreationTime.IsOlderThan(aDayAgo))
      {
        File.Delete(path + file.Name);
      }
    }
    taskLastRun= DateTime.Now;
  }
}
 
//Extension method to compare two dates 
public static bool IsGreaterThan(this DateTime dt1, DateTime dt2)
{
  return dt1 < dt2;
} 

Thursday, August 14, 2014

Check if page is PostBack in asp.net at the client side using Jquery

 

Design:

 
<script type="text/javascript">
    $(document).ready(function () { 
    //Check here if Page is postback and fire events accordingly.
    if (isPostBack){ 
 
     }
});  
</script>
 

Code Behind:


    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack",
                                                   IsPostBack ? "var isPostBack = true;" : "var isPostBack = false;",
                                                   true);
    }