WCF Async Without Changing The Contract

Someone asked a group of people recently about how to prevent overloading a WCF service that gets blocked. It sounded like the WCF service was getting called a lot and this was causing many threads to get created to service all of the requests, but nearly all of those threads were blocked handling some IO requests.

I vaguely recalled something about WCF async and I suggested this person look into that. I even looked up the AsyncPattern=true property and value for the OperationContract attribute, but the person didn’t want to break the contract. I was pretty sure that this change was only a server side change and that it wouldn’t break any contract, but I wasn’t 100% sure.

Today I confirmed that I was right. The generated WSDL does not change when you change your contract from something like this:

[ServiceContract]

public interface IOrderService

{

[OperationContract]

Order[] GetOrders(int numOrders);

}

To something like this:

[ServiceContract]

public interface IOrderService

{

[OperationContract(AsyncPattern=true)]

IAsyncResult BeginGetOrders(int numOrders, AsyncCallback callback, object state);

Order[] EndGetOrders(IAsyncResult result);

}

If you want to convert existing WCF services to server-side async style, you can do so without your clients ever knowing. (There may be a caveat when using a ChannelFactory, see the docs.)

The MSDN docs are pretty good. An overview here http://msdn.microsoft.com/en-us/library/ms730059.aspx some better details here http://msdn.microsoft.com/en-us/library/ms731177.aspx

Dan Rigsby had some blog posts from when these features were rolled out, but beware his examples, he keeps a sync version and an async version, which is not strictly required. http://www.danrigsby.com/blog/index.php/2008/03/26/async-operations-in-wcf-iasyncresult-model-server-side/

Finally, Wenlong Dong’s blog gives great reasons why you would want this and even goes as far as suggesting using the async version of the datareader for async database access. http://blogs.msdn.com/b/wenlong/archive/2009/02/09/scale-wcf-application-better-with-asynchronous-programming.aspx

50 Simple Steps To Debugging IE7 Javascript

I had the need to debug javascript in IE7. After the Spoon studio distribution didn’t work for me in 64bit Windows 7, I decided to try the VM approach. Here are 50 simple steps to debugging Javascript in IE7 in a Virtual PC Virtual Machine.

* Download Virtual PC without XP Mode.
* Download IE7 VHD.
* Create a new VPC pointed to the VHD.
* upgrade the vpc integration components.
* defer the reboot.
* Install web developer toolbar.
* install Visual Studio WEb Dev Express 2010 which requires…
* WebPI which requires…
* .NET 2.0
* which fails because of the pending integration components installation.
* reboot.
* watch the upgrade fail when it prompts you for a XP CD ROM.
* Be happy that now you have no intergration components…
* Your mouse it now captured in the VPC window…
* be in awe of how much slower IE7 browsing is without the integration components.
* ITs so slow its going to be unusable for actual work so try installing the integration components again.
* Watch the installer simply fail with no explaination.
* Try WebPI again, even though it will be slow.
* be amazed at how long it takes to ngen System.Design.
* reboot after .net2.0 install.
* reboot after microsoft installer installation.
* be in awe of how long it takes SQL Express 2008 to install.
* reboot after web developer express partly installs.
* be in awe of how long you still have to wait for WebDevExpress to install.
* now that it is all done, try once more for the integration tools.
* get prompted for the CD again for usbhub.sys.
* search your system for this file. c:\> dir /s usbhub.sys
* curse when it is missing.
* google it (you don’t bing it at this point because of MSFT anger).
* after much clicking find this awesome post http://superuser.com/questions/244659/where-can-i-find-windows-xp-sp3-as-a-zip-file.
* nearly get a virus trying to get usbd.sys from memers.driverguide.com.
* find usbd.sys at sysfiles-download.com.
* complete integration components installation.
* wonder what this RemoteApp redirect is… sounds like Unity Mode on a mac for XP in Win7.
* reboot (to complete integration components installation).
* start Visual Web Developer and be in awe of how slow that first time launch is in a VM.
* Create an empty ASP.net web app and click run.
* see the 404 in IE7 and be happy because your browser is now attached to the VWD debugger.
* browse your site with the JS that kills IE7.
* click debug when IE7 prompts you.
* go back to VWD and see the JS open with cursor on the line with the error and no error message and no exception or other information about what is wrong with the JS.
* find a corner.
* sit down.
* curl into fetal position.
* rock yourself gently.
* sing yourself a slow and calm song.
* remember that you go home at 5pm and don’t think about software again until 9am tomorrow.
* be glad you aren’t one of those "passionate" devs that never stops thinking about software.
* think of your children.
* ask a coworker who knows js better than you and let them point to where you don’t have valid js.

