LP on .NET

April 3, 2013

Dependency Injection – A Compromise

Filed under: .NET,C#,Software Development — Larry Parker @ 9:38 pm

I’ve blogged a lot over the past few years about writing testable code, as well as using stubs and mocking frameworks in unit tests to test all that testable code.

The common denominator to all this has been dependency injection.  To quote myself from a previous post:

Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system. … in a nutshell you simply hand the dependencies (typically as interfaces) to your class or method which then works with them in an abstract way.

I also said this in another post:

It seems that I can’t say enough about dependency injection these days. It gives me an incredible amount of control over my code in the form of testability and modularity.

I’ve been using this pattern for a couple of years now.  It really has given me an incredible amount of control over my code, especially in the form of testability.  I love writing unit tests that can mock out some or all of the injected interfaces.  It really makes testing simple.

But incredible control in the form of modularity?  When’s the last time I swapped out my persistence layer with a new module that provided a new and improved persistence layer?  Or swapped out a configuration manager with a better one by simply editing an app.config setting that pointed to another assembly?

Let me think.

Still thinking…

Hmmm.  Haven’t done it.  Except perhaps as a proof-of-concept and maybe a demo or two.

As for “simply handing the dependencies” to my classes, it’s simple in theory.  Until you end up with a constructor that takes a whole bunch of parameters and you end up writing code like this just to create an instance of your class:

   1: WidgetProvisioningManager widgetProvisioningManager = new WidgetProvisioningManager(

   2:     new WidgetProvisioningDataManager(systemContext),

   3:     new WidgetDbProvisioningDataManager(databaseServer),

   4:     o => new OrganizationDataManager(o),

   5:     (u, c) => new EmployeeDataManager(u, c),

   6:     emailServerConfiguration,

   7:     (m, t) => QueueManager.Enqueue(m, t, null),

   8:     executionContext.LogWriter,

   9:     new WidgetMembershipManager());

So much for the simple part.  Try showing this to another developer who needs to actually work with your WidgetProvisioningManager class.  “Yes Joe, to create a new instance of my WidgetProvisioningManager class, you do need to pass in seven parameters to the constructor.”  (pause)  “You got a problem with that?”

There are other options, like inversion of control containers such as StructureMap.  I’ve looked at these a bit but have not been able to warm up to them.  Too much up-front configuration, and your application becomes too dependent on them at runtime (whereas something like Moq never leaves the lab).

So now what?

Without getting into all of the heated discussions about which pattern is best (and I have encountered many both on the web and in the office), may I suggest a compromise.

Make your class’s public constructor as simple as possible, but no simpler (Einstein would love your constructor).  And developers who use your classes will not complain that they don’t have to pass in seven parameters.

As for testability, dependency injection still plays a part, as do mocking frameworks.  But make the constructor with the seven parameters internal so nobody else has to see it (and make your assembly’s internals available only to your unit test assemblies).

Using this approach, we can have our cake and eat it too.  Our WidgetProvisioningManager class now has two constructors.  The easy one marked as public for everyone to use:

   1: public WidgetProvisioningManager()

   2: {

   3:     _widgetProvisioningDataManager = new WidgetProvisioningDataManager(AppRuntime.SystemContext);

   4:     _widgetDbProvisioningDataManager = new WidgetDbProvisioningDataManager(AppRuntime.DatabaseServer);

   5:     _organizationDataManagerFactory = o => new OrganizationDataManager(o);

   6:     _employeeDataManagerFactory = (u, c) => new EmployeeDataManager(u, c);

   7:     _emailServerConfiguration = AppRuntime.EmailServerConfiguration;

   8:     _enqueueFunc = (m, t) => QueueManager.Enqueue(m, t, null);

   9:     _logWriter = AppRuntime.LogWriter;

  10:     _widgetMembershipManager =  new WidgetMembershipManager();

  11: }

