Pranay Rana: July 2011

Saturday, July 30, 2011

Generate thousand of request

Lastly I was working on the project where I have to designed web page which is exposing some set of the functions and which is get consume by some external application like java and flex. It's worked fine and providing the output I want.

But now I want to perform the load test, so for that I want to generate thousand of request which consume the page and show me how it works. But the problem is how to generate the request because I don't have that many people who can make request at given time.

Solution for this problem I make use of the Thread class and loop it to the no. of request I have to generate as you see in below code.
for (int i = 0; i < 100; i++)
{
    Thread thread1 = new Thread(new ThreadStart(WorkThreadFunction1));
    thread1.Start();
}
Now the secondly I made use of HttpWebRequest class which allow me to call the page and to get the response. You can get more information about HttpWebRequest.
public void WorkThreadFunction1()
{
   try
   {
     string param = string.Empty;
     HttpWebRequest oWebReq =     
      (HttpWebRequest)WebRequest.Create("http://mywebsite/WebForm1.aspx" + param);
     HttpWebResponse oWebResp = (HttpWebResponse)oWebReq.GetResponse();
     StreamReader oStream = new StreamReader(oWebResp.GetResponseStream(),     
                                                     System.Text.Encoding.ASCII);
     Console.WriteLine(oStream.ReadToEnd());
   }
   catch (Exception ex)
   {
      // log errors
   }
}
As you can see in the above code I am making the call to the my page and writing the response to the console window.
Note:
Here WebForm1 is entry point based on the parameter passed to it , it calls the different function and may be the pages in your site.
Here I am making request to one single page but you can write you own script to call the different page and pass the parameter to it.

Summary
So you can easily make no. of request without need of the no. of people. But this thing depends on the requirement in you case.

Friday, July 29, 2011

Difference between Object, Dynamic and Var

In this post I am going to write the points about the three type of the variable Object, Var and Dynamic. Most of the developer not able to get what is difference between this three kind of variable.
ObjectDynamicVar
Can able to store any kind of value, because object is the base class of all type in .net framework.Can able to store any type of the variable, similar to old VB language variable.Can able to store any type of value but it require to initialize at the time of declaration.

Compiler has little information about the type

Compiler doesn't have any information about the this type of variable.

It's compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Object type can be passed as function argument and function also can return object typeDynamic type can be passed as function argument and function also can return object typeVar type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for primitive data type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation.

Allows to perform operation of given type once it get cast any user defined or primitive data type.
Casting is not require but you need to know the property and methods related to stored typeNo need to cast because compiler has all information to perform operation.
Cause the problem at run time if the stored value is not get converted to underlying data type.

Cause problem if the wrong method or property accessed because all the information about stored value is get resolve only at run time

Doesn't cause problem because compiler has all info about stored value.
Useful when doesn't have more information about the data type.Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

Thursday, July 21, 2011

Handle Exception Carefully

