Tag Archives: .net

Create a Single WSDL File for WCF Services in .NET 4.5

One of the things that I’ve always found to be annoying is that WSDL files generated for WCF services that reference objects in different namespaces include wsdl:import links to other WSDLs. This separation by namespace may make sense from an organizational/maintainability standpoint, but it makes it difficult to provide a WSDL for a privately hosted service to a third party consumer doing external development.

I was excited to learn that .NET 4.5 has an option to generate WSDLs as a single file–what a great idea! It’s easy to do, too. All you do is append ?singlewsdl to your service instead of the standard ?wsdl. When you do this, all of the types from the various namespaces that might be in-use are included in a single file. It’s wonderful!

Read more about this and other new enhancements to WCF in .NET 4.5 here.

Advertisements

Unit Test Sending Email with SmtpClient

I have a workflow activity that sends email (the code for this activity can be found here), and I wanted to write integration tests using SpecFlow. This creates an interesting problem. I don’t want to simply mock everything out, but I also don’t want to require a valid SMTP server and email addresses. I also want the test to pass or fail without having to check an email inbox.

Luckily, there are configuration options used by the SmtpClient class that can be used to create files when email messages are sent. This is accomplished by adding some simple code to your application configuration file. (Source here.)

<system.net>
    <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail" />
        </smtp>
    </mailSettings>
</system.net>

This solution is easy and it works, but it creates another problem: I want my test to run automatically on other machines. I don’t want to hardcode a path into the config file because I could run into problems with user permissions or directory structure. I found this blog post that demonstrates how to change the directory programmatically. The only thing I didn’t like about that solution is that it requires the app.config change shown above. I modified the posted solution slightly so that the configuration file section is not needed. Here’s the result:

var path = GetTempPath();

// get mail configuration
var bindingFlags = BindingFlags.Static | BindingFlags.NonPublic;
var propertyInfo = typeof(SmtpClient)
    .GetProperty("MailConfiguration", bindingFlags);
var mailConfiguration = propertyInfo.GetValue(null, null);

// update smtp delivery method
bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
propertyInfo = mailConfiguration.GetType()
    .GetProperty("Smtp", bindingFlags);
var smtp = propertyInfo.GetValue(mailConfiguration, null);
var fieldInfo = smtp.GetType()
    .GetField("deliveryMethod", bindingFlags);
fieldInfo.SetValue(smtp, SmtpDeliveryMethod.SpecifiedPickupDirectory);

// update pickup directory
propertyInfo = smtp.GetType()
    .GetProperty("SpecifiedPickupDirectory", bindingFlags);
var specifiedPickupDirectory = propertyInfo.GetValue(smtp, null);
fieldInfo = specifiedPickupDirectory.GetType()
    .GetField("pickupDirectoryLocation", bindingFlags);
fieldInfo.SetValue(specifiedPickupDirectory, path);

Using this code, I’m able to change the email delivery method and specify the output path programmatically. In my SpecFlow test, I create a temporary directory, process and verify email files created by my workflow, and cleanup. It works like a charm!

Call Method Overloads Based on Derived Type

I was creating a data access component that performed different operations based on the type of request that it received. In order to accommodate this, I have an abstract base request type defined, and handled requests derive from this type. Without getting too deep into why I had to do it this way, I had overloaded methods to which I needed to “route” an instance of the abstract class.

.NET 4 gives us an easy way to do this with the dynamic keyword. Consider the following example, which will correctly call the correct method overload:

void Main()
{
    MyBase obj = new MyOne();
    var p = new Printer();
    p.Print(obj);
}

public class Printer
{
    public void Print(MyBase item)
    {
        dynamic i = item;
        Print(i);
    }
    
    public void Print(MyOne item)
    {
        Console.WriteLine("Print(MyOne)");
    }
}

public abstract class MyBase
{
}

public class MyOne : MyBase
{
}

dynamic wasn’t introduced until .NET 4, though. So, if you have an older application, it may not be available to you. The good news is that you can accomplish the same goal by using reflection. It’s just as effective, but it’s a bit gnarlier.

