<charliedigital /> Programming, Politics, and uhh…pineapples

13Jul/100

HTML-ifying Text in SharePoint

Posted by Charles Chen

This has probably been done to death, but here's my version of how to "HTML-ify" HTML text in SharePoint calculated fields into rendered HTML using jQuery:

var htmlPattern = /[^<]*<([^ ]+)[^<]+<\/\1>.*/;
var ltPattern = /&lt;/g;
var gtPattern = /&gt;/g;
 
$(selectors).each(function(index, item){
    var html = $(item).html().replace(ltPattern, "<").replace(gtPattern, ">");

    if(!htmlPattern.test(html)) { return; }

    $(item).html(html);
});

Perhaps the most interesting part of this script is the regular expression used to capture the HTML tag. Unlike other versions I've seen, it easily handles any HTML tag and will match-and-replace even elements that don't start and end with HTML tags (your content can have leading and trailing text or other HTML). This is exceedingly useful if your calculated field contains textual content or if you need to HTML-ify some string that is rendered in say the newsletter list style.

Specify your selectors wisely to minimize the number of elements to scan.

Here it is again in a "best practices" format hooked up to a simple namespace:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title> Sample HTMLIFY </title>
        <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            // Create a simple namespace.
            var my = {};

            // Define the util class.
            function util() {
                var htmlPattern = /[^<]*<([^ ]+)[^<]+<\/\1>.*/;
                var ltPattern = /&lt;/g;
                var gtPattern = /&gt;/g;

                return {
                    // The main function which takes a set of jQuery selectors.
                    htmlify: function(selectors) {

                        $(selectors).each(function(index, item){
                            var html = $(item).html()
                                .replace(ltPattern, "<")
                                .replace(gtPattern, ">");

                            if(!htmlPattern.test(html)) { return; }

                            $(item).html(html);
                        });
                    }
                }
            }

            // Instantiate the object.
            my.util = new util();

            // Convert to rendered HTML
            $(document).ready(function() {
                my.util.htmlify(".text1, .text2");
            });
        </script>
    </head>

    <body>
        <div class="text1">This is some HTML text &lt;a href=""&gt;a link&lt;/a&gt;</div>
        <div class="text2">This is some HTML text &lt;a href=""&gt;a link&lt;/a&gt; 
            <span style="background:green">This text is in a span</span></div>
        <div class="text2">This is some HTML text &lt;span style="background:red"&gt;some text&lt;/span&gt;</div>
    </body>
</html>

You should be able to copy/paste that and run it.

Filed under: Dev, SharePoint No Comments
5Apr/101

jsTree and Nested XML Data Stores

Posted by Charles Chen

I happened upon jsTree a few months back while searching for a solid jQuery based tree.

Without a doubt, it is one of the most well implemented and functional Javascript trees I've used with perhaps the most powerful feature being the built-in support for client-side XML representations of the tree and the ability to add arbitrary metadata to the tree using the Sarissa library.

While the tree itself is extremely powerful, some of the documentation is actually out of date and made my implementation of the tree a bit more tasking than it should have been.

For example, the option for initializing the tree with a static XML string (as demonstrated here) actually requires using staticData instead of static in the latest version.  Adding metadata to the tree is also made far more complicated by the documentation and examples I found online.

In reality, the datastore implementation for the nested XML support is powerful enough to extract arbitrary DOM attributes (online posts seem to indicate that you need to use the custom metadata plugin and/or the jQuery metadata plugin).  You can see in the sample below, that I set the attribute "md" to an encoded JSON string (you'll want to do this for when you reload the tree as a Javascript string) and then retrieve the value as a part of the XML by specifying the attributes to collect:

/*--- test adding data ---*/
$("#test").click(function() {
    var t = $.tree.focused();

    if (!t.selected) {
        return;
    }

    /*--- sets a person on the node ---*/
    var person = {
        "FirstName": $("#firstName").val(),
        "LastName": $("#lastName").val(),
        "Age": $("#age").val() 
    };

    var serialized = JSON.stringify(person);

    /*--- sample of adding an arbitrary attribute at the DOM level ---*/
    t.selected.attr("md", encodeURI(serialized));

    /*--- ...and how to retrieve it in XML ---*/
    var opts = {};
    opts.outer_attrib = ["id", "rel", "class", "md"];

    var xml = t.get(null, "xml_nested", opts)

    $("#xml-d").text(xml);
    $("#treeXml").val(encodeURI(xml));              
});

In real usage, you'd assign some more meaningful values to the metadata and save it.  I find that with a library like this, it's probably easier to just save the whole XML string and that's simple enough by just pushing the XML to a hidden input before submitting the form (as I've done in the last line).

