07 Oct 2009

Two new Visual Studio snippets

Blue Man Holding a Pencil and Drawing a Circle on a Blueprint Clipart Illustration I’ve been working on an interesting project recently and found that I needed two pieces of code a lot, so what better than wrapping them as snippets.

What are snippets?

Well if you start typing in VS you may see some options with a torn paper icon, if you select that and hit tab (or hit tab twice, once to select and once to invoke) it will write code for you! These are contained in .snippet files, which are just XML files in a specific location.

image 

To deploy these snippets copy them to your C# custom snippet’s folder which should be something like C:\Users\<Username>\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets

You can look at the end of this post for a sample of what the snippets create, but lets have a quick overview of them.

Snippet 1: StructC

Visual Studio already includes a snippet for creating a struct (which is also the snippet) however it is very bland:

image

StructC is a more complete implementation of a struct, mainly so it complies with fxCop requirements for a struct. So it includes:

  • GetHashCode method
  • Both Equals methods
  • The positive and negative equality operators (== and !=)
  • Lots of comments

which all in all runs in at 74 lines of code, rather than the three you got previously.

Warning - the GetHashCode uses reflection to figure out a unique hash code, but this may not be best for all scenarios. Please review prior to use.

Snippet 2: Dispose

If you are implementing a class that needs to inherit IDisposable you can use the the option in VS to implement the methods.

image

Once again from a fxCop point of view it is lacking since you just get the Dispose method. Now instead of doing that you can use the dispose snippet which produces 41 lines of code which has:

  • Region for the code - same as if you used the VS option
  • Properly implemented Dispose method which calls Dispose(bool) and GC.SuppressFinalize
  • A Dispose(bool) method for cleanup of managed and unmanaged objects
  • A private bool variable to make sure we do not call dispose multiple times.

StructC Sample

/// <summary></summary>
struct MyStruct
{
    //TODO: Add properties, fields, constructors etc...

    /// <summary>
    /// Returns a hash code for this instance.
    /// </summary>
    /// <returns>
    /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
    /// </returns>
    public override int GetHashCode()
    {
        int valueStorage = 0;
        object objectValue = null;
        foreach (PropertyInfo property in typeof(MyStruct).GetProperties())
        {
            objectValue = property.GetValue(this, null);
            if (objectValue != null)
            {
                valueStorage += objectValue.GetHashCode();
            }
        }

        return valueStorage;
    }

    /// <summary>
    /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
    /// </summary>
    /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
    /// <returns>
    ///     <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
    /// </returns>
    public override bool Equals(object obj)
    {
        if (!(obj is MyStruct))
            return false;

        return Equals((MyStruct)obj);
    }

    /// <summary>
    /// Equalses the specified other.
    /// </summary>
    /// <param name="other">The other.</param>
    /// <returns></returns>
    public bool Equals(MyStruct other)
    {
        //TODO: Implement check to compare two instances of MyStruct
        
        return true;
    }

    /// <summary>
    /// Implements the operator ==.
    /// </summary>
    /// <param name="first">The first.</param>
    /// <param name="second">The second.</param>
    /// <returns>The result of the operator.</returns>
    public static bool operator ==(MyStruct first, MyStruct second)
    {
        return first.Equals(second);
    }

    /// <summary>
    /// Implements the operator !=.
    /// </summary>
    /// <param name="first">The first.</param>
    /// <param name="second">The second.</param>
    /// <returns>The result of the operator.</returns>
    public static bool operator !=(MyStruct first, MyStruct second)
    {
        return !first.Equals(second);
    }
}                

Dispose Sample

#region IDisposable Members

/// <summary>
/// Internal variable which checks if Dispose has already been called
/// </summary>
private Boolean disposed;

/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
private void Dispose(Boolean disposing)
{
    if (disposed)
    {
        return;
    }

    if (disposing)
    {
        //TODO: Managed cleanup code here, while managed refs still valid
    }
    //TODO: Unmanaged cleanup code here

    disposed = true;
}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
    // Call the private Dispose(bool) helper and indicate 
    // that we are explicitly disposing
    this.Dispose(true);

    // Tell the garbage collector that the object doesn't require any
    // cleanup when collected since Dispose was called explicitly.
    GC.SuppressFinalize(this);
}

#endregion
04 Sep 2009

ASP.NET MVC Cheat Sheets

