Tuesday, February 9, 2010

The Weekly Source Code 49 - SmallBasic is Fun, Simple, Powerful Programming for Kids and Adults

The Weekly Source Code 49 - SmallBasic is Fun, Simple, Powerful Programming for Kids and Adults


The Weekly Source Code 49 - SmallBasic is Fun, Simple, Powerful Programming for Kids and Adults

Posted: 09 Feb 2010 01:18 PM PST

While the boys are only 2 and 4, I'm always keeping an eye out on new ways to teach them programming. Certainly I hope they'll be more well-rounded and I and spend more time outside, but a even a basic background in programming and logic, I think, produces Read More......(read more)

24 Hour 50% off Deal on my Upcoming Manning Book: Silverlight in Action, Revised Edition

Posted: 09 Feb 2010 12:25 PM PST

On Wednesday February 10, 2010 my book is on sale at Manning for 50% off.That's print, MEAP, e-book or any combination of the bunch. This is a special thanks for blog subscribers and twitter followers. To get the discount, visit my book page on...( read more )...(read more)

WPF Performance Suite

Posted: 09 Feb 2010 10:50 AM PST

Learn about the WPF performance tools for .NET 3.5.

Tell me about your services…

Posted: 09 Feb 2010 10:36 AM PST

My team has been doing a little thinking recently about the "services" space.  Basically I have been trying to figure out how folks think about accessing data and business logic across tiers.  What are the ty pes of development projects are services the core thing they are building and for what types of development projects are services simply pluming for getting the job done? I'd love to have you folks chime into this conversation.   For starters, I have posted a very simple\quick survey.    Please take 30 secs and fill it out . What statement best describes the type of work you typically do? (check all that apply) 1 - I write applications that happen to span across multiple tiers. My code runs on the web...(read more)

Quick FAQ on Visual Studio 2010 RC release (February 2010) and Silverlight development

Posted: 09 Feb 2010 07:37 AM PST

Yesterday Microsoft announced that Visual Studio 2010 Release Candidate was available for MSDN subscribers and would be generally available on 10 February 2010 for the public. This release represents a significant improvement in the overall Visual Studio Read More......(read more)

Quick FAQ on Visual Studio 2010 RC release (February 2010) and Silverlight development

Posted: 09 Feb 2010 07:37 AM PST

Yesterday Microsoft announced that Visual Studio 2010 Release Candidate was available for MSDN subscribers and would be generally available on 10 February 2010 for the public. This release represents a significant improvement in the overall Visual Studio...( read more )...(read more)

VS 2010 / .NET 4 Release Candidate

Posted: 08 Feb 2010 11:39 PM PST

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu ] This afternoon we made available the VS 2010 and .NET 4 release candidates.  You can find download links here . Right now the downloads are available only to MSDN subscribers.  Starting Wednesday (Feb 10th) everyone will be able to download them (regardless of whether you are a MSDN subscriber or not). Background on the Release Candidate I blogged about us deciding to ship a public VS 2010 release candidate last December.  The primary motivation behind releasing a public RC was to ensure that we could get broad testing and feedback on the performance and stability work we've been doing since the last...(read more)

jQuery 1.4.1 Intellisense with Visual Studio

Posted: 08 Feb 2010 10:30 PM PST

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu ] A few people have emailed me recently asking about the availability of a Visual Studio –vsdoc intellisense hint file for jQuery 1.4.1.  I blogged about –vsdoc files in the past – they provide additional intellisense help information for Visual Studio, and enable you to get a richer intellisense experience with dynamic Javascript libraries.  If you are using VS 2008 SP1 you'll want to download and install this patch in order to have VS 2008 automatically use –vsdoc files with intellisense.  VS 2010 has support for –vsdoc files built-in. jQuery 1.4.1 –vsdoc download The good news is that you can download...(read more)

SmallestDotNet Update - Now with .NET 4 support and an includable JavaScript API

Posted: 08 Feb 2010 09:44 PM PST

A few years back I wrote a post on the size of the .NET Framework . There's historically been a lot of confusion on the site of the .NET Framework. If you search around on the web for ".NET Framework" or ".NET Framework Redistributable" you'll often get a link to a 200 meg download. That download is the complete offline thing that developers redistribute when they want to install the .NET Framework on any kind of machine without an internet connection. The .NET 3.5 Client Profile is more like 28 megs and the .NET 4 Client Profile is a looking smaller that than, in fact. Back then I made this website, SmallestDotNet.com to help out. It'll sniff your browser's UserAgent and tell you want version of .NET you...(read more)

Ajax Control Toolkit (Now part of the ASP.NET Ajax Library) – Accordion Control CLOSED Startup State

Posted: 08 Feb 2010 08:47 PM PST

I get many (MANY) email from customers who are struggle to answer specific technical problems. As time permits I'm going to start answering them here, I recently received an email from a developer building an application using the Ajax Control Toolkit and he needed his page to contain an Accordion Control in which all Panes were CLOSED when the page was initially loaded. Like this …… The Accordion Control in the earliest versions of the Ajax Control Toolkit lacked this ability but now it's pretty easy. By default, the Accordion Control requires one of it's contained Panes must be open at all times. So, there are two things we need to do in our Accordion Control configuration. Configure the control so that it does NOT require at least one open...(read more)

