Posts Tagged ‘.Net 3.5’

5 Performance Enhancement Tips for LINQ Coupled With MSSQL Server

Tuesday, July 27th, 2010

LINQ is one of the most exciting enhancements made in the Microsoft.NET languages in the recent years.

Essentially, it’s a new way to represent different data models in OOPs notation.

While working extensively with LINQ in last couple of years on mission critical .NET projects, I’ve observed the following five performance enhancement possibilities.

1. Lazy Loading & Eager Loading

Lazy Loading:

By default LINQ loads the related objects lazily. Lazy loading means Loading Object with that associate Objects.

For example, If I have two tables called User (UserId, Name) and User_Car  (UserId, CarID, CarBrand), whenever we initiate a User object, it will automatically load User_Car object details also as shown in the code below.

var userObj = from user in DataContext.User
              Select user;

The above query returns the User Object with the details of associate object of User_Car.  E.g.

Int carId= userObj.User_Car.CarID;

The above statement will fire two queries on database.

First one will be fired when we write query on User Object. E.g.

var userObj = from user in datacontext.User
              Select user;
(Select ID, Name from User)

And second query will fired when we try getting the value from User_Car object.

E.g

Int carId=userObj.User_Car.CarID;
(Select User_Car.CarID, User_Car.User_ID, User_Car.CarBrand
from User_Car where User_Car. User_ID =@userID)

This leads to more round trips to the database. Instead, we can opt for Eager loading.

Eager Loading:

Defining associate Objects  which are require in advance.So when LINQ execute query then it fetch only that objects.And LINQ fire a single on database.

For Example,

DataContext dc= new DataContext ();
DataLoadOptions options = new DataLoadOptions ();
option.Loadwidth<User> (U => U.User_Car)
dc.LoadOptions = options; 

(Here, User_Car object as pre-fetch object. So when we write query on User Object then automatically User_car records get fetch.)

e.g

var userObj = from user in DataContext.User
               Select user;

SQL Query is,

(Select User.ID, User.Name, User_Car.CarID, User_Car.User_ID,
User_Car.CarBrand from User join User_Car on
User.ID=User_Car.User_ID)

And when we write

Int carId= userObj.User_Car.CarID

It fetches the record from memory only. So Eager Loading reduce the Database round Trips and Improve the performance.

2. Use DataLoadOption.AssociateWith ()

In Eager Loading, When association of Master object and child object are based on non PrimaryKey then use DataLoadOption.AssociateWith (). It will optimize SQL query and give better Performance.

3.Set ObjectTrackingEnabled = False

LINQ objects are use only for data retrieval (No insert, update, delete operations are required) then make this flag off.It will avoid Identity Field(Auto-Increment Field) management process.

4. Set Delay Loaded = True

Field which is not in use or huge in size of contain for particular object then set this property as True.So we access the field then only data get  load.

5. Use Compiled Query

Compiled Query skip the steps of  generating Expression Tree and generating SQL Query  of Process Life Cycle.When First time query get executed, the expression tree and SQL query is generated and next time system will use same for execution.

e.g

Public static Func<DataContext, int, IQueryable<User>>
    UserByID=
	    CompiledQuery.Compile ((DataContext db, int UserID) =>
            From U in db.User where U.ID == UserID select U);

When we call Function first time the expression tree and SQL query will be generate and next time system will use the same to execute query on database.

After applying one or more of the above tips, a LINQ application will definitely perform better and thus will ensure faster response times to business needs.

Benefits of using RESTful WCF Services

Monday, June 7th, 2010

Overview

WCF Restful service is a simple yet very useful concept of WCF Services. Either in .Net 2.0 or .Net 3.5 the web services whether by ASMX or WCF have been implemented using SOAP and WS-* standards. WS-* Standards are extensions of the SOAP specification which defines the Advance level functionalities such as Transactions, Reliable Messaging and much more. There is no doubt that if you create the web service using SOAP protocol with HTTP carrier, you can create viable solution for big Enterprise Problems. Due that SOAP is a very heavy weight and complex protocol; it cannot be easily readable by human. It also contains lot of extra xml markups which are protocol oriented or sometimes really not required by the solution. Those xml markups increase the size of the messages resulting into higher data transfer rate on the wire.

In the release of .Net 3.5 Framework WCF offers support for both the programming model Web & SOAP. So the Restful web services are nothing but a web programming model to expose WCF Service.  REST can have more impact on data transfer reduction in combination with JSON or other serialization techniques.

What is REST?

REST stands for REpresentation State Transfer. Representation State Transfer term is invented by one of the original author of the HTTP protocol, Roy Fielding in his 2000 doctoral dissertation.  Visit the wiki for more about REST.

Key concepts of REST

  • Resources: Resources are nothing but entities in a business domain for ex.  Items, Vendors, Customer etc…
  • URIs: All resources are referenced using URIs (Universal Resource Identifiers)
  • Representations: It consist of 2 things Data that reflects current or desired state, meta data that provides description of data values. For ex. HTML, XML, JSON, Text files, zip, Images, Mpegs etc…

Limited Set of Methods

There are uniform interfaces like methods, operations, verbs

Verbs are actually HTTP verbs

GET

  • Retrieves a resource
  • Guaranteed not to cause side-effect (SAFE)
  • Cacheable

POST

  • Creates a new resource
  • Unsafe, effect of this verb isn’t defined by HTTP

PUT

  • Updates an existing resource
  • Used for resource creation when client knows URI
  • Can call N times, same thing will always happen

DELETE

  • Remove a resource
  • Can call N times, same thing will always happen

IMPLICIT INTERFACE DESIGN

  • REST does not call meta-languages to describe Structure of representations, Data Types used in representations, What operations are supported at a given URI, How input data must be sent for a given URI/Operation combination.

Why to Prefer REST?

  • REST is powerful, intuitive, and relatively easy to implement.
  • Light weight – not lot of extra xml markup as in SOAP.
  • Unlike SOAP it provides much simpler result that can be human readable.
  • It is very easy to build no extra toolkits are required.
  • Improve scalability of the application through caching and session state.
  • Custom URIs using URI templates
  • Consistency with design of the World Wide Web

Examples

Below examples are taken from one of our existing project & describes how the message size on the wire has been reduced to optimize the performance and reduce the cost overhead when the Bandwidth is concerned as per business need.

SOAP vs. REST

Above example clearly indicates that WCF REST services better takes care of Data usage size than the WCF SOAP services. Hence, whenever data usage size is a matter of concern, WCF REST is the way to go.