Mahr Mohyuddin has a much more complex and more generic implementation of ASP.NET integration here, but I think that might be more complexity than is needed.  In practice, it makes more sense to use full JSON objects on the client side (as I've used above) and embed them into the attribute and then, using the JavaScriptSerializer class, extract the objects into domain objects on the server side.  Here's an example:

string xmlString = Uri.UnescapeDataString(treeXml.Value);

XDocument xml = XDocument.Parse(xmlString);

// Get all the <items/>.
var items = from x in xml.Descendants()
            where x.Name == "item"
            select x;

List<Person> people = new List<Person>();

JavaScriptSerializer serializer = new JavaScriptSerializer();

// Resolve the paths and Person instances.
foreach(var item in items) {
    string[] parts = item.AncestorsAndSelf()
        .Select(a => a.Descendants("name").First().Value)
        .Reverse().Skip(1).ToArray();

    string path = string.Join("/", parts);

    if(item.Attribute("md") == null) {
        continue; // Next iteration.
    }

    string serializedPerson = 
        Uri.UnescapeDataString(item.Attribute("md").Value);

    Person p = serializer.Deserialize<Person>(serializedPerson);
    p.OrgPath = path;

    people.Add(p);
}

_people.DataSource = people;
_people.DataBind();

Nothing fancy here; the only thing of note is the little LINQ query to resolve the node path (may or may not be useful).

The Person class is also very simple and barebones:

using System;

namespace JsTreeSample {
    /// <summary>
    /// Models a person.
    /// </summary>
    /// <remarks>
    /// Serializable to support deserialization from JSON.
    /// </remarks>
    [Serializable]
    public class Person {
        private string _orgPath;
        private int _age;
        private string _firstName;
        private string _lastName;

        public string FirstName {
            get { return _firstName; }
            set { _firstName = value; }
        }

        public string LastName {
            get { return _lastName; }
            set { _lastName = value; }
        }

        public int Age {
            get { return _age; }
            set { _age = value; }
        }

        public string OrgPath {
            get { return _orgPath; }
            set { _orgPath = value; }
        }
    }
}

The full project is included.  Some usage notes: select a node first and then enter a first name, last name, and age.  Then click "Set Data" to create a Person object at the node (this will also show the full XML of the tree).  Then click Submit to send the data (displays in a repeater).

JsTreeSample.7z (144.07 KB)

Definitely check out jsTree for your next project; it's amazingingly versatile and rich in functionality.

Filed under: Dev, DevTools 1 Comment
19Feb/101

FluentNHibernate And NHibernate.Linq

Posted by Charles Chen

Just a little blurb on FluentNHibernate and NHibernate.Linq.

I've been working through the samples for FNH and decided to try out some different query scenarios to see how the queries would be generated. I stumbled a bit on the first rather simple scenario: selecting an item based on the total count of related items. In this case, from the FNH demo, I wanted to select "all stores with more than 2 employees". Seems like a simple enough query, right?

You can see from the full code that this should return "Bargain Basement". However, in going through the documentation, it wasn't exactly apparent how this could be done; it seemed a lot more convoluted than necessary using criteria queries and it simply wasn't working. Via Google, I came across a blog post that mentioned using either DetachedCriteria or HQL. Quite frankly, neither was very appealing.

So I figured I'd download NHibernate.Linq and see if it would be better. Not knowing what I would get, SQL-wise, I wrote the following query:

using (session.BeginTransaction())
{
    IQueryable<Store> stores = from s in session.Linq<Store>()
                               where s.Staff.Count > 2
                               select s;

    foreach (Store store in stores)
    {
        Console.WriteLine("STORE: {0}", store.Name);
    }
}

Of course, the interesting question is whether the the Staff list would be loaded to perform the count and to my pleasant surprise, it was not. Here's the query in profiler (reformatted for legibility):

exec sp_executesql N'
    SELECT 
        this_.Id as Id1_0_, 
        this_.Name as Name1_0_ 
    FROM 
        [Store] this_ 
    WHERE 
        @p0 <   (
                SELECT 
                    count(staff1_.Id) as y0_ 
                FROM [Store] this_0_ 
                    left outer join [Employee] staff1_ 
                        on this_0_.Id=staff1_.Store_id 
                WHERE 
                    this_.Id = this_0_.Id
                )',N'@p0 int',@p0=2

Sweet! The framework correctly builds a sub-select query to count the staff members.

I guess I'm just easy to impress :-) but I'm digging it.

I think what I like about FluentNHibernate the most is that I can stop building database applications. What I mean by this is an application built from the database up. The main issue this raises is complexity with regards to mapping to a data layer and of course continuously having to synchronize your DDL and SQL with your class files. The following code configures the database, including dropping and creating the tables based on mapping classes in my assemblies:

private static ISessionFactory CreateSessionFactory()
{
    return Fluently.Configure()
        .Database(
        MsSqlConfiguration.MsSql2008.ConnectionString(
            @"Data Source=SCOOBY;Initial Catalog=FluentNHDemo;
            Integrated Security=SSPI;Application Name='FNHDemo'"))
        .Mappings(m =>
                  m.FluentMappings.AddFromAssemblyOf<Store>())
        .ExposeConfiguration(BuildSchema)
        .BuildSessionFactory();
}

private static void BuildSchema(Configuration config)
{
    // this NHibernate tool takes a configuration (with mapping info in)
    // and exports a database schema from it
    SchemaExport schema = new SchemaExport(config);

    schema.Drop(false, true); // Drops the tables only.
    schema.Create(false, true);
}

With no mapping files to speak of, persistence plumbing becomes trivial and I can work entirely within Visual Studio. Of course, for complex queries and queries that need to be highly performant, you may still be better off writing stored procedures (as I've advocated in the past), but the productivity gains to be had can't be ignored and I find the compile-time validation of the queries eases some of my indifference towards dynamic SQL.

Filed under: .Net, Dev 1 Comment
5Feb/102

Paging With SPListItemCollectionPosition

Posted by Charles Chen

Let it be known that Microsoft's terrible design of list paging is inexecusable and to make matters worse, the documentation is practically non-existent. You would think that paging with a SPQuery would be a piece of cake! I mean, I write paged data queries all the time.

NOT!

Colby Africa has a good overview of the issues and some basics that gave me some good insight into the core issues. Of course, the difficulty with the SPQuery and paging isn't really with going forward, it's with going backwards. One MSDN poster suggested storing the previous pages (see the last post here), which when you think about it, isn't a really good solution given the amount of paging strings you'd have to store (you can't just store the last navigation since going "Previous" twice requires going back twice).

Since going forward is the easy part, I won't get into that. With regards to paging to previous pages, I hacked around a bit and spent a good 2-3 hours trying to deduce how the paging query string worked before I finally figured it out.

The algorithm works like so:

  1. When paging FORWARD, capture the ID <AND SORT FIELD VALUE> of the first item on the newly retrieved result collection.
  2. When paging BACKWARDS, use the previously captured ID <AND SORT FIELD VALUE> of the first item on the current result collection to generate the paging string.
  3. Once paged BACKWARDS, capture the ID <AND SORT FIELD VALUE> of the first item on the loaded page for the next BACKWARDS operation (just leave this off of the input query if going forwards again).

By capture, I mean to store the data and persist the data somehow (perhaps in the ViewState or SessionState).

And there you have it: three simple steps :-D

As an example, consider the following data set, sorted by Title:

ID		TITLE
---------------------------PAGE 1
17		Apple
21		Banana
18		Currant
---------------------------PAGE 2
19		Durian
5		Elderberry
1		Fig
---------------------------PAGE 3
7		Guava
10		Honey Dew
12		Indian Gooseberry

Consider a scenario where we're building a web application. After the result set for page 3 of the data is loaded, I want to capture three pieces of data if I want to be able to load the previous page:

  1. The value of the ID of the FIRST item on the page
  2. The value of the TITLE of the FIRST item on the page (or whatever field you are sorting on)
  3. The PagingInfo string after the query is executed

The PagingInfo is already set for paging foward again. When I page backwards, I will need to generate a new query using the PagingInfo. To do so, I will need to:

  1. Replace the p_ID and set it to p_ID=7
  2. Replace the p_Title and set it to p_Title=Guava (replace p_Title with the static name of your sort field)
  3. Add two parameters:
    1. PagedPrev=TRUE
    2. PageLastRow=6 (last index of the second page, where we're going - this is easily calculated if you know your page size and your current page (keep these in the ViewState))

I used the following two regular expression patterns:

Regex _pidPattern = new Regex("p_ID=(?'pid'\\d+)");
Regex _pTitlePattern = new Regex("p_Title=[^&]+");

To replace the values in the string like so:

pagingInfo = _pidPattern.Replace(pagingInfo,
	string.Format("p_ID={0}", firstItemId));
pagingInfo = _pTitlePattern.Replace(pagingInfo,
	string.Format("p_Title={0}", firstTitle));

In this case, if I'm on page 3, the string for going back to page 2 should be:

Paged=TRUE&PagedPrev=TRUE&p_ID=7&p_Title=Guava&PageLastRow=6

And once I'm on page 2, the string required to go back to page 1 should be:

Paged=TRUE&PagedPrev=TRUE&p_ID=19&p_Title=Durian&PageLastRow=3

Well, actually, you don't need the string to go back to page 1; but this is just to give you the general idea. In summary, the trick is pretty simple: you always need to store the PageInfo string for paging SharePoint queries and when you retrieve a resultset, you want to capture the ID and sort field of the first item. When you go forward, the PageInfo string is enough. When you go backwards, you need to use the captured pieces of info.

Hope that this has shed some light on the otherwise nebulous paging functionality with SharePoint list queries!

Filed under: .Net, Dev, SharePoint 2 Comments
26Jan/102

Simple (?) AJAX Upload For ASP.NET

Posted by Charles Chen

As I was working on an AJAX upload web part for SharePoint, I looked around to see if there was anything out there that would be suitable before I rolled my own after discovering that the ASP.NET UpdatePanel doesn't play nicely with file inputs. Since I'm using jQuery, I figured I'd start there and see if there were any plugins which would meet the need.

To my dismay, it seems as if kids these days are all using flash (flash!) to implement asynchronous upload. This was wholly unacceptable to me for some reason (not to mention it might cause compatibility issues for downstream clients) so I ended up tackling it myself :-D

The basics of getting this to work are simple enough; the solution is made of three main components:

  1. The main page that is displaying the upload control. Since I was using this in a SharePoint site, I wanted to write my uploader as a web part (the control) that could be placed on any page. The main page is simply the container for your control. It does not post back.
  2. The control that basically just renders the <iframe/>. The control is relatively simple. It provides a container for the <iframe/> and also the scripts which are executed when the frame is loaded and unloaded. The control also holds the progress layer since we want this to be shown when the user starts the upload. This also does not post back.
  3. The upload page that receives the actual file. This page is the target for the <iframe/> and contains the logic that validates the posted file. This is the only page that posts back.

Before we go into the details, let's look at the screens of this in action (pay particular attention to the times):

The first screen shows the general layout of the page in the default state. In case you're wondering, I found a handy guide for hacking the file input control and used that to customize the appearance. Again, note the time.

Once you click "Upload", a progress layer is shown over the control. You can also see that we've got an unloaded time now as well.

And finally, you can see that the loaded time changed once the form upload completes.

The control ASCX file contains two very simple scripts:

    function handleFrameLoaded() {
        // Do animation here.
        $("#progress").hide();

        $("#load").html("<b>Loaded!</b> " + 
            (new Date()).toTimeString());
    }

    function handleFrameUnloaded() {
        // Do animation here.
        $("#progress").show().fadeTo("fast", .90);

        $("#unload").html("<b>Unloaded!</b> " + 
            (new Date()).toTimeString());
    }

The first function is called when the frame is loaded and the second function is invoked when the file upload is submitted. Note that both functions are called from the upload page in the <iframe/>. In this case, I've just added simple animation calls to show and hide a progress panel. You can hook up whatever custom code you want here.

On the upload page itself, we need to wire the events to the functions above:

    $(window).load(function() {
        parent.handleFrameLoaded();
    });

    $(document).ready(function() {
        $(".upload-button").click(function() {
            parent.handleFrameUnloaded();
        });

        /* simulate hover */
        $("#fake-container").hover(
            function() {
                $(this).addClass("hover");
            },
            function() {
                $(this).removeClass("hover");
            });

        /* simulate populating the file value since 
            we can't see the file input */
        $("input.file").change(function() {
            $("#fake input").val($(this).val());
        });
    });

It's important to note that the upload page gets its own set of window events since it's loaded inside of the frame. The upload page makes calls to functions in the control. I've highlighted the points of interest; you'll note that I only bind the load event of the window (I don't bind the unload). It's also possible to do this using the onbeforeunload event, but I found that this would fire the progress layer even if I was browsing away from the page (which may confuse your users). So it made more sense to just do it simply from the upload button click.

The upload page itself is remarkably simple:

<body>
    <form id="_form" runat="server">
    <div>
        <div id="fake-container">            
            <input type="file" id="_file" runat="server" class="file"/>            
            <div id="fake">
                <input type="text" />
            </div>            
        </div>
        <asp:Button runat="server" ID="_upload" 
            Text="Upload" OnClick="HandleUploadClick" 
            CssClass="upload-button"/>
    </div>
    </form>
</body>

The control isn't much more complex either:

<div id="frame">
    This is an asynchronous upload control.  
    The control load time is <asp:Label ID="_time" runat="server"/>

    <iframe id="upload-frame" src="Upload.aspx" 
        frameborder="0" scrolling="no" height="100px">

    </iframe>  
    <div id="progress" style="display:none;"></div>
</div>
<div>
    <div id="load"></div>
    <div id="unload"></div>
</div>

There's no codebehind for the control to speak of. The only place where you need to implement custom code is in the codebehind of the upload page to receive the posted file:

using System;
using System.Threading;
using System.Web.UI;

namespace AsyncUploadControlTest
{
    /// <summary>
    /// This is the actual page that handles the upload.
    /// </summary>
    public partial class Upload : Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> 
        /// instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Handles the upload click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> 
        /// instance containing the event data.</param>
        protected void HandleUploadClick(object sender, EventArgs e)
        {
            // Just fake a long running upload for dramatic effect
            Thread.Sleep(2500);

            // Add your logic here
        }
    }
}

There you have it. Works in SharePoint 2007 just fine. Works in IE7 and Firefox 3.5 as well. Because the receiving upload page is just an ASPX page, you can simply output your errors or success messages to the page itself; no special hackery required.

Download the source code here: AsyncUploadControlTest.7z (17.54 KB)

Filed under: .Net, Dev, SharePoint 2 Comments
30Dec/090

C# and ASP.NET Syntax Highlighting in Trac

Posted by Charles Chen

Well, spent the good amount of time trying to figure this out. See the configuration info below from my trac.ini file.

[mimeviewer]
max_preview_size = 262144
mime_map = text/x-dylan:dylan,text/x-idl:ice,text/x-ada:ads:adb,
php_path = php
pygments_default_style = trac
pygments_modes = text/x-csharp:csharp:7,text/plain:aspx-cs:7
tab_width = 4
treat_as_binary = application/octet-stream,application/pdf,application/postscript,application/rtf

Oh yeah, it helps if you actually install Pygments, too.

Filed under: Dev, Self Note No Comments
22Dec/090

SharePoint Design Patterns: Entry 2.5

Posted by Charles Chen

In the previous entry, we looked at how we can model a SharePoint list item using a more domain specific model to simplify programmatic access to the list item thus reducing otherwise error prone data access code and making the overall framework easier to use. Again: the idea is to promote reuse and decrease complexity through domain specific code that abstracts the underlying SharePoint object models, making it easier for a team to build functionality on top of this framework.

One interesting point is that if you're already building your fields and content types using features XML, the work required to generate the domain specific wrappers can be simplified dramatically using automation. In a sense, a content type is basically a class (this is generally how I map them in my domain design); why double your effort and write both the content types and the classes?

So how do we go about this?

(Side note: this isn't so much a "design pattern" as it is an "implementation pattern")

As an example, here is a simple XML file which defines a set of fields and content types which use those fields:

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field DisplayName="Model Code"
    Name="Model_Code"
    StaticName="Model_Code"
    ID="{F0000000-0000-0000-0000-000000000001}"
    Type="Integer"
    SourceID="http://schemas.someusedcarinventory.com"
    Group="My Custom Columns"/>
  <Field DisplayName="VIN"
    Name="VIN"
    StaticName="VIN"
    ID="{F0000000-0000-0000-0000-000000000002}"
    Type="Text"
    SourceID="http://schemas.someusedcarinventory.com"
    Group="My Custom Columns"/>
  <Field DisplayName="Make"
    Name="Make"
    StaticName="Make"
    ID="{F0000000-0000-0000-0000-00000000003}"
    Type="Text"
    SourceID="http://schemas.someusedcarinventory.com"
    Group="My Custom Columns"/>
  <ContentType Name="Vehicle"
    ID="0x0100FC000000000000000000000000000001"
    Description="Used car inventory"
    Group="My Custom Content Types" >
    <FieldRefs>
      <FieldRef ID="{c042a256-787d-4a6f-8a8a-cf6ab767f12d}" Name="ContentType" />
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" 
        Required="TRUE" ShowInNewForm="TRUE" ShowInEditForm="TRUE" />
      <FieldRef ID="{F0000000-0000-0000-0000-000000000001}" Name="Model_Code"/>
      <FieldRef ID="{F0000000-0000-0000-0000-000000000002}" Name="VIN"/>
      <FieldRef ID="{F0000000-0000-0000-0000-000000000003}" Name="Make"/>
    </FieldRefs>
  </ContentType>  
  <Field DisplayName="Dealership Code"
    Name="Dealership_Code"
    StaticName="Dealership_Code"
    ID="{F0000000-0000-0000-0000-00000000004}"
    Type="Integer"
    SourceID="http://schemas.someusedcarinventory.com"
    Group="My Custom Columns"/>
  <Field DisplayName="Dealership Fax Number"
    Name="Dealership_Fax_Number"
    StaticName="Dealership_Fax_Number"
    ID="{F0000000-0000-0000-0000-00000000005}"
    Type="Text"
    SourceID="http://schemas.someusedcarinventory.com"
    Group="My Custom Columns"/>
  <ContentType Name="Dealership"
    ID="0x0100FC000000000000000000000000000002"
    Description="Dealerships"
    Group="My Custom Content Types" >
    <FieldRefs>
      <FieldRef ID="{c042a256-787d-4a6f-8a8a-cf6ab767f12d}" Name="ContentType" />
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" 
        Required="TRUE" ShowInNewForm="TRUE" ShowInEditForm="TRUE" />
      <FieldRef ID="{F0000000-0000-0000-0000-000000000004}" Name="Dealership_Code"/>
      <FieldRef ID="{F0000000-0000-0000-0000-000000000005}" Name="Dealership_Fax_Number"/>
    </FieldRefs>
  </ContentType>    
</Elements>

When approaching this problem, I considered three ways of handling the class file generation:

  1. Use an object model and StringTemplate to create .cs files. This invovled writing POCO classes (or generating them from the schema) which I could deserialize the XML to and then passing those objects to a template instance. This seemed like too much work, given that I really didn't feel like maintaining all of that code as well. Plus, while StringTemplate isn't - by any sense of the imagination - hard, it is a non-standard syntax that someone would have to learn to maintain and/or extend the conversion.
  2. Use an XDocument and CodeDom to create .cs files. This seemed like even more work! While it's framework supported, I feel like this solution would be hard to extend and maintain for most developers.
  3. Use an XSL transform to create .cs files. This seemed to be the most natural solution given that the source file is already in XML format and a the target content structure is far from complex (the basic class file is fairly simple). Plus, while XSLT isn't trivial, it's not that hard either (and the syntax is "standard").

One of the cool features of XSL 2.0 is the xsl:result-document element which allows you to create multiple documents from one source document. Only one problem: .NET's XSLT engine doesn't implement XSLT 2.0! What a bummer; it seemed like if I wanted to get this to work and generate multiple output files, it was going to take some work in code or find an XSLT 2.0 capable processor.

Enter Saxon, which provides an XSLT 2.0 processor for .NET. The following code takes the XML above and uses the xsl:result-document to create two class files, one for each content type:

using System;
using System.IO;
using Saxon.Api;

namespace FeatureToClass
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Uri xmlFile = new Uri(
                @"C:\Users\Charles\Desktop\elements.xml");

            // Create a Processor instance.  
            Processor p = new Processor();

            // Load the source document.  
            XdmNode node = p.NewDocumentBuilder().Build(xmlFile);

            using (Stream stream = File.OpenRead("core-transform.xslt"))
            {
                // Create a transformer for the stylesheet.  
                XsltTransformer transformer = 
                    p.NewXsltCompiler().Compile(stream).Load();

                // Set the root node of the source document
                // to be the initial context node.  
                transformer.InitialContextNode = node;

                // BaseOutputUri is only necessary for xsl:result-document.  
                transformer.BaseOutputUri = xmlFile;

                transformer.SetParameter(
                    new QName("ct", "http://www.customtransform.com", "namespace"), 
                    new XdmAtomicValue("My.Custom.Package"));

                // Create a serializer.  
                Serializer serializer = new Serializer();
                transformer.Run(serializer);
            }
        }
    }
}

The code above is a simple console program that takes a (hardcoded) path to a source XML file (a SharePoint elements.xml file) and (hardcoded) namespace and loads an XSL file to transform the XML to C# class files.

Here's the transform (it's a bit messy for output formatting reasons, so you're best off copying it into an XML aware text editor to get a better view):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE stylesheet [
    <!ENTITY space "<xsl:text> </xsl:text>">
    <!ENTITY cr "<xsl:text>
</xsl:text>">
]>

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:sp="http://schemas.microsoft.com/sharepoint/"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:functx="http://www.functx.com"
  xmlns:ct="http://www.customtransform.com"
  version="2.0">
    <xsl:param name="ct:namespace"/>
    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:for-each select="//sp:ContentType">
            <xsl:variable name="classname" select="replace(@Name, ' ', '')"/>
            <xsl:variable name="filename" select="concat($classname,'.cs')" />
            <xsl:value-of select="$filename" />
            <!-- Creating  -->
            <xsl:result-document href="{$filename}">
using System;

    namespace <xsl:value-of select="$ct:namespace"/>
    {
        public partial class <xsl:value-of select="$classname"/>
        {
            private string _contentTypeId;
            
            public string ContentTypeId {
                get { return _contentTypeId; }
                set { _contentTypeId = value; }
            }

            public <xsl:value-of select="$classname"/>()
            {
                _contentType = "<xsl:value-of select='@Name'/>";
                _contentTypeId = "<xsl:value-of select='@ID'/>";
            }

            <xsl:apply-templates/>
    }
}
            </xsl:result-document>
        </xsl:for-each>
    </xsl:template>

    <!--///
        Templates
    ///-->
    <xsl:template match="sp:FieldRef">
        <xsl:variable name="fieldname" select="functx:lower-first(replace(@Name, '_', ''))"/>
        <xsl:variable name="fieldid" select="@ID"/>
        <xsl:variable name="dotnettype">
            <xsl:choose>
                <xsl:when test="//sp:Field[(@ID = $fieldid) and (@Type = 'Integer')]">int</xsl:when>
                <xsl:otherwise>string</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>

        private <xsl:value-of select="$dotnettype"/> _<xsl:value-of select="$fieldname" />;
        <xsl:call-template name="attribute"><xsl:with-param name="fieldid" select="$fieldid"/></xsl:call-template>
        public <xsl:value-of select="$dotnettype"/>&space;<xsl:value-of select="replace(@Name, '_', '')"/>
        {
            get { return _<xsl:value-of select="$fieldname" />; }
            set { _<xsl:value-of select="$fieldname" /> = value; }
        }
    </xsl:template>

    <xsl:template name="attribute">
        <xsl:param name="fieldid"/>
    <xsl:if test="exists(//sp:Field[@ID = $fieldid]/@ID)">[Caml(Id="<xsl:value-of select='//sp:Field[@ID = $fieldid]/@ID'/>", StaticName="<xsl:value-of select='//sp:Field[@ID = $fieldid]/@StaticName'/>", Type="<xsl:value-of select='//sp:Field[@ID = $fieldid]/@Type'/>")]</xsl:if></xsl:template>

    <!--///
        Custom functions
    ///-->
    <xsl:function
        name="functx:lower-first" as="xs:string"
        xmlns:functx="http://www.functx.com" >
        <xsl:param name="arg" as="xs:string"/>
        <xsl:sequence select="concat(lower-case(substring($arg,1,1)), substring($arg,2))"/>
    </xsl:function>
</xsl:stylesheet>

I borrowed one function from the FunctX library to create the camelCased field names. The XSL probably isn't nearly as clean or optimized as it should be (my XSL is admittedly a bit rusty), but it gets the job done. Here's one of the two classes (and class files) which get generated at the source directory of the input XML file:

using System;

namespace My.Custom.Package 
{
    public partial class Dealership
    {
        private string _contentTypeId;
        public string ContentTypeId {
            get { return _contentTypeId; }
            set { _contentTypeId = value; }
        }   

        public Dealership()
        {
            _contentType = "Dealership";
            _contentTypeId = "0x0100FC000000000000000000000000000002";
        }

        private string _contentType;
        public string ContentType
        {
            get { return _contentType; }
            set { _contentType = value; }
        }      

        private string _title;
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }

        private int _dealershipCode;
        [Caml(Id="{F0000000-0000-0000-0000-000000000003}", 
            StaticName="Dealership_Code", Type="Integer")]
        public int DealershipCode
        {
            get { return _dealershipCode; }
            set { _dealershipCode = value; }
        }

        private string _dealershipFaxNumber;
        [Caml(Id="{F0000000-0000-0000-0000-000000000004}", 
            StaticName="Dealership_Fax_Number", Type="Text")]
        public string DealershipFaxNumber
        {
            get { return _dealershipFaxNumber; }
            set { _dealershipFaxNumber = value; }
        }
    }
}

Awesome! It's amazing how little code was required to get this basic scenario working.

Now we have a single source which defines our SharePoint artifacts and our code artifacts; I love it. Write your fields and content types in your feature and you get class files for free! You'll note that I've added a simple CamlAttribute where applicable. This will prove handy when it comes time to automate construction of the object instance from a SharePoint list item, which we'll look at next time (for the time being, feel free to modify the XSL and remove the line for it or write an implementation of CamlAttribute).

Again, to reiterate: the goal is make it easy to build applications on top of a SharePoint deployment by adding a layer of domain specific APIs and objects so that a team can be productive while reducing duplication and the ramp up time required to understand the business domain.

Other points for improvement and enhancement (look for these in a future installment):

  1. Parameterize the program.
  2. Consider making it a Visual Studio add-in or a custom tool.
  3. Make it go the other way; in other words: generate the content type and field XML from class files (which would be cool, too).

But even as it is, it's incredibly useful. On the next installment, we'll see how we can build more intelligence into the model and make it more useful.

Filed under: .Net, Dev, SharePoint No Comments
30Sep/092

Chain Of Command And Passing Parameters

Posted by Charles Chen

One of the more useful patterns that I've used quite frequently is a version of Chain of Responsibility that integrates with the Command pattern. In a classic CoR, the idea is that only one component in the chain handles the request and then execution flows out of the chain. In a CoC pattern, the idea is that the execution flows through the entire chain.

I like Shahan Khatchadourian's description of this pattern:

When programming, certain sections of code can sometimes be viewed as a workflow or preset sequence of tasks or commands. This can considered to be the design pattern called Chain of Command...

There are two key problems that this pattern solves that make it immensely useful in everyday programming (it's a bit surprising that dofactory's listing of CoR lists the frequency of use as a 2/5).

The first problem that it solves is extensibility. By implementing the chain as a list of abstract types (Command or Validator or whatever), using reflection (one way or another), you can build a list of concrete commands, giving each element in the chain a chance of working on the input request. One example of how I use this is to implement validation where I might have an abstract base class called Validator. To build the chain of validators, one very quick and easy solution is to reflect on the assembly and simply find all of the classes which implement Validator (additional complexity can be added as necessary, such as supporting validators in external assemblies or different groupings of validators).

The second (related) problem that it solves is excessively large blocks of if statements. In a validation example, you can imagine that if it were written in-line, each validation rule would essentially map to an if statement in a large block. In a way, it's a very useful pattern for exchanging a tiny bit of performance and memory for more modular organization of logic. Without the CoC pattern, adding a new validation rule would mean adding another if block - yuck! Using CoC with reflection, we can simply add another class which inherits Validator to our project and count on the component building the chain to find our class and add it to the chain.

Here is a very simple, barebones implementation:

/// <summary>
/// A simple command chain factory that doesn't do wiring.
/// </summary>
public static class SimpleCommandChainFactory
{
    /// <summary>
    /// Creates a simple list of commands to execute using reflection.
    /// </summary>
    public static List<Command> Create()
    {
        var commands = new List<Command>();

        Type[] types = Assembly.GetExecutingAssembly().GetTypes();
        Type commandType = typeof (Command);

        foreach (Type type in types)
        {
            if (!type.IsSubclassOf(commandType))
            {
                continue;
            }

            MemberInitExpression init = Expression.MemberInit(
                Expression.New(type), new MemberBinding[0]);

            Command command = Expression.Lambda<Func<Command>>(init)
                .Compile().Invoke();

            commands.Add(command);
        }

        commands = commands.OrderBy(c => c.Priority).ToList();

        return commands;
    }
}

The code checks to see if a type if a sub-type of Command and, if so, creates an instance and puts it on the chain. The commands could then be executed like so:

internal class Program
{
    private static void Main(string[] args)
    {
        List<Command> commands = SimpleCommandChainFactory.Create();

        // Execute each command.
        foreach(Command command in commands)
        {
            command.Execute();
        }
    }
}

In this case, I'm not passing in data or checking for stop conditions (which might be useful in a validation scenario where the first failure stops processing). To do so, you could simply pass in a single instance of some context class to each command when executing and check to see if the stop condition is true after the execute call (and break out of the for-loop).

While this pattern is immensely useful any time you find a big if or switch block that's particularly volatile, one problem that I've found with this pattern is passing parameters between two elements in the chain. Ideally, no element in the chain should have a dependency on another element in the chain. We want to decouple each of the elements to make it easier to build the chain dynamically. What this means is that no element should directly set values on another element in the chain. In essensce, to emulate the functionality of DependencyObject and DependencyProperty that we find in WF and WPF. (Why not just use WF then? Complexity and performance.)

At least two solutions come to mind. The first is to pass a context with a dictionary through each element of the chain. This would allow each element to place an output value into the dictionary and downstream components to pull these values out. The downside of this approach is that unless you force everything into one value type (i.e. serialize to an XML string?), you can't really pass strongly typed data and now you're keyed by strings (or whatever value type) which you need to have know about in order to retrieve the value.

A second approach would be to leverage DependencyObject and DependencyProperty. While this sounds good in principle, it requires a mess of code to accomplish in your own code with your own objects. Not only that, it seems to be overkill since many times, you don't need the full capabilities of the dependency system - you just want to pass a value downstream in a nice, strongly typed manner.

(There is a third approach using thread local storage, but this is probably an even worse option than the first since it wouldn't be very accessible to most developers and it doesn't really address the issue at hand.)

In the past, I've relied on the dictionary based approach. While it wasn't ideal, it was the simplest solution that got the job done. Deep down, I always hated this approach because I didn't like having to know the keys and having to know how to cast the results retrieved from the dictionary. However, I recently came up with a much better solution to this issue: dynamically wired events.

We introduce two attribute classes which we can use to identify our event publishers and event subscribers. For brevity, I'll only show the publisher attribute (they are pretty much the same in this implementation):

/// <summary>
/// Attribute used to identify event publishers.
/// </summary>
[AttributeUsage(AttributeTargets.Event)]
public class EventPublisherAttribute : Attribute
{
    private readonly string _eventName;

    /// <summary>
    /// Initializes a new instance of the <see cref="EventPublisherAttribute"/> class.
    /// </summary>
    /// <param name="eventName">Name of the event.</param>
    public EventPublisherAttribute(string eventName)
    {
        _eventName = eventName;
    }

    /// <summary>
    /// Gets the name of the event.
    /// </summary>
    /// <value>The name of the event.</value>
    public string EventName
    {
        get { return _eventName; }
    }
}

The only difference between the two in this case is the AttributeUsageAttribute. In the case of the subscriber, we want it to apply to methods, not events. Next, we need to apply these attributes to our concrete command types that we're going to chain. For this example, let's say that the first item in the chain generates a GUID key that the rest of the items in the chain also need to use:

/// <summary>
/// Generates a GUID that may be needed by the rest of the chain.
/// </summary>
public class GenerateKeyCommand : Command
{
    /// <summary>
    /// Raised when a key is generated;
    /// </summary>
    [EventPublisher(EventNames.KeyGenerated)]
    public event EventHandler<EventArgs<Guid>> KeyGenerated;

    /// <summary>
    /// Executes this instance.
    /// </summary>
    public override void Execute()
    {
        Guid key = Guid.NewGuid();

        Console.Out.WriteLine("From GenerateKeyCommand: {0}", key);

        OnKeyGenerated(key);
    }

    /// <summary>
    /// Gets the priority.  A lower value indicates higher priority.
    /// </summary>
    /// <value>The priority.</value>
    public override int Priority
    {
        get { return 1; }
    }

    /// <summary>
    /// Raises the key generated event.
    /// </summary>
    /// <param name="key">The key.</param>
    private void OnKeyGenerated(Guid key)
    {
        if(KeyGenerated != null)
        {
            KeyGenerated(this, new EventArgs<Guid>(key));
        }
    }
}

As you can see, it's pretty standard stuff, with the exception of the additional attribute on the event. Downstream, we want to handle these events in other commands:

/// <summary>
/// Simple command just for demonstration purposes.
/// </summary>
public class DoSomethingWithKeyCommand : Command
{
    private Guid _key;

    /// <summary>
    /// Executes this instance.
    /// </summary>
    public override void Execute()
    {
        Console.Out.WriteLine("From DoSomethingWithKeyCommand: {0}", _key);
    }

    /// <summary>
    /// Gets the priority.  A lower value indicates higher priority.
    /// </summary>
    /// <value>The priority.</value>
    public override int Priority
    {
        get { return 100; }
    }

    [EventSubscriber(EventNames.KeyGenerated)]
    private void HandleKeyGenerated(object sender, EventArgs<Guid> e)
    {
        _key = e.Data;
    }
}

You can see that in the event handler method, we just grab the value from the event arguments and set it on a local variable for use when Execute() is called.

Now the trick is to wire these events up using reflection to avoid creating the direct dependency between the different elements in the chain. Spring.NET offers one way to do this using declarative events, however, it should be noted that it only works with singleton objects (this bit me in the butt until I figured it out). Depending on the nature of your elements in the chain, that may or may not be sufficient for you. If you need new instances every time, then we can accomplish this ourselves using a bit of reflection.

(Note that none of the code that follows has been optimized; there are a few caching opportunities to take advantage of to cut down on some of the reflection calls.)

The first step is to modify the factory method:

/// <summary>
/// Creates a command chain using reflection.
/// </summary>
/// <returns></returns>
public static List<Command> Create()
{
    List<Command> commands = new List<Command>();

    Type[] types = Assembly.GetExecutingAssembly().GetTypes();
    Type commandType = typeof (Command);

    Dictionary<string, List<EventCoupling>> eventSources
        = new Dictionary<string, List<EventCoupling>>();

    Dictionary<string, List<MethodCoupling>> eventTargets
        = new Dictionary<string, List<MethodCoupling>>();

    foreach(Type type in types)
    {
        if(!type.IsSubclassOf(commandType))
        {
            continue;
        }

        MemberInitExpression init = Expression.MemberInit(
            Expression.New(type), new MemberBinding[0]);

        Command command = Expression.Lambda<Func<Command>>(init)
            .Compile().Invoke();

        commands.Add(command);

        BuildHandlerCache(command, eventTargets, 
            type.GetMethods(_methodFlags));

        // Parse the events.
        EventInfo[] events = type.GetEvents(
            BindingFlags.Public | BindingFlags.Instance);

        if(events.Length == 0)
        {
            continue; 
        }

        BuildEventCache(command, eventSources, events);
    }

    WireEvents(eventSources, eventTargets);

    commands = commands.OrderBy(c => c.Priority).ToList();

    return commands;
}

We create two caches as we iterate through the types to hold the events and handler methods that we encounter as we iterate the types and as a final step, we wire the events together from the caches. The cache building logic is fairly straightforward:

/// <summary>
/// Builds the handler cache.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="eventTargets">The event targets.</param>
/// <param name="methods">The methods.</param>
private static void BuildHandlerCache(
    Command command, 
    IDictionary<string, List<MethodCoupling>> eventTargets, 
    IEnumerable<MethodInfo> methods)
{
    foreach(MethodInfo method in methods)
    {
        EventSubscriberAttribute[] subscriberAttributes =
            (EventSubscriberAttribute[])
            method.GetCustomAttributes(
                typeof(EventSubscriberAttribute), false);

        if (subscriberAttributes.Length == 0)
        {
            continue;
        }

        foreach(EventSubscriberAttribute attribute in subscriberAttributes)
        {
            if(!eventTargets.ContainsKey(attribute.EventName))
            {
                eventTargets[attribute.EventName] = new List<MethodCoupling>();
            }

            eventTargets[attribute.EventName].Add(
                new MethodCoupling(method, command));
        }
    }
}

/// <summary>
/// Builds the event caches.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="eventSources">The event sources.</param>
/// <param name="events">The events.</param>
private static void BuildEventCache(
    Command command,
    IDictionary<string, List<EventCoupling>> eventSources,  
    IEnumerable<EventInfo> events)
{
    foreach(EventInfo eventInfo in events)
    {
        EventPublisherAttribute[] publisherAttributes =
            (EventPublisherAttribute[])
            eventInfo.GetCustomAttributes(
                typeof (EventPublisherAttribute), false);

        if(publisherAttributes.Length == 0)
        {
            continue;
        }

        foreach (EventPublisherAttribute attribute in publisherAttributes)
        {
            if(!eventSources.ContainsKey(attribute.EventName))
            {
                eventSources[attribute.EventName] = new List<EventCoupling>();
            }

            eventSources[attribute.EventName].Add(
                new EventCoupling(eventInfo, command));
        }
    }
}

The gist of it is that we want to iterate through the events and the methods, find the ones with the attributes, map them to instances of commands, and throw them into a dictionary. As you can see, the dictionary values are generic lists on both sides; this means that a single event can fire multiple event names and a single handler method can handle multiple events (as long as the method input types are the same). This may or may not be useful in any given scenario, but it's easy enough to rewrite this to make it a bit simpler if it's not required.

Finally, we need to wire the events together in the chain after it's created:

private static void WireEvents(
    Dictionary<string, List<EventCoupling>> eventSources,
    Dictionary<string, List<MethodCoupling>> eventTargets)
{
    foreach(string key in eventSources.Keys)
    {
        if(!eventTargets.ContainsKey(key))
        {
            continue;
        }

        List<MethodCoupling> targets = eventTargets[key];
        List<EventCoupling> sources = eventSources[key];

        foreach(EventCoupling source in sources)
        {
            foreach(MethodCoupling target in targets)
            {
                Delegate d = Delegate.CreateDelegate(
                    source.Event.EventHandlerType,
                    target.Command,
                    target.Method);

                source.Event.AddEventHandler(source.Command, d);
            }
        }
    }
}

It's as simple as that: we loop through each event (publishers) and see if there is a list of methods (subscribers) to handle it in the chain. If so, we add a delegate as a handler to the event. In my sample project, I created three simple command types to demonstrate; here's the output when I run my program:

You can see, once the key is generated in the first command, the value is available in the downstream commands using the events. The nice thing is that we can add more steps to our logic without much extra work. This is particularly handy for something like implementing a chain of validation rules as it means that you don't end up writing a big if if block. But even in general usage, this pattern is useful for breaking out a large method into smaller, more modular pieces in a much more extensible manner.

One neat thing is that it allows you to not only wire events downstream, but also upstream as well. This means that if an element in your chain triggers an event, code in a previous even is executed if there is a handler wired for it.

In a more complete implementation, you may consider using Spring.NET or Unity or simply .NET configuration to statically identify the elements of the chain (instead of the basic reflection I've used). You may also consider more error handling logic ;-) and passing an instance of a context through each element in the chain.

The full sample project is available here: ChainOfCommandSample.zip (11.21 KB)

Filed under: .Net, Dev 2 Comments
21Sep/090

Yet Another .NET Interview Questions List

Posted by Charles Chen

There are tons of blog posts on .NET interview questions out there on the 'Net; here's another list...just because I feel like it, okay :-P ?

In general, when I am interviewing people, I don't go for the obvious questions.  Not only are they boring because I've answered them so many times, but most of them can be easily studied for.  For most C#/.NET positions, there's a pretty standard set of questions that you'll encounter, most of which can be easily answered by simply reading Troelsen's Pro C# (I know because I picked it up the first time I was burned after a phone screen - I recommend this book to all junior developers looking to move up the payscale).

I do incorporate a few "template" questions, but in general, I like to keep things away from fact based questions and geared towards open-ended questions (I want to see that a candidate has actually done more than just use a feature after looking it up on MSDN or whatever - I want to see that a developer has actually sat there and thought about the technology or feature or whatever).

Here are a few of my favorite questions for interviews; perhaps you'll find them useful for your own interviews:

[ASP.NET] Discuss the strengths and weaknesses of ASP.NET, out of the box.

I ask this question because I want to see if a developer has thought really thought about ASP.NET as a framework.  Developers who have can answer this pretty easily.  Developers who just write the code and move on will give some really perplexing answers or flat out stumble on this one.  I like this question because it's completely open-ended and a developer is free to use anything in his/her past experience as a context.  Some developers may compare and constrast it to other frameworks they've used (ASP, JSP, Python, Ruby, etc).  Some will describe past frustrations or projects as points of reference for weaknesses.  In general, I like this question because it shows whether an individual can discuss the technology intelligently.

[ASP.NET] What's the difference between an HtmlControl and a WebControl?

What I'm looking to find out with this question is whether a candidate can show some restraint with regards to using web controls on a page where an HTML control would work just as well.

[ASP.NET] Can you describe any approaches or patterns to make ASP.NET web forms programming more manageable?

In the simplest case, I'd like to hear something like "In the past, I've implemented MVC" or any sort of presenter/controller-view style pattern or - at the least - "I've created a custom base class which inherits Page", to show that the developer won't be inclined to just throw a bunch of code in the codebehind and call it a day.  One common answer is some variation of "I use an N-tier approach", but I find this answer to be insufficient since an N-tier approach doesn't mean much in terms of ensuring that your UI code is clean and well organized.  Developers who mostly think of ASP.NET as drag-drop-fill in code will never be able to give any sort of satisfactory answer to this question.

[.NET] How many major versions of the .NET runtime have there been?

Okay, this one is kind of a "gotcha" question, I admit, but it is relevant for a couple of reasons.  Developers who follow up on blogs and stay current will undoubtedly know that there is a new version of the runtime shipping with the next release of VS/.NET.  Developers who have worked extensively with ASP.NET will also know that in IIS, you can only select from 1.x or 2.x versions of the runtime.  I don't think anyone has gotten this one right yet, even though I put a particular emphasis on "runtime" when reading the question.

[.NET] What access modifier does Microsoft recommend for constructors on abstract classes?

What I'm hoping for is to one day hear: "Well, according to Framework Design Guidelines..." (or something equivalent).  The goal of the question is to see if a candidate understands some of the nuances of API and framework design, especially important for senior developer roles.  There are other questions along this vein, one of my other favorites is...

[.NET] What does the following code statement imply?

public readonly List MyStrings;

Again, the goal is to see how well a candidate understands the implications of their design decisions and some basic C#.  I won't give up on a candidate if they get it wrong; I try to coax them the correct conclusion, but few candidates can right the course once they make up their mind on this one.

If they bring up ReadOnlyCollection, they get bonus points.

[.NET] Can you expose abstract classes in an ASMX or WCF service contract?

This question can, answered correctly, indicate an above average level of understanding of .NET web services but, more importantly, I think it offers a peek at whether a candidate embraces object oriented design principals.  Candidates who have designed or worked with systems with rich object models will have undoubtedly encountered this problem (unless there were some specific interoperability scenarios which they had to design around).

[.NET] What is a custom attribute and how can you read one?

This question can reveal a lot about a candidate since there are some design scenarios that can be resolved pretty elegantly by taking advantage of custom attributes.  In addition, a candidate that can answer this question necessarily has experience working with reflection.  With regards to the second part, I'm not looking for specifics in terms of syntax and namespaces and classes, but rather a generic answer like "By using reflection" or something.

[.NET] What is the default() statement used for?

This is more of a textbook question, but candidates who have worked extensively with generics will be able to answer this with ease.  Again, being able to answer this reveals a lot about a candidate, especially when considering one for a senior developer position since being able to leverage generics is a big part of writing a solid API or framework.

[.NET] Desribe your approach to exception handling.

Another open-ended question that allows a candidate to shine - or to flail.  I've heard a wide range of responses to this one, but none that indicate that a developer has put any significant thought into one of the most important aspects of writing code on the .NET platform (especially framework level code).  Most responses fall into the basic structural elements of exception handling (try-catch-finally), but I am looking forward to the day that someone gives a response which addresses it at a much higher level than that.

[GENERAL] What is object oriented programming?

I usually preface this by stating that I'm not looking for the bullet-list textbook definition of it; I'm looking for a candidate to provide a much deeper answer than that.  There's no "right" answer, but there are definitely bad answers or responses (I've heard some wacky ones) that reveal that a candidate hasn't really thought deeply about just what it means to write good object oriented code.  To me?  Aside from the textbook stuff, OOP is about modeling complexity using structural interactions instead of straight-line, imperative logic.

This is just a small slice of my list, but they are perhaps the most important ones with regards to ASP.NET/C#, IMO.  What do you think?  Too abstract?  Too high level?  Too awesome ;-) ?  Hopefully, you've found something useful in here, either as an interviewer or an interviewee.

Filed under: .Net, Dev No Comments
19Sep/090

MbUnit CsvDataAttribute

Posted by Charles Chen

MbUnit has several cool features which distinguish it from some of the other unit testing frameworks on the .NET platform. Among them are the RollbackAttribute, PrincipalAttribute, ThreadedRepeatAttribute, and the Csv/XmlDataAttribute.

I hadn't noticed the CsvDataAttribute previously when I've worked with MbUnit, but it's definitely one that I think that most teams can make the most use of. While the RowAttribute allows developers to externalize and parameterize their unit tests, the CsvDataAttribute takes it to another level by allowing developers to put test parameters in a simple text file. This is extremely handy since it becomes easier to add more test conditions as you come up with new scenarios without recompiling code. Theoretically, you could even involve your QA team in getting the right set of test data since they could modify the external CSV file. I find this extremely handy :-)

The documentation on how to use it was lacking a bit; while it explained that you can add metadata (custom attributes) via the CSV file, it didn't give an example for the ExpectedExceptionAttribute, one of the most common ones, I'd imagine.

Consider the following property which normalizes and validates a phone number (note: this was meant as a simple example):

/// <summary>
/// Gets or sets the number.
/// </summary>
/// <value>The number.</value>
public string Number
{
    get { return _number; }
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            throw new ArgumentException(
                "The phone number cannot be null or empty.");
        }

        // Grab all the digits.
        char[] digits = value.ToCharArray()
            .Where(c => char.IsDigit(c)).ToArray();

        if (digits.Length != 10)
        {
            throw new FormatException(
                "A phone number must contain 10 digits.");
        }

        _number = new string(digits);
    }
}

