SCSS Gotchas

September 3rd, 2013 by David Bending No comments »

If you use a @charset directive, it must be the first line in the file.  don’t even put a comment in front of it.

Right:

@charset "UTF-8";

Wrong:

// Set up my charset
@charset "UTF-8";
Share

Azure Gotchas II

July 19th, 2013 by David Bending No comments »

When you build a VM in the Azure Portal, don’t choose the username ‘tester’.  If you do the machine won’t start and will remain stuck in the provisioning phase.

Share

Azure Gotchas

July 18th, 2013 by David Bending No comments »

Having fun getting your Azure startup tasks to run?  One things to beware of when debugging this is to know where your code runs.  If you are deploying a web role you’ll likely see your startup script in e:\approot.  However, most likely it’s actually running the copy in e:\approot\bin that got there because you selected ‘Build Action’ as ‘Content’ and ‘Copy to Output Directory’ as ‘Always’ or ‘If Newer’.

Similarly you’ll see your Web.config in e:\approot.  But that isn’t what the site is using, which will be somewhere lower down (check from IIS).

Finally Azure is fussy about encodings for startup scripts.  Try using codepage 1252 and you should be OK.

Share

The type TraceListener cannot be constructed

May 22nd, 2013 by David Bending No comments »

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 by David Bending No comments »

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 by David Bending No comments »

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 by David Bending 6 comments »

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 by David Bending No comments »

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 by David Bending No comments »

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

Brown M&M’s and Coding Standards

March 2nd, 2010 by David Bending No comments »

I've been doing more work on running coding dojos and as part of that I've been thinking about compliance to published coding standards and what the purpose of those standards are.  Some of the rules have a very clear purpose: doing it in a certain way is just plain better.  Other rules have a more subtle intentI think: essentially they are brown M&M's. 

Let me explain: Van Halen arranged notoriety for having a rider than insisted on having all brown M&M's removed on pain of forfeiture of the show.  Most people put this down to rock star arrogance, but actually the reason for this clause is a lot more interesting.  This is from David Lee Roth's autobiography:

Van Halen was the first band to take huge productions into tertiary, third-level markets. We'd pull up with nine eighteen-wheeler trucks, full of gear, where the standard was three trucks, max. And there were many, many technical errors — whether it was the girders couldn't support the weight, or the flooring would sink in, or the doors weren't big enough to move the gear through. The contract rider read like a version of the Chinese Yellow Pages because there was so much equipment, and so many human beings to make it function. So just as a little test, in the technical aspect of the rider, it would say "Article 148: There will be fifteen amperage voltage sockets at twenty-foot spaces, evenly, providing nineteen amperes . . ." This kind of thing. And article number 126, in the middle of nowhere, was: "There will be no brown M&M's in the backstage area, upon pain of forfeiture of the show, with full compensation."

So, when I would walk backstage, if I saw a brown M&M in that bowl . . . well, line-check the entire production. Guaranteed you're going to arrive at a technical error. They didn't read the contract. Guaranteed you'd run into a problem. Sometimes it would threaten to just destroy the whole show. Something like, literally, life-threatening.

So maybe that's what some of the style rules in coding standards are.  Brown M&M's.  A way to see if whoever wrote the code was paying attention and thinking about what they are doing.

Share