Paul Glavich 

Paul is currently an ASP.NET MVP and works as a senior consultant for readify. Previously he was a technical architect for EDS Australia and he has over 15 years of industry experience ranging PICK, C, C++, Delphi and Visual Basic 3/4/5/6 to his current speciality in .Net with C#, COM+ and ASP.NET.

Paul has been developing in .Net technologies since .Net was first in Beta and was technical architect for one of the worlds first internet banking solutions using .Net technology.

Paul can be seen on various .Net related newsgroups, has presented at the Sydney .Net user group (www.sdnug.org) and TechEd, and is also a board member of ASPInsiders (www.aspinsiders.com). He has also written some technical articles which can be seen on community sites such as ASPAlliance.com (www.aspalliance.com). Paul has authored a book on Beginning AJAX in ASP.NET, is co-authoring a second book on Microsoft ASP.NET AJAX, and is currently focusing on Microsoft ASP.NET AJAX and Windows Communication Foundation technologies.

On a more personal note, Paul is married with 3 children, 2 grandkids, and holds a 4th degree black belt in Budo-Jitsu.


Glavs Blog

ASP.NET MVC 3 and Custom Extensions

When playing with the latest ASP.NET MVC 3 Preview 1 bits, some people have mentioned their dislike of the .cshtml extension used for the “razor” view engine that comes with ASP.NET MVC 3 and also WebMatrix. Well there are a number of ways you can change this. For the purposes of learning and tinkering, I decided to try and register a new view engine using the new Dependency Injection support within ASP.NET MVC 3.

So, in the Global.asax.cs file I did this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    IUnityContainer container = new UnityContainer();

    container.RegisterInstance<IControllerFactory>(new UnityControllerFactory(container));
    container.RegisterType<IViewEngine, TestViewEngine>();
   
    UnityMvcServiceLocator svcLocator = new UnityMvcServiceLocator(container);
    MvcServiceLocator.SetCurrent(svcLocator);

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Note: Previously (and this options is still available), you would register your custom view engine by adding it to the existing Engines collections like so:

ViewEngines.Engines.Add(new TestViewEngine());

My Custom view engine looked like this:

public class TestViewEngine : VirtualPathProviderViewEngine
{
    public TestViewEngine()
    {
        base.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.glav", "~/Areas/{2}/Views/Shared/{0}.glav" };
        base.AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.glav", "~/Areas/{2}/Views/Shared/{0}.glav" };
        base.AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.glav", "~/Areas/{2}/Views/Shared/{0}.glav" };
        base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.glav", "~/Views/Shared/{0}.glav" };
        base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.glav", "~/Views/Shared/{0}.glav" };
        base.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.glav", "~/Views/Shared/{0}.glav" };

    }
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        return new CshtmlView(partialPath, "");
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        return new CshtmlView(viewPath, masterPath);
    }
}

This view engine implementation looked for a view extension of ‘.glav’ and invokes the “razor” view to parse the document/page (CshtmlView)

ASP.NET MVC 3 will use the MvcServiceLocator that we have supplied, and call the ‘GetAllInstances’ method when determining what classes implement IViewEngine so that it can invoke the correct view engine.

By default, ASP.NET MVC 3 has the System.Web.Mvc.WebFormViewEngine and the System.Web.Mvc.CshtmlViewEngine registered. We are adding a new custom view engine to the mix by registering it with the service locator that ASP.NET MVC uses ( MvcServiceLocator ). When ASP.NET MVC goes looking for a view engine it will use the MvcServiceLocator to get all instances of IViewEngine (via a call to ‘GetAllInstances’ ) in order to try and satisfy the request to process/render a particular view.

Now all this theory is good and well, and I thought it would work however it didn’t. One of the issues with Unity (and thats what I was basing my testing on since that was the example provided with ASP.NET MVC 3) is the the ' MvcServiceLocator.GetAllInstances ‘ method, calls the ResolveAll method of the UnityContainer. Now this *only* returns all instances if they have been registered by name, so I had to change one line of my code in the Global.asax.cs from:

container.RegisterType<IViewEngine, TestViewEngine>();

to

container.RegisterType<IViewEngine, TestViewEngine>("test");