Agile Solves a Specific Problem

Bill Wagner has a great post on agile titled “What can we learn from the Agile Backlash

Every time I read about agile I’m reminded of how distorted my view of agile had become because I was listening to everyone else’s distortions of agile. I always go back to the manifesto and read a few simple words

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer Collaboration over contract negotiation
  • Responding to change over following a plan

The rest of the manifesto is important too, but I find these points are to what I come back the most often. It took someone smart figuratively smacking me in the face for me to notice how messed up I was and then I noticed how messed up many others are on the meaning of agile. (Thanks Amanda!)

Something that agile states is that your goal is to write software in ways better than you are doing now. This is from the first sentence of the manifesto, “We are uncovering better ways of developing software…” What I’ve noticed on a current consulting project is that agile is not applicable if the team (or client) is not interested in this goal.

Unbelievable I know, but not everyone is a software developer and so developing software in better ways may not be important to everyone. Specifically, it probably isn’t important to management, until you can show management that it saves them money.

Even given all of that evidence, some groups may still not share values with agile. For example, favoring individuals and interactions over processes and tools is not going to fit into an organization whose top down leadership absolutely requires people to use tool X from vendor Y, and it doesn’t matter that it doesn’t fit the current project or that it slows down velocity. It doesn’t fit when developers (individuals) show evidence (Mythical Man Month is the tip of the iceberg) that working on many projects causes thrashing that greatly hinders developer productivity when the organization doesn’t value delivery of software in a timely manner, but instead values a high number of concurrent projects. Its not that one set of values is necessarily better than the other, there might be a very good business case to retain existing values in that organization over the agile values.

Finally, it is of absolute importance as a consultant, programmer, team lead or program manager to recognize what you can change and what you can not in any organization. Sometimes you won’t know and you may go ahead trying to get some change. This is fine, but always be on the lookout to see how well that change is being adopted and be ready to “respond to change” even if that means not adopting agile in that particular situation.

Why I Love C# More Than I Care About Ruby

@robconnery I’m really glad that you are excited. I think anytime someone is healthily and safely passionate about something, it can only be a good thing.

Rob has a great post where he lists 4 cases where he likes Ruby and compares to the same thing in C#. Case 1 Expressiveness: Rob likes the unless statement and the post expression if statement. Case 2: Rob likes Gems. Case 3: Rob likes simple things. Case 4: Rob likes sending messages, open classes and method missing.

Python and Perl already did all this, so why Ruby?

Case 1 and 3 were true in python when i started writing it in 1996 and case 1, 2 and 3 were true in perl when i started writing it in 2000. I’m sure case4 is true in both python and perl too, but I never went that deep into either of them. Much like in Ruby, you don’t have to go that deep to get things done.

I am of the opinion that if you have never seen a dynamic typed language before, or maybe a dynamic typed language other that BASIC or VB before, that Ruby has all of the appeal which you tout. However, there are some of us who write C# because we actually like it, we write desktop applications, and find it to be the best static and strong typed language around. We came to C# and were super impressed because the weak typing of C wasn’t there. The rough edges of C++ wasn’t there and for nearly all applications there is no performance difference and sometimes the GC and managed environment actually gives a boost in performance over some of the bad C++ we were writing before.

So should someone who has never written in Perl, Python, Pike and PHP go try out Ruby… absolutely… get the exposure.

