Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Sunday, February 27, 2011

Why RepositoryBase?

Repository pattern suggests using a base for repository layer objects, either through an Interface or an Abstract Class. The benefit is, in addition to reuse of the shared logics, testability.

When a Repository has a base, we can build its client only referencing to the base, instead of the concrete repository class, and exposing interface for DI (Dependency Injection). Then we can test the client with a mock Repository instance. That makes testing of the client code very easy, without really calling to the database.

Following code snippets shows the big picture.

class BlogRepoBase
{
// create a mockup BlogEntry list in memory
private List _blog = new ...;

//public override interfacing methods;

// shared protected methods;
}

If use Interface, we can take out the public interface members into a seperate Interface:

interface IBlogRepo
{
// public interfacing method
}

Nevertheless, we also need a base class in order to create the in-memory fake data instance and shared logics.

class BlogRepoBase
{
// create a mockup BlogEntry list in memory
private List _blog = new ...;

// shared protected methods;
}

Now we can create a variety of concrete Repositories inheriting from the base, e.g. a FakeBlogRepository

class FakeBlogRepository : BlogRepBase, IBlogRepo
{
// the implementation ...
}

Next, suppose a Controller uses the Repository, we put code like:

class BlogController: Controller
{
private IBlogRepo _rep;
public BlogController() : this(new RealBlogRepo()){ }
public BlogController(IBlogRepo rep){ this._rep = rep;}
}

Now we can test the controller,

[TestMethod]
public void ShowBlogEntriesTest()
{
// arrange
var rep = new FakeBlogRepo();
var ctr = new BlogController(rep);

// act
var result = (ResultView)ctr.Index();

// assert
CollectionAssert.AllItemsAreInstanceOfType()( (ICollection) result.ViewData.Model, TypeOf(BlogEntry));

}

Wow, you see how we have achieved testability with the Interface! Next, we take a look of creating the real Repository. There are different ways. A typical way is with EF(Entity Framework).

class EFBlogRepository : BlogRepBase, IBlogRepo
{
private BlogEntryEntity MapTo(BlogEntry entry)
{
return new BlogEntryEntity()
{
P1 = entry.P1,
P2 = entry.P2,
...
}
}

// public override repository interface methods

}

It is not uncommon that these public methods are implemented with EF functionalities and LINQ operations, but one may wonder why do we need the MapTo function? The simple reason is that we don't want to expose BlogEntryEntity that is created by EF and dependent on EF. We just want to constrain the XxEntryEntity classes within the repository layer, but not beyond. So we create XxEntry, that is used across application layers.

This totally makes sense, but there is an argument on how we define XxEntry classes. Would we define them as having exactly the same properties as XxEntryEntity, or would we defined them inline with the ViewModel? Theoratically, ViewModel works on top of XxEntry (suppose we call it Domain Model, while call XxEntryEntity Data Model), because View Model addresses the concern of Views and the related validation rules and so forth, while Domain Model is the data used to define business logics.

So we end up having DataModel, DomainModel and ViewModel. In practice, if there is not much business logic out there, people define Domain Model as ViewModel, because in this way we decreases redundancy of code.

This article has examined using RepositoryBase to achieve testability. Also, we examined DataModel, DomainModel and ViewModel and why we need mapping among them.

Tuesday, September 21, 2010

Measure Execution Time with "Using"

To have an instrument measuring code execution time could be very desired when optimization of an application is a high concern. We've seen code doing that, but it's through the way of putting code to record the current time before and after the to-be-measured code block, it then calculates the duration and outputs the result or generating logs. It works. But obviously it is tedious for a developer to implement here there in the code. It also messes up the business code flow by adding time-measuring code snippets. C# language's "using" element provides a clean way to maintain a live instance context without developer caring about disposal of the instance. Is "using" can be used to measure execution time? Yes, I wrote a "watch" and I am "using" the watch measure time. lt looks pretty cute.

The Watch class

using System;
using System.Text;

