Wednesday, March 24, 2010

MVVM - Windows phone 7 series pattern of choice

This post is really for my benefit (although it might help others). Here is a good article on the MVVM (Model-View-ViewModel) pattern that is showing a lot of interest in the WPF communities.

It is very much a different way of thinking when designing UI architecture although very similar to Fowlers relatively new Presentation Model pattern.

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Implementing an IoC container in Silverlight on Windows phone 7 series

I wrote a while ago about implementing a Service Locator for the CompactContainer on the Compact Framework here: http://www.simonrhart.com/2010/02/implementing-commonservicelocator-on.html

I mentioned in that post that I was using the CompactContainer for the CF freely available here: http://code.google.com/p/compactcontainer/ But now as I'm getting into Silverlight as it's the technology of choice when building applications for the Windows phone 7 series platform (as well as XNA), I needed an IoC container to solve the same problems on Silverlight as they do on the Compact Framework.

So I tried to port the container along with the ServiceLocator as blogged about before. I recieved errors in the ComponentCollection class after I tried to compile under Silverlight. Mainly because the following predicate methods such as:
  1. List.FindAll
  2. List.Find

Are not supported in Silverlight 3 as the documentation suggests. However, they are in XNA. As the generic List class belongs to mscorlib.dll (System.Collections.Generic) I noticed that mscorlib is shared for both XNA and Silverlight applications on WP7. I'm trying to find out why this is, or if there is a way of making those methods work in Silverlight.

Anyway it's not the end of the world that those methods are not in Silverlight, all I had to do was replace the following methods in the ComponentCollection class:


public List<ComponentInfo> GetComponentInfoListFor(Type serviceType)
{
return _list.FindAll(ci => ci.ServiceType == serviceType);
}

public ComponentInfo FindForService(Type serviceType)
{
return _list.Find(ci => ci.ServiceType.Equals(serviceType));
}

public ComponentInfo FindForClass(Type classType)
{
return _list.Find(ci => ci.ClassType.Equals(classType));
}

public ComponentInfo FindKey(string key)
{
return _list.Find(ci => ci.Key.Equals(key));
}
With the following code:
public List GetComponentInfoListFor(Type serviceType)
{
List<ComponentInfo> results = new List<ComponentInfo>();

foreach(ComponentInfo component in _list)
{
if (component.ServiceType == serviceType)
results.Add(component);
}
return results;
}

public ComponentInfo FindForService(Type serviceType)
{
ComponentInfo result = null;
foreach(ComponentInfo component in _list)
{
if (component.ServiceType == serviceType)
{
result = component;
break;
}
}
return result;
}

public ComponentInfo FindForClass(Type classType)
{
ComponentInfo result = null;
foreach (ComponentInfo component in _list)
{
if (component.ClassType.Equals(classType))
{
result = component;
break;
}
}
return result;
}

public ComponentInfo FindKey(string key)
{
ComponentInfo result = null;
foreach (ComponentInfo component in _list)
{
if (component.Key.Equals(key))
{
result = component;
break;
}
}
return result;
}
That was all I had to change everything else just compiled and worked. Full dependency injection worked as per on the Compact Framework. It seems moving to Silverlight is going to be less painful than I originally thought!

Tuesday, March 16, 2010

Windows Phone 7 Series emulator is running slow

When I first downloaded the new Windows Phone 7 Series developer tools CTP package, I found the new emulator to be very slow. This is the opposite of what I was expecting as the new emulator is built for x86, runs within a VM and supports hardware GPU host acceleration (so long as you have a gx capable of DirectX10 and at least support for DDI10) - which my laptop does.

To determin whether you have DirectX10 support and at least DDI10, run DxDiag.exe from the command-prompt and inspect the Display tab.

So what next, ok so I learned that in order for the emulator to make use of the GPU host from the VM I needed to enable HW virtualization. So how do I know if I have this enabled? this is enabled at BIOS level and normally disabled by OEMs by default. You can run the Microsoft Hardware-Assisted Virtualization Tool here: http://go.microsoft.com/fwlink/?LinkId=163321



