XSD Schema’s – Reference

If you have ever come across generating XSD’s then you will soon find out that it’s a new ball game.  So in order to help you along I have generated this reference point of items that I have found useful.

XML Schema data types. The most common types are:

  • xs:string
  • xs:decimal
  • xs:integer
  • xs:boolean
  • xs:date
  • xs:time

Optional and Required Attributes

Attributes are optional by default. To specify that the attribute is required, use the “use” attribute:

<xs:attribute name=”lang” type=”xs:string” use=”required”/>

WCF Message can only be read once

WCF is a very powerful tool for developers, and I’m sure as you dive in to the development environment you will come across the WCF Message, which is part of System.ServiceModel.Channels Namespace. You should be aware that a message body can only be accessed once and a message can only be written once.  This will in turn can cause a problem if you are creating your own IDispatchMessageInspector, as at some you will need to read the message and once you have read it, you are buggered!

So in order to use the Message you will have to copy the message in to a buffer using the CreateBufferCopy method, here is how you go about it

public void Validate(ref Message message)
{
    MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue);
   
try
    {
    ValidateInput(buffer.CreateMessage());
    }
   
catch (Exception)
    {
   
throw;
    }
   
message = buffer.CreateMessage();
}

XSD to Objects

I’ve been dealing with REST services within WCF, and one thing that has come to my attention is that the calling service or third party only has access to the REST interface and the XSD’s.

The XSD’s holds all the contract information, therefore if you need to generate a concreteclass you are going to have to translate the XSD to an object. 

I’ve have come across the XSD Object Generator frm Microsoft which appears to do the job.

XSDObjectGen.msi (667.00 kb)

MVVM Material

After attending a talk on Silverlight 4, MVVM and TDD with Jesse Liberty, I thought it would be an idea to find out more information on MVVM, James Green provided me with a number of worth while links by Jason Dollinger from Lab49.  The main blog post is here http://blog.lab49.com/archives/2650 but the actual video is here http://www.lab49.com/files/videos/Jason%20Dolinger%20MVVM.wmv big download (about 1.5 hours).

The source code for the project he is doing is here http://blog.lab49.com/archives/2689

Another good one is by Karl Shifflet (he’s a VS IDE developer) http://channel9.msdn.com/shows/Continuum/MVVM/

This guy is worth following as well http://sachabarber.net/?cat=17

Want to know not only MVVM but all about Silverlight 4 too, check out Scott Gu’s post for Silverlight 4 Training Kit

Passing Validation exceptions via WCF REST

When using WCF and Rest one thing you’re going to have to consider is the validation of the object, the way to do this is using the Validation Application Block included in the Microsoft Enterprise Library to validate the data transfer objects. This way you can decorate the objects with attributes to validated the objects

Here is an example

public static void Validate<T>(T obj)
{
     ValidationResults results = Validation.Validate(obj);

     if (!results.IsValid)
         
string[] errors = results
          .Select(r => r.Message)
         
.ToArray();

     WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
     WebOperationContext.Current.OutgoingResponse.StatusDescription = String.Concat(errors);
}

thanks to Enrico Campidoglio for helping out on this

Lifestyles of the Castle Windsor IoC Containers

It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs.  These lifestyles that are available in Castle Windsor are:

  • Singleton: components are instantiated once, and shared between all clients
  • Transient: components are created on demand
  • PerWebRequest: components are created once per Http Request
  • Thread: components have a unique instance per thread
  • Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them
  • Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface

For further information on this take a look at Castle Windsors Lifestyles or  Windsor and component instance lifetimes

MVC 2 makes it easier to copy models

With MVC 2 now released, I have found a nice little feature for updating models.

The normal practice is to use, a mapping technique like this

public void Save(EmployeeViewModel employeeViewModel)
{
    var employee = (from emp in dataContext.Employees
                   where emp.EmployeeID == employeeViewModel.EmployeeID
                   select emp).SingleOrDefault();

    if (employee != null)
    {
        employee.Address = employeeViewModel.Address;
        employee.Salary = employeeViewModel.Salary;
        employee.Title = employeeViewModel.Title;
    }
    dataContext.SubmitChanges();
}

But now we can use the ModelCopier, which uses reflection to transpose the model

public void Save(EmployeeViewModel employeeViewModel)
{
    var employee = (from emp in dataContext.Employees
                    where emp.EmployeeID == employeeViewModel.EmployeeID
                    select emp).SingleOrDefault();

    if (employee != null)
    {
        ModelCopier.CopyModel(employeeViewModel, employee);
    }
    dataContext.SubmitChanges();
}

So, you’ve tried it out, but you can’t find ModelCopier?  That is because is part of MVC 2 futures, what a tease 😉

I have however created this extended version of an Object Copier, which also copies objects inside of the object.

ObjectCopier.zip (50.83 kb)

Introduction to Dependency Injection

Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test.

I like to use samples to explain Dependency Injection. We’ll use a SqlMetaDataProvider class which needs to provide the meta data coming from a SQL Server database. It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model. Obviously, i want to be able to test this class without actually going to the database because that would make the tests slow. So how can we test if the relational data is being converted to the object model without going to the database?

