Jan
31
2013

Excellent set of JSON samples

Check out this site for a break set of JSON samples.

 

Some information from the site:

 

Over 100 code samples covering Json.NET's most commonly used functionality.

Samples

  • Serializing JSON - Serializing and deserializing JSON, serializer settings and serialization attributes
  • LINQ to JSON - Parsing, querying, modifying and writing JSON
  • JSON Schema - Loading schemas and validating JSON
  • Converting XML - Converting JSON to XML and XML to JSON
  • BSON - Serializing and deserializing BSON
  • Reading and Writing JSON - Reading JSON with JsonTextReader, writing JSON with JsonTextWriter
May
31
2012

An extension method to convert a flat collection to a Hierarchical collection

This is a report from here...

 

A while ago I posted an article about LINQ to SQL and WPF treeviews. I demonstrated how to use multiple levels in treeviews and how to group data with LINQ. One interesting subject wasn't covered, namely self referencing tables or the adjacency list model. A WPF TreeView control does not support this. That is why I created a LINQ extension method to convert a flat collection to a hierarchical structure of nested collections which can be assigned to the ItemsSource of a WPF Treeview.

 

 

 

 

Adjacency model / self referencing table

 

Hierarchies like trees, organizational charts, ... are sometimes difficult to store in database tables. The most common database pattern to store hierarchical data is known as the adjacency model. It has been introduced by the famous computer scientist Edgar Frank Codd. It's called the "adjacency" model because a reference to the parent data is stored in the same row as the child data, in an adjacent column. These kind of tables are also called self referencing tables.

 

Let's crystalize this by displaying the Employees table in the Northwind database.

 

EmployeeIDLastNameFirstNameReportsTo
1 Davolio Nancy 2
2 Fuller Andrew null
3 Leverling Janet 2
4 Peacock Margaret 2
5 Buchanan Steven 2
6 Suyama Michael 5
7 King Robert 5
8 Callahan Laura 2
9 Dodsworth Anne 5

 

In this table, the child is the same kind of row as the parent. The ReportsTo column is a foreign key referencing the EmpNo column. So each employee has a reference to his/her boss.

 

If you want to use this data in a WPF TreeView, then you have to convert the adjacency list model to a hierarchical model/nested set model. This should be the result :

 

EmployeeIDLastNameFirstNameReportsToDepth
2 Fuller Andrew null 1
      1 Davolio Nancy 2 2
      3 Leverling Janet 2 2
      4 Peacock Margaret 2 2
      5 Buchanan Steven 2 2
            6 Suyama Michael 5 3
            7 King Robert 5 3
            9 Dodsworth Anne 5 3
      8 Callahan Laura 2 2

 

In SQL Server 2005 you can use CTE (Common Table Expressions) and a recursive function to query this kind of data. And SQL Server 2008, which will be released one of the next months, will provide a new SQLCLR datatype called HierarchyID which will support manipulating and querying hierarchical data. Besides these database features, I wanted to create a .NET solution which can be used to convert a flat collection to a hierarchical structure of nested collections. Next steps will describe how I implemented the LINQ AsHierarchy extension method.

 

 

 

GetEmployeesHierarchy() method

 

I first started creating a new EmployeeHierarchy class. This class contains an Employee entity (the boss) and a collection of child employees.

public class EmployeeHierarchy
{
  public Employee Employee { get; set; }
  public IEnumerable<EmployeeHierarchy> Employees { get; set; }
}

 

In .NET 3.5 we have LINQ at our's disposal. So I created a recursive GetEmployeesHierachy function which will start with the director (who does not have to report to anyone, ReportsTo = null) and query all employees which are working for him (ReportsTo == EmployeeId of boss). This will be repeated recursively. Finally this function will return a collection of EmployeeHierarchy objects.

 

public IEnumerable<EmployeeHierarchy> GetEmployeesHierachy(IEnumerable<Employee> allEmployees, Employee parentEmployee)
{
  int? parentEmployeeId = null;
 
  if (parentEmployee != null)
    parentEmployeeId = parentEmployee.EmployeeID;
 
  var childEmployees = allEmployees.Where(e => e.ReportsTo == parentEmployeeId);
 
  Collection<EmployeeHierarchy> hierarchy = new Collection<EmployeeHierarchy>();
 
  foreach (var emp in childEmployees)
    hierarchy.Add(new EmployeeHierarchy() { Employee = emp, Employees = GetEmployeesHierachy(allEmployees, emp) });
 
  return hierarchy;
}

 

