Archive for the ‘.NET’ category

The type TraceListener cannot be constructed

May 22nd, 2013

If you are using the Enterprise Library Logging block and you get this error:

The type TraceListener cannot be constructed. You must configure the container to supply this value.

It’s because you’ve referenced a listener in your sources block that isn’t defined in the listeners block.

e.g.:

<loggingConfiguration name="" tracingEnabled="true" defaultCategory="Error">
  <listeners>
    <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  name="Azure Diagnostics Trace Listener" />
  </listeners>
  <categorySources>
    <add switchValue="All" name="Error">
      <listeners>
        <add name="Azure Diagnostics Trace Listener" />
      </listeners>
    </add>

is OK, but

        <add name="Foo" />

is wrong.

Share

RhinoMocks 3.6 with “Just My Code” disabled

July 17th, 2012

When I turned off the debug ‘Just My Code’ setting, RhinoMocks started throwing an exception claiming it can’t mock sealed classes.  This is very mysterious, because my mock is a multi-mock of two interfaces.  Bizarre.  Equally as bizarre is the fix, which is to close Visual Studio, delete the .suo file, and restart – at which everything is fine…

Share

Concurrent Sessions in MVC2

September 21st, 2010

There’s lots of rules that control how many concurrent connections you can have in an ASP.net MVC2 application.

Firstly the browser itself limits the number of connections it will make to the same domain.  The limit used to be 2 (as per the HTTP specification).  Some browsers increase this limit, but older browsers like IE6 will still stick to it.

Secondly you have the number of threads available in IIS to content with.  Thomas Masquardt’s Blog gives a very detailed explanation of this.

Finally MVC itself has some limitations. Basically you can only have a single request using a read-write session at any given time.  This means that if you have a controller serving up images, and you don’t take any steps to avoid the problem, you will only ever serve up one image at a time.  Imran Baloch’s Blog gives a lot more information about this and shows how to create session-less actions to avoid the issue.  For me the solution is quite simple.  By placing the following code in Global.asax.cs:

protected void Application_BeginRequest()
{
    if((Request.Url.AbsoluteUri.ToUpperInvariant().Contains("REFRESHPRICES")
        && Request.Cookies["ASP.NET_SessionId"] != null))
    {
        Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
    }
}

I can make the session for my action read-only, and sidestep the limit.

Warning

Just marking the session sate as read-only doesn’t prevent you from trying to modify the session.  It’s up to you to maintain thread-safety if you decide to lie to the framework.

Share

MVC2 Cross Field Validation

August 10th, 2010

Introduction to Validation

Nearly all web applications require some form of validation. Validation performs two main purposes: helping the user to enter correct values on a web page, and protecting the application from invalid or malicious input.

Validation can take place client-side within the browser, or server-side when the page is posted to the server. ASP.NET MVC2 comes with a flexible framework for applying validation using data annotations on the view model. Scott Gu has written an excellent tutorial on basic MVC validation here: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.

Limitations of Built-in MVC Validation

The built-in validation works well for standard scenarios, but there are a few common scenarios it can’t cope with. One of the main issues is that validation can only be done on a model property in isolation. Often we will want to validate a property based on the current value of some other property: for instance we may want our confirm password field value to be the same as the password box.

In this article we will extend the MVC validation framework to provide support for cross-field validation. We’ll do this in part by creating custom validation attributes as described in Phil Haack’s article (http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx) but we’ll also need to extend the validator framework to allow us to validate across fields.

Extending the Framework to Support Cross-Field Validation

To create a custom validation attribute we usually derive from ValidationAttribute and override the IsValid method, however IsValid only gets passed the value of the property to validate and we are going to need to see the value of other fields in the model. To accommodate this we’ll create an interface ICrossFieldValidationAttribute that has an IsValid method with access to the entire view model (note these code snippets only show significant lines – download the example solution to get the whole files):

public interface ICrossFieldValidationAttribute
{
    bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata);
}