and it all worked and my new engine was invoked. Apparently this is known behaviour with Unity and may be changed in future versions, but for now, this is how it works.

Note: There are a few other ways of registering custom view engines and also associating file extensions with a particular view engine. This is just one way of doing it.

Fujitsu T900 and Fingerprint Sensor Problems

Not so long ago, I bought a Fujitsu T900 Notebook computer from TegaTech (many thanks to the great service and help I received from Hugo Ortega who runs it).

Anyway, I bought a fairly stock system with 4Gb memory and a 320Gb 5400 rpm HDD. Later I updated to 8Gb memory and a 128Gb SSD with the 320Gb HDD as my secondary drive. This of course meant a full rebuild of Windows 7 and associated drivers and applications.

The rebuild went pretty smoothly but it soon became apparent that some things were not working. One of the most annoying was the fingerprint sensor. I had installed the drivers from the Fujitsu site a few times over.

I saw the ‘Authentic’ device in the Biometric section in Windows Device Manager, and when I went to the ‘Biometric Devices’ in control panel it had a simple message saying:

There were no Biometric devices found on this computer. Try installing some drivers ..” or some such thing. After much hunting around, removing the device, re-installing etc… I have finally got it working and thought I would post how I did it here for others if interested, but also for myself so I don't have to remember what I did.

Its pretty simple though so here goes:

1. Go Windows Device Manager via Control Panel and delete/uninstall the device from the Biometric devices Section.
image

2. Don't reboot! I don't know why but when I rebooted after uninstalling it and tried this it didn’t work.

3. Right click on the very top node and select ‘Scan for Hardware Changes’
image

Windows will then detect the device, and search windows update for the drivers. After about 5 minutes it should find the driver and install it.

And that's it. Simple enough but all the installing of drivers from the Fujitsu site didn’t seem to do anything. Perhaps this acted as part of the step for resolution but it didn’t seem to make much different.

At any rate, I am back to logging into windows using my fingerprint.

Making WCF Output a single WSDL file for interop purposes.

By default, when WCF emits a WSDL definition for your services, it can often contain many links to others related schemas that need to be imported. For the most part, this is fine. WCF clients understand this type of schema without issue, and it conforms to the requisite standards as far as WSDL definitions go.

However, some non Microsoft stacks will only work with a single WSDL file and require that all definitions for the service(s) (port types, messages, operation etc…) are contained within that single file. In other words, no external imports are supported. Some Java clients (to my working knowledge) have this limitation. This obviously presents a problem when trying to create services exposed for consumption and interop by these clients.

Note: You can download the full source code for this sample from here

To illustrate this point, lets say we have a simple service that looks like:

Service Contract

public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(DataFault))]
    string GetData(DataModel1 model);

    [OperationContract]
    [FaultContract(typeof(DataFault))]
    string GetMoreData(DataModel2 model);
}

Service Implementation/Behaviour

public class Service1 : IService1
{
    public string GetData(DataModel1 model)
    {
        return string.Format("Some Field was: {0} and another field was {1}", model.SomeField,model.AnotherField);
    }
    public string GetMoreData(DataModel2 model)
    {
        return string.Format("Name: {0}, age: {1}", model.Name, model.Age);
    }
}

Configuration File

<system.serviceModel>
<services>
  <service name="SingleWSDL_WcfService.Service1" behaviorConfiguration="SingleWSDL_WcfService.Service1Behavior">
<!-- ...std/default data omitted for brevity..... -->
    <endpoint address ="" binding="wsHttpBinding" contract="SingleWSDL_WcfService.IService1" >
          .......
 </services>
      <behaviors>
      <serviceBehaviors>
        <behavior name="SingleWSDL_WcfService.Service1Behavior">
             ........
        </behavior>
      </serviceBehaviors>
    </behaviors>

</system.serviceModel>

When WCF is asked to produce a WSDL for this service, it will produce a file that looks something like this (note: some sections omitted for brevity):

 <?xml version="1.0" encoding="utf-8" ?> 
- <wsdl:definitions name="Service1" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"     ...... namespace definitions omitted for brevity
+ &lt;wsp:Policy wsu:Id="WSHttpBinding_IService1_policy">
      ... multiple policy items omitted for brevity
  </wsp:Policy>
