Often I will write class libraries for Silverlight but also want to make the library available for .net. The CLRs are not binary compatible so you need to have both a Silverlight and .net project and somehow share the code – you don’t want to have to maintain two sets of identical files. The common method of doing this is to develop the Silverlight library and link the source files in the .net library. You can do this by right clicking on the .net project and clicking Add Existing Item then selecting Link instead of Add. This works ok but you’ll still have to maintain two projects when you add/remove/rename files and directories in the Silverlight project.

I like to re-factor my code often and the task of manually modifying the .net project is a real pain. So I wrote a tool to update the .net csproj as per the Silverlight csproj and to copy the source files to the correct location. It only updates the Compile ItemGroup, so any manual changes to the .net csproj are not lost. The tool runs as part of the build process. A NAnt script builds the Silverlight solution, runs the copysrc tool to update the .net solution projects, builds the .net solution, and then runs unit tests for both solutions. I then only need to worry about editing the Silverlight source.

public class Program
{
	public static int Main(string[] args)
	{
		if (args.Length != 2)
		{
			Console.Error.WriteLine("usage: copysrc sourceDir destDir");
			return 1;
		}

		try
		{
			Copy(args[0], args[1]);
		}
		catch (Exception e)
		{
			Console.Error.WriteLine(e.Message);
			return 1;
		}

		return 0;
	}

	private static void Copy(string sourceDir, string destDir)
	{
		const string namespaceName = "http://schemas.microsoft.com/developer/msbuild/2003";
		XName itemGroupName = XName.Get("ItemGroup", namespaceName);
		XName compileName = XName.Get("Compile", namespaceName);

		Func<string, string> projNameFromDir =
			dir => Path.Combine(dir, dir.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Last() + ".csproj");

		string sourceProjFileName = projNameFromDir(sourceDir);
		string destProjFileName = projNameFromDir(destDir);

		Func<XDocument, XElement> findCompileItemGroup =
			doc =>
				{
					if (doc.Root == null)
						throw new InvalidOperationException("Xml document has no root.");

					return doc.Root.Elements(itemGroupName).Where(element => element.Elements(compileName).Count() > 0).FirstOrDefault();
				};

		// load dest csproj
		XDocument destDocument = XDocument.Load(destProjFileName);
		// find and clear dest compile itemgroup
		XElement destCompileItemGroup = findCompileItemGroup(destDocument);
		if (destCompileItemGroup != null)
			destCompileItemGroup.RemoveAll();
		else
			destCompileItemGroup = new XElement(itemGroupName);

		// load source csproj
		XDocument sourceDocument = XDocument.Load(sourceProjFileName);
		XElement sourceCompileItemGroup = findCompileItemGroup(sourceDocument);
		if (sourceCompileItemGroup != null)
		{
			// copy files and populate dest compile itemgroup
			foreach (XElement compileElement in sourceCompileItemGroup.Elements(compileName))
			{
				XAttribute includeAttribute = compileElement.Attribute("Include");
				if (includeAttribute == null)
					continue;

				// copy include to dest csproj
				destCompileItemGroup.Add(compileElement);

				// create dest dir
				string filename = includeAttribute.Value;
				string directoryName = Path.GetDirectoryName(filename);
				if (!string.IsNullOrEmpty(directoryName))
					Directory.CreateDirectory(Path.Combine(destDir, directoryName));

				//copy file
				File.Copy(Path.Combine(sourceDir, filename), Path.Combine(destDir, filename), true);
			}
		}

		destDocument.Save(destProjFileName);
	}
}

I use this tool for ValidationAspects, Bloom, and many other projects and it works fine. I use ifdefs in the .cs file to separate Silverlight and .net code for incompatibilities. I don’t know how well this would work for xaml files that describe UIs. Does xaml have something similar to ifdef? I personally haven’t found this an issue though as I develop UIs for their specific platform and haven’t had the need to share controls’ View code. ViewModels are shared however.