So after running this tool I got the above. So this confirms that I didn't have hw virtualization enabled. After enabling it in the BIOS my Windows Phone 7 Series emulator is now running much faster!

More details about this process here (not WP7 specific): http://www.microsoft.com/windows/virtual-pc/support/configure-bios.aspx



New Windows phone series 7 forum

Ask your new Windows phone 7 series questions here:
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/

Monday, March 15, 2010

Friday, March 12, 2010

Pre-order VS 2010 discount

Microsoft Visual Studio 2010 Professional will launch on April 12 but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of £484.99.

If you use a previous version of Visual Studio or any other development tool then you are eligible for this upgrade. Along with all the great new features in Visual Studio 2010 (see www.microsoft.com/visualstudio) Visual Studio 2010 Professional includes a 12-month MSDN Essentials subscription which gives you access to core Microsoft platforms: Windows 7 Ultimate, Windows Server 2008 R2 Enterprise, and Microsoft SQL Server 2008 R2 Datacenter.

So visit http://www.microsoft.com/visualstudio/en-gb/pre-order-visual-studio-2010 to check out all the new features and sign up for this great offer.

Sunday, February 28, 2010

[ Application Tier ] TF255437: An error occured while querying the Windows Management Instrumentation (WMI) interface on the following computer:

You may have received the following error messsage while processing the Readiness checks during the installation of TFS 2010 CTP recently: [Application Tier] TF255437: An error occured while querying the Windows Management Instrumentation (WMI) interface on the following computer:. The following error message was received: Invalid Namespace.

So I though I'd check that WMI Service is running, and it was. After searching around it turns out I needed to enable WMI Compatibility for IIS 6 under IIS. You can enable this under Server Manager in Server 2008 and change the IIS role.

I think this 'feature' has been fixed for RTM of TFS 2010.

Friday, February 19, 2010

How to find out when your pre-release version of Windows 7 will expire

If you are still running pre-release Windows 7 OS like I am, it will expire soon. So how do you find out when it expires? Simple run winver.exe on the run menu and you'll get this. My copy expires on 1st March 2010.



Zune HD software for x64 platforms

Don't make the same mistake as I did in downloading the x86 version of Zune if you run x64 version of Windows.

Get the x64 version here: http://www.microsoft.com/downloads/details.aspx?FamilyID=9d25c2a6-cae3-49b0-a474-124fe79628a8&displaylang=en

Note: The x64 version is ~400mb where as the x86 is ~50mb !

Preview of Windows phone 7 Series

Thursday, February 18, 2010

It's Windows phone 7 Series time at MIX this year

It's no secret that MIX will be covering a lot of the Windows phone 7 Series content this year in Las Vegas (March 15th - 17th).

I just wish I was going, perhaps if I can find a cheap flight.....

Note: Windows phone sessions to be confirmed...

http://live.visitmix.com/

Wednesday, February 17, 2010

Implementing the CommonServiceLocator on the Compact Framework

You may have come across or used the CommonServiceLocator API as developed by the p&p team at Microsoft for your desktop applications in the past.

Before we go any further, it is worth explaining what a Service Locator is. The Service Locator is a pattern that abstracts your retriveal of components or services from the underlying container model that is used to house them.

So no matter what container you use, i.e. Castle Windsor, Spring, StructureMap etc pulling anything from the container in code will always be the same and consistent across layers.

Martin Fowler explains it better than I can here: http://www.martinfowler.com/articles/injection.html

All you have to do is write an implementor for the Service Locator to use. You'll note all the famous ones on the site above have already been implemented. But of course these don't work on the CF, so what do we do?