namespace Instrument
{
public class Watch : IDisposable
{
DateTime _begin;
DateTime _end;

// ref string x; //c# doesn't have ref
//object _ret;
StringBuilder _ret;
public Watch(out StringBuilder ret)
{
ret = new StringBuilder();
_ret = ret;
_begin = DateTime.Now;
}

~Watch()
{
// can not rely on GC's call

}
public void Dispose()
{
_end = DateTime.Now;
_ret.Append((_end - _begin).ToString());
}
}
}


Example of "using" the Watch to measure execution time

StringBuilder span;
#if DEBUG
using (Instrument.Watch wat = new Instrument.Watch( out span))
{
#endif
Console.WriteLine("elapsing...");
Thread.Sleep(1000 * 5);
#if DEBUG
}
#endif
Console.WriteLine(span.ToString());


How it works
Under the hood, "using" creates and disposes an instance without developer writing any code. So I have my Watch implemented Idisposable, when the "using" scope is over, the .Net runtime calls the Dispose method, where the time span is calculated. The execution time of the code part included in "using" block is exactly the time the using scope lives.

Then I need to pass back the result to the caller. Originally I want to pass a reference of a string variable, and assign the result from within the Watch, but it doen't work. As a workaround, I use StringBuilder type, that is a reference type, and there is no warries with it.

To measure execution time is part of optimization. As such, I may want run the function only in development and testing code, without in production, one solution is using conditional compiling, I show it in above code.

Monday, June 7, 2010

Session Pattern

Following figure shows a scenario where a number of clients accessing a server.

In order to improve efficiency, maintaining a session context makes perfect sense. Data and resources that a client uses repeatitively are held in the memory cache.

This pattern is well-known in web applications and database connection pooling.

Following points characterize this scenario:

1. The linkage is temporary;
2. The server doesn't rely on client issuing a closing message to release session data;
3. Resources and data accessed through the linkage identifier as the key;

This pattern works in the following approach:

1. Clients access server with a unique session identifier as part of the request;
2. The server is preset with a timeout value, which controls when the session to be removed or reclaimed as with pooling;

Thursday, May 27, 2010

Make .Net App Blackberry Sniffed

Blackberry, and other modern handsets as well, are not just phone, emailer or messenger only, they are gaining ground as web application terminals. In my current application, Blackberryers can view business data and take actions on their business just with their handset.

As a designer/developer, I am trying to find out a general pattern to facilitate a whole web application Blackberry sniffed, instead of, as some applications did, just sniff a couple of pages. Here is a solution I worked out:


1. BBSniff base page
Create a base page so as to avoid sniffing on each portal page.

class BBSnifferPage : System.Web.UI.Page

2. Routing
In Init event of the base page, implement sniffing and routing logic. There are three cases:

A. A regular browser request;
B. a Blackberry request and the BB version page is available;
C. a Blackberry request and the BB version page is not found;

Following code shows the implementation:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);

// sniff and route
if (!IsBB())
{
// Render current page for regular browser
Response.Write("<b>This is for IE, Firefox etc.</b>");
}
else if (!IsBBFileExist())
{
// BB version page showing no bb version for requested page (this page)
Server.Transfer(System.IO.Path.Combine("bbPages","NoBBVersion.aspx"));
}
else
{
// render BB version page
string[] parts = Request.Url.PathAndQuery.Split('/');
Server.Transfer(System.IO.Path.Combine("bbPages", "bb" + parts[parts.Length - 1]));
}
}

3. BB Page Convention
In order to redirect requests to their BB pages, a convention for storing that pages is needed. In following example, all BB pages' name starts with "bb" and followed with the portal page name, and all BB pages are stored under "bbPage" subfolder.

private bool IsBBFileExist()
{
string[] parts = Request.Url.LocalPath.Split('/');
string fileName = parts[parts.Length - 1];
return (System.IO.File.Exists(Server.MapPath(System.IO.Path.Combine("bbPages", "bb" + fileName))));
}

4. Portal Pages are BBSnifferPage
Because all portal pages are exposed to web access, they are suggested to be Blackberry sniffered.

class FuncPage : BBSnifferPage
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<b>This is for Black Berry. </b>");
}
}

5. BB Function Page
The corresponding BB pages of portal pages are regular web pages.

class BBFuncPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<b>This is for Black Berry. </b>");
}
}