And the DI constructor marked as internal for your unit tests:

   1: internal WidgetProvisioningManager(IWidgetProvisioningDataManager widgetProvisioningDataManager = null,

   2:     WidgetDbProvisioningDataManager widgetDbProvisioningDataManager = null,

   3:     Func<IContext, IOrganizationDataManager> organizationDataManagerFactory = null,

   4:     Func<IContext, EmailServerConfiguration, IEmployeeDataManager> employeeDataManagerFactory = null,

   5:     EmailServerConfiguration emailServerConfiguration = null,

   6:     Func<Int32, String, Int64> enqueueFunc = null,

   7:     ILogWriter logWriter = null,

   8:     IWidgetMembershipManager widgetMembershipManager = null)

   9: {

  10:     _widgetProvisioningDataManager = widgetProvisioningDataManager;

  11:     _widgetDbProvisioningDataManager = widgetDbProvisioningDataManager;

  12:     _organizationDataManagerFactory = organizationDataManagerFactory;

  13:     _employeeDataManagerFactory = employeeDataManagerFactory;

  14:     _emailServerConfiguration = emailServerConfiguration;

  15:     _enqueueFunc = enqueueFunc;

  16:     _logWriter = logWriter;

  17:     _widgetMembershipManager = widgetMembershipManager;

  18: }

Note that both constructors save things to private fields (the ones with the underscore prefix), and the rest of the class just uses interfaces and doesn’t care where they came from.

The public constructor creates concrete classes so consumers of the class can just use your class without any headaches.

The internal constructor is the one with all the (optional) parameters, so you can still go to town using mocking frameworks for your unit tests.

So that’s my dependency injection compromise.

Hope this helps.

Advertisements

June 3, 2012

Writing Explicit Code with Dependency Injection

Filed under: .NET,C#,Software Development — Larry Parker @ 5:30 pm

It seems that I can’t say enough about dependency injection these days.  It gives me an incredible amount of control over my code in the form of testability and modularity.

One of the additional benefits I have gained by following this pattern is that my code has become more explicit.  What do I mean by that?

Consider the following example of “classic” programming:

CustomerDataManager customerDataManager = new CustomerDataManager();

Customer customer = customerDataManager.GetCustomerById(1001);

This code is simple enough.  We just create an instance of our customer data manager, call the GetCustomerById method, and get our customer back.  The GetCustomerById method hits the database with the appropriate SQL statement (or using some other data access technology) and we’re done.  The code looks like this:

public class CustomerDataManager
{
    public CustomerDataManager()
    {
        _connString = ConfigurationManager.ConnectionStrings["MainDbConnectionString"].ConnectionString;
    }

    private String _connString;

    public Customer GetCustomerById(Int32 customerId)
    {
        Customer customer = ... // hit db using above connection string

        return customer;
    }
}

Note the connection string obtained in the constructor using the .NET ConfigurationManager class.  This requires your app to have the following in its app.config file:

<configuration>
  <connectionStrings>
    <add name="MainDbConnectionString" connectionString="Data Source=.; Initial Catalog=TheDb; etc...;"/>
  </connectionStrings>

And we’re done.  The customer data manager can now be used by anyone on your team.  All that they need to know is that their executable’s app.config file needs a connection string called MainDbConnectionString.  But you’ve documented that (right? Smile), so that won’t be a problem for anyone.

Well, it turns out that the developers on your team using your CustomerDataManager class already have their own connection string defined in their executable’s app.config and it’s not called MainDbConnectionString.  You ask them why it’s not called MainDbConnectionString.  They ask you why you’re not calling it ApplicationDbConnectionString.  And like the north and south going Zax, you just stare each other down with your arms folded.

OK, hopefully it’s not that bad.  But why even go there?  Why have your data manager define an external dependency like an app.config setting in the first place?

The way around this whole thing is to just inject the connection string into the constructor and remove the dependency.

Let’s rewrite our customer data manager’s constructor to handle this:

public CustomerDataManager(String connString)
{
    _connString = connString;
}

Now your CustomerDataManager class is out of the business of app.config settings.  It doesn’t know or care anything about configuration and doesn’t need to access the dubious ConfigurationManager class (dubious because it makes it so easy to create dependencies like this).

And now your CustomerDataManager class can be used by the developer who gets all of his connection strings from an encrypted XML file, and can also be used by the other guy who gets them from the registry (using his own encryption algorithm, of course).  They don’t mind passing the connection string into your data manager and can’t stop talking about how easy your classes are to work with.

You’re a hero.

