Featured Post

Outpost.Com no longer offering free shipping

I recieved the following email from Darryl Peck, CEO of OutPost.Com. They are an online computer hardware vendor that has been loosing millions of dollars due to there free shipping rates and 24 hour service. Personally, I don’t know why they started it in the first place. Yeah, it is a great idea,...

Read More

WCF Data Service Error – Request Error

Posted by Keith Elder | Posted in .Net, C#, WCF | Posted on 09-03-2010

3

I’ve done this twice now and I know if I’ve done it others probably have as well.  Here’s the short story and the fix.

Let’s say you create a new project to play around with a WCF Data Service to create some OData.  You add an entity framework model from an existing database and then add a WCF Data Service.  Things are going along nicely.  To get something up and running quickly you modify the WCF Data Service to look like the following.  All looks good.

   1: namespace WcfService2

   2: {

   3:     public class WcfDataService1 : DataService<NutshellEntities>

   4:     {

   5:         // This method is called only once to initialize service-wide policies.

   6:         public static void InitializeService(DataServiceConfiguration config)

   7:         {

   8:             // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

   9:             // Examples:

  10:             // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);

  11:             // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);

  12:             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

  13:             config.SetEntitySetAccessRule("Customer", EntitySetRights.All);

  14:         }

  15:     }

  16: }

Then you build your solution thinking you are about to strike gold when all of a sudden you are presented with this nasty unhelpful error:

image

Request Error

The server encountered an error processing the request. See server logs for more details.

The problem lies in line 13.  See the string?  Yeah, that’s a spot where we as humans have to type something and let’s face it, we make mistakes.  I’ve done this several times already.  To fix this, look at your model and make sure you have the correct name.  Here is my playground model:

image

Yep, it was suppose to be “Customers” instead of “Customer”. Change line 13 to “Customers” and all is well.

.Net 4.0 – Start Reading Between the Lines – Learn Silverlight and Entity Framework

Posted by Keith Elder | Posted in .Net, Asp.Net, C#, Internet, Mobile Devices, MVP10, PC Software, Smart Clients, SQL Server | Posted on 30-11-2009

11

I started writing this as a general recap of PDC for team members but the more I thought about what was announced at PDC, the longer the email got.  Ultimately I decided to put it out so you dear reader could also gain some insight from things announced at PDC. 

For starters listen to the podcast we recorded with Scott Guthrie or “The Gu”, or “His Guness”, or “ScottGu” about Silverlight 4 announcements among other things while at PDC. 

The big stories out of PDC that I think everyone should take note of are Silverlight 4, Entity Framework 4 and Windows Mobile. Wait Windows Mobile 7? Yes.  Wait… I didn’t hear anything about Windows Mobile 7? Well I didn’t either and that is why this post is called “read between the lines”.  Call it speculation or whatever, but I think I can bring you up to speed on what is about to happen (and no I have no official behind the scenes information, I’m just a guy with a brain).  Before we get to Windows Mobile 7, let’s start with Silverlight.

Silverlight

Silverlight 4 had tons of announcements including:

  • Camera and microphone support
  • Trusted out of browser support.  This means one can access COM (for example, an application could access Outlook APIs)
  • Lots of line of business app controls
  • Added support for drag and drop
  • WCF RIA Services (this is basically what I’m calling the new CSLA, if you listen to the podcast you’ll find out that Rocky worked with the team closely on RIA Services)
  • Print natively
  • More…

Tim has a great recap of all the Silverlight announcements here with links to videos:

http://timheuer.com/blog/archive/2009/11/22/pdc-silverlight-resources-link-dump-learn-silverlight.aspx