Firstly, you need to download the source code for the CommonServiceLocator as the project needs to be modified slightly. Simply remove all references to the ActivationException.Desktop class as the constructors in that class are not supported on the CF. That is it! - for the service locator project. Now all that remains is the implementor. This depends on what container you are using. We have been using a container called CompactContainer written by Germán Schuager that works well (uses reflection as it supports true dependency injection).

CompactContainer can be downloaded from here: http://code.google.com/p/compactcontainer/ it is freely available under the Apache Licence.

In order to write an implementor for the CommonServiceLocator, all you need to do is write a class that derives from abstract class ServiceLocatorImplBase, then tell the service locator where the instance of the container is and a reference to itself. This class implements IServiceLocator too, so itself can be injected into classes - for whatever reason.

The class is really simple, it could look something like this, here we have named it CompactServiceLocator:

public class CompactServiceLocator : ServiceLocatorImplBase
{
private readonly IContainer _compactContainer;
private bool _disposed;
public CompactServiceLocator(IContainer compactContainer)
{
_compactContainer = compactContainer;
}


protected override object DoGetInstance(Type serviceType, string key)
{
object resolvedObject = null;

// Resolve using a key if we have a key
if (!key.IsNull())
{
resolvedObject = _compactContainer.Resolve(key);
}

// Resolve using type if the object has not been resolved
if(resolvedObject == null && !serviceType.IsNull())
{
resolvedObject = _compactContainer.Resolve(serviceType);
}

return resolvedObject;
}

protected override IEnumerable<object>
DoGetAllInstances(Type serviceType)
{
return _compactContainer.GetServices(serviceType);
}

private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_compactContainer.Dispose();
}
_disposed = true;
}
}

public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

}
So essentially the above code is fairly simple in that all it is doing is it allows the service locator to call your specific container method. i.e. the implementation of method DoGetInstance() calls the specific container method to get an instance from the container. In this case it is method Resolve(). It is just implementation specific code which will look different from container to container.

So now you have written an implementor to go along side the Castle Windsor etc adapters, how do you use it? Well first you have to tell the Service Locator the container instance it should use, then set a reference to the service locator interface that maps to itself, like so:
Container container = new Container();
ServiceLocator.SetLocatorProvider(() => new CompactServiceLocator(container));
container.AddComponentInstance<IServiceLocator>(ServiceLocator.Current);
Container in this case is the CompactContainer freely available as mentioned above.

Asking for services is done as follows:
ServiceLocator.Current.GetInstance<IFooBar>();
Where IFooBar is your registered interface on the container.

That is it - as easy as that. If anyone would like me to put together a complete solution demoing this, please let me know. I didn't do it as the code is all available on line apart from the CompactContainer ServiceLocator implementor.

Windows Mobile 6.5.3 Developer Toolkit Released

You may have noticed that the Windows Mobile 6.5.3 SDK was released two weeks ago for 1 day then pulled from MSDN. I don't think Microsoft has made a public announcement why this was, but it is back under a new name. The 6.5.3 Developer Toolkit was uploaded today and can be downloaded from here:

http://www.microsoft.com/downloads/details.aspx?FamilyID=c0213f68-2e01-4e5c-a8b2-35e081dcf1ca&displaylang=en

Of course be sure to change your target project type within Visual Studio to make use of the new emulators.

Tuesday, February 16, 2010

Windows Phone 7 Series Announced at MWC



You've probably heard by now that Microsoft has announced Windows Phone 7 Series to the community on 15 Feb at the Mobile World Congress conference in Barcelona by Steve Ballmer. The Microsoft official press release can be found here.

I have to say the platform looks awesome. It looks very Zune HD like which is partly to do with the fact that Joe Belfiore is on the design team.

The best publicly available video to date that shows the platform UX is over on channel9 here:
http://channel9.msdn.com/posts/LauraFoy/First-Look-Windows-Phone-7-Series-Hands-on-Demo/