I believe this is a easy-to-apply, easy-to-maintain, loose-coupling framework for blended browsers support.

Friday, May 14, 2010

AOP with Spring.Net

AOP - Aspect Oriented Programming, coined by Xerox long time ago, shines again lately. Because it is a way to separate cross-cutting concerns such as Cache, Log, Performance Monitoring from the business process in a non-invasive way.

This led me to think about abstraction - by making a level higher abstraction, we get more valuable information to use, as levels of differentiation in Calculus.

In a OO world, AOP is all about defining scheme to apply certain functionality onto classes or methods that has something in common. To me, it is a level higher of abstraction on top of classes and methods that, in turn, are abstraction of the real world.

Spring.Net AOP called the functionality advices. To be able to be adviced, a class has to implement ICommand:

public interface ICommand
{
object Execute(object context);
}

public class ServiceCommand : ICommand
{
public object Execute(object context)
{
Console.Out.WriteLine("Service implementation : [{0}]", context);
return null;
}
}

Then we define an advice,

public class ConsoleLoggingAroundAdvice : IMethodInterceptor
{
public object Invoke(IMethodInvocation invocation)
{
Console.Out.WriteLine("Advice executing; calling the advised method...");
object returnValue = invocation.Proceed();
Console.Out.WriteLine("Advice executed; advised method returned " + returnValue);
return returnValue;
}
}

Now we need define relationship between an Advice and an advicible target, once a method in the target class get executed, designated advice is applied.

ProxyFactory factory = new ProxyFactory(new ServiceCommand());
factory.AddAdvice(new ConsoleLoggingAroundAdvice());
ICommand command = (ICommand)factory.GetProxy();
command.Execute("This is the argument");

Spring.Net simply wraps up a method call with Reflection feature and tweaks around. Because ProxyFactory returns with ICommand, advicible targes have to implement the interface. This is obviously a limitation, as thus existing normal classes are not advicible. Spring.Net promised to change in future version.

In practice, of course, declarative and through configuration is prefered.

<object id="consoleLoggingAroundAdvice" type="Spring.Examples.AopQuickStart.ConsoleLoggingAroundAdvice"/>
<object id="myServiceObject" type="Spring.Aop.Framework.ProxyFactoryObject">
<property name="target">
<object id="myServiceObjectTarget" type="Spring.Examples.AopQuickStart.ServiceCommand"/>
</property>
<property name="interceptorNames">
<list>
<value>consoleLoggingAroundAdvice</value>
</list>
</property>
</object>

Above configuration just says the mapping between advices and targets in a different way. Spring.Net now knows everything needed. What we need to do is run the adviced method to check if it is really take the advice.

ICommand command = (ICommand) ctx["myServiceObject"];
command.Execute();


Ref:
1. http://www.springframework.net/doc-latest/reference/html/aop-quickstart.html#aop-quickstart-introduction

Wednesday, April 28, 2010

The WorkflowRuntime Pattern

.Net WF facilitates the idea of decoupling business activities and the overall controlling logic. In that model, specific granular business activities are developed in terms of workflow first, and then they are assembled into an application with the medium of WorkflowRuntime.

Technically WF brings a pattern how to integrate workflow oriented development. Specifically, an application holds a WorkflowRuntime (Sure it holds multiple runtimes on branched threads) and a signal(s) for synchronization with the main thread of hosting application. By assigning a WorkFlow type and a callback handler delegate, the runtime then creates the workflow instance, executes on it, and call the callback delegate upon finishing. A sample code shows on List 1.

List 1: Use WorkflowRuntime synchronization

using (WorkflowRuntime r = new ~()){
AutoResetEvent waitHandle = new ~();

r.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e){
waitHandle.Set();

}

WorkflowInstance ins = r.CreateWorkflow(typeOf(WorkflowApp.Workflow1));
ins.Start();

waitHandle.WaitOne();

}

A WorkFlow instance runs on a backend thread, where it can be synchronized with the main thread or other threads with WaitHandlers.

Monday, December 21, 2009

Common Knowledge of Optimization

For a web application, we can improve system performance in the following respects:

