Problem after update to Framework v4.5.2

January 15th, 2015 by admin No comments »

After installing the update to .Net Framework v4.5.2 and rebooting, Visual Studio 2013 would no longer load my Azure SDK 2.3 cloud service, complaining that “The CctSharedPackage did not load correctly”.  The fix was to go to the Control Panel and select ‘Azure Tools for Microsoft Visual Studio 2013 – v2.3’, then hit change and repair.

 

Share

Keeping Web Applications out of the load balancer pool until they have initialized

January 9th, 2015 by admin No comments »

Some of our web applications take a little while to start-up.  Unity resolution, cache warming, configuration build etc. all take time.  Normally Azure will put a web role in the load balanced pool as soon as its OnStart has completed, which means a user may hit a cold application and have to wait 30-60s for their request to be processed.

AppPools also recycle at least every 29 hours by default.  This can be overridden but the periodic recycle is intended to cope with memory leaks, LOH fragmentation etc., so this may be counter-productive.

This is one way of dealing with it.

  1. Call the application on the internal (i.e. non-load balanced endpoint) from the role’s OnStart method synchronously.  This means that OnStart won’t return until the application has completed a request, and so the role won’t be marked as Ready and added to the pool until it’s warm.
  2. In the Application_End method, request a page from the application.  The role’s OnStart method isn’t called on a AppPool recycle, so doing this will ensure that the AppPool immediately restarts.
  3. Register a RoleEnvironmentStatusCheck callback that will make sure that if the application is in the pool while it is initialising, it will be immediately removed.

Here’s the code.

In your WebRole.cs (or whatever derives from RoleEntryPoint), call the main application.  Note that we are ignoring SSL errors, because we aren’t using the domain name.  I’ve also found that hitting it on localhost or 127.0.0.1 won’t work.  Your mileage may vary here.

 

public override bool OnStart()
{
    try
    {
        // If the app pool is recycling, make sure we start up again straight away.  Note that
        // we need to do this by IP address, local host name or localhost or 127.0.0.1 won't work.
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslpolicyerrors) => true;
        var ipEntry = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var address in ipEntry.AddressList)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (address.Equals(IPAddress.Loopback)) continue;
                var client = new WebClient();
                client.DownloadString(string.Format("https://{0}/", address));
            }
        }
    }
    catch (Exception exception)
    {
        System.Diagnostics.Trace.WriteLine(exception);
        // Don't deal with errors here.  The main application will do that.
    }
    return base.OnStart();
}

In Global.asax.cs

protected void Application_End()
{
    try
    {
        // If the app pool is recycling, make sure we start up again straight away.  Note that
        // we need to do this by IP address, local host name or localhost or 127.0.0.1 won't work.
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslpolicyerrors) => true;
        var ipEntry = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var address in ipEntry.AddressList)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (address.Equals(IPAddress.Loopback)) continue;

                var client = new WebClient();
                client.DownloadString(string.Format("https://{0}/?", address));
            }
        }
    }
    catch(Exception exception)
    {
        _logger.Log(exception, "Error trying to restart application");
    }
}

In Global.asax.cs add this callback:

/// <summary>
/// Keep the instance out of the load balancer pool until initialisation is complete.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoleEnvironmentStatusCheck(object sender, RoleInstanceStatusCheckEventArgs e)
{
    if (_isBusy)
    {
        e.SetBusy();
    }
}

Add this field to the class:

 private volatile bool _isBusy = true;

And modify Application_Start to look like this:

protected void Application_Start()
{
    RoleEnvironment.StatusCheck += RoleEnvironmentStatusCheck;
 
    // Initialisation code
    _isBusy = false;
}

 

Share

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: 0x80131045)

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