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.

Advertisements

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.