Wednesday, December 9, 2009

A Scalable Architecture Built on Window Azure with Table Storage and AppFabric Caching

Are you interested in seeing a real-world architecture of an application on Windows Azure?  I wrote an article that details the architecture of my side project, an aggregate RSS Feed Reader called Feed Me Daily.  It shows how you can use Azure to scale your application as your audience grows.  The example architecture uses multiple web and worker roles, AppFabric Caching for its distributed caching layer, and Azure Table Storage  for its database.

Check out the Architecture of Feed Me Daily

Thursday, October 15, 2009

Ambiguous SharePoint HRESULT Exception DISP_E_EXCEPTION When Editing Web Parts; Pages Referencing a Page Layout in the Wrong Environment

This is one of those ambiguous SharePoint 2007 COM+ exceptions that kept us troubleshooting at 2am. Many different causes and symptoms produce an HRESULT error. The one I’m covering here is HRESULT 0x80020009 (DISP_E_EXCEPTION). The particular symptom that we see in this case is when we try to add a custom web part on a page that read data from pages in the Pages Library. We check in a draft of the page then add an out of the box webpart like the content editor. Either when we add the content editor, or after we try to check in any changes, we get the very nasty HRESULT Exception.

In order to get some more detail on the cause of this ambiguous SharePoint HRESULT exception, we need to turn on verbose logging, reproduce the error, then dive into the SharePoint error logs. In our case, we got the following GetFileFromUrl: ArgumentException:

10/15/2009 00:34:19.42 w3wp.exe (0x10630) 0x84C4 CMS Publishing 6wyd Medium GetFileFromUrl: ArgumentException when attempting get file Url http://stage.yoursite.com/_catalogs/masterpage/YourPageLayout.aspx Value does not fall within the expected range. at Microsoft.SharePoint.Library.SPRequestInternalClass.GetMetadataForUrl(String bstrUrl, Int32 METADATAFLAGS, Guid& pgListId, Int32& plItemId, Int32& plType, Object& pvarFileOrFolder) at Microsoft.SharePoint.Library.SPRequest.GetMetadataForUrl(String bstrUrl, Int32 METADATAFLAGS, Guid& pgListId, Int32& plItemId, Int32& plType, Object& pvarFileOrFolder) at Microsoft.SharePoint.SPWeb.GetMetadataForUrl(String relUrl, Int32 mondoProcHint, Guid& listId, Int32& itemId, Int32& typeOfObject, Object& fileOrFolder) at Microsoft.SharePoint.SPWeb.GetFileOrFolderObject(String strUrl) at Mic...

Notice the page layout URL points to staging. The site in question is in production. So the issue here is a custom webpart is reading data from a page that references a page layout from a different environment.

This happens sometimes when you manually move pages across environments using SharePoint Designer, i.e. from staging to production.

Solution

The good news is it’s easy to spot and fix this incorrect page layout referencing error.

  • In SharePoint Designer, click Task Panes -> Hyperlinks
  • In the Hyperlink pane, click the bottom "Show Internal Hyperlinks" icon (bottom icon on left side)
  • Click the "Verify Hyperlinks" icon and verify all hyperlinks (top icon on left side)
  • Sort the results by the Hyperlink column and scroll to links starting with http://
  • Look for any links referencing page layouts in an environment other than your current environment, i.e. staging when the page is in prod
  • Right click and go to Edit Hyperlink. Change the reference to the production URL and click Replace
  • Verify the changes by re-running "Verify Hyperlinks"

I really hope this helps for some of you. There are many causes to an HRESULT error in SharePoint and this is one possible solution. Be sure to leave comments below.

Big thanks to Josh Gaffey from our project team for figuring out the solution.

Wednesday, July 8, 2009

Parse the Domain from a URL String with a C# Extension Method

Many times I’ll need to parse the domain name, including the http[s]:// from a URL.  Yet there’s no straightforward way to get it using the Uri class.  This is especially useful when writing custom webparts for SharePoint.  I like to avoid using the Uri class anyway because it tends to just be a headache to use (it doesn’t serialize, you need to check for a null or empty string, object overhead, and what’s-the-point-anyway).  I wrote two C# extension methods that parse a domain from a URL string or a Uri object using Regex.

Usage