All because your code was explicit and didn’t make any assumptions about its runtime environment.

January 31, 2012

Obtaining SQL Identity Information

Filed under: Software Development,SQL Server — Larry Parker @ 7:05 pm

I found a great query today on this blog for obtaining information about SQL identity columns.  Here’s my updated version to handle SQL schemas:

SELECT IDENT_SEED(TABLE_SCHEMA + '.' + TABLE_NAME) AS Seed,
    IDENT_INCR(TABLE_SCHEMA + '.' + TABLE_NAME) AS Increment,
    IDENT_CURRENT(TABLE_SCHEMA + '.' + TABLE_NAME) AS Current_Identity,
    TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), 'TableHasIdentity') = 1
  AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_SCHEMA + '.' + TABLE_NAME

This allows you to easily find out every table in your database that has an identity column, and what the seed, increment, and current values are.

Super helpful!

September 6, 2011

Using a Collection Initializer with a Dictionary

Filed under: .NET,C#,Software Development — Larry Parker @ 10:39 pm
Tags: , ,

Collection initializers (introduced in C# 3.0) provide an easy way to initialize a collection of items.  For example, instead of doing this…

List<Color> colors = new List<Color>();
colors.Add(new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" });
colors.Add(new Color { Value = 0xFF9400D3, Name = "Dark Violet" });
colors.Add(new Color { Value = 0xFF708090, Name = "Slate Gray" });

…we can do this:

List<Color> colors = new List<Color>
{
    new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" },
    new Color { Value = 0xFF9400D3, Name = "Dark Violet" },
    new Color { Value = 0xFF708090, Name = "Slate Gray" }
};

But what if we want to initialize a dictionary?  The traditional way would be like this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>();
colors.Add(0xFFF0F8FF, "Alice Blue");
colors.Add(0xFF9400D3, "Dark Violet");
colors.Add(0xFF708090, "Slate Gray");

But how would we use a collection initializer?  When you iterate through a dictionary, each item is a KeyValuePair<TKey, TValue>.  But we can’t do this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    new KeyValuePair<UInt32, String>(0xFFF0F8FF, "Alice Blue"),
    new KeyValuePair<UInt32, String>(0xFF9400D3, "Dark Violet"),
    new KeyValuePair<UInt32, String>(0xFF708090, "Slate Gray")
};

The solution is not entirely obvious, but it is succinct:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    { 0xFFF0F8FF, "Alice Blue" },
    { 0xFF9400D3, "Dark Violet" },
    { 0xFF708090, "Slate Gray" }
};

This is not mentioned in the MSDN link shown above, but MSDN does discuss it here.

Hope this helps!

August 29, 2011

Dependency Injection and Delegates

Filed under: .NET,C#,Software Development — Larry Parker @ 10:46 pm
Tags: , ,

A couple of weeks ago I blogged about writing testable code using dependency injection.  This was done by injecting interface references into a class’s constructor:

public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
{
    _userPersistence = userPersistence;
    _emailManager = emailManager;
}

Assuming we have concrete classes called UserPersistence and EmailManager that implement these interfaces, we could simply inject the dependencies like this:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager());
}

But what happens if the dependencies cannot actually be injected during construction because it’s too early to create them?  A good example of this is when the concrete classes themselves are constructed with a parameter that is not yet available.

Let’s say that when we register a user we get a guid back from our persistence layer that identifies the user.  Now let’s also say that our IEmailManager interface is written to apply to a single user at a time, and there’s a concrete class called EmailManager with a constructor that looks like this:

public class EmailManager : IEmailManager
{
    public EmailManager(Guid userId)
    {
        _userId = userId;
    }
...
}

Since we don’t know the guid until we register the user (via the UserManager class), we can’t inject an IEmailManager into the UserManager class’s constructor.

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager(<oops!  What’s the guid?>));
}

The solution is to change UserManager’s constructor to take a delegate instead of an interface:

public class UserManager
{
    public UserManager(IUserPersistence userPersistence,
        Func<Guid, IEmailManager> emailManagerFactory)
    {
        _userPersistence = userPersistence;
        _emailManagerFactory = emailManagerFactory;
    }

