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
}

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/

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.

LINQ basic query samples in csharp asp.net with join

Assuming “db” is considered as databasecontext object

/////// typical query with condition that returns annonymous object ///////////
var contacts =
from customer in db.Customers
where customer.Name.StartsWith(“A”) && customer.Orders.Count > 0
orderby customer.Name
select new { customer.Name, customer.Phone };

/////// get count with running query///////////
var query = (from o in Order
where CustomerID = 2
select o).Count();

/////////////// inner join (matching in both only) //////////////

var cr = from c in MyDatabase.GetReadOnlyContext().tblCategories
join p in MyDatabase.GetReadOnlyContext().tblProducts on c.CategoryId equals p.CategoryId
select new { c.CategoryName, p.ProductName };

//////////////// left outer joing

var crForLeftOuterJoin = from cat in dc.tblCategories
join pro in dc.tblProducts
on cat.CategoryId equals pro.CategoryId
into xname
from pro in xname.DefaultIfEmpty()
select new {
CAP_Cat = cat.CategoryName,
CAP_Product = pro == default(tblProduct) ? “(no product)” : pro.ProductName
};

//////// getting rows from table as LIST collection /////////////
List lstCat= dc.tblCategories.ToList();

//////// getting rows from table as Array /////////////
tblCategory[] arrCat= dc.tblCategories.ToArray();

///////////////seeking particular element/single element from query ///////////////////

var firstproduct = (from product in db.Products
where product.Category.CategoryName == “Beverages”
select product
).AsEnumerable().ElementAt(0);

Display SQL SERVER Message,Using InfoMessage Event from SQL SERVER, to troubleshoot stored procedure

Big stored procedures which are building QUERY dynamically according to parameters are used sometime for large web applications.

Bad luck starts when such procedure gives error, and as query itself build at run time, user may frustrates catching the right error.

Also,Debugging becomes challenging with it.

One way is to use PRINT statement at end of procedure, so when stored procedure executed it displays DYNAMIC QUERY.

In SQL Server Management studio we can easily view the printed query.

But what if you want it in ASP.NET environemt?

SqlConneciton class has
SqlConnection.InfoMessage event, which occurs, when SQL Servers returns a warning or informational message.

First create ‘SqlConnection’ object.

string connectionString = “Your Connection String…”;
SqlConnection myConn = new SqlConnection(connectionString);
Then, Relate method to event.

myConn.InfoMessage += new SqlInfoMessageEventHandler(MyConnection _InfoMessage);

 

Your method may look like following:
System.Text.StringBuilder sbLog = new System.Text.StringBuilder();

void MyConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
sbLog.AppendLine(e.Message);
}

Execute following code and test output with ‘sbLog.ToString()’.

SqlCommand cmd = new SqlCommand();

if (cn.State != ConnectionState.Open)
cn.Open();

cmd.Connection = myConn;
cmd.CommandText = “SP_That_Prints_Query”;

cmd.CommandType = CommandType.StoredProcedure;

cmd.ExecuteNonQuery();

 

‘sbLog.ToString()’ will give you dynamic query generated in your stored procedure.

 

DATA CACHING in asp.net with cache class

ASP.Net caching feature stores objects in memory.

By using instance of ‘Cache’ class, we can use this feature. Internally key/value pairs

Unlike sessions, application cache is global (application wide) and every user who accesses that application can access the value in the cache.

Syntax:

Store data in cache

HttpContext.Current.Cache.Insert(key, data)

Retrieve data from cache

HttpContext.Current.Cache(“keyname”)

Clear all cached items

ClearCache(“”)

See one example:

If you set following page load function, then each time you refresh page, you will see same time value each time.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If IsNothing(HttpContext.Current.Cache(“mykey”)) Then

HttpContext.Current.Cache.Insert(“mykey”, “This message was stored in cache at : ” & Date.Now)

End If

Response.Write(HttpContext.Current.Cache(“mykey”))

End Sub

Advantages to your web application by using ASP.NET Data Caching :

With ASP.Net Caching, you have to add just few line of code will reduce database access from your application.

As web server will send fewer requests to database Performance of web application will be improved. (As in many cases redundant data will be retrieved from ASP.NET Cache)

Quick responding web application, gives more satisfaction to end user, while spending time on your site.

Web development small tips

Single quote in java script, may result in error

In Javascript,when using or concatenating string, use it with double quotes.
Or it may generate error.

Recommanded:
var str="Some String" + document.getElementById("txtName").value;

Should be avoid:
var str='Some String' + document.getElementById("txtName").value;


To overcome Date format related error, in .Net, with CompareValidator validation control
You can, specify culture in web config file.


Put Share Button on your website with ADD THIS

Go to http://www.addthis.com site, and it will ask you button layout you want to Choose.
And that site will display code snippet, which will contain one SCRIPT tag and HTML lines.

So you have to add script line in your page and put ‘html’ tags at place where you want to display share icons.


To set content in tinyMCE editor box by using javascript
var editorInstance = tinyMCE.getInstanceById("ctl00_cpMain_txtCampaignDesc"); //specify clientid of textarea field
editorInstance.getBody().innerHTML = "This is dynamic text set by javascript.";

online video conversion(flv conversion) using asp.net(web development) – borania siddharth

Audio and Video files are becoming important part of web sites, now a days.

Many social networking and job portal sites are built to offer audio/video upload and play functionality.

These videos are then played in client’s browsers.

Playing video in client’s machine is preferred with FLV format rather than any other(like .wmv).

And same technology is applied for audio playing.

and as there is different format files may be uploaded by user, always there is question to weather restricting users for ONLY uploading FLV files or giving them FLEXIBILITY to upload file in their desired(available) format, and online convert it into FLV.

So, here i have present small code snippet, to outline how FLEXIBILITY may be given to user for uploading any audio/video format, and same time its playable by website.

string strinp;
strinp = Server.MapPath(“~/test1.wmv”).ToString();

string strop;
strop = Server.MapPath(“~/test2.flv”);

Process p;
try
{
ProcessStartInfo info = new ProcessStartInfo(Server.MapPath(“~/ffmpeg.exe”));

info.Arguments = “-i \”” + strinp + “\” \”” + strop + “\””;

p = Process.Start(info);
p.Start();
p.Kill();
}
catch (Exception ex)
{
//catch error here
p.Kill();
}

Any Suggestions are welcome.

-By Siddharth Borania from Dhanashree Incorporation