Web Layer
Slim the javascript. Tools do this job by stripping unnecessary white spaces, renaming local variables.
Manage ViewState - remove all the unnecessary view state data. some pages don't need view state, we can turn off this feature.

We also can use platform feature - web servers support gzip to compression the load from client to server back and forth.

Web farm is a system level approach to achieve higher performance. In respect of code, we need to take care of the following two issues:

Use universal session solution by set up database session repository;
Uniform of the ViewState key - view state is encrypted by .net framework - we need to setup the encryption key for each server of the web farm with the same explicit value

Database Layer
In addition to using query optimizer, denormalization and such from the perspective of design matter, use database server provided performance monitor to help finding the bottleneck and improving performance.


Middle Tier
An advised way would be adding trace log to major business methods to catch their execution time and times called, so as to find which the critical component to improve performance.

In addition, parallelize coding by multi-threading, forking web service calls. For example, instead of:

svcA();
svcB();
svcC();

we can do:

svcAAsync();
svcBAsync();
svcCAsync();

then use WaitOne or WaitAny or WaitAll to syncronize (join) the treads.

Using proper memory model in our code is also important. e.g. when a string involves a lot of changes, we should use StringBuilder rather than string data type, because, every time change the value of a string, system will create a new string with the new data and abandon the old one. With StringBuilder, it is much faster because it is a chain of nodes.

Tuesday, December 15, 2009

The Trend of Web UI Development

When it comes to Web application development, new ideas seem endlessly emerging. Definitely a lot of great people are there in this paradigm keep come up with great imagination and amazing ideas.
Like any other part of a software application development, Web UI is evolving from heavy framework controls, such as Asp.Net, JSP etc. to light weight frameworks such as JQuery, Dojo.

Here we definitely need a change, we really need a higher layer on top of the html, javascript and css ground, but higher than that, so that we don't need to reinvent the wheel every time.

In respect of css development, a number of "css frameworks" are there. A framework is something laying a foundation that we can work on to achieve something much easier than not having it. Blueprint is a css framework, for example, that we can define css on top of for our application, in stead of working from scratch.

JQuery and Dojo are javascript packages for develop Ajax centric application. Both of them give power to Web UI through widgets - combination of CSS, javascript and html. In the core, they facilitate DOM traverse by defining kind of query language with innovative vocabulary.

Here is an example of Dojo. You will see the invention of new vocabulary on top of javascript language.


<script type="text/javascript">
dojo.requir("dojox.widget.FisheyeLite");
dojo.addOnLoad(function(){dojo.query("a", dojo.byId("myParagraph")).forEach(
function(n){
new dojox.widget.FisheyeLite(
{properties:{
fontSize:1.50,
letterSpacing:2.00
}},n);})
.connect("onclick",dojo,"stopEvent");});

</script>

Monday, December 14, 2009

Reuse via 'Sourced In'

Seperating concerns, reuse and maintainability are among the most essential principles in software engineering. These principles can be seen everywhere through the frameworks we use at work, such as MVC pattern and IOC. CSS is probably the everybody-know separation example.

When we decouple a monolithic problem space, we get better understand the domain of the given problem, what is the boundary and how the system communicate with outside world. As well, we get better understand what is the responsibility of each part that comprises the whole system.

CSS allows common style elments separted from html files and defined in an external file that can be "souced in" by several pages. When it comes to any change, we only need to change one file, rather than in each page individually. This reduces possible errors, inconsistencies and saves efforts. This is the essence of reuse.

CSS also comes with inheritance feature, we can reduce duplication by sharing style classes. We can also "source in" css with a css with @import as seen in W3C CSS2 Spec.

Another example is Struts Tiles. It is something similar to Master Page in ASP.Net. It provides a framework to support separation of JSP pages into "tiles" which are then used to assembly pages in a shared manner. A page can include certain number of tiles and a tile can be used in multiple pages. Even better, all these assembly information blueprint is defined in an xml configuration file - declarative decoupling.

Sunday, December 6, 2009

Dependency Injection

Dependency Injection, also called IoC - Invertion of Control, originated from Martin Fowler's famous article Inversion of Control Containers and the Dependency Injection pattern. Basically the idea is "let the outside caller provide the desired implementation."

