Code Camp 2008 – Wagga Wagga

April 24, 2008 at 9:49 am | Posted in Uncategorized | Leave a comment

Tomorrow I’m heading to Wagga for Code Camp 2008 with Grant and Steve. Grant has been kind enough to drive us up and Emma, Grant’s wife, has baked Anzac cookies.

Other friends heading up are Rory, John and Sean (where’s your blog???).

This will be my first time to Code Camp and the only other major conferences I have been to are Tech Ed and VSLive. I think its great that people are taking there own personal time and freely contributing to the community.

According to Yahoo, the weather forecast is looking fairly fine.

image

I’ve borrowed my girlfriend’s Apple MacBook Pro and tonight I will have a crack at setting it up with Vista and Visual Studio 2008.

Error when Behaviour Extension types are not fully qualified

April 23, 2008 at 12:58 pm | Posted in WCF | Leave a comment

Custom behaviour extensions are a great way to customise service behaviour such as implementing exception shielding as described here in Rory’s post  or message validation using the Microsoft Enterprise Library Validation Application block.

I recently implemented a custom WCF behaviour extension for shielding exceptions when I came across the following cryptic exception.

“An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.”

image

While the message was somewhat cryptic, it pointed me to the service behaviour were I realised I had specified the incorrect version on the type attribute.

Steps

1. Create new behaviour extension. My extension shielded and traced certain exceptions using the IErrorHandler.
2. Use SVC Configuration Editor to plug the extension in. It added the following configuration as expected.

<system.serviceModel>

  <extensions>

    <behaviorExtensions>

      <add name=ErrorHandlerBehavior

           type=Wcf.Demo.Service.ErrorHandlerElement, Wcf.Demo.Service,

                 Version=1.0.0.0, Culture=neutral, PublicKeyToken=null />

    </behaviorExtensions>

  </extensions>

</system.serviceModel>

3. Ran integration unit tests that passed.
4. The service build was integrated into TeamBuild which happen to automatically update my AssemblyInfo version files.
5. As soon as a TeamBuild kicked off and the assembly version changed, I received the cryptic error.
6. I realised I had an incorrect version configured in the web.config so I replaced the fully qualified type with:

<behaviorExtensions>

  <add name=ErrorHandlerBehavior

       type=Wcf.Demo.Service.ErrorHandlerElement, Wcf.Demo.Service />

</behaviorExtensions>

7. Ran tests and failed.

After attempting to diagnose the issue using tools such as Fusion Log Viewer, I checked Google (which I should have done first) and came across several posts also identifying the issue – including a closed and unresolved issue on Microsoft Connect. This is the second time round I have been to Microsoft Connect regarding a bug and it does not look like they will resolve this anytime soon.

A Way Forward

At this stage since there is no fix, a tedious workaround will have to be to get TeamBuild to modify the web.config and update the version number of the behaviour extension when applying a new version – which in my case is for every CI build triggered by a code checkin.

Links

Suppressing Code Analysis Rules

April 15, 2008 at 3:13 pm | Posted in Code Analysis, Visual Studio | Leave a comment

I’ve been using Code Analysis (FxCop) for a few months now and every now and then I come across a CA rule that I my solution violates. In 99% of situations, I comply to all the CA rules. In a previous post, I could not satisfy the CA1304 rule. Spelling checks is also another area where CA rules fail all the time.

The process that I use for checking in code to TFS ensures that Code Analysis is run before hand and that the project setting “Treat Warnings as Errors” is set to true. This means that the CA rules that I want to ignore fail my project build.

There are several ways to get around this:

1. Don’t use CA – not an option for me.
2. Don’t treat warnings as errors – not an option for me.
3. Apply a Suppression “In Source”- an option.
4. Apply a Suppression in “Project Suppression File (GlobalSuppression.cs) – an ideal option.

The last two options are my choice. Suppressing a CA rule places an attribute in code that informs FxCop to ignore the rule and therefore not raise a Warning or an Error.

