Posts Tagged ‘ASP.NET’

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.

A Quick Look at Model-View-Presenter (MVP) Architecture

Monday, July 12th, 2010

As UI-creation technologies such as ASP.NET and Windows® Forms become more and more powerful, it’s common practice to let the UI layer do more than it should. Without a clear separation of responsibilities, the UI layer can often become a catch-all for logic that really belongs in other layers of the application. One design pattern, the Model View Presenter (MVP) pattern, is especially well suited to remove lost of logic from UI layer.

Some noteworthy benefits of MVP pattern:

  • Platform independent: In this Pattern application make independent from its platform so when ever requirement comes to move to window to web or any other version its only need to change on code behind page for view Implementation, so later on required to any of the application portion convert in web to window or any other platform we can handle it by minimum efforts.
  • Loose couples form UI: So application stays loose couples from code behind page (UI) to business layer or any other next latter.
  • Useful to create automated unit test: MVP is purely loose couples from any plate form so that it is very use to prepare automated unit test cases.
  • Increase code maintainability: Keeps code more maintainable throughout the lifetime of the project, especially during the maintenance phase.

Overall Application Architecture:

mvp-diagram

  1. Model: Model is UI interface for how and what the data are needed to displayed.
  2. View: Show the representation of model, that can be build in presenter
  3. Presenter: Build all data for model and pass all data to model in form of view by communicating with services class( or business logic layer)

Below is the MVP patterns example with service class:

1. User Interface Layer

In this section contains actual UI, in .net terms its aspx or ascx pages.

2. Presentation Layer ( MVP :- Code behind + view (interfaces) + Presenter)

In this layer we have designed as MVP patters so it’s divided in below three parts.

a. View – It is interfaces. This interface contains signature of all properties and events that needs to implement in code behind page that will be use in presenter class.

I.e.

Public Interface Icustomer

ReadOnly Property CustomerName()

WriteOnly Property DisplayMessage()

End Interface

b. Code Behind (Model) – In this class we need to implement View.(No need to specify any logic). We are just implement properties which is defined in view.

#Region “Member”

Dim Presenter As CustomerPresenter

#End Region

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Presnter = New CustomerPresenter(Me)

Presnter.LoadData()

End Sub

ReadOnly Property CustomerName() Implements ICustomer.CustomerName

Get

Return textCustomerName.Text

End Get

End Property

WriteOnly Property DisplayMessage() Implements ICustomer.DisplayMessage

Set(ByVal value)

Response.Write(value)

End Set

End Property


c. Presenter - In this class we are using all those members which we have specified in view and implemented in code behind. Presenter class is responsible for execute methods of business layer.

Public Class CustomerPresenter

Private iView As ICustomer

Private SessionProvider As ISessionProvider

Public Sub New(ByVal view As ICustomer)

Me.iView = view

End Sub

‘Public Sub New(ByVal view As ICustomer, ByVal SessionProvider As ISessionProvider)

‘ Me.iView = view

‘ Me.SessionProvider = SessionProvider

‘End Sub

Public Sub LoadData()

Me.iView.DisplayMessage = Me.iView.CustomerName

End Sub

End Class

Summary:

  • MVP is little prolonged process to implement and understanding in the beginning, but later on it will be very useful as it provides application maintainability on application maintenance phase, increase code re-usability. A good thing about it is a clear distinction of different layers.  For example, all the code is separate from the user interface.
  • MVP is a strong consideration candidate for large scale projects especially where project maintainability re-usability are the key success criteria. It suits well with automated test cases methods also.

Leverage the Power of ASP.NET and Silverlight Platforms with WCF RIA Services

Wednesday, May 12th, 2010

It has always been difficult if not impossible to develop N-Tier applications. Though there were few applications framework some commercial and other few open source which helped the developers in building the apps based on the N Tier architecture and SOA principles. But the tables are now turning around; Microsoft has added one more jewel in their crown called WCF Ria Services, formerly known as .NET Ria services. I have been using this framework right from its raw bits and it is now in its RC2 stage. I must admit that that features have exponentially grown with every new release. It is now complete end to end application framework to build N-tier apps.

As the name suggests the framework in based on Core WCF (Windows Communication Foundation), which is a great enabler of SOA.As a developer using WCF Ria Services Framework you don’t have to worry about nities and grities of WCF. All that plumbing code is readily available to you from out of the box. But I recommend that knowledge of WCF can help you to troubleshoot your app develop on this framework. The framework uses the DomainService pattern, which is highly scalable pattern. It means that the framework can be glued to any UI Technologies, be it Silverlight, Ajax or Asp.net.The diagram below gives more clear idea.

WCFRiaClients

Gateway’s Customer Advantage

  1. You get your app developed in the latest technology with UI as Silverlight and all Domain Operations based on the WCF Ria Services. Asp.net Web Forms are now a decade old technology.
  2. Your application gets developed in true N-tier sense where the separation of concerns is also taking into the consideration by following MVVM pattern. This pattern is a great booster in Unit Testing.
  3. Your core business logic is given utmost priority because the developer is free from the plumbing logic code of various tiers as the framework is tightly integrated with Microsoft DAL Technologies like Linq and Entity Framework.
  4. Your offshore team can get started right away as Visual Studio 2010 provides the complete application template to develop the application based on this framework. So you save that precious hours ($) as developer does not have to assemble different projects and assemblies.
  5. Last but not least our technical expertise in this application framework.

Should you have any questions or feedback, feel free to post a comment and I’d be happy to discuss about that.