My latest batch of cheat sheets is out on DRP which are focused on ASP.NET MVC. So what is in this set:

ASP.NET MVC View Cheat Sheet

This focuses on the HTML Helpers, URL Helpers and so on that you would use within your views.

Slide1 

ASP.NET MVC Controller Cheat Sheet

This focuses on what you return from your controller and how to use them and it also includes a lot of information on the MVC specific attributes.

Slide2

ASP.NET MVC Framework Cheat Sheet

This focuses on the rest of MVC like routing, folder structure, execution pipeline etc… and some info on where you can get more info (is that meta info?).

 Slide3

ASP.NET MVC Proven Practises Cheat Sheet

This contains ten key learnings that every ASP.NET MVC developer should know - it also includes links to the experts in this field where you can get a ton more information on those key learning's.

 Slide4

What are the links in the poster?

Think before you data bind
    TinyURL: http://TinyURL.com/aspnetmvcpp1
    Full URL: http://www.codethinked.com/post/2009/01/08/ASPNET-MVC-Think-Before-You-Bind.aspx

Keep the controller thin
    TinyURL: http://tinyurl.com/aspnetmvcpp2
    Full URL: http://codebetter.com/blogs/ian_cooper/archive/2008/12/03/the-fat-controller.aspx

Create UrlHelper extensions
    TinyURL: http://tinyurl.com/aspnetmvcpp3
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#urlHelperRoute

Keep the controller HTTP free
    TinyURL: http://tinyurl.com/aspnetmvcpp4
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#httpContext

Use the OutputCache attribute
    TinyURL: http://tinyurl.com/aspnetmvcpp5
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#outputCache

Plan your routes
    TinyURL: http://tinyurl.com/aspnetmvcpp6
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/03/asp-net-mvc-best-practices-part-2.aspx#routing

Split your view into multiple view controls
    TinyURL: http://tinyurl.com/aspnetmvcpp7
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/03/asp-net-mvc-best-practices-part-2.aspx#userControl

Separation of Concerns (1)
    TinyURL: http://tinyurl.com/aspnetmvcpp8
    Full URL: http://blog.wekeroad.com/blog/asp-net-mvc-avoiding-tag-soup

Separation of Concerns (2)
    TinyURL: http://tinyurl.com/aspnetmvcpp9
    Full URL: http://en.wikipedia.org/wiki/Separation_of_concerns

The basics of security still apply
    TinyURL: http://tinyurl.com/aspnetmvcpp10
    Full URL: http://www.hanselman.com/blog/BackToBasicsTrustNothingAsUserInputComesFromAllOver.aspx

Decorate your actions with AcceptVerb
    TinyURL: http://tinyurl.com/aspnetmvcpp11
    Full URL: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practi...

08 May 2009

My Presentation @ Dev4Devs

If you are attending Dev4Devs on Saturday (or are here after the event) and you are looking for a copy of the slides and code you can get them below! If are looking for the ADO.NET Data Services cheat sheet I mentioned then you need to go here.

Code

The code here is also different from what I presented in the following ways:

  • There is a timer control in it - so if you add items to the DB while on the site, it updates and shows those changes within 5 seconds.
  • The layout is slightly bigger (bigger header) and has buttons (to make it look like an email client) - these were removed because it doesn’t work at 1024x768 (aka the projector resolution). So they back in their graphical beauty.
  • There is a feed button which links to a ATOM feed for the last 10 emails - something I mentioned you could do, well now you can see it.
  • There is a database creation script, but no data. You need to create your own data.
Slide Show
06 Apr 2009

VSTT Reference Guide

If you are looking for some serious guidance on Visual Studio test, then the Rangers have come to the rescue (again) with a lovely 83 page document on VSTT. Get it from CodePlex

It sounds like a contraction that 83 pages is a reference guide but from my use this morning of it (couldn’t of come out at a better time for me), it isn’t. It is not meant to be read from beginning to end, rather you can easily skip between parts because the material is presented in a Q&A format which is easy to manage.