The test method might look like this:

[Test]
[CsvData(FilePath = "CsvData\\PhoneNumbers.txt", HasHeader = true)]
public void TestPhoneNumberNormalizationWithCsv(
    string type, string number, string expected)
{
    PhoneNumber phoneNumber = new PhoneNumber(0, 0, number, type);

    Assert.AreEqual(expected, phoneNumber.Number);
}

Now we'd like to test our validation logic to gaurd against future refactorings to make sure that anyone refactoring this code throws the appropriate exceptions that our downstream callers expect.

You can see that I've used the FilePath property and the HasHeader property (you have to use this if there is a header, otherwise, it detects the header as a row; it's not true by default it seems). The text file to go with this test would then look like:

Type, Number, Expected, [ExpectedException]
Home, (732) 555-1012 begin_of_the_skype_highlighting              (732) 555-1012      end_of_the_skype_highlighting, 7325551012
Home, , , ArgumentException

There are a few things to note here:

  1. If no exceptions are associated with the row, don't include a trailing comma and empty value (see the first line).
  2. The headers are not case sensitive.
  3. Null values can be specified using an empty value.
  4. When specifying exceptions, you do not need to use typeof(ArgumentException), just the type is enough.

Happy (unit) testing!

Filed under: .Net, Dev No Comments