This function can be called after a LINQ to SQL or LINQ to Entities (Entity Framework) query. Make sure to call the ToList() extension method. It is much more performant to first load all data from the database and then convert it to a hierachical structure. By calling the ToList() method all references to the database will be removed.

 

NorthWindDataContext dc = new NorthWindDataContext();
 
var employeesHierarchy = GetEmployeesHierachy(dc.Employees.AsEnumerable(), null);
 
treeViewEmployees.ItemsSource = employeesHierarchy;

 

AsHierarchy() extension method

 

Previous routines did work fine but I wanted a more generic solution. My motto is "do more with less code" so I created a HierarchyNode<T> class and a LINQ AsHierarchy() extension method which uses generics and anonymous functions (=Func delegates). This method will return an IEnumerable collection of generic HierarchyNode<T> objects.

 

This is the source code which does all the magic. Just copy it to one of your own projects.

using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ScipBe.Common.LinqExtensions
{
  // Stefan Cruysberghs, http://www.scip.be, March 2008
 
  /// <summary>
  /// Hierarchy node class which contains a nested collection of hierarchy nodes
  /// </summary>
  /// <typeparam name="T">Entity</typeparam>
  public class HierarchyNode<T> where T : class
  {
    public T Entity { get; set; }
    public IEnumerable<HierarchyNode<T>> ChildNodes { get; set; }
    public int Depth { get; set; }
  }
 
  public static class LinqExtensionMethods
  {
    private static System.Collections.Generic.IEnumerable<HierarchyNode<TEntity>> CreateHierarchy<TEntity, TProperty>
      (IEnumerable<TEntity> allItems, TEntity parentItem, 
      Func<TEntity, TProperty> idProperty, Func<TEntity, TProperty> parentIdProperty, int depth) where TEntity : class
    { 
      IEnumerable<TEntity> childs;
 
      if (parentItem == null)
        childs = allItems.Where(i => parentIdProperty(i).Equals(default(TProperty)));
      else
        childs = allItems.Where(i => parentIdProperty(i).Equals(idProperty(parentItem)));
 
      if (childs.Count() > 0)
      {
        depth++;
 
        foreach (var item in childs)
          yield return new HierarchyNode<TEntity>() { Entity = item, ChildNodes = CreateHierarchy<TEntity, TProperty>
            (allItems, item, idProperty, parentIdProperty, depth), Depth = depth };
      }
    }
 
    /// <summary>
    /// LINQ IEnumerable AsHierachy() extension method
    /// </summary>
    /// <typeparam name="TEntity">Entity class</typeparam>
    /// <typeparam name="TProperty">Property of entity class</typeparam>
    /// <param name="allItems">Flat collection of entities</param>
    /// <param name="idProperty">Reference to Id/Key of entity</param>
    /// <param name="parentIdProperty">Reference to parent Id/Key</param>
    /// <returns>Hierarchical structure of entities</returns>
    public static System.Collections.Generic.IEnumerable<HierarchyNode<TEntity>> AsHierarchy<TEntity, TProperty>
      (this IEnumerable<TEntity> allItems, Func<TEntity, TProperty> idProperty, Func<TEntity, TProperty> parentIdProperty)
      where TEntity : class
    {
      return CreateHierarchy(allItems, default(TEntity), idProperty, parentIdProperty, 0);
    }
  }
}

AsHierarchy() examples

Call the AsHierachy() method and pass the Id/Key and the ParentId/Key of the entity as anonymous functions. As you can see, it really is that simple.

NorthWindDataContext dc = new NorthWindDataContext();
 
var hierachy = dc.Employees.ToList().AsHierarchy(e => e.EmployeeID, e => e.ReportsTo);
 
treeView1.ItemsSource = hierarchy;

 

Within each level of the hierarchical tree the original order will be preserved. So it is possible to use the LINQ OrderBy and OrderByDescending extension methods.

var hierachy = dc.Employees.OrderByDescending(e => e.LastName).ToList().
  AsHierarchy(e => e.EmployeeID, e => e.ReportsTo);

 

Of course this extension method will also work with anonymous classes.

var hierachy = (from e in dc.Employees
               select new { Id = e.EmployeeID, FullName = e.FirstName + " " + e.LastName, ParentId = e.ReportsTo }).ToList()
               AsHierarchy(e => e.Id, e => e.ParentId);

 