To use it I create both a Silverlight and a .net solution. For every project in the Silverlight solution I create its partner in the .net solution. I set the .net projects’ properties as required and then only check-in the .net csproj files. I set subversion to ignore all source files under the .net solution dir. If I do need to open the .net solution in Visual Studio, I first run the build script to update and populate the .net solution’s projects. If you want to see the tool in action and what the NAnt and project structure look like, take a look at Bloom on codeplex.


I recently purchased a Dell Mini 9 netbook with the intention of using it for a little c# hacking on the go or when the missus or my three year old daughter hog the desktop. There are lots of good reviews on the web but I couldn’t find much to persuade me either way if it was actually a usuable machine for running Visual Studio 2008 and ReSharper. My main concern was the 9inch screen and the 1024×600 resolution.

I took a gamble and I’m really happy I did. For me, the Mini 9 is easily one of the best bits of kit I’ve ever bought. Regarding some of the negative reviews, I think you have to have realistic expectations – I know it’s going to be slower than my quad core Xeon, and I know I’m going to have to do a lot more scrolling than I do for my 24inch monitor. I also surf the web on my PSP so I know what slow really is!

Mine has 2GB RAM and 32GB SSD HDD. I also installed Windows 7 which I’m really loving right now. I think this OS fits the Mini much better than XP. The startup time is just under 30 seconds. Shutdown time appears quite slow and I expect this is to do with the slow SSD write times. Running applications are fine with no noticable slowdown. Visual Studio can take about 15 seconds to startup. Once in, editing code, even with ReSharper enabled is pretty quick. Compilation is quick too – but then for someone who used to wait half a day to do a c++ build, c# is always quick!

The keyboard is on the small side but not difficult to use. On the GB keyboard only the ‘\’ key is out of place. I use the Home and End keys quite a lot and this involves pressing the Fn and arrow keys which I did initially struggle with. Despite what is reported, there are F11 and F12 keys. You have to hit Fn+Z and Fn+X. You may need to get the latest bios if this doesn’t work for you.

The screen size and resolution are actually fine. I run all the apps in fullscreen mode if they support it and 1024×600 doesn’t feel small. I’ve seen a Sony netbook with a similar sized screen but much higher resolution and that for my eyes was too small. The most important question though is how much code can you get on the screen. The following image shows a screen grab of VS running in fullscreen mode. I’m using the ProggyTinyTT font.

 VisualStudio_DellMini9_1024x600

With the tool windows unpinned and set to popup when a compilation or unit test run fails, you get a decent amount of space to write code. Learn the shortcut keys and you’ll have no problem.

For me, the Dell Mini 9 is a very usable light development machine. Mine’s fully set up now and it gets used everyday – more than my home desktop. I use it for browsing, watching channel 9 vids, development, and writing this blog. Now I have no excuse for not updating it more frequently. In a recent company meeting I plugged a projector into it and connected to a webex – well, it would be rude not to show it off! It’s a proper PC but also a fun and very cool toy.


I’ve just started reading Event-Driven Architecture by Addison Wesley. EDA interests me and I’m hoping to take away something that I can apply to non-enterprise specific systems such as AI agents and ecosystems. I’m only a few pages in.

Consider how critical the human nervous system is to your survival as a metaphor to EDA for the enterprise. How critical? Either a cat or a lion steps on your toe – what do you do?

Cat Lion Gun

There’s a guy pointing a gun at a cat! How weird is that? Hopefully the rest of the book is as entertaining.


ValidationAspects v2.1.0 has just been released and is available from codeplex.

ValidationAspects provides State and Interception validation on .net Objects, Properties and Method Parameters. Validation can be declared via attributes and/or augmented/replaced with validation functions at runtime. Supports asp.net MVC, WPF, Silverlight, PostSharp, and Unity.

This release is a mixed bag of minor usability enhancements, bug fixes for when using VA to validate Models derived from generic base classes, and a new built-in validator to validate strings against a Date Format.