Example Rule Failures

The following CA rules came up as Warnings for my solution. Both Suppress options are available. CA1304 gives two suppression options where as CA2210 (strong name key required) only allows a Project suppression because it is applied only at the assembly level. For a full list of the CA rules shipped with each version of VS/FxCop see this post.

image

In Source Suppression

When available, a CA rule can suppressed in the source code where the rule failed. Use the SuppressMessageAttribute to disable the CA rule.

[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo",
MessageId = "System.ServiceModel.FaultReason.#ctor(System.String)")]
public void ProvideFault(Exception error,
MessageVersion version,
ref Message fault)
{
// Return a 'ServiceFault' Fault Contract
ServiceFault faultDetail = new ServiceFault("An error occured");

// Construct FaultException with Fault Contract and FaultReason
FaultException<ServiceFault> faultException =
new FaultException<ServiceFault>(faultDetail,
new FaultReason("FaultReasonText"));
}

The benefit of applying the rule override in the source, is that code reviewers can easily see where the attribute has been placed. An additional file is is not required. The disadvantages is that you must apply the the attribute for every rule failure even if they are the same failures across multiple operations in the same code file and multiple code files. It also dirties the code with an messy attributes.

Project Suppressions

When selecting the Project Supressions File option, the SuppressMessageAttribute is placed in the projects GlobalSuppressions.cs file – Visual Studio will create one automatically. The attribute has overrides which allows you to target the exact place of the rule failure such as a class, method, field, namespace etc.

In my example, I have suppressed botth CA2210 and CA1304 rules in the GlobalSuppressions.cs. Visual Studio generates the code.

// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage(
"Microsoft.Design",
"CA2210:AssembliesShouldHaveValidStrongNames")]

[assembly:
SuppressMessage(
"Microsoft.Globalization", "CA1304:SpecifyCultureInfo",
MessageId = "System.ServiceModel.FaultReason.#ctor(System.String)",
Scope = "member",
Target = "Wcf.Demo.Service.ErrorHandler.#ProvideFault(System.Exception,System.ServiceModel.Channels.MessageVersion,System.ServiceModel.Channels.Message&)"
)]

Notice the the CA1304 suppression contains Scope and Target properties. This can be changed so that the suppression is scoped to a wider code base such a a namespace.

The benefits of project suppressions is cleaner code, less duplication of the SuppressMessage attribute and easier to remove if failure is fixed. It’s also easier to code review as all failure overrides are in the one place. The only disadvantage that I can see is that there is an additional code file.

My preference is to always use project suppressions. In the near future , I will discuss some of the processes of how I use Code Analysis.

Debugging WCF Clients and Services

April 15, 2008 at 2:09 pm | Posted in Visual Studio, WCF | 1 Comment

Debugging WCF services from the client through to the service is much easier when attaching the debugger to either the service or both the client and the service.

In the past, I have debugged services by firing up the client application and manually attaching to the WCF Service Host – which in this case is the ASP.NET worker process. This process is quite cumbersome.

Visual Studio has feature that supports attaching to multiple projects when starting up. 

In this example, I have a WCF service hosted in IIS which lives in the Wcf.Demo.IisServiceHost project. I also have a Wcf.Demo.TestHarness project which calls the service. I want to be able to attach the debugger to both the client and service by simply pressing F5.

Steps

1. Right click on the solution and select “Set StartUp Projects…“.

image

2. In the StartUp tab, select “Multiple startup projects” and select the projects you want to start up.

3. On the Action of the selected projects, select “Start” to start with the debugger attached.

image

If you now run (F5) the application, it will fire up both the Test Harness and a Internet browser to the service virtual directory. You can disable this.

4. Go to the Web project properties for the WCF web project and select “Don’t open a page“.

 image

Now when you hit F5, the test harness will launch and the debugger will be attached to both processes.

image

Handling Fault Contracts

April 15, 2008 at 1:35 pm | Posted in WCF | 1 Comment