For example, when accessing a service, instead of holding a reference to that service, a software component provide a property that can hold that type of reference, when the object is created, a service implementation reference is automatically injected into the property.

Here is an example with factory pattern:

public class DAOFactory
{
public static T Create<T>()
{
IDatabase db = Registry.Fetch<IDatabase>();
T dao = Registry.Fetch<T>();
dao.Database = db;
return dao;
}
}
ICustomerDAO dao = DAOFactory.Create<ICustomerDAO>();


when dao is created, the Database reference is automatically injected by the factory method, rather then with code by dao itself.

Why IOC? one good reason is that IOC gives more power for decoupling componments, as a result, unit test is a lot easier. Actually, there are already dependency injection frameworks out there to provide mock components to facilitate unit test.

Based on Martin Fowler, there are three types of injection: Constructor, Setter and interface. Injection can also be defined with configure file, that gives more flexibility to assemble an application.


SOA - service oriented architecture, ervice - a set of business or functionalities. In SOA development, usually use configure mechanism for deciding which implementation gets injected into an object.

It is kind of implementation of ObserverFactory pattern.

Tuesday, December 1, 2009

IoC, Configure Workflow Runtime

WorkflowRuntime is to run an workflow instance. The way it does requires adding the
workflows to it (register if you like) before running it. Of course we can add it through code; However it is rigid. The most flexible and liked way is do IoC with app.config file. The following snippet shows the two ways.

// with hard code
instance.AddService(new MyWorkflow(p1, p2));
instance.AddService(new MyWorkflow2(p1, p2, p3));
instance.StartRuntime();

// with app.config
-configuration
--configSections
---setion name="WorkflowRuntime" type=""
-WorkflowRuntime Name = ""
--CommonParameters
---add name="" value=""
-Services
--add type=""

To run a workflow:
//instance.CreateWorkflow(Type WorkflowType, Dictionaryparameters)
instance.Start();

With values set in the configure file, new instance of WorkflowRuntime will reflect that configured values, as a result it already has the services we want to add. In this way, we can add different services to the runtime without needs of change code or recompile code.

Wednesday, October 1, 2008

Strong and Weak Dependency

By S.Luann

Dependency between classes could be strong or weak. If a class just has a reference to another class without accessing it's members, it is a weak dependency, because changes in the referenced class won't affect the referencing class code. In contrast, if a class has reference to another class and access it's members, the relation ship is strong dependency.

In my idea, strong dependency can be noted with sold line and an arrow, while a weak dependency uses dash line with an arrow.

I found this issue when implementing proxy design pattern.



class Client
{
void CallMethod()
{
private ISubject proxy = new Proxy();
proxy.doAction();
}

}

interface ISubject
{
void DoAction();
}

class Proxy : ISubject
{
public void DoAction()
{
// implementation
}
}

class Proxee
{
public void DoAction()
{
// implementation
}
}


In above code, class Client has dependency to ISubject and Proxy, but the dependency to Proxy is weak dependency while to ISubject is strong.

Monday, September 22, 2008

Factory Method Design Pattern

There are different uses of Factory Method design pattern. but not make much sense to me. I believe this pattern is to create an instance from a class you don't exactly know, otherwise it is not that necessary.


The following is my way:

static void Main(string[] args)
{
Creater creater = new Creater();
Product product = (Product)creater.GetProduct(typeof(Bike));


product.name = "red flag";
product.model = "man";
if(product is Car)
{
Bike bike = (Bike)product;
bike.style = "light";

Console.WriteLine(string.Format("{0}-{1}-{2}", bike.name, bike.model, bike.style));
Console.ReadLine();
}

}


abstract class Product
{
public string model;
public string name;

}
class Bike : Product
{
public string style;
}

class Car : Product
{
public string produce;
}

interface ICreater
{
object GetProduct(Type type);
}

class Creater
{
public object GetProduct(Type type)
{
return Activator.CreateInstance(type);
}
public object GetProduct2(Product product)
{
return Activator.CreateInstance(typeof(product));
}

}


For further research:
http://www.ondotnet.com/pub/a/dotnet/2003/08/11/factorypattern.html