Alternatively, if you have done some Perl or Python and now you are a C# guy. Ruby might not seem so impressive. In fact, it looks more like the same thing with a new coat. I can’t tell what the hype is about. There isn’t much new and different.

All that said, after years of Perl, learning C# was a challenge, especially since I was using it to solve many of the same problems for which I had been using Perl. WHY? was I doing it that way? Well I wanted Windows Forms UI front ends on my Perl versions of programs there were ultimately just sed/awk/grep and some ldapsearch/ldapadd/ldapmodify commands. Not commands really, but calls to libraries.

There is a good reason that the “simple things” aren’t AS simple.

What I learned was that there is a damned good reason that Case 3 “The Simple Things” were a little more complex in C#. The separation of stream and textreader abstract types in C# make huge sense once you realize that doing the same thing in perl or python (or ruby) can be a bit of a hassle. The organization of decorator streams in the .NET BCL just makes sense. Want to compress? Decorate with the stream compressing class. Want to encrypted? Decorate with the stream encrypting class. Want to do both? In either order? Decorate appropriately.

I do share Rob’s opinion. It is a little prettier in Ruby. I’ve already gone on record as saying that “var” in C# should be optional. In VB6 the Let statement was optional. In VB.NET the Let statement is no supported. IMO C#’s var isn’t much different than VB.NET’s Let and Dim. Sure would be nice if it were optional.

I’ve also requested static imports so that we could do things like just call the open method instead of saying File.Open. When you are in a nice tiny singly responsible file, it just makes sense.

These things don’t change my ability to write code.

On .NET’s lack of a CPAN, Cheeseshop, Gem equivalent: YES! YES! YES WE NEED IT NOW!

I can’t say anything other than .net needs CNAN (comprehensive .net archive network) or maybe CCAN (comprehensive CIL archive network). I can’t decide which name I like better.

As for metaprogramming, I think that Python, Perl and Ruby’s ability for runtime metaprogramming will continue to be far beyond anything you see in the C# world. That is not say that metaprogramming is not possible in C#. Its just very different. Its typically compile time metaprogramming. Thanks to the addition of T4 in VS2008 and 2010, metaprogramming in C# is readily available and powerful.

I could go on and insert above about how I learned to love the .NET RegularExpression API after having it blow my mind in comparison to perl’s. Or about how poorly documented the System.DirectoryServices API is, but that once I got it I loved it so much more than Net::LDAP. Or about the extreme pain in building CPAN modules on a Sun Sparc and how installing Mono and using Visual Studio and C# was actually easier than making Perl work properly.

But rather than elaborate on those things, I’ll end by saying, yes, Ruby is awesome, if you have never seen any of the things which make it awesome before.

C# 4 Optional Parameters Limits Default Value

Jon Skeet has an excellent C# 5 talk video from the recent Norwegian Developer Conference. Go watch it.

When he showed Default<T>, I immediately thought it was just an variation of Option<T> or F#’s option type, but with added default value logic. Its cool.

He was asking for compiler support so that things like this would be possible.

Default<int> a = 1;

Well, I thought, you don’t need compiler support for that, just add an implicit type converter to your definition of Default<T>

        public static implicit operator Default<T>(T value)
        {
            return new Default<T>(value);
        }

No worries, right?

Oh I was so wrong. While this will work for the regular above statement, it won’t work as a default parameter value.

     class Things { public Things(Default<int> a = 5) { } }

This provides a wonderfully descriptive error (I love this compiler) which says “a value of type ‘int’ cannot be used as a default parameter because there are no standard conversions to the type ‘Default<int>’”

Now I’m crying? Why the limit? Instead of Jon’s request for awesome Default<T> support in C# 5, I request considering implicit type converters on optional parameter default values.

WlanChannelInfo aka Windows 7 Net Stumbler aka Wifi Channel Info

I finally got around to updating WlanChannelInfo. It started because I wanted to play with some .NET 4 beta features and I also struggled with getting a simple net stumbler running. I figured that Windows had to have something better to offer, and it turns out that in windows 7 the WLAN API was updated to expose everything that I cared about. I really only want to see what WIFI channel’s my neighbors are on so that I can move my WIFI AP to an unused channel.

