Async in c# (.Net Framework)

Here I am presenting the idea about time efficient execution.

Two methods are declared as ‘async’

First method requires 5 seconds time to finish execution, another one requires 8 seconds.

Two cases i have covered here with two button click events. First approach takes longer time(with await keyword) while second one finishes quickly as separate tasks defined hence their thread DOES NOT BLOCK main thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading.Tasks;

public partial class RnD_AsyncIdea : System.Web.UI.Page
{
public string Result = “”;

protected void Page_Load(object sender, EventArgs e)
{

}

//Time Required=5 Seconds work
private async Task DoSubTask1()
{
    await Task.Delay(5000);
    Result += "<br/>" + DateTime.Now + "|" + "task1 done.";
}

//Time Required=8 Seconds work
private async Task DoSubTask2()
{
    await Task.Delay(8000);
    Result += "<br/>" + DateTime.Now + "|" + "task2 done...";
}

//CASE-1
//Job finishing in same order its called
//TOATL TIME=5+5+8=18 
protected async void btnCase1_Click(object sender, EventArgs e)
{
    Result += "<br/>" + DateTime.Now + "|" + "Starting Main Job";
    await DoSubTask1();     //await keywork will hold on execution untill method finished
    await DoSubTask2();
    await DoSubTask1();
    Result += "<br/>" + DateTime.Now + "|" + "Finished Main Job";
    Response.Write(Result);

    /*
    07/07/2023 13:43:07|Starting Main Job
    07/07/2023 13:43:13|task1 done.
    07/07/2023 13:43:21|task2 done...
    07/07/2023 13:43:26|task1 done.
    07/07/2023 13:43:26|Finished Main Job 
    */
}

//CASE-2
//Job finishing in 
//TOATL TIME=8 only
protected async void btnCase2_Click(object sender, EventArgs e)
{
    Result += "<br/>" + DateTime.Now + "|" + "Starting Main Job";

    Task task1 = DoSubTask1();      //NO await, so cursor will move ahead
    Task task2 = DoSubTask2();
    Task task3 = DoSubTask1();

    await Task.WhenAll(task1, task2, task3);

    Result += "<br/>" + DateTime.Now + "|" + "Finished Main Job";
    Response.Write(Result);

    /*
    07/07/2023 13:44:10|Starting Main Job
    07/07/2023 13:44:15|task1 done.
    07/07/2023 13:44:15|task1 done.
    07/07/2023 13:44:18|task2 done...
    07/07/2023 13:44:18|Finished Main Job 
    */
}

}

Delegate in asp dotnet csharp, with simple example

In asp.net csharp, delegates allow programmer to create a variable that ‘points’ to a method.

We know that variables STORES VALUES, similar way deligates STORES POINTER TO METOD.

So we can dynamically or at various time SET DELIGATE in a way that our CALL actually invokes different method.

First step when using a delegate is to define its signature.

So when we use(or point) a delegate variable, we can point only to a method that matches its specific signature.

//declare deligate signature
public delegate int myCustomDeligate(int v1, int v2);

protected void Page_Load(object sender, EventArgs e)
{
//deligate variable created
myCustomDeligate objPointerToMethod;

objPointerToMethod = AddNumber;
Response.Write(“At time 1 result is=” + objPointerToMethod(3,5) + “<br/>”);

objPointerToMethod = AddNumberV2;    //this is interesting our variable now pointing to second method
Response.Write(“At time 2 result is=” +objPointerToMethod(3, 5) + “<br/>”);

}

//one method
public int AddNumber(int a1, int a2)
{
return a1 + a2;
}

//second method with same signature,but some other logic here
public int AddNumberV2(int b1, int b2)
{
return b1 + b2 + 10;    //here adding numbers, and adding 10 also to it
}

Simplest way to calculate first and last day of month and week for specific date in MS Sql Server

I have come up with following few lines that illustrate a way to find first and last day(date) for specified date.

And then given same thing for week.

Declare @SpecifiedDate DateTime;
Set @SpecifiedDate=GETDATE();
Declare @XStart int;
Set @XStart=0;

SELECT @XStart=DATEDIFF(mm,0,@SpecifiedDate)
SELECT DATEADD(mm,@XStart,0) ‘First Day of Specific Month’
SELECT DATEADD(d,-1,DATEADD(mm,@XStart+1,0)) ‘Last Day of Specific Month’

SELECT DATEADD(wk,DATEDIFF(wk,0,@SpecifiedDate ),0) ‘First Day of Week’
SELECT DATEADD(wk,DATEDIFF(wk,0,@SpecifiedDate ),6) ‘Last Day of Week’

Visual Studio 2008 intellisense not working <asp: or stops working for aspx page code view

I just realize importance of ‘intellisense’, as before 2 days visual studio 2008 version, got some issue and when i type TAG for example <asp: , i was not getting immediate menu with suggestion to finish line.

I tried with, Restarting studio and even from Visual Studio Command prompt tried executing command

devenv /ResetSettings