    private IUserPersistence _userPersistence;
    private Func<Guid, IEmailManager> _emailManagerFactory;

Instead of the UserManager constructor directly taking an IEmailManager, it now takes a delegate that expects a guid and returns an IEmailManager.

Since the delegate is only supplied during UserManager’s construction and not executed, we don’t need to know the guid at this time:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), o => new EmailManager(o));
}

Our delegate can be passed in several ways, but a lambda expression is a nice easy way to do it (“o” is a local variable of type Guid).

With this new approach, our RegisterUser method from our previous post now looks like this:

public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
{
    try
    {
        Boolean result = false;

        Guid userId = _userPersistence.AddUser(lastName, firstName, emailAddress);

        IEmailManager emailManager = _emailManagerFactory(userId);
        result = emailManager.SendLoginInfo();

        return result;
    }
    catch (Exception ex)
    {
        // Log the exception...

        return false;
    }
}

Note that when we execute our delegate (i.e. the _emailManagerFactory field) we pass in the user ID guid as a parameter (i.e. the value we just obtained from calling the AddUser method) and get back our IEmailManager interface reference.  Now we can call its methods and they will all act on the newly registered user.

Delegates are a great way to defer execution until needed, and this is a very useful technique to let you follow the dependency injection pattern even when you don’t have everything you need during object construction.

Hope this helps.

August 19, 2011

Serializing and Deserializing JSON Data

Filed under: .NET,C#,Software Development — Larry Parker @ 7:31 pm
Tags: , ,

My team is working on a web site that consumes JSON (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data.

I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.  A colleague pointed me to MSDN (always a good start) with this link, and a quick search pointed me to this site which had some nice JSON helpers.

After looking at the examples on both sites, I wrote some extension methods to make things easier.  Here’s what I came up with (after some suggestions on the method names by my team):

public static class JsonExtensionMethods
{
    /// <summary>
    /// Serializes an object to a JSON string.
    /// </summary>
    /// <typeparam name="T">The serializable class.</typeparam>
    /// <param name="entity">The object that will be serialized to JSON.</param>
    /// <returns>Returns a serialized representation of the object as a JSON string.</returns>
    public static String ToJson<T>(this T entity)
        where T : class
    {
        String result = null;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, entity);
            result = Encoding.Default.GetString(ms.ToArray());
        }

        return result;
    }

    /// <summary>
    /// Deserializes a JSON string into an object.
    /// </summary>
    /// <typeparam name="T">The class to deserialize the JSON string into.</typeparam>
    /// <param name="jsonObject">The serialized object as a JSON string.</param>
    /// <returns>Returns an instance of the concrete class representing the JSON string.</returns>
    public static T FromJson<T>(this String jsonObject)
        where T : class
    {
        T entity = Activator.CreateInstance<T>();

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonObject)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            entity = (T)serializer.ReadObject(ms);
        }

        return entity;
    }
}

Here are some unit tests that show how they are used:

[TestMethod()]
public void SerializeTest()
{
    Customer customer = new Customer { FirstName = "Joe", LastName = "Smith" };

    String actual = customer.ToJson();

    Assert.AreEqual("{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}", actual);
}

[TestMethod()]
public void DeserializeTest()
{
    String jsonObject = "{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}";

    Customer actual = jsonObject.FromJson<Customer>();

    Assert.AreEqual("Joe", actual.FirstName);
    Assert.AreEqual("Smith", actual.LastName);
}

Both of the tests use a class called Customer that looks like this:

[DataContract]
public class Customer
{
    [DataMember]
    public String LastName { get; set; }

    [DataMember]
    public String FirstName { get; set; }
}

Notice that the ToJson extension method is applied to a class, while the FromJson extension method is applied to a string.  The extension methods are a nice touch because you don’t have to go through a static helper class in your code, but instead just use the applicable extension methods directly on your variable (depending if you’re serializing to JSON or deserializing from JSON).

Hope you like it!

August 14, 2011

Writing Testable Code

Filed under: .NET,C#,Software Development — Larry Parker @ 5:59 pm

About a year ago, my idea of unit testing included anything that could be tested no matter how heavy the setup.  This included having an available test database, available web services, and other external resources (like the file system) that were needed to test my code.