http://wlanchannelinfo.codeplex.com/

I finally updated it to use a .NET release instead of a .NET 4 beta, but when I did, I decided that I didn’t need .NET 4. I just stuck to using 3.5 so that this app will run out of the box on Windows 7. No need to get .NET 4 to run this. I figure my parents might have windows 7 but probably won’t have .NET 4 installed just yet. Maybe someone else’s parents would have the same issue, and since the download is only 19KB… yes, 19KB… since the app is dead simple and does nothing but use existing WPF controls and p/invoke into the WLAN api (via the ManagedWifi.dll also on codeplex) its *TINY*.

Let me know if you find this useful.

Method I Wish Was There: AsUri

I never got used to the .NET Uri type. It seems like I only had to use it occasionally and even then where I really only wanted to type a string url.

public static Uri AsUri(this string uri) { return new Uri(uri); }

This way I can just add a AsUri() when I forgot that I was supposed to pass a Uri instead of a string.

webclient.DownloadFileAsync( “http://blah.com”, filename );

doesn’t compile and so I can scratch my head once again and replace it.

webclient.DownloadFileAsync( “http://blah.com”.AsUri(), filename );

I like trivial things 🙂

Method I Wish Was There: IsWithin

I don’t think I like the name, but I couldn’t come up with something better.

public static bool IsWithin(this DateTime datetime, TimeSpan distance) {
  var now = DateTime.Now;
  return (now – datetime).Duration() < distance;
}
public static bool IsWithin(this DateTime datetime, TimeSpan distance, DateTime now) {
  return (now – datetime).Duration() < distance;
}

Coupled with extension methods from yesterday you can write code like this:

if ( postDate.IsWithin(24.Hours()) ) { … }

nice and readable.

Method I Wish Was There: Minutes, Hours, Seconds

Ok, the ruby lovers will laugh, the ruby haters will, well, hate.

public static TimeSpan Minutes (this int minutes) {
  return new TimeSpan(0, minutes, 0);
}
public static TimeSpan Hours (this int hours) {
  return new TimeSpan(hours, 0, 0);
}
public static TimeSpan Seconds (this int seconds) {
  return new TimeSpan(0,0, seconds);
}

So that now I can write readable code like this:

var fiver = 5.Seconds();
var fivertoo = 5.Hours();
Assert.That( fiver.IsLessThan(fivertoo) );

Method I Wish Was There: DataGridView.GetDisplayIndexToPropertyNameMap

Alright, I’ll admit it, this one is rather obscure and only useful if you are doing strange things with a Windows Forms DataGridView.

I like this method because I think its a good use of Fold… err.. I mean Aggregate. I’m convinced Aggregate is an underutilized method so far by .NET developers.

In this case I like it because I can state what I want to do in a single statement rather than multiple statements.

public static IDictionary<int, string> GetDisplayIndexToPropertyNameMap(this DataGridView datagridview)
{
  var boundColumns = 
          datagridview.Columns.Cast<DataGridViewColumn>().Where(c => null != c.DataPropertyName);
  return boundColumns.Aggregate(
                new Dictionary<int, string>(),
                (a, b) => a.Insert(b.DisplayIndex, b.DataPropertyName));
   }

Notice the use of yesterday’s Dictionary.Insert so that we return the Dictionary at every iteration of the Aggregate*.

I find this MUCH more readable than if the Aggregate statement had been

return boundColumns.Aggregate(new Dictionary<int,string>(),
   (a,b) => { a.Add(b.DisplayIndex, b.DataPropertyName); return a; } );

The curly braces for the block lambda syntax and the return statement inside them really take away from the readability IMO.

* Note that this is why I put Insert explicitly on Dictionary instead of IDictionary. C# 3’s type inference is not good enough to figure out that we would want the signature of Aggregate to be IDictionary<int,string> instead of Dictionary<int,string> if Insert returned an IDictionary