Wednesday, June 16, 2010

Moving my house to weblogs

Dear everyone,
This morning I received the email from Microsoft that they just created for me the blog at I really happy about that and decided to moving my house from Blogger ( to blogs ( If anyone want to read some articles at Blogger, you still read all of it at those. I will not move all articles to weblogs, and in the future I will try to write new articles at blog. I hope anyone will support me in that. And in next time, I will try to finish the NMA project at codeplex.
Sorry for this inconvenience! 

Thursday, June 10, 2010

Cast anonymous types

Today, when coding for one module in my project at company, I had a problem that make me crazy. Used var keyword on .NET 3.5, it's a anonymous type, so when we go out its scope, we don't know its type. I think many people also had this problem like me. So after using many methods for solve this problem, I also found the best solution for it. Thanks Alex for best idea from him! Now there are some my effort for solve it:
+ First thing, I tried to coding and gave this error:
                 Cannot cast 'exampleObj' (which has an actual type of '<>f__AnonymousType0<string,string>') ...
+ Next, I started my working for solving it. Wrote the extension method for cast anonymous method:
+ Object that content the anonymous type:
Binding this object to ListView:
+ And used the extension method for cast anonymous type:
Now we can use it very normally:
+ References:

Tuesday, May 25, 2010

Implementing Service Locator pattern

Today, I will write about Service Locator pattern. Reason, because I must make sure that all thing shall run well up to now on NMA project.

The first thing, we should mention about the theory. So what is the Service Locator? In Java community, they defined it is
"The Service Locator abstracts the API lookup (naming) services, vendor dependencies, lookup complexities, and business object creation, and provides a simple interface to clients. This reduces the client's complexity. In addition, the same client or other clients can reuse the Service Locator"
But this definition also don't make you clear about Service Locator. I only give you one example as: Do you know your manager in company? Yeah, you must know him/her. But now, I suggest you a orther question, do you know about all employees in your company? Maybe you know all. But with me, I don't need to know that. When I want to find some information about the employee that work in my company, I only contact with my Human Resource Manager (HRM). So he will give me full of information about this employee. Now come back to our situation about Service Locator, you can imagine your HRM is a Service Locator. You don't need know full of information about all employees in company. He will keep all information for you, and that is his work in company.

Now if you want to know more clearly about Service Locator, you can reference to the article that had written by Martin Powler. I will give you all links at a bottom of this post.

So why do we use Service Locator? Because Service Locator make you free in your work, you don't need care about detail implementation of dependency classes. You shall assign this task for Service Locator, so you have much time to concentrate other task in your project. Service Locator will help you managed life cycle of all instances in your project (maybe its task do by Structure Map). All class only know about the contract (here is interface and abstract class), so it make your components don't couples each other. Your components shall be easy to re-use, maintain,...

Nearly 3 months ago, I read some articles said that Service Locator is a anti-pattern, hard to Unit Testing the dependency class, but I also find method to avoid it. I think you need research about Opaque dependencies and Tranparent Dependencies.

And now is the time I will show you about my work in NMA project. In MNA, I used Microsoft Service Locator that integrated with Structure Map for taking care all components in MNA. You should download the Structure Map adapter at here into your computer and try to build it. After you built successful, you are able to reference it in your solutions. In my solution, I combined Service Locator with Bootstrapper for building unify system in NMA. This is my code:
If you used to read about my Bootstrapper article, you maybe saw this code. But anyway, it's not make you disturb! I continue implemeting the concreate class as:
In this trunk of code, you only need notice some lines code as below:
I registered my Service Locator and used Structure Map adapter in this function. And that is all thing I want to shared with you. Now we only need new the Bootstrapper, so your Service Locator will register with it, and all components of own application shall be available to using.

+ References:

Thursday, May 20, 2010

Implementing the Bootstrapper for your application

Do you know about Bootstrapper?
If you don't know about it before, I will explain it now. If you used to turn on your computer, you shall see that you only are able to work when your operating system (OS) ready to booting. And underline your computer must do many works for preparing your OS. You can't see those, it only run underline. That is a bootstrapper task. You shall not be care about all task that run under OS, you only need working. Do you agree with me? Yeah! If you agree with me, you understood the jobs that Bootstrapper take it to you.
Now is the time that we come back to software world, How are we able to boot all our tasks in software (include Windows Form & Web)? And why must we run bootstrapper in our application? The second question, one articles can answer for you at here. And the first question I will answer for you after my post end. OK now we shall start to preparing all thing for implementing the Bootstrapper at below:

+ First thing, we must define the interface for the contract in each task:
+ Next, I will implement the abstract class for compositing all functions that I think I can re-use:
+ And I continue to implement sub-class for CommonBootStrapper that I just implemented:
+ Don't confuse about some messy thing in my code. Because I copied it in NMA project, so it have many things (StructureMap, Automapper, Fluent NHibernate,...) in it. But if you follow all post at my blog, I will explain all thing for you. Now continue, we shall implement one class for registering Automapper task when my application started:
Please go to for clear about AutoMapper.
Certainly, you can inplement many tasks for booting, such as setup action filter, add model binder, add custom view engine,...
+ Finally, we shall call it in Global.asax for web or App.xaml in WPF. But in this post I only implement in web:
At here, I used StructureMap for scanning 3 dlls: NMA.Infrastructure.NHibernate, NMA.Application, NMA.Infrastructure.AutoMapper for finding all tasks in my application.
I implemented scanning dll at CoreRegistry.cs, and this is the important function inside this class:
As you see this function will find all class that implemented interface IBootstrapperTask. If you implement it in any other dll, you also show it for Bootstrapper.

* And I answered for you the first question if you read all my post.
In past time, I also suggested this ideas for Deran Schilling and he also implemented very excellent post at here.
OK, I just finished the post about Bootstrapper, if you don't want to implement from scratch, you can use Unity Bootstrapper that mention at here. But it use Prism on WPF.
Finally you can find all my source code on NMA project. Good bye and see you next time!

Wednesday, May 12, 2010

Publishing a open source project on CodePlex

In 2 days later, I published NMA project on CodePlex. Now you can access to my project with URL Now I'm trying to finishing this project. I finished the all layers except for UI layer. And now I 'm designing the GUI for it.
In next post, I intend to writing the series posts about NMA project. Some posts that I wrote in past as:

Hope I will write many posts in future!

Thursday, May 6, 2010

Unit testing uses NUnit in Visual Studio 2010

Have you ever used NUnit in Visual Studio 2010?
If you used it once times, I thought you shall be realized the problem at here. NUnit can't run on .NET 4.0. So how can I run it when I writes Unit Testing? There is have a little trick for running it well. You only added some line of XML in configuration file of NUnit. And this is my work:

Finding the tag and adding the configuration tag is . And the result is

Hope it is useful trick for you!

Wednesday, April 28, 2010

Customizing controller factory used Structure Map

I recently started to working on new version of ASP.NET MVC 2. And the first thing I must to do is customizing the controller factory to using IoC for getting controller type. In the first stable version of ASP.NET MVC (1.0), I had done it, but in this version it had some thing changed. In special, when you inherited from the DefaultControllerFactory class it didn't have the RequestContext instance to the constructor. In the version 2, the constructor is have 2 parameters.

But why do you need customizing the Controller Factory? That because you need injecting some instances to the constructor of Controller. For example, you coded the CategoryFacade class and wanted to injecting into the CategoryController for getting some data from Database. this is a situation that you need customizing the Controller Factory.

Now, we started to implementing it. The first thing you need is inheriting the DefaultControllerFactory class:
In my case, I used Structure Map  for IoC container. And in my Registry class, I need scanning the Web assembly as below:

Now, we must notify for ASP.NET engine for it can understand my custom Controller. How do I make it?. It's really easy, I implemented as below:
Don't confuse about it. At here, I only implement the Bootstrapper for my application. So don't care about it. We only concentrate on the ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()). As you see I replaced the default Controller Factory with my custom Controller Factory.

Next step, we need registering all my configuration, so when the website started we shall have all instances to using. In this post, I implemented the Bootstrapper for booting the Website. So we only write the simple line of code as below in Global.asax:

As you see, we registered all Areas and continued to booting my website by the Bootstrapper. Just simple thing! Now saving all codes, and press F5 in Visual Studio's IDE. We shall possible injecting the Category Facade instance as here:

Finally, in order to writing this post, I referenced many articles from Internet. And this is my resources:

Tuesday, April 27, 2010

Configurating the AutoMapper

Have you ever configured the AutoMapper for your Application?

I really impressed with AutoMapper's Jimmy Bogard. If you aren't try it before, I advice you should try it now. It's so good for mapping objects (maybe entity to DTO). I still remembered I take many time for writing mapping objects in past. But now with AutoMapper all thing is simple. Now I'm trying to collecting all best practices that I learned from co-worker and Internet, trying to implementing the project (it's not publish yet). And when implemented the AutoMapper for my Application, I also get some problems from it. So finally, I also finished my work. Now I will show it for you.

In this post, I used Bootstrapper for booting my Application. I attend to writing a post about it later (comming soon :D). So I need when my Application run, I will have any thing I need. So I will implement IBootstrapperTask for it. Next, I used the StructureMap for scanning all assemblies implement
IBootstrapperTask interface.

And there are some code as below:

+ Registry class (implement Registry class from Structure Map)

+ Profile class

+ AutoMapperConfigurator class

As you see, it's seen very easy (^_^). I'm many thanks to some articles that I read in Internet. In specially, I really referenced to 2 articles as below:
Good bye and see you next post!

Friday, April 23, 2010

Converting Expression Tree

In this articles, I'm going to divide my post into 3 sections: Problem, Design, Solution.
  • In Problem, I will describe about the problem that I got in my implementaion
  • In Design, I will show all method that I used in my implementation
  • Finally, I will show you my solution that I used for finishing my this article.
Now, I start with Problem section. In my solution, I built some entity and in the Facade layer I wanted to export my entity to UI layer, but in Design Principle, we shouldn't expose my entity to UI layer. We can figure out it same with the shell, with my Facade layer is a shell of application. And now, my problem appeared, if I try to expose the service with Expression Tree (maybe Expression<...<Entity>>) is a parametter. At here, I just want to expose the service with Expression<...<DTO>>. So, how do I do that? Maybe I must to convert the Expression Tree from my entity to my DTO (Data Transfer Object)

That is my problem, and now I will show you about my Design for solving it. The first thing, I can do for now is introduction about Expression Tree (ET) in .NET. Do you know about ET?
"In general, expression trees are special kind of binary trees. Binary tree is a tree in which all nodes contain zero, one or two children. Why expression trees have been implemented as binary trees? Mainly because binary trees allows you to quickly find what you are looking for. The upper limit of steps necessary to find required information in binary tree equals to log2N, where N denotes the number of all nodes in a tree."
Do you know the difference between Lambda Expression (LE) with the Expression Tree? All of people didn't know about it, so I will show you now.

LE is a wrapper of delegate function in .NET 2.0. And in the .NET 3.0 above, we wrap it with Func, Action, Predicate key word. So you can call the delegate function so easy and readable. Now we change to ET, as you saw in the definition above, did it make sense for you? ET is only a Data Structure contains the LE. You can figure out that you must transfer your object through the wire, and this is the place that ET participate in. Because ET is a Data Struture so when you transfered it to the UI layer, you must compile it into the LE and call LE to executing it. I hope you clear about this procedure. And the last thing I want to show you: "only using the ET when you want to transfer your object through the wire, maybe SOA architecture"

That definition about ET & LE is so far, I will turn back now. So what Solution will I use to make it working in my code? In my Application layer, I used AutoMapper for mapping my entity with my DTO, and all thing it worked normally. Only one thing, the ET wasn't converted.And this was a place that I must to working.

Go go, I start to introducing my code for you. My entities design is

And my entity code is

The DTO's code is

Now I must to writing some code for my Repository class.

And in the implementation for Repository is

Finally, I implemented the Application layer is

Do you see the line: var lambda = LambdaExpressionHelper.Convert(condition, identifyColumn);
That is my work, we are to divide the helper into 3 classification:
  • x => x.Name == "name"
  • x => x.Id == Guid.NewGuid()
  • x => x.CreatedDate.CompareTo(DateTime.Now) == 0
So I will show you the detail of it at here:

And the finally, we shall wrap it into a helper function at here:

In the unit testing, I executed unit testing for this and the result is:

IMHO, Maybe have many method for this convert, but It's my work, and I really appreciate to anyone who comment for improving my post. Thanks!

You can reference to for clear more about Expression Tree..
@Martinez: Really thank about your articles!

    Tuesday, April 20, 2010

    Mocking the Lambda Expression method

    Today, when trying to unit testing for some code in Specification class, I just found that "It's very difficult to mock the Lambda Expression in code". But I also try mocking it in 2 hours and I mocked it perfectly (:D). And my work start now

    + First thing I have the class as:

    As you see the red rectangle, we have the Lambda Expression like this Expression<...>>, so we must to mock it for unit testing (I used Rhino Mock for mocking object in my test fixture). And now I want to show you the UserRespository class as below:

    Don't refuse about that, we only demonstrated about this function for my post. Don't care about other code in this function. We shall pass the Lambda Expression (LE) for executing in run time. So how do you mock this LE? It's not secret for anyone, and now I will show you about it

    Pay attention to the red rectangle, I mocked the LE using Rhino Mock. As you see, it's very simple, we only supposed that the LE is not null and expected that if it's not null we shall return true for it. IMHO maybe have many methods for mocking the LE but anyway this is my working for it.

    Tuesday, March 30, 2010

    Validating ViewModel use Regular Expression

    What do you think about Regular Expression(RE)?
    Today, when working on RE in Validate ViewModel (used DataAnnotation), I just found important thing in RE. After reading about it, I implemented something very interested in it.
    For examples:
    In bussiness rule request me validate for string not contain any speial characters. So I can use this pattern ^[(0-9|a-z|\s|A-Z\.)]*$. It's so good. We can used this tool for validate string.
    I also found useful stuff at here. This is very easy for understanding. In real working, RE's really important, and it make my work is easier. But we always had some problems when using it :D.

    Thursday, March 25, 2010

    Five Rules for IOC container

    Today, I found the interesting article about 5 rules in using IOC container. And I really eager about it. In this article impressed in Service Locator is dead, and we need saying no with it. That is five rules about using IOC container:

    + Rule 1: Store in IoC container only services. Do not store any entities
    + Rule 2: Any class having more then 3 dependencies should be questioned for SRP violation
    + Rule 3: Every dependency of the class has to be presented in a transparent manner in a class constructor
    + Rule 4: Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies
    + Rule 5: IoC container should be explicitly used only in Bootstrapper. Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container

    Inspite of it really old, publishing in 2009 but this article have something that I interested in. And we need make sense about Opaque dependencies and Tranparent Dependencies. What happen here if I use opaque denpendencies? It's make your class very hard for unit testing because it's seen hidden dependency class in your class. So you don't know to testing your class anywhere.In this articles of Mark Seemann, he's only showed for us about Oquaque Dependencies and he talked Service Locator is anti-pattern. But according to me, if we can use Transparent Dependencies, we can realize that Service Locator still use in the other context, and make your class don't know anything about existence Service Locator on it. In this articles, malovicn also showed for us about using internal key word for internal constructor, it's really useful for us when design the class that using Service Locator

    Thursday, March 4, 2010

    Differences between Custom Service and RESTful service

    Up to before read this articles in MSDN magazines, I still know very implicit about RESTful service and Custom Service. Now I can define it as "Custom service is define orient-operator and RESTful service is define orient-resources". It's really make me clearly about ADO.NET Data services. And I think it will be development in the future (.NET 4 and Entity framework 4)

    Friday, February 12, 2010

    Active Directory Role Provider

    Time passed very past. Today, it's very near Tet holiday. And I found a article from Mr. Thoai Nguyen, my co-worker at Hvn. It's really cool and useful for my work at company. I want to shared to all you about it. Click here for it

    Monday, January 25, 2010

    S.O.L.I.D principles

    S: The Single Responsibility Principle
    O: The Open Closed Principle
    L: The Liskov Substitution Principle
    I: Interface Segregation Principle
    D: The Dependency Inversion Principle

    Five principles that made the OOP world is re-use and easily maintain.
    All thing is found by Robert Martin (a.k.a. Uncle Bob). And today, i find a link that write very good about S.O.L.I.D principles. You can find this at here.

    Friday, January 22, 2010

    How to references mutilple databases in SQL Server 2005

    Today, when working with SQL Server 2005, I have a issue. This situation as "I have a select statement that references to multiple tables that reside in 2 different database". After finding in internet and helping from my team leader, I found a solution as below;

    + Using Synonyms in SQL Server 2005 for taking references to other database (other database server)
    USE "Database using references";
    IF OBJECT_ID('dbo.OrgUnit', 'SN') IS NOT NULL
    DROP SYNONYM dbo.OrgUnit;
    CREATE SYNONYM dbo.OrgUnit FOR ["name of database referenced"].security.orgunit.OrgUnit;

    select * from dbo.OrgUnit

    Note: I you want to know about "name of database referenced", using as
    select * from sys.servers

    + Adding:
    USE master;
    EXEC sp_addlinkedserver
    '"IP Address"',
    N'SQL Server'

    + And now you can select the table that reside in the other location as

    USE "Database using references";
    select * from dbo.OrgUnit

    For example:

    Assume we have [Client] database at local and [Security] database at the remote side

    USE master;
    EXEC sp_addlinkedserver
    N'SQL Server'

    select * from sys.servers

    USE Client;
    IF OBJECT_ID('dbo.OrgUnit', 'SN') IS NOT NULL
    DROP SYNONYM dbo.OrgUnit;
    CREATE SYNONYM dbo.OrgUnit FOR [SECURITY_DATABASE_ADDRESS].security.orgunit.OrgUnit;

    select * from dbo.OrgUnit

    Tuesday, January 19, 2010

    Thinking about Patterns in ASP.NET for developer

    Today, when try to finding about pattern, I found the new series articles about patterns for developer. It's really attractive me for exploring pattern in ASP.NET.

    This is a three parts: part 1, part 2 and part 3 at
    And this is a some pattern that apply for ASP.NET website at here and here

    Maybe, It's not new (because publish in 2007) but as me this very useful.

    Post, Redirect, Get Pattern in ASP.NET MVC

    The ASP.NET MVC pattern tends to lead itself into a more simplified and "true" HTTP experience by re-introducing patterns that have been lost, or at least, not followed in many years. One such pattern is the Post, Redirect, Get (PRG) pattern in which it is "to help avoid duplicate form submissions and allow web applications to behave more intuitively with browser bookmarks and the reload button" (Wikipedia).

    A normal ASP.NET Web Form Lifecycle has the following pattern

    1. HTTP GET of "Create.aspx"
    2. HTTP POST of "Create.aspx"
    3. Validation Fails, "Create.aspx" is Re-Rendered
    4. HTTP POST of "Create.aspx"
    5. Item is created, "Create.aspx" is Re-Rendered with confirmation message

    The major problems with this Postback pattern, is that hitting the Refresh button of your browser in steps 3 or 5 will re-post your submitted data. Step 5 is more of a problem as it could possibly re-submit that created information. Granted, there are steps that you can take to approach this problem, but this is how default ASP.NET Web Forms are treated.

    Taking this same approach within ASP.NET MVC, can be achieved in the same manner by rendering a your "Create" view from your POST action. For example:

    1. HTTP GET of "/products/create", "Create" view is rendered
    2. HTTP POST to "/products/submit"
    3. Validation Fails, "Create" view is rendered
    4. HTTP POST to "/products/submit"
    5. Item is created, "Confirm" view is rendered

    As you'll notice, the same problems we had with ASP.NET Web Forms exists with ASP.NET MVC. The really nice option, is that ASP.NET MVC gives you a lot more "freedom" of how the workflow is processed. If we strictly follow the PRG pattern within ASP.NET MVC, it would look something like

    1. HTTP GET of "/products/create", "Create" view is rendered
    2. HTTP POST to "/products/submit"
    3. Validation Fails, redirect to "/products/create", "Create" view is rendered
    4. HTTP POST to "/products/submit"
    5. Item is created, redirect to "/products/confirm", "Confirm" view is rendered

    As you'll notice, where we previously could have had issues in step 3 or 5 before, we no longer have issues. If a user presses the Refresh button in either of those steps, they'll not get the lovely "Would you like to resubmit the form data" confirmation as featured below - instead, the page just reloads.

    All detail information, please go ASP.NET MVC - Using Post, Redirect, Get Pattern

    Monday, January 18, 2010

    WCF Error - The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state

    While working on a WCF service, I ran into the following error.

    The communication object, System.ServiceModel.Channels.ServiceChannel,cannot be used for communication because it is in the Faulted state.

    This occurred when called Close method on instance of my WCF service client object. For a moment it took me by surprise. The code has been working fine and I was doing the right thing of closing connection to my WCF service after I was done using it. When I looked at the stack trace, I realized that it got thrown from a finally block of a method where I was calling a method on my WCF object. And before that there was an exception thrown. After further investigation it turned out that my WCF service was not running. So when I called method on the object, I got EndpointNotFoundException exception thrown when method was called. And in the same exception handling block I tried to call Close on client object. Since the client was already in bad state so next exception was thrown. So as a best practice, before you call Close method on your service object, check if its in Open state or not. This is exactly like a database connection object where you can check if its in open state or not. The following code snippet shows the change that I made to check for state of the WCF client object.

    if (_serviceClient.State == CommunicationState.Opened)

    Sunday, January 17, 2010

    The first post in blogspot

    I will try to make some thing that i learned from Internet (certainly about OOP)