Now what does this all mean? It means the line is blurring between client and server applications. It also means we are coming back full circle to “Smart Clients” (which were hot in 2005/2006 but were forgotten due to the Web 2.0 hype.  The only difference is this new breed of application (Silver Clients?) can run directly from a web site, or on a client’s machine.  It also means that Silverlight is going to finally fulfill the vision we heard about a long long time ago that was called WPF/e (WPF Everywhere).  A lot of people have forgotten this but we are seeing it take full shape now.  For businesses that are writing applications internally, I think we are going to start seeing a huge shift away from writing Asp.Net/MVC apps and a move towards the rich model with Silverlight.  I mean seriously, why wouldn’t you? If you get cross platform compatibility, rich data binding, write once and work in any browser, why would developers that are trying to build internal business applications continue to kill themselves writing JavaScript, fighting CSS and browser compatibility?  I can’t think of a reason either.  In my opinion this is just a waste of time (and always has been).  There is something extremely powerful putting a variable in memory and having it be there when you need it without having to worry about sessions, state, etc.  Yes we are FINALLY getting back to the client programming model, just coming at it a different way. 

Entity Framework

Let’s talk about Entity Framework 4.0 for a moment.  This is another big piece of news.  It is big because as .Net developers we will finally have one true way to access data that fits the multitude of ways we have to work.  Here’s a recap of announcements (not a complete list, watch the videos from PDC):

  • POCO – supports plain old clr objects
  • EDM designer enhancements
  • Better stored proc support
  • Model first (then gen database model)

Doug Purdy (who we also interviewed for Deep Fried Bytes while at PDC) has a list of the sessions that cover the Entity Framework 4.0.  Just start at the top and work your way down as far as you can.  At least watch the first video as it shows off all the features of EF.

http://www.douglaspurdy.com/2009/11/22/pdc-2009-data-and-modeling-talks-2/

With the number of features that were announced in EF4 I think we are on the verge of seeing the demise of NHibernate usage by developers in the .Net stack.  For those that have used NHibernate in the past, it is worth another look at the Entity Framework to be released in .Net 4.0.  About the only thing EF4 doesn’t do that NHibernate does do is built-in caching (which hey, there’s this caching thing that AppFabric does, hmm, wonder if they’ll use that? Why not! :) ).  But the big thing to note between EF4 and NHibernate is we are starting to see where this whole modeling thing with OSLO is going (edm files are m fles and so on).  And of course there is the bigger picture of reusing this model in report services, BI and other areas (although we haven’t *seen* that really working yet, it is coming though see next sentence).  As EF4 makes it way into other products throughout the Microsoft ecosystem it is going to be extremely hard to avoid the Entity Framework.  Read between the lines, the writing is on the wall, LEARN THE ENTITY FRAMEWORK.

Just a side bar here because I know someone is going to ask me this at a later time.  Will the Entity Framework kill NHibernate? Answer: Nope I’m not saying that. 

Out of band developers that seem to have a knack for yelling the loudest will continue to use NHibernate but a much larger ecosystem will leverage the out of the box Entity Framework in .Net 4.0.  Think back for just a bit.  History is about to repeat itself all over again.  Remember when we got MSTest and or MSBuild?  Same thing is happening again. There is now an out of the box product for standardizing data access.  Are their alternatives? Sure.  Just as MSTest didn’t kill NUnit or MBUnit and MSBUILD didn’t kill NAnt, EF4 will not kill NHibernate.  However, if you look at the number of developers using MSBuild or MSTest it is high. Extremely high.  Why is that? Answer: pain, ease of use, integration, documentation.  MSTest is not the best testing framework out there (this is a proven fact), but it is good enough for 90% plus test cases.  Entity Framework 4.0 is going to put an ORM in the hands of developers.  And you know what, it doesn’t suck either. 

Windows Mobile 7

And now onto Windows Mobile 7. 

Is this WinMo 7 above?  I honestly don’t know, I found these screen shots on http://windowsphonemix.com/ web site.  BTW, notice that URL?  Mix? Yes Mix.  Mix is the first of the three major conferences Microsoft puts on each year.  The very last slide at PDC during the last keynote said, “Come to Mix 2010 for Windows Mobile 7 futures”.  A lot of people missed this because they were tuned out from the SharePoint demos and already packing to leave.  But there it was on the big screens.  Thus we know Mix is when we’ll see Windows Mobile 7.  Again, listen to the podcast to get some other insight. 

