Thursday, December 31, 2009

Extension points for ADO.NET Entity framework

I explored a bit more on Entity framework,during last week of 2009 and here goes my observations on how to extend the Entity Framework functionality if you want to customize the normal/ideal flow of Entity framework execution engine.

1) OnContextCreated

By default a declaration of this method will be there as a partial method in the generated code, and as the name suggest this will be invoked during the first time when the ObjectContext class gets created,Hence this is the right place if you want to execute some operation after the ObjectContext creation

2) OnChanging(value)

Again this is the partial method which will be executed when the value of the property of an EntityObject is getting materialized,Hence if you wanna to add some logic/validation when the object property is getting assigned this is the right place of choice for you

3) OnChanged

This is the other partial method which will be executed after the property value of an EntityObject is assigned,Hence after the assignement if you want to perform any operation here you can write..

Note : Both the OnChanging and and OnChanged will be executed every time when the EntityObject is getting materialized, So if you wanna to write performance intent code be aware of the side effects !

Happy programming and a very Happy new year

Regards,
-Vinayak

Sunday, December 27, 2009

A note on Entity Framework

From past few days i was doing some R & D on the upcoming Entity framework from Microsoft, and i found it was interesting in many ways,
The first part which i liked the most is -
Querying to the Entity Data Model(EDM) rather than the real data store.
At a high level , we have plenty of options to query for the data store.
some of the options i had listed down here.
1) By using ObjectService API
2) By using Entity Client
3) By using LINQ to Entities
4) By usnig LINQ to SQL
5) By using Object Builder

The second part which i liked the most is - about the pattern which is invloved for any querying (Pattern : Unit of Work)
This is achieved by using the Class which is derived from the ObjectContext, which knows what happens to the entities(EntityObject)(New,Edit,Delete) during its(Context) life time, Hence context knows how to update the status back to the data store when the user finally submits back.(by doing many operations locally on the entities and finally invokes the command to the store),Best part is Entity framework know what command to generate depends on the status(EntityState) of the Entity.
How cool right???
Happy reading
Regards
-Vinayak

Monday, December 21, 2009

.Net Coding Best practices

.Net Coding Best practices - Vinayak's thumb rules

1. Do not hard code strings/ numerics. Instead of that use constants as shown below.

Bad practice

Int Count;
Count = 100;
If( Count == 0 )
{
// DO something…
}

Good practice

Int Count;
Count = 100;
private static const int ZERO = 0;
If( Count == ZERO )
{
// DO something…
}

2. For string comparison - Use String. Empty instead of “”

3. By default keep the scope of member variables to ‘private’, based on the needs expand the scope either to protected or public or internal.

a. Other advantage of making the scope private by default is that during XMLSerilaization, by default it will serialize all the public members.

4. When we have to manipulate the strings inside a loop, use StringBuilder instead of string as shown below.

Bad practice

String temp = String.Empty;
For( int I = 0 ; I <= 100; i++)
{
Temp += i.ToString();
}

Good practice

StringBuilder sb = new StringBuilder();
For ( int I = 0 ; I <= 100; i++)
{
Sb.Append(i.ToString());
}

5. Prefer Arrays over Collections for simple operations.

6. Prefer Generic Collections over ArrayList

7. Prefer Generic Dictionaries over HashTable *.

8. Prefer StringCollections and StringDictionaries for String manipulations and storage.

9. Use the appropriate data types.

For ex: if you want to check for any status, prefer bool rather than int.

Bad practice

Int Check = 0;
If( Check == 0 )
{
// DO something
}

Good practice

Bool Check = false;
If( !Check)
{
// DO something
}

10. Use ‘as’ operator for type casting and before using that resultant value check for null.

Class A
{
}
Class B : A
{
}
B objB = new B();
A objA1 = (A) objB;
A objA 2 = objB as A;
If( objA2 != null)
{
//Do something
}

11. For WCF proxy creation, use the using statement

Using(Cerate the proxy)
{
//Do the required operation
}

12. Follow ‘Acquire late, release early’ rule for expensive resources such as Connection, File etc.

For ex : if you want to make use of SqlConnection Object for any data operations, create the instance at the method level rather than at the class level.

Class MyData
{
Public MyData()
{

}
Public List<Customer> GetAllCustomer()
{
Using(SqlConnection objConnection = new SqlConnection(“Connection string”))
{
//Do the operation and get the required data..
}
}
}

If you want to create the SqlConnection instance at the class level, ensure that you are implementing the IDisposable for the class and doing the cleanup of SqlConnection instance at the Dispose();

Class MyData : IDisposable
{
SqlConnection objConnection = default(SqlCOnnection);
Public MyData()
{
objConnection = new SqlCOnnection(“Connection string”);
}
Public List<Customer> GetAllCustomer()
{
By using objConnection get the required data
}
Public void Dispose()
{
//Do the cleanup of SqlCOnnection
If( objConnection != null )
{
If( objConnection.State == ConnectionState.Open)
{
objConnection.Close();
}
}
}
}