"http://bing.com/hello".AsDomain();      // => "http://bing.com"
"https://bing.com/hello".AsDomain();     // => "https://bing.com"
"http://bing.com:1234/hello".AsDomain(); // => "http://bing.com:1234"
"/hello".AsDomain();                     // => "/hello" 

I like to write methods that are forgiving, in that they don’t complain by throwing exceptions when inputs aren’t quite right.  You can use the method on an empty string, a null string, a relative domain, or even a string that’s not even a domain.  In those cases, the method just returns the input string.  This way it’s very easy to use and you don’t need to check for IsNullOrEmpty() every time.

Parse URL from a string, C# extension method

using System.Text.RegularExpressions;
namespace System
{
    public static class StringExtensions
    {
        /// <summary>
        /// Parses the domain from a URL string or returns the string if no URL was found
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string AsDomain(this string url)
        {
            if (string.IsNullOrEmpty(url))
                return url;

            var match = Regex.Match(url, @"^http[s]?[:/]+[^/]+");
            if (match.Success)
                return match.Captures[0].Value;
            else
                return url;
        }

        /// <summary>
        /// Parses the domain from a URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string AsDomain(this Uri url)
        {
            if (url == null)
                return null;

            return url.ToString().AsDomain();
        }
    }
}

Complete with Unit Tests

Just so you know it’s been tested at least a small bit.  I combine most tests into a single method because I’m lazy.  Deal with it.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringExtensionsTests
{
    /// <summary>
    ///This is a test class for StringExtensionsTest and is intended
    ///to contain all StringExtensionsTest Unit Tests
    ///</summary>
    [TestClass()]
    public class StringExtensionsTest
    {
        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        /// <summary>
        ///A test for AsDomain
        ///</summary>
        [TestMethod()]
        public void AsDomainTest1()
        {
            Assert.IsNull(((string)null).AsDomain());
            Assert.AreEqual(string.Empty, string.Empty.AsDomain());
            Assert.AreEqual("http://www.bing.com", "http://www.bing.com/hello".AsDomain());
            Assert.AreEqual("http://localhost:1234", "http://localhost:1234/hello".AsDomain());
            Assert.AreEqual("http://www.bing.com", "http://www.bing.com".AsDomain());
            Assert.AreEqual("https://www.bing.com", "https://www.bing.com/hello".AsDomain());

            Assert.AreEqual("/relative", "/relative".AsDomain());
        }

        /// <summary>
        ///A test for AsDomain
        ///</summary>
        [TestMethod()]
        public void AsDomainTest()
        {
            Assert.AreEqual("http://bing.com", new Uri("http://bing.com/hello").AsDomain());
        }
    }
}

I used this amazing online app called RegExr to build the regular expression used here.  It’s a great replacement for Expresso (my trial ran out!).  Check it out, it’s awesome.

Thursday, June 18, 2009

Parallel ForEach Loop in C# 3.5

You can take advantage of multi-core processors and execute foreach loops in parallel.  This works especially well when getting multiple chunks of data from external data sources such as a database, web service, or RESTful API.  I designed this after the upcoming parallel features coming in .NET 4.0, but for now they’re in beta and I’ve had trouble using them.  So this method is a simple implementation of it.

Usage (not that this example makes any sense…)

string[] names = { "cartman", "stan", "kenny", "kyle" };
names.EachParallel(name =>
{
    Console.WriteLine(name);
});

Of course you’ll probably want some exception handling to prevent the threads from aborting if an exception occurs.

string[] names = { "cartman", "stan", "kenny", "kyle" };
names.EachParallel(name =>
{
    try
    {
        Console.WriteLine(name);
    }
    catch { /* handle exception */ }
});

Here is the source

Update: Added special handling for the case when the enumerable only contains one element.  It just executes the method directly (in serial) to avoid the overhead of creating a thread and using the WaitHandle, since that will essentially execute it in serial anyway.

Update: Some systems have a cap of 64 threads that you can track with WaitHandle.  An anonymous developer posted a solution in the comments.  I integrated his changes and made some modifications.  It breaks up the enumerable into 64-item chunks and processes those items in parallel.