Here’s a quote:  “Three screens and the cloud”

We heard this over and over at PDC.  Let’s read between the lines a bit shall we?

I have three screens:  Windows Desktop, Web, Mobile.  Ok, if I want to write an app that will run on all three what do I as a developer have to do today?  Let’s see, well, we could write a ClickOnce deployed Smart Client for the Desktop that uses WPF.  For the web, well, we would have to switch gears completely and rewrite our app in Asp.Net or Asp.Net MVC to get that screen.  For mobile, even tougher, we have to rewrite the app again to get the mobile version.  Let’s think about this differently again.  Think about it, how many technologies would a developer have to know in order to an application for these three different screens;  WPF, JavaScript, HTML, and CSS will be used just to name a few.

Now, let’s switch gears.  What if I used Silverlight 4 to write my app?  Well, it could work in the browser no doubt.  Hmmm, it could also work on the Desktop using the out of browser experience with elevated permissions.  What about mobile? 

“Wait, didn’t you just say Keith that at Mix we’ll get to see Windows Mobile 7?”

Yes! 

“And hasn’t there already been talk of using Silverlight for mobile?”

Yes!

“Aha! Three screens with Silverlight, I get it!”

That’s right my friendly .Net developers the writing is on the wall. The vision of WPF/e (WPF Everywhere) is about to come true.  We’ve waited for years but it is just around the corner as I predicted would happen years ago.

http://www.keithelder.net/blog/archive/2007/01/12/Microsofts-Response-To-The-iPhone-Is-Right-Around-The-Corner.aspx 

(ok, so it wasn’t right around the corner but 3+ years later)

Moral of the story?

LEARN SILVERLIGHT so you can make millions of dollars building Mobile applications just like the iPhone devs.  There, I just made you rich by putting this puzzle together for you, please send me 20% of all profits.

You are welcome.

Fun With the ?? Operator in C#: if { } or ?? – Which is Faster?

Posted by Keith Elder | Posted in C# | Posted on 06-08-2009

7

Yesterday evening at work a team member and I were pair programming.  We had a disagreement about how to code a few lines.  The question was around whether to use the ?? operator or to use an if statement using String.IsNullOrEmpty.  We settled it like most developers do and that is with a benchmark.  Here’s the fun we had.

To give you an idea as to what we were doing here’s some context.  We had a function that took an object.  We wanted to add extra context data to the object, but only if the object didn’t have it set.  In other words, the data may have already been set somewhere else in the application and we didn’t want to override what was already set.  There were two ways to do this and since I was typing I started typing the following.

   1: private void AddContextData(LogEntry entry)

   2: {

   3:     entry.Url = entry.Url ?? HttpContext.Current.Request.Url.ToString();

   4:     entry.UserIpAddress = entry.UserIpAddress ?? HttpContext.Current.Request.UserHostAddress;

   5:     entry.UserName = entry.UserName ?? HttpContext.Current.User.Identity.Name;

   6: }

My pairing partner started in on me immediately.  He was thinking it should be written like this.

   1: private void AddContextData(LogEntry entry)

   2: {

   3:     if (String.IsNullOrEmpty(entry.Url)) entry.Url = Context.Current.Request.Url.ToString();

   4:     if (String.IsNullOrEmpty(entry.UserIpAddress)) entry.UserIpAddress = HttpContext.Current.Request.UserHostAddress;

   5:     if (String.IsNullOrEmpty(entry.UserName)) = entry.UserName = HttpContext.Current.User.Identity.Name;

   6: }

The ?? for those that aren’t familiar with it is called the “null coalescing” operator. Scott Gu wrote about it late 2007 if you want some additional information and samples.  It is a fun little operator and can save you a lot of typing in more places than you think.  Most developers though don’t think to use it and instead code the long handed version doing a check using a if block. 