What’s in it?

  • SETUP CONSIDERATIONS 9
  • WEB TEST CONSIDERATIONS 14
  • WEB SERVICE TEST CONSIDERATIONS 35
  • UNIT TEST CONSIDERATIONS 36
  • LOAD TEST CONSIDERATIONS 42
  • LOAD TEST RIG CONSIDERATION 56
  • PERFORMANCE DATA COLLECTION AND USAGE 66
  • LOAD TEST RESULTS STORE INFORMATION 73
  • TEST CUSTOMIZATION 76
  • ITEMS CHANGED OR FIXED IN VSTS 2008 SP1 77
  • GENERAL COMMANDS AND TRICKS (NOT VSTS SPECIFIC) 79
02 Apr 2009

How to convert a VS standard class library to a Workflow activity library

Introduction

image VS. image

If you are working in a workflow foundation project you may find you have created a class library (see image below) and want to put workflow activities into it but you may have issues with that because you didn’t create a Workflow activity library.

Issues

Some of the issues you may find are the add item menu doesn’t have the options you expect and the workflow designer interface doesn’t work.

image VS. image

Solution

To solve this you need to modify the class library project file very slightly. To do that simply open the file with a text editor such as Notepad or use the options in Visual Studio to unload and edit the project.

image

The first thing is to add a ProjectTypeGuids node to the base PropertyGroup node. To get there you need to navigate to the PropertyGroup node (it is under the Project node) without any Condition attributes. On my machine that is on line 3

image

Next add the following line in the node:

<ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Example: image

Next you need add a new project target into the Project node. You should already have one of these  around line 56

image

Right below that you need to add a new one (so you will have two), the line to add is:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.5\Workflow.Targets" />

Example: image

Now save the project file and re-open it in Visual Studio and the problems should be gone!

Troubleshooting

You may find that the designer is not working or you get errors when adding new activities still. In such a case it could be that you are missing the workflow foundation assemblies (System.Workflow.Activities; System.Workflow.ComponentModel; System.Workflow.Runtime):

image

Once you have those added everything should be working fine.

05 Feb 2009

Workflow Foundation Activity Template

WF has two two types of activities you can create, the easy one and the hard one. That’s not really their names (though it would be cool), the first (easy) is a composite activity. This is is the one that Visual Studio lets you create and is in effect just another sequential workflow which you build up and reuse.

image

However when you use them they just look like sequence activities. If you want something that looks like a “real” (read: what you get out of the box) activity to need to create the hard one which is call an activity (so clear a name, ain’t it). The smallest this can be is one class and the biggest it can be is five classes and they all basically have the same structure. So it’s weird that there is no easy way to build these, say a template. Well I have created one which sets up the base for an activity and lets you get going as quickly as possible.

Usage

To use it, select the normal Add -> New Project, and under Visual C#, My Templates will be the template called WF Activity! Some things that should become clear from that little sentence

  • You need Visual Studio 2008 (yeah, that wasn’t clear but I need to sneak it in somewhere).
  • It’s C# only
  • It creates a project for your new activity for ease of packaging purposes.
  • And for some reason if I put a space in the name, if crashes my Visual Studio - so um, that could just be me.

 

image

When you create it, it creates 4 files which all start with the name you choose (that will also be the name for your activity, so I don’t suggest putting activity in it) - For example mine was called ConsoleWriteLine so my files are:

  • ConsoleWriteLineActivity.cs
  • ConsoleWriteLineActivityDesigner.cs
  • ConsoleWriteLineActivityDesignerTheme.cs
  • ConsoleWriteLineActivityValidator.cs

image 

Special Features

I will come back to what they do but I thought I would point out that I have taken special care with the code so that if you run code analysis (fxcop) you get no issues with the code - you will get five for the project not being signed and com visibility stuff - and that StyleCop also reports no issues. I have also added in three TODO’s (if you use the VS task list)

image

  • The first one (Write Code) takes you to the Execute method in the {Project}Activity.cs file. This is what will run when your activity is executed.
  • The second one (Pick some nice colours) takes you to {Project}ActivityDesignerTheme.cs file where you can specify the start and end colours for the gradient. By default it’s dark to light blue.

image

  • The third one (Add validation) takes you to the Validate method in the {Project}ActivityValidator.cs file where you can add any design time validation you need. It even has a sample of how to add a validation failure message.

image

What do I need to add to use it?

Basically all you need to do to get up and running is

1) Add the properties you need to the {Project}Activity.cs file.

2) Add the code as indicated by the task item.

3) Compile and use.

Optionally you can change the colours, add validation, add an icon or change what is shown on the component. The changing of what is shown is controlled via the SetText method in {Project}ActivityDesigner.cs and it has been wired up so that it will respond to property changes. So you can actually have the text change if the properties change with very little code needed.