Next we build a base class for cross-field validators. This base class uses the extended IsValid defined above, rather than the narrower method used in the framework’s DataAnnotationsModelValidator class.

public abstract class CrossFieldValidator<TAttribute> : DataAnnotationsModelValidator<TAttribute>
        where TAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        var attribute = Attribute as ICrossFieldValidationAttribute;

        if (!attribute.IsValid(ControllerContext, container, Metadata))
        {
            yield return new ModelValidationResult {Message = ErrorMessage};
        }
    }
}

Building the Validation

Now that we have a cross-field validation framework in place, we can build our new attribute.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EqualToPropertyAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public string OtherProperty { get; set; }

    public bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata)
    {
        var propertyInfo = model.GetType().GetProperty(OtherProperty);
        var otherValue = propertyInfo.GetGetMethod().Invoke(model, null);

        if (modelMetadata.Model == null) modelMetadata.Model = string.Empty;
        if (otherValue == null) otherValue = string.Empty;

        return modelMetadata.Model.ToString() == otherValue.ToString();
    }
}

And apply it to the view model:

public class Account
{
    public string Password { get; set; }

    [EqualToProperty(OtherProperty = "Password")]
    public string ConfirmPassword { get; set; }
}

We also need to create a validator class to emit the correct client-side rules, and to invoke the IsValid method.

public class EqualToPropertyValidator : CrossFieldValidator<EqualToPropertyAttribute>
{
    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "equaltoproperty",
            ErrorMessage = Attribute.FormatErrorMessage(Metadata.PropertyName),
        };

        rule.ValidationParameters.Add("otherProperty", Attribute.OtherProperty);

        return new[] { rule };
    }
}

Finally we need to create a JavaScript function to evaluate the rule client-side:

jQuery.validator.addMethod("equaltoproperty", function (value, element, params) {
    if (this.optional(element)) {
        return true;
    }

    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue = otherPropertyControl[0].value;
    return otherPropertyValue == value;
});

function testConditionEqual(element, params) {
    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue;
    if (otherPropertyControl[0].type == "checkbox") {
        otherPropertyValue = (otherPropertyControl[0].checked) ? "True" : "False";
    } else {
        otherPropertyValue = otherPropertyControl[0].value;
    }

    return otherPropertyValue == params.comparand;
}

And the final step is to register our new attribute with MVC. We do this in Global.asax Application_Start method like this:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EqualToPropertyAttribute),
                                                      typeof(EqualToPropertyValidator));
 

Example

The example code is here CrossFieldValidation.

Share

Exception in WCF Service (HRESULT: 0×80131045)

August 2nd, 2010

I couldn’t understand why I could call my WCF service from WcfTestClient, but when I hit it with integration tests built using the unit test framework I got this message:

Test method Lookup.IntegrationTests.HttpLabelTests.GetLabel threw exception:
System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '<html>
    <head>
        <title>Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common' or one of its dependencies. Strong name signature could not be verified. &nbsp;The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)</title>
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Lucida Console";font-size: .9em}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandabl'. ---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.

The answer is CodeCoverage.  By default Visual Studio 2010 tries to measure coverage for every assembly in the service bin.  To avoid the problem turn this off, and add coverage for each assembly you are interested in individually.

Share

Removing types from Unity in unit tests

April 27th, 2010