public void Print(MyBase item)
{
    this.GetType()
        .GetMethod("Print", new[] { item.GetType() })
        .Invoke(this, new object[] { item });
}

So there you have it–two different ways to call method overloads based on object type!

Parse Camel Case into Words

I was working on a small project that had a list of camel case strings that I wanted to display to users. Displaying values as camel case feels dirty, though, so I wanted to pretty it up by parsing the strings into words. Sounds like a job for regular expressions!

After a few tries, this is what I settled on:

var x = Regex.Replace(value, @"([A-Z][^A-Z])", " $1");
x = Regex.Replace(x, "([a-z])([A-Z])", "$1 $2");
x = x.Trim();

Here are my test cases and the results:

Input:
  HelloWorld
  SuperMB
  SMBros
  OneTWOThree

Results:
  Hello World
  Super MB
  SM Bros
  One TWO Three

Ahh, just what I was hoping for. Thanks again, regular expressions!

Events with Return Values

I was working with a team on an interface project that allowed for the transferring of records between N different systems. Once the record was transferred, updates can flow in both directions. I suggested that we use events to begin transactions from source systems, and the event arguments would contain the necessary routing information to help get the data to the correct destination.

Great plan, but we ran into a problem because one of the systems involved uses asynchronous operations for its transactions and another uses synchronous operations. No problem, though. We can get around this with the creative use of callbacks and wait handles.

Let’s look at an example. In the code below, the application calls a method that raises an event. The method needs to return a response, and the event handler produces a response, but there is no way to return the response from the event handler to the method.

class Program
{
    static event EventHandler<SampleEventArgs> Sample;

    static void Main(string[] args)
    {
        Sample += SampleEventHandler;
        var response = RaiseAnEvent();
        Console.WriteLine("Response: {0}", response);
        Console.ReadLine();
    }

    static string RaiseAnEvent()
    {
        if (Sample != null)
        {
            var args = new SampleEventArgs();
            Sample(null, args);
        }
        return null; // need the response!
    }

    static void SampleEventHandler(object sender, SampleEventArgs e)
    {
        string response = "foo";
    }
}

public class SampleEventArgs : EventArgs
{
}

When program runs, the following output is produced:

Response: 

The first problem we need to deal with is that the event handler needs a way to provide its response to the calling code. This could be accomplished by adding a response property to the event argument OR by adding a callback to the event argument. I prefer the latter because the former will require me to know when it is safe to retrieve the value from the event argument whereas the callback is more like a “push.” So, let’s add a callback!

public class SampleEventArgs : EventArgs
{
    public Action<string> SampleCompleted { get; set; }
}

Now that we have the ability to specify a callback to capture the response, guess what the next step is. That’s, right: create the callback method! This is also our opportunity to block execution while we wait for a response. I’ll use a ManualResetEvent to block execution, and I’ll set it in the callback. Perfect, and lambdas make the whole thing a breeze!

static string RaiseAnEvent()
{
    string response = null;
    if (Sample != null)
    {
        var args = new SampleEventArgs();
        var manualResetEvent = new ManualResetEvent(false);
        args.SampleCompleted = r =>
            {
                response = r;
                manualResetEvent.Set();
            };
        Sample(null, args);

        if (!manualResetEvent.WaitOne(1000))
        {
            // timeout waiting for response
        }
    }
    return response;
}

Now that we’ve got our callback created and defined, we just need the event handler to invoke it.

static void SampleEventHandler(object sender, SampleEventArgs e)
{
    string response = "foo";
    if (e.SampleCompleted != null)
    {
        e.SampleCompleted(response);
    }
}

And with that, we’re done! We run the application, and we get the expected output.

Response: foo

Complete sample:

namespace EventsWithReturnValues
{
    using System;
    using System.Threading;

    class Program
    {
        static event EventHandler<SampleEventArgs> Sample;

        static void Main(string[] args)
        {
            Sample += SampleEventHandler;
            var response = RaiseAnEvent();
            Console.WriteLine("Response: {0}", response);
            Console.ReadLine();
        }

