Reduce nesting from null checking by using null coalescing operator

Quite often in code I have this.

var groups = data.GetGroups();
if(groups != null) {
// work some magic
}

Yesterday I realized I could made the code a little cleaner, by using the null coalescing operator.

var groups = data.GetGroups();
groups = groups ?? new List<Group>();
// work some magic

This may not be useful in all cases, but is helpful when you don’t care if the return value is null, and a null will break your code.  And it is definitely better than not checking at all :)

Fix ASP.NET MVC 2 Blank Pages and Debugging Errors

My environment is Windows 7 with Visual Studio 2010 RTM.  I’m using IIS as my development web server instead of Casini.

If you get an error like “unable to start debugging on the web server” when trying start your site using F5, make sure DOTNET 4 is registered with IIS.

%windir%\Microsoft.NET\4.0.x\aspnet_regiis -i

I had this problem, because I installed Visual Studio 2010 before IIS.

Next if you just get 404 errors or blank pages when trying to navigate through your site, make sure the following settings in the IIS setup under “Turn Windows features on or off” are selected:

Internet Information Services -> World Wide Web Services -> Common HTTP Features -> HTTP Errors

Internet Information Services -> World Wide Web Services -> Common HTTP Features -> HTTP Redirection

Internet Information Services -> World Wide Web Services -> Common HTTP Features -> Static Content

This HTTP Redirection and Static Content are especially important.  ASP.NET MVC 2 won’t work at all without HTTP Redirection and when selecting ASP.NET under Application Development Features Static Content isn’t enabled by default.

Anyway I hope this helps somebody.

UPDATE: Make sure you also have the Application Pool set to DefaultAppPool.

MVVM is the New Code Behind

I’ve been working with WPF and by extension MVVM over the last month or two, and to be honest it has been no less than painful.  What used to be simple is now hard, although many things are now possible that perhaps were not before without more effort.  That being said this post mainly about MVVM and how it appears to be more like a fresh new version of code behind.  The basis for my conclusion is that the ViewModel although it allows for “unit testing” ui code, it does not facilitate code reuse.  I personally am I big proponent of unit testing, but that doesn’t necessarily mean others feel the same.  Therefore I cannot judge the merit of MVVM solely based on testability, although in many cases that can be a good measure.  My main issue with MVVM is in the area of code reuse.

Let’s say I have a UI defined for executing a calculation:

:UI
     :Input<TextBox>
     :Result1<TextBox>
     :Result2<TextBox>
     :Calc<Button>

If I were you use MVVM I would need a ViewModel defined like so:

:ViewModel
     :Input<string>
     :Result1<string>
     :Result2<string>
     :Calc()
          :Perform a complex 20 line calculation
          :Set Result1 = calculated result1
          :Set Result2 = calculated result2

Notice the Calc method is pretty complex and to update the view I just need to set Result1 and Result2 equal to my calculated result1 and result2 and all will update nicely.  But let’s say I would like to use that complex 20 line Calc function somewhere else, say in a web app, or in a silverlight app.  It would make sense to me to create an object like so:

:Calculator
     :Input<string>
     :Result1<string>
     :Result2<string>
     :Calc()
          :Perform a complex 20 line calculation
          :Set Result1 = calculated result1
          :Set Result2 = calculated result2

Then the ViewModel would be refactored to this.

:ViewModel
     :Input<string>
          :set()
               :calculator.Input = value
          :get()
              :return calculator.Input
     :Result1<string>
          :get()
              :return calculator.Result1
     :Result2<string>
          :get()
              :return calculator.Result2
     :Calc()
          :calculator.Calc()

Ok so that isn’t so bad, but here is the problem.  Calling calculator.Calc() updates the internal state of the Calculator object.  Part of that change involves updating calculator.Result1 and calculator.Result2, so that the internal state can be read from the object and reflected in the UI.  The problem is how does the ViewModel know that calculator.Result1 and calculator.Result2 have been updated?  There is no way to hook the ViewModel’s Result1 and Result2 to the calculator.Result1 and calculator.Result2.  As far as I can tell the general MVVM implementation doesn’t account for this scenario and would need to be handled using some sort of eventing or other implementation between the Model and the ViewModel.  It is the complexity introduced by this disconnect that leads me to conclude that the ViewModel is just another business logic silo, much like code behind of old in both WebForms and WinForms.  Yes you can now unit test your code behind, but it is code behind nonetheless.

UPDATE1: Similar Post The MVVM Pattern Is Highly Overrated

Visual Studio Themes

Just thought I would shared a link to site I thought was really cool.  It allows you to download Visual Studio themes as well as easily create one using a really cool editor.

Check it out.

http://studiostyles.info

Also here is a link to my current Visual Studio 2008 theme if you would like to check it out.

New Blog Up

I’ve never liked the fact that my domain randallsutton.net has the suffix .net instead of .com, so I’ve decided to move my blog to a new domain I aquired a while back randallbits.com.  I’m going to try and import all my posts and redirect all the links, but for now you can update your readers and such.