Calling teardown on the UnityContainer doesn’t remove a registration from Unity.  Here’s how to unit test code that resolves a type configured by RegisterInstance rather than configuration.  IoC is a thin wrapper around the UnityContainer.

        private ControllerContext _controllerContext;
        private ModelMetadata _modelMetadata;
        private Proposer _proposer;
        private ILookup _lookup;
        private LifetimeManager _lifetimeManager;

        [TestInitialize]
        public void SetupTest()
        {
            _controllerContext = new ControllerContext();
            _modelMetadata =
                ModelMetadataProviders.Current.GetMetadataForType(() => _proposer.AcceptedTerms, typeof (bool));
            _proposer = new Proposer();
            _lifetimeManager = new ContainerControlledLifetimeManager();
            _lookup = MockRepository.GenerateStrictMock<ILookup>();
            IoC.UnityContainer.RegisterInstance(typeof(ILookup), _lookup, _lifetimeManager);
        }
        [TestCleanup]
        public void VerifyExpectations()
        {
            _lifetimeManager.RemoveValue();
            _lookup.VerifyAllExpectations();
         }       
        [TestMethod]
        public void ErrorMessageIsCorrectlyGenerated()
        {
            var target = new NotDefaultIfAttribute("test/notDefaultIf")
            {
                OtherProperty = "Surname"
            };
            _lookup.Expect(l => l.GetLabel("test/notDefaultIf")).Return("Blah blah {0} blah");
            Assert.AreEqual("Blah blah AcceptedTerms blah", target.FormatErrorMessage("AcceptedTerms"));
        }

Share

Pex – Some Early Thoughts

February 2nd, 2010

I've been looking recently at Pex, Microsoft's automated white box testing software. There's basically 4 parts to Pex:

  1. A framework for writing parameterised unit tests.
  2. An explorer, for finding boundary conditions in code.
  3. Suggestions of preconditions that should be added to methods.
  4. Moles – a way of stubbing even static properties and methods (such as DateTime.Now).

Parameterised Unit Tests (PUT)

When manually writing unit tests, we often end up with blocks of tests that are essentially the same in concept, but with different input/output combinations.  For example, an addition routine might have tests for different combination of negative and positive numbers.  Pex creates its tests a parameterized tests.  There is a template test, and underneath that an instance of each test value.

The templates are placed in a source file and look like normal unit tests.  The parameterised versions are stored underneath in a .g.cs file.  These files are not intended to be edited and are created automatically by the Pex explorer.

You can also write your own PUTs.  More on this later…

The Explorer

The 'white box' part of Pex refers to the explorer.  This essentially looks at all the possible paths through a piece of code and generates a test for each. Let's look at this piece of code:

public int Add(int x, int y)
{
    return x + y;
}

If we run Pex on this, we get the following test:

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Add01()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Add(s0, 0, 0);
    Assert.AreEqual<int>(0, i);
    Assert.IsNotNull((object)s0);
}

Actually there's a bit more to it – but this shows the basic details.  As we can see, it's a fairly dull test.  in particular Pex hasn't added any code to see if the result of the operation has overflowed. On the other hand let's see what it does if there's a bit more going on in the method:

public int Fibonacci(int n)
{
    if (n < 0)
    {
        throw new ArgumentOutOfRangeException("n");
    }

    if (n == 0)
    {
        return 0;
    }

    if (n == 1)
    {
        return 1;
    }

    return Fibonacci(n - 2) + Fibonacci(n - 1);
}

This is an (admiteddly rubbish) implementation of Fibonacci. It's more interesting that Add because there's more paths through it. This time when we run Pex we get:

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci01()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 0);
    Assert.AreEqual<int>(0, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci02()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 1);
    Assert.AreEqual<int>(1, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci03()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 2);
    Assert.AreEqual<int>(1, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Fibonacci04()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, int.MinValue);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci05()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 14);
    Assert.AreEqual<int>(377, i);
    Assert.IsNotNull((object)s0);
} 

So Pex has created a test case for each path through the program.

Suggestions

When passing reference types to a method, Pex will realise that the value could be null.  For all such methods it will suggest the a pre-condition is added.  There's also a button that will get Pex to automatically insert the pre-condition into the code for you.  This saves a bit of time, but isn't a huge win.  That said Pex does understand code contracts so there may be bigger wins to be had here.

Moles

Pex also contains a mocking framework called Moles.  Unlike most mocking frameworks, Moles do their work at runtime level (like Isolator) and consequently you can use them to mock static properties.  Consider this code:

public void Y2kBug()
{
    if (DateTime.Now == new DateTime(1999, 12, 31))
    {
        throw new InvalidProgramException("Arrgghhh!!!!");
    }
} 

