Dear everyone,
This morning I received the email from Microsoft that they just created for me the blog at http://weblogs.asp.net. I really happy about that and decided to moving my house from Blogger (http://thangcq.blogspot.com) to asp.net blogs (http://weblogs.asp.net/thangchung). If anyone want to read some articles at Blogger, you still read all of it at those. I will not move all articles to asp.net weblogs, and in the future I will try to write new articles at asp.net 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!
Wednesday, June 16, 2010
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:
http://blogs.msdn.com/b/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx?wa=wsignin1.0
http://msdn.microsoft.com/en-us/library/bb383973.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
+ 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:
public static class Extender
{
public static T Cast(this object obj, T what)
{
return (T)obj;
}
}
+ Object that content the anonymous type:var exampleObj = from node in rootNode.Descendants()
where node.FirstAttribute != null && node.FirstAttribute.Value == "ExampleName"
select new
{
FirstField = node.FirstAttribute.Value,
SecondField = node.LastAttribute.Value
};
Binding this object to ListView:exampleObj .All(x =>
{
lstView.Items.Add(x);
lstView.ValueMember = "FirstField ";
lstView.DisplayMember = "SecondField ";
return true;
});
+ And used the extension method for cast anonymous type:var exampleObj= lstView.SelectedItem;
var castObj = exampleObj.Cast(new {
FirstField = "", SecondField = ""
});
Now we can use it very normally:var firstField = castObj.FirstField; var secondField = castObj.SecondField;+ References:
http://blogs.msdn.com/b/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx?wa=wsignin1.0
http://msdn.microsoft.com/en-us/library/bb383973.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
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:
+ References:
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
http://msdn.microsoft.com/en-us/library/ff649658.aspx
http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
http://msdn.microsoft.com/en-us/magazine/cc337885.aspx
http://msdn.microsoft.com/en-us/magazine/cc163739.aspx
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:
public abstract class CommonBootStrapper
{
public static IServiceLocator Locator;
protected IConfigurationManager _configurationManager;
protected IList _registries;
protected CommonBootStrapper(IList registries, IConfigurationManager configurationManager, string conStringName, params string[] bootTaskAssemblies)
{
_registries = registries;
_configurationManager = configurationManager;
Locator = CreateServiceLocator(conStringName, bootTaskAssemblies);
Run();
}
///
/// Create Service Locator object, including create and configure Nhibernate object
///
/// Service Locator instance
protected abstract IServiceLocator CreateServiceLocator(string conStringName, params string[] bootTaskAssemblies);
///
/// Run all task in background
///
protected abstract void Run();
}
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:public class BootStrapper : CommonBootStrapper
{
public BootStrapper() : this(null, null, "", "") { }
public BootStrapper(IList registries, IConfigurationManager configurationManager, string conStringName, params string[] bootTaskAssemblies)
: base(registries, configurationManager, conStringName, bootTaskAssemblies)
{ }
///
/// Create ServiceLocator object
///
///
protected override IServiceLocator CreateServiceLocator(string conStringName, params string[] bootTaskAssemblies)
{
RegisterRegistry(conStringName, bootTaskAssemblies);
return new StructureMap.ServiceLocatorAdapter.StructureMapServiceLocator(
ObjectFactory.Container);
}
///
/// Using Structure Map for scanning all instances from Assemply
/// , after that we call for execiting it
///
protected override void Run()
{
var listTask = IoC.GetAllInstances();
if (listTask != null)
{
foreach (var task in listTask)
{
task.Execute();
}
}
}
///
/// Register NHibernate configuration is a first component
/// and other component we'll register after that
///
private void RegisterRegistry(string conStringName, params string[] bootTaskAssemblies)
{
Check.Assert(_registries != null, "List of Registries is null");
Check.Assert(_registries.Count > 0, "List of Registries must be larger than zero");
Check.Assert(_configurationManager != null, "ConfigurationManager instance is null");
Check.Assert(string.IsNullOrEmpty(conStringName) != true, "Connnection string name is null or empty");
Check.Assert(bootTaskAssemblies != null, "list of assemblies is null");
ObjectFactory.Initialize(x =>
{
foreach (var registry in _registries)
{
if (string.Compare(registry.Name, typeof(CoreRegistry).Name) == 0)
{
Registry coreRegistry = (Registry)Activator.CreateInstance(typeof(CoreRegistry), _configurationManager, conStringName, bootTaskAssemblies);
x.AddRegistry(coreRegistry);
}
else
{
Registry otherRegistry = (Registry)Activator.CreateInstance(registry);
x.AddRegistry(otherRegistry);
}
}
});
}
}
In this trunk of code, you only need notice some lines code as below:protected override IServiceLocator CreateServiceLocator(string conStringName, params string[] bootTaskAssemblies)
{
RegisterRegistry(conStringName, bootTaskAssemblies);
return new StructureMap.ServiceLocatorAdapter.StructureMapServiceLocator(
ObjectFactory.Container);
}
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:
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
http://msdn.microsoft.com/en-us/library/ff649658.aspx
http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
http://msdn.microsoft.com/en-us/magazine/cc337885.aspx
http://msdn.microsoft.com/en-us/magazine/cc163739.aspx
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:
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:
I implemented scanning dll at CoreRegistry.cs, and this is the important function inside this class:
* 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!
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:
public interface IBootstrapperTask
{
void Execute();
}
+ Next, I will implement the abstract class for compositing all functions that I think I can re-use:public abstract class CommonBootStrapper
{
public static IServiceLocator Locator;
protected IConfigurationManager _configurationManager;
protected CommonBootStrapper(IConfigurationManager configurationManager, string conStringName, params string[] bootTaskAssemblies)
{
_configurationManager = configurationManager;
Locator = CreateServiceLocator(conStringName, bootTaskAssemblies);
Run();
}
///
/// Create Service Locator object, including create and configure Nhibernate object
///
/// Service Locator instance
protected abstract IServiceLocator CreateServiceLocator(string conStringName, params string[] bootTaskAssemblies);
///
/// Run all task in background
///
protected abstract void Run();
}
+ And I continue to implement sub-class for CommonBootStrapper that I just implemented:public class BootStrapper : CommonBootStrapper
{
public BootStrapper() : this(null, "", "") { }
public BootStrapper(IConfigurationManager configurationManager, string conStringName, params string[] bootTaskAssemblies)
: base(configurationManager, conStringName, bootTaskAssemblies)
{ }
///
/// Create ServiceLocator object
///
///
protected override IServiceLocator CreateServiceLocator(string conStringName, params string[] bootTaskAssemblies)
{
HibernateRegister(conStringName, bootTaskAssemblies);
return new StructureMap.ServiceLocatorAdapter.StructureMapServiceLocator(
ObjectFactory.Container);
}
///
/// Using Structure Map for scanning all instances from Assemply
/// , after that we call for execiting it
///
protected override void Run()
{
var listTask = IoC.GetAllInstances();
if (listTask != null)
{
foreach (var task in listTask)
{
task.Execute();
}
}
}
///
/// Register NHibernate configuration for container
///
private void HibernateRegister(string conStringName, params string[] bootTaskAssemblies)
{
ObjectFactory.Initialize(x => {
x.AddRegistry(new NHibernateRegistry(_configurationManager, conStringName, bootTaskAssemblies));
});
}
}
+ 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: public class AutoMapperConfigurator : IBootstrapperTask
{
public void Execute()
{
Initialize();
}
public static void Initialize()
{
Mapper.Initialize(x => x.AddProfile());
}
}
Please go to http://thangcq.blogspot.com/2010/04/configurating-automapper.html 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:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
new NMA.Infrastructure.NHibernate.Bootstrapper.BootStrapper(
new ConfigurationManagerWrapper(),
"NMAConnectionString",
"NMA.Infrastructure.NHibernate", "NMA.Application", "NMA.Infrastructure.AutoMapper");
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
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:
private void ScanTaskAssemblies(IAssemblyScanner scanner, params string[] bootTaskAssemblies)
{
for (int i = 0; i < bootTaskAssemblies.Length; i++)
{
scanner.Assembly(bootTaskAssemblies[i].ToString());
}
scanner.AddAllTypesOf();
scanner.WithDefaultConventions();
}
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 http://nma.codeplex.com. 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:
http://thangcq.blogspot.com/2010/04/mocking-lamda-expression-method.html
http://thangcq.blogspot.com/2010/04/converting-expression-tree.html
http://thangcq.blogspot.com/2010/04/configurating-automapper.html
http://thangcq.blogspot.com/2010/04/customizing-controller-factory-used-ioc.html
http://thangcq.blogspot.com/2010/05/unit-testing-uses-nunit-in-visual.html
Hope I will write many posts in future!
In next post, I intend to writing the series posts about NMA project. Some posts that I wrote in past as:
http://thangcq.blogspot.com/2010/04/mocking-lamda-expression-method.html
http://thangcq.blogspot.com/2010/04/converting-expression-tree.html
http://thangcq.blogspot.com/2010/04/configurating-automapper.html
http://thangcq.blogspot.com/2010/04/customizing-controller-factory-used-ioc.html
http://thangcq.blogspot.com/2010/05/unit-testing-uses-nunit-in-visual.html
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:
tag and adding the configuration tag is . And the result is
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
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:
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:
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
//Debug.Print("Controller: {0}, Action: {1}", requestContext.RouteData.Values["Controller"], requestContext.RouteData.Values["Action"]);
if (controllerType == null)
{
//Debug.Print("Is IController: {0}", (controllerType is IController));
//Debug.Print("Is null: {0}", (controllerType == null));
return null;
}
return (IController)IoC.GetInstance(controllerType);
}
}
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:
http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx
http://elijahmanor.com/webdevdotnet/post/using-structuremap-with-aspnet-mvc-mvc-contrib.aspx
Hope this post making you enjoy! Thanks and see you next time!
http://elijahmanor.com/webdevdotnet/post/using-structuremap-with-aspnet-mvc-mvc-contrib.aspx
Hope this post making you enjoy! Thanks and see you next time!
Subscribe to:
Posts (Atom)