Handle Exception carefully means I am not going to discuss some rocket science about exception handling but I am going to discuss not to shadow the exception in your program. Not going to discuss more I am starting my example
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Program p = new Program();
                p.MethodA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }

        public void MethodA()
        {
            try
            {
                MethodB();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void MethodB()
        {
            try
            {
                MethodC();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void MethodC()
        {
            int a = 10;
            int b = 0;
            int c = 0;
            try
            {
                c = a / b;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
When execute the program you will get the following output as result. Yes you can able to handle the exception thrown by the method and displayed on the console.
Output
But the actual thing is you hiding the stack trace and each time you throw the exception by writing throw ex you are creating new stack trace. So you are not able to get the actual path from where the exception get thrown.

Now to understand the thing properly, write the program again and now replace throw ex by the throw
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Program p = new Program();
                p.MethodA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }

        public void MethodA()
        {
            try
            {
                MethodB();
            }
            catch
            {
                throw;
            }
        }

        public void MethodB()
        {
            try
            {
                MethodC();
            }
            catch
            {
                throw;
            }
        }

        public void MethodC()
        {
            int a = 10;
            int b = 0;
            int c = 0;
            try
            {
                c = a / b;
            }
            catch
            {
                throw;
            }
        }
    }
When execute the program get the following output
Output
Now as you see when you replace the line there is no new stacktrace get created and you get actual path from where exception get thrown.
Summary
So make use of the throw to get the actual path of the exception rather than using throw ex.

Sunday, July 17, 2011

String Split Utility

Note: Split function has more no of overload method but the below two I found useful. You may found other overloads helpful in your code.

In this post I am going to discuss about two important thing about Split function of String class. Split function of the string class split the string in array of string.

Split function to split string in array
String.Split( char[])
For example
string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','}); 
Above code create a string array which has
//output
split[0]=stringa
split[1]=stringb
split[2]=
split[3]=stringc
split[4]=stringd
split[5]=stringe
but What If I want to remove empty string from the array when I split string.
Solution to this problem is to make use of second overload method of the the string Split where you can specify the option to remove string. So above code is rewritten as

Overload method with option
String.Split(Char[], StringSplitOptions)
string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries); 
Created string array is
//output 
split[0]=stringa
split[1]=stringb
split[2]=stringc
split[3]=stringd
split[4]=stringe

Now consider case where I have to limit no of return string. Consider for example
string a = "key:mykey, Value : test1,test2";  
Now I have to get the key:mykey in string 1 and Value : test1,test2 in string 2.
Overload function to split string in limited no. of string
Split(Char[], Int32)
So the code for this is
string a = "key:mykey, Value : test1,test2";
string [] split = words.Split(new Char [] {','},2);   
Now the split array have
//output
split[0]= "key:mykey";
split[1]= "Value : test1,test2";
Summary
There are also other variable of Split method which you can refer form the msdn link :String.Split. But I fond above two more useful than others.

Tuesday, July 12, 2011

ForEach Method for the collections

In this small post I am going to discuss about the new method introduce in the .net framework ForEach which allow to perform the action on the each set of element.

Syntax
public void ForEach(Action<t> action)
Action<t> is delegate or function to perform on each element of the List.

To get in more detail how it works check check the following code.
Below is Employee class which has property related to employee of the company.
public class Employee
{
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public int Id { get; set; }
}
and now in following line of code I am initializing list of employees
class Program
    {
        static void Main(string[] args)
        {
          List<employee> emplst = new List<employee> { 
          new Employee() { Name="pranay", Address = "Ahmedabad", Id=1, Salary=1234},
          new Employee() { Name="Hemang", Address = "Ahmedabad", Id=2, Salary=2348},
          new Employee() { Name="kurnal", Address = "Himmatnagar", Id=3, Salary=8999},
          new Employee() { Name="Hanika", Address = "Ahmedabad", Id=4, Salary=7888}
        };
Now I want to increase salary of each employee by 10%, so with the the help of new ForEach construct I can easily achieve it by using following line of code.
emplst.ForEach(new Program().incSalary);
     }

  private void incSalary(Employee emp)
  {
     emp.Salary += (emp.Salary * 10)/100; 
  }
}
As you can see in above code I have written new Program().incSalary as action, in the incsalary method as you see I increase the salary of each employee 10%.
This thing can easily also done by making use of the foreach loop available but if you see the the ForEach in reflector it does the same thing.
ForEach method make code more simple and easy to understand.

Friday, July 8, 2011

Jquery Ajax Calling functions

Download Code

Recently I am working on Website with the asp.net and jQuery. While working with jquery library I found that there are 5 diffrent function that used to make ajax call to page and to fetch data. I am going to discuss about that five function one by one.

Following is list of that five function availale in jquery libaray to make ajax call.
  1. Load
  2. getJson
  3. GET
  4. POST
  5. Ajax
Load
Method allow to make ajax call to the page and allows to send using both Get and Post methods.
var loadUrl = "TestPage.htm";
$(document).ready(function () {
   $("#load_basic").click(function () {
     $("#result").html(ajax_load).load(loadUrl, function (response, status, xhr) {
                    if (status == "error") {
                        var msg = "Sorry but there was an error: ";
                        $("#dvError").html(msg + xhr.status + " " + xhr.statusText);
                    }
                }
                );
                return false;
});
As you can see in above code you can easily make call to any page by passing it Url. The call back function provide more control and allows to handle the error if any by making use of the Status value.
One of the important thing about the load method is its allow to load part of page rather than whole page. So get only part of the page call remains same but the url is
var loadUrl = "TestPage.htm #dvContainer";   
So by the passing above url to load method it just load content of the div having id=dvContainer. Check the demo code for detail.



Firebug shows the repose get return by when we call the page by Load method.

Important Feature
  • Allow make call with both Get and Post request
  • Allow to load part of the page.
getJson
Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed. One more thing this method treat the respose as Json.
var jsonUrl = "Json.htm";
            $("#btnJson").click(function () {
                $("#dvJson").html(ajax_load);

                $.getJSON(jsonUrl, function (json) {
                    var result = json.name;
                    $("#dvJson").html(result);
                }
                );
                return false;
            });
Above code make use of getJSON function and displays json data fetch from the page.
Following is json data return by the Json.htm file.
{
"name": "Hemang Vyas",
"age" : "32",
"sex": "Male"
}

Following image displays the json Data return as respose.


Important Feature
  • Only send data using get method, post is not allowed.
  • Treat the response data as Json only

get
Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.
var getUrl = "GETAndPostRequest.aspx";
            $("#btnGet").click(function () {
                $("#dvGet").html(ajax_load);

                $.get(getUrl, { Name: "Pranay" }, function (result) {
                    $("#dvGet").html(result);
                }
                );
                return false;
            });
As in code I am passing Name parameter to the page using get request.
On server side you can get the value of the Name parameter in request object querycollection.
if (Request.QueryString["Name"]!=null)
{
    txtName.Text = Request.QueryString["Name"].ToString();
} 

The firebug shows the parameter passe by me as Get request  and  value of the parameter is pranay



Important Feature
  • Can handle any type of the response data.
  • Send data using get method only.

post
Allow to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just send data using post method.
var postUrl = "GETAndPostRequest.aspx";
            $("#btnPost").click(function () {
                $("#dvPost").html(ajax_load);

                $.post(postUrl, { Name: "Hanika" }, function (result) {
                    $("#dvPost").html(result);
                }
                );
                return false;
            });
As in code I am passing Name parameter to the page using post request.
On server side you can get the value of the Name parameter in request object formcollection.
if (Request.Form["Name"] != null)
{
    txtName.Text = Request.Form["Name"].ToString();
}

The firebug shows the parameter passe by me as Get request  and  value of the parameter is Hanika



Important Feature
  • Can handle any type of the response data.
  • Send data using post method only.

ajax
Allow to make the ajax call. This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter.
var ajaxUrl = "Json.htm";
            $("#btnAjax").click(function () {
                $("#dvAjax").html(ajax_load);


                $.ajax({
                    type: "GET", //GET or POST or PUT or DELETE verb
                    url: ajaxUrl, // Location of the service
                    data: "", //Data sent to server
                    contentType: "", // content type sent to server
                    dataType: "json", //Expected data format from server
                    processdata: true, //True or False
                    success: function (json) {//On Successfull service call
                        var result = json.name;
                        $("#dvAjax").html(result);
                    },
                    error: ServiceFailed// When Service call fails
                });


                return false;
            });
In above code you can see the all the parameter and comment related to each parameter describe the purpose of each one.

Fire bug shows the called page return json data and Ajax function treat the respose as Json because in code datatype = json


Important Feature
  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successfull.

Summary
So each method of jQuery ajax is different and can use for the difference purpose.

Tuesday, July 5, 2011

Get time of Code Execution Using StopWatch

During Development of the application/product or after deployment of the application/product there might be a situation where you want to find out the the how much time is taken by you code to execute ? Is it too much slow ?

Answer to this problem is make use of StopWatch class of System.Diagnostics namespace which is usefull to find out the time taken to execute given line of code. The class is helpfull to find out how efficient code develop by measuring the time of execution.

To understand how to use it consider the below demo
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//instead of this there is line of code that you are going to execute
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime);
Console.ReadLine();
Stopwatch class has method Start() and Stop(), So the as name suggest call start when you want to start your watch and call Stop when you want to stop the watch. Once you stop the watch i.e called stop method of the StopWatch class you can get the value of time of execution by using Elapsed property of the class which return TimeSpan object.

Output



There are also other important methods which are very usefull you can get the more infomation about those on the MSDN documentation over here : StopWatch Class
Methods
StartNew - Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
Restart - Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
Reset - Stops time interval measurement and resets the elapsed time to zero.

Properties
ElapsedMilliseconds - Gets the total elapsed time measured by the current instance, in milliseconds.
ElapsedTicks - Gets the total elapsed time measured by the current instance, in timer ticks.

Advantage
  • Easy and Simple to use.
  • Useful when want to find out the time take by the line of code to execute.
  • By using the class there is no need of any third party tool because it part of the .net framework.

Monday, July 4, 2011

Lazy initialization of object in C# with Lazy<T> class

Lazy<T> is class introduced in the .Net framework 4.0 to initialize the object later on i.e allow to initialize object when we are going to utilize or assigning value to the object.

To understand Lazy initialization consider below class.
public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public int Id { get; set; }
    }
In the following code I am using the Employee class. As you can see I have initialize the class to null
Employee emp1=null;
     Console.WriteLine(emp1);
     ///Code do perform other task
     if(Condition)
     {
      if (emp1 == null)
        emp1 = new Employee();
     }
In above code I am initializing class when I need it rather than initializing before using it same way we can do in the Singleton design pattern, by this way we are lazing initializing the object and consume memory when need it rather than initializing it in the first line of the method.

But now .net 4.0 framework provide the new class to do this thing easily. The class is Lazy<T>. So the above code is something like as below
Lazy<employee> emp = new Lazy<employee>();
     Console.WriteLine(emp);

     emp.Value.Id = 1;
     emp.Value.Name = "pranay";
     emp.Value.Salary = 123;
     emp.Value.Address = "Ahmedabad";
     Console.WriteLine(emp);
Output of the program
As you can see in output window it display no value is defined.

Important Properties
Object is get created when we access property Value and assign value to it. To find out the detail I used reflector and which shows that the object get created when I access property.

Another the important property is IsValueCreated-Gets a value that indicates whether a value has been created for this Lazy instance.