We'd like to unit test this, and we don't want to have to change the system clock to do so.  Unfortunately, DateTime.Now is static so the likes of Rhino Mocks and MoQ can't help.  With Pex Moles we can do the following:

[TestMethod]
[ExpectedException(typeof(InvalidProgramException))]
[HostType("Moles")]
public void Y2kBugTest()
{
    MDateTime.NowGet = () => new DateTime(1999, 12, 31);

    Y2k target = new Y2k();
    target.Y2kBug();
} 

We have generated Moles for mscorlib (by choosing Add New Item -> Pex Moles) in Visual Studio.  This creates a mole for each mscorlib type in the Moles namespace with the M prefix.  We then tell the mole to return the value we ant in the unit test (note that we supply a delegate not a value, and that properties are a Put and a Get mole).  By specifying the HostType attribute for our test, we cause the unit test runner to route the code trhough a mole supplying the value we want.

See Nikolai Tellman's video for more on this at: http://channel9.msdn.com/posts/Peli/Moles-Replace-any-NET-method-with-a-delegate/.

 

Share

Code Contracts and Entity Framework

January 29th, 2010

Using Code Contracts in projects that use Entity Framework for data access is possible, but there are a few wrinkles to consider.

Although the designer emits partial classes, that isn’t enough to add contracts because we need to add pre and postconditions directly to the generated methods.

The answer is to use a reference assembly. This contains the contract information for the data access classes, but is otherwise not used by the client class.

Here’s how this is done:

1. Move the Entity Framework code into its own project. This isn’t absolutely essential, but will keep things simpler.

2. Make sure that we don’t attempt to emit contract information for this assembly. On the pojrect properties screen move to the Code Contracts tab and select ‘Do Not Build’.

3. Create a new project for the contract information. You should name the project MyModel.Contracts but the assembly name should be the same as the Model project, so you will need to move to the Application tab of project properties.

4. In the contract assembly create classes for each entity object you want to specify conditions for.  For example:

public partial class MyObject : EntityObject
{
    public void Foo()
    {
        Contract.Requires(Bar != null);
    }
}

Remember the code doesn’t need to do anything except specify contract conditions.  It won’t be run by the real application although it must compile.

5. Make sure the contract assembly emits contract information by selecting ‘Build’ on the Code Contracts tab of the assembly properties.

6. In your client class, make sure it picks up contract information from the contract assembly rather than looking in the model assembly itself. To do this go to the Code Contracts tab and check the ‘call-site requires checking’ box. Then in the Lib Paths section of the advanced settings on the contracts tab add the path to the contract assembly (e.g. ..\..\MyModel.Contract\bin\debug). The deployed code will now use the objects from the model assembly at runtime, but will obtain contract information from the contract assembly.

Share

ReSharper and Microsoft Code Contracts

January 27th, 2010

I’m using code contracts in an MVC RC / .NET 3.5 application and I don’t want ReSharper 5 complaining about potential null reference accesses that aren’t in fact possible due to the contracts.

The solution (pieced together from StackOverflow and JetBrains) is to add the following XML to a file named C:\Program Files\JetBrains\ReSharper\v5.0\Bin\ExternalAnnotations\Microsoft.Contracts\Microsoft.Contracts.xml.

<assembly name="Microsoft.Contracts">
  <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
    </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Requires``1(System.Boolean)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean,System.String)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Requires``1(System.Boolean,System.String)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Invariant(System.Boolean)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Invariant(System.Boolean,System.String)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
  <member name="M:System.Diagnostics.Contracts.Contract.Assume(System.Boolean)">
    <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/>
    <parameter name="condition">
      <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)">
        <argument>0</argument>
      </attribute>
    </parameter>
  </member>
</assembly>
Share

Adobe BrowserLab

January 20th, 2010

I got forwarded this link to Adobe BrowserLab.  Is a great way of seeing how your site looks in different browsers.  Thanks Nick!

Adobe Labs – Adobe BrowserLab.

Share