Please see the release notes for full details of the changes.


Bloom is a light weight extensibility, discovery and composition framework for Silverlight 2 and the .net Framework. Bloom simplifies the development of component orientated applications and provides simple but flexible Inversion of Control and Dependency Injection.

Bloom has many of the features common to the popular IoC containers and has a similar goal to MEF in that it simplifies the development of extensible component orientated applications.

This will probably be the last release of Bloom – after 3 years of use and several rewrites, I’m happy that it is probably the most near feature complete software I’ve ever written. It is possible that Bloom could be made redundant if MEF makes it into Silverlight for .net 4, but I’m not saddened by this – Bloom has been a great hobby project from which I’ve been able to better architect commercial and hobby projects and also learn a great deal more about .net. I still plan to use Bloom in new projects. It isn’t as powerful as MEF but IMO easier and quicker to use.

You can visit the Bloom wiki on codeplex for more info, and get a taster of some of the things it can do from the following code snippets.

Registering Components

// create a catalog
ICatalog catalog = new Catalog();
// register some components
catalog.Register<Customer>();
catalog.Register(typeof(Account));
// register as a singleton
catalog.Register<User>().SingleInstance();
// register a build function
catalog.Register<AddressBook>.Build(c => new AddressBook(foo));

You can decorate your component classes with the [ComponentAttribute] instead and the Catalog can find and register them. Services do not need to be registered.

Mapping Services to Components

catalog.Map(typeof(ICustomer), typeof(Customer));
catalog.Map<IAddress, Address>();
// perform runtime conditional mapping
catalog.Map<IAccount>(c => condition ? c.Resolve<StandardAccount>() : c.Resolve<GoldAccount>());

Setting the mapping is optional – by default a service will be mapped to the first registered compatible component.

Resolving Components

// resolve a service and perform dependency injection
object instance = catalog.Resolve(typeof(IAccount))
IAccount instance = catalog.Resolve<IAccount>();

Declarations

[Component] // optional
public class User : IUser
{
  // constructor dependency injection
  public User(ILogger logger) {}

  // property dependency injection
  [Dependency]
  public IAddressBook AddressBook { get; set; }

  // factory dependency injection for lazy instantiation
  [Dependency]
  public IFactory<ITransaction> TransactionFactory {get; set; }

  public void Foo()
  {
    // dependency lazy instantiation
    ITransaction t = TransactionFactory.Build();
    t.Do();
  }

  // factory enumeration dependency injection
  [Dependency]
  public IEnumerable<IFactory<IAccount>> AccountFactories { get; set; }

  public void Bar()
  {
    // query and select a factory from the catalog
    foreach (var factory in AccountFactories)
    {
      // query IAccount component type
      if (factory.Type...)
        factory.Build().Do();
    }
  }
}

Bloom v2.1 is open source and can be downloaded from here.


note: This post is just some fun – kerazy speculation on future tech!

I’m currently reading Redemption Ark by Alastair Reynolds. If you’re a space sci-fi fan but haven’t come across Reynolds before, I highly recommend him. Start with Revelation Space. I really like how everything he describes is very technical. His technology of the future is grounded on what we know today but developed from discoveries of particles and laws of physics we have yet to identify. It seems very plausible – well maybe only to someone like me who’s ignorant of anything beyond basic physics 😉

Reynolds describes a human faction called the Conjoiners. They have hive-minded consciousness such that they are able to read and share thoughts and other data with each other by means of their neural implants and brains saturated with nano-technology. They are individuals who share data and not like the Borg drones. What really got me thinking is that you could consider the Conjoiners as being users of Social Networking software such as Twitter and Facebook, directly accessing these apps and data from within their minds instead of a PC and a browser.