Today I had an issue with catching Fault Contracts thrown from my WCF service. Every FaultException type raised by the service (excluding Communication Exceptions) were caught by the client as a FaultException instead of the expected FaultException<T>.

The issue was that I defined the FaultContractAttribute(type) on the operations in the Service Implementation class instead of on the Service Contract’s (Interface class) operations.

A service should always handle/shield exceptions and throw them as either a FaultException or a FaultException<T>. These types will not cause the channel to be faulted. I recommend defining Fault Contracts to convey information about the problem to client applications, and DO NOT provide the internal exception such as service stack traces. I’ll blog a post in the future on my recommendations service exception shielding patterns.

To catch Fault Contract types on the client, make sure that each Fault Contract type you require for that service operation, ensure that the FaultContractAttribute(Type) is specified.

Service code

Error Handler

The following code is implemented in the IErrorHandler class and is based on Rory’s post on Implementing IErrorHandler . In this example, all exceptions in my WCF service are changed to FaultException<ServiceFault>.

public void ProvideFault(Exception error,
                         MessageVersion version,
                         ref Message fault)
{
    // Return a 'ServiceFault' Fault Contract
    ServiceFault faultDetail = new ServiceFault("An error occured");

    // Construct FaultException with Fault Contract and FaultReason
    FaultException<ServiceFault> faultException = 
        new FaultException<ServiceFault>(faultDetail, 
        new FaultReason("FaultReasonText"));

    // Construct MessageFault to return.
    MessageFault messageFault = faultException.CreateMessageFault();

    fault = Message.CreateMessage(version, 
        messageFault, 
        faultException.Action);
}

Service Contract

Now this is where I went wrong. I did not decorate my service contract with the FaultContractAttribute. This attribute accepts a Type parameter which should be the type of the Fault Contract.

namespace DJ.Wcf.Demo.ServiceContracts

{

    [ServiceContract(Name = “DJ.Wcf.Demo.DemoService”, Namespace = “DJ.Wcf.Demo”)]

    public interface IDemoService

    {

        [OperationContract]

        [FaultContract(typeof(ServiceFault))]

        DemoData GetDemoData(Int32 demoId);

    }

}

Service Fault Contract code

Here is a defined Fault Contract used by the service and client. Being a Data Contract, it could contain a collection of error messages e.g. a collection of validation error messages for a set of fields that were incorrectly set on the service operation.

using System;
using System.Runtime.Serialization;

namespace Wcf.Demo.ServiceContracts
{
    [DataContract]
    public class ServiceFault
    {
        public ServiceFault(String message)
        {
            Message = message;
        }

        [DataMember]
        public String Message
        {
            get;
            set;
        }
    }
}

Client code