VSDoc for jQuery 1.4.1 Now Available

Posted: 08 Feb 2010 07:07 PM PST

We finished generating a new VSDoc for the latest update of jQuery. You can download it from the jQuery Downloads page . A refresher on how to use the file can be found here or here . Happy coding! Jeff King Program Manager Visual Studio Web Tools Read More......(read more)

Answering A C# Question

Posted: 08 Feb 2010 05:17 PM PST

I often receive questions about topics covered in one or another of my books, and I respond, most often, privately. Every once in a while, however, a question comes along that may be of more general interest. This question, though about C#, has a profound...( read more )...(read more)

Learn from the Best in Web Design and Development at MIX10

Posted: 08 Feb 2010 05:43 PM PST

MIX10 favorites Scott Guthrie and Bill Buxton have been announced as keynote speakers. Come hear these experts and others speak on UX, design, Windows phone, and much more. Register by February 21st to take advantage of the US$200 discount on your pass.

U.S. MSDN Premium Subscribers: Test and Develop at No Cost on Windows Azure

Posted: 08 Feb 2010 05:43 PM PST

As an MSDN Premium Subscriber, you can leverage your MSDN subscription to obtain over 700 hours of compute time on Windows Azure to test and develop your latest cloud applications. U.S. developers can also benefit from no-cost phone and e-mail technical support to help fast-track your cloud application development by using Front Runner for Windows Azure.

Answering A C# Question

Posted: 08 Feb 2010 05:17 PM PST

I often receive questions about topics covered in one or another of my books, and I respond, most often, privately. Every once in a while, however, a question comes along that may be of more general interest. This question, though about C#, has a profound effect on Silverlight programming as well…

Question:

… I still can't figure out when I would need to create an interface when designing my application….

 

Short Answer

When you want to abstract out what is required from how that requirement is met.  

Full Answer

The short answer is correct as far as it goes, but it doesn't help at all [footnote 1]

The somewhat longer answer is to start with some of the premises of writing Clean Code:

  • Each method should be very short and do just one thing
  • Each class should have one easily articulated area of responsibility
  • Classes should know what other classes do but not how. 

Let's look at how that might play out…

You might start off by refactoring into a Note class and a FileManager class like this:

 

using System.IO; using System;  namespace Interfaces {    class Program    {       static void Main( string[] args )       {          var np = new NotePad();          np.NotePadMainMethod();       }    }     class NotePad    {       private string text = "Hello world";        public void NotePadMainMethod()       {          Console.WriteLine( "Here I would interact with you and offer you a writing surface" );          Console.WriteLine( "Then when you push the right button, I ask FileManager to " );          Console.WriteLine("print the file..." );           var fm = new FileManager();          fm.Print(text);       }    }      class FileManager    {       public void Print(string text)       {          Console.WriteLine( "I'm pretending to backup the old version of the file and then " );          Console.WriteLine( " print the text you sent me " );          Console.WriteLine( " printing {0}" , text );          var writer = new StreamWriter( @"c:\temp\HelloWorld.txt", true );          writer.WriteLine( text );          writer.Close();       }    } }            

This console program is stripped of all error checking and all three classes are in one file to keep things simple. The idea is that the NotePad class interacts with the user, obtains a string to print, and then sends it to the FileManager whose job is to see if the file exists, if so make a backup, and then write the user's text to the file (presumably we'd open a file save dialog rather than just assuming the user wants to write to c:\temp\HelloWorld.txt).

Adding A Second Writer

After creating the above, you realize that there will be times that you will want to write to, e.g., Twitter.  You could put in a branching statement:

using System.IO; using System;  namespace Interfaces {    class Program    {       static void Main( string[] args )       {          new NotePad().NotePadMainMethod();       }    }     class NotePad    {       private string text = "Hello world";                 public void NotePadMainMethod()       {          var dest = "Twitter";          switch ( dest )          {             case "File":                var fm = new FileManager();                fm.Print( text );                break;             case "Twitter":                var tm = new TwitterManager();                tm.Tweet( text );                break;          }       }    }      class FileManager    {       public void Print(string text)       {          // write to file       }    }     class TwitterManager    {       public void Tweet( string text )       {          // write to twitter       }    } }            

Adding An Interface

This begins to get ugly, and more important, the NotePad class is now entirely iStock_connectTwoWiresXSmalldependent on both the FileManager class and the TwitterManager class.  It is cleaner, easier to maintain, and far easier to test, if we remove those dependencies.

The first step in doing so is to have the NotePad not know which class will take care of writing the message; all it needs to know is that some class that knows how to "Write" will do the work.  We accomplish this by creating an interface, Writer[footnote b] that has a Write method.

 

 

   interface Writer    {       void Write(string whatToWrite);    }

We then have the FileManager and TwitterManager classes implement this interface:

   class FileManager : Writer    {       public void Write( string text )       {          // write to a file       }    }     class TwitterManager : Writer    {       public void Write( string text )       {          // write to Twitter stream       }    }

At this point, we return to the NotePad and it can instantiate the class it wants as a Writer:

      public void NotePadMainMethod()       {          var w = new TwitterManager();          w.Write( text );       }

That is step 1 in decoupling the NotePad from the other classes; now all it knows is that it has a Writer, which can be one or the other of the streams (or any other class that implements that method) but we're hard coding which implementing class to use (in this case TwitterManager) in the NotePad class… not great.

Dependency Injection

iStock_InjectionRedXSmall Dependency Injection is one of those terms you really want to work into your conversation at every conference you attend. It marks you as a cutting edge, in the know kind of geek. 

Here's how it works.  You don't want to hard-code the dependency into NotePad because that makes for code that is hard to maintain and hard to test (the technical term is "bad.")

What you can do, instead, is "inject" the dependency at run time. You can inject in a number of ways, the most common of which are:

  • Constructor injection
  • Property injection
  • Parameter injection
  • Using a Factory
  • Using an Inversion of Control (IoC) container

(Yes, IoC container may be even cooler than dependency injection. More on IoC below, but not much more)

Constructor injection just says that we'll let the Notepad know which type of writer it is going to use when we create the class:

   class NotePad    {       private string text = "Hello world";       private Writer w;       public NotePad( Writer w )       {          this.w = w;       }                 public void NotePadMainMethod()       {          w.Write( text );       }    }

Notice that we pass in an instance of Writer, stash it away in a member variable and then NotePadMainMethod just uses it.  The actual instance is not created in NotePad, it is created in whomever instantiates the NotePad and "injected" into NotePad through the constructor.

Property Injection works the same way, but instead of passing in the writer through the constructor, you set a property,

      public Writer MyWriter { get; set; }                 public void NotePadMainMethod()       {          MyWriter.Write( text );       }

Now whoever instantiates MyWriter just sets the property and NotePad can take it from there. 

Parameter Injection, as you can, by now imagine, eschews having a member variable, and just passes the type of writer into the method as a parameter

      public void NotePadMainMethod(Writer w)       {          w.Write( text );       }

Factory Pattern and IoC Containers

Each of these three approaches has its advantages, but none of them scale very well. To solve this problem, developers often turn to the Factory Pattern which allows for another level of indirection: an object that creates other objects (the factory).  We won't go into that as it isn't essential to understanding interfaces, but I will also mention that beyond the Factory, when you want the ability to "compose" your application at run time, with totally decoupled objects (that is, at run time you'll decide what writer the NotePad will use, and neither the writer nor the NotePad need depend on the other) you can then turn to Inversion Of Control (IoC) containers; a big topic covered in some detail here, and here.

The Curve, and Being Behind It

Reading Scott's great review of Alt.NET and Open Spaces and many topics related to the above; I am reminded of a cartoon in which you see a man and woman in a tree, while others are running by holding torches, and the woman says to the man, "How come it seems like everyone else is evolving but us?"

More from me on Open Spaces, Dependency Injection, Alt.Net and much else coming soon. You can join me in working through all this while creating a truly amazingly fun open source project here, the documentation for which is here.

jessesig

 

 

 

 

----

footnote 1: Old joke: two guys are in a helicopter over Washington state, and the fog comes in too fast; they are totally lost and running low on fuel.  The chopper pilot pulls up next to an office building, knocks on the window and when a man comes to the window, hollers "Where am I?"

The guy looks at him and says "You're in a helicopter" and shuts the window.

The pilot flies directly to the airport and lands safely. His passenger, stunned, asks him, "how did that help?"  "Oh," says the pilot, "I was in a life and death situation, and asked a perfectly reasonable question. He gave me an answer that was both true and totally unhelpful; so I knew right where I was: Microsoft Tech Support."

(With apologies to the terrific and truly helpful people at tech support, who will please have a sense of kajf;320 <abend>)

 

footnote b: Notice that my interface is named Writer, not IWriter.  I'd like to say that I had the courage of my convictions to stop putting the Silly I in front of every interface (IWrite, IClaudius, IThinkThereforeIAm…) but it took reading Bob Martin's wonderful book Clean Code to get me to step up.

This work is licensed under a Creative Commons license.

Silverlight Cream for February 08, 2010 -- #794

Posted: 08 Feb 2010 03:06 PM PST

In this Issue: Fons Sonnemans , Mark Monster , Karl Shifflett , Einar Ingebrigtsen ( 2 ), Jeremy Likness , Emil Stoychev , Andrew Veresov , Sergey Barskiy ( 2 ), and Tim Heuer . Shoutout: Karl Shifflett announced Karl Now Using Vimeo for Videos ... check...( read more )...(read more)

MSDN Subscribers: Download the VS 2010 Release Candidate

Posted: 08 Feb 2010 04:10 PM PST

The Visual Studio 2010 and .NET Framework 4 Release Candidate is available to MSDN subscribers on Monday, February 8th, with general availability on February 10th.

This posting includes an audio/video/photo media file: Download Now

No comments:

Post a Comment