/// <summary>
/// Enumerates through each item in a list in parallel
/// </summary>
public static void EachParallel<T>(this IEnumerable<T> list, Action<T> action)
{
    // enumerate the list so it can't change during execution
    list = list.ToArray();
    var count = list.Count();

    if (count == 0)
    {
        return;
    }
    else if (count == 1)
    {
        // if there's only one element, just execute it
        action(list.First());
    }
    else
    {
        // Launch each method in it's own thread
        const int MaxHandles = 64;
        for (var offset = 0; offset <= list.Count() / MaxHandles; offset++)
        {
            // break up the list into 64-item chunks because of a limitiation 
// in WaitHandle
var chunk = list.Skip(offset * MaxHandles).Take(MaxHandles); // Initialize the reset events to keep track of completed threads var resetEvents = new ManualResetEvent[chunk.Count()]; // spawn a thread for each item in the chunk int i = 0; foreach (var item in chunk) { resetEvents[i] = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback((object data) => { int methodIndex = (int)((object[])data)[0]; // Execute the method and pass in the enumerated item action((T)((object[])data)[1]); // Tell the calling thread that we're done resetEvents[methodIndex].Set(); }), new object[] { i, item }); i++; } // Wait for all threads to execute WaitHandle.WaitAll(resetEvents); } } }

Saturday, June 13, 2009

ASP.NET Data Caching Helper Extension Method

Sometimes ASP.NET output caching doesn’t do the trick and you need to implement data caching to avoid trips to the database or to external API’s.  Data caching is pretty simple- check the cache via a cache key and if the data doesn’t exist, get it and store it in the cache.  The code you’ll write to implement that pattern is simple, but instead of copy and pasting each time you need to use cache, why not write an extension method to help out?

Here’s the typical pattern to implement data caching

// get from cache
var items = context.Cache[cacheKey] as IEnumerable<Foo>;
if (items == null)
{
    // get from database
    items = GetData();

    // insert into cache
   context.Cache.Insert(cacheKey, items, null, DateTime.Now.AddSeconds(cacheSeconds), 
Cache
.NoSlidingExpiration); }

Here’s data caching with my helper extension method

// get from cache
var items = context.Cache.Data(cacheKey, cacheSeconds, () =>
{
    return GetData();
});

Data caching extension method source

I wrote a simple extension method that caches the return value of a method (you can use a lambda expression here).  It prepends the hash code of that method to the cache key to isolate a method’s set of cached data.  I wrote this to be thread safe, although you’ll need to make sure your method is thread safe as well.

namespace System.Web.Caching
{
    public static class CacheExtensions
    {
        static object sync = new object();

        /// <summary>
        /// Executes a method and stores the result in cache using the given cache key.  
If the data already exists in cache, it returns the data
/// and doesn't execute the method. Thread safe, although the method parameter
isn't guaranteed to be thread safe.
/// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache"></param> /// <param name="cacheKey">Each method has it's own isolated set of cache items,
so cacheKeys won't overlap accross methods.
</param> /// <param name="method"></param> /// <param name="expirationSeconds">Lifetime of cache items, in seconds</param> /// <returns></returns> public static T Data<T>(this Cache cache, string cacheKey,
int expirationSeconds, Func<T> method) { var hash = method.GetHashCode().ToString(); var data = (T)cache[hash + cacheKey]; if (data == null) { data = method(); if (expirationSeconds > 0 && data != null) lock (sync) { cache.Insert(hash + cacheKey, data, null, DateTime.Now.AddSeconds
(expirationSeconds), Cache.NoSlidingExpiration); } } return data; } } }

Saturday, May 16, 2009

LINQ: Select an object, but change some properties without creating a new object

Q: Using LINQ, if I wanted to perform some query and return the object from the query, but change only some of the properties in that object, how would I do this without creating a new object and manually set every property? Is this possible?

Example:

var list = from something in someList
           select x; // but change one property

This post is based off of my Stack Overflow post on the same topic.

You can do it via the LINQ extension methods pretty easily, as JaredPar answered:

var query = someList.Select(x => { x.SomeProp = "foo"; return x; })

But what if you wanted to use declarative syntax similar to my above example?  You could write a simple extension method to do that.   Example usage:

// select some monkeys and modify a property in the select statement
// instead of creating a new monkey and manually setting all properties
var list = from monkey in monkeys
           select monkey.Set(monkey1 =>
           {
               monkey1.FavoriteFood += " and banannas";
           });

This is much quicker and more concise than creating a new monkey object and manually setting all properties, like so:

// instead of
var list = from monkey in monkeys
           select new Monkey
           {
               Name = monkey.Name,
               FavoriteFood = monkey.FavoriteFood += " and banannas",
               FavoriteBeer = monkey.FavoriteBeer,
               FavoriteActivity = monkey.FavoriteActivity,
               EyeColor = monkey.EyeColor,
               HairColor = monkey.HairColor,
               LikesToFlingPoo = monkey.LikesToFlingPoo
               // etc...
           };

Answer: Write an extension method.  I wrote an extension method called Set that to facilitate this.  All it does is allow you to write a lambda expression inside your select statement that returns the same object that you pass it.  You can set any number of properties on that object without creating a new instance of it.  Here’s the source code:

namespace System.Linq
{
    public static class LinqExtensions
    {
        public delegate void Updater<TSource>(TSource updater);

        /// <summary>
        /// Used to modify properties of an object returned from a LINQ query
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="input"></param>
        /// <param name="updater"></param>
        /// <returns></returns>
        public static TSource Set<TSource>(this TSource input, 
Updater<TSource> updater) { updater(input); return input; } } }

Tuesday, April 28, 2009

Ensure Latest Javascript & CSS in Browser Cache in ASP.NET MVC

Each time you update your website’s Javascript and CSS files through a deployment, there’s a good chance returning visitors will use their outdated cached copy of those files.  All web browsers cache Javascript & CSS files for good reason – performance.  The browser is supposed to ask the server if the version they have is the latest copy, but often the browser doesn’t ask or this just doesn’t work.  Bottom line: if users are using an outdated version of Javascript or CSS, things won’t work or look right for them.   It’s a big deal but there’s an easy fix.

The solution is to append a string to the querystring of your Javascript and CSS files that changes every time you build your project.  This tells the browser that the file is different and it should go and get the new version.  A good way to do this is to use the hash of your web project.  You want to use the hash instead of the version number in case your project doesn’t use automatic versioning.

Here are two HTML helper method for those of you using ASP.NET MVC:

Update: We now pass in a type in order to make a hash of its assembly.  Since you’ll use this from a markup page, the calling assembly is automatically generated so users will get the files more often than needed.

using System;
using System.Reflection;
using System.Text;

namespace System.Web.Mvc
{
public static class HtmlExtensions
{
    /// <summary>
    /// Renders a Javascript script include tag and appends the assembly's hash code as a querystring to the file 
    /// to ensure users load the latest code file when the code is updated.
    /// </summary>
    /// <param name="type">Pass a type so we can make a hash of its assembly.  This should be a class in your web project.</param>
    public static string JavascriptInclude(this HtmlHelper html, Type type, params string[] urls)
    {
        var sb = new StringBuilder();
        var hash = type.Assembly.GetHashCode();
        foreach (string url in urls)
            sb.AppendLine(string.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}?{1}\"></script>",
                url, hash));
        return sb.ToString();
    }

    /// <summary>
    /// Renders a CSS include tag and appends the assembly's hash code as a querystring to the file
    /// to ensure users load the latest code file when the code is updated.
    /// </summary>
    /// <param name="type">Pass a type so we can make a hash of its assembly.  This should be a class in your web project.</param>
    public static string CssInclude(this HtmlHelper html, Type type, params string[] urls)
    {
        var sb = new StringBuilder();
        var hash = type.Assembly.GetHashCode();
        foreach (string url in urls)
            sb.AppendLine(string.Format("<link rel=\"Stylesheet\" type=\"text/css\" href=\"{0}?{1}\" />",
                     url, hash));
        return sb.ToString();
    }
}
}