The service calling code below shows several catch statements. When the service passes back a ServiceFault, it will be caught in: catch (FaultException<ServiceFault>. All other FaultException and FaultException<T> types will be handled by: catch (FaultException fault) block.

Unhandled service exceptions will be raised and caught in:  catch (CommunicationException cex) which will cause the WCF channel to fault, thus forcing the client to create a new channel.

try
{
    using (ChannelFactory<IDemoService> channel = 
        new ChannelFactory<IDemoService>("DemoService"))
    {
        IDemoService service = channel.CreateChannel();
        channel.Open();

        return service.GetPerson(42);
    }
}
catch (FaultException<ServiceFault> serviceFault)
{
    MessageBox.Show(serviceFault.Message);
}
catch (FaultException fault)
{
    MessageBox.Show("Unknown Service Fault");
}
catch (TimeoutException tex)
{
    MessageBox.Show("Service call timed out. Please retry.");
}
catch (CommunicationException cex)
{
    MessageBox.Show("Unknown Communications exception occured.");
}

Controlling the serialized order of WCF Data Contract Members

April 12, 2008 at 1:08 am | Posted in WCF | Leave a comment

There are situations where you wish to specify the order of fields when they are serialized. I believe that a good designed service should not specify the ordering of fields nor should a service consuming application expect it..

In some applications, it is useful to know the order in which data from the various data members is sent or is expected to be received (such as the order in which data appears in the serialized XML). Sometimes it may be necessary to change this order…..

Recently, I started using ReSharper (now I’m hooked). I used it to reformat my code based on a style which alphabetically reordered all the properties in the data contracts. The changes were checked in, unit tested, integrated united tested and deployed to Test. The changes I made broke the client application as the application was relying on the serialised Xml to be in a certain order. In my opinion this is definately not service design.

I was told about the DataMemberAttribute.Order property by Rory and reluctantly added the Order property to every data contract member. This change still broke the client application. The reason was that the client application was using the XmlSerializer which does not change its behvaior with the new DataMember attributes.

The solution was to serialise a Data Contract using the DataContractSerializer. I still consider this to be a dirty solution because the ordering of the properties must always be the same, otherwise the consumer may break.

Data Contract

The following data contract lists fields in alphabetical order. The Order attribute forces the DataContractSerializer to output elements in the requested order.

    [DataContract]

    public class Person

    {

        [DataMember(Order = 2)]

        public Int32 Age { get; set; }

 

        [DataMember(Order = 0)]

        public String FirstName { get; set; }

 

        [DataMember(Order = 1)]

        public String LastName { get; set; }

 

    }

 

Serializing using the XmlSerializer

    Person person = new Person { Age = 25, FirstName = “Bob”, LastName = “Jane” };

    using (FileStream writer = new FileStream(“Person.xml”, FileMode.Create))

    {

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));

        xmlSerializer.Serialize(writer, person);

        writer.Close();

    }

The XML is written in the order the fields are defined in the class.

  <?xml version=1.0?>

  <Person xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

          xmlns:xsd=http://www.w3.org/2001/XMLSchema>

    <Age>25</Age>

    <LastName>Jane</LastName>

    <FirstName>Bob</FirstName>

  </Person> 

Serializing using the DataContractSerializer

    Person person = new Person { Age = 25, FirstName = “Bob”, LastName = “Jane” };

    using (FileStream writer = new FileStream(“Person.xml”, FileMode.Create))

    {

        DataContractSerializer contractSerializer = new DataContractSerializer(typeof (Person));

        contractSerializer.WriteObject(writer, person);

        writer.Close();

    }

 

The XML is written in the expected order defined by the Order property, even though the data contract defines in another order.

  <Person xmlns=http://schemas.datacontract.org/2004/07/Wcf.Demo.ServiceContracts

          xmlns:i=http://www.w3.org/2001/XMLSchema-instance>

    <FirstName>Bob</FirstName>

    <LastName>Jane</LastName>

    <Age>25</Age>

  </Person>

 

So if you require a specific order to be xml serialized, make sure you use the DataContractSerializer.

CA1304 – Must specify CultureInfo when using FaultReason

April 9, 2008 at 12:36 pm | Posted in Code Analysis, Visual Studio, WCF | 1 Comment

Today I came across the following issue when running Code Analysis over my WCF Error Shielding solution.

CAError

Because I have “Treat Warnings as Errors” enabled for all projects, Code Analysis fails.

Rory Primrose has recently blogged a very nice Error Handling solution which have implemented in a WCF service. As soon as I implemented the solution and specified to return a custom Fault Contract, WCF returned an exception indicating that the “FaultReason” was not provided. So I constructed a new FaultReason, and passed it in to the FaultException(Fault, FaultReason).

The FaultReason class contains a set of System.ServiceModel..::.FaultReasonText objects, each of which contains a description of the fault in a specific language.

Sample

public void ProvideFault(Exception error, MessageVersion version, ref Message fault)

{

// Return a ‘ServiceFault’ Fault Contract

ServiceFault faultDetail = new ServiceFault(“An error occured”);


// Construct FaultException with FaultContract and FaultReason

FaultException<ServiceFault> faultException =

new FaultException<ServiceFault>(faultDetail, new FaultReason(“FaultReasonText”));


MessageFault
messageFault = faultException.CreateMessageFault();

fault = Message.CreateMessage(version, messageFault, faultException.Action);

}