        static string RaiseAnEvent()
        {
            string response = null;
            if (Sample != null)
            {
                var args = new SampleEventArgs();
                var manualResetEvent = new ManualResetEvent(false);
                args.SampleCompleted = r =>
                    {
                        response = r;
                        manualResetEvent.Set();
                    };
                Sample(null, args);

                if (!manualResetEvent.WaitOne(1000))
                {
                    // timeout waiting for response
                }
            }
            return response;
        }

        static void SampleEventHandler(object sender, SampleEventArgs e)
        {
            string response = "foo";
            if (e.SampleCompleted != null)
            {
                e.SampleCompleted(response);
            }
        }
    }

    public class SampleEventArgs : EventArgs
    {
        public Action<string> SampleCompleted { get; set; }
    }
}

Group Strings Using LINQ and Regular Expressions

I was working on a problem yesterday where I needed to combine strings that were the same except for one part. Here’s a simplified version of the problem:

Input Array:
"Adam likes apples."
"Adam likes bananas."

Desired Output:
"Adam likes apples and bananas."

It was a no-brainer to use regular expressions to do the matching and parsing, but I couldn’t figure out immediately how to use them in to accomplish my goal. I decided to use LINQ’s ToLookup method to create groups of matching items, and then loop through the groups to implement my combine logic.

The first step is to define a regular expression that lets me do two things. It needs to let me create a group “key,” and it needs to let me extract the data part that I’m ultimately trying to combine. For the simple example above, I can use the following pattern:

^(Adam likes )(.*)\.$

I can create the lookup using the regular expression like so:

var input = new[] 
    {
        "Adam likes apples.",
        "Adam likes bananas.",
    };
var regex = new Regex(@"^(Adam likes )(.*)\.$");
var lookup = input.ToLookup(x => regex.Replace(x, "$1"), x => x);

The final step is to loop through the lookup’s keys and do processing on the groups:

foreach (var key in lookup.Select(x => x.Key).ToList())
{
    if (lookup[key].Count() > 1)
    {
        var items = string.Join(
            " and ",
            lookup[key].Select(x => regex.Replace(x, "$2")).ToArray());
        
        var output = regex.Replace(
            lookup[key].First(),
            string.Format("$1{0}.", items));
        Console.WriteLine(output);
    }
    else
    {
        Console.WriteLine(lookup[key].First());
    }
}

Here’s another example to illustrate how this might be useful:

static void Main(string[] args)
{
    var input = new[] 
        {
            "Adam ate 3 apples.",
            "Adam ate 1 apple.",
            "Adam ate 1 banana.",
            "Adam ate 1 banana.",
            "Adam ate 1 orange.",
        };
    var regex = new Regex(@"^(Adam ate)\s+(\d+)\s+(.*?)s?\.$");
    var lookup = input.ToLookup(x => regex.Replace(x, "$1$3"), x => x);
    foreach (var key in lookup.Select(x => x.Key).ToList())
    {
        if (lookup[key].Count() > 1)
        {
            int sum = 0;
            foreach (var item in lookup[key])
            {
                sum += int.Parse(regex.Replace(item, "$2"));
            }

            var target = regex.Replace(lookup[key].First(), "$3");
            if (sum > 1)
            {
                target += "s";
            }
            var output = regex.Replace(
                lookup[key].First(),
                string.Format("$1 {0} {1}.", sum, target));
            Console.WriteLine(output);
        }
        else
        {
            Console.WriteLine(lookup[key].First());
        }
    }
    Console.ReadLine();
}

// Output:
//   Adam ate 4 apples.
//   Adam ate 2 bananas.
//   Adam ate 1 orange.

Loggin’ Like Bunyan: An NLog Tutorial

Enterprise Library has been my go-to for logging for the past few years. This is largely because I’ve worked on a project that was using it, and it did what I needed. It was relatively easy to use, and I didn’t really have a reason to look elsewhere.

However, I was working on a new project that needed some logging, and I decided to explore some other options on a whim. Another team in the company was using NLog, so that’s where I went first. I gotta say, it seems a lot lighter weight and easier to use than Enterprise Library. It’s all available through NuGet, so adding it to any new project is a breeze.

Adding support for NLog to your application requires just two things: a reference to NLog.dll and an NLog.config file. Here’s how you can go from zero to logging in three steps.

  1. Install the “NLog Configuration” package from NuGet. This gives your project a reference to NLog.dll, the NLog schema (for Intellisense when editing NLog.config), and an empty NLog.config.
  2. Edit NLog.config to have a target and a rule. Here’s a very basic log-to-file config:
    <?xml version="1.0" encoding="utf-8" ?>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <targets>
        <target name="logfile" xsi:type="File" fileName="log.txt" />
      </targets>
      <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" />
      </rules>
    </nlog>
    
  3. Get to loggin’! Create a Logger and use it.
    var logger = LogManager.GetCurrentClassLogger();
    logger.Info("Loggin' like Bunyan!");
    

It’s really that simple. The above config and logging code produce the following log entries:

2013-10-29 10:18:53.7819|INFO|NLogSample.Program|Loggin' like Bunyan!

Writing Maintainable Regular Expressions

If you’ve worked with regular expressions at all, you know it’s easy for them to become quite unruly. It can be hard to decipher a regular expression as you’re working on it, when you know everything you’re trying to accomplish. Imagine how hard it will be for the poor guy who has to do maintenance on that thing later!

There are a few things you can do to make it better for everybody in the long run.

Write Unit Tests

Unit tests are PERFECT for any code that uses regular expressions because you can write a test for each different scenario that you’re trying to match. You don’t have to worry about accidentally breaking something that you had working previously because the tests will regression test everything as you go.

Include Samples

I like to include samples in the code to make it as obvious as possibly what’s going on to anybody looking at the code. I don’t want developers to have to mentally process a regular expression unless they’re there to work on the regular expression itself. I like to provide simple examples like this:

// matches a field and value in quotes
// matches
//   foo = "bar"
//   foo="bar"
// doesn't match
//   foo = bar
//   foo : "bar"
var pattern = @"((\w+)\s*=\s*("".*?"")";

Include Comments in the Pattern

Another trick you can do is to include comments in the regular expression itself by using #. This can be a helpful development tool, too, because it allows you to write out what you’re trying to match in isolated chunks. Note that you’ll need to use the IgnorePatternWhitespace option for this technique to work.

var pattern = @"(
    (?:"".*?"") # anything between quotes (?: -> not-captured)
    |           # or
    \S+         # one or more non-whitespace characters
)"; 
Regex re = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);

I really, really like regular expressions, but they can definitely be maintenance land mines. So, when you use them, do future developers a solid and use tips like these to make them as maintainable as possible.

Convert JSON to XML in .NET

I was working on a project where we were receiving data in a JSON-like format, and we needed the ability to extract values by field name. After doing just a bit of research, I found that the .NET Framework has a JsonReaderWriterFactory class that allows you to create an XmlDictionaryReader that processes JSON data.

Converting JSON to XML is perfect for my needs because it allows me to use LINQ to XML to query and retrieve the values I’m looking for. So, I wrote a few regular expressions to transform the JSON-like format into actual JSON. Then I used the JsonReaderWriterFactory to do the conversion and loaded the resulting XML into an XDocument.

Here’s an example.

const string json = @"{
    ""foo"":""bar"",
    ""complexFoo"": {
        ""subFoo"":""subBar""
    }
}";
byte[] bytes = Encoding.ASCII.GetBytes(json);
using (var stream = new MemoryStream(bytes))
{
    var quotas = new XmlDictionaryReaderQuotas();
    var jsonReader = JsonReaderWriterFactory.CreateJsonReader(stream, quotas);
    var xml = XDocument.Load(jsonReader);
    Console.WriteLine(xml);
}

/*--------
 Output:
 <root type="object">
   <foo type="string">bar</foo>
   <complexFoo type="object">
     <subFoo type="string">subBar</subFoo>
   </complexFoo>
 </root>
--------*/