You are currently browsing the category archive for the ‘Development’ category.
Let’s say you have a third party library that you want to reference from your project. By default platform target in Visual Studio is “Any CPU”. But the library is compiled for specific target – x86 or x64. When you’re working in a team, have a build server and all of them is in different platforms you’ll start to have issues. Like, project with an x64 referenced assembly working ok on your x64 machine and failing on x86 computers and so on.
For us it was the “System.Data.SQLite” – the ADO.NET provider for SQLite. It is provided compiled separately for 32 and 64 bit systems. It was not easy to figure out how to manage references to SQLite provider without making too much changes in our projects and build scripts.
I’ve found an elegant solution for it: manually modifying project files that are using it to add a condition to “Reference” task of MSBuild. Look at this code:
<Reference Include="System.Data.SQLite, Version=…, … , processorArchitecture=AMD64" Condition="$(PROCESSOR_ARCHITECTURE) == 'AMD64' Or $(PROCESSOR_ARCHITEW6432) == 'AMD64'"> <SpecificVersion>False</SpecificVersion> <HintPath>..\Lib\x64\System.Data.SQLite.DLL</HintPath> </Reference> <Reference Include="System.Data.SQLite, Version=…, … , processorArchitecture=x86" Condition="$(PROCESSOR_ARCHITECTURE) == 'x86' And $(PROCESSOR_ARCHITEW6432) == ''"> <SpecificVersion>False</SpecificVersion> <HintPath>..\Lib\x86\System.Data.SQLite.DLL</HintPath> </Reference>
We’ve added the “Condition” attributes to “Reference” task and we specify when we’re making the reference and specify in “HintPath” the assembly for current platform.
Detection of the current platform is based on checking of two environment variables: PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432 to detect “bitness” of running OS/processes. Details of this you can find in the post of David Wang HOWTO: Detect Process Bitness.
Working like a charm for us.
A snippet from a project I’ve been reading:
// -- FILE ------------------------------------------------------------------ // name : UserConfig.cs // created : // language : c# // environment: .NET 2.0 // -------------------------------------------------------------------------- using System; namespace TheNamespace.Configuration { // ------------------------------------------------------------------------ public class UserConfig { // ---------------------------------------------------------------------- public UserConfig( System.Configuration.Configuration configuration ) { if ( configuration == null ) { throw new ArgumentNullException( "configuration" ); } this.configuration = configuration; } // UserConfig // ---------------------------------------------------------------------- public System.Configuration.Configuration Configuration { get { return this.configuration; } } // Configuration // ---------------------------------------------------------------------- public string FilePath { get { return this.configuration.FilePath; } } // FilePath // ---------------------------------------------------------------------- // members private readonly System.Configuration.Configuration configuration; } // class UserConfig } // namespace TheNamespace.Configuration // -- EOF -------------------------------------------------------------------
It’s a matter of taste, of course, but I’m wondering, what is the reason to decorate the code with a such ceremony?
Much of the time we, developers, are spending reading the code. That’s why the code that is clean, easy to read and understand is so much appreciated.
Jimmy Bogard has a very nice summary of steps you can do to speed up building of your project or solution. By “build” I mean not just rebuilding solution from scratch, but doing also a complete run down: cleanup, rebuild and run your tests. This can be a local build performed on a developer’s machine, or a continuous integration build performed by dedicated build/integration server.
Some time ago, when build times grew to intolerable limits, we cut down number of projects in our solution. Along with a common output folders, this improved dramatically performance especially on integration server, where a single committed change threw running of few cascading builds and code analyses.
Now, slowest part of our build process are integration tests. A big part of them are “testing integrations” with database. Since we’re using real MS SQL Express 2008 instances to run them, tests are very slow. A natural solution is using of an in-memory database like SQLLite. We spent some time on this, but since our database interactions are not trivial (kind of multi-tenant & multi-database application) we gave up until better times. But I think we will be back to finish that, because with more tests written we’re pushing up build times. To give an idea how this can be done, Ayende Rahien has a very basic example how to use in-memory database to run NHibernate integration tests.
As always, business requirement went over existing code base to ask for a minor change that wasn’t compatible with our existing infrastructure: all surrogate keys are unique identifiers (Guid) and all infrastructure was built around that. The business people asked to add to an existing domain entity a natural key – integer identity number (auto increment field), to serve as a reference number.
We had two choices:
- to generate the identity from business code
- to let database manage it for us.
The second approach it preferable for us because it’s the database’s job to generate the keys.
Out of the box NHibernate doesn’t support such a thing. Answers to my question in NHibernate Users discussion group led to the next solution.
Given the class:
public class Entity { public int Id { get; set; } public int Id2 { get; set; } }
First “Id” is the primary key, the second is the key that we want to map to identity column. To have that done we should do two things:
- Map “Id2″ property as “generated”
- Use “database-object” to drop the column generated by NHibernate & create new one, with IDENTITY set on.
The complete mapping:
<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" namespace="NHibernate.Playground" assembly="NHibernate.Playground" default-lazy="false" xmlns="urn:nhibernate-mapping-2.2"> <class name="Entity"> <id name="Id"> <generator class="increment" /> </id> <property name="Id2" type="int" generated="always" insert="false" /> </class> <database-object> <create> ALTER TABLE Entity DROP COLUMN Id2 ALTER TABLE Entity ADD Id2 INT IDENTITY </create> <drop> ALTER TABLE Entity DROP COLUMN Id2 </drop> </database-object> </hibernate-mapping>
I like the flexibility offered by NHibernate. Even if you don’t have required feature, you can always use naked ADO.NET or raw SQL.
I’m evaluating the NServiceBus communication framework for using it in some parts of application that we’re working on. I like the messaging infrastructure that it offers and how it all is implemented – behind a simple interface is hidden a modular, extensible, reliable and extremely powerful messaging engine. Sure, like any other framework, it has his own pitfalls and places that requires a special knowledge about how things works to use it efficiently.
One of those tricky places is his configuration system. To start use NServiceBus you have to do few steps to properly configure it. You have to use 2-3 “app.config” configuration sections with approximately 10-15 various parameters and few configuration classes provided by NServiceBus.
Another place that make me stuck is his integration with IoC (Inversion of Control) container. It has an abstraction over all container stuff, so you can pretty easily create an adapter to use it with container of your choice. I don’t like how this abstraction is used and implemented, a bit unnatural for my habits on how to put container to work.
Anyway, we have to deal with it, and use the NServiceBus with Castle Windsor container. As I said to do that you have to create an adapter for IBuilder interface. The NServiceBus Contrib project contains a patch that do this, but it is done in a completely wrong way – by mimicking the adapter for Spring framework. Bad, bad, bad…
So let’s take our big gun – Binsor from Rhino.Tools (I wrote about here) that should do all dirty work by configuring NServiceBus and integrating it in our existing Windsor container. The link to VS solution with all code shown here is provided at the end of the page.
Here we go – how to configure a subscriber for Pub/Sub interactions:
1. Binsor configuration (.boo file):
import System.Reflection
import NServiceBus
import NServiceBus.Unicast
import NServiceBus.Serialization
import NServiceBus.Serializers.Binary
import NServiceBus.Unicast.Transport
import NServiceBus.Unicast.Transport.Msmq
import NServiceBus.Unicast.Subscriptions
import NServiceBus.Unicast.Subscriptions.Msmq
import ObjectBuilder
import nServiceBus.CastleIntegration
component IBus, NServiceBus.Unicast.UnicastBus:
MessageOwners = {"Messages":"messagebus"}
MessageHandlerAssemblies = [Assembly.Load("Subscriber1")]
component ITransport, MsmqTransport:
InputQueue = "worker"
ErrorQueue = "error"
NumberOfWorkerThreads = 1
MaxRetries = 5
IsTransactional = false
PurgeOnStartup = false
component IMessageSerializer, MessageSerializer
component IBuilder, Builder
2. Program initialization:
var container = new WindsorContainer(); BooReader.Read(container, "nServiceBus.boo"); container.Register(SagasAndMessageHandlers.From(typeof(EventMessageHandler).Assembly)); var bus = container.Resolve<IBus>(); bus.Start();
That’s all. Now you can start send/receive messages.
For my taste this is much more readable and maintainable than traditional NServiceBus configuration. Less code, no XML, much cleaner, container friendly.
To make this work you have need for adapter class itself. His responsibility is to forward IBuilder.Build<T> calls to Castle’s Resolve<T> methods. Also, a small helper class that will register Sagas and MessageHandlers in container. Here it is:
public static class SagasAndMessageHandlers { public static IRegistration[] From(params Assembly[] assemblies) { var registrations = new List<ComponentRegistration>(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { var implementedInterfaces = type.GetInterfaces(); foreach (var interf in implementedInterfaces) { if (!interf.IsGenericType) continue; var genericArguments = interf.GetGenericArguments(); if (genericArguments.Length != 1) continue; if (!typeof(IMessage).IsAssignableFrom(genericArguments[0])) continue; var sagaHandlerType = typeof(ISaga<>).MakeGenericType(genericArguments[0]); if (sagaHandlerType.IsAssignableFrom(interf)) { registrations.Add(CreateRegistration(type, sagaHandlerType)); registrations.Add(CreateRegistration(type, type)); } var messageHandlerType = typeof (IMessageHandler<>).MakeGenericType(genericArguments[0]); if (messageHandlerType.IsAssignableFrom(interf)) registrations.Add(CreateRegistration(type, type)); } } } return registrations.ToArray(); } private static ComponentRegistration CreateRegistration(Type type, Type handlerType) { string componentName; if (type == handlerType) componentName = type.FullName; else componentName = type.FullName + handlerType.FullName; return (ComponentRegistration)Component .For(handlerType) .ImplementedBy(type) .LifeStyle.Is(LifestyleType.Transient) .Named(componentName); } }
One thing to notice here, NServiceBus required that a saga to be registered as a saga handler ( ISaga<Message>) and as a Saga class itself. A better way will be to use Castle’s newly added forwarding ability, when a component implementation can be accessed through multiple interfaces all forwarded to component’s instance. Bud I had no time to play with this feature yet, so this duplication will still here some time given the fact that no bugs showed up.
You can download a Visual Studio solution with all code shown here from this place. It contains all infrastructure code and two working sample projects ported from original NServiceBus samples – Pub/Sub & Saga.
In our projects we’re using Binsor to configure services in our Windsor container. Main reason to do that is Binsor’s extreme expressiveness. It’s much easier to write and maintain next fragment:
import MyApp.Services component IMyService, MyService
compared with standard way of configuring components in Windsor:
<component id="my_service" type="MyApp.Services.IMyService, MyApp" service="MyApp.Services.MyService, MyApp" />
Difference is more evident when you have to maintain files with tens and hundreds of components. Sure, you can use some kind of “autoregistration” for components, this can reduce dramatically size of configuration files.
But, since Binsor is a kind of DSL, is not always evident how to configure complex components that have dependencies and configuration properties to specify. The Binsor’s unit tests are the place where to look for samples, but they don’t cover everything.
Today, I had to configure a NHibernateIntegration facility from Castle with Binsor. After some time I had next solution for configuring two factories:
import Castle.Facilities.NHibernateIntegration import Rhino.Commons import NHibernate.Playground
facility NHibernateFacility:
configuration:
factory:
@id = 'factory_1'
settings(keymap):
dialect = 'NHibernate.Dialect.MsSql2005Dialect'
connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test;Integrated Security=SSPI"
assemblies:
assembly = 'NHibernate.Playground'
configuration:
factory:
@id = 'factory_2', alias = 'test2'
settings(keymap):
dialect = 'NHibernate.Dialect.MsSql2005Dialect'
connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test2;Integrated Security=SSPI"
assemblies:
assembly = 'NHibernate.Playground'
You can see here the XML way to configure NHibernate facility.
This time it’s about useful macro that speeds up writing test names. Although we’re not using yet BDD development style (BDD is for Behavior Driven Design) I like to give to my test BDD-style names. You know, something like
[Test] public void When_user_pressed_OK_message_should_be_prepared_and_sent() { }
Writing down these names, when words are separated by underscores is not easy and error prone.
Fortunately, Jean-Paul S. Boodhoo has posted in his blog an updated macro for formatting test names in BDD-style manner:
Using this macro you can write test name as an usual sentence, having words separated by spaces. After running the macro it will replace all space characters by underscores.
For me it was first macro written for Visual Studio, but after some rambling within VS I have the macro running and working well. Thereafter, found these links than can help to setup and use VS macros:
It seems to be that Patterns & Practices team continues to do what they do the best – creating guidance within different development areas.
The last release of this group is the WCF Security Guidance. It contains description for a few application scenarios & a list of various How-Tos, including few video walkthroughs of common WCF solutions.
It’s different from usual way to dig into WCF infrastructure details. It’s not crawling over hundreds of MSDN pages, it’s not like reading MSDN samples trying to understand what’s going on.
It is a very detailed step-by-step description on how to do some tasks touching different aspects of WCF, starting from opening a certificates store, and ending with deployment advices.
Keep it going, P&P!
I have shown today few tricks with ReSharper to one of my teammates. I think it worth to be shared/stored in the blog.
1. View the code used from a referenced assembly
Very often you want to see how a referenced assembly is used in your project. We can use dedicated tools to work this out (for example, NDepend) or you can just click on a project in solution explorer, expand “References” node, select an assembly, right-click and select “Find Dependent Code“. You will see a nice “Find Results” window with all places where this referenced assembly is used.
Same way, you can analyze project dependencies in a multi-project solution. I think you will be rewarded in future if your presentation assemblies will not depend from a project with database stuff.
2. Setting a keyboard shortcut to run a unit test
I’m sure that any keyboard ninja knows it. Do you want to learn a bit of kung-fu? Go to keyboard settings configuration in Visual Studio (Tools > Options… > Environment > Keyboard), find a command named “ReSharper.UnitTest_ContextRun” and assign a shortcut to it. I hang it to “Ctrl+1″.
Now, when you’re editing a class containing unit tests, you can just press your newly created shortcut and ReSharper will run the tests: if you’re inside a test method (method marked with [Test]) only the current test will run; if you’re somewhere in the class, but outside of a test method, R# will run all tests from this class.
WCF infrastructure allows you to store context sensitive data in InstanceContext of the service instance. For that you should implement from IExtension<InstanceContext> and plug that class into WCF’s infrastructure in any of available ways.
When I worked on a class that can store contextual information in Web context or WCF context depending on some configuration parameters, I preferred to have similar idioms, and I wrote an HttpContext-like class for WCF.
///<summary> /// This class incapsulates context information for a service instance ///</summary> public class WcfInstanceContext : IExtension<InstanceContext> { private readonly IDictionary items; private WcfInstanceContext() { items = new Hashtable(); } ///<summary> /// <see cref="IDictionary"/> stored in current instance context. ///</summary> public IDictionary Items { get { return items; } } ///<summary> /// Gets the current instance of <see cref="WcfInstanceContext"/> ///</summary> public static WcfInstanceContext Current { get { WcfInstanceContext context = OperationContext.Current.InstanceContext.Extensions.Find<WcfInstanceContext>(); if (context == null) { context = new WcfInstanceContext(); OperationContext.Current.InstanceContext.Extensions.Add(context); } return context; } } /// <summary> /// <see cref="IExtension{T}"/> Attach() method /// </summary> public void Attach(InstanceContext owner) { } /// <summary> /// <see cref="IExtension{T}"/> Detach() method /// </summary> public void Detach(InstanceContext owner) { } }
Now, you can use this class to store and retrieve data in the same manner as you’re working with HttpContext:
WcfInstanceContext.Current.Items["key"] = new MyClass(); MyClass myClass = WcfInstanceContext.Current.Items["key"] as MyClass;
Of course, when doing this you should be inside of WCF session…
Enjoy!