I compiled the code in Debug which was successful. I then switched on Code Analysis and it raised CA1304 : Microsoft.Globalization. The Code Analysis rule made sense to ensure I was using CultureInfo for the reason text.

However, the FaultReason does not provide any ‘public‘ constructor overrides to accept the CultureInfo. It does however provide an internal FaultReason(string text, CultureInfo cultureInfo) constructor.

FaultReason

After the help of Rory who confirmed with David Kean from the Code Analysis Team that this was a bug, I submitted feedback to Microsoft Connect.

You can keep track of this bug here: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=337431&wa=wsignin1.0

In the meantime, I have suppressed this CA rule in my GlobalSupressions.cs for the project.

Internode Naked ASDL2+ Plans

March 15, 2008 at 3:22 am | Posted in Uncategorized | Leave a comment

News Link: http://www.internode.on.net/news/2008/03/78.php

Internode have beaten TPG to the market with ADSL/ADSL2+ broadband plans that do not require a third party line rental account such as Telstra. On average, Internode state that there is about a $20 saving per month.

Through a network agreement with Optus Wholesale, Internode will offer Naked ADSL2+ from $59.95 a month including a NodePhone1* telephone service. Since customers can save money by no longer paying for a third party phone line rental fee (typically $30 per month), this prices the Naked ADSL2+ service at a nett cost of as little as $29.95 per month – or less, if low cost call charges are included.

There is an setup cost of $149 and then you can say goodbye to your analogue line. But if you require fax or back-to-base security monitoring, then you will still need a standard phone line connection.

There are cheaper options such as going with TPG value plans and a budget Telstra line connection, however Internode are known to provide one of the highest quality broadband services in Australia.

Supported Exchanges: https://secure.internode.on.net/webtools/dsl-coverage-table?carrier=Optus

image

Google releases "official" Outlook Sync

March 10, 2008 at 4:40 am | Posted in Uncategorized | Leave a comment

I have been using Google Calendar for some time now as I can:

  • Access it on any PC
  • See multiple calendars at a time (colour coded)
  • Share Calendars
  • Send out invites
  • Receive notifications on events via SMS and/or Email.

I still prefer to use Microsoft Outlook 2007 and have wanted to sync my Outlook and Google calendars together. I have used several custom sync tools that have been slow and buggy.

Google have now officially released a sync tool. 🙂

You can download the FREE software from here.

image

Outlook Links & Firefox

November 12, 2007 at 11:15 am | Posted in Uncategorized | Leave a comment

For the past few months after upgrading to a newer version of FireFox 2.x, every time I click on a link in Outlook I get an error box. I was also having the same problem at work with a Windows XP Pro / Outlook 2003 setup. I finally decided to look into it and fix the problem.

It was harder to fix the problem in Vista than in Windows XP.

Vista

In Vista, they have removed (or hidden) where you customise File Type extensions so you must create a registry file or use RegEdit to add a key.

  1. Using notepad create a reg file (ending in .reg)
  2. Paste the following into the file:

    Windows Registry Editor Version 5.00

    [HKEY_CLASSES_ROOT\FirefoxURL\shell\open\ddeexec]
    @=””

  3. Run the reg file and restart Outlook.

Windows XP

Windows XP allows you to customise the File Type extensions from Explorer.

  1. Open Windows Explorer (Not IE)
  2. Click on Tools | Options | FileTypes
  3. Find the extensions that are marked (NONE) and start with URL: HyperText
  4. Click Advanced
  5. Edit the Open action and clear out text in the DDE Message field.
  6. Apply changes.

Thanks to Dean Lisenby and Dosboy’s Bits and Bytes.

Next Page »

Create a free website or blog at WordPress.com.
Entries and comments feeds.