Well, let’s look at what the class does. First of all, it retrieves sql server meta data. Then it converts it to an object model. But retrieving the meta data doesn’t really belong here… it should be functionality that’s offered by another class. So we create a SqlDataRetriever class. All it will do is return meta data in the relational structure. Nothing more. So now, our SqlMetaDataProvider class can simply use the SqlDataRetriever class to retrieve the meta data. So basically, SqlDataRetriever is now a dependency of the SqlMetaDataProvider class because SqlMetaDataProvider is depending on SqlDataRetriever to return the relational meta data.

At this point, our class could look like this:

    public class SqlMetaDataProvider : IMetaDataProvider
    {
        private readonly string _connectionString;
        private readonly SqlDataRetriever _sqlDataRetriever;
 
        public SqlMetaDataProvider(string connectionString)
        {
            _connectionString = connectionString;
            _sqlDataRetriever = new SqlDataRetriever();
        }
 
        public MetaDataStore GetMetaDataStore()
        {
            SqlMetaData sqlMetaData = _sqlDataRetriever.GetMetaData(_connectionString);
 
            return ConvertToMetaDataStore(sqlMetaData);
        }
 
        private MetaDataStore ConvertToMetaDataStore(SqlMetaData sqlMetaData)
        {
            MetaDataStore store = new MetaDataStore();
 
            AddTablesToStore(sqlMetaData.TableInfo, store);
            AddColumnsToTablesInStore(sqlMetaData.ColumnInfo, store);
            CreateRelationshipsBetweenTables(sqlMetaData.RelationshipInfo, store);
 
            return store;
        }
    }

Note: I left out the code for the AddTablesToStore, AddColumnsToTablesInStore and CreateRelationshipsBetweenTables methods because they aren’t relevant to this specific topic.

Now we need to make sure we can replace the instance of SqlDataRetriever during testing with one we can supply ourselves. That test instance could then simply return a DataSet that was created in-memory, thus keeping our tests running fast. Notice how SqlMetaDataProvider has a reference of the type SqlDataRetriever. The type is essentially fixed, which creates a strong dependency on the SqlDataRetriever class. If we were to replace the type of the reference with an interface, it would at least make it easier to use another type for our required dependency, one that simply implements the interface.

So we create the ISqlDataRetriever interface:

    public interface ISqlDataRetriever
    {
        SqlMetaData GetMetaData(string connectionString);
    }

And then we modify the definition of SqlDataRetriever to implement the interface:

    public class SqlDataRetriever : ISqlDataRetriever

Now we need to modify our SqlMetaDataProvider class so it holds a reference to the interface type, instead of the class type:

        private readonly ISqlDataRetriever _sqlDataRetriever;

We still need to find a way to inject our dependency into our SqlMetaDataProvider so we’ll modify the constructor:

        public SqlMetaDataProvider(string connectionString, ISqlDataRetriever sqlDataRetriever)
        {
            _connectionString = connectionString;
            _sqlDataRetriever = sqlDataRetriever;
        }

The only downside to this is that it now takes more work to create an instance of SqlMetaDataProvider… work that clients shouldn’t need to do if they just want to use the default ISqlDataRetriever implementation. If you’re using an Inversion Of Control (IoC) container, you can simply request an instance of SqlMetaDataProvider and the IoC container would also create the necessary dependency for you. Using an IoC container however is outside of the scope for this post, so we won’t do that. In fact, if you know that your production code will always use the SqlDataRetriever implementation, you could also provide a simpler constructor which takes care of that for you:

        public SqlMetaDataProvider(string connectionString)
            : this(connectionString, new SqlDataRetriever()) {}

So you could use the simpler constructor in your production code, and the other one in your test code. Speaking of test code, we still need to write that test which tests the conversion without hitting the database. First, we need to create an implementation of ISqlDataRetriever which allows us to pass a DataSet to it which the ISqlDataRetriever instance should return to its consumer (our SqlMetaDataProvider):

    public class SqlDataProviderStub : ISqlDataRetriever
    {
        private SqlMetaData _sqlMetaData;
 
        public SqlMetaData SqlMetaData
        {
            set { _sqlMetaData = value; }
        }
 
        SqlMetaData ISqlDataRetriever.GetMetaData(string connectionString)
        {
            return _sqlMetaData;
        }
    }

And finally, the test:

        [Test]
        public void GetMetaDataStore_ProvideDataSetWithTwoTablesAndRelationship_MetaDataStoreIsCorrect()
        {
            SqlMetaData sqlMetaData = PrepareMetaDataSetInMemoryWithTestData();
 
            SqlDataProviderStub sqlDataProvider = new SqlDataProviderStub();
            sqlDataProvider.SqlMetaData = sqlMetaData;
 
            // pass null as the connectionString, and pass our SqlDataProviderStub
            IMetaDataProvider metaDataProvider = new SqlMetaDataProvider(null, sqlDataProvider);
 
            MetaDataStore store = metaDataProvider.GetMetaDataStore();
 
            AssertStoreContainsOurTestData(store);
        }
Original article by Davy Brion