Attaching the Debugger only in Debug

by Alex Meyer-Gleaves 16 June 2010 - 1:41 AM

I noticed an article on the Infinite Codex blog that demonstrates how to debug CLR Stored Procedures. The example uses a #if preprocessor directive to compile the debugging code only if the DEBUG symbol is defined. Personally, I find using the #if directive makes your code look rather ugly, and accidentally including code inside the directive that you did not intend to becomes a real possibility. My preferred solution is to use the ConditionalAttribute to refactor such code out into a separate method.

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated withConditionalAttribute is defined.

Using this approach you can create a helper class that includes methods that should only be called when the DEBUG symbol is defined. When you compile with the RELEASE symbol defined all calls to the methods will simply be excluded from the generated MSIL.

public static class Debugging
{
    [Conditional("DEBUG")]
    public static void Break()
    {
        Debugger.Break();
    }
}

If you run the code below in Debug mode with the debugger attached, a breakpoint will occur immediately after the first Console.WriteLine method call.

class Program
{
    static void Main()
    {
        Console.WriteLine("Before the Debugging.Break() method.");
        Debugging.Break();
        Console.WriteLine("After the Debugging.Break() method.");
        Console.ReadLine();
    }
}

When the debugger is not attached and you compiled in Debug mode, the Visual Studio Just-In-Time Debugger dialog is presented for you to selected a debugger to attach with.

Visual Studio Just-In-Time Debugger Dialog

If you run in Release mode no breakpoint will be hit when the debugger is attached, and the Visual Studio Just-In-Time Debugger dialog will not be presented when you run without the debugger attached.

Tags: ,

Development Tools | Microsoft .NET

Fault Contract support in WSCF.blue

by Alex Meyer-Gleaves 31 May 2010 - 12:23 AM

Adding support for fault contracts to WSCF.blue has been on my TODO list for quite a while now. It was left behind when the port to WCF was done because ASMX did not have proper support for fault contracts so it was never actually part of WSCF.classic. Back in the old ASMX days you had to manually set the Detail property in the SoapException yourself and then add the fault details to the WSDL by hand.

In WCF your fault messages are declared on your operation using the FaultContractAttribute. When using WSCF.blue you could manually add the fault details to your WSDL and the appropriate FaultContractAttribute would be added to the generated service interface code. The problem was that if you edited your WSDL in the wizard the manually added fault details would be lost. Introducing a manual step like that into your process is something that we all want to avoid. Well, you no longer need to worry about that, because I have now added support for fault contracts to WSCF.blue.

Defining fault messages in your WSDL can be a little different to defining your input and output messages. For example, you can have multiple fault messages for a single operation and the same fault message is often reused for different operations. I decided that the message mapping page of the WSDL Wizard would be a reasonable place to put the configuration for your fault contract.

When you select an operation in the tree control a link label is displayed in the properties pane. Clicking the link will add a new fault message to the operation.

Operation Properties

When you select the fault message in the tree control you can then select a type from your schema to be used as the message body. You must provide a name for the message and that name must be unique to the operation. It does not have to be unique to the entire contract though. This means that you can reuse the same message name for a different operation and only a single message will be added to the WSDL. There is also a link label that allows you to remove the fault message if required.

Fault Message Properties

Lets use the fault message being configured in the screen capture above as an example of how this fits together in regards to the XSD and WSDL. The type for the fault in the XSD is called customFault and is an explicitly named complexType.

<xs:complexType name="customFault">
  <xs:sequence>
    <xs:element name="errorCode" type="xs:string"/>
    <xs:element name="message" type="xs:string"/>
    <xs:element maxOccurs="unbounded" minOccurs="0" name="messages" type="xs:string" />
  </xs:sequence>
</xs:complexType>

The message is then defined as an element with the type set to the customFault type. Do not create your fault type as an anonymous type definition directly under the element for the message. Doing so will result in an error about a missing data type during code generation.

<xs:element name="customFault" type="import:customFault" />

When the type and message schemas are run through the WSDL Wizard, and the fault message is added as shown in the screen capture above, the resulting WSDL will have a new message defined as follows.

<message name="customFaultMessage">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <part name="fault" element="import0:customFault" />
</message>

The portType will then have the fault defined for the operation.

<operation name="getRestaurants">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <input message="tns:getRestaurantsIn" />
  <output message="tns:getRestaurantsOut" />
  <fault name="customFaultMessage" message="tns:customFaultMessage" />