13. If you do not want anybody to extend your class functionalities, make it ‘sealed’ to get the inlining and compile time benefits

14. Avoid declaring the ‘destructor’ for every class. This will increase the life time of the class which un necessarily makes them long lived

15. Prefer using Thread Pool over manual threading.

16. Do not make any calls to a method from the loop.

For ex :

Bad practice

For( int I = 0; I <= 100; i++)
{
Calculate(i);
}

Good practice

For( int I = 0; I <= 100; i++)
{
//Inline the body of Calculate.
}
17. Do not handle exceptions inside a loop, rather handle looping logic inside try/catch

For ex:

Bad practice

For(int I = 0 ; I <= 100; i++)
{
Try
{
}
Catch(Exception ex)
{
Throw ex;
}
}

Good practice

Try
{
For(int I = 0 ; I <= 100; i++)
{
}
}
Catch(Exception ex)
{
Throw ex;
}

18. Do not handle application logic by using Exception.

For ex :

Bad practice

try
{
Int x,y,z;
X = 0;
Y = 10;
Z = y/x;

}
Catch(DevideByZeroException ex)
{
Throw ex;
}

Good practice

Try
{
Int x,y,z;
X = 0;
Y = 10;
If( X != 0 )
{
Z = y/x;
}
}
Catch(Exception ex)
{
}

19. Prefer for/while loop over foreach

20. For communication between the layers, prefer Data Transfer objects over DataSet/DataTables.

I hope this will help you all to improve the code quality!!


Happy programming

Regards,
-Vinayak

Friday, December 18, 2009

Best practices for creation of WCF proxy's in .Net

From past few days i was doing some findings about the best way of creating the service proxy's in WCF.

Here goes the result of that exercise..

1)

In this first case, We are creating the service proxy with the help of the ChannelFactory and we are closing that factory once we are done with the exercise,but it might so happen that during close call it might throw an exception,Afterwards that proxy state becomes faulted and it may be of no use(you cant make any call on that), hence to be on the safer side, by using a bool we are cleaning the instance if at all any exception happens. How cool right?


















2)

In this second case, using block will ensure that the proxy is Disposed, because the equivalent of the below code or using statement is




using (OrderServiceReference.OrderServiceClient proxy = new WindowsFormsApplication1.OrderServiceReference.OrderServiceClient())

{

int i = proxy.GetScore();

}





Equivalent code after compilation -

OrderServiceReference.OrderServiceClient proxy = default(OrderServiceReference.OrderServiceClient);

try
{

proxy = new WindowsFormsApplication1.OrderServiceReference.OrderServiceClient();

int i = proxy.GetScore();

}

finally
{

proxy.Dispose();

}



Thats all for now...

Regards,
-Vinayak


Thursday, December 17, 2009

Exception Handling Strategy by using WCF Services at Business layer for Enterprise .Net application

Today I would like to discuss a bit on the best practices for handling Exceptions in Enterprise applications where in WCF Service is used at the business layer

Ideally any standard Enterprise application will have 3 layers – Presentation, Business and Data Access.

Predominantly the WCF role will come in to play at Business layer (where in the real business rules are defined/ elicited).

So as a best practice it would be good if you follow these thumb rule at each layer to ensure the smoother operations or flow

Rule 1:

Identify & Define the Type of exception which you want to handle at the business layer

For ex : MyException

[DataContract]

Public class MyException

{

Describe/Collect the details which you want to handle.

}

Rule 2:

Decorate the method/operation with the identified exceptions – Define FaultContract’s for the Operations

For ex:

[ServiceContract]

Public interfact IMyService

{

[OperationContract]

[FaultContract(typeof(MyException))]

Void Get();

}

Rule 3:

Throw the FaultException at the Business layer.

For ex :






















Rule 4
At the configuration side – Enable Exception propagation












Rule 5:


At the Presentation layer catch the respective exception which you are throwing from the Business layer.









That’s it!!!

I hope this helps.

Regards,
-Vinayak

Tuesday, December 1, 2009

Kick Start to REST Full .NET WCF Service

Recently I was doing some investigation about how to create a Restful .Net WCF service. I had encountered some interesting hiccups in between during the course of action, so I just thought of to share with you all.

Steps to create the Restful WCF service
  1. Create the WCF project by using VS template

  2. Add the namespace System.Servicemodel.web to the project

  3. Decorate the default service with the REST attribute to convert it into a Restful service(WebInvoke,WebGet ,URI definition to access the respective operations etc)

  4. At the configuration side of the service change the binding of an endpoint to webHttpBinding

  5. Describe the REST endpoint behavior as shown below





  6. Link the service endpoint behavior to REST endpoint description by the attribute 'bindingConfiguration' here in this case value is - 'webHttp'

  7. Finally the entry of endpoint should similar to this






Thats all is needed to have a basic REST Service.

I hope this will help you all to have a gook kick start for the REST WCF Service.

Regards,
-Vinayak