Social Networking applications and SaaS (Software as a Service) in general is a big thing right now. So too is cloud computing (this time around at least). We’re starting to see more mainstream uses for the cloud, somewhere to store and share all our data, somewhere to locate an application (software) to do some work on that data. Microsoft Research are working on Social Desktop, which enables you to access your data online and for others to read, reference and comment your data. Could all computing go this way, making use of the infinite storage and processing power of the cloud, where there is just one super computer, the internet, to which we connect to?

Client operating systems would be very lightweight, simply providing connection, presentation, and IO. Mobile devices do this today. Large display and input devices for general application usage are an issue for mobile devices. But what if that client device was a neural implant and your brain provided the display in your mind and took your thoughts as input?

Could the cloud become the Hive? Is this the start of Conjoiner society?

I like the idea of being able to program my own neural implant – TDD obviously! Maybe an application mashup to provide a visual overlay (HUD) of statistics when watching sport, or to program my nano-teched brain to do something more efficient. I guess this would naturally follow that you could simulate the neural behaviour of talented individuals, people who are the best at what they do because of the way their brain is naturally wired. You would download a program which made you talented also – digital, not organic evolution of the human species. I know Kung Fu.


ValidationAspects v2.0.1 has just been released and is available from codeplex.

ValidationAspects provides State and Interception validation on .net Objects, Properties and Method Parameters. Validation can be declared via attributes and/or augmented/replaced with validation functions at runtime. Supports asp.net MVC, WPF, Silverlight, PostSharp, and Unity.

This release fixes a few bugs and adds support for Silverlight (currently State Validation only) and Unity Interception. VA can now run without a dependency on PostSharp for State Validation only. I’ve made a few breaking changes to the core VA API for simplification and to provide validation functions with the validation context – you can now write very powerful validation. I’m pretty happy with the API now so it should be stable going forwards. Future releases will target (lots of) examples, new built-in validators, Silverlight interception, and integration with other technologies.

Please see the release notes for full details of the changes.


This is a post for .net developers using VA, developers considering VA, and also developers not considering VA as the validation framework of their choice.

VA (ValidationAspects) is an validation framework used to validate Objects, Properties and Method Parameters against coding contracts and business rules. Validation can be declared via attributes and/or augmented/replaced programmatically at runtime … more.

ValidationAspects is two and a half months old now, not nearly old enough to have had serious use, but the core, for me, is feature complete. I want to broaden the feature set and the appeal of VA for the next release. I want to know what I can do to make it the right validation framework for your project.

I’ve identified the following three areas where I may be able to achieve this:

  1. Support other aspect frameworks such as Unity Interception and Castle.DynamicProxy2.
  2. Build for different platforms such as Silverlight and the Compact Framework.
  3. Add to the current set of built-in validators.

But I’m guessing – I’d love some feedback – what else could be added or enhanced. Please let me know what’s important to you.

  • If you are using VA, what are the features you would like to see implemented? Are there any general case validators that you would find useful – validators beyond the typical set? How about “FileExists” or “DateBefore”?
  • If VA doesn’t offer what you need, what are the features that you require? What don’t you like about it?
  • In regard to what VA currently offers, what would you like improved? Is the exception formatting approach good for you? Are the default exception messges good to go? What features could do just a little bit more for you? Is there anything that is confusing about the api or the wiki documentation?

Please reply on this post, reply on this discussion thread, raise a new issue, or vote on an issue. I would very much appreciate any feedback you may have.

Many thanks
Mike


Whatever your view on c# regions – love ’em or hate ’em, check out Ora, a popular Visual Studio add-in to aid code navigation written by my colleague Daniel Earwicker.

Why am I telling you this? Because in the latest version Dan added a button to delete regions to meet a requirement I raised.

I want a big button that when clicked will delete all regions in the currently opened file and optionally also the current project / solution / local machine / the world!

This is great! When I see this button I don’t think of it as the Remove Regions button, I think of it as Mike’s button. OK, I sit next to the guy – it’s not the same as emailing Microsoft with a feature request, but it does feel really good being the customer and seeing your feature requests implemented.