In the end we decided to settle our disagreement and go with the one that was the fastest.  Thus we whipped up a quick benchmark to test one vs. the other.  Here’s the benchmark code for both samples.

?? Operator Benchmark Code

   1: string x = "foo bar";

   2: Stopwatch watch = new Stopwatch();

   3: long ticks = watch.Time(() => x = x ?? "bar foo", 100000);

   4: textBox1.Text += "??: " + ticks.ToString() + Environment.NewLine;

 

Note: If you copy the above code, it will not work on your machine unless you have a Time() extension method as part of your arsenal. 

if { } Benchmark Code

   1: string x = "foo bar";

   2: Stopwatch watch = new Stopwatch();

   3: long ticks = watch.Time(() =>

   4:                             {

   5:                                 if (String.IsNullOrEmpty(x))

   6:                                 {

   7:                                     x = "bar";

   8:                                 }

   9:                             }

  10:                 , 100000);

  11: textBox1.Text += "if: " + ticks.ToString() + Environment.NewLine;

The Results

The results were not all that exciting. Really it only proved there was wasn’t any difference in speed, if anything giving a very very slight edge to the ?? operator.  At any rate it was a fun side bar to end the evening.  Happy null coalescing!

image

Deep Fried Bytes Episode #27: Present and Future of the C# Language

Posted by Keith Elder | Posted in C#, Podcast | Posted on 23-02-2009

0

Listen To This Episode 

http://deepfriedbytes.com/podcast/episode-27-present-and-future-of-the-csharp-language/

 

In this episode we sat down with Mads Torgersen, Language PM for C# at Microsoft, at the Codemash 2009 conference.  We discussed a variety of languages including Beta, Self, IronPython, IronRuby, F# and of course C#.  Listen in as we discuss the ins and out of C# and why C# and VB are on the same feature path.

Cleaning Up Your C# Closet, Making Messy C# Code More Readable

Posted by Keith Elder | Posted in C# | Posted on 22-12-2008

10

How Clean is Your Closet?

image

Have you ever been instructed to make an enhancement to an existing project where the codebase looked like the picture above?  I have.  As a matter of fact, I’ve done my fair share of creating messy code just like that.  I’m not saying I’m proud of admitting that but as they say, “The truth hurts”.

Let’s pretend for a moment this is my closet and you were visiting.  We were about to leave to go to town and you said, “Brrrr, it is cold outside, do you have a scarf?”.  I said, “Sure, it is in the closet, there is a purple one in there.”. 

You then stumble into the closet to find the scarf.  How long do you think it would take you?  The likelihood of you finding it within a few seconds is slim to none. 

Let’s switch gears to programming.  How long would it take to implement a task if the picture above represented the codebase of an existing project?  A long time for sure, definitely longer than it should take no doubt.  Why?  Because things that are messy take longer!  Here is an Elderism (common sense words of wisdom to live by) that sums up messy projects:

ELDERISM – “A messy project takes longer to understand and will only get messier.”

Switch gears for a moment and let’s say you needed to find the purple scarf in this closet.  Obviously since things are organized and well laid out, it becomes easy to locate, add, and remove things. 

image The really sad part about this whole analogy is that for some reason, a lot of developers are happy with wallowing in a perfect mess.  Not only does this make things hard for them but for other developers on the team as well. 

A Real World Mess

I was reminded of this the other day when I started to work on Witty Twitter, an open source WPF Twitter client several of us work on.  I hadn’t worked on the project very much lately but I wanted to take some time during vacation to clean some things up and add some new features.  I know how most things work in codebase but the biggest problem with the codebase is the lack of structure and organization to it.  I started to implement a new feature and suddenly I realized I was contributing to the code rot.  Remember the Elderism, “A  messy project takes longer to understand and will only get messier.”?  Well, here I was adding more mess to the codebase to get something to work. 