- <wsdl:types>
- <xsd:schema targetNamespace="http://tempuri.org/Imports">
  <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd0" namespace="http://tempuri.org/" /> 
  <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd3" namespace="Http://SingleWSDL/Fault" /> 
  <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/" /> 
  <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd2" namespace="http://SingleWSDL/Model1" /> 
  <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd4" namespace="http://SingleWSDL/Model2" /> 
  </xsd:schema>
  </wsdl:types>
+ <wsdl:message name="IService1_GetData_InputMessage">
      ....
  </wsdl:message>
- <wsdl:operation name="GetData">
     .....
  </wsdl:operation>
- <wsdl:service name="Service1">
     .......
  </wsdl:service>
  </wsdl:definitions>

The above snippet from the WSDL shows the external links and references that are generated by WCF for a relatively simple service. Note the xsd:import statements that reference external XSD definitions which are also generated by WCF.

In order to get WCF to produce a single WSDL file, we first need to follow some good practices when it comes to WCF service definitions.

Step 1: Define a namespace for your service contract.

[ServiceContract(Namespace="http://SingleWSDL/Service1")]
public interface IService1
{
       ......
}

Normally you would not use a literal string and may instead define a constant to use in your own application for the namespace.

When this is applied and we generate the WSDL, we get the following statement inserted into the document:

  <wsdl:import namespace="http://SingleWSDL/Service1" location="http://localhost:2370/HostingSite/Service-default.svc?wsdl=wsdl0" /> 

All the previous imports have gone. If we follow this link, we will see that the XSD imports are now in this external WSDL file. Not really any benefit for our purposes.

Step 2: Define a namespace for your service behaviour

[ServiceBehavior(Namespace = "http://SingleWSDL/Service1")]
public class Service1 : IService1
{
      ......
}

As you can see, the namespace of the service behaviour should be the same as the service contract interface to which it implements. Failure to do these tasks will cause WCF to emit its default http://tempuri.org namespace all over the place and cause WCF to still generate import statements. This is also true if the namespace of the contract and behaviour differ. If you define one and not the other, defaults kick in, and you’ll find extra imports generated.

While each of the previous 2 steps wont cause any less import statements to be generated, you will notice that namespace definitions within the WSDL have identical, well defined names.

Step 3: Define a binding namespace

In the configuration file, modify the endpoint configuration line item to iunclude a bindingNamespace attribute which is the same as that defined on the service behaviour and service contract

<endpoint 
    address="" 
    binding="wsHttpBinding" 
    contract="SingleWSDL_WcfService.IService1" 
    bindingNamespace="http://SingleWSDL/Service1">

However, this does not completely solve the issue. What this will do is remove the WSDL import statements like this one:

<wsdl:import namespace="http://SingleWSDL/Service1" 
location="http://localhost:2370/HostingSite/Service-default.svc?wsdl" /> 

from the generated WSDL.

Finally…. the magic….

Step 4: Use a custom endpoint behaviour to read in external imports and include in the main WSDL output.

In order to force WCF to output a single WSDL with all the required definitions, we need to define a custom WSDL Export extension that can be applied to any endpoints. This requires implementing the IWsdlExportExtension and IEndpointBehavior interfaces and then reading in any imported schemas, and adding that output to the main, flattened WSDL to be output. Sounds like fun right…..? Hmmm well maybe not.

This step sounds a little hairy, but its actually quite easy thanks to some kind individuals who have already done this for us.

As far as I know, there are 2 available implementations that we can easily use to perform the import and “WSDL flattening”.  WCFExtras which is on codeplex and FlatWsdl by Thinktecture. Both implementations actually do exactly the same thing with the imports and provide an endpoint behaviour, however FlatWsdl does a little more work for us by providing a ServiceHostFactory that we can use which automatically attaches the requisite behaviour to our endpoints for us.

To use this in an IIS hosted service, we can modify the .SVC file to specify this ne factory to use like so:

<%@ ServiceHost Language="C#" 
          Debug="true" 
          Service="SingleWSDL_WcfService.Service1" 
          Factory="Thinktecture.ServiceModel.Extensions.Description.FlatWsdlServiceHostFactory"  %>

Within a service application or another form of executable such as a console app, we can simply create an instance of the custom service host and open it as we normally would as shown here:

FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1));
host.Open();

And we are done. WCF will now generate one single WSDL file that contains all he WSDL imports and data/XSD imports.

You can download the full source code for this sample from here

Hope this has helped you.

Note: Please note that I have not extensively tested this in a number of different scenarios so no guarantees there.

Sydney Architecture User Group – WPF Architecture

Bit short notice for a blog post but eminent WPF expert Paul Stovell will be presenting on WPF Architecture at the Sydney Architecture User Group on thursday 25th February. (Full details here)

Here is the abstract:

.NET 4.0 will mark the fourth release of Windows Presentation Foundation, and the take up continues to rise as the platform matures. For architects, such a new technology means a new set of patterns, approaches and trade-offs that we need to understand when designing solutions. In this session, Paul will lead you on a guided tour of the WPF client application problem space. We will look at patterns for presentation, composition, navigation, and communication needs, as well as resource management, localization, and performance. We will also look at strategies for enforcing UI standards, maximising code leverage, and handling cross-cutting concerns. Bring questions!

Location and specific details are:

Title: Architecting solutions with Windows Presentation Foundation
Date/Time:Thursday 25/02/2010 06:00 PM
Where:Grace Hotel , Kiralee or Pinaroo Function Room77 York st,Sydney,NSW. 2000

 

Hope to see you there!

.Net Performance Testing and Optimisation – Free eBook

This blog has been super quiet lately. This is mainly because I have been hard at work writing a book around .Net Performance Testing and optimisation. Well, I am happy to say that part 1 of this book is available as a free download from here.

The full book will follow shortly and will contain concrete examples of popular performance issues in .Net applications, what to watch out for, and how to mitigate them. Additionally, you’ll get performance tips for Internet Information Server, web apps, SQL, caching strategies and a whole lot more.

In part 1, you will learn how to setup a performance test rig, how it works, how to record tests, replay them, what metrics to collect, and how to analyse them.

In addition, you will find out how to automate all this. Finally, you will get insight into profiling an application to improve performance. This is the one stop shop for performance testing and optimisation on the .Net platform.

Since its free, download it now!

iPhone Apps using Microsoft .NET

My good friend Wally McClure has written a short eBook on “Building iPhone and iPod touch Applications for the .NET/C# Developer with MonoTouch”.

You can check it out here

Given that iPhone is a very popular phone and that some of the development barrier for Microsofties like me is no .Net language support (Objective-C being the native development language), this can now be overcome with the help of Wally’s eBook.

Its small and concise with topics covering class library support, deployment and debugging. I encourage you to check it out.

Sydney Architecture User Group – Next Meeting: Why Windows Azure is not just Generic Brand Web Hosting

