Total Pageviews

Friday, 22 July 2011

Some basics about C# like string or String or System.String etc.

I have seen a lot of confusion amongst a lot developers about some basic things of C#. I am going to discuss some of them here.

The very first thing, In C# every thing is a struct or a Class. And every type(Class) is a derived from System.Object, whether is of reference type or Value type.

All Value type variables are derived from System.Value type and System.Value type itself is derived from System.Object. And every value type variables is declared sealed type so no one can derive from it.

Now Lets move some basic Questions.

- What is the difference string, String and System.String?

- What is the difference amongst int, System.Int32, System.Int64.

So these are few basic things, some always have confusion. So lets try to clear it out.

int c;
System.Int32 c;

int c=0;
System.Int32 c = 0;
int c= new int();
System.Int32 c = new System.Int32();

So what is the difference in all above. or Is there any differences?

In one word answer: NO

All of the above would be compiled and will produce the same and exact IL code.

It means all of these are same. Actually C# define primitive types and every primitive is directly mapped to some Class in FCL. So whenever you are going to write the primitive type, compiler while compiling finds the exact Class from the FCL and replaces with it.

Similarly, System.String or String or string all are same. Even I had confusion earlier between String and string. Even when you type both in Visual Studio IDE, both are in different color.

One more thing, I want to say every value type is initialized to its defined default value. Whether you give its default value or not Compiler does it for you, but this is not true for Reference Type.

One already know, writing int is mapped Int32 or is of 32 bit. But some people have different view, according to them int is of 32 bit in 32 bit machines and is of 64 bit on 64 bit machines. Which is absolutely wrong and int is always of 32 bit in C#, whether is of 32 bit or 64 bit machines.

Thursday, 21 July 2011

ASP.NET: Asynchronous Programming

  • Introduction
  • What is Async Programming
  • Async Programming in ASP.NET
  • Detail about Asyncronous programming
  • An example of Asynchrounous programming
  • When to use Async pages
  • Conclusion

Introduction:

Have you ever tried using Async pages in asp.net? Did you ever explore it in
respect of ASP.NET?
If No. This is the article for you. In this, I will be discussing, what is Async
programming? what are the benefits? Async in respect of ASP.NET and its uses
and lots more.

Async programming:

In a literal meaning, Asynchronous operation means that a process operates independently of other processes. If there are multiple operations, All that can be handled different processes/thread without waiting to complete the other ones. So here in coming sections, we will be discussing, how Asynchronous programming comes into the picture in ASP.NET.

Async Programming in ASP.NET:

Normally the kind of websites that we make are not scalable enough that could have been. These websites are very limited and confined. ASP.NET provides us a way to develop our websites more scalable.
Now lets discuss Async programming in respect of ASP.NET. We need to understand how ASP.NET processes the request. When ASP.NET receives a request from a Client, a thread is assigned to request from Thread pool that takes care all the request processing for the request. In normal cases, the thread is kept engaged till the request completes like this
instantiates the page, runs the event handling code and returns the rendered HTML. If this request
requires some long running process or wait for some I/O process then it takes. In the mean time if another request comes, the other free thread is assigned to the request. But thread pool has a limited number of threads and if requests continues pouring when all the thread were exhasted.ASP.NET is forced to deny further requests and User will start getting Server Unavailable errors. Which you seriously does not want. Let’s have a pictorial view.


So in this article I am going to discuss, one of the most unused features of ASP.NET but that will be really helpful for developing highly scalable and available applications.

Details of Async Programming in ASP.NET:

As we already discussed the need and benefits of Async programming in ASP.NET. Lets discuss how ASP.NET leverages Async programming. There is a series of steps/method gets executed ASP.NET loads a page or post back occurs. Every ASP.NET process goes through HTTP pipeline and the finally served by an Handler. A normal handler implements IHTTPHandler. Even if have ever implemented the Handler you must be knowing it. But in case of Async pages a normal HTTPHandler cannot serve the purpose. ASP.NET provides another type of Handler that serves it, that implements IAsyncHTTPHadler. Lets have comparative look on Synchronous and Asynchronous page processing.


So now lets see a example: How to implement Asunchrponous page with ASP.NET.
I have created a sample page and would be showing step by step.

- Create a page and set Async=”true” at page directive of aspx page as

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Async.aspx.cs"
     Inherits="Async" Async="true" %>

- Now at code behind, we need to two methods say BeginTask and EndTask. BeginTask takes some parameters and returns IAsuncresult ad start the task that takes long. and EndTask will be called when the task gets completed and is
handled by another thread. The BeginTask woul be like

private IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)
{
//Write you code here
}

And your EndTask method would be like

private void EndTask(IAsyncResult ar)
{
//Write you code here
}

- We also need to tell the Page these BeginTask and EndTask methods. So that it will be called appropriately. It will done on Page_Load as

protected void Page_Load(object sender, EventArgs e)
{
Page.AddOnPreRenderCompleteAsync(BeginTask, EndTask);
}

