Archive

Archive for the ‘.Net Fundations’ Category

Centralizing Users’ Authentication at Active Directory Level

December 23, 2011 Leave a comment

First of all, sorry for my long absence.

One month ago, I had a talk at TechInsights South East Asia, 2011 related to one of my favorite security topics for centralizing user management. I thought why not share it with you guys.

I hope you enjoy it.

Peace and love …

Advertisements

IIS Smooth Streaming

After surviving from toughest weeks of final exams, having a talk at MIND (Malaysian Independent Developers) event was an amazing relief. My chosen topic was IIS Smooth Streaming from development prospective. After a good presentation, I decided to share the resulting presentation file in my blog to make it available to wider audience.

This work is a collection of notes around the web that can be gathered together to form a solid scenario. I hope you enjoy it.

Finally I should deeply thank some respected members of the community because of their helps and their informative presentations at this event: Daqing Lee, Riza Marhaban, Arsalan Pour Fard and Mostafa Abedi.

.Net Generics (Performance and flexibility)

April 17, 2011 2 comments

I discussed the reason of using Generics in another article. Here it’s aimed to talk about Generics in detail.

Generics are a part of CLR type system that allows you to develop your own types which are flexible in their parameters’ type. Therefore, it allows you to help your consumers feel comfortable while using your class. The most common use for Generics is data types such as lists, linked lists, stacks, trees etc where the operations on each item is done in the same way regardless of their types.

MS Generics

Fig 1

Why using Generics:

1-      Improve performance: As it’s discussed in my previous article, assume that you have a class that its parameters’ type is not specified. You have two choices to build it. One way is to use Object as your parameters’ type which in most cases it needs boxing and unboxing. The second way is to use Generics which has no boxing and unboxing but has almost the same flexibility as Object hast.

2-      Less runtime errors: While you are using Object you need to convert it in order to use it. And because it is not possible to check the parameters’ type in compile-time compiler needs to do type-checking in runtime. In this case, if you cast it to wrong type compiler raises type mismatch error. In contrary, using Generics doesn’t have this issue since its strongly-typed data type, compiler can catch this matching at compile-time.

 

Creating generics types:

It is quite a fun. You just need to specify the name of parameters that are type flexible. After that everything is done by .Net.

class GenericsTemplate<T, U>

{

T t;

U u;

public GenericsTemplate(T t, U u)

{

this.u = u;

this.t = t;

}

public string getT

{

get { return t.ToString(); }

}

public string getU

{

get { return u.ToString(); }

}

}

Here you have a flexible class which can accept all possible types! Isn’t it easy!! :D. It can be int, string, a custom class or any other type.

How to use it:

Parameters’ type are defined in class instantiation.

class Program

{

static void Main(string[] args)

{

GenericsTemplate<string, int> genClass = new GenericsTemplate<string, int>("Hello World", 560);

Console.Write(genClass.getT + Environment.NewLine + genClass.getU);

Console.ReadKey();

}

}

Since parameters’ type is specified in declaration, compiler can check for any mismatch error.

How to use constraints:

Did you find it useful? But I think you found some limitations in using these variables inside the generic class. You can only have capabilities of base Object data-type which are ToString() and GetHashCode() methods. To overcome this problem .Net introduces a key word called where. This key word can be used to limit the range of possible types that parameter’s can accept. This limitation may also reduce the complexity of consuming your generic class since developers (consumers) won’t be confused among too many possible types can be used.

This limitation can be applied for:

1-      Reference or value type: Forces a parameter to accept data-types which are either reference type or value type. (Key words are class for reference type and struct for value type)

2-      Interface: Parameter can accept types which have a specific implemented interface.

3-      Base class: Parameter can accept types which have a specific inherited interface.

4-      Constructor: Forces a parameter to accept data-types which has a default constructor (parameterless constructor). (Key word is new())

class Program

{

static void Main(string[] args)

{

System.Drawing.Bitmap bt = new System.Drawing.Bitmap(800, 500);

//Bitmap is an inherited class from Image and int is a value type which has implemented IComparable interface

GenericsTemplate<System.Drawing.Bitmap, int> genClass = new GenericsTemplate<System.Drawing.Bitmap, int>(bt, 560);

Console.Write(genClass.getT + Environment.NewLine + genClass.getU);

Console.ReadKey();

}

}

//T should be a reference type and an instance of Image class or any class inherited from Image. U sould be value type and has implemented IComparable interface

class GenericsTemplate<T, U> where T: class, System.Drawing.Image where U: struct, IComparable

