Category: Code

To automagically pass a select option (a.k.a. DropDownBox or ComboBox) to a post action’s viewmodel using MVC.NET’s built in model binding, simply set the “name” (not the “id”) of the select element to the name of the viewmodel parameter. Make sure the option values are also being populated.  Like so:

@using (Html.BeginForm())

public class MyViewModel
    public string ItemId{ get; set; }
    public List Items{ get; set; }

ToXmlString extension method

This is an extension method that serializes any object to xml. Note that it is “null resistant” in that if the target is null, the extension does not throw an object-not-set-to-an-instance exception, but instead simply returns null.

public static string ToXmlString(this T item) where T : class
            if (item == null)
                return null;
            string xml;
            using (var stream = new MemoryStream())
            using (var writer = XmlWriter.Create(stream))
                new XmlSerializer(item.GetType()).Serialize(writer, item);
                xml = Encoding.UTF8.GetString(stream.ToArray());
            return xml;

UPDATE:  I’ve created a solution script so you can run this with a single command


If you want to quickly delete all the bin and obj folders in a solution:

  1. Make sure you have Microsoft’s Productivity Power Tools 2012 installed in your Visual Studio’s Extensions and Updates.
  2. Right-click on the solution in Solution Explorer
  3. Open Command Prompt
  4. Run powershell
  5. Paste and run this:  Get-ChildItem -include bin,obj -recu -Force | remove-item -force -recurse

FizzBuzz in one line

Subtract 10 pts if you actually implement anything like this in real life code:

using System;
using System.Linq;
namespace FizzBuzzInOneLine
    internal class Program
        private static void Main(string[] args)
            Console.Write( String.Join("\n",
                Enumerable.Range(1, 100)
                    .Select(x => (x%3 == 0) 
                        ? (x%5 == 0)
                            ? "FizzBuzz"
                            : "Fizz"
                        : (x%5 == 0)
                            ? "Buzz"
                            : x.ToString())));

Free multi-server caching from Microsoft

Caching is absolutely the most effective way to speed up the performance of an app.  However, .NET does not have a reasonable tool for caching data, such as the contents of a database table, across all servers for all users.*  There are third party tools that do this, but they are pricey.

A tool called AppFabric is available from Microsoft (for free) that spans the cache for all users across all web servers in a farm/garden/cluster.  Downside: it’s only available for current operating systems like Windows 7, Vista, and Server 2008.

If you’re interested, here are some tutorials:

  • Categories

  • Browse articles by tags

  • Archives

  • © 2014 Robert Corvus