The Sydney Architecture User Group is having its second meeting this month on Thursday, 26th November. Full details can be found on our new (but very simple) website located here ( http://thesaug.org ). You can subscribe to the monthly email and also indicate your intention to come by selecting the RSVP option (which would be really nice if you did :-) )

Here is what the next Sydney Architecture meeting has in store. Hope to see you there.

Why Windows Azure is not just Generic Brand Web Hosting

Presenter Nick Randolph
Date/Time: Thursday 26/11/2009 06:00 PM
Where: Grace Hotel , Function Room 77 York st Sydney,NSW. 2000

Abstract

If you take only a glimpse at the offerings on the Windows Azure platform it may just appear to be a form of generic/home brand web hosting from Microsoft. However you’d be sorely mistaken as the platform is significantly different from not only traditional web hosting offerings but also from its competitors in the cloud computing space. In this session we will cover the unique offerings of cloud computing before looking at each of the components of the Windows Azure platform. Cloud computing is new, hot and sexy, but does that mean it’s right for you? Make sure you’re ready to interact and discuss the relative merits of building on the cloud.

Presenter Bio

Nick currently runs Built To Roam (http://www.builttoroam.com) which focuses on building rich mobile applications. Previously Nick was co-founder and Development Manager for nsquared solutions where he lead a team of developers to build inspirational software using next wave technology. Prior to nsquared, Nick was the lead developer at Intilecta Corporation where he was integrally involved in designing and building their application framework.

Sample chapter from upcoming book

There is a sample chapter from my upcoming book on all things performance related within the Microsoft platform. Specifically, the book will be about performance testing, profiling and optimisation for web and desktop applications developed using Microsoft.NET.

This sample chapter is just a teaser and the book itself goes into great detail about how to setup a performance test rig using Visual Studio, how to record, manage and analyse performance metrics, and what you can change to make your apps fly.

Anyways, the sample chapter is located here.

( http://www.simple-talk.com/dotnet/performance/understanding-performance-profiling-targets/ )

Hope you like it.

SAUG – Sydney Architecture User Group

The first meeting of the Sydney Architecture User Group is going to be held on Thursday, October 22nd, 2009, form 6.00pm to 8.00pm, at the Grace Hotel, 77 York st, Sydney. (Link to map) It will be housed in one of the very nice function rooms they have. Food and drink will be provided. Omar Besiso and myself will be hosting the event, with all funding and sponsorship graciously provided by our company Datacom.

We intend on having a proper site to provide RSS feeds, email subscription and the like, but until we get better organised, we have a facebook page at : http://www.facebook.com/event.php?eid=173036810551 or you can contact myself directly on paul.glavich AT datacom.com.au or you can contact Omar on omar.besiso AT datacom.com.au

Note: If you do intend on coming along, it would be appreciated if you could RSVP via our facebook page, or contact me directly at paul.glavich AT datacom.com.au so we can order to right amounts of food

The goal of the group will obviously be to discuss architecture related matters, but we are going to try and obtain a diverse range of speakers to cover all aspects of architecture. From application architecture, infrastructure, process, and although I am a Microsoft advocate, there is no intent to solely focus on Microsoft related technologies. We will try and cover the whole landscape of enterprise and solution architecture from a variety of angles.

Our first meeting will be a little introduction to the group itself, and then straight onto a presentation by Richard Banks. Details below:

Title:  Architecture in the Small

No matter how good your design or how well the big pieces of your architecture fit together it's the little things that really count.  The little things are the things that can take your vision of beauty and either make it a reality or turn it into a thing of nightmares. Richard will talk about what these little things are, the impact they have and, most importantly, what to do about them.

Bio: Richard Banks is a Principal Consultant with Readify, with a history that includes building ERP, HR, point of sale and student administration systems as well as being the CIO/CTO for a listed company.  He is a Certified Scrum Practitioner, runs the Sydney and Virtual Alt.Net user groups and has spoken at both Tech.Ed and a number of other user groups around the state.  His blog can be found at http://richardsbraindump.blogspot.com

Further meetings will see a format of a short half hour presentation, followed by a longer presentation typically of an hour. We have some interesting speakers lined up for future meetings and if you are interested in presenting at the group, I would love to hear from you.

We look forward to seeing you there!

ASP.NET v4 Presentation Deck and Demo’s

My ASP.NET v4 New Features overview presentation that I delivered at Sydney Deep .Net User Group (http://sdnug.org ) is available for download here (http://sdnug.org/presentations/200910.zip).

Note: If the above link returns a 404 error, please try here instead.

It covers almost every single new feature that will be covered in ASP.NET v4 in the next release With some demo’s showing off the permanent redirect feature, a bunch of templating demo’s, new client ID functionality and the new chart control.

Hope you enjoy it.

2 TechEd Interviews are live

Its been a long time since I wrote a blog post but I have been a very busy boy.

This week I have been at TechEd Australia on the sunny Gold Coast in Queensland. I have been keeping a pretty low profile this year but I did participate in 2 interviews that are now available for viewing or download from the Microsoft online site.

The first one is an interview with Omar Besiso, friend, colleague and Enterprise Architect at Datacom on the topic of Building Enterprise Software. You can grab it from here.

The second is an interview with Damian Edwards and Tatham Oddie on the topic of ASP.NET WebForms vs ASP.NET MVC framework. You can access it here.

Hopefully you find them valuable, or at the very least, somewhat entertaining.

Silverlight 3 and WCF Faults

On  a previous project that utilised WCF and Silverlight 2, I began implementing an error handling strategy that was going to rely on certain FaultExceptions being propagated to the Silverlight client. Well it turned out that Silverlight 2 does not support FaultExceptions so that was not going to fly and a custom solution was built.

Well Silverlight 3 does change this to some degree. Silverlight 3 now supports to the notion of Fault Contracts and FaultExceptions. In your Silverlight client code, if I have a WCF service called ThrowExceptionMethod (which as you may have guessed throws a FaultException) you can do something like this:

First wire up the service call:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    TestRef.TestServiceClient client = new TestSilverlightApplication3.TestRef.TestServiceClient();
    client.ThrowExceptionMethodCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_ThrowExceptionMethodCompleted);
    client.ThrowExceptionMethodAsync();
}

Then handle any error situation in the completed event:

void client_ThrowExceptionMethodCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    if (e.Error == null)
        MessageBox.Show("Call sucessfull");
    else
    {
        string msg;
        FaultException<ExceptionDetail> fex = e.Error as FaultException<ExceptionDetail>;
        if (fex != null)
            msg = string.Format("Fault Exception recevied. Reason: {0}, Message: {1}", fex.Reason, e.Error.Message);
        else
            msg = string.Format("Error recevied of type: {0}, Message: {1}",e.Error.GetType(),e.Error.Message);
        MessageBox.Show(msg);
    }
}

Here you can see that we test the ‘e.Error’ property to see if its an exception of type FaultException, otherwise the error will flow through generally as a CommunicationException as per normal WCF behaviour.

That all sounds easy, however you still need to tell the WCF service (or more specifically WCF itself) to return the fault using a HTTP status code of 200 (OK) instead of a HTTP status code of 500 (server error) which is the default. If you don’t do this, then the error will always come through as a CommunicationException .

You need a little bit of code and configuration for this. First you need to define a custom behaviour like so:

public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
    {        
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
        }

        public class SilverlightFaultMessageInspector : IDispatchMessageInspector
        {
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
                if (reply.IsFault)
                {
                    HttpResponseMessageProperty property = new HttpResponseMessageProperty();

                    // Here the response code is changed to 200.
                    property.StatusCode = System.Net.HttpStatusCode.OK;
                    reply.Properties[HttpResponseMessageProperty.Name] = property;
                }
            }
            
            public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
            {
                // Do nothing to the incoming message.
                return null;
            }
        }

        // The following methods are stubs and not relevant. 
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }
        public void Validate(ServiceEndpoint endpoint)
        {
        }
        public override System.Type BehaviorType
        {
            get { return typeof(SilverlightFaultBehavior); }
        }
        protected override object CreateBehavior()
        {
            return new SilverlightFaultBehavior();
        }
    }