While this kind of test environment is useful, it’s more along the lines of an integrated test environment that QA would have set up.  Test likes these can really be categorized as integration tests and not unit tests.

If you want to really unit test your code, you don’t want any of the aforementioned dependencies to be part of your tests.  Unit tests should be fast and should just test a single piece of code – not your entire application’s runtime environment.

Let’s take a look at both of these approaches.  Consider the following code that registers a user with your application:

public class UserManager 
{
    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try 
        {
            String connString = "...";

            using (var connection = new SqlConnection(connString))
            using (var cmd = new SqlCommand())
            {
                cmd.CommandText = @"
INSERT INTO User (LastName, FirstName, EmailAddress)
VALUES (@LastName, @FirstName, @EmailAddress)
";

                cmd.Parameters.Add("LastName", SqlDbType.NVarChar).Value = lastName;
                cmd.Parameters.Add("FirstName", SqlDbType.NVarChar).Value = firstName;
                cmd.Parameters.Add("EmailAddress", SqlDbType.NVarChar).Value = emailAddress;

                connection.Open();
                cmd.Connection = connection;
                cmd.ExecuteNonQuery();
            }

            return true;
        }
        catch (Exception ex)
        {
            // Log the exception... return false;
        }
    }
}

Now let’s write a test for the RegisterUser method.

