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
Thursday, June 18, 2009
Sunday, June 14, 2009
DbDataReader.DoesColumnExist
Have you ever wanted to code something like the following:
I thought this extension method solves this problem and would be useful for others:
The unit test class for this is as follows:
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.
var dbCommand = Database.DbProviderFactory.CreateCommand();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.
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.
}
}
I thought this extension method solves this problem and would be useful for others:
public static class DbDataReaderExtensionsIt's relatively straight forward but saves you from writing the same piece of code over and over again.
{
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;
}
}
The unit test class for this is as follows:
[TestClass]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 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"));
}
}
public class MockDbDataReader : IDataReaderAll 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.
{
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
}
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:
Saturday, May 23, 2009
Microsoft patterns & practices Summit 2009

Microsoft are hosting the patterns & practices Summit Oct 12th - 16th 2009 at the Microsoft Conference Centre on Microsoft Campus in Redmond, WA.
To learn more about this event, see here: http://msdn.microsoft.com/en-us/practices/dd578307.aspx
Saturday, May 09, 2009
Microsoft Architect Insight Conference May 8th 2009 Mobile Decks for download

As promised to the delegates at the recent Microsoft Architect Insight Conference held on 8th May 2009 at Microsoft London Victoria, I have uploaded the decks from my breakout which was presented with Dave Baker from the Developer and Platform Group at Microsoft and my interactive session for download.
The two decks were used in the sessions Extending the Enterprise through Mobile and Mobile Implementation Patterns. Please note: the interactive Mobile Implementation Patterns deck is very light and the session was very much a chalk and talk session. I opened it up for debate for just about anything mobile. This deck contains some information about Hitachi Consulting who we are, our clients we've worked with which may interest you.
Thanks to Dave for giving a great session and also thanks to all the delegates in the interactive who made it a good discussion session.
You can download the decks here.
Monday, April 13, 2009
Copying dependency files to the output directory when running unit tests with MSTest
A rather long title don't you think :) But have you ever wanted to write a unit test using Visual Studio Test Edition and MSTest to have a dependency on configuration files other than app.config to fulfill your test?
This post is mainly about test support for device testing but is the same for desktop testing too.
Now, most people use app.config as a configuration file in .NET for desktop applications. On devices, System.Configuration is not supported. So some device developers end up writing there own configuration reader by serializing the XML into an object. Alternatively they use the class from OpenNETCF SDF or they might parse the XML using LINQ to XML or plain old System.Xml.
Personally I tend to use the serialization option. My configuration files are not named app.config I tend to name them something more specific. You'll find Visual Studio or the test engine does not deploy any other file to the tests Output directory, even if you set properties Build Action to Content and Copy to Output Directory to Copy always. Running your test will fail if you have a dependency on the given configuration file as Visual Studio will not deploy the custom configuration file. It is highly likely most desktop developers have never seen this or unaware this limitation exists because most desktop devs use app.config. In most cases for desktop devs there is no problem.
So how do device guys get around this problem? You can use the same technique as the Mobile p&p team do with the DataAccess block which forms part of the recent Mobile Application Blocks drop: http://www.codeplex.com/Mobile. In one of there test projects they have a mock database dependency that is tested on the desktop but need a sample database to test against.
They set the Build Action to Embedded Resource then they use reflection to unpack it. You might think this is quite a bit of work, but they have a reusable class named TestResourceFile that belongs to the TestUtilities project. Using this class does all the unpacking for you.
The code to copy this dependency could look like the following (I've taken this from the p&p Mobile codebase):
I've got to say thanks to Chris Tacke for telling me about this attribute class.
This post is mainly about test support for device testing but is the same for desktop testing too.
Now, most people use app.config as a configuration file in .NET for desktop applications. On devices, System.Configuration is not supported. So some device developers end up writing there own configuration reader by serializing the XML into an object. Alternatively they use the class from OpenNETCF SDF or they might parse the XML using LINQ to XML or plain old System.Xml.
Personally I tend to use the serialization option. My configuration files are not named app.config I tend to name them something more specific. You'll find Visual Studio or the test engine does not deploy any other file to the tests Output directory, even if you set properties Build Action to Content and Copy to Output Directory to Copy always. Running your test will fail if you have a dependency on the given configuration file as Visual Studio will not deploy the custom configuration file. It is highly likely most desktop developers have never seen this or unaware this limitation exists because most desktop devs use app.config. In most cases for desktop devs there is no problem.
So how do device guys get around this problem? You can use the same technique as the Mobile p&p team do with the DataAccess block which forms part of the recent Mobile Application Blocks drop: http://www.codeplex.com/Mobile. In one of there test projects they have a mock database dependency that is tested on the desktop but need a sample database to test against.
They set the Build Action to Embedded Resource then they use reflection to unpack it. You might think this is quite a bit of work, but they have a reusable class named TestResourceFile that belongs to the TestUtilities project. Using this class does all the unpacking for you.
The code to copy this dependency could look like the following (I've taken this from the p&p Mobile codebase):
private TestResourceFile CreateDbFile()But even still there is a better way to solve this problem and that is to use the DeploymentItemAttribute class. It's use is simple. The following code illustrates it use:
{
dbFile = new TestResourceFile(this, "MockDatastore.sdf");
connectionString = String.Format(connectionStringPattern, dbFile.Filename);
return dbFile;
}
[TestMethod]
public void ThrowsIfNullParameterNameIsPassed()
{
using (TestResourceFile file = CreateDbFile())
{
using (Database database = new SqlDatabase(connectionString))
{
Database service = new SqlDatabase(connectionString);
ExtendedAssert.Throws(
delegate { DbParameter param = service.CreateParameter(null, "Maria Anders"); });
}
}
}
[DeploymentItem("Mobile.DataMapper.config")]The above code will copy the file "Mobile.DataMapper.config" to the test output directory. You need to ensure to set the file properties Build Action to Content and Copy to Output Directory to Copy always.
[TestClass]
public class DataContextFactoryTests
{
}
I've got to say thanks to Chris Tacke for telling me about this attribute class.
Sunday, April 12, 2009
http://answers.microsoft.com
Microsoft has recently (last few months) announced and released a website for Windows Vista users to post questions here: http://answers.microsoft.com.
There is quite a large MVP presence there to answer your Windows Vista questions.
There is quite a large MVP presence there to answer your Windows Vista questions.
Friday, April 10, 2009
What type of applications can we build on Windows Mobile today - Part 3 of 10
This is part 3 of 10 of the getting started with Windows Mobile development series. For previous posts in this series please see here.
Today mobile development is getting easier. Many folks from the desktop can port there C# skills over and hit the ground running fairly quickly. The Compact Framework is maturing nicely. Development tools and emulators are getting more feature rich and more reliable.
The types of applications you can build today for Windows Mobile - with regards to managed code fall into the following groups:
ASP.NET for Mobile no longer has designer support in Visual Studio 2008. You can simply use the desktop controls and they will render. Now with "6on6" which is IE 6 engine on Windows Mobile 6.1 this will make web development for mobile easier. You can test IE 6 with the recently released WM 6.1 emulators. I wrote a post on this here. One thing to bear in mind is of course screen size.
Most developers write .NET Compact Framework applications over ASP.NET for LOB (Line of Business applications) due to the smart client nature. Also the power of a .NET CF application allows the developer to do whatever he wants. You can access the camera the GPS chipset the radio or the phone. You can access Outlook, manipulate appointments or add/change a contact. You can access a Relational Database Management system such as SQL Server Compact to store your applications data then sync back to SQL Server desktop using Sync Services (Sync Framework). You can write very compelling UI using GDI or on later devices GDI+ for support such as gradient backgrounds and transparency. XNA sadly is not supported, however DirectX is but is limited and memory intensive.
The main power of using the .NET Compact Framework over any other technology is the fact that it is embedded and works great in smart client environments where connectivity is an issue.
ASP.NET is rarely used in my experience, one reason is due to the connectivity issues. Under ASP.NET, mobile devices require a constant connection with the server in order for this type of architecture to work. Web applications do not work well in enterprise solutions for mobile devices. They do work well for consumer applications but not mission critical ones.
You'll probably be thinking how do you architect an application for the .NET Compact Framework. Most developers adopt the Active record pattern for the business layer. This tends to work well as mobile applications tend not to be as complex as desktop applications. And now performance tends not to be so much of a problem as it once was. ORMs and Domain Driven Development with patterns such as the repository data access layer is not quite as good a story.
The only ORM that supports the CF and SQL CE to date is LLBLGen. I am in the process of building an ORM for the Compact Framework and intend on writing an MSDN article how I did it.
The CF 3.5 does support WCF as a consumer, ServiceHost is not supported. There are many binding and other limitations however. Usually the device will have its own domain that uses either a message protocol which can be completely bespoke over TCP or a service layer with standard DTOs via HTTP. Or in some cases Sync data directly using Sync Services or merge replication. Each application is different. Of course vanilla Web Services ASMX has been supported since CF 1.0.
Today mobile development is getting easier. Many folks from the desktop can port there C# skills over and hit the ground running fairly quickly. The Compact Framework is maturing nicely. Development tools and emulators are getting more feature rich and more reliable.
The types of applications you can build today for Windows Mobile - with regards to managed code fall into the following groups:
- Microsoft .NET Compact Framework. This is a subset of the Microsoft .NET Frameworkdesigned specifically for mobile devices. Use this technology for mobile applications that must run on the device without guaranteed network connectivity.
- ASP.NET Mobile. This is a subset of ASP.NET, designed specifically for mobile devices. ASP.NET Mobile applications can be hosted on a normal ASP.NET server. Use this technology for mobile Web applications when you need to support a large number of mobile devices and browsers that can rely on a guaranteed network connection.
ASP.NET for Mobile no longer has designer support in Visual Studio 2008. You can simply use the desktop controls and they will render. Now with "6on6" which is IE 6 engine on Windows Mobile 6.1 this will make web development for mobile easier. You can test IE 6 with the recently released WM 6.1 emulators. I wrote a post on this here. One thing to bear in mind is of course screen size.
Most developers write .NET Compact Framework applications over ASP.NET for LOB (Line of Business applications) due to the smart client nature. Also the power of a .NET CF application allows the developer to do whatever he wants. You can access the camera the GPS chipset the radio or the phone. You can access Outlook, manipulate appointments or add/change a contact. You can access a Relational Database Management system such as SQL Server Compact to store your applications data then sync back to SQL Server desktop using Sync Services (Sync Framework). You can write very compelling UI using GDI or on later devices GDI+ for support such as gradient backgrounds and transparency. XNA sadly is not supported, however DirectX is but is limited and memory intensive.
The main power of using the .NET Compact Framework over any other technology is the fact that it is embedded and works great in smart client environments where connectivity is an issue.
ASP.NET is rarely used in my experience, one reason is due to the connectivity issues. Under ASP.NET, mobile devices require a constant connection with the server in order for this type of architecture to work. Web applications do not work well in enterprise solutions for mobile devices. They do work well for consumer applications but not mission critical ones.
You'll probably be thinking how do you architect an application for the .NET Compact Framework. Most developers adopt the Active record pattern for the business layer. This tends to work well as mobile applications tend not to be as complex as desktop applications. And now performance tends not to be so much of a problem as it once was. ORMs and Domain Driven Development with patterns such as the repository data access layer is not quite as good a story.
The only ORM that supports the CF and SQL CE to date is LLBLGen. I am in the process of building an ORM for the Compact Framework and intend on writing an MSDN article how I did it.
The CF 3.5 does support WCF as a consumer, ServiceHost is not supported. There are many binding and other limitations however. Usually the device will have its own domain that uses either a message protocol which can be completely bespoke over TCP or a service layer with standard DTOs via HTTP. Or in some cases Sync data directly using Sync Services or merge replication. Each application is different. Of course vanilla Web Services ASMX has been supported since CF 1.0.
Monday, April 06, 2009
Preview of Windows Mobile 6.5 at MIX
Checkout WM 6.5 by Loke Uei Tan (requires Silverlight). See other videos here: http://videos.visitmix.com/MIX09/All
Thursday, April 02, 2009
An example of the Plugin pattern on the Compact Framework
I have been talking about IoC containers on the Compact Framework lately and thought I'd show an example of implementing a simpler example of separating concerns. There is another common pattern to which IoC I believe was derived called the Plugin pattern.
The Plugin pattern is talked about by Martin Fowler in his Patterns Of Enterprise Application Architecture book (good book by the way). It is (in my opinion) a simpler solution to IoC but is a little more limited and doesn't usually involve a framework.
I involves using reflection and creating a factory to create a type usually specified in a configuration file using a common interface. This pattern promotes Aspect Oriented Programming.
As I am in the process of building a managed ORM for the Compact Framework, I decided to use the Plugin pattern for building the data context part of the API. I decided this because the Plugin is easy to implement and doesn't require any framework to implement. I wanted to keep the ORM as simple as possible while at the same time making the framework decoupled from the type of database desired.
As mentioned I am using this pattern for the data context part of my ORM and I have a configuration file used to specify the type of database. Doing this enables me to easily change my database without having to rewrite a vast majority of my application. I don't even need to recompile my app. I can simply change the config and re-run my app.
The configuration setting that specifies the database dialect looks like this:
Part of the DataContext class looks like this:
For those interested, this is based on the Mobile Client Software Factory. I will be publishing the source code to my ORM for Windows Mobile soon - once finished.
So as we saw, the DataContext is abstract and it contains an interface. Just so you can see, the interface looks like this:
So now we have four things:
1. Configuration file that tells us what datacontext to use.
2. The datacontext implementation (SQL CE Server) to use.
3. The base datacontext class.
4. The datacontext implementation.
The only thing that is missing to put all this together so the consumer can just work with the interface (as the consumer doesn't care about where the data lives or how the data is retrieved) is the DataContextFactory.
The Factory is very simple. It looks like this:
So using this code from the consumer looks like this:
You could implement this architecture with the IoC framework and using dependency injection pattern but the current one developed by the p&p team at Microsoft doesn't have support for configuration files. This means you'd have to recompile your app anytime you change the DataContext implementor. Now, no doubt Microsoft will roll out another version that supports configuration files in the future as the ContainerModel is a fairly early drop.
So the benefit with this implementation is, it's really really easy to implement and doesn't require any framework. If the implementors existed in another assembly, you could easily change the DataContextFactory to use the LoadFrom method to load a given assembly.
The Plugin pattern is talked about by Martin Fowler in his Patterns Of Enterprise Application Architecture book (good book by the way). It is (in my opinion) a simpler solution to IoC but is a little more limited and doesn't usually involve a framework.
I involves using reflection and creating a factory to create a type usually specified in a configuration file using a common interface. This pattern promotes Aspect Oriented Programming.
As I am in the process of building a managed ORM for the Compact Framework, I decided to use the Plugin pattern for building the data context part of the API. I decided this because the Plugin is easy to implement and doesn't require any framework to implement. I wanted to keep the ORM as simple as possible while at the same time making the framework decoupled from the type of database desired.
As mentioned I am using this pattern for the data context part of my ORM and I have a configuration file used to specify the type of database. Doing this enables me to easily change my database without having to rewrite a vast majority of my application. I don't even need to recompile my app. I can simply change the config and re-run my app.
The configuration setting that specifies the database dialect looks like this:
<property name="datacontext" value="Mobile.DataMapper.Dialect.SqlServerCe35DataContext"/>The SqlServerCe35DataContext looks like:
public class SqlServerCe35DataContext : DataContextThe DataContext class contains the default implementation of SQL Server CE and is defined as an abstract class. It also implements the IDataContext interface which we use in our factory. This enables us to use the Plugin pattern successfully.
{
private SqlDatabase _database;
private readonly MsSqlCe35Dialect _dialect;
public SqlServerCe35DataContext()
{
_dialect = new MsSqlCe35Dialect();
}
internal override Database Database
{
get
{
if (_database == null) _database = new SqlDatabase(ConnectionString);
return _database;
}
}
internal override Dialect Dialect
{
get { return _dialect; }
}
}
Part of the DataContext class looks like this:
public abstract class DataContext : IDataContextI've omitted many memebers as it's not important what this class does. What is important is the implementation in order to implement this pattern for devices.
{
private DbTransaction _transaction;
private string _connectionString;
public virtual void Commit()
{
if (_transaction.IsNull()) throw new InvalidOperationException("There is no transaction for this session.");
_transaction.Commit();
}
public virtual void BeginTransaction()
{
_transaction = Database.GetConnection().BeginTransaction();
}
public virtual void BeginTransaction(IsolationLevel isolationLevel)
{
_transaction = Database.GetConnection().BeginTransaction(isolationLevel);
}
internal abstract Database Database
{
get;
}
internal abstract Dialect Dialect
{
get;
}
}
For those interested, this is based on the Mobile Client Software Factory. I will be publishing the source code to my ORM for Windows Mobile soon - once finished.
So as we saw, the DataContext is abstract and it contains an interface. Just so you can see, the interface looks like this:
public interface IDataContext : IDisposableAs I said I omitted most of the above members from the DataContext class above for clarity as I want to focus on the architecture not implementation details for this post.
{
string ConnectionString { get; set; }
//Transaction management.
void Commit();
void Rollback();
bool IsInTransaction{ get;}
void BeginTransaction();
void BeginTransaction(IsolationLevel isolationLevel);
IList<TEntity> Read<TEntity>(QueryExpressionCollection queryExpressionCollection);
IList<TEntity> Read<TEntity>(QueryExpressionCollection
queryExpressionCollection, List<Func<ObjectProperty>> columnsInScope);
IList<TEntity> FindAll<TEntity>();
TEntity Read<TEntity>(object id);
int Delete<TEntity>(TEntity entity);
TEntity Save<TEntity>(TEntity entity);
string DatabaseName { get; set; }
}
So now we have four things:
1. Configuration file that tells us what datacontext to use.
2. The datacontext implementation (SQL CE Server) to use.
3. The base datacontext class.
4. The datacontext implementation.
The only thing that is missing to put all this together so the consumer can just work with the interface (as the consumer doesn't care about where the data lives or how the data is retrieved) is the DataContextFactory.
The Factory is very simple. It looks like this:
public class DataContextFactoryNotice how we have another dependency the IDataMapperConfiguration. There's no need to document this code but quite simply it's a serialized object of the XML posted earlier. We get two things from this XML file 1. The ConnectionString and 2. The concrete DataContext class that implements DataContext. Notice how we set the ConnectionString property after the type has been created. We do this because the CF only supports one Assembly.CreateInstance method that accepts the type to create.
{
private IDataContext _instance;
public DataContextFactory()
{
CreateInstance(null);
}
public DataContextFactory(IDataMapperConfiguration dataMapperConfiguration)
{
CreateInstance(dataMapperConfiguration);
}
private void CreateInstance(IDataMapperConfiguration dataMapperConfiguration)
{
if (dataMapperConfiguration == null)
dataMapperConfiguration = MapperFactory.CreateDataMapperConfiguration();
var dataContext = dataMapperConfiguration.DataContext;
var asm = Assembly.GetExecutingAssembly();
_instance = (IDataContext)asm.CreateInstance(dataContext.Value);
if (dataMapperConfiguration.HasConnectionString)
_instance.ConnectionString = dataMapperConfiguration.ConnectionString.Value;
}
public IDataContext GetDataContext
{
get
{
return _instance;
}
}
}
So using this code from the consumer looks like this:
IDataContext context = new DataContextFactory().GetDataContext;then the consumer can work with this interface as opposed to the implementation. The consumer knows nothing about the underlying database or storage. If you changed the database from Sql CE to SQLLite for example, it is a simple case of changing the configuration file, then re-running the app.
You could implement this architecture with the IoC framework and using dependency injection pattern but the current one developed by the p&p team at Microsoft doesn't have support for configuration files. This means you'd have to recompile your app anytime you change the DataContext implementor. Now, no doubt Microsoft will roll out another version that supports configuration files in the future as the ContainerModel is a fairly early drop.
So the benefit with this implementation is, it's really really easy to implement and doesn't require any framework. If the implementors existed in another assembly, you could easily change the DataContextFactory to use the LoadFrom method to load a given assembly.
Wednesday, April 01, 2009
Dependency injection using the ContainerModel on the Compact Framework
I mentioned a few weeks ago about the availability of an IoC framework for the Compact Framework here.
But a question related to this is how do you implement the dependency injection pattern with this IoC framework as IoC (Inversion of Control) and dependency injection go hand in hand with one another.
The most common way to implement dependency injection is via the constructor. Sadley this container doesn't work like Castle Windsor where Castle resolves dependencies for you automatically without you having to define then when registering the class. However the class still needs to be defined by an interface! With the device Container model you have to explicitly define your dependencies at registration. I'm ok with this as I'm happy to have a half decent container model for the Compact Framework.
So we have our CustomerRepository class that has a dependency on some Adapter (I just made this adapter up, it could do anything). The class looks like this:
So how do we set up the container to inject the adapter. Something like the following should do the trick:
There we have it, dependency injection using an IoC container on the Compact Framework 3.5.
But a question related to this is how do you implement the dependency injection pattern with this IoC framework as IoC (Inversion of Control) and dependency injection go hand in hand with one another.
The most common way to implement dependency injection is via the constructor. Sadley this container doesn't work like Castle Windsor where Castle resolves dependencies for you automatically without you having to define then when registering the class. However the class still needs to be defined by an interface! With the device Container model you have to explicitly define your dependencies at registration. I'm ok with this as I'm happy to have a half decent container model for the Compact Framework.
So we have our CustomerRepository class that has a dependency on some Adapter (I just made this adapter up, it could do anything). The class looks like this:
public class CustomerRepository : Repository<Customer, int>, ICustomerRepositoryNow, there are no methods in this class but the point is to show the dependency because later, we want to use the adapter class to do some... adapting.
{
private IAdapter _adapter;
public CustomerRepository(IAdapter adapter)
{
if (adapter.IsNull()) throw new ArgumentNullException("adapter");
_adapter = adapter;
}
}
So how do we set up the container to inject the adapter. Something like the following should do the trick:
using Microsoft.Practices.Mobile.ContainerModel;
var builder = new ContainerBuilder();Then from the consumer, we can code something like the following:
builder.Register<IAdapter>(adapter => new Adapter());
builder.Register<ICustomerRepository>(repository => new CustomerRepository(Resolve<IAdapter>()));
builder.Build(container);
var customerRepository = ComponentContainer.Resolve<ICustomerRepository>();We didn't have to declare our dependency, it was injected by the framework. We just resolved the adapter when we registered the repository. Of course you need to register this dependency with the framework first. You could use the concrete type here but this means if you change implementation details, you'd have to change the implementor in more than one place.
There we have it, dependency injection using an IoC container on the Compact Framework 3.5.
Wednesday, March 25, 2009
Missing IEnumerable<T>.ForEach(Action<T> action)
Have you ever wanted to code something like this in .NET 3.5:
The Repository and domain object in the above case looks like this:
The benefit of this is it simply reads better with less code.
You might find this library found on codeplex useful: http://extensionmethodsyay.codeplex.com/
var repository = new CustomerRepository();Where Customers is of type Collection. Well you can't out of the box as the framework doesn't provide an extension for IEnumerable foreach (which is what Collection implements).
repository.Customers.ForEach(customer => Console.WriteLine(string.Format("Customer: {0} {1}",
customer.FirstName, customer.LastName)));
Console.Read();
The Repository and domain object in the above case looks like this:
public class CustomerRepositoryYou can make the above call work with this simple extension for IEnumerable:
{
public CustomerRepository()
{
Customers = new Collection<Customer>()
{
new Customer()
{
FirstName = "Simon",
LastName = "Hart"
},
new Customer()
{
FirstName = "Joe",
LastName = "Bloggs"
}
};
}
public ICollection<Customer> Customers
{
get; set;
}
}
public class Customer
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
}
public static class GenericIEnumerableExtensionsIt's quite simple in that it accepts one parameter, an Action delegate with one parameter - this could be extended to do whatever you want. Although the above is in line with the List.ForEach extension method.
{
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (var item in collection)
{
action(item);
}
}
}
The benefit of this is it simply reads better with less code.
You might find this library found on codeplex useful: http://extensionmethodsyay.codeplex.com/
Wednesday, March 18, 2009
Mobile Application Architecture Guide
The p&p team at Microsoft has put together this document on Mobile Application Architecture best practice. You can find it here on codeplex: http://www.codeplex.com/AppArch/Release/ProjectReleases.aspx?ReleaseId=19798
I am currently putting together a solution that I plan to write an MSDN document detailing many of these technologies referenced in the document - some of which do not exist for mobile devices. This solution contains all the cool new stuff like, object relational mapping, Inversion of control, dependency injection, crosscutting inteceptors, domain driven design and how to achieve this in a mobile application. The latest UI controls in the market place. The repository data pattern. .NET CF 3.5, LINQ and lambdas - when to use them. Test driven development using MSTEST for devices.
I will post the link here when done.
I am currently putting together a solution that I plan to write an MSDN document detailing many of these technologies referenced in the document - some of which do not exist for mobile devices. This solution contains all the cool new stuff like, object relational mapping, Inversion of control, dependency injection, crosscutting inteceptors, domain driven design and how to achieve this in a mobile application. The latest UI controls in the market place. The repository data pattern. .NET CF 3.5, LINQ and lambdas - when to use them. Test driven development using MSTEST for devices.
I will post the link here when done.
Tuesday, March 17, 2009
Apple iPhone OS 3.0 preview event
A first look at the coming release of the Apple iPhone OS 3.0 by engadget: http://www.engadget.com/2009/03/17/live-from-apples-iphone-os-3-0-preview-event/
Monday, March 09, 2009
Microsoft Recite Technology Preview

There is a lot of cool stuff coming out of Redmond lately and Microsoft Recite is no exception.
Microsoft Recite is a tool that allows you to verbally record your thoughts to aid you to remember things, then retrieve them by asking (voice recognition) Recite for the content using any of the phrases in the recorded message.
Recite is supported on these devices:
AT&T BlackJack II
AT&T Pantech Duo
HTC Diamond
Moto Q9m
Palm Treo 800w
Palm Treo Pro
SMT 5800
T-Mobile Dash
T-Mobile Shadow
T-Mobile Wing
Motorola Q9C
Checkout a video of Recite in action here: http://recite.microsoft.com/Pages/ReciteVideo.aspx
Get it here: http://recite.microsoft.com/Pages/download.aspx
I am unaware of any Recite managed SDK at this point.
Microsoft TechDays Developer 2009 - 24hr Virtual Event

On April 1st 2009, be part of Microsoft history and join developers all over the world for the first ever 24-hour day of technology learning.
Participate in 95 live sessions anywhere, at anytime or on-demand at your convenience.
It is a free event.
To register for this event, click here: http://www.msfttechdays.com/public/home.aspx
To view the sessions, click here: http://www.msfttechdays.com/public/sessionlist.aspx
Microsoft are still calling for content so not all sessions are visible. Also you will be able to build you're own schedule in due course.
I'm not aware of any mobility tracks as yet, but my best guess is there will be some.
Wednesday, March 04, 2009
Broadband Speed test - South East England
I recently changed ISPs for my home network. I now use O2 (in UK) O2 bought Be Un Limited a while back. I was on Sky - Sky bough Easynet a few years ago. Sky was very slow and unreliable.
The upload bandwidth was almost no-existent. Experience playing on-line games was not much fun due to the lag. You need good upload bandwidth for playing on-line games successfully otherwise you just get slaughtered.
I used http://www.speedtest.net to measure the speed of both networks. As you can see, it is a big difference between the two networks. Also notice the ping response differences.
Anyone else in my area, Guildford, South East England who is on Sky should consider O2.
Here are the results:

Sky Easynet (before)

O2 (Be Un Limited)
I am around 5 miles from the BT exchange.
The upload bandwidth was almost no-existent. Experience playing on-line games was not much fun due to the lag. You need good upload bandwidth for playing on-line games successfully otherwise you just get slaughtered.
I used http://www.speedtest.net to measure the speed of both networks. As you can see, it is a big difference between the two networks. Also notice the ping response differences.
Anyone else in my area, Guildford, South East England who is on Sky should consider O2.
Here are the results:

Sky Easynet (before)

O2 (Be Un Limited)
I am around 5 miles from the BT exchange.
Tuesday, March 03, 2009
IoC framework for the Compact Framework
Andy Wigley mentioned the other day the p&p team has released a series of blocks for the Compact Framework including a dependency injection framework called ContainerModel. So I decided to have a look.
You can get the code from codeplex here: http://www.codeplex.com/Mobile
It is based on the MCSF but for .NET CF 3.5.
I have had a look at the IoC framework and it is pretty good but would be even better if it had support for configuration files (XML). So currently you have to code something like this:
It's quite cool as you can pass in an Action delegate at the time of register to instantiate the class.
You can get the code from codeplex here: http://www.codeplex.com/Mobile
It is based on the MCSF but for .NET CF 3.5.
I have had a look at the IoC framework and it is pretty good but would be even better if it had support for configuration files (XML). So currently you have to code something like this:
builderThen you can code this:
.Register<IEditCustomersView>(
c => new EditCustomersView())
.InitializedBy(
(c, v) => v.Presenter = c.Resolve<EditCustomersPresenter>());
var view = ApplicationRoot.Container.Resolve<IEditCustomersView>();This is a first cut so maybe we will see support for configuration files in the future. If I get time I'll add support for it.
It's quite cool as you can pass in an Action delegate at the time of register to instantiate the class.
Tuesday, February 24, 2009
Oracle Day 2009 - Smart Strategies for Uncertain Times

On March 5th 2009 in London, Oracle is holding an event "Oracle 2009 - Smart Strategies for Uncertain Times" to which Edenbrook is a key sponsor. A snip from the event website:
The Oracle Day 2009 will cover the Oracle Technology stack from the Database and Middleware through to SOA, Enterprise 2.0, Business Intelligence and Security. This event will bring together IT professionals across industry sectors to address the real challenges faced by IT today - consolidating, cutting costs and innovating. After the keynote speaker presentations the event will break into two distinct tracks, one for IT Management and one for IT professionals and architects, providing the opportunity to select the sessions most relevant to you.
The address for this event is:
Renaissance Chancery Court Hotel
252 High Holborn
London
WC1V 7EN
Subscribe to:
Posts (Atom)