Then some config:

<system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name=”silverlightFaults” 
             type=”Microsoft.Silverlight.Samples.SilverlightFaultBehavior, 
             SilverlightFaultBehavior, 
             Version=1.0.0.0, 
             Culture=neutral, 
             PublicKeyToken=null/>
      </behaviorExtensions>
    </extensions>
    <behaviors>
        <endpointBehaviors>
          <behavior name=”SilverlightFaultBehavior”>
            <silverlightFaults/>
          </behavior>
        </endpointBehaviors>
    </behaviors>
    <services>
        <service name=”Calculator.Web.Service”>
            <endpoint address=”” 
                      binding=”basicHttpBinding” 
                      contract=”Calculator.Web.Service” 
                      behaviorConfiguration=”SilverlightFaultBehavior” />
</service>
  </services>
</system.serviceModel> 

So, its still not quite there yet, but its better. It would be nice if this status code behaviour were part of the default Silverlight service template and that it was a provided behaviour, rather than a roll your own custom one.

Note: The custom behaviour, as well as more information on this subject, can and was taken from this article here.

Getting better performance in web apps with a few lines of script

We had a situation where a web application was utilising near 100% of CPU all the time under light load and it was proving very hard to reduce this significantly through code optimisation. We were performance testing and profiling, but only seeing marginal gains.

The infrastructure that was hosting the web application was as follows:

  • Virtual Server (Hosted via VMWare Server) running Windows Server 2003 64 bit
  • .Net 3.5
  • Dual Virtual CPUs
  • 2 Gb of memory.

Now I am not a big fan of virtualisation for hosting high performance web sites but we were stuck with this. At any rate, we had consistently high CPU utilisation for seemingly no real reason. Some of the most simple requests were generating high CPU usage.