How do I deploy it?

To use it just dump the ZIP file in the Visual Studio 2008 > Templates> ProjectTemplates > Visual C# in your documents folder and restart Visual Studio!

image

Where can I get it?

 

Note: My hosting provider has something that corrupts zip files so it has been uploaded in 7-zip format which you will need to extract it.

Hopefully you get some productivity benefit from this component or it helps you learn how to write your own, and if it does please leave a comment here so I know (and get that warn fuzzy feeling I like so much).

30 Dec 2008

TFS Branching Guidance is Out

Very late notice from me (been sitting in my inbox for 2 weeks) but the TFS branching guidance is now out on CodePlex: http://dotnet.org.za/willy/archive/2008/12/20/vsts-branching-guidance-ii-a-great-guidance-release.aspx

Interesting it’s the 25th highest download on CodePlex at the moment too! Guess it shows that it isn’t just me and Ryan spending a lot of time trying to figure out the perfect strategy!

09 Dec 2008

Scott Hanselman - Last night at Microsoft

Being on the southern tip of the world and add the slowest bandwidth anywhere (confirmed by Scott himself) we seldom get the greats like Scott Hanselman out to talk to us, let alone for free, and when he is on holiday… but that is what the S.A. Developer community got last night and what a night it was. He spoke last night on MVC and I made some notes I thought I would share.

The first concept is that

  • ASP.NET > Web Forms
  • ASP.NET > MVC

It’s an interesting way of thinking that ASP.NET is not Web Forms, since it is normally that we use those two interchangeable. ASP.NET is a framework for building web applications, if we use web forms on that framework is a choice not a requirement. Web forms in itself is a lie, it tries to make us believe that the web is stateful… so that we get the RAD/VB6 experience for development. The problem is that like the Matrix, the lie constrains us. MVC is the anti-RAD in a way, it opens up a lot more to the developer than Web Forms traditionally does. Knowing there is a lie, and knowing the truth can hurt you (the same way Neo knew there was no gravity, yet fell) and so MVC can hurt you. MVC is NOT a replacement for Web Forms, it is another way to solve a set of problems and some problems are better solved in web forms, and others in MVC (or ASP.NET Dynamic Data).

MVC is made up of models, viewers and controls and all of these are changeable. So the viewers uses web forms to render the HTML, but there are other options. One of those is NHaml which is a very different way to create HTML (can read about it here) and I thought that looked very interesting. Viewers should contain no logic, they should focus on rendering HTML only. What is very nice is that for the rendering side JQuery is bundled directly into MVC! It is also important to note that ascx files (ASP.NET controls) are not a

Separate from the viewers is the controls which uses the ASP.NET Routing feature of 3.5 SP 1 heavily. It is very elegant in it’s implementation and shows a forward thinking of convention over configuration. In other words it if you type in a URL like http://test/account/view, it will first check in the viewers\account folder for a view.aspx or ascx file and then in the viewers\shared folder for a view.aspx or ascx file. No config to say that this URL maps to this file. Controllers should contain the bulk of the logic but should not have any web concepts (i.e. don’t use the Request object). Obviously you could, but this breaks the important separation in the MVC design. What is nice, is that because the design of MVC is to help enforce separation, unit testing is amazingly simple and if you have the full versions of Visual Studio then it even builds unit tests for you! So while it may be very easy to put some code in a controller to check if a user is authenticated, you need to decide what level of tolerance for code smell you can handle.

Separate still from both of those is the models. Which is your data model for example LINQ to SQL. The purest form of MVC is you have your data model and then a model to talk to controllers so there is a separation in the models and everything is clean. How much benefit that has in real world is unfortunately not that much and because you have the power (you took the red pill) you can share the model from the models to the controllers.

After that Scott showed his latest project, called NerdDinner. Which is based on MVC and will be an open source solution through CodePlex one day. He showed a lot of the code and highlighted the good bits and the bad bits. This really highlighted what he was talking about and some of the problems you need to solve when working with MVC. After that was Q&A with Pizza.

Defiantly one of the best talks I have attended in a long time. He is on his way to Cape Town (taking a day out of his holiday to fly specially to CT) so if you are in CT, you must go and see him! Details can be found on S.A. Developer!

Pages