</operation>

The binding will also have the fault defined for the matching operation.

<operation name="getRestaurants">
  <soap:operation soapAction="http://www.thinktecture.com:getRestaurantsIn" style="document" />
  <input>
    <soap:body use="literal" />
  </input>
  <output>
    <soap:body use="literal" />
  </output>
  <fault name="customFaultMessage">
    <soap:fault use="literal" name="customFaultMessage" namespace="" />
  </fault>
</operation>

Now when you generate your service code a FaultContractAttribute will be applied to the method on your service interface that declares the operation. Note that the FaultContractAttribute specifies customFault as the type to be used for the message body.

[System.ServiceModel.OperationContractAttribute(Action="http://www.foo.com/:getRestaurantsIn", ReplyAction="*")]
[System.ServiceModel.FaultContractAttribute(typeof(customFault), Action="http://www.foo.com/:getRestaurantsIn", Name="customFault", Namespace="urn:thinktecture-com:demos:restaurantservice:messages:v1")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
getRestaurantsResponse getRestaurants(getRestaurantsRequest request);

There have been a number of requests for fault contract support on the CodePlex forum and I hope that you too will find this helpful. A new V1.0.9 update release is now available on CodePlex for download. Please put this new feature through its paces and report any problems you find on the discussion forum.

Tags: ,

Web Services | WSCF | Development Tools

WSCF.blue Roadmap

by Alex Meyer-Gleaves 6 May 2010 - 12:00 AM

image The WSCF.blue team has been discussing the features we should include in the next release. Benjy has done a great job summarising the current roadmap on his blog and is inviting feedback. You might feel that important features are missing, or perhaps that a particular feature is a bad idea, and would take the tool in the wrong direction. I decided that I would share what features are important to me, and put out for consideration and feedback some concerns I have with particular features. It is worth noting at this point that this is not an official roadmap, and is really just a summary of the ideas that we have been throwing around.

Having used WSCF.blue in a team environment, I would certainly put having the ability to permanently persist the settings for a web service in a way that makes them easy to share at the top of my list. Perhaps some sort of project structure that keeps your WDSL and XSD files along with your preferences altogether. There are a number of different options that can be applied when generating your web service code, and it is important that this step be repeated consistently, regardless of the developers familiarity with that particular web service. In regards to the actual options, I would also like to see support for WS-Addressing and fault contracts in the WSDL generation process. Adding these into the contract manually becomes another step that could be forgotten.

The issues noted about T4 templates are primarily concerns that I raised with the team. You get great flexibility with such a technology but it does come at a cost. These templates are not immediately approachable to all developers, especially when you are dealing with a complex model with many possible combinations. There are tools that make developing templates a more pleasant experience, but the mixing of static and dynamic content in such a manner still makes it fairly easy to introduce errors. I worry that it would become difficult to determine if a problem exists within the codebase or has been introduced in a customised template. Being an open source project there is only so much time that can be dedicated to support, so making things simple and reliable feels important. There is of course also the issue of upgrading templates, which forces users to migrate their customisations each time changes are made to the original.

Microsoft has released Feature Builder and it looks like it would be a very good fit for a tool like WSCF.blue. It certainly appears to be a considerable improvement over the Guidance Automation Toolkit (enough said). I would think that if we chose Feature Builder as the primary user experience, we would want to write an Ultimate Feature Extension that takes advantage of the modeling and visualization features that exist in Visual Studio 2010 Ultimate Edition. This is the point that you can start to do some really interesting things with Feature Builder. The problem is of course the requirement to have the most recent and expensive version of Visual Studio. My concern here is that we would make the tool inaccessible to a number of developers, and we really want as many people as possible to use the tool and embrace the contract-first approach.

There are a lot of great ideas on the roadmap and some really interesting technology choices to be made. I would be glad to hear your thoughts on any of these issues and the roadmap in general.

Tags: ,

Web Services | WSCF | Development Tools

Refactor to the NUnit Fluent API with ReSharper Code Patterns

by Alex Meyer-Gleaves 15 April 2010 - 2:19 AM

ReSharper Logo One of the new features in the recently released ReSharper 5 is Structural Search and Replace. This allows you to perform complex searches on your code, and then make equally complex replacements on the resulting matches. You can read the Introducing ReSharper 5.0: Structural Search and Replace post on the JetBrains blog to quickly bring yourself up to speed.

Solutions are commonly flooded with various code smells that are hard to eliminate right away. ReSharper 5 helps you get rid of them in existing code, but more than that, it allows you to create custom inspections to remove poor coding artifacts on a recurring basis.

Specifically, ReSharper helps configure custom, sharable code patterns, search for them, replace them, include them in code analysis, and even use quick-fixes for regular code maintenance! Building patterns and enforcing good practices has never been this easy. Corporate and team policies, custom frameworks, favorite open source libraries and tools — structured patterns are able to cover them all.

The coolest part of all this is being able to save the Structural Searches and include them alongside the built-in code inspections. NUnit is my preferred unit testing framework and I really like the fluent API it offers for making assertions. This seemed like the perfect opportunity to test out Structural Search by creating some code patterns that would find usages of the regular API and convert them to the new fluent API.

I basically wanted to find assertions that look this this.

object foo = new object();
object nullFoo = null;

Assert.AreEqual(1, 1);
Assert.AreNotEqual(1, 2);
Assert.AreNotSame(1, 2);
Assert.AreSame(foo, foo);
Assert.Contains(1, new List<int> {1, 2, 3});
Assert.False(false);
Assert.Greater(2, 1);
Assert.GreaterOrEqual(2, 1);
Assert.IsAssignableFrom(typeof(int), 1);
Assert.IsNotAssignableFrom(typeof(int), false);
Assert.IsEmpty(new List<int>());
Assert.IsFalse(false);
Assert.IsInstanceOf(typeof(int), 1);
Assert.IsNaN(double.NaN);
Assert.IsNotEmpty(new List<int> {1});
Assert.IsNotInstanceOf(typeof(int), false);
Assert.IsNotNull(foo);
Assert.IsNotNullOrEmpty("Foo");
Assert.IsNull(nullFoo);
Assert.IsNullOrEmpty(string.Empty);
Assert.IsTrue(true);
Assert.Less(1, 2);
Assert.LessOrEqual(1, 2);
Assert.NotNull(new object());
Assert.Null(nullFoo);
Assert.ReferenceEquals(foo, foo);
Assert.True(true);

And make them look like this instead.

object foo = new object();
object nullFoo = null;

Assert.That(1, Is.EqualTo(1));
Assert.That(2, Is.Not.EqualTo(1));
Assert.That(2, Is.Not.SameAs(1));
Assert.That(foo, Is.SameAs(foo));
Assert.That(new List<int> {1, 2, 3}, Contains.Item(1));
Assert.That(false, Is.False);
Assert.That(2, Is.GreaterThan(1));
Assert.That(2, Is.GreaterThanOrEqualTo(1));
Assert.That(1, Is.AssignableFrom<int>());
Assert.That(false, Is.Not.AssignableFrom<int>());
Assert.That(new List<int>(), Is.Empty);
Assert.That(false, Is.False);
Assert.That(1, Is.InstanceOf<int>());
Assert.That(double.NaN, Is.NaN);
Assert.That(new List<int> {1}, Is.Not.Empty);
Assert.That(false, Is.Not.InstanceOf<int>());
Assert.That(foo, Is.Not.Null);
Assert.That("Foo", Is.Not.Null.Or.Empty);
Assert.That(nullFoo, Is.Null);
Assert.That(string.Empty, Is.Null.Or.Empty);
Assert.That(true, Is.True);
Assert.That(1, Is.LessThan(2));
Assert.That(1, Is.LessThanOrEqualTo(2));
Assert.That(new object(), Is.Not.Null);
Assert.That(nullFoo, Is.Null);
Assert.That(foo, Is.SameAs(foo));
Assert.That(true, Is.True);

Nothing particularly difficult in this task other than a fair dose of pounding on the keyboard. After creating the first couple of patterns using the Pattern Catalogue dialog in Visual Studio, I exported the patterns to an XML file and continued my editing from there. Working directly with the XML in your favourite editor will certainly save you some time when making edits to your patterns in bulk. The end result was the list of code patterns below.

Pattern Catalogue

Now ReSharper will include these code patterns into its code inspections, and show the usual visual indicators for the Suggestion severity level.

Visual Indicators

JetBrains have given me yet another reason to love ReSharper. You can find an XML export of the code patterns attached.

NUnit Fluent API Code Patterns.xml (12.61 kb)

Tags: ,

Development Tools

.NET Reflector V6 Released

by Alex Meyer-Gleaves 16 February 2010 - 1:14 PM

Reflector Logo With this latest release of the recently acquired Reflector tool, Red Gate have provided both free and paid versions. The free version only has a couple of new features, the first of which was already available in the TestDriven.NET add-in for Visual Studio:

  • Jump straight to .NET Reflector from Visual Studio
  • Support for .NET 4 assemblies

Red Gate have decided to bundle a trial of the paid version along with the free one. Even though they are still releasing a free version, I find the forced bundling of the trial a little annoying. They are certainly trying to sell this as a good thing on their website:

image

The paid version, marketed as .NET Reflector Pro, is actually a Visual Studio add-in and offers some additional features:

  • Integrates the power of .NET Reflector into Visual Studio
  • Decompile third-party assemblies from within VS
  • Step through decompiled assemblies and use all the debugging techniques you would use on your own code

These certainly are very cool features, but ones that I would like to be given the option of trailing. Regardless, at the end of the day Reflector is still free, and still rocks!

Tags:

Development Tools

More than 1000 downloads for WSCF.blue V1

by Alex Meyer-Gleaves 5 January 2010 - 12:41 AM

On the last day of September in 2009 we released the first version of WSCF.blue on CodePlex. I was very pleased to see that there has now been more than 1000 downloads of the V1 release. Congratulations to the team and thank you to everyone who has downloaded WSCF.blue. It is great to see that interest in contract-fist development is still alive and well. Of course, Christian and Buddhike did a great job of spreading the word with their excellent MSDN article.

image

Now that everyone is back from holidays and feeling refreshed there is no doubt work will continue on the next version. We all have plenty of ideas for the features we would like to see, but what we would really like is feedback from the community on what you want. If you have ideas on what you would like to see in future versions of WSCF.blue please jump onto the forum and let us know.

Tags:

WSCF | Web Services | Development Tools

ReSharper 5.0 Beta available

by Alex Meyer-Gleaves 23 December 2009 - 12:24 PM

ReSharper JetBrains has provided developers with an early Christmas present releasing the ReSharper 5.0 Beta on Christmas Eve. It looks there are plenty of new features to take for a test drive.

ReSharper 5.0 Beta introduces a great web development feature set; code analysis extended with call tracking, value tracking, and foreach-to-LINQ transformations; project-level refactorings; and a lot more enjoyable features.

The Beta version will work with both Visual Studio 2010 and Visual Studio 2008, although according to this post from JetBrains there are a number of known issues causing problems with support for Visual Studio 2010 Beta 2.

However, keep in mind that Visual Studio 2010 Beta 2 has a number of known issues that in certain scenarios prevent ReSharper from working well. Don’t worry too much though: it doesn’t mean your Visual Studio crashes every time you press Alt+Enter! JetBrains and Microsoft engineers are aware of the problems and working together to solve them by the time Visual Studio 2010 goes RTM.

Head on over to the What's New in ReSharper 5.0 Beta page for a download link and more information on the new features.

Tags:

Development Tools

Free database goodness: LightSpeed Express and SQLite

by Alex Meyer-Gleaves 17 November 2009 - 11:24 PM

I have used VistaDB Express for many hobby projects in the past and found it to be simple and reliable. This blog is running on VistaDB Express and it has never given me any trouble. Unfortunately, with the release of VistaDB 4 there will no longer be a free edition available for any purpose. While this is very disappointing I can understand why they have taken this stance.

Sorry, we had to discontinue the free edition of VistaDB due to the support demands, and the number of companies who were using it for commercial purposes.  We have to put food on the table and feed our families just like anyone else, this was the free as in beer problem (it cost us a lot to build and support, but people used it to make money and not pay us).

When it comes to small hobbyist projects this is not the end of the world, as there are other free products available that will meet such needs. I made the jump over to SQLite, another very popular and free embedded database engine. The main reason I chose to use VistaDB Express over SQLite in the past, was the fact that it had a wider range of supported data types and good management tools provided out of the box. However, there is a free management tool for SQLite called SQLite Database Browser that does a good job, and when used with a decent ORM the reduced number of supported data types in SQLite is soon forgotten.

image I have been using LightSpeed Express from Mindscape as the ORM atop of both database engines, and I must say that I absolutely love it. This free edition is limited to creating a model with at most eight classes, which I have found to be enough when coding for fun. If you don’t need many entities in your model it is well worth using given the features it provides. To see how the LightSpeed feature set stacks up against other ORM technologies including LINQ to SQL and LINQ to Entities have a read of the comparison document on the Mindscape website. LINQ to LightSpeed is the standout feature that makes this framework a winner for me. It enables you to use LINQ against any of the databases that LightSpeed supports: SQL Server, Oracle, PostgreSQL, MySQL, SQLite, VistaDB, Firebird and Amazon SimpleDB.

LightSpeed has an editor for Visual Studio that allows you to build your model in a manner similar to that provided by LINQ to SQL and LINQ to Entities. You can even use the design time tools to create a new database from an existing one. This is exactly what I did when moving an existing project from VistaDB Express to SQLite.

The LightSpeed designer extends that portability to design time. By changing the connection string and data provider on a model, and choosing Update Database, you can rapidly create much of your schema on the new database, rather than having to manually translate the SQL CREATE scripts from one dialect to another.

Once you have a good ORM in place you tend not to worry so much about the underlying database engine, well at least when your requirements are simple and you have no desire to spend money. This was certainly the case for me with VistaDB Express and SQLite. It would be interesting to know how many other VistaDB Express users have switched to a completely different database engine for their home projects despite the low price of the entry level VistaDB 4 Lite version. Regardless, I can assure you that LightSpeed Express will make any database engine you choose easier to work with, and like any good ORM will allow you to more easily change it at a later point in time.

Tags: ,

Database | Development Tools

Comparison keyboard shortcuts for Pending Changes in TFS

by Alex Meyer-Gleaves 5 September 2009 - 1:01 AM

Logitech MX5500 One of the first things I configured in my Visual Studio environment when I starting using TFS was keyboard shortcuts to make comparing my pending changes easier. I find having to right-click on each item in the Pending Changes window and navigate through the context menu to perform a comparison quickly tests my patience. The drop down menu on the tool bar button is slightly faster but still not quick enough for my liking. I am always fastest when my hands don’t need to leave the keyboard.

I have configured keyboard shortcuts to compare my pending changes with the Latest, Workspace and Previous versions. Obviously the shortcuts only work when the option would normally appear enabled on the context menu. To configure these shortcuts select Options from the Tools menu in Visual Studio. In the Options dialog use the tree to drill into Environment and then to the Keyboard settings. Enter the command names below into the Show commands containing text box one at a time:

  • TeamFoundationContextMenus.SourceControlPendingChangesSourceFiles.Compare.TfsContextPendingCheckinsCompareWithLatestVersion
  • TeamFoundationContextMenus.SourceControlPendingChangesSourceFiles.Compare.TfsContextPendingCheckinsCompareWithWorkspaceVersion
  • TeamFoundationContextMenus.SourceControlPendingChangesSourceFiles.Compare.TfsContextPendingCheckinsCompareWithPreviousVersion

For each command enter your desired keyboard shortcut into the Press shortcut keys text box and click the Assign button. I have used the shortcut keys below, assigned to the commands in the same ordinal position above:

  • Ctrl+`
  • Ctrl+Shift+`
  • Ctrl+Alt+`

With this in place I can quickly fire up and navigate through my diffs in WinMerge using only my keyboard. No mucking about and no reaching for the mouse. Even a simple set of steps can become frustrating when you have to repeat them a large number of times. Save yourself all that clunky mouse based GUI interaction and embrace the power of the keyboard!

Tags: ,

Development Tools

ReSharper 4.5.1 Maintenance Release

by Alex Meyer-Gleaves 26 July 2009 - 12:22 AM

image JetBrains have made a 4.5.1 maintenance release of ReSharper available for download. It is a free upgrade from any 4.x version, and the Release Notes indicate that a large number of bugs have been addressed. Despite some issues I had with the Beta version I happily found the 4.5 release to be stable. I have been regularly testing the nightly builds and think that 4.5.1 will be a stable and reliable release.

A couple of highlights for me are that the default Naming Style rules have certainly been improved, with more options available for both private and non-private accessible members. Also, method names with an underscore are no longer considered erroneous, which was a problem for auto-generated event handlers in Visual Studio. It was also a problem if your unit test naming convention involves the use of underscores as a separator, like this one recommended by Roy Osherove.

Tags:

Development Tools

About the author

Alex Meyer-Gleaves I'm a Technical Architect living in Australia (that island like continent in the southern hemisphere). I love Microsoft .NET and C#. I hate early mornings, slow drivers and Lotus Notes.

Google Shared

 

Month List

Recent Posts

Recent Comments

Comment RSS

Links

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010