ora

I’ve now experienced both sides of feature requests – implementing them, and seeing them implemented for me. Both feel good.

If you’d like to see feature X, consider raising a request. The developer will thank you for the interest, and maybe, you’ll get some software written just for you.

Anyone want to see validator X in the next version of ValidationAspects? 😉


As ValidationAspects is gaining awareness in the .net community I have been asked several times questions regarding its use at a conceptual level, in particular the two modes of validation offered (State & Interception), and how VA (ValidationAspects) differs and overlaps with Code Contracts.

I think the idea of what “Validation” is depends on your viewpoint of whether a model is permitted enter an invalid state. Typically for existing validation frameworks, models are updated with a value that can put the model into an invalid state. The model would then be validated which would check if any of the properties had an invalid value. I call this State Validation. Using aspects to intercept the method or property setter, the setting value can be validated prior to updating the model. The update fails if the value is invalid. I call this Interception Validation. I see Code Contracts pre-conditions as providing the same feature as Interception Validation – the body of the method/property setter will not execute unless all contracts are met.

But can you call Code Contracts pre-conditions Validation? Maybe – in the following example, for Interception Validation you could take the view that you are validating the directoryPath value. So code-contracts are validation but on the value and not the object. If you don’t buy this don’t worry – I want to compare functionality rather than terminology.

public class MyModel
{
  public void Export( string directoryPath )
  {
    Contract.Requires( Directory.Exists( directoryPath ));
    ....
  }
}

OK, so how would you implement this with VA and what do you gain?

[Validate]
public class MyModel
{
  static MyModel()
  {
    // put this code anywhere - it doesn't have to be in the model!
    typeof(Utilities).GetMethod("Export").GetParameters()[0].AddValidation<string>((v, i) => {
      if (!Directory.Exists(v))
        throw new ValidationException(string.Format("Directory {0} does not exist.", v));});
  }

  public void Export([NotNullOrEmpty] string directoryPath )
  {
    ....
  }
}

We’ve added the Validate attribute. This is a PostSharp attribute that will apply VA interceptors to the properties and methods of MyModel. When Export(…) is invoked, the VA interceptor will invoke all VA validation registered to the method and to its properties. We have two validators registered to the directoryPath parameter. The first is applied by an attribute, the second is a lambda expression registered on the parameter. We’ve placed the expression registration in the static constructor but this could be done anywhere AND at any time. VA allows for programmatic replacement and augmentation of validation applied to Types, Properties, Methods, and Method Parameters. This is a very important difference from Code Contracts. We’ve hardcoded validation/pre-conditions but we can change these at runtime.

Why is this useful? Because validation extends beyond simple code contracts into business rules validation – custom/dynamic validation to reflect changing business goals or possibly different deployments. Let’s say you build an Invoice Management system for two different customers, and the system uses an Invoice domain model with an InvoiceId property. For customer A, their business rules dictate that a valid InvoiceId must be an 8-digit numeric, where customer B’s business rules dictate that a valid InvoiceId is 4 digits followed by the invoice’s CustomerId. In code we can declare using a validation attribute that an InvoiceId must not be null or empty – this is one of our model rules. At runtime we augment this validation with the customer’s business rules validation via configuration. Using this approach we can augment domain model validation rules for different deployments. Now when the InvoiceId is set by some means, say UI data entry, and the value fails the business rules validation, a validation exception is thrown to ensure that the Invoice does not enter an invalid state and the user is notified via WPF/asp.net MVC.

So there is an overlap between Code Contracts and Interception Validation but also several important benefits for both approaches. Of course you can always switch off Interception Validation if you prefer and use State Validation and Code Contracts. In the latest drop of VA, the interception feature has been moved out to a separate assembly so there’s no need for the Validate attribute or dependecy on PostSharp.

For a short introduction to ValidationAspects please see this post. VA is open-source and available on codeplex.