[TestMethod()]
public void RegisterUserTest()
{
    UserManager target = new UserManager();
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

This test attempts to register a user named Bert Smith and verifies that the registration succeeded (i.e. we assert that the RegisterUser method returned true).

The test is simple enough, but in order to run it we need a database and also a User table in it.  It’s possible to set up a test database like this and ensure that the connection string is supplied for the test.  But now we have a heavy dependency that probably needs to be in a certain state every time we run the test (e.g. we probably don’t already want the user Bert Smith in the database before we run the test).

Let’s step back a second and ask ourselves exactly what we want to test in our RegisterUser test.  Do we want to test that ADO.NET works?  Hopefully Microsoft has already tested that well enough.  Do we want to test that we can write SQL that inserts a row into our User table?  At some point, but not right now.

The job of the RegisterUser method is to register a user with our system.  This probably involves some data validation (like ensuring the email address was supplied and is in a valid format), adding the user to persistent storage (like in a User table in a SQL database), and possibly sending an email to the user to let him know the registration succeeded.

All of these things are possible tasks that the RegisterUser method might need to execute, but we don’t necessarily want to test the tasks themselves – we only want to test that the tasks were called in the expected way.

Consider the email step.  How would we test that anyway?  We could use .NET’s SmtpClient class and have RegisterUser send the registration email to ourselves via our company’s email server (if we had rights to do so) and verify that we did indeed receive the email in our inbox.

The problem with this is that you need to verify that the email arrived in your inbox by looking at your inbox.  But when you run this test along with hundreds of other tests, you are not going to do this.  And neither is an automated test system.

So how do we write our RegisterUser test so we can test what we need without having all of these external dependencies?

The answer is:  dependency injection.

Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system.  There are plenty of discussions about this (Martin Fowler, Wikipedia, etc.), but in a nutshell you simply hand the dependencies (typically as interfaces) to your class or method which then works with them in an abstract way.  In other words, instead of working directly with ADO.NET, your method works with an interface responsible for adding the user to persistent storage.

Let’s revisit the RegisterUser method with a couple of dependencies injected into the UserManager class’s constructor.

public class UserManager 
{
    public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    private IUserPersistence _userPersistence;
    private IEmailManager _emailManager;

    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try 
        {
            Boolean result = false;

            if (_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            return result;
        }
        catch (Exception ex)
        {
            // Log the exception... return false;
        }
    }
}

Notice that our constructor takes two parameters that are interfaces that define our tasks.

public interface IUserPersistence 
{
    Boolean AddUser(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

public interface IEmailManager 
{
    Boolean SendUserRegistrationEmail(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

As for the RegisterUser method, what happened to the SQL that will add the user to the User table in our database?  The short answer is, “Who cares?”

Persisting the user to the database is now farmed out to an interface called IUserPersistence that has a method called AddUser.  The SQL will probably be in there, but as far as the RegisterUser method is concerned, it doesn’t care.  Our RegisterUser method just works with the interfaces:

        if (_userPersistence.AddUser(lastName, firstName, emailAddress))
            result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                emailAddress);

This is dependency injection at work.  Our code is now testable and our test can now inject dependencies into the UserManager class without having to have a database and email server set up to run the test!

Let’s rewrite our test and inject some home-grown dependencies.

public class UserPersistenceStub : IUserPersistence 
{
    public Boolean AddUser(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

public class EmailManagerStub : IEmailManager 
{
    public Boolean SendUserRegistrationEmail(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceStub = new UserPersistenceStub();
    var emailManagerStub = new EmailManagerStub();

    UserManager target = new UserManager(userPersistenceStub, emailManagerStub);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

We simply created two stub classes that implement our interfaces and then injected instances of those classes into our UserManager instance.

Now our test runs without the need for a database or an email server.  We were able to achieve this because we rewrote our UserManager class and RegisterUser method as testable code using dependency injection.

Our unit test can be improved (e.g. by using tools like Moq), but I will save that for another post.  For now, the main takeaway of this post is that code can be written to be testable using dependency injection.

It took me a while to realize the importance of writing testable code.  The fact that testable code can be unit tested without needing external resources like databases opens up the door to writing a slew of tests to thoroughly test your code, and this gets you into the area of code coverage and even test-driven development.

More to come on this…

June 21, 2011

Errors Generating WSDL for WCF Service

Filed under: .NET,C#,Software Development,WCF — Larry Parker @ 2:42 pm

Our team recently started specifying a namespace for our WCF data contracts.  We were already supplying a namespace for our service contracts, but for some reason we never did it for the data contracts.

The service contracts look something like this:

[ServiceContract(Namespace = ServiceConstants.ServiceContractNamespace)]
public interface ICustomerService
{
    [OperationContract]
    CustomerResponse GetCustomer(CustomerRequest request);
...
}

The namespace is defined as a constant in a static class:

public static class ServiceConstants
{
    public const String ServiceContractNamespace = "http://Company/2011/06/Product";
...
} 

So we just applied the same technique to our data contracts:
[DataContract(Namespace = ServiceConstants.ServiceContractNamespace)]
public class CustomerResponse
{
    [DataMember]
    public String LastName;

    [DataMember]
    public String FirstName;
}

But when we tried to generate a service proxy we got the following error (once we set IncludeExceptionDetailInFaults to true):

System.Xml.Schema.XmlSchemaException: The global element ‘http://Company/2011/06/Product:CustomerResponse’ has already been declared.

After much trial and error, we renamed the class to CustomerResp and everything worked fine.  We originally thought there must have been an older assembly causing the trouble, but a Google search turned up this page…  Problem solved!  🙂

Evidently, WCF uses some reserved suffixes (like Response and Request) and this causes problems when the data contract has the same namespace as the service contract.

Fortunately, the workaround was as simple as changing the data contract’s namespace:

[DataContract(Namespace = ServiceConstants.DataContractNamespace)]
public class CustomerResponse
{
...
}

public static class ServiceConstants
{
    public const String ServiceContractNamespace = "http://Company/2011/06/Product";

    public const String DataContractNamespace = "http://Company/2011/06/Product/Data";
...
}

Aside from fixing the problem, it seems like a good idea to separate the namespaces between the service and data contracts.

But this was a tough one (took all morning).

Hope this helps.

June 9, 2011

WCF Tracing can also be used on the Client

Filed under: .NET,C#,Software Development,WCF — Larry Parker @ 4:42 pm

I helped track down an issue at a customer today where we couldn’t determine if one of the client machines was making any WCF service calls to the server.

So we used the WCF Configuration Editor Tool (SvcConfigEditor.exe) and the WCF Service Trace Viewer Tool (SvcTraceViewer.exe) on the server to check for incoming messages.

This helped us get to the bottom of the problem, but it would have been better if we could have directly done a trace on the client machine to monitor the outgoing messages.

I had used Fiddler for something like this many years ago, but before I threw that into the mix I figured I would check if the WCF tools could be used on the client side.

And they can!  🙂

You simply need to run SvcConfigEditor.exe on the client application’s app.config file and set it up for message logging and / or tracing.  Now after you restart your client app you can run SvcTraceViewer.exe and see the WCF service calls being made from it.

Hope this helps!

February 11, 2011

Using LINQ to Create a Dictionary

Filed under: .NET,C#,Software Development — Larry Parker @ 10:22 pm

Often when I use LINQ to run a query against my data (whether objects, SQL or XML) I call .ToList() or .ToArray() at the end to execute the query and get a full in-memory representation of the result set.

Less frequently, but still useful at times, I will call .ToDictionary() to convert the collection into a Dictionary<TKey, TValue>.  For example, say we have a Customer class:

public class Customer
{
    public Int32 CustomerId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

We could write a test like this:

[TestMethod]
public void DictionaryTest()
{
    Customer[] customers =
    {
        new Customer { CustomerId = 1001, FirstName = "Bill", LastName = "Smith" },
        new Customer { CustomerId = 1002, FirstName = "Mary", LastName = "Jones" },
        new Customer { CustomerId = 1003, FirstName = "Joe", LastName = "Thomas" }
    };

    Dictionary<Int32, Customer> dict = customers.ToDictionary<Customer, Int32>(o => o.CustomerId);
    Assert.AreEqual("Smith", dict[1001].LastName);
    Assert.AreEqual("Jones", dict[1002].LastName);
    Assert.AreEqual("Thomas", dict[1003].LastName);
}

The key of the dictionary is the customer ID (an integer), and each dictionary element contains the customer itself.  This is a great way to quickly convert a collection of elements into a keyed lookup that returns a particular object from a collection.

But what if we want our lookup to return something other than the full object?  Say we need to create a dictionary keyed by customer ID that returns the first and last name as a single string?

We could do something like this:

public Dictionary<Int32, String> GetCustomerDict(IEnumerable<Customer> customers)
{
    Dictionary<Int32, String> dict = new Dictionary<Int32, String>();

    foreach (Customer customer in customers)
        dict.Add(customer.CustomerId, customer.FirstName + " " + customer.LastName);

    return dict;
}

Then we could change our test like this:

[TestMethod]
public void DictionaryTest()
{
    Customer[] customers =
    {
        new Customer { CustomerId = 1001, FirstName = "Bill", LastName = "Smith" },
        new Customer { CustomerId = 1002, FirstName = "Mary", LastName = "Jones" },
        new Customer { CustomerId = 1003, FirstName = "Joe", LastName = "Thomas" }
    };

    Dictionary<Int32, String> dict = GetCustomerDict(customers);
    Assert.AreEqual("Bill Smith", dict[1001]);
    Assert.AreEqual("Mary Jones", dict[1002]);
    Assert.AreEqual("Joe Thomas", dict[1003]);
}

The key is still the customer ID, but instead of the dictionary element returning the full customer object, it now returns a simple string containing the customer’s first and last name.  Note also that the new dictionary has no reference to the original customer objects (which is sometimes desirable).

So our GetCustomerDict method works and was just a few lines of code.

But LINQ’s .ToDictionary extension method provides another overload that makes our lives much easier.  Here’s how it looks:

.ToDictionary<TSource, TKey, TElement>

Note that this overload take three types.  TSource is the type of our collection (Customer in this example), TKey is the type of the dictionary’s key (integer), and TElement is the type of the element we want to return (string in this case).  Just what we need!  🙂

Here’s the final version of the test:

[TestMethod]
public void DictionaryTest()
{
    Customer[] customers =
    {
        new Customer { CustomerId = 1001, FirstName = "Bill", LastName = "Smith" },
        new Customer { CustomerId = 1002, FirstName = "Mary", LastName = "Jones" },
        new Customer { CustomerId = 1003, FirstName = "Joe", LastName = "Thomas" }
    };

    Dictionary<Int32, String> dict = customers.ToDictionary<Customer, Int32, String>(k => k.CustomerId,
        e => e.FirstName + " " + e.LastName);

    Assert.AreEqual("Bill Smith", dict[1001]);
    Assert.AreEqual("Mary Jones", dict[1002]);
    Assert.AreEqual("Joe Thomas", dict[1003]);
}

One line of code does the trick.  The power of LINQ!  🙂

Next Page »

Blog at WordPress.com.