AsHierarchy() in LINQPad

External extension methods can also be used in LINPad. Go to Query >> Advanced Properties and add a reference to the assemby which holds the AsHierachy extension method. Don't forget to add the name of the namespace at the tabsheet Additional Namespace Imports.

LINQPad will show you a nice representation of the hierarchical structure.

 

 

 

Display hierarchy with WPF TreeView

Binding a collection of generic HierarchyNode<T> objects to a WPF TreeView is quite easy. Just set the ItemsSource of the HierarchicalDataTemplate to ChildNodes. Now the TreeView will recursively display all HierarchyNode<T> objects. Make sure you use the fixed name Entity in the binding of the template.

<TreeView Name="treeView1">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=ChildNodes}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Entity.FirstName}"></TextBlock>
                <TextBlock Text=" "></TextBlock>
                <TextBlock Text="{Binding Path=Entity.LastName}"></TextBlock>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

 

his is how the TreeView will look like :

Once you have the data in the TreeView it is up to you to give it a nice visual representation. Take a look at the Custom TreeView Layout in WPF article of Josh Smith who demonstrates how to render a TreeView as an organizational chart. I already copied his XAML example and this is how my Employees tree will be displayed :

Let's summerize this article :

  • Copy the source of the AsHierarchy() extension method to your project
  • Add a TreeView control and define a HierarchicalDataTemplate which uses the ChildNodes and Entity properties in your XAML file
  • Call the AsHierarchy() method with the id/key and parentid/key in a LINQ to Objects, LINQ to SQL or LINQ to Entities query
  • Assign the result query to the ItemsSource of the WPF TreeView

I hope you like this LINQ extension method and that you can take advantage of this free code.

New improvements and a LINQ to SQL (IQueryable) version can be found in a more recent article.

 

Sep
28
2011

WSDL Contract First Development

Couple of good articles for Contract First Development

 

WSDL-First development for WCF

http://blogs.msdn.com/b/dotnetinterop/archive/2008/09/24/wsdl-first-development-with-wcf.aspx

 

WSCF - Web Service ContractFirst

http://www.thinktecture.com/resourcearchive/tools-and-software/wscf/wscf-walkthrough

 

thinktecture WSCF.blue (set of good tools)

http://wscfblue.codeplex.com/

 

Handcrafting WCF-frieldly WSDLs

http://blogs.msdn.com/b/donsmith/archive/2006/10/06/handcrafting-wcf_2d00_friendly-wsdls.aspx

Sep
23
2011

A couple of great resources for Developer Cheat Sheets

Here are a couple of great sites that supply cheat sheets

http://john-sheehan.com/blog/net-cheat-sheets/

http://devcheatsheet.com/

http://www.addedbytes.com/cheat-sheets/

 

Here are a couple of specific links to cheat sheets

http://duartes.org/gustavo/articles/Asp.net-Runtime-Cheat-Sheet-HttpRequest-HttpRuntime.aspx

 

And here are a bunch of cheat sheets all in one place for you to grab :)

 

aspnet-lifecycle-events-poster.pdf (60.92 kb)

aspnet-lifecycle-events-poster.png (96.79 kb)

aspnet-mvc-lifecycle-poster.pdf (489.01 kb)

css-v2-cheat-sheet.pdf (315.28 kb)

dotnet-string-formatting-cheet-sheet.pdf (123.71 kb)

HTML5-cheat-sheet.pdf (148.82 kb)

html-character-entities-cheat-sheet.pdf (958.89 kb)

javascript-cheat-sheet-v1.pdf (452.93 kb)

jquery-1.4-cheat-sheet.pdf (436.00 kb)

jquery-1.6-cheat-sheet.pdf (347.90 kb)

linq-cheat-sheet.doc (69.00 kb)

microformats-cheat-sheet.pdf (603.49 kb)

msajax-client-lifecycle-events-cheat-sheet.pdf (101.83 kb)

python-cheat-sheet.pdf (388.90 kb)

regular-expressions-cheat-sheet.pdf (647.55 kb)

rgb-hex-cheat-sheet.pdf (198.65 kb)

ruby-on-rails-cheat-sheet.pdf (752.11 kb)

sql-server-cheat-sheet.pdf (937.46 kb)