Finally I said, enough is enough.  My contribution is going to be to simplify and clean up this code.  In other words, clean up and organize the closet.  To give you an idea of the mess staring me in the face, here is the constructor of the main application.  This is ONE function which initializes the main form Witty uses.

   1: public MainWindow()
   2: {
   3:     this.InitializeComponent();
   4:  
   5: #if DEBUG
   6:     Title = Title + " Debug";
   7: #endif
   8:  
   9:     // Trap unhandled exceptions
  10:     LayoutRoot.Dispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException);
  11:  
  12:     #region Minimize to tray setup
  13:  
  14:     _notifyIcon = new System.Windows.Forms.NotifyIcon();
  15:     _notifyIcon.BalloonTipText = "Right-click for more options";
  16:     _notifyIcon.BalloonTipTitle = "Witty";
  17:     _notifyIcon.Text = "Witty - The WPF Twitter Client";
  18:     _notifyIcon.Icon = Witty.Properties.Resources.AppIcon;
  19:     _notifyIcon.DoubleClick += new EventHandler(m_notifyIcon_Click);
  20:  
  21:     System.Windows.Forms.ContextMenu notifyMenu = new System.Windows.Forms.ContextMenu();
  22:     System.Windows.Forms.MenuItem openMenuItem = new System.Windows.Forms.MenuItem();
  23:     System.Windows.Forms.MenuItem exitMenuItem = new System.Windows.Forms.MenuItem();
  24:  
  25:     notifyMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { openMenuItem, exitMenuItem });
  26:     openMenuItem.Index = 0;
  27:     openMenuItem.Text = "Open";
  28:     openMenuItem.Click += new EventHandler(openMenuItem_Click);
  29:     exitMenuItem.Index = 1;
  30:     exitMenuItem.Text = "Exit";
  31:     exitMenuItem.Click += new EventHandler(exitMenuItem_Click);
  32:  
  33:     _notifyIcon.ContextMenu = notifyMenu;
  34:     this.Closed += new EventHandler(OnClosed);
  35:     this.StateChanged += new EventHandler(OnStateChanged);
  36:     this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(OnIsVisibleChanged);
  37:  
  38:     // used to override closings and minimize instead
  39:     this.Closing += new CancelEventHandler(MainWindow_Closing);
  40:  
  41:     #endregion
  42:  
  43:     #region Single instance setup
  44:     // Enforce single instance for release mode
  45: #if !DEBUG
  46:     Application.Current.Exit += new ExitEventHandler(Current_Exit);
  47:     _instanceManager = new SingleInstanceManager(this, ShowApplication);
  48: #endif
  49:     #endregion
  50:  
  51:     // Set the data context for all of the tabs
  52:     LayoutRoot.DataContext = tweets;
  53:     RepliesListBox.ItemsSource = replies;
  54:     UserTab.DataContext = userTweets;
  55:     MessagesListBox.ItemsSource = messages;
  56:  
  57:     // Set how often to get updates from Twitter
  58:     refreshInterval = new TimeSpan(0, int.Parse(AppSettings.RefreshInterval), 0);
  59:  
  60:     this.Topmost = AlwaysOnTopMenuItem.IsChecked = AppSettings.AlwaysOnTop;
  61:  
  62:     // Does the user need to login?
  63:     if (string.IsNullOrEmpty(AppSettings.Username))
  64:     {
  65:         PlayStoryboard("ShowLogin");
  66:     }
  67:     else
  68:     {
  69:         LoginControl.Visibility = Visibility.Hidden;
  70:  
  71:         System.Security.SecureString password = TwitterNet.DecryptString(AppSettings.Password);
  72:  
  73:         // Jason Follas: Reworked Web Proxy - don't need to explicitly pass into TwitterNet ctor
  74:         //twitter = new TwitterNet(AppSettings.Username, password, WebProxyHelper.GetConfiguredWebProxy());
  75:         twitter = new TwitterNet(AppSettings.Username, password);
  76:  
  77:         // Jason Follas: Twitter proxy servers, anyone?  (Network Nazis who block twitter.com annoy me)
  78:         twitter.TwitterServerUrl = AppSettings.TwitterHost;
  79:  
  80:         // Let the user know what's going on
  81:         StatusTextBlock.Text = Properties.Resources.TryLogin;
  82:         PlayStoryboard("Fetching");
  83:  
  84:         // Create a Dispatcher to attempt login on new thread
  85:         NoArgDelegate loginFetcher = new NoArgDelegate(this.TryLogin);
  86:         loginFetcher.BeginInvoke(null, null);
  87:     }
  88:  
  89:     InitializeClickOnceTimer();
  90:  
  91:     InitializeSoundPlayer();
  92:  
  93:     ScrollViewer.SetCanContentScroll(TweetsListBox, !AppSettings.SmoothScrolling);
  94:  
  95:     //Register with Snarl if available
  96:     if (SnarlConnector.GetSnarlWindow().ToInt32() != 0)
  97:     {
  98:         //We Create a Message Only window for communication
  99:  
 100:         this.SnarlConfighWnd = Win32.CreateWindowEx(0, "Message", null, 0, 0, 0, 0, 0, new IntPtr(Win32.HWND_MESSAGE), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
 101:         WindowsMessage wndMsg = new WindowsMessage();
 102:         SnarlConnector.RegisterConfig(this.SnarlConfighWnd,"Witty",wndMsg);
 103:         
 104:         SnarlConnector.RegisterAlert("Witty", "New tweet");
 105:         SnarlConnector.RegisterAlert("Witty", "New tweets summarized");
 106:         SnarlConnector.RegisterAlert("Witty", "New reply");
 107:         SnarlConnector.RegisterAlert("Witty", "New direct message");
 108:         
 109:     }
 110: }