Can you solve this?

There is an interesting problem I solved today that I thought I might share.  The basic idea can be solved by figuring out how to solve the following problem.

Consider this JavaScript
funcs = []
for(var i=0;i<10;i++)
       funcs[i] = function() { alert(i); }
funcs[4]();

This will alert "10".  Can you change it to alert "4"?  The key to solving this problem is being able to create a function that stores i and then will evaluate the alert later.

Also
funcs[0] alerts "0"
funcs[1] alerts "1"

funcs[9] alerts "9"

Get the idea?  Good luck!

Get Values Out of a Dictionary Using Reflection in C#

As part of the project I’m currently working on I had the need to get all the values out of a dictionary without the benefit of typing, so I had to use reflection.  Here is the best was I’ve been able to come up with and hopefully it is useful to others.

    1 

    2 private void GetDictionaryValues(object obj)

    3 {

    4     var t = obj.GetType();

    5 

    6     // Handle dictionaries.

    7     if (typeof(IDictionary).IsAssignableFrom(t))

    8     {

    9         // Get the methods we need to deal with dictionaries.

   10         var keys = t.GetProperty("Keys").GetGetMethod().Invoke(obj, null);

   11         var item = t.GetProperty("Item");

   12         var enumerator = keys.GetType().GetMethod("GetEnumerator").Invoke(keys, null);

   13         var moveNext = enumerator.GetType().GetMethod("MoveNext");

   14         var current = enumerator.GetType().GetProperty("Current").GetGetMethod();

   15 

   16         // Get all the values.

   17         while ((bool)moveNext.Invoke(enumerator, null))

   18         {

   19             var key = current.Invoke(enumerator, null);

   20             var value = item.GetValue(obj, new object[] { key });

   21 

   22             // Do Stuff.

   23         }

   24     }

   25 }

   26 

Better JavaScript Object Creation

So I’ve decided that I don’t like the two general ways of creating objects in JavaScript so I’ve decided to create my own.  This one is partially inspired by ruby :)

    1 

    2 Hello = function() {

    3     return {

    4         new: function(a,b) {

    5             return {

    6                 one: a,

    7                 two: b,

    8                 talk: function() {

    9                     alert(‘hello: ‘ + a + ‘ ‘ + b);

   10                 }

   11             };

   12         }

   13     }

   14 }();

   15 

I am using the object literal notation to create the object.  Generally this notation works well until you want multiple instances of the object you are creating.  This is why I have added the new method.  This new method acts as a constructor and will return a function.  This function creates a closure and so all the properties (one,two) and methods (talk) will be unqiue to each “instance”.

So usage would be like this:

world = Hello.new(‘my’,’world’);
universe = Hello.new(‘my’,’universe’);

alert(world.b); // “world”
alert(world.talk()); // “hello: my world”
alert(universe.b); // “universe”
alert(universe.talk()); // “hello: my universe”

As you can see each “instance” is unique.  What makes this instance unique is that you are actually not dealing with the Hello object directly, but with the new function on the hello object.  It is important to place everything inside the new function so that all the variables and functions will be unqiue to each instance.

Good luck!

Dramatically Improve ASP.NET Compile Time for Less Than $1500

One thing that really bothers me is a slow compile time.  A slow compile time causes me to do other things when compiling, which in turn causes a loss of focus.  Basically a context switch I wish to avoid.  So the other day I decided to try out an SSD drive to see if I could get an improvement, because I thought that my hard drive was the bottleneck.  My results were rather interesting.

First I would like to say that I work on a very large solution with a very large (7000+ files) ASP.NET website.  A few months ago I converted our IIS website project to a Web Application Project.  That caused our build time to go from about 5 minutes to around a minute or so.  That was a huge improvement, but we still had issues with that one minute.  The reason was because in addition to the one minute lag time caused by the build, when you went to any page for the first time you got a hesitation while the page was being compiled.  The reason this happens is the Web Application Project doesn’t fully compile the pages using the aspnet_compiler.  So for us the bottleneck is the execution of the aspnet_compiler.  For this reason I chose to use our build script as the benchmark test.  The build script spends about 80% of its time fully compiling our website using the aspnet_compiler.  All of the results are given using this benchmark.

The result before I decided to start my testing varied between programmers, but the general case outside myself was the build took about 400-500 seconds.  My machine was taking about 320s.  The main reason for that was my machine had 4 250G 7400 rpm drives in a RAID 0 with an Adaptec RAID card.  With this in mind I thought for sure the bottleneck was hard drive, but that wasn’t necessarily the case.

Here are my results:

The first two machines were brand new reasonably priced and powerful machines with a 7200 RPM hard drive.

Core 2 Quad 2.53 (350s) with SSD (270s)

Core 2 Quad 2.83 (280s) with SSD (230s)

This made me realize that the combination of CPU and Hard Drive made a difference, so I took this to the next level.  I ordered an i7 960 and I already had 2 10,000 rpm raptors so I threw those into the mix as well.