After some investigation, and also the help of a friend and very smart dude, Scott Forsyth (who works for Orcsweb a high profile web hosting company) we decided to try setting Internet Information Services to 32 bit mode to see if any difference was seen.

To cut a long story short, we changed Internet Information Services to run in 32 bit mode. This simple switch, yielded significant lower CPU utilisation and in some case, almost cut the CPU utilisation in half!

Why would this be so? Well, it turns out there are a few reasons for this. Probably the primary reason is the fact the we get less information within the level 1 cache of the processor because of the increased structure size (pointers are bigger) within 64 bit systems. The same information in a 64 bit system occupies more memory than its 32 bit counterpart, therefore we can fit less into the processor cache. More information on this can be found here.

Its really easy to change IIS to 32 bit mode. The steps are:

  1. To enable 32 bit mode on IIS in 64 bit windows, at a command prompt type:
    cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1
  2. Once this is done, 32 bit mode is enabled but we need to ensure that the 32 bit DLL’s are used as IIS will still have the 64 bit DLL’s defined for the ISAPI handler. To do this, all we have to do is re-register ASP.NET. At a command prompt, simply type:
    %SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –i
  3. Finally, just make sure the status ASP.NET version 2.0.50727 (32-bit)  in the web services extension, within IIS, is set to allowed.
    (More information on this process can be found here http://support.microsoft.com/kb/894435)

And that’s it. A few lines of script, and we had effectively reduced CPU utilisation by somewhere in between 30% and 50%!

Conclusion

So my rule is this, If you are:

  • Running Windows server in 64 bit mode.
  • Running a standard .Net web application
  • Do not need a large memory address space (ie. over 4 gigabytes)
  • Have no special 64 bit optimisations

Then this change will yield immediate performance improvements in your application, and in some cases (dependent on what your application does), yield significant performance improvements.

FromTheGrey – Arts Site

Recently, I have been working on creating an arts based website called “FromTheGrey” at http://FromTheGrey.com

Its a site devoted to showcasing the pictures and artwork created by my wife Michele. Previously, Michele has been very reluctant to showcase these pieces, but I really like them, as do many others I know, so it took some time and coaxing to convince Michele to show them to the world.

However, I finally managed to do. As a result, “FromTheGrey” was born. Its a relatively simple site but I hope you like the art on the site and if so, would really appreciate you recommending it to others.

Its currently simple but functional, and will have many more pieces of work from Michele on there, as well as enhanced styling and functionality.

For now though, we would love your feedback which can be submitted via the Contact Form on the site.

For the technically inclined, it utilises ASP.NET 3.5 Webforms, jQuery 1.3.2, and jQuery plugins for the dialog box and gallery effects, Thickbox and Galleria respectively.

AjaxView – Javascript profiling

A little while ago, I posted about a tool called AjaxView to allow you to profile javascript code within your web applications.

Well, I was contacted by Adam who is working on this tool about its latest incarnation. It appears had a lot of work done to it, and now looks quite slick and is really nice to use. Previously, it was quite raw in use and also with the metrics its provides. Now, it acts very similar to one of my favourite profilers, Ants Profiler.

What does it do?

This tool injects profiling code into your javascript that enables it to analyse your javascript code and provide accurate metrics around all the operations being performed, including anonymous functions. It then provides these metrics to the Visual Studio performance tools for you to view in a very simple and familiar manner.

How do you use it?

You need to be using IIS7 in Integrated mode for this tool to work. A full set of install instructions is listed here along with the installation files. It installs pretty easily.

What do you get?

In short, you get detailed metrics on each page and javascript file in your site. When access a site with the AjaxView profile tools installed, all metric information is automatically being recorded. You can then access a web site on your local machine that is installed when AjaxView is installed. (Something like http://localhost/AjaxView).

When you do that, you can view the session profiles you have created (or the default one that is created for you on install). Something like this:

image

Select any of the files on the right which constitute all the files access by your web app (either a page or javascript file). Select the ‘Get profile data’ button and it launches Visual Studio and provides the profile metric data so that you can view it within Visual Studio. You end up getting access to detailed multiple views like the ones shown below:

image

image

image

All in all, a pretty useful tool to look at your Javascript performance. I recommend you take a look. Get it from here.