Archives de la catégorie Microsoft Infrastructure Framework – Unity MEF Moles … – IoC AOP …
Code Contract, a way to control authorized values input output method or in interface at building time ! – Microsoft Static Check
Publié par hassanboutougha dans Code Contract, Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ... le décembre 16, 2012
From Microsoft research, with code contract, it is allowed to make verification on input, ouput arguments on methods and make other check on Interface.
First check in object explorer if you have Microsoft.Contracts.
1/ if you have an old Visual studio download Code contract assembly on download panel: http://research.microsoft.com/en-us/projects/contracts/
run MSI installer as follows:
Add a reference on Microsoft.Contracts assembly (which implements Data Contract you have just installed before 😉 :
in object explorer, (double click on Microsoft.Contracts to run it), you will see the 2 namespaces and classes contained:
2/Now you have Code Contract Assembly
in BizProcess method, use Contract class and call Requires method to check input value (here we check that b is different of 3 ;-):
Go to properties solution and in Code Contracts panel (left side), Check Perform Static Contract Checking in order to make checks on build time 😉
when you build solution, you will see a warning as below because a business rule is violated (b different of 3 in our sample)
Code contract is very interesting to make some check at build time because at runtime it is too late… 😉
You can also make check on Interface by using attributes ContractClass and ContractClassFor
For sure when data are knowing at runtime, you will make your check in code.
PEX – Program EXploration with a simple sample – a Microsoft framework to have a complete test coverage
Publié par hassanboutougha dans Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ..., PEX le octobre 29, 2012
Pex is a Microsoft framework that explore all execution branch in a method and create all the unit test unit to have a complete test coverage.
Create a library class we will use to create unit test with pex :
create a method in BizService with a simple algorithm that shows how Pex Framework create unit test for you in order to have a complete test coverage that test all execution Branches:
Now run Pex (to download it http://research.microsoft.com/en-us/projects/pex/downloads.aspx) on right clicking on the method and select run Pex:
you obtain in Pex exploration result 4 test, using a null value, an empty value and the value you want to test. Pex run 4 times the method in order to discover all execution branch:
as you can see a failure test appears because we throw an exception : it is an expected result so we will allow this one by right clicking on this test and we will allow it:
Pex ask us to create a test project : accept
we can see the new test project in solution explorer:
in MyBizServiceTest.cs file, Pex create a unit test:
Pex create those tests in MyBizServiceTest.runDifferentExecutionBranch.g.cs (solution explorer):
at the first test, we can see the expected exception NullReferenceException
re-run test by clicking Run buttong in Pex exploration Results and now all are passed:
we have also a panel Pex explorer where we can see unit test name
Conclusion : Pex create all test for us in order to test all execution path
Publié par hassanboutougha dans AOP, Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ... le octobre 23, 2012
AOP – Aspect Oriented Programming allows you to decorate all methods before and after execute them using a proxy pattern.
In this article, we will build a simple application using Unity Microsoft Framework to apply AOP.
First download Unity framework: http://unity.codeplex.com/releases
Create a console application solution and
Reference two Unity assemblies:
-Microsoft.Practices.Unity which allows Dependency injection (see an article below)
-Microsoft.Practices.Unity.Interception allowing Aspect Oriented Programming
Add to the solution two folders:
-AOP : Folder for the class used to decorate our Business class
-BIZ: Folder for a simple Business service
Create a PerformanceHandler class which implements ICallHandler interface.
Use the unity interception namespace:
Below, we set a stopwatcher to mesure the execution time of the method called
And we print in console the interception before and after call really the method
The ICallHandler interface have an invoke method where you decorate your method (proxy pattern). You can make technical log, get the methode name decorated, set your security strategy…
Add a new class , PerformanceAttribute which implement HandlerAttribute and override CreateHandler method to return an instance of PerformanceHandler.
This class create an attribute you have to set before a method you want to decorate
in our folder BIZ, create a simple Business service and its interface:
and its interface IBizService. Note that we decorate execute method with Performance Attribute (our PerformanceAttribute class):
Now add the following code in the main program:
Execute, and you will stop at differents place where we set a Console.ReadLine()
Before the execute method of our service is runned
Press enter key : the method is executed and new print appears after
the execution is completed and we return on our main program
Publié par hassanboutougha dans Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ..., Moles le octobre 22, 2012
Go to Microsoft url to download Moles and Pex – (in a new article I will discuss about Pex)
install Moles and Pex:
Moles is a framework which allow to use:
-Stub type : Fake
-Mole type : in order to fake some external ressource like IO or external classes.
1/Create a library class where you will call your external ressource like an IO assembly, WCF service… :
-use an interface that your business layer will use to call the external method
-wrap in a class that implement the interface your external resource
2/Create a console application that use your business library:
In solution explorer click on the desired assembly you want to “Mole”, here MyBizService, referenced in BizConsumer and in the context menu click Add mole Assembly
a moles file appear in the solution explorer :
the content of the moles file:
Rebuild your solution and a new assembly appears:
Double click in MyBizServiceMoles reference to explore the assembly:
Moles create two type of class for each class discovered in the assembly “ Moled”
-Stub class which name begins with S : for replacing your component you control
-Mole class which name begins with M : to create detours on external component like IO…
Now we create a unit test on Execute method by right clicking on this method and select create unit test:
click ok on Create Unit Test to create a new Test Project:
enter a name to the new test project:
In solution explorer, you see the new test project and the reference on Mole assembly ( we can add mole assembly after creating test project)
In AssemblyInfo file add a reference assembly to the type you want to mole, here BizService
add Mole Assembly to MyBizService assembly and rebuild Test project :
Go to AssemblyInfo file in test project to add an assembly attribute:
set the MoledType you want , it allows Moles not to mole whole assembly
which optimize Building Time (here we mole only MyExternalRessource class):
Finally, create a unit test with a mole type of your External resource like below (here we rewrite the implementation of method to verify that our external resource is called ( we set a lambda expression for all instances before calling the method that use our external resource):
Conclusion : the external resource is diverted using Mole
You can have some mistake using Mole with the following error message :
The test adapter (‘Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’) required to execute this test could not be loaded. Check that the test adapter is installed properly. Object reference not set to an instance of an object.
the solution is to reinstall mole framework
Publié par hassanboutougha dans MEF, Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ... le octobre 21, 2012
First download MEF assembly from Microsoft url:
Managed Extension Framework, called Mef, is usefull when you want to extend your application. To do it, Mef allow Dependency injection between composant or layers.
When use Unity and Mef ?
-use Unity to do dependency injection during development when you know all components
-use MEF for components that will come in future, or when you want your application splitted in assembly that are not in the same solution or you want not to have reference (prefering to “bind” assembly) – interesting in a plugin architecture…
So, you can use both each one having its own purpose.
We will create three assemblies:
-Contracts.dll which provides all contracts
-MyBusinessComponent.dll which provides the implementation of our business
-Form1 : a winform where we will call dynamically our business layer through MEF and without any reference on the winform project
1/Create a Contracts assembly:
add to your solution a new Class library project and call it Contracts
add a IBusinessService interface
2/create our business assembly
add a second class library project called MyBusinessComponent:
add a reference on MEF assembly (System.ComponentModel.Composition.CodePlex ) in this project in order to expose our business service methode:
Create a MyBusinessService class and implement IBusinessService as below :
an export attribute decorate MyBusinessService class with the interface we want to expose (here IbusinessService). You have to add a MEF namespace
3/Create a winform that will act as a presentation layer:
Add a windows form application to the solution
add a control button and a label called it LabelInfo
add a MEF reference as follows:
add also a reference only on Contracts assembly :
Now on winform code :
-Use Import attribute with the type of the interface and define a IBusinessService property
-Create a DirectoryCatalog and pass the location of your BusinessService assembly (you can use a relative path as below)
– Instantiate a compositioncontainer and pass the DirectoryCatalog: MEF will understand that all assemblies to explore are in the path of your DirectoryCatalog. MEF will get all attributes (here export of our business service) by reflection.
-Finally, call ComposeParts on form class, it enables Mef container to make the dependency mapping (using Export and Import Attribute)
all work fine and note that there isn’t any reference to BusinessService assembly.
Conclusion: in this sample, MEF is used as a third part that manage externe dependencies from different assemblies.
Publié par hassanboutougha dans Microsoft Infrastructure Framework - Unity MEF Moles ... - IoC AOP ... le octobre 20, 2012
Go to Microsoft url to download Unity Framework
in the main :
we make a Console application in which we instantiate a simple class MyBusinessService and call an Execute method on it. This method only log usinge the Logger class in the solution.
the MyBusinessService class instantiate a logger class in execute method. We have a high dependence because MyBusinessService is responsible of the Logger Creation … So it will be hard to make good test because if we test execute the mistake can come from Logger Creation…
Logger class log on standard output (console):
In order to loose dependency between MyBusinessService and Logger, we will create an interface logger.Why ? Because we want through MyBusinessService to use not directly an instance of Logger object but use its interface. It will allow us to use Logger or any Logger which implement Ilogger interface.
Create a ILogger interface:
Now, modify MyBusinessService in order to use an interface ILogger instead of an instance. Create a property with a ILogger type :
the logger property is only an interface and we refer this interface ( for a good comprehension, I comment the instantiation of Logger object)
So now, MyBusinessService has losen the high dependency with Logger class by using an interface ILogger .
How and who will instantiate Logger class?
A third part, a Microsoft framework that will make a Dependency Injection : Unity.
Add a reference to Unity Framework
select Microsoft Practice Unity
we make four steps:
-first, create an instance of UnityContainer (namespace Microsoft.Practices.Unity)
-use registerType method to map interface and the class we want to use (this class have to implement this interface of course)
-use resolve method when you will need to use an instance of your desired class
-finally, pass this instance here by property, but you can also pass it in the constructor 😉
imagine now that we want to use another logger called logger2:
now we have only to change one line in our main program to pass logger2 instead logger class:
run it, it is incredible we use now our new class with little work: