Subscribe: Cook Computing
Added By: Feedage Forager Feedage Grade B rated
Language: English
add  code  errorcode  exception  expectedexception  fakes  message  new  public  string  studio  types  visual studio  visual 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Cook Computing

Cook Computing

Mainly technical stuff from Charles Cook

Last Build Date: Mon, 24 Oct 2016 19:46:29 -0700


Implementing an XML-RPC Service with ASP.NET MVC

I received a couple of emails recently asking how to implement an XML-RPC service in an ASP.NET MVC application. In case anyone is interested this is how to do it (this is an expanded version of an earlier post).

Define an interface for your XML-RPC service, for example:

using CookComputing.XmlRpc;

public interface IStateName
  string GetStateName(int stateNumber);

Implement the service:

using CookComputing.XmlRpc;

public class StateNameService : XmlRpcService, IStateName
  public string GetStateName(int stateNumber)
    if (stateNumber < 1 || stateNumber > m_stateNames.Length)
      throw new XmlRpcFaultException(1, "Invalid state number");
    return m_stateNames[stateNumber - 1];

  string[] m_stateNames
    = { "Alabama", "Alaska", "Arizona", "Arkansas",
        "California", "Colorado", "Connecticut", "Delaware", "Florida",
        "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", 
        "Kansas", "Kentucky", "Lousiana", "Maine", "Maryland", "Massachusetts",
        "Michigan", "Minnesota", "Mississipi", "Missouri", "Montana",
        "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", 
        "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma",
        "Oregon", "Pennsylviania", "Rhose Island", "South Carolina", 
        "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", 
        "Washington", "West Virginia", "Wisconsin", "Wyoming" };

Implement a custom route handler:

using System.Web;
using System.Web.Routing;

public class StateNameRouteHandler : IRouteHandler
  public IHttpHandler GetHttpHandler(RequestContext requestContext)
    return new StateNameService();

Register the custom route in global.asax.cs:

public static void RegisterRoutes(RouteCollection routes)

  routes.Add(new Route("api/statename", new StateNameRouteHandler()));

  // ...


Check that everything is working by pointing your browser to the url for the handler, for example something like http://localhost:33821/api/statename in this case when running from Visual Studio. You should then see an automatically generated help page for the service. If this is ok then point your XML-RPC client to the service and start making calls.

Faking In Visual Studio 11
The Problem Dealing with Now and why I'm almost done with C# and Java — Karl Seguin's post about how the way you code is a by-product of the progamming language you use — discusses how difficult it is to test unit code like this in C#: var audit = new Audit { UserName = user.Name, Dated = DateTime.Now, //... }; The following test might work or not, depending on how quickly the code runs: public void ItSetsTheAuditTimeToRightNow() { var audit = CreateAuditItem(new User{Name = "Leto"}); audit.Dated.ShouldEqual(DateTime.Now);} } Unfortunately it's difficult to mock DateTime.Now because it's a static method, which leads to more complicated solutions such as injecting an abstract dependency into objects or using a C# lambda such as Ayende's SystemTime class: public static class SystemTime { public static Func Now = () => DateTime.Now; } This allows you to write test code like this: SystemTime.Now = () => new DateTime(2000,1,1); repository.ResetFailures(failedMsgs); SystemTime.Now = () => new DateTime(2000,1,2); var msgs = repository.GetAllReadyMessages(); Assert.AreEqual(2, msgs.Length); Another solution mentioned in the post's comments is to use NUnit's Within: Assert.That(audit.Dated, Is.EqualTo(DateTime.Now).Within(new TimeSpan(0, 0, 0, 0, 50))); This works, sort of, but isn't a general solution to this type of problem. Visual Studio 11 Fakes Some of the comments mention TypeMock Isolator and the Moles project from Microsoft, and it so happens the Visual Studio 11 beta reveals that Moles has been productized into Visual Studio as the Fakes Framework. This can inject two types of dummy implementation into unit tests: stub types for interfaces and overridable methods, and shim types for static and non-overridables methods: Stub types Stub types make it easy to test code that consumes interfaces or non-sealed classes with overridable methods. A stub of the type T provides a default implementation of each virtual member of T, that is, any non-sealed virtual or abstract method, property, or event. The default behavior can be dynamically customized for each member by attaching a delegate to a corresponding property of the stub. A stub is realized by a distinct type which is generated by the Fakes Framework. As a result, all stubs are strongly typed. Although stub types can be generated for interfaces and non-sealed classes with overridable methods, they cannot be used for static or non-overridable methods. To address these cases, the Fakes Framework also generates shim types. Shim types Shim types allow detouring of hard-coded dependencies on static or non-overridable methods. A shim of type T can provide an alternative implementation for each non-abstract member of T. The Fakes Framework will redirect method calls to members of T to the alternative shim implementation. The shim types rely on runtime code rewriting that is provided by a custom profiler. Delegates Both stub types and shim types allow you to use delegates to dynamically customize the behavior of individual stub members. Faking DateTime To test the DateTime code, create a unit test project and right click on one of the referenced assemblies in Solution Explorer. This displays a context menu which has an "Add Fakes Assembly". Select this and two more referenced assemblies are automatically added to the project: Microsoft.QualityTools.Testing.Fakes Microsoft.VisualStudio.QualityTools.UnitTestFramework. Visual Studio will automatically generate a file called Microsoft.VisualStudio.QualityTools.UnitTestFramework.fakes in a directory in the project called Fakes. This XML file is used to configure the assembly for which fakes are generated and the namespaces and types that are included. We want to generate a shim type for DateTime so we can change the file to specify the mscorlib assembly: Bui[...]

Visual Studio - Function Return Value In Debugger

While preparing for job interviews after I arrived in the US I rehearsed questions such as — how would you improve your favourite programming language — what new features would you like in your favourite IDE — and so on. As it happened I never got asked any of these questions but browsing through the Visual Studio UserVoice site I noticed that one of my desired Visual Studio enhancements is under consideration but won't make it into Visual Studio 11. This is Function return value in debugger. I've never liked having to modify code to be able to see the value being returned from a function, for example changing code like this:

string Foo()
    /// ...

    return Bar();

So that a local variable can be used to watch the return value from the call to Bar():

string Foo()
    /// ...

    string ret = Bar();
    return ret;

One of the site admins added a comment:

For those out there who have experience debugging native C++ or VB6 code, you may have used a feature where function return values are provided for you in the Autos window. Unfortunately, this functionality does not exist for managed code. While you can work around this issue by assigning the return values to a local variable, this is not as convenient because it requires modifying your code.

In managed code, it’s a lot trickier to determine what the return value of a function you’ve stepped over. We realized that we couldn’t do the right thing consistently here and so we removed the feature rather than give you incorrect results in the debugger. However, we want to bring this back for you and our CLR and Debugger teams are looking at a number potential solutions to this problem. Unfortunately this is will not be part of Visual Studio 11.

Oh well, back to using local variables for the time being, even if they result in code review comments such as "Remove unnecessary variable".