but not got sllution, then from http://forums.asp.net/t/1205528.aspx

seen one comment that states that we can clear all files from following two path:

C:\Documents and Settings\<username>\Application Data\Microsoft\VisualStudio\9.0\ReflectedSchemas

C:\Documents and Settings\<username>\Application Data\Microsoft\VisualStudio\9.0\ReflectedTypeLibs

and my Problem Gone. All kind of suggestions are working now in aspx file.

Use of CASE END in ms sql query to get conditional result column.

When we need some conditional output in sql script or query, below syntax will help to achieve.

SELECT Field1,Field2
(CASE
WHEN  exists(select top 1 Some_Field from Some_Table where [Condition])
THEN ‘OutputA’
ELSE ‘OutputB’
END) as ”AliasName”
From Table1

 

Read more,
https://siddharthboraniait.wordpress.com/2012/05/03/display-sql-server-messageusing-infomessage-event-from-sql-server-to-troubleshoot-stored-procedure

Return json format data from code behind of asp.net csharp

Review following code snippet to retrive json data in c#.

String strResult = “”;
strResult += “{‘xproducts’: “;
strResult += “[“;
if (dtable.Rows.Count > 0)
{
for (int i = 0; i < dtable.Rows.Count; i++)
{
strResult += “{ “;
strResult += “‘xid’:'” + dtable.Rows[i][“Id”].ToString() + “‘, “;
strResult += “‘xname’:'” + dtable.Rows[i][“Name”].ToString() + “‘, “;
strResult += “‘xprice’:'” + dtable.Rows[i][“Price”].ToString() + “‘, “;
strResult += “} “;
if (i != dtable.Rows.Count – 1)
{ strResult += “,”; }
}

}
strResult += “]”;
strResult += “}”;

context.Response.ContentType = “text/html”;
context.Response.Write(strResult);

 

Other Post for javascript:

https://siddharthboraniait.wordpress.com/2013/09/11/show-current-date-using-javascript-in-web-browserclient-side-date-in-web-browser/

Show current date using Javascript in web browser(Client side date in web browser)

For client side scripting,

Go through following lines to product date in DD/MM/YYYY format:

var objToday = new Date();
var dd = objToday.getDate();
var mm = objToday.getMonth() + 1;  //January is 0
var yyyy = objToday.getFullYear();

if (dd < 10) { dd = ‘0’ + dd }
if (mm < 10) { mm = ‘0’ + mm }

var strToday = dd + ‘/’ + mm + ‘/’ + yyyy;

alert(strToday);       // will show like ’17/07/2013′

How to make custom Task Scheduler in asp.net c# using thread

In asp.net there are needs for performing few activities periodically. For that  we can use some class libraries or third party component to schedule a task or function to execute periodically.

Recently i found following simplest way to execute periodically any code.

Suppose you have  a class and routine as follow in App_Code/CS,

public class ClassABC
{
public static void SomeFunctionToRunPeriodically()
{
try
{
System.IO.File.WriteAllText(System.Web.Hosting.HostingEnvironment.MapPath(“~/LatestRunSaved.txt”), “Last Run of function at : ” + DateTime.Now.ToString() + Environment.NewLine);
}
catch (Exception ex)
{
string t = ex.Message;
}
System.Threading.Thread.Sleep(20000);
SomeFunctionToRunPeriodically();    //calling self after interval

}
public ClassABC()
{
//
// TODO: Add constructor logic here
//
}
}

If you notice in above function then its calling to itself after interval.

Now in global application file ‘global.asax’  inside application start event use following lines to create a new thread based call to a function above.

void Application_Start(object sender, EventArgs e)
{
System.Threading.Thread obj = new System.Threading.Thread(new System.Threading.ThreadStart(ClassABC.SomeFunctionToRunPeriodically));
obj.Name = “AnyTestName”;
obj.IsBackground = true;
obj.Start();
}

New thread based function call will run until your application is running in IIS process, It is a background process. Other routine things on site will work normally without problem.

Sticky Div, Area that remains at top on scroll of page

If you want your site header or  menu or other section(div) to remain at top of page when user scrolls a page. You can try with following jquery code.

It will not workin in IE. So first flag need check if browser is IE or not.

if (!IsIE) {
jQuery(document).ready(function() {
jQuery(window).scroll(SomeScrollResponder);
});
function SomeScrollResponder() {
var tmpScroll = $(window).scrollTop();

//when page scrolls 100 px then following  code will run
if (parseInt(tmpScroll) > 100) {
jQuery(“#divTop”).css(“position”, “absolute”);
jQuery(“#divTop”).css(“top”, (parseInt(tmpScroll) – 1) + “px”);  //-1 will hide top border
jQuery(“#divTop”).css(“width”, (parseInt($(document).width()) – 60) + “px”);

}
else {
jQuery(“#divTop”).css(“position”, “relative”);
jQuery(“#divTop”).css(“top”, “0px”);
}
}
}

In above example “divTop” is a div that will display at top, overlapping on page.