subversion-cheat-sheet.pdf (292.49 kb)

wpf-cheat-sheet.pdf (38.51 kb)

xhtml-cheat-sheet.pdf (71.99 kb)

Aug
16
2011

How to use InternalsVisibleTo with strong named assemblies

 

Routinely I am forgetting how to do this :) So to make life easier I am writting up a blog posting. 

When writting unit tests for VS2008/VS2010 you will may find yourself needing to access internals.  While it is possible to use the "_Accessor" classes, this is not always a friendly way to write tests (especially for complex objects and operations)

To that end, there is a nice and easy way (once you jump through a copy of configuration hoops) to handle this and that is via the "InternalsVisibleTo" attribute that lives at the assembly level.

I usually place my in the AssemblyInfo.cs file

 

[assembly: InternalsVisibleTo("MyProject.Tests")]

 

Now the trick comes when your assembly is signed with a Strong Name.  When this is the case, you will most likely receive the following error when you attempt to compile:

 

Error: "Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations"

To fix this, we must do two things.  The first is that you must sign the test assembly, and the second is that you must include the public key in the InternalsVisibleTo statement. 

To get the public key value from the .snk file, use the sn.exe utility included in the .NET SDK. You must do two things, first, create a .snk file that contains only the public key:

 

sn -p MyKey.snk MyKey.PublicKeyOnly.snk

Then, you can extract the public key value with this command:

 

sn -tp MyKey.PublicKeyOnly.snk

This will produce a similar output:

Public key is

0024000004800000940000000602000000240000525341310004000001000100cfb8bc23b86a08e70d021dd53d3b0293e716e71015870bdcc58a0231a4228618851a83e06077f5a44f42beb2baf356ad2d344521a96b0081ed0f25f9227523e3625eda524efe1cf2e1e5e41f3693a76ec52347684b8129a4bb2d5fc49681adf33da0eecc4f81f011af4539d12abe1b4e760b5ce32d766db1012d44028381f0b4

Public key token is 2ff2b71993eeff95

Once you get this, copy the public key value (the really long one) and update the InternalsVisibleTo:

 

[assembly: InternalsVisibleTo("MyProject.Tests,  PublicKey=0024000004800000940000000602000000240000525341310004000001000100cfb8bc23b86a08e70d021dd53d3b0293e716e71015870bdcc58a0231a4228618851a83e06077f5a44f42beb2baf356ad2d344521a96b0081ed0f25f9227523e3625eda524efe1cf2e1e5e41f3693a76ec52347684b8129a4bb2d5fc49681adf33da0eecc4f81f011af4539d12abe1b4e760b5ce32d766db1012d44028381f0b4")]

Voila! You can now access the internals from your test project for strong named assemblies.

May
23
2011

StickOut: A Desktop Sticky Notes Application in the .NET Framework 2.0

Summary: StickOut is a desktop sticky note with multi-user support and Outlook integration. As a .NET Framework 2.0 Windows Forms application, it uses .NET Remoting to communicate with other StickOut users and exchange sticky notes with them. (85 pages)

Download the associated StickOut.msi code sample.

Original Article: http://msdn.microsoft.com/en-us/library/aa480731.aspx

Mar
8
2011

C# Enum Flags Attribute Use

Good article on enum flags for C# 

You want to use enum flags to assign and check multiple constant values, and switch on these enums. Enum flags are a powerful but limited way to deal with combinations of enums. In this article, we process enum flags with bitwise operators, and then switch on those flags, using the C# language.

Using enum flags

The [Flags] attribute on an enum allows you to assign multiple values to your enum at once. You can do this with bitwise manipulations, meaning you can store an enum with A and C set, not just A and not just C. This approach has benefits in some cases, but also problems.