Dev Story:
If you're expecting to hear about the developer story or anything to do with the application platform then you'll be disappointed. Microsoft has not made any thing public regarding tools, frameworks etc for the new wave of Windows Phone 7 Series products. Microsoft is gearing up to tell the community about the developer story at MIX in Las Vegas on March 15-17. For sessions on Windows Phone 7 Series at this event see here.

For developer story announcements keep an eye on Charlie Kindels' blog as he is responsible for the Windows Phone 7 Series application platform.

The Windows team blog has a post on the announcement here.

The Windows Phone twitter hashtag is: #wm7

In Seattle at Summit



So it's that time of year again, I'm at the MVP Summit 2010 this year and looking forward to it as there are many new and exciting technologies being released out of Redmond.

I will post the stuff I can here.

Friday, October 30, 2009

Writing designer friendly controls for Windows Mobile

One thing that you sometimes need when writing Visual Studio designer friendly controls for Windows Mobile, is knowing if your code is running in design time - which is essentially running on the desktop or not. You need to know this because if you are running on the desktop (design time) you don't want to call device specific dlls.

The following code can be used to determine this:
public static class DesignMode
{
private static byte _mode = 255;

public static bool IsTrue
{
get
{
if (_mode == 255)
_mode = AppDomain.CurrentDomain.FriendlyName.Contains("DefaultDomain")
? (byte)1 : (byte) 0;
return _mode == 1;
}
}
}
So essentially you can then code in your application:
if (DesignMode.IsTrue)
{
//don't call coredll.dll
}
else
{
//call coredll.dll
}

Thursday, September 24, 2009

Zune HD

Review by WMExperts on the new Zune HD, very cool indeed:

Thursday, June 18, 2009

TechNet UK Virtual Conference 2009

Another virtual conference will be taking place tomorrow (Friday 19th June) which is the TechNet UK Virtual Conference.

Please find more information here: http://technet.microsoft.com/en-gb/dd819085.aspx

Sunday, June 14, 2009

DbDataReader.DoesColumnExist

Have you ever wanted to code something like the following:
var dbCommand = Database.DbProviderFactory.CreateCommand();
dbCommand.CommandText = "select * from MyTable";
var reader = Database.ExecuteReader(dbCommand, null);
if (reader.Read())
{
if (reader.DoesColumnExist("mycolumn")
{
//Then we know its safe to select the column.
}
}
You're probably thinking, why would I want to do that? well if you're building a generic data handler library and you don't know what columns have been selected but you know the columns that could be selected then it is very useful as using the indexer to return the data for the specified column will throw an exception if it doesn't exist.

I thought this extension method solves this problem and would be useful for others:
public static class DbDataReaderExtensions
{
public static bool DoesColumnExist(this IDataReader reader, string column)
{
if (reader.IsNull()) throw new ArgumentNullException("reader");
if (string.IsNullOrEmpty(column)) throw new ArgumentNullException("column");

for (var i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Equals(column))
return true;
}
return false;
}
}
It's relatively straight forward but saves you from writing the same piece of code over and over again.