Usage:

<head runat="server">
    <%= Html.CssInclude(typeof(MyController),
        "/content/site.css",
        "/content/openid.css") %>


<%= Html.JavascriptInclude(typeof(MyController), "/scripts/openid-jquery.js", "/scripts/jquery.simplemodal-1.2.2.min.js", "/scripts/site.js") %> </head>

Output:

<head>
    <link rel="Stylesheet" type="text/css" href="/content/site.css?5462907" />
    <link rel="Stylesheet" type="text/css" href="/content/openid.css?5462907" />

    <script language="javascript" type="text/javascript" src="/scripts/openid-jquery.js?5462907"></script>
    <script language="javascript" type="text/javascript" src="/scripts/jquery.simplemodal-1.2.2.min.js?5462907"></script>
    <script language="javascript" type="text/javascript" src="/scripts/site.js?5462907"></script>
</head>

Thursday, April 23, 2009

Using jQuery to Read JSON Returned from an MVC Controller Method

It’s easy to return a complex C# object from an MVC controller as JSON for your client-side JavaScript to consume.  Just use the Json() method of the Controller class to serialize your C# object to JSON and return it as an ActionResult.  You can use jQuery to wire up the AJAX and call the controller method via HTTP GET or POST using $.get() and $.post() respectively.  The trick is to set the type parameter of the jQuery AJAX method that you’re using to ‘json’.  This will tell jQuery to expect JSON as the response data and deserialize/evaluate it as JavaScript.  Check it:

jQuery Javascript:

$.get('/MyController/GetSomething, { name: 'value' },
    function(data) {
        alert(data.Name);
    },
    'json'); // Set the type to 'json'!

MVC Controller C#:

public ActionResult GetSomething(string name)
{
    return Json(new
    {
        Name = name,
        Description = "hey!"
    });
}

 

Wednesday, February 18, 2009

C# Parallelism: Executing Methods in Parallel in .NET 3.5

To fully take advantage of multi-core processors and to speed up response times, developers have to embrace parallel design patterns.  Most of the code we write today is in serial; we execute one method after another in a linear fashion.  There are some pretty advanced libraries available to us thanks to the .NET Framework (e.g. ThreadPool, Thread), but for many reasons they are under utilized.

Coming in .NET 4.0 with Visual Studio 2010, we will get a whole new library that will allow us to easily take advantage of parallelism in our apps -- without drastically changing the code structure.  I think this is the biggest selling point here.  The .NET wizards at Microsoft took a look at the structure of our existing code and figured out some intuitive and non-intrusive ways for us to leverage parallel execution.  This article has a very thorough explanation of the new classes.

For now, we can use existing classes like ThreadPool, Thread, and BackgroundWorker to execute code in multiple threads, which in turn should be processed in parallel from the multiple cores available on the system.

I've written a simple helper method that will execute chunks of code in parallel using ThreadPool.  You can use the method in pretty much the same way as the Parallel.Do() method coming in .NET 4.0.  So once you're on 4.0, just swap out the method calls.

Example usage:

ParallelProcessor.ExecuteParallel(()=>
{
    // Get some data
}, ()=>
{
    // get some different data
}, ()=>
{
    // get some data from a web service
});

// do something else after all of the delegate methods have completed

Here is code for ExecuteParallel:

public class ParallelProcessor
{
    public delegate void Method();

    /// <summary>
    /// Executes a set of methods in parallel and returns the results
    /// from each in an array when all threads have completed.  The methods
    /// must take no parameters and have no return value.
    /// </summary>
    /// <param name="m"></param>
    /// <returns></returns>
    public static void ExecuteParallel(params Method[] methods)
    {
        // Initialize the reset events to keep track of completed threads
        ManualResetEvent[] resetEvents = new ManualResetEvent[methods.Length];

        // Launch each method in it's own thread
        for (int i = 0; i < methods.Length; i++)
        {
            resetEvents[i] = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>
            {
                int methodIndex = (int)index;

                // Execute the method
                methods[methodIndex]();

                // Tell the calling thread that we're done
                resetEvents[methodIndex].Set();
            }), i);
        }

        // Wait for all threads to execute
        WaitHandle.WaitAll(resetEvents);
    }
}

Thursday, February 12, 2009

Designing a LINQ to SQL Application's Data Access Layer

I've been playing around with various designs to a DAL that uses LINQ to SQL in one of my side projects.  Before LINQ, I would usually create a set of data manager classes that would perform CRUD operations on a database and return custom business entities.  We have to modify this model when using LINQ to SQL though.  First I'll show the example DAL code and usage, when I'll explain my approach for designing the DAL and go through the benefits.

Using Extension Methods on Table<Entity> objects to create DAL Data Manager classes