~~~ Program that uses [Flags] (C#) ~~~

using System;

class Program
{
    [Flags]
    enum RenderType
    {
        None = 0x0,
        DataUri = 0x1,
        GZip = 0x2,
        ContentPage = 0x4,
        ViewPage = 0x8,
        HomePage = 0x10 // Next two values could be 0x20, 0x40
    }

    static void Main()
    {
        // 1.
        // Set the first type.
        RenderType type1 = RenderType.ContentPage;

        // 2.
        // Set the second type if the condition matches.
        if (true)
        {
            type1 |= RenderType.GZip;
        }

        // 3.
        // Check the enum flags.
        Check(type1);

        // 4.
        // Set a new enum in three statements.
        RenderType type2 = RenderType.ViewPage;
        type2 |= RenderType.DataUri;
        type2 |= RenderType.GZip;

        // 5.
        // See if the enum contains this flag.
        if ((type2 & RenderType.DataUri) == RenderType.DataUri)
        {
            Console.WriteLine("True");
        }

        // 6.
        // See if the enum contains this flag.
        if ((type2 & RenderType.ContentPage) == RenderType.ContentPage)
        {
            throw new Exception();
        }

        // 7.
        // Check the enum flags.
        Check(type2);
    }

    static void Check(RenderType type)
    {
        // Switch on the flags.
        switch (type)
        {
            case RenderType.ContentPage | RenderType.DataUri | RenderType.GZip:
                {
                    Console.WriteLine("content, datauri, gzip");
                    break;
                }
            case RenderType.ContentPage | RenderType.GZip: // < first match
                {
                    Console.WriteLine("content, gzip");
                    break;
                }
            case RenderType.ContentPage:
                {
                    Console.WriteLine("content");
                    break;
                }
            case RenderType.ViewPage | RenderType.DataUri | RenderType.GZip: // < second match
                {
                    Console.WriteLine("view, datauri, gzip");
                    break;
                }
            case RenderType.ViewPage | RenderType.GZip:
                {
                    Console.WriteLine("view, gzip");
                    break;
                }
            case RenderType.ViewPage:
                {
                    Console.WriteLine("view");
                    break;
                }
            case RenderType.HomePage | RenderType.DataUri | RenderType.GZip:
                {
                    Console.WriteLine("home, datauri, gzip");
                    break;
                }
            case RenderType.HomePage | RenderType.GZip:
                {
                    Console.WriteLine("home, gzip");
                    break;
                }
            case RenderType.HomePage:
                {
                    Console.WriteLine("home");
                    break;
                }
        }
    }
}
~~~ Output of the program ~~~ content, gzip True view, datauri, gzip

Overview of the example. This example shows an enum with six bit flags in it. Note how the word [Flags] appears on top of the enum, with the square brackets. This is an attribute that tells .NET to allow you to assign the enum with bitwise operators.

Attribute Tips and Examples

Description of the enum values. The values 0x0, 0x1, 0x2, 0x4 and so on indicate powers of two. In computer bits, powers of two contain one bit set, moving from the first bit to the final bit. You could use the decimal values, 0, 1, 2, 4, 8... instead.

Description of Main entry point. The Main method here has several example steps. First it declares a new RenderType enum and assigns the RenderType.ContentPage value. This is the same as you would use a normal enum.

Setting an enum flag. The |= operator next actually adds a flag to the enum, so the enum now contains two flag bits. You can use |= to add bits, while & will test bits without setting them.

Description of switch method. The method Check is the final part of the example. It shows how you can switch on enum flags. This is very useful because it allows you to act on combinations of the flags in a constant-time expression. The switch statement here is faster than other constructs. Note how the | operator is used in the cases; this simply means the values are combined.

Steps 5 and 6. These two steps show how you can test your enum with flags using the & bitwise AND operator. You have to check the result of & with the actual enum flag again.

Understanding bitwise AND, bitwise OR

Bitwise AND, which you use with &, returns a value with 1 in the targeted bit if both values contain the bit. Therefore, you can AND two values together and test the result for the target bit. Bitwise OR, which you use with |, returns 1 in the bit if either value has it set. This means it can be used in the switch, setting all bits in the | expressions.

Binary Representation for Integer

Benefits of switch on enum flags

When you are using enum flags, you are concerned about performance. The switch compiles to a jump table which is lots faster than if/else chains. I could not find other examples on the Internet that use the flags in a switch.

Switch Enum

Limitations

Unfortunately, using bitwise flags on your enum has severe limitations. It can help improve certain code that has few flags that are often combined. However, you cannot extend your enum flags nearly as much as a regular enum. Therefore, if you need 100 enum values, or may need that many in the future, you should use separate integer enums.

Summary

Enum flags are a versatile and powerful way to represent more complex constants and combinations. Here we saw how you can use bitwise flags with your enums in the C# language. The example shows how you can assign, add, set, check, and switch on your enum with the [Flags] attribute. We also looked at the flaws in this approach and how it can limit the development of your code.

Enum Overview

Attribute Overview