i7 960  Raptor (180s) with Raptor RAID 0 (160s) with SSD (190s)

As  you can see the raptor appeared to be beating my SSD drive and was really screaming in RAID 0.  The strange thing though was that the OS didn’t feel as good with the Raptors as with the SSD even when they were in a RAID 0.  The other thing that didn’t make sense was that the windows experience index on the drives didn’t seem to match the performance I was getting.

Raptor RAID 0 (5.9)

SSD (7.1)

That made me wonder if there was something going on when I used the onboard Intel ICH controller vs the standard IDE interface with the SSD drive, so I decided to turn on the RAID but use the SSD drive as a non-RAID disk.  This yielded much better results.

i7 960 SSD using ICH controller (155s)

Much better.  The windows experience nudged up a bit to 7.4 as well.  It appears that the standard ide controller had a bottleneck that wasn’t allowing me to take full advantage of the SSD drive.  I also tried two SSD drives in a RAID 0 and ended up with 150s and the windows experience index ticked up to 7.7, so not much of an improvement for the price.

The moral of the story is that the combination of CPU and Hard Drive are key to getting your compile times down, and the best part is that this modification costs less than $1500 from newegg.

Below I have listed the links to the hardware I used.  Hopefully this post has been useful.

CPU – http://www.newegg.com/Product/Product.aspx?Item=N82E16819115216
CPU Cooler – http://www.newegg.com/Product/Product.aspx?Item=N82E16835103055
RAM – http://www.newegg.com/Product/Product.aspx?Item=N82E16820104132
Motherboard – http://www.newegg.com/Product/Product.aspx?Item=N82E16813131365
HD – http://www.newegg.com/Product/Product.aspx?Item=N82E16820227469

NOTE: I had a 550W power supply and for now this seems to work.  It does run a little warm so it wouldn’t hurt to have a better one, but I wouldn’t recommend anything less than 550W.

NOTE2: The selection of SSD drive is very important.  I chose the OCZ Vertex Turbo, because it had sustained writes of 100 MB/s as opposed to the normal drive at 70 MB/s.  The Intel drive also rates at 70 MS/s, so be careful.  The bigger drives are more expensive, but they seem to perform even better according to the specs so if you can get a bigger drive go for it.  I would recommend going with one bigger drive as opposed to 2 smaller ones in a RAID 0, because I saw almost no improvement in RAID 0 with the SSDs.

Embedded IronRuby and IronPython in Silverlight with Multiple Source Files

I have yet to find a simple clear example of using multiple files when embedding IronPython or IronRuby in Silverlight, so I decided to share an example I have been working on.

NOTE: During testing have found this does not work with 0.91 or 0.92 of the DLR.  I guess there is a bug with imports and it should be fixed any day now.  Go here and click all releases to get 0.90 of the IronRuby and IronPython dlls.

Here is the code in my MainPage.xaml.cs:

    public delegate string pyFunc(string s);
    public delegate IronRuby.Builtins.MutableString rbFunc(string s);
 
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
 
            pythonblock.Text = DoPython();
            rubyblock.Text = DoRuby();
        }
 
        private string DoPython()
        {
            var setup = Python.CreateRuntimeSetup(null);
            setup.HostType = typeof(BrowserScriptHost);
 
            var runtime = new ScriptRuntime(setup);
            var engine = Python.GetEngine(runtime);
            var scope = engine.CreateScope();
 
            var mscope = engine.CreateScope();
            var module = engine.CreateScriptSourceFromFile("module1.py");
            module.Execute(mscope);
 
            runtime.Globals.SetVariable("module1", mscope);
 
            var source = engine.CreateScriptSourceFromFile("main.py");
            source.Execute(scope);
 
            var func = scope.GetVariable<pyFunc>("hello");
 
            return func("world");
        }
 
        private string DoRuby()
        {
            var setup = new ScriptRuntimeSetup();
            setup.HostType = typeof(BrowserScriptHost);
            setup.AddRubySetup();
 
            var runtime = new ScriptRuntime(setup);
            var engine = Ruby.GetEngine(runtime);
            var scope = engine.CreateScope();
 
            var mscope = engine.CreateScope();
            var module = engine.CreateScriptSourceFromFile("module1.rb");
            module.Execute(mscope);
 
            runtime.Globals.SetVariable("module1", mscope);
 
            var source = engine.CreateScriptSourceFromFile("main.rb");
            source.Execute(scope);
 
            var func = scope.GetVariable<rbFunc>("hello");
 
            return func("world");
        }
    }

Here are the source files:

main.py:

import module1
 
def hello(s):
    return module1.f1('python hello ' + s)
 

module1.py:

def f1(s):
    return 'python f1: ' + s

main.rb:

require "module1"
 
def hello(s)
    f1('ruby hello ' + s)
end
 

module1.rb:

def f1(s)
    'ruby f1: ' + s
end

 

I hope this is helpful and if anyone has any suggestions for improvement please let me know.