{

T t;

U u;

public GenericsTemplate(T t, U u)

{

this.u = u;

this.t = t;

}

public string getT

{

//You can use all properties of Image base class while useing t

get { return t.Width.ToString(); }

}

public string getU

{

get { return u.ToString(); }

}

}

You should follow a correct order (order as listed above).

After defining constraints for generic class you can use added capabilities of parameters inside the class. Here I used Width property of base Image class.

Boxing and Unboxing (A key reason to use Generic)

April 7, 2011 2 comments

This article is a discussion about boxing and unboxing in .Net and also the ways to overcome it.

This term is mostly used when we want to convert value types to reference types or vice versa. We really should care about it in development of critical systems, web applications with high traffic or using classes or methods with frequent use.

Boxing: This is the process of converting the value of a value type variable to a reference type variable.

Assume that you want to store a user-defined type (struct) into an ArrayList (As you know user-defined/struct types are value type). Now let’s know what is stored in this ArrayList?

If you take a look at the Add() method of ArrayList, it has only one overload for this method which is Add(Object object) [and Object is a reference type]. It is good news due to the possibility of storing totally different types into each index of an ArrayList. However, it has some bad news too because it needs to convert your value type variable to a reference type variable. It means that it needs a boxing to fulfill this need.

struct TypeA

{

public int VarA;

public int VarB;

public TypeA(int VarA, int VarB)

{

this.VarA = VarA;

this.VarB = VarB;

}

}

public void TestBoxingAndUnBoxing()

{

TypeA typeA = new TypeA(10, 20);

System.Collections.ArrayList arrList = new System.Collections.ArrayList();

//Boxing occures here 

arrList.Add(typeA);

}

What Happens when a boxing occurs:

1- Because value-typed variables are stored in stack, a new memory cell in heap must be allocated to store this object. Reference types use heap (dynamic memory space) to be stored.

2- The value type’s bits are copied from stack to their new location in heap.

3- The new address is returned to be stored in ArrayList. So we now have a reference type instead of a value type.

Therefore, boxing can be very expensive and sometimes harmful.

Unboxing: is, of course, exactly opposite to boxing, it is the time when a reference type is converted to a value type.

After storing value types into ArrayList, they are wanted to be used somewhere. In other words, you should convert them to their original type in order to use them.

typeA = (TypeA)arrList[0];

System.Console.Write(typeA.VarB.ToString());

What happens in unboxing?

1- It Checks whether it is null or not, then it checks whether the specified type is convertible or not. If both of the above conditions fail it returns an exception.

2- The reference of the object inside the ArrayList is returned. Then bits are copied into the value typed variable.

It has some penalties again. To overcome this problem .Net suggests using Generics when time is totally eminent (But it is a better to consider it always).

Generics is out of scope of this article; however, I describe it briefly in a sample code to show its power and its immense difference compared with objects.

Generics classes/methods are similar to type-less ones but they are not. You can specify their types before compile time when you are coding. For example for classes their types must be specified during their instantiation. Therefore, it gives you the flexibility to have different types in each instance of a class.

Code below is a comparison between a Generic class and an Object one.

//T and U are generic types. It means that you can specify their types in class instantiation. So

class GenericClass
{
public T t;
public U u;

 public GenericClass(T t, U u)
{
this.t = t;
this.u = u;
}
}

//An object class that may cause boxing and unboxing during run-time
class ObjectClass
{
public object t;
public object u;

&nbsp;

 public ObjectClass(object t, object u)
{
this.t = t;
this.u = u;
}
}

Now I want to show you the time it takes to work with each one of them for ten million iterations.

protected void Page_Load(object sender, EventArgs e)
{
DateTime dt1 = DateTime.Now;
ObjectClass ObjClass;
for (int i = 0; i &lt; 10000000; i++)
{
ObjClass = new ObjectClass(10, "Peace");
}
DateTime dt2 = DateTime.Now;

TimeSpan tsDef = dt2.Subtract(dt1);
Response.Write("Object: " + tsDef.TotalMilliseconds.ToString() + "
");

 dt1 = DateTime.Now;
GenericClass GenClass;
for (int i = 0; i &lt; 10000000; i++)
{
GenClass = new GenericClass(10, "Peace");
}
dt2 = DateTime.Now;
tsDef = dt2.Subtract(dt1);
Response.Write("Generic: " + tsDef.TotalMilliseconds.ToString());
}
Boxing and Unboxing

Fig 1, the result of comparision

The result clearly shows this difference. (Of course, you get different results each time you run the program but the ratio remains almost the same)

As you see, it is near to two times faster by using the Generic types.

Reference: Jeffrey Richter, MSPress: MCTS Self-Paced Training Kit (Exam 70-536)