The unit test class for this is as follows:
[TestClass]
public class DataReaderExtensionsTests
{
[TestMethod]
public void ThrowsIfNullReaderIsPassed()
{
const MockDbDataReader reader = null;
AssertExt.Throws<ArgumentNullException>(() => reader.DoesColumnExist("foo"));
}

[TestMethod]
public void ThrowsIfNullColumnIsPassed()
{
var reader = new MockDbDataReader();
AssertExt.Throws<ArgumentNullException>(() => reader.DoesColumnExist(null));
AssertExt.Throws<ArgumentNullException>(() => reader.DoesColumnExist(string.Empty));
}

[TestMethod]
public void ValidExists()
{
var reader = new MockDbDataReader();
Assert.IsTrue(reader.DoesColumnExist("One"));
Assert.IsTrue(reader.DoesColumnExist("Two"));
Assert.IsTrue(reader.DoesColumnExist("Three"));
Assert.IsTrue(reader.DoesColumnExist("Four"));
Assert.IsTrue(reader.DoesColumnExist("Five"));
}

[TestMethod]
public void InvalidExists()
{
var reader = new MockDbDataReader();
Assert.IsFalse(reader.DoesColumnExist("foo"));
Assert.IsFalse(reader.DoesColumnExist("bar"));
}
}
You'll notice I have mocked the DbDataReader. Because there are mocking frameworks on the Compact Framework and probably will not be for some time (due to CF limitations) I have created a mocked class implementing the IDataReader interface. This mock class looks like the following:
public class MockDbDataReader : IDataReader
{
readonly Dictionary<int, string> getName = new Dictionary<int, string>();
public MockDbDataReader()
{
getName.Add(0, "One");
getName.Add(1, "Two");
getName.Add(2, "Three");
getName.Add(3, "Four");
getName.Add(4, "Five");
}

#region IDataReader Members

public void Close()
{
throw new NotImplementedException();
}

public int Depth
{
get { throw new NotImplementedException(); }
}

public DataTable GetSchemaTable()
{
throw new NotImplementedException();
}

public bool IsClosed
{
get { throw new NotImplementedException(); }
}

public bool NextResult()
{
throw new NotImplementedException();
}

public bool Read()
{
throw new NotImplementedException();
}

public int RecordsAffected
{
get { throw new NotImplementedException(); }
}

#endregion

#region IDisposable Members

public void Dispose()
{
throw new NotImplementedException();
}

#endregion

#region IDataRecord Members

public int FieldCount
{
get { return 5; }
}

public bool GetBoolean(int i)
{
throw new NotImplementedException();
}

public byte GetByte(int i)
{
throw new NotImplementedException();
}

public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}

public char GetChar(int i)
{
throw new NotImplementedException();
}

public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}

public IDataReader GetData(int i)
{
throw new NotImplementedException();
}

public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}

public DateTime GetDateTime(int i)
{
throw new NotImplementedException();
}

public decimal GetDecimal(int i)
{
throw new NotImplementedException();
}

public double GetDouble(int i)
{
throw new NotImplementedException();
}

public Type GetFieldType(int i)
{
throw new NotImplementedException();
}

public float GetFloat(int i)
{
throw new NotImplementedException();
}

public Guid GetGuid(int i)
{
throw new NotImplementedException();
}

public short GetInt16(int i)
{
throw new NotImplementedException();
}

public int GetInt32(int i)
{
throw new NotImplementedException();
}

public long GetInt64(int i)
{
throw new NotImplementedException();
}

public string GetName(int i)
{
return getName.ContainsKey(i) ? getName[i] : string.Empty;
}

public int GetOrdinal(string name)
{
throw new NotImplementedException();
}

public string GetString(int i)
{
throw new NotImplementedException();
}

public object GetValue(int i)
{
throw new NotImplementedException();
}

public int GetValues(object[] values)
{
throw new NotImplementedException();
}

public bool IsDBNull(int i)
{
throw new NotImplementedException();
}

public object this[string name]
{
get { throw new NotImplementedException(); }
}

public object this[int i]
{
get { throw new NotImplementedException(); }
}

#endregion
}
All we have done is returned 5 for the FieldCount, then provided some data so when GetName() is called we return the relevant item in the dictionary to resemble a real data reader object.

We could have written an integration test but this is pointless as we know the DataReader class has been tested and works.

The unit test class above gives 100% code coverage.

Thursday, June 04, 2009

JP Morgan Chase & Co. Corporate Challenge



Hitachi Consulting (including me) is participating in the JP Morgan Chase & Co. Corporate Challenge which is a world wide fundraising event in most major cities throughout the world.

Hitachi Consulting's goal is to raise £1000 for the Down's Syndrome Association and the challenge is a 6.5km run around Battersea park in London on the 9th July 2009.

If you were feeling generious :) you can sponsor the us over at:

http://www.justgiving.com/hcukjpmorganchallenge2009