Unit Testing With ExpectedException
@mentalguy must have been having a frustrating day: I've come across this problem with .NET code. Often a single exception type will cover several different error conditions and so when writing the corresponding unit tests it's tempting to assert on the exception's Message property. Of course this is bad because it assumes the text of the message won't be changed. NUnit NUnit encourages the checking of exception messages when using the ExpectedException attribute, for example [ExpectedException(typeof(ArgumentException), ExpectedMessage="expected message" )] but suggests that this is not good practice by allowing you to match on a substring or a regular expression: public enum MessageMatch { /// Expect an exact match Exact, /// Expect a message containing the parameter string Contains, /// Match the regular expression provided as a parameter Regex } For example, this is for a test that passes only if an ArgumentException with a message containing "unspecified" is received. [ExpectedException(typeof(ArgumentException), ExpectedMessage="unspecified", MatchType=MessageMatch.Contains)] public void TestMethod() { ... } It's better to have some way of specifying an error code which can be checked independently of the message, for example say we have an exception base class supporting an error code from which we derive custom exception classes: public class ExceptionBase : Exception { public ExceptionBase(int errorCode, string message) : this(errorCode, message, null) { } public ExceptionBase(int errorCode, string message, Exception innerException) : base(message, innerException) { ErrorCode = errorCode; } public int ErrorCode { get; private set; } } public class MessageException : ExceptionBase { public MessageException(int errorCode, string message) : base(errorCode, message) { } public MessageException(int errorCode, string message, Exception innerException) : base(errorCode, message, innerException) { } } We can test for exceptions with a particular error code like this: [TestFixture] public class Tests { [Test] public void Test1() { MessageException ex = Assert.Throws(() => { // code which is expected to throw the exception // ... } ); Assert.AreEqual(ErrorCodes.HEADER_MISSING, ex.ErrorCode); } } Visual Studio Visual Studio does the right thing and doesn't have a built-in way of checking the exception message. You can even use your own attributes derived from its ExpectedExceptionBaseAttribute class. This allows us to implement an attribute which can be used to check the error code in exception classes derived from the above ExceptionBase class: [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class ExpectedExceptionWithErrorCode : ExpectedExceptionBaseAttribute { public Type ExpectedException { get; set; } public int ExpectedErrorCode { get; set; } public ExpectedExceptionWithErrorCode(Type expectedException) : this(expectedException, 0, "") { } public ExpectedExceptionWithErrorCode(Type expectedException, int errorCode) : this(expectedException, errorCode, "") { } public ExpectedExceptionWithErrorCode(Type expectedException, int errorCode, string noExceptionMessage) : base(noExceptionMessage) { if (expectedException == null) throw new ArgumentNullException("exceptionType"); if (!typeof(Exception).IsAssignableFrom(expectedException)) throw new ArgumentException("Expected exception type must be " + "System.Exception or derived from System.Exception.", "expectedException"); ExpectedException = expectedException; ExpectedErrorCode = errorCode; } protected override void Verify(Exception exception) { if (exception.GetType() != ExpectedException) { base.RethrowIfAssertException(exception); string msg = string.Format("T[...]

More on Collection Initializers

While looking at collection initializers I came across mucking about with hashes... and more mucking about with hashes by Alex Henderson (via Phil Haack). In these posts he describes ways of creating an instance of a string-keyed Dictionary in a Ruby-like way using lambda expressions, for example:

Dictionary items = Hash(Age => "10", Height => "20");

The second post contains the fastest implementation (contributed by Andrey Shcekin):

public Dictionary Hash(params Func[] args)
where T : class  
    var items = new Dictionary();
    foreach (var func in args)
        var item = func(null);
        items.Add(func.Method.GetParameters()[0].Name, item);
    return items;

[Comment: I don't see why the class constraint is necessary]

This led me to think that I could implement an Add extension method which would allow a collection initializer to be used, for example like this:

var items = new Dictionary {  Name => "alex",  Age => "10" };

I came up with this:

static class Extensions
  public static void Add(this Dictionary dict, Func args)
    var item = args(null);
    dict.Add(args.Method.GetParameters()[0].Name, item);

Unfortunately, although this works fine when Add is invoked explicitly, it fails to compile when attempting to use it in a collection initializer. The compiler only recognizes member functions called Add, not extension methods. C# PM Alex Turner wrote on Connect:

You're right that the spec is ambiguous here! There was no explicit decision in C# 3.0 to prevent this from working; it was simply an implementation limitation we accepted when we discovered it late in the product cycle. We see no design reason not to add this now, but unfortunately, we are starting to lock down on our feature set and won't be able to get to this feature for this release. We'll definitely keep this in mind when planning for our next release!

...I've added a vote for collection initializers binding to Add extension methods to the OneNote notebook we use internally to track C# compiler and language requests. We can't promise if or when we'll get to this feature, but we'll definitely keep it in mind during planning for the next release!

I tried this with the .NET 4.5 Developer Preview and it still fails to build, but of course this may change before the final release.

On the other hand, VB does support the use of extension methods called Add in collection initializers but its syntax for lambda expressions rather misses the point of the exercise:

Imports System.Runtime.CompilerServices

Module Sample
    Sub Main()
        Dim dict As New Dictionary(Of String, Integer) _
            From { Function(Age As String) 10, Function(Height As String) 20 }
    End Sub

    Sub Add(Of T)(ByVal dict As Dictionary(Of String, T), 
                  ByVal args As Func(Of String, T))
        Dim item As T
        item = args(Nothing)
        dict.Add(args.Method.GetParameters()(0).Name, item)
    End Sub
End Module