My approach to writing a DAL for LINQ to SQL is to write Extension Methods on the Table<Entity> properties that are already exposed on your DataContext.  These extension methods perform CRUD operations and return IEnumerable<Entity> or Entity where appropriate.  These extension methods replace the traditional data manager classes.

Simple Example Usage:

db.Products.GetByID(productID);
db.Products.GetPopular(page, pageSize);

Real-World Example Usage:

using (SlackLabsDataContext db = new SlackLabsDataContext())
{
    // load with features and sort them by popularity
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<Product>(p => p.Features);
    options.AssociateWith<Product>(p => p.Features.OrderByDescending(f => f.Rank).ThenByDescending(f => f.CreatedOn);
    db.LoadOptions = options;

    // popular products
    ProductsRepeater.DataSource = db.Products.GetPopular(page, pageSize);
    ProductsRepeater.DataBind();

    // get other products with the same load options in the same Data Context
    // ...
}

Example Implementation:

namespace LinqDalExample
{
    public static class ProductExtensions
    {
        /// <summary>
        /// Gets a Product by its ID
        /// </summary>
        public static Product GetByID(this Table<Product> products, int productID)
        {
            if (productID < 0)
                throw new ArgumentOutOfRangeException("productID");
            
            return products.Single(p => p.ID == productID);
        }

        /// <summary>
        /// Gets Products sorted by popularity and skip to the correct page
        /// </summary>
        public static IEnumerable<Product> GetPopular(this Table<Product> products, int page, int pageSize)
        {
            return (from p in products
                    where p.IsPublished
                    orderby p.Rank descending, p.CreatedOn descending
                    select p).Skip(page * pageSize).Take(pageSize);
        }

Benefits

  • Follows a traditional DAL pattern of using a set of "manager" classes to retrieve data in custom business entities or sets of entities
    • ex: db.Products.GetPopular();
    • The code reads very logically; we are getting popular products from a database
    • All LINQ statements that query the database are centralized in these extension classes
    • Reuses the Table<Entity> properties that are already exposed on your DataContext
  • You can use the same context to make multiple db calls
  • Control Eager Loading from the front-end instead of hard-coding it into the DAL since this is where we'll know what data we'll need
    • ex: We have 2 web forms that consume the GetPopular method.  Only one page needs to get product features.  We can set the proper eager loading options on that one page and use a common GetPopular method in the DAL.  Otherwise we'd need multiple DAL methods: GetPopular and GetPopularWithFeatures.  We wouldn't be able to use the same data context this way.
  • Maintain Deferred Execution on LINQ queries
    • Database is queried only when the data is needed, ex: on DataBind() or other methods which will call Enumerate on the set
    • You can modify the query on the front end.  Ex: to implement paging or limit the result set
    • Return IEnumerable instead of List or Array for flexibility
      by using extension methods on the table class, we are 'querying' on the table, which seems very logical

Feedback

I'd like to hear your opinion on this approach.  Has anyone found another pattern that works well for them?  Have you found any issues with this approach?

Friday, January 23, 2009

Get a Filename from a Path in Javascript

Here's a quick Javascript function that will parse the filename from a path using regex.  It looks for any letter or digit, hyphen, or underscore followed by a dot (.) followed by a letters or numbers for the extension.

function getFileName(path) {
    return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

Wednesday, January 21, 2009

Using LINQ to Serialize a C# Object into JSON

Here's the problem: You have a complex object and you need to serialize it into JSON (JavaScript Object Notation).  But your client code only needs one of the properties.  So why serialize the whole thing?

The solution: LINQ to Objects + JavaScriptSerializer

With LINQ, you can very easily create an array of strings from one property of the complex object.  Notice the 'var' keyword - the variable type is determined at compile time.  This requires .NET 3.5.

Check it out:

class People
{
    public string Name { get; set; }
    public string OtherData { get; set; }
}

void CreateNamesJavascript()
{
    List<People> people = new List<People>();
    people.Add(new People() { Name = "Bobby Chaz" });
    people.Add(new People() { Name = "Omar" });

    // build an array of names with LINQ
    var names = from person in people
                select person.Name;

    // serialize the names to JSON
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string json = jss.Serialize(names);

    LiteralControl script = new LiteralControl();
    script.Text = string.Format(string.Format(@"<script language=""javascript"" type=""text/javascript"">
        <!--
        var names = {1};
        //-->
        </script>", json));

    Controls.Add(script);
}

Notice the LINQ code (from...select).  It's very compact and elimates the need to declare a list, create for loops, etc just to get the array we want.  You can also wrap the from..select statement in parenthesis and call .ToArray(), .ToList(), etc.

Next we use JavaScriptSerializer to convert the array to JSON.

Here's the output:

<script language="javascript" type="text/javascript">
<!--
var names = ["Bobby Chaz","Omar"];
//-->
</script>
I highly recommend playing around with LINQ to Objects and LINQ to XML.  It's very cool and very progressive.

Saturday, January 17, 2009

jQuery Form Input Hints Plugin

Use this script to automatically display hints on input textboxes in your forms. It uses the amazing jQuery library. I converted the script into a jQuery plugin called Form Input Hints to make it more flexible.

Update: I created an open source project on CodePlex to host the project. You can download the source with a demo there. I encourage anyone who would like to add to the functionality or change the code to do so in the project & commit your changes. I'll monitor the activity and create releases after testing.

Check it out:

Usage:

<input type="text" title="Hint Text!" />

$(document).ready(function() {
   $('input[title]').inputHints();
});

Download from CodePlex: http://jqueryhints.codeplex.com (includes minified, debug, & demo)

Alt Download: jquery.inputhints.js (debug) jquery.inputhints.min.js (minified)

Here is the Input Hints jQuery Plugin code:

jQuery.fn.inputHints = function() {
   // hides the input display text stored in the title on focus
   // and sets it on blur if the user hasn't changed it.

   // show the display text
   $(this).each(function(i) {
       $(this).val($(this).attr('title'));
   });

   // hook up the blur & focus
   $(this).focus(function() {
       if ($(this).val() == $(this).attr('title'))
           $(this).val('');
   }).blur(function() {
       if ($(this).val() == '')
           $(this).val($(this).attr('title'));
   });
};

Wednesday, January 7, 2009

Visual Studio 2008 Keyboard Shortcuts

Here are some extremely helpful keyboard shortcut keys for Visual Studio 2008. You probably know most, but some you won't know. For instance, did you know that Ctrl+. is the same as Sift+Alt+F10?

Note: Some of the shortcuts won't work in all environment configurations (web, C#, etc).

To use, hold down the control key and hit the key combination. Works on the whole document, a specific line, or a selection of code.

Go to Definition (F12) Navigate to the definition of the method or variable. Super useful.

Find all References (Shift + F12)

Update References/ Add Using Statement (Ctrl +. or Shift +Alt +F10) I'm referring to the underline that appears under a variable to perform an action like add a using statement, or refacter a method or class name. Not sure what it's called but I use it all the time. Ex: ClassName

List Members (Ctrl +J or Ctrl +K, L) Displays the autocomplete list for classes, methods, or properties.

List Parameter Info (Ctrl +Shift +Space or Ctrl +K +P) Lists the parameters for a method. Use this shortcut when your cursor is inside the parenthesis of a method.

Auto Format (Ctrl +K, D or Ctrl +E, D) Formats C#, VB, ASPX, Javascript, CSS, XML, XSL, and HTML code according to generally accepted formatting standards for the respective programming language. Makes code look nice and neat.

Quick Watch (Ctrl +Alt +Q) Highlight some code and hit these shortcut keys to display the Quick Watch dialog.

Comment / Uncomment (Ctrl +K, C / Ctrl +K, U) Comments or uncomments a block of code. Works with C#, VB, ASPX.

Code Bookmarks Use these to bookmark a line of code. You can cycle through the bookmarks across any file within a project. Bookmarks come in very handy, try it out.

Set/Unset Bookmark (Ctrl +K, K) Next Bookmark (Ctrl +K, N)

Surround With (Ctrl +S) Surrounds a block of code with a code snippet.

Build & Debug Shortcuts Set/Unset Breakpoint (F9) Build (F6 or Ctrl +Shift +B) Start Debugging (F5) Start Without Debugging (Ctrl +F5) Stop Debugging (Shift +F5) Continue (F5) Step Over (F10) Step Into (F11) Step Out (Shift +F11) Attach to Process (Ctrl + Alt + P)

That's it for now, feel free to add more in the comments below. I'll try to update this post periodically.