- You need to write your code at Page_PreRenderComplete
- We have to override dispose method, that should dispose any connection that we open.

public override void Dispose()
{
//Write you disposal code here
}

I have attached one sample code for example in attachment. That gets the data from database and bind it to the GridView.Assume that data is very large and your database is at some remote machine then it may take long to load.So in that senario, it will be very helpful. You can change the connection string and query to run the sample.

When to use Async pages:

We have discussed a lot about Async pages. But is it advisable to use this in every application. Absolutely not.Because to change the thread between the operation, requires context switching, saving temporary data and lots more. This is itself not very simple operation. So one need to intelligently select this option.
Actually when we have pages that involves some Non ASP.NET thread like getting result from some Web services, printing several pages, reading a file from remote places. These type of Applications are the best candidates of Async programming. Because say, If you have a page that requires to access a file from remote location. So while accessing the file system from the remote location, the ASP.NET thread gives the control to another thread for accessing the file. And ASP.NET thread does not do anything till it receives the result from continuation thread. And if it takes long your ASP.NET site provide less throughput. So for better throughput, you can engage the thread to serve another request.

 Conclusion:

Asynchrounos programming in ASP.NET , one of most unused programming in ASP.NET. But this technology can be very useful in several scenarios as we discussed above.
Please provide your valuable feedback, it will help me a lot in my upcoming writings.

Wednesday, 20 July 2011

Generics and Constraints over Generics

In this post,  I am going to discuss about Generic Classes and bit more on this.  Just for a smooth start,

“Generics were introduced in .NET 2.0, which provides us a way to create Classes/Methods/Types and many more without specifing the specific type of parameters. Parameters must be provided at the time of creating the instances. So we can say Generics are only a blueprint/templated version and actual type is defined at Runtime.”

So lets first create a simple Class say Point

  public class Point<T>
  {
  }

Here as you can see, I have created a generic class Point, its coordinates X and Y can be of any type.

So in this post, I am going to mainly discuss, Constraint with generics.

Its very imperative to have a Generic Class, which can accept any type of parameter. But sometimes one might require that your generic Class can be instantiated with only specific types. Like say you want that a Generic can be instantiated with only say a Class Point Type or of its derived types.  Is it possible ?

Yes this is possible.

And also, C# provides a very robust way to implement this feature. So using it, It can be very helpful at certain times to define a constraint over Generic.

So what are the ways to do this. We’ll first take few examples then. Later we will conclude .

So First, How can we define constraint with Generics. It is done using where clause.

We have two types of variable in C#. reference and Value..

No.. …

Now we have three types:

    Reference
    Value
    Nullable ( It is having feature of both types)

So we’ll discuss about Nullable type in some other post. Let’s stick to to constarint in Generic type. So what will you do if you want to have Generic type that can be instantiated as Value type. Do we need to make a comma separated list of all the possible value types.
NO..
We know, In C#, A Class is a reference type and Struct is a value type. So we can define a generic that will be instantiated of Value type only. Like here my Point class could be one real time example that can be instantiated to a Value Type. It can be done as

  public class Point
         where T1 : struct
  {
        ...
   }

Similarly,  If we want a generic that can be of  Reference type only, that can be as just opposite to above one.

Public Class Queue: where T:Class
{

}

You also can have multiple restriction. You can put a comma separated list. So how can you do this. It can be like

 public class Point
       where T1 : class
 {
     ...
 }

But what is meant Whether T would follow all or anyone of them. It should follow all, like here T must implement all three interfaces  IEnumerable, IList, IDisposable.
There are few restriction on this. While providing multiple restriction, it can contain only one class but it can have multiple interfaces. Also there are some restrictions on ordering of the types. The class or struct key word should come first and if Class/Struct is there it requiries to be written ahead of All. And after this any class or base class then all other Interfaces.
We can also have multiple restriction on a Generic Type but it should not be conflicting. Like we can never say

Public class Point where T: struct, class
{
   ...
}

It’ll be a compile time error.
So One more constraint we can have like

Public class Point where T: new()
{
    ...
}

So what it means here, It means T must be a type that have a parameter less constructor. I can have parameterized but it also must have parameter less one also. It can also also be accompanied with other restriction also but this should be last in the list.
Similarly, you can apply contstraint on those Generic Types that have multiple parameters. Like my below one

public class Point
       where T1 : class, new()
          where T2 : IList
{
  ...
}

Here also you have option to apply the constraint to any one of  them or both of them or some of them.
I think that’s all about Generic constarint.
One thing you might wonder, whether the following is possible

public class Point
            where T1 : int
{
     ...
}

But this is not possible. The constraint must be an interface, a non-sealed class or a type.

When you will compile will get an ERROR “A type used as a constraint must be an interface, a non-sealed class or a type”.

I was thinking to have this one also, but not there. But you might except it in the coming version of C#.

Hope you all must have liked this. Do share your feedback

Cheers,

Anil