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);
    }

Wednesday, July 9, 2014

Allow entering only numeric values using jquery in asp.net

Jquery


<script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8);                       //Backspace

        jQuery(document).ready(function () {
            $(".numeric").bind("keypress", function (e) {
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
                $(".intervalError").css("display", ret ? "none" : "inline");
                return ret;
            });
            $(".numeric").bind("paste", function (e) {
                return false;
            });
            $(".numeric").bind("drop", function (e) {
                return false;
            });
        });
    </script>

 .Aspx Web Form

//Textbox for Entering Age (allowing only numeric values to enter here)
 <div>
<asp:TextBox CssClass="numeric" ID="txtAge" runat="server" />
</div>





Tuesday, July 1, 2014

Reference CSS / Js Files in asp.net using ResolveUrl()

If you need to reference jQuery and jQueryUI your MasterPage <head> should look similar as the following:



<link href="<%# ResolveUrl("~/") %>css/custom-theme/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />

 <script src="<%# ResolveUrl("~/") %>Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
 <script src="<%# ResolveUrl("~/") %>Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>

Monday, June 23, 2014

Autoclose Message box in Window Forms C#


Helper Class:

public class AutoClosingMessageBox
    {
        System.Threading.Timer _timeoutTimer;
        string _caption;
        AutoClosingMessageBox(string text, string caption, int timeout)
        {
            _caption = caption;
            _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
                null, timeout, System.Threading.Timeout.Infinite);
            MessageBox.Show(text, caption);
        }
        public static void Show(string text, string caption, int timeout)
        {
            new AutoClosingMessageBox(text, caption, timeout);
        }
        void OnTimerElapsed(object state)
        {
            IntPtr mbWnd = FindWindow(null, _caption);
            if (mbWnd != IntPtr.Zero)
                SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            _timeoutTimer.Dispose();
        }
        const int WM_CLOSE = 0x0010;
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    }

Calling:

//Three parameters: Text to be shown, Caption and message timeout in milliseconds
AutoClosingMessageBox.Show("Message to be shown", "Caption", 5000);

Monday, June 2, 2014

Change Language in SQL

SQL Query


Set LANGUAGE Norwegian

Select Datename(month, getdate())


Output:


juni

Wednesday, May 21, 2014

Another way to remove the specific item From n-dimensional array using Jquery


//Array 
var elementsArray = [
        { name: 'First Element', id: 1},
        { name: 'Second Element', id: 2 },
        { name: 'Third Element', id: 3 },
       ];


//Jquery Function to remove the current object from the array
    function RemoveElementFromArray(array, id) {
        if (array != null && array.length > 0) {
            array = $.grep(array, function (value) {
                return value.id != id;
            });
            return array;
        }
        else {
            return null;
        }
    }


//Calling
function remove()
{
//For instance, we want to remove the 2nd element having ID 2

elementsArray  =  RemoveElementFromArray(elementsArray, 2);
for(int i=0; i<elementsArray.length; i++)
{
alert(elementsArray[i].name);
}
}