In case you don’t scroll down and actually glance at the code, there are over 100 lines of code for this constructor.  No matter how smart you are, there is no way one can read that code and fully understand “what” it is doing without devoting an enormous amount of time to it.  Everything in there, with the exception of a few functions that get called, the code is all about “how”.  All of the code in that constructor is needed too.  It isn’t like it can be taken out, it must be there to set things up in the application. 

Cleaning Up The Closet

If you don’t take anything else away from this article remember this one fact.  Developers reading your code rarely are worried about the “how”, they need to know the “what” so they can figure out where to put their code.  This concept is earth shatteringly simple, yet as you can see with the above code, we have a perfect real world example of a “how” that has turned itself into a mess. 

Code Smell #87 – Comments

A code smell is something we refer to in the business as something that doesn’t look right, or that shouldn’t be done that way, or something that will lead the developer down a dark path.  It means many things and that’s why I labeled this as #87. 

Comments in code have saved many developers endless hours, but they have also cost many developers thousands of hours.  A rule I have, is code shouldn’t have any comments in the code.  My main reason for this is refactoring. 

Code refactoring is the process of changing a computer program‘s code to make it amenable to change, improve its readability, or simplify its structure, while preserving its existing functionality.

In software development we constantly refactor our code.  Guess what happens to those comments though?  They don’t get refactored! 

A developer can completely change how a program works and those nasty comments are still there.  Then along comes someone else who reads the comment and thinks the code is broken because it doesn’t do what the comment said it was doing.  They then refactor it back and things break.

The best thing to do is not comment your code.  If you have the urge to put a comment on something, that means you didn’t express the intent of the code clearly enough, thus it is a code smell.  Let’s look at a few examples from our example above to see how this plays out.

Let’s start with line #95 in the example above.  Here is that example:

//Register with Snarl if available
if (SnarlConnector.GetSnarlWindow().ToInt32() != 0)
{
    //We Create a Message Only window for communication
 
    this.SnarlConfighWnd = Win32.CreateWindowEx(0, "Message", null, 0, 0, 0, 0, 0, new IntPtr(Win32.HWND_MESSAGE), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
    WindowsMessage wndMsg = new WindowsMessage();
    SnarlConnector.RegisterConfig(this.SnarlConfighWnd, "Witty", wndMsg);
 
    SnarlConnector.RegisterAlert("Witty", "New tweet");
    SnarlConnector.RegisterAlert("Witty", "New tweets summarized");
    SnarlConnector.RegisterAlert("Witty", "New reply");
    SnarlConnector.RegisterAlert("Witty", "New direct message");
 
}

Notice the comment in the first line of the code?  The comment is telling us “what” the if block is doing.  Even though I can read this:

(SnarlConnector.GetSnarlWindow().ToInt32() != 0)

I honestly do not know the Snarl API and thus I have no idea “what” that is doing, or why.  In this case, the developer that wrote this in their mind said this was something they had to figure out “how to do” so they wanted to leave a bread crumb here to tell everyone “what it’s doing”.

Now think for a second.  Without using a comment, how else could they have told us the exact same thing?  The answer: CODE. 

If a developer focuses on making their code more readable the end result will be much neater and it will also express the “what it is doing”.  This means other developers can move quickly through the project / closet to figure out where things are.

For those cleaning up code like this, more times than not you can just take the comments and turn that into functions.  This is the case so much in fact that Visual Studio plug-ins like Refactor! Pro automatically turn comments like that into the name of the function when extracting code into a method. 

In this example there are two comments.  We’d refactor this to read like this:

public MainWindow()
{
    RegisterWithSnarlIfAvailable();
}
 
private void RegisterWithSnarlIfAvailable()
{
    if (SnarlConnector.GetSnarlWindow().ToInt32() != 0)
    {
        CreateSnarlMessageWindowForCommunication();
    }
}
 
private void CreateSnarlMessageWindowForCommunication()
{
    this.SnarlConfighWnd = Win32.CreateWindowEx(0, "Message", null, 0, 0, 0, 0, 0, new IntPtr(Win32.HWND_MESSAGE), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
    WindowsMessage wndMsg = new WindowsMessage();
    SnarlConnector.RegisterConfig(this.SnarlConfighWnd, "Witty", wndMsg);
 
    SnarlConnector.RegisterAlert("Witty", "New tweet");
    SnarlConnector.RegisterAlert("Witty", "New tweets summarized");
    SnarlConnector.RegisterAlert("Witty", "New reply");
    SnarlConnector.RegisterAlert("Witty", "New direct message");
}

With a simple refactor we have fully expressed the “what” the code is doing and made it more readable. 

Applying these simple concepts to the original example that was over 100 lines long, we can refactor this into readable code with zero comments that expresses what is going on instead of how.  The end result is less code to read in the constructor that reads more like a story describing what the constructor is doing. 

   1: public MainWindow()
   2: {
   3:     this.InitializeComponent();
   4:  
   5:     TrapUnhandledExceptions();
   6:  
   7:     SetupNotifyIcon();
   8:     
   9:     SetupSingleInstance();
  10:  
  11:     SetDataContextForAllOfTabs();
  12:     
  13:     SetHowOftenToGetUpdatesFromTwitter();
  14:  
  15:     InitializeClickOnceTimer();
  16:  
  17:     InitializeSoundPlayer();
  18:  
  19:     InitializeMiscSettings();
  20:  
  21:     RegisterWithSnarlIfAvailable();
  22:  
  23:     DisplayLoginIfUserNotLoggedIn();
  24: }

Do you see the difference?  It is night and day isn’t it?  There is no more wondering, guessing, and also worrying about doing something in the wrong place. 

If you are dealing with messy closets, I mean code, apply these basic principles and you’ll wind up with codebases that are more readable and easier to refactor down the road.  This is only one thing you can do to clean up messy projects.  There are others but we have to start somewhere. 

Once things are refactored so they express the what things will get more clear and other refactorings will start to bubble up.  For example, if you look at the final code above, you’ll notice the DisplayLoginIfUserNotLoggedIn() method is called last in the constructor.  This makes sense.  We should call the login screen after everything else is initialized.  However, in the original code it wasn’t last.  How would I have figured that out if I hadn’t made the code more readable?  Exactly my point!

It is a very powerful concept, give it try.