Archive for the ‘Technology’ Category

The Template Method Pattern

Monday, July 19th, 2010

The Template Pattern uses the inheritance beautifully to take advantage of code reuse. No composition is used because of the strict nature of the circumstances where this pattern should be used. The subclasses are bound to implement the abstract behavior of superclass and give the implementation in their own way and yet the sequence of algorithm is made unchangeable by making the method, of superclass which has the algorithm, final.

Definition: Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

When to use it: When you have a fixed algorithm to execute from a superclass and which must not be changed in sequence but should behave differently in subclass specific way then its good to use this pattern for

  1. Integrity reason of the algorithm’s sequence.
  2. Code reuse, if there are many subclasses which all depend on superclass implementation of certain functions which are of similar nature.

How to use it: Superclass will have certain methods, whose implementation is given by superclass itself and some methods which are defined as abstract, and thus, must be implemented by the subclasses. In this pattern, a superclass will define a method, which has a fixed sequence in calling some methods, we call it template method or an algorithm. Define this template method as final in superclass so that, subclasses can not change the sequence of algorithm and still contribute subclass-specific way by giving their own implementation of abstract methods. So the client will call the final method of subclass, inherited from superclass, and get the implementation of the algorithm in the subclass-specific way.

Example: The diagram 1.1 shows the initial design, where two different classes has an algorithm which has same sequence of methods but each having its implementation of those methods in their own way. Here, the same code is scattered across the classes.

Diagram 1.1

The diagram 1.2 shows the Template Method Pattern, where we take out the common behavior of subclasses into superclass creating a common point of change which will reflect to all the subclasses. We define the subclass-specific methods in superclass as abstract thus making mandatory for subclass to give implementation. Also, we create a new method, Template Method(on which the name is given to this pattern), by calling the methods in the sequence by which we want our common algorithm to be executed. And , defining it as final so that we are sure that no subclass can change the sequence and just give its own implementation.

Diagram 1.2

Conclusion: To conclude, the sequence,which must be same throughout the subclasses, is defined by the superclass and some part of the algorithm is executed by subclasses .Such design is a very good example of secure algorithm ensuring fixed sequence but with added touch of subclasses who give their own implementation.

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.

Smart and Effective Use of SQL Server’s Pool of Shared Memory

Wednesday, June 30th, 2010

Microsoft SQL Server has an effective pool of shared memory which ideally is used for two purposes .

  1. Data buffer;
  2. Execution plan cache.

It is commonly known that a query executed second time always gives response faster than the first time. In this post I’m going to discuss what works behind this and how can we make sure that the shared memory is effectively used.

What works behind this?
The shared memory part which is commonly known as execution plan cache (also known as procedure cache) save the execution plans of all the queries executed in SQL Server. When a query is executed this area of memory is looked into to determine if any of the existing execution plan can be re-used for this query. If the plan is not found then the query is parsed, compiled, optimized for execution and then the execution plan of the same is stored in the execution plan cache. That is the reason of queries working faster in subsequent time than the first time.

How to make effective use of execution plans
For each query executed in SQL Server an execution plan is saved but its not necessary that the execution plan stored is useful enough that its used for other queries also. To better understand this lets have an look how SQL Server saves the execution plan.

SELECT UseCounts, CacheObjType, ObjType, ST.Text FROM sys.dm_exec_cached_plans
cross apply sys.dm_exec_sql_text(plan_handle) as ST
ORDER BY ST.text



In the above screenshot let’s concentrate on the area which is in red. These three execution plans are the result of non-parameterized ad-hoc queries executed from the code of application inside an iteration. In this case none of the execution plans are effective, for each query a new execution plan is required. The query in the code was written something like below.

string sql = “SELECT * FROM URls where urlid=” + a;
where “a” is the varying value of the iteration

Had this query been a parametrized query only one execution plan would have been created and used for all the iteration. Let’s take an example to understand this better. Now my query would be something like.

string sql = “SELECT * FROM URls where urlid=@a”;
SqlCommand cmd = new SqlCommand(sql, myConn);
cmd.Parameters.Add(new SqlParameter(“@a”, a));

Now let’s have a look at the execution plans

In the above screenshot you would realize that only one execution plan has been created and its “usecounts” is 3, that means this plan has been used three time. Reusable execution plans means lesser CPU utilization , lesser utilization of memory for execution plan cache there by leaving more memory available for data buffer.

Conclusion
Though SQL Server maintains the execution plan of each query but making effective use of it is some what in our hands. There should be no piece of code in the application which is making use of ad-hoc queries it should always be parameterized queries. Though I personally prefer to use stored procedure since allowing direct access to the tables can be a security risk.

Entity Framework – Microsoft’s Step Towards ORM Building

Saturday, June 19th, 2010

Whenever we develop a new application, lots of things play key role to decide application architecture. Among these, database interaction is the major. In earlier days of .NET 2.0, no significant tools were available from Microsoft to create data access layer for database interaction. People had to use third party utilities for conceptual data modeling over the physical database.

Realizing this need Microsoft introduced LINQ to SQL for conceptual data modeling, though it comes with limited set of functionalities and can be used by SQL Server database only. To overcome this situation, Microsoft has taken steps to release new feature called Entity Framework with ADO.NET 3.5 SP1 release.

ADO.NET Entity Framework is an Object – Relational Mapping (ORM) framework. It builds on the concept of Entity Relationship Model by introducing a conceptual model, called the Entity Data Model (EDM) which sits between your code and the underlying schema (database). This abstraction helps a lot to reduce the efforts as well the complexity for moving relational data to object oriented programming.

Entity Framework architecture:

Here is how the Entity Framework is layered to abstract the relational schema of a database and present a conceptual model.

Entity Framework Architecture
  • Data Source: It represents one or many databases.
  • ADO.NET Data Providers: It will access data from data source.
  • Entity Data Model (EDM): EDM contains entity classes, storage container and mapping of the entity with the table.
  • Entity Client: It is an ADO.NET managed provider that supports accessing data described in an EDM.
  • Object Services: This component enables you to query, insert, update, and delete data, expressed as strongly typed CLR objects that are instances of entity types.
  • Entity SQL (ESQL): It is a derivative of Transact-SQL, designed to query and manipulate entities. Both Object Services and Entity Client components can execute Entity SQL statements.
  • LINQ to Entities: It is used to query against entities defined in the EDM.

Advantages:

  • You can use the Entity Framework against not only SQL Server but also Oracle, DB2, Informix, MySQL, Postgres etc with the help of its data providers.
  • You can create data access layer with the ease of Entity Framework wizards. Developer can work with data rather than coding against rows and columns.
  • It is truly a foundation stone for Microsoft’s data access platform. one of the use of this platform  is REST based ADO.NET data service aka Astoria.

How to build: (more…)