March 31st, 2022.
New home base.
seen from China

seen from Canada
seen from Singapore

seen from United States

seen from Netherlands

seen from United States

seen from France
seen from Russia
seen from United States
seen from United States
seen from United States

seen from Pakistan
seen from United States
seen from China
seen from Italy
seen from Canada
seen from Italy

seen from United States
seen from United States

seen from United States
March 31st, 2022.
New home base.
Dear RIA,
You were not the cause of my problem. It was a hidden exception generated by an incorrect enterprise library version.
My apologies.
This explains why whenever anyone opens up a solution they automatically check out the file with no changes.
Microsoft Enterprise Library 4.1 Released
Microsoft Enterprise Library 4.1 has been released with some improvements and fixes. What's new
Unity interception mechanism and integration of the Policy Injection Application Block with the Unity Application Block
Added support for generics in the Unity Application Block
Added support for arrays in the Unity Application Block
Performance improvements
Usability improvements to the configuration tool
Visual Studio 2008 Service Pack 1 support
Bug fixes
Enterprise Library homepage Quick Starts
Method Tracing with Unity Interception
Everyone loves tracing and logging when developing an application, however in no time your code begins to look like a hot mess and you cant figure out where the tracing stops and the business logic begins.
public DidSomeLogicResult DoLogic(DoLogicCommand command) { Debug.Write("DoLogic Start"); Debug.Write(string.Format("DoLogicCommand: {0}", command.Number)); int magicNumber = _makeMagicNumberService.GetLogic(command.Number); Debug.Write(string.Format("magicNumber: {0}", magicNumber)); Debug.Write("DoLogic End"); return new DidSomeLogicResult { MagicNumber = magicNumber }; }
Now this is just a contrived example, but all the noise of Debug.Write is all over the place. Plus if the method name changes, arguments change you have to some how remember to go back and fix the magic strings. Man it sure would be awesome if somehow we could abstract all that noise away and make our method clean so all we can see is the business logic and nothing else. Thankfully there is such a mechanism called Aspect Oriented Programming (AoP)
Now everyone loves IoC and my favorite being Microsoft Unity, one of the added features of using Unity and Enterprise Library is an AoP framework included called Interception which can use Unity.
Consider the following example.
public interface IDoLogicService { DidSomeLogicResult DoLogic(DoLogicCommand command); } public class DoLogicService : IDoLogicService { private readonly IMakeMagicNumberService _makeMagicNumberService; public DoLogicService(IMakeMagicNumberService makeMagicNumberService) { _makeMagicNumberService = makeMagicNumberService; } public DidSomeLogicResult DoLogic(DoLogicCommand command) { int magicNumber = _makeMagicNumberService.GetLogic(command.Number); return new DidSomeLogicResult { MagicNumber = magicNumber }; } } public interface IMakeMagicNumberService { int GetLogic(int input); } public class MakeMagicNumberService : IMakeMagicNumberService { public int GetLogic(int input) { return input*2; } } public class DoLogicCommand { public int Number { get; set; } } public class DidSomeLogicResult { public int MagicNumber { get; set; } }
Now lets say we wanted to add tracing to every method defined on the interface for IDoLogicService and IMakeMagicNumberService.
HandlerAttribute
This first thing we need to do is derive an attribute from HandlerAttribute. A handler attribute allows us to use an attribute based policy for our Unity Interception.
public class TraceAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new TraceCallHandler(); } }
In this implementation we simply return a new class called TraceCallHandler, this class could even be resolved via Unity since CreateHandler passes in the current UnityContainer.
ICallHandler
The next piece we need to implement is the TraceCallHandler which derives from ICallHandler. This handler is called each time in the pipeline for the current unity interception context. This is the portion that you will put in your tracing/logging logic.
public class TraceCallHandler : ICallHandler { public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.WriteLine("Called: {0}.{1}", input.Target.GetType(), input.MethodBase.Name); if (input.Arguments.Count > 0) { Console.WriteLine("\tWith Arguments"); for (int i = 0; i < input.Arguments.Count; i++) { Console.WriteLine("\t\tName:" + input.Arguments.ParameterName(i)); } } InvokeHandlerDelegate next = getNext(); Console.WriteLine("Execute..."); IMethodReturn methodReturn = next(input, getNext); string result = methodReturn.ReturnValue == null ? "(void)" : methodReturn.ReturnValue.ToString(); if (methodReturn.Exception != null) Console.WriteLine("Exception: {0}", methodReturn.Exception); Console.WriteLine("Result: {0}", result); return methodReturn; } public int Order { get; set; } }
Looking at the above you can see we have access to the input (IMethodInvocation), which contains the method name being called (input.MethodBase.Name), the type of the object being invoked (input.Target.GetType()), and also all the arguments passed into the method (input.Arguments). The next piece of information is the getNext delegate, this is used to get the method that is actually going to be invoked. To accomplish this you need to call the getNext delegate and call that method with the input and getNext delegate. This portion is what actually executes the method. From there you can get the IMethodReturn, this will contain the return result of the method invoked and any exceptions (methodReturn.Exception) that might have been generated by the call. From there you can simply log the result and return the methodReturn variable.
Add the Attribute
Now that we have our two pieces setup we can easily add the attribute to your interfaces, this is done simply be adding the attribute to the interface definition.
[Trace] public interface IDoLogicService { DidSomeLogicResult DoLogic(DoLogicCommand command); } [Trace] public interface IMakeMagicNumberService { int GetLogic(int input); }
This addition will allow for logging of any method call to the interface when resolved from unity.
Configuring the Container
The next piece will be to configure the container for Interception this is done by adding a new extension to the container.
container.AddNewExtension<Interception>();
This ends up adding all the needed bits for interception. The next piece will be to configure interception for our two interfaces, this is also done by the following:
container.Configure<Interception>().SetInterceptorFor<IDoLogicService>(new InterfaceInterceptor()); container.Configure<Interception>().SetInterceptorFor<IMakeMagicNumberService>(new InterfaceInterceptor());
What we need to do is use Configure<Interception>() and SetInterceptorFor<> to describe the interface we want to intercept and then define the interceptor, in this example we are using interfaces so we need a new InterfaceIncterceptor. With those three lines we are done.
Testing out our Tracing
Next we need to resolve our IDoLogicService from our container and execute the method DoLogic
var doSomeLogic = container.Resolve<IDoLogicService>(); DidSomeLogicResult didSomeLogicResult = doSomeLogic.DoLogic(new DoLogicCommand {Number = 21}); Console.WriteLine("DidSomeLogicResult: {0}", didSomeLogicResult.MagicNumber); Console.ReadKey();
If you run the application you will see all the additional information obtained via the TraceCallHandler we defined.
Called: ConsoleApplication.DoLogicService.DoLogic With Arguments Name:command Execute... Called: ConsoleApplication.MakeMagicNumberService.GetLogic With Arguments Name:input Execute... Result: 42 Result: ConsoleApplication.DidSomeLogicResult DidSomeLogicResult: 42
Because of this our DoLogic method remains very clean and all the Debug.Write noise from the first Example is gone.
public DidSomeLogicResult DoLogic(DoLogicCommand command) { int magicNumber = _makeMagicNumberService.GetLogic(command.Number); return new DidSomeLogicResult { MagicNumber = magicNumber }; }
Bonus points…
If you wrap the Interception configuration into an UnityContainerExtension you could easily enable system wide tracing with a simple alteration of a configuration file.
public class LogicTraceExtension : UnityContainerExtension { protected override void Initialize() { Container.AddNewExtension<Interception>(); Container.Configure<Interception>().SetInterceptorFor<IDoLogicService>(new InterfaceInterceptor()); Container.Configure<Interception>().SetInterceptorFor<IMakeMagicNumberService>(new InterfaceInterceptor()); } }
And then the corresponding *.config file
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <namespace name="ConsoleApplication"/> <assembly name="ConsoleApplication"/> <container> <extension type="LogicTraceExtension"/> </container> </unity>
There you have it a simple use of Unity Interception to handle some trace logging with very little work on modifying existing code. This concept could even be taken further to exception out method execution if the day is Sunday or some other criteria.
Using Unity Design Time Configuration
Chances are when designing an application with IoC you end up wishing you had some way to inject in some sort of configuration into you business layer. Normally you might end up building up some sort of ConfigSection that allows you to have a nicely wrapped up area for your business configuration. Now doing this you will end up creating a few additional classes just for the need for the ConfigSection implementation, this can be time consuming and result in wasted time. Instead of doing that simply let Unity’s Design Time configuration do the heavy lifting for you.
Now lets consider the following example.
Interface
Now this is just simply our interface to your configuration which you want to inject into your business logic, just a few basic properties.
public interface IConsoleApplicationConfiguration { string ClientName { get; } decimal Cost { get; } List<int> ValidCodes { get; } }
Code
Next up simply derive a concrete type that implements this interface, you could use auto properties or use constructor parameters to build up your type, for this example we will do both so you can see how the configuration is declared.
public class ConsoleApplicationConfiguration : IConsoleApplicationConfiguration { public ConsoleApplicationConfiguration(string clientName, int[] validCodes) { ClientName = clientName; ValidCodes = validCodes.ToList(); } public string ClientName { get; private set; } public decimal Cost { get; set; } public List<int> ValidCodes { get; private set; } }
*.config file
Now comes the config file that unity will use to build up your derived type.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <namespace name="ConsoleApplication.Configuration"/> <assembly name="ConsoleApplication"/> <container> <register type="IConsoleApplicationConfiguration" mapTo="ConsoleApplicationConfiguration"> <constructor> <param name="clientName" value="Console Application"> </param> <param name="validCodes"> <array> <value value="0"/> <value value="1"/> <value value="1"/> <value value="2"/> <value value="3"/> <value value="5"/> <value value="8"/> <value value="13"/> </array> </param> </constructor> <property name="Cost" value="25.95"/> </register> </container> </unity> </configuration>
Some things to notice with the configuration above.
We need the <assembly/> node to define which assembly is used to search for types, this is optional but helps keep things clean.
<namespace/> node is also an optional element, but allows for your <register type=”” mapTo=””/> elements to omit the fully qualified name.
<register/> is simply a registration for you Unity mapping, this is the same as doing Container.RegisterType<ISomeInterface, SomeType>() in code.
<constructor/> inside of this node you define any parameters needed to build up the mapTo type
Each constructor parameter needs a corresponding <param/> node which maps the name of the parameter to the value of the parameter.
If one of the parameters is an array, simply use the <array/> element with as many <value/> elements needed.
<property/> nodes are needed if you want to inject a value into the property, simply name it the same as the property name and give it a corresponding value. You can also use <array/> elements here if the type is an array of some type.
Now looking at what you did above it has to be easier than designing a configuration section and all of the required classes and attributes needed to get that to work. If you want to read more about other things you can do with design time configuration read the full article on MSDN which gives a ton of additional information on how to handle dependencies to your mapTo type and other built in features.
Using rowversion with Enterprise Library Data Access Block for Optimistic Concurrency Control
When developing any type of data intensive application you should always be aware of concurrency issues. Neglecting this concept can result in lost data if two users are updating the same record at the same time.
Consider the following scenario:
User A gets a record from the database
User B get the same record from the database
User A submits their changes to the database successfully.
User B takes a bit longer and submits their changes to the database.
Now when User A loads up the record again User B’s records overwrote User A’s modifications.
Now with concurrency control:
User A gets a record from the database
User B get the same record from the database
User A submits their changes to the database successfully.
User B takes a bit longer and submits their changes to the database, however this time there is a notification that the record changed and the record is reloaded.
User B sees the changes and realizes User A already made the modifications and only needs to update the one field.
Now when User A loads up the record again they will see their changes and also User B’s changes.
To implement this with Enterprise Library you are going to need a bit of SQL and simply pass in the row version when doing updates.
SQL
Create your table with rowversion,
Rowversion is a auto generated column that updates any time the row is modified.
CREATE TABLE [dbo].[SomeTable]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [SomeText] [varchar](200) NOT NULL, [Version] [rowversion] NOT NULL, CONSTRAINT [PK_Reminders] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
Create your stored procedures for getting all the records
SELECT [Id] ,[SomeText] ,[Version] FROM [dbo].[SomeTable]
Create the stored procedure for updating the record
This was obtained by the msdn article on rowversion, what this simply does is attempt to update the record with the [Id] and [Version] pair, if no records were updated (record version mismatch) an error is raised that the update did not occur.
ALTER PROCEDURE [dbo].[SomeTable_Update] @Id as bigint ,@SomeText as varchar(200) ,@Version as rowversion AS BEGIN DECLARE @t TABLE (myKey int); UPDATE [dbo].[SomeTable] SET [SomeText] = @SomeText OUTPUT inserted.Version INTO @t(myKey) WHERE [Id] = @Id AND [Version] = @Version IF (SELECT COUNT(*) FROM @t) = 0 BEGIN RAISERROR ('error changing row with [Id] = %d' ,16 ,1 ,@Id) END; END
Code
Model
The model simply has an byte[] array as the Version of the model.
public class SomeTable { public string SomeText {get;set;} public byte[] Version { get; set; } public long Id { get; set; } }
Create IRowMapper<SomeTable>
With using the built in BuildAllProperties() Version was always null, to fix that simply use .Map() and .WithFunc() to grab the version field and cast it to a byte[].
IRowMapper<SomeTable> mapper = MapBuilder<SomeTable>.MapAllProperties() .Map(r => r.Version).WithFunc(d => (byte[])d["Version"]) .Build();
GetAll()
public List<SomeTable> GetAll() { return _database.ExecuteSprocAccessor("SomeTable_GetAll", mapper).ToList(); }
Update
Simply pass in Version with the update statement.
public void Update(SomeTable someTable) { DbCommand command = _database.GetStoredProcCommand("SomeTable_Update"); _database.AddInParameter(command, "@Id", DbType.String, someTable.Id); _database.AddInParameter(command, "@SomeText", DbType.String, someTable.SomeText); _database.AddInParameter(command, "@Version", DbType.Binary, someTable.Version); _database.ExecuteNonQuery(command); }
That is all you need to do to implement some simple concurrency control in your application. Any update will work correctly, but if a record is changed between the get and update an error will be be thrown that the update was not successfully because of a row version mismatch.