<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
    <channel>
        <title>Joe Ferner - Blogs at Near Infinity</title>


        <link>http://www.nearinfinity.com/blogs/</link>
        <description>Employee Blogs</description>
        <language>en</language>
        <copyright>Copyright 2010</copyright>
        <lastBuildDate>Tue, 29 Sep 2009 11:05:03 -0500</lastBuildDate>
        <generator>http://www.sixapart.com/movabletype/</generator>
        <docs>http://www.rssboard.org/rss-specification</docs>
        
        <item>
            <title>Spell checking your SharePoint custom application pages</title>
            <description><![CDATA[<p>I had a requirement to spell check some fields on a custom application page and I knew SharePoint had the ability because on the edit item page there is a "Spelling" button.  Come to find out this is one of the easiest things to do and there is really no excuse to not include it on all of your application pages.</p>

<p>First step is to include the javascript needed to run the spell checking. You'll need two includes form.js and SpellCheckEntirePage.js.
</p>

<pre class="prettyprint">
&lt;script type="text/javascript" language="javascript" 
  src="/_layouts/1033/form.js?rev=df60y6YolDjUVbi91%2BZw%2Fg%3D%3D"&gt;&lt;/script&gt;
&lt;script type="text/javascript" language="javascript"
  src="/_layouts/1033/SpellCheckEntirePage.js?rev=zYQ05cOj5Dk74UkTZzEIRw%3D%3D"&gt;&lt;/script&gt;
</pre>

<p>When I saw SpellCheckEntirePage.js for the first time I had to laugh because my initial estimate of the task was 3-4 days, I ended up doing it in less than 4 hours.</p>

<p>Next step is to add the button to actually check the spelling.</p>
<pre class="prettyprint">
&lt;input type="button" value="Spell Check"
  onclick="javascript:SpellCheckEntirePage('<%= SPContext.Current.Web.Url %>/_vti_bin/SpellCheck.asmx', '<%= SPContext.Current.Web.Url %>/_layouts/SpellChecker.aspx');" /&gt;
</pre>

<p>
<b>Done!</b>
</p>

<p>
Well almost. There were a couple of fields on the form which didn't make sense to spell check. But looking at the source of SpellCheckEntirePage.js you can quickly find the solution.  Just add excludeFromSpellCheck="true" to the fields you don't want to check.
</p>

<p>
OK, now I'm done.
</p>

<p>
Well not quite yet. The "excludeFromSpellCheck" doesn't work on People pickers. But SharePoint has this problem too.  If you edit a list item with a people picker and run the spell checker it will try to spell check people's login names which is never going to work. I went ahead and added a method to my master page which turns spell check off for people picker fields. It fixed the edit list item spell checking problem too :).  I do have to warn you I suck at javascript so if anyone can send me a better way of doing this I would appreciate it.
</p>

<pre class="prettyprint">
function disableSpellCheckOnPeoplePickers() {
  var elements = document.body.getElementsByTagName("*");
  for (index = 0; index &lt; elements.length; index++) {
    if (elements[index].tagName == "INPUT"
        && elements[index].parentNode
        && elements[index].parentNode.tagName == "SPAN") {
      var elem = elements[index];
      if (elem.parentNode.getAttribute("NoMatchesText") != "") {
        disableSpellCheckOnPeoplePickersAllChildren(elem.parentNode);
      }
    }
  }
}

function disableSpellCheckOnPeoplePickersAllChildren(elem) {
  try {
    elem.setAttribute("excludeFromSpellCheck", "true");
    for (var i = 0; i &lt; elem.childNodes.length; i++) {
      disableSpellCheckOnPeoplePickersAllChildren(elem.childNodes[i]);
    }
  } catch (e) {
  }
}
</pre>
]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/spell_checking_your_custom_lay.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/spell_checking_your_custom_lay.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">C#</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">SharePoint</category>
            
            <pubDate>Tue, 29 Sep 2009 11:05:03 -0500</pubDate>
        </item>
        
        <item>
            <title>Why I dislike TFS - Team Foundation Server</title>
            <description><![CDATA[<p>I don't usually blog about subjective things like my likes and dislikes, and I usually like (some will say I am in love with) Microsoft, but TFS is just horrible.</p>

<p>Here is a list of why I don't like it, in no particular order:</p>

<ul>
<li><strong>CodePlex</strong> -- First there was the SVN bridge (yes, someone hated TFS enough to make a product to make it look like something else) then Microsoft just caved and supported SVN directly. Not really a problem with TFS, it's just an indication that others feel the same way as I do.</li>
<li><strong>Size</strong> -- I guess Microsoft doesn't really like it either since they don't even ship it with Visual Studios, if you do need it, its a separate download and a big one at that -- 200MB+. Subversion, Tortoise SVN, and Ankh on the other hand combined are less than 15MB. How they filled up 200MB I have no idea, maybe they installed a client that doesn't suck somewhere I don't know about.</li>
<li><strong>Read-only Files</strong> -- Every file on your system is read-only. Why does everything need to be read-only. If I'm in another editor and I want to make a change to a file, I need to switch over to VS and check out a file for edit. This is rediculous.</li>
<li><strong>Identical Files</strong> -- I just want to see what changed. Why does TFS insist upon showing me all the files even if they are identical. Call me crazy but I like to see what files I actually changed when I check in. Someone told me there is some command line tool to see this but that's just silly.</li>
<li><strong>Code reviews/update</strong> -- On my current project I'm the project lead and I like to review the junior developers code when I update my code. Yeah, I can't do that, or I haven't found the button yet. Nor can I find the button to view a particular revision without finding a file that was part of that change and viewing it's history.</li>
<li><strong>Deleted files</strong> -- Team Explorer doesn't show them by default. This took me a while to figure this one out. You need to go into VS options then find TFS and then click show deleted files. Why is this not on by default and why isn't there a button to toggle this setting in Team Explorer.</li>
<li><strong>Project file modification</strong> -- We have some people working inside a VPN and some out, the TFS server name is different depending on where you sit. Since the solution file stores the connection string to TFS it's constantly getting checked in.</li>
<li><strong>Everything needs to be in the solution</strong> -- If you have a bunch of support files or non-.NET files, all of them need to be added to the solution or they don't get checked in or out. VS doesn't help you with this either because you can't have a solution folder map to a directory.</li>
<li><strong>Integrating with non-.NET developers</strong> -- If you have a mixed development environment (Java, Ruby, etc) like we do. You need to run TFS and something else because all the non-.NET developers can't use TFS especially if they are on a Mac. Usually the something else is much better anyway so you might as well use that instead.</li>
<li><strong>Working offline/Speed</strong> -- If you ever travel relax and take a nap because you won't be developing. Everything you do talks to the server and that in turn makes it slow. Open up a file and start making changes, to the server you go.  Move a file, to the server you go. Diff a change you made, to the server you go.</li>
<li><strong>Workspaces</strong> -- Who ever came up with the concept of workspaces at Microsoft should be ashamed of him/herself. They are just a stupid idea. If you want two copies of the same project checked out (I do it with SVN if I'm working on a quick bug fix and a big feature at the same time) good luck because I can't figure it out.</li>
<li><strong>Server isn't free</strong> -- 'Nuff said.</li>
</ul>

<p>I'm sure there are other problems but this is all I could think of while writing this.</p>

<p>Sure there are some nice things about TFS, but honestly the cons far outweigh the pros. So if you have to decide which SCM to use and you run across this blog I think it's pretty obvious that I don't recommend it. I love SVN and as GIT (tools) mature I'm sure I will switch to that.</p>
]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/why_i_dislike_tfs_-_team_found.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/why_i_dislike_tfs_-_team_found.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">TFS</category>
            
            <pubDate>Wed, 09 Sep 2009 18:43:05 -0500</pubDate>
        </item>
        
        <item>
            <title>Creating and Using Tasks in SharePoint State Machine Workflow</title>
            <description><![CDATA[<p>I had a problem with creating and using tasks in a SharePoint state machine workflow so I wanted to capture it in a blog so that others wouldn't need to. There isn't a lot of magic just a few gotchas which I'll point out.</p>
<p>Let me start by showing an overview of the workflow we are trying to create.<br>
<img class="mt-image-none" alt="workflow_overview.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/workflow_overview.jpg" width="435" height="338" /><br>
This is about as simple as it gets. Start -> Manager Approve -> Done.</p>
<p>If you look at "ManagerReview" you see we have three things.
<ul>
<li>ManagerReviewInit - This activity is responsible for creating the task<br>
<div class="gotcha"><span class="gotcha-title">Gotcha #1</span> - If we create the task here we encapsulate the ability that later in the workflow we can transition back to the ManagerReview state and it will know how to create a new task.</div></li>
<li>OnManagerReviewTaskCreatedEvent - This activity is going to initialize the task</li>
<li>OnManagerReviewTaskChangedEvent - This activity is going to perform the logic of when the task is completed</li>
</ul>
</p>

<p>
  <h3>ManagerReviewInit</h3>
  <img alt="manager_review_init.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/manager_review_init.jpg" width="215" height="267" class="mt-image-none" style="" /><br>
  No surprises here. Unless you take a look at the CorrelationToken on
  the create task.<br>
  <img alt="create_manager_review_task_props.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/create_manager_review_task_props.jpg" width="395" height="297" class="mt-image-none" style="" /><br>
  <div class="gotcha"><span class="gotcha-title">Gotcha #2</span> - 
  The OwnerActivityName needs to be scoped at the "State" level
  (in our case "ManagerReview"). This is important because later if
  you add a state that transitions back to "ManagerReview" you will
  get an exception stating that the correlation token was already
  initialized. Narrowing the scope will invalidate the correlation token
  when you leave the state.
  </div>
</p>

<p>
  <h3>OnManagerReviewTaskCreated</h3>
  <img alt="manager_review_on_create.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/manager_review_on_create.jpg" width="206" height="201" class="mt-image-none" style="" /><br>
  <div class="gotcha"><span class="gotcha-title">Gotcha #3</span> -
  At first I assumed that you needed to have a "set state" at the end
  of every event to loop back onto itself. Well you don't, there is an implied loop back. In fact if you do, the state initialization
  routine will be called causing a task to be created which will
  basically create an infinite recursion.
  </div>
</p>

<p>
  <h3>OnManagerReviewTaskChanged</h3>
  <img alt="manager_review_on_change.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/manager_review_on_change.jpg" width="432" height="514" class="mt-image-none" style="" /><br>
  If we take a closer look at the conditional you'll see I'm using
  a property I created, TaskComplete.<br>
  <img alt="complete_rule.jpg" src="http://www.nearinfinity.com/blogs/2009/08/20/complete_rule.jpg" width="334" height="140" class="mt-image-none" style="" /><br>
  <div class="gotcha"><span class="gotcha-title">Gotcha #4</span> -
  Microsoft doesn't expose the task status and since
  most users don't update percent complete when completing tasks you have to attach to the changed event
  and expose it to the workflow.
  </div>
  <pre class="prettyprint">
public bool TaskComplete { get; set; }

private void OnManagerReviewTaskChanged_Invoked(object sender, ExternalDataEventArgs e) {
  TaskComplete = AfterTaskProperties.ExtendedProperties[SPBuiltInFieldId.TaskStatus].ToString() == "Completed";
}
</pre>
</p>

<p><style type="text/css">
            .gotcha {
  font-style: italic;
  border: 1px solid #888888;
  margin: 1em;
  padding: 1em;
}</p>

<p>.gotcha-title {
  font-weight: bold;
}
</style></p>
]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/creating_and_using_tasks_in_sh.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/creating_and_using_tasks_in_sh.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">.NET</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">C#</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">SharePoint</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">Workflow</category>
            
            <pubDate>Thu, 20 Aug 2009 22:23:49 -0500</pubDate>
        </item>
        
        <item>
            <title>Changing the toolbar on a SharePoint ListViewWebPart</title>
            <description><![CDATA[<p>I know what you are thinking, another article on how to change the toolbar on a SharePoint ListViewWebPart. Well I have to say, I have tried every method documented on the web and none of them work consistantly for me. I thought I was doing something wrong until I read all the comments and I was but one of many having similar results. Most of the articles go down the path of grabbing the view XML from the ListViewWebPart and modifing the toolbar type attribute which I have found to only exist about 25% of the time. </p>
<p>My method takes a different approach. I started my journey by looking at the ListViewWebPart code directly in <a href="http://www.red-gate.com/products/reflector/">Reflector</a>, because it obviously needs to know how to do this because that's where the user changes it from the web site. From there I looked at "ListViewWebPart.GetToolParts" method which is the method SharePoint calls to get additional web part setting controls from the web part. In the case of the ListViewWebPart it returned a ListViewToolPart. The ListViewToolPart had a method called "ApplyChanges", this looks promising. Damn, obfuscated. No worry I can decipher IL for the most part. Bingo, there was the call I was looking for "ApplyViewToListWebPart". It took all the parameters I would expect, a reference to the ListViewWebPart and a toolbar type. </p>
<p>Here is the resulting code to wrap all the reflection nasty bits... </p><pre style="WIDTH: 500px; OVERFLOW: scroll" class="prettyprint">public static class ListViewWebPartHelper {
  public static void SetToolbarType(
    this ListViewWebPart lvwp,
    SPLimitedWebPartManager limitedWebPartManager,
    ListViewWebPartToolbarType type) {
#pragma warning disable 618
    string storageKey = lvwp.StorageKey.ToString("B").ToUpper();
    string listId = lvwp.ListName;
    string viewId = lvwp.ViewGuid;
    uint toolbarType = (uint)type;

    // get the SPWebPartManager from SPLimitedWebPartManager
    PropertyInfo webPartManagerProp = typeof(SPLimitedWebPartManager).GetProperty(
      "WebPartManager",
      BindingFlags.NonPublic | BindingFlags.Instance);
    SPWebPartManager webPartManager = (SPWebPartManager)webPartManagerProp.GetValue(limitedWebPartManager, null);

    // get the SPWebPartConnection from SPWebPartManager
    PropertyInfo spWebPartsProp = typeof(SPWebPartManager).GetProperty(
      "SPWebParts",
      BindingFlags.NonPublic | BindingFlags.Instance);
    SPWebPartCollection webParts = (SPWebPartCollection)spWebPartsProp.GetValue(webPartManager, null);

    // Call the ApplyViewToListWebPart method on the SPWebPartConnection
    // internal void ApplyViewToListWebPart(
    //    string storageKey,
    //    string listID,
    //    string viewID,
    //    uint toolbarType,
    //    out uint flags)
    MethodInfo applyViewToListWebPart = typeof(SPWebPartCollection).GetMethod(
      "ApplyViewToListWebPart",
      BindingFlags.NonPublic | BindingFlags.Instance,
      null,
      new[]{
        typeof(string),
        typeof(string),
        typeof(string),
        typeof(uint),
        typeof(uint).MakeByRefType()
      },
      null);
    object[] parameters = new object[5];
    parameters[0] = storageKey;
    parameters[1] = listId;
    parameters[2] = viewId;
    parameters[3] = toolbarType;
    applyViewToListWebPart.Invoke(webParts, parameters);
#pragma warning restore 618
  }
}

public enum ListViewWebPartToolbarType {
  Full = 0,
  Summary = 1,
  NoToolbar = 2
}
</pre>
<p></p>
<p>And here is how to use the code... </p><pre style="WIDTH: 500px; OVERFLOW: scroll" class="prettyprint">SPFile homePage = _ctx.Site.Files["default.aspx"];
SPLimitedWebPartManager limitedWebPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
ListViewWebPart webPart = (ListViewWebPart)limitedWebPartManager.WebParts[0];
webPart.SetToolbarType(limitedWebPartManager, ListViewWebPartToolbarType.NoToolbar);
limitedWebPartManager.SaveChanges(webPart);
</pre>
<p></p>
<p>And here is my rant to Microsoft that each and everyone of these articles about this issue must include... Really, Microsoft did you not think that people would want to do this. You have had 2 service packs come out for SharePoint and you couldn't have fixed this yet. Please fix this in SharePoint 2010. </p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/changing_the_toolbar_on_a_shar.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/changing_the_toolbar_on_a_shar.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">C#</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">ListViewWebPart</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">SharePoint</category>
            
            <pubDate>Sun, 12 Jul 2009 19:58:27 -0500</pubDate>
        </item>
        
        <item>
            <title>Calling a private .NET method with ref or out parameters using reflection</title>
            <description><![CDATA[<p>I needed this yesterday and was amazed at how many forums and blogs I needed to visit before I found the answer. So I decided to blog about it myself so that I wouldn't forget about where to find the answer again.</p>
<p>If you have a class like this and need to call "PrivateMethod" <pre class="prettyprint">public class PrivateMethodClass {
  private int PrivateMethod(int arg1, ref int arg2, out int arg3) {
    arg2 = arg2 + 10;
    arg3 = 999;
    return arg1;
  }
}
</pre>
<p></p>
<p>This is the code you need to call it <pre class="prettyprint">PrivateMethodClass target = new PrivateMethodClass();
MethodInfo methodInfo = typeof(PrivateMethodClass).GetMethod(
  "PrivateMethod",
  BindingFlags.NonPublic | BindingFlags.Instance,
  null,
  new[] {
    typeof(int), 
    typeof(int).MakeByRefType(), 
    typeof(int).MakeByRefType()
  },
  null);
object[] parameters = new object[3];
parameters[0] = 1;
parameters[1] = 2;
parameters[2] = 3;
int result = (int)methodInfo.Invoke(target, parameters);
Console.WriteLine("parameter[0]: " + parameters[0]);
Console.WriteLine("parameter[1]: " + parameters[1]);
Console.WriteLine("parameter[2]: " + parameters[2]);
Console.WriteLine("result: " + result);
</pre>
<p></p>
<p>There are two things that are different from a typical reflection call. The first is the call to "MakeByRefType" which as the name suggests makes a reference type from a type. This is required for a "ref" or a "out" parameter. The second is the creation of the parameters array before invoking the method. </p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/calling_a_private_method_with.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/calling_a_private_method_with.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">.NET</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">C#</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">reflection</category>
            
            <pubDate>Sun, 12 Jul 2009 16:38:30 -0500</pubDate>
        </item>
        
        <item>
            <title>How to add a custom action to a SharePoint list actions menu for a specific list or content type.</title>
            <description><![CDATA[<p>
If you have ever tried adding a SharePoint custom action to the actions menu and tried using "List" or "ContentType" as the "RegistrationType" and then tried to specify a specific list or content type in the "RegistrationId" you know that it doesn't work. SharePoint will silently not render your custom action. If you try and target a generic list using a "RegistrationId" of "100" you will see that SharePoint will gladly render your action on every list in the site. I have found a rather kludgy work around to the problem.
</p>
<p>
First off in your element manifest file you need to use the "ControlAssembly" and "ControlClass" attributes off of CustomAction. MSDN doesn't say a whole lot about these attributes but essentially they allow you to specify a web control class in your assembly which can render the action. (If you need to create hierarchical menus check out this <a href="http://weblogs.asp.net/jan/archive/2008/05/08/creating-hierarchical-menus-with-a-customaction-in-sharepoint.aspx">article</a>.) Here is the XML to get you started:
</p>
<pre class="prettyprint">
&lt;Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt;
  &lt;CustomAction
    Id="MyCustomAction"
    RegistrationType="List"
    GroupId="ActionsMenu"
    Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1000"
    ControlAssembly="[Fully qualified assembly name]"
    ControlClass="MyNamespace.MyCustomAction"&gt;
  &lt;/CustomAction&gt;
&lt;/Elements&gt;
</pre>
<p>
Next you will need to create a web control class which renders the menu item, as seen below:
</p>
<pre class="prettyprint">
public class MyCustomAction : WebControl {
  private MenuItemTemplate _action;

  protected override void CreateChildControls() {
    SPWeb site = SPContext.Current.Web;

    _action = new MenuItemTemplate {
      Text = "My Action",
      Description = "My Action",
      ImageUrl = "/_layouts/images/NEWITEM.GIF",
      ClientOnClickNavigateUrl = "http://www.nearinfinity.com"
    };

    Controls.Add(_action);
  }
}
</pre>
<p>
Compile and deploy your solution. Oh and make sure to add your assembly and namespace to the safe control list or you will end up pulling your hair out because once again SharePoint will silently not render your menu item. You should now see the "My Action" on every list in the site. We have now reproduced what a standard CustomAction element in your element manifest would do normally. Now we need to find a way to determine which list our control is being added to. The best way I found for doing that is to traverse the control hierarchy up the parent chain until I found the containing ListViewWebPart. The code is quite simple and looks like this:
</p>
<pre class="prettyprint">
private ListViewWebPart GetParentListViewWebPart() {
  Control parent = Parent;
  while (parent != null) {
    if (parent is ListViewWebPart) {
      return (ListViewWebPart)parent;
    }
    parent = parent.Parent;
  }
  return null;
}
</pre>
<p>
You should know where I'm going with this now, but for completness I will show you the last piece of code below which restricts it to a single list instance:
</p>
<pre class="prettyprint">
private Guid TARGET_LIST_ID = new Guid ("0D9B9302-8599-4CE5-8695-1B95FE7378F1");

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  if (!Page.IsPostBack) {
    EnsureChildControls();
    _action.Visible = false;
    ListViewWebPart listView = GetParentListViewWebPart();
    if (listView != null) {
      Guid listGuid = new Guid(listView.ListName);
      if (TARGET_LIST_ID == listGuid) {
        _action.Visible = true;
      }
    }
  }
}
</pre>
<p>
Now that we have the list Guid that our control is being rendered for I will leave it as an exercise to the reader to restrict it to a given content type.
</p>
<p>
Why SharePoint doesn't provide this kind of functionality out of the box amazes me, but at least they provide a powerful API that you can get in there and work around it in a not so horribly kludgy way. Maybe SharePoint 2010 will include this :)
</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/how_to_add_a_custom_action_to.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/how_to_add_a_custom_action_to.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">.NET</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">SharePoint</category>
            
            <pubDate>Sun, 10 May 2009 12:35:59 -0500</pubDate>
        </item>
        
        <item>
            <title>Micro-optimization</title>
            <description><![CDATA[<p>This is my attempt at micro-optimizing code that Jeff Atwood posted about <a href="http://www.codinghorror.com/blog/archives/001218.html#comments">micro-optimization</a>. To summarize Jeff talks about 5 ways to do string concatenation and how the difference between them is negligible compared to the readability trade-offs. I agree with him 100%, unless you are faced with the need to optimize to that level make it readable first and fast second. I did on the other hand want to know why string.Concat was the fastest.</p>

<p>I&#8217;m going to ignore samples 2 (String.Format) and 4 (String.Replace) because those are obviously going to be slow. They require parsing the string to find tokens.</p>

<p>Sample 5 (StringBuilder) is a little more interesting. Looking at the StringBuilder in <a href="http://www.red-gate.com/products/reflector/">Reflector</a> you&#8217;ll see it&#8217;s doing some tricks under the cover to handle multi-threaded access to the StringBuilder object. Which from what I can deduce causes performance degradations. Not to mention the need to make 10 method calls (Append) and one object allocation (StringBuilder) from my code.</p>

<p>Sample 1 (Simple Concatenation) and 3 (string.Concat) are actually identical when viewed in <a href="http://www.red-gate.com/products/reflector/">Reflector</a> (other than the minor difference of new lines, but that is caused by the difference in the code).

<table border="1">
    <tr>
        <td>
            1. Simple Concatenation
            <pre class="prettyprint" style="width: 250px;">
.maxstack 3
.locals init (
    [0] string s,
    [1] string CS$1$0000,
    [2] string[] CS$0$0001)
L_0000: nop 
L_0001: ldc.i4.s 10
L_0003: newarr string
L_0008: stloc.2 
L_0009: ldloc.2 
L_000a: ldc.i4.0 
L_000b: ldstr "&lt;div class=\"user-action-time\">"
L_0010: stelem.ref 
L_0011: ldloc.2 
L_0012: ldc.i4.1 
L_0013: call string perftest.Program::st()
L_0018: stelem.ref 
L_0019: ldloc.2 
L_001a: ldc.i4.2 
L_001b: call string perftest.Program::st()
L_0020: stelem.ref 
L_0021: ldloc.2 
L_0022: ldc.i4.3 
L_0023: ldstr "&lt;/div>\r\n&lt;div class=\"user-gravatar32\">"
L_0028: stelem.ref 
L_0029: ldloc.2 
L_002a: ldc.i4.4 
L_002b: call string perftest.Program::st()
L_0030: stelem.ref 
L_0031: ldloc.2 
L_0032: ldc.i4.5 
L_0033: ldstr "&lt;/div>\r\n&lt;div class=\"user-details\">"
L_0038: stelem.ref 
L_0039: ldloc.2 
L_003a: ldc.i4.6 
L_003b: call string perftest.Program::st()
L_0040: stelem.ref 
L_0041: ldloc.2 
L_0042: ldc.i4.7 
L_0043: ldstr "&lt;br/>"
L_0048: stelem.ref 
L_0049: ldloc.2 
L_004a: ldc.i4.8 
L_004b: call string perftest.Program::st()
L_0050: stelem.ref 
L_0051: ldloc.2 
L_0052: ldc.i4.s 9
L_0054: ldstr "&lt;/div>"
L_0059: stelem.ref 
L_005a: ldloc.2 
L_005b: call string [mscorlib]System.String::Concat(string[])
L_0060: stloc.0 
L_0061: ldloc.0 
L_0062: stloc.1 
L_0063: br.s L_0065
L_0065: ldloc.1 
L_0066: ret</pre>
            </td>
            <td>
                3. string.Concat
                <pre class="prettyprint" style="width: 250px;">.maxstack 3
.locals init (
    [0] string s,
    [1] string CS$1$0000,
    [2] string[] CS$0$0001)
L_0000: nop 
L_0001: ldc.i4.s 10
L_0003: newarr string
L_0008: stloc.2 
L_0009: ldloc.2 
L_000a: ldc.i4.0 
L_000b: ldstr "&lt;div class=\"user-action-time\">"
L_0010: stelem.ref 
L_0011: ldloc.2 
L_0012: ldc.i4.1 
L_0013: call string perftest.Program::st()
L_0018: stelem.ref 
L_0019: ldloc.2 
L_001a: ldc.i4.2 
L_001b: call string perftest.Program::st()
L_0020: stelem.ref 
L_0021: ldloc.2 
L_0022: ldc.i4.3 
L_0023: ldstr "&lt;/div>&lt;div class=\"user-gravatar32\">"
L_0028: stelem.ref 
L_0029: ldloc.2 
L_002a: ldc.i4.4 
L_002b: call string perftest.Program::st()
L_0030: stelem.ref 
L_0031: ldloc.2 
L_0032: ldc.i4.5 
L_0033: ldstr "&lt;/div>&lt;div class=\"user-details\">"
L_0038: stelem.ref 
L_0039: ldloc.2 
L_003a: ldc.i4.6 
L_003b: call string perftest.Program::st()
L_0040: stelem.ref 
L_0041: ldloc.2 
L_0042: ldc.i4.7 
L_0043: ldstr "&lt;br/>"
L_0048: stelem.ref 
L_0049: ldloc.2 
L_004a: ldc.i4.8 
L_004b: call string perftest.Program::st()
L_0050: stelem.ref 
L_0051: ldloc.2 
L_0052: ldc.i4.s 9
L_0054: ldstr "&lt;/div>"
L_0059: stelem.ref 
L_005a: ldloc.2 
L_005b: call string [mscorlib]System.String::Concat(string[])
L_0060: stloc.0 
L_0061: ldloc.0 
L_0062: stloc.1 
L_0063: br.s L_0065
L_0065: ldloc.1 
L_0066: ret</pre>
            </td>
        </tr>
    </table>
</p>

<p> So now lets get to why I&#8217;m writing this post. Trying to micro-optimize code that is already micro-optimized. So lets start by looking at what string.Concat is doing inside.
<pre class="prettyprint">public static string Concat(params string[] values)
{
    int totalLength = 0;
    if (values == null)
    {
        throw new ArgumentNullException("values");
    }
    string[] strArray = new string[values.Length];
    for (int i = 0; i < values.Length; i++)
    {
        string str = values[i];
        strArray[i] = (str == null) ? Empty : str;
        totalLength += strArray[i].Length;
        if (totalLength < 0)
        {
            throw new OutOfMemoryException();
        }
    }
    return ConcatArray(strArray, totalLength);
}</pre>
Allocating a new array, that's got to take some time, and in fact it does, not much but it does take time. So do we have an alternative? Sure by using "string.Concat(string str0, string str1, string str2, string str3)". Looking at it's code it does essentially the same thing as "string.Concat(params string[] values)" but without the new array. So without further ado here is my over micro-optimized code.
<pre class="prettyprint">string s =
string.Concat(
    string.Concat(@"&lt;div class=""user-action-time"">", st(), st()),
    string.Concat(@"&lt;/div>&lt;div class=&#8221;&#8220;user-gravatar32&#8221;&#8220;>&#8221;, st(), @&#8221;&lt;/div>&lt;div class=&#8221;&#8220;user-details&#8221;&#8220;>&#8221;, st()),
    string.Concat(&#8220;&lt;br/>&#8221;, st(), &#8220;&lt;/div>&#8221;));
return s;</pre>
This code makes sure to only use the string.Concat that takes 4 arguments instead of the variable number of arguments. This speeds up the code by a whopping 2-3% on my machine. Sure it makes the code even more unreadable but if you are doing this 10 trillion times that might be necessary.
</p>
]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/micro-optimization.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/micro-optimization.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">performance</category>
            
            <pubDate>Fri, 30 Jan 2009 09:34:35 -0500</pubDate>
        </item>
        
        <item>
            <title>Is F# faster than C#</title>
            <description><![CDATA[<h3>Description</h3>
<p>
	I had a bet with a co-worker that C# would outperform F# for a simple counting exercise. This
	turned out to be quite a surprise for many reasons. In this blog post I will try to explain why.
</p>

<style>
  .codeComment {
    color: #008000;
  }
  .codeKeyword {
    color: #0000FF;
  }
  .codeString {
    color: #A31515;
  }
   .prettyTable {
   border-collapse:collapse;
   border: 1px solid black;
  }
  .prettyTable td {
    border: 1px solid black;
  }
  .prettyTable th {
    border: 1px solid black;
  }
</style>


<h3>Problem</h3>
<p>
	Sum the numbers from 1 to n using brute force (can't use the (1 + N)*(N/2) equation). Do this
	in both C# and F# and compare the speed. Since F# needs to do this recursively I thought this should
	be a no contest win for C#.
</p>

<h3>Using F#</h3>
<p>
	We initially wrote the code without using tail recursion which immediately ended with a stack
	overflow. So we went back and wrote it doing it the functional way, with tail recursion.
	Here is what we came up with.
	</p><pre class="prettyprint"><span class="codeKeyword">module</span> FSharpLib

	<span class="codeKeyword">let</span> sumNum fromNum toNum =
		<span class="codeKeyword">let</span> <span class="codeKeyword">rec</span> sumNumTail fromNum toNum result =
			<span class="codeKeyword">if</span> fromNum &gt; toNum then 
				result 
			<span class="codeKeyword">else</span> 
				sumNumTail (fromNum+1L) toNum (result+fromNum)
		sumNumTail fromNum toNum 0L</pre>


<h3>Using C# - Attempt 1</h3>
<p>
	You'll see later why I say attempt 1. But, this is the simplest C# code <b>I</b> could think of.
	</p><pre class="prettyprint"><span class="codeKeyword">public</span> <span class="codeKeyword">static</span> <span class="codeKeyword">long</span> CSharpForLoop(<span class="codeKeyword">long</span> fromNumber, <span class="codeKeyword">long</span> toNumber) {
	<span class="codeKeyword">long</span> result = 0;
	<span class="codeKeyword">for</span> (<span class="codeKeyword">long</span> i = fromNumber; i &lt;= toNumber; i++) {
		result += i;
	}
	<span class="codeKeyword">return</span> result;
}</pre>


<h3>The Results - Attempt 1</h3>
<p>
	This is the results of running the above code using a fromNumber of 1 and a toNumber of
	10000000 and running it 10 times alternating between C# and F# to filter out start-up times, etc.
	<br /><br />
	</p><table class="prettyTable" cellpadding="2" cellspacing="0">
		<tbody><tr><th>F#</th><td>0.8606902s</td><td>11% faster</td></tr>
		<tr><th>C#</th><td>0.9556198s</td><td></td></tr>
	</tbody></table>
	<br />
	I ran it like 20 times because I couldn't believe it. I looked at the C# code for any possible
	optimizations I could add. But, being so simple there wasn't a lot I could do.


<h3>Reflector is an amazing tool</h3>
<p>
	I turned to my good friend <a href="http://www.red-gate.com/products/reflector/">Reflector</a>
	to see what was going on. Here is what the F# code looked like when viewing it as C# code.
	</p><pre class="prettyprint"><span class="codeKeyword">public</span> <span class="codeKeyword">static</span> <span class="codeKeyword">long</span> sumNum(<span class="codeKeyword">long</span> fromNum, <span class="codeKeyword">long</span> toNum)
{
    FastFunc&lt;<span class="codeKeyword">long</span>, FastFunc&lt;<span class="codeKeyword">long</span>, FastFunc&lt;<span class="codeKeyword">long</span>, <span class="codeKeyword">long</span>&gt;&gt;&gt; sumNumTail = <span class="codeKeyword">new</span> clo@7();
    <span class="codeKeyword">return</span> FastFunc&lt;<span class="codeKeyword">long</span>, <span class="codeKeyword">long</span>&gt;.InvokeFast3&lt;<span class="codeKeyword">long</span>, <span class="codeKeyword">long</span>&gt;(sumNumTail, fromNum, toNum, 0L);
}</pre>
	and clo@7.Invoke looks like
	<pre class="prettyprint"><span class="codeKeyword">public</span> <span class="codeKeyword">override</span> <span class="codeKeyword">long</span> Invoke(<span class="codeKeyword">long</span> fromNum, <span class="codeKeyword">long</span> toNum, <span class="codeKeyword">long</span> result)
{
	<span class="codeKeyword">while</span> (fromNum &lt;= toNum)
	{
		result += fromNum;
		toNum = toNum;
		fromNum += 1L;
	}
	<span class="codeKeyword">return</span> result;
}</pre>
	They used a while loop instead of a for loop. OK, I can do that. But, what happened to <a href="http://books.google.com/books?id=50PhgS8vjhwC&amp;pg=PA511&amp;vq=tail&amp;dq=cil+instruction+reference+tail&amp;source=gbs_search_s&amp;cad=0">tail</a>, I thought that tail is why the CLR is so good at functional language implementations.


<h3>C# - Attempt 2</h3>
<p>
	</p><pre class="prettyprint"><span class="codeKeyword">public</span> <span class="codeKeyword">static</span> <span class="codeKeyword">long</span> CSharpWhileLoop(<span class="codeKeyword">long</span> fromNumber, <span class="codeKeyword">long</span> toNumber) {
	<span class="codeKeyword">long</span> result = 0;
	<span class="codeKeyword">while</span> (fromNumber &lt;= toNumber)
	{
		result += fromNumber;
		<span class="codeComment">// I left out the toNum = toNum because it didn't do anything.</span>
		fromNumber += 1L;
	}
	<span class="codeKeyword">return</span> result;
}</pre>

	and the results (I've got you now F#)...
	<br /><br />
	<table class="prettyTable" cellpadding="2" cellspacing="0">
		<tbody><tr><th>F#</th><td>0.8606902s</td></tr>
		<tr><th>C# For Loop</th><td>0.9556198s</td></tr>
		<tr><th>C# While Loop</th><td>0.9105592s</td></tr>
	</tbody></table>
	<br />
	Oh wait... DAMN! What could F# be doing to make it almost 10% faster than C#.


<h3>To the IL code Batman</h3>
<p>
	This is the IL for the F# code.
	</p><pre class="prettyprint">	L_0000: nop              <span class="codeComment">// while loop</span>
	L_0001: nop 
	L_0002: ldarg.1          <span class="codeComment">// fromNum &lt;= toNum</span>
	L_0003: ldarg.2 
	L_0004: ble.s L_0009     
	L_0006: nop              <span class="codeComment">// return result</span>
	L_0007: ldarg.3 
	L_0008: ret              
	L_0009: nop              <span class="codeComment">// result += fromNum</span>
	L_000a: ldarg.1 
	L_000b: ldc.i8 1
	L_0014: add              
	L_0015: ldarg.2          <span class="codeComment">// fromNum += 1L</span>
	L_0016: ldarg.3 
	L_0017: ldarg.1 
	L_0018: add              
	L_0019: starg.s result   <span class="codeComment">// loop</span>
	L_001b: starg.s toNum
	L_001d: starg.s fromNum
	L_001f: br.s L_0000      
	</pre>
	This is the IL for the C# while loop.
	<pre class="prettyprint">	L_0000: nop                   <span class="codeComment">// long result = 0L</span>
	L_0001: ldc.i4.0
	L_0002: conv.i8 
	L_0003: stloc.0               
	L_0004: br.s L_0012           <span class="codeComment">// while loop</span>
	L_0006: nop                   <span class="codeComment">// result += fromNumber</span>
	L_0007: ldloc.0 
	L_0008: ldarg.0 
	L_0009: add                   
	L_000a: stloc.0               <span class="codeComment">// fromNumber += 1L</span>
	L_000b: ldarg.0 
	L_000c: ldc.i4.1 
	L_000d: conv.i8 
	L_000e: add                   
	L_000f: starg.s fromNumber    
	L_0011: nop 
	L_0012: ldarg.0               <span class="codeComment">// fromNumber &lt;= toNumber</span>
	L_0013: ldarg.1 
	L_0014: cgt 
	L_0016: ldc.i4.0 
	L_0017: ceq 
	L_0019: stloc.2 
	L_001a: ldloc.2 
	L_001b: brtrue.s L_0006       <span class="codeComment">// loop</span>
	L_001d: ldloc.0 
	L_001e: stloc.1 
	L_001f: br.s L_0021
	L_0021: ldloc.1 
	L_0022: ret 
	</pre>


<h3>What just happened.</h3>
<p>
  Wow, the C# compiler is quite a bit more verbose. First of all, C# makes the while
  loop into a do/while loop. Secondly, in the loop condition C# creates a temporary variable
  to store the comparison and then checks for 'true' ("brtrue.s"). If you look at the F# IL you'll
  see the use of the "ble.s" instructions (branch if less or equal) instead. Finally we see that
  C# uses a few	"conv.i8"	instructions (convert to 8 byte/64-bit int) which I can only guess adds to
  it's defeat.
</p>

<h3>Conclusion</h3>
<p>
	So is F# just a more performant language or is C# just compiling to more robust IL code which
	as F# matures will end up suffering the same fate? I personally think (hope actually) the later
	is true. I'm not an expert in compilers but I would have to assume the C# compiler team is using
	every trick in the book to make highly performant IL code without sacrificing robustness and I can
	only assume that F# will get to a point where it needs to make the same concessions to handle some
	obscure cases.
</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/is_f_faster_than_c.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/is_f_faster_than_c.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
            <pubDate>Thu, 11 Dec 2008 10:47:49 -0500</pubDate>
        </item>
        
        <item>
            <title>DEFCON Badge Hacking</title>
            <description><![CDATA[<p>
I wrote my first firmware for the DEFCON badge. Doesn't do much other than replace the default Knight Rider LED sequence with my own, but it's a first step. I did want to note a couple of things that were not mentioned in the badge hacking information that might make it easier to get started.
</p>
<p>
There are two drivers for windows, one when the badge is in USB bootloader mode and one while the badge is in normal mode. To get to bootloader mode you need to hold down the mode select button while inserting the battery. The driver provided on the CD is for normal mode which took me a while to figure out. To get to the normal mode you need to plug the USB cord in BEFORE you insert the battery. Looking at the firmware I noticed the check for a USB connection is done as one of the very first things. Windows will then recognize the device and you can install the driver from the CD. The driver for bootloader mode is actually part of the Freescale JM60 bootloader program which can also be found on the CD but must be installed before you try bootloader mode.
</p>
<p>
Also, I couldn't get the full version of Code Warrior so the next best thing was the demo from Freescale. But, the demo has a 32k firmware limit which means removing some of the original firmware code. I removed fat.c from the project and recompiled and fixed until I got it working. This will of course remove your ability to read or write to the SD card using FAT.
</p>
<p>
Next step is to make the final hack which will hopefully be done by tomorrow so we can show it off to Kingpin. I'll post the final hack information and code tomorrow if it gets done.
</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/defcon_badge_hacking.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/defcon_badge_hacking.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">General</category>
            
            
            <pubDate>Sun, 10 Aug 2008 05:37:55 -0500</pubDate>
        </item>
        
        <item>
            <title>RemoteLINQ - How to make your LINQ span the globe</title>
            <description><![CDATA[<!-- code formatted by http://manoli.net/csharpformat/ -->
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }

.code {
  border: 1px solid #ccc;
  background-color: #efefef;
  font-size: small;
  padding: 5px;
  line-height: 110%;
}
</style>
<div>
<p>
	After reading <a href="http://msmvps.com/blogs/jon.skeet/default.aspx">John Skeet's blog</a> about <a href="http://msmvps.com/blogs/jon.skeet/archive/2007/10/03/linq-to-silliness-generating-a-mandelbrot-with-parallel-potential.aspx">Generating Mandelbrot images using PLINQ</a>
	I got the idea to build my own LINQ extension. Instead of just splitting the work across processors like PLINQ does, 
	I decided to split it across machines as well. Thus was born RemoteLINQ. The concept is simple, take each item from an
	enumeration and send it to a remote machine for processing. From a users perspective it is just that easy. The magic behind
	the curtains is not. Handling threading, ordering, communication, etc. was and still is difficult. The code I provide is still very beta and I cannot guarantee it won't blow up, but it's getting better and it does generates Mandelbrot
	images just fine across 3 machines containing a total of 5 processors.
</p>
</div>
<p>
</p><h2>Code You Write To Make It Work</h2>
	Here is an example of what you as a user of RemoteLINQ would need to do:
<div class="csharpcode code">
<pre style="overflow: auto;"><span class="lnum">   1:  </span>IEnumerable&lt;<span class="kwrd">int</span>&gt; numbers = Enumerable.Range(0, 500);
<span class="lnum">   2:  </span>RemoteContext remoteContext = <span class="kwrd">new</span> RemoteContext(
<span class="lnum">   3:  </span>   <span class="kwrd">new</span>[] { <span class="kwrd">this</span>.GetType().Assembly }, 
<span class="lnum">   4:  </span>   <span class="kwrd">new</span>[] { <span class="str">"localhost"</span>, <span class="str">"someremotehost"</span> },
<span class="lnum">   5:  </span>   7776);
<span class="lnum">   6:  </span>RemoteOptions remoteOptions = <span class="kwrd">new</span> RemoteOptions();
<span class="lnum">   7:  </span>IEnumerable&lt;<span class="kwrd">int</span>&gt; results = numbers.AsRemotable(remoteContext, remoteOptions).Select(i =&gt; DoSomeWork(i));</pre></div><br />
	This will take the numbers 0 to 500 and send half of the numbers to "localhost" and half of the numbers to "someremotehost"
	for processing.
<p></p>
<p>
	Let's walk through the code.
	</p><ul>
		<li><b>Line 1</b>, gives us an enumerable of numbers from 0 to 500 for processing.</li>
		<li><b>Line 2</b>, creates the RemoteContext. This is really just a client which has a list of server connections to which we can send work.</li>
		<li><b>Line 3</b>, is a list of assemblies that contain the necessary code to run your LINQ statement. The client will actually send 
					a copy of the dll	to the RemoteLINQ server so that the server will have a copy of the "DoSomeWork" (line 7) method so 
					that it can execute it.</li>
		<li><b>Line 4</b>, is the list of servers to divvy the work across.</li>
		<li><b>Line 5</b>, is just the port that the client will try to connect to the server on.</li>
		<li><b>Line 6</b>, contains any options to direct how the work gets split across the servers, etc.</li>
		<li><b>Line 7</b>, is your LINQ statement. Notice the "AsRemotable". This is where all the magic starts.
					This will actually return a IRemoteEnumerable which knows how to take anything to the right of
					it and run it remotely.
	</li></ul>
	Lines 2-6 can be put into some fields somewhere and be reused across multiple RemoteLINQ calls. This will actually
	buy you a couple things. First, you will only have one connection to the server. Second, only one copy of your assemblies
	will be sent across to the server.<br /><br />

<h2>How it works</h2>
<p>
	Lets start out with what lambda expression look like in compiled code. When we compile lambda expressions they are moved into a
	new method with a compiler generated name. If you reflect on a class with lambdas and get all the methods on that type you will see
	a bunch of method names which you didn't create. Those are your lambdas. The fact that they are first class methods allows us
	from the outside, with reflection of course, to call those methods. So when we call "Select" on an IRemoteEnumerable,
	RemoteLINQ is taking the lambda expression passed in, and storing information about it into a serializable object (assembly, 
	declaring type, method name, etc.). This will allow us to send that information to the server, who can then call the method
	without all the other stuff around it.
</p>
<p>
	On the server side of things, when we start up a RemoteLINQ server, it will create a worker thread for each processor in the machine.
	The worker thread will wait quietly until new work arrives on the socket connection. When work arrives we take the serialized object
	I mentioned before and find the assembly, type, and method and execute that method with the work given to us. In this case the work will
	be one of the numbers from 0 to 500. The client will handle load balancing the servers by choosing the server with the least amount of pending
	work per processor. The amount of work queued up on the server is sent back after each unit of work is completed so that the client
	will have the most up to date picture of what the servers are doing to make the best guess as to where to send the next piece of work.
</p>
<p>
	That's about it. You now have a way to split complex LINQ tasks across multiple machine with just a single call on your LINQ statement.
</p>

<p>
  <a href="http://www.fernsroth.com/tech/RemoteLinq.zip">Download The Code</a>
</p><p></p>]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/remotelinq_how_to_make_your.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/remotelinq_how_to_make_your.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
            <pubDate>Thu, 22 May 2008 14:39:29 -0500</pubDate>
        </item>
        
        <item>
            <title>Performance: LINQ to XML vs XmlDocument vs XmlReader</title>
            <description><![CDATA[<!-- code formatted by http://manoli.net/csharpformat/ -->
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }

.resultsTable {
	border-collapse: collapse;
}

.resultsTable th {
	text-align: right;
	border: 1px solid black;
}

.resultsTable td {
	text-align: right;
	border: 1px solid black;
}

.winner {
	background-color: yellow;
}

</style>

I recently had a project where I needed to ingest large XML documents using C# so I was curious which XML reader technology would be the fastest. So I coded up a quick benchmark that would compare LINQ to XML, XmlDocument.Load, and XmlReader against each other.<br /><br /><h2>The Test Data</h2>
I generated a very simple XML file before each run of a test. The id's were random and the number of "child" nodes varied based on the run. The following is an example of the test data I used.
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">root</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">child</span> <span class="attr">id</span><span class="kwrd">='123'</span><span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">child</span> <span class="attr">id</span><span class="kwrd">='234'</span><span class="kwrd">/&gt;</span>
  ...
<span class="kwrd">&lt;/</span><span class="html">root</span><span class="kwrd">&gt;</span></pre>
<h2>The Test</h2>
As I said before I wanted to compare LINQ to XML, XmlDocument.Load, and XmlReader against each other. I ran each of these technologies using 1, 10, 100, 1000, 10,000, 100,000 "child" nodes. I also ran each against a XML document using UTF-8, ASCII, and UTF-32 encodings. Each iteration was run 100 times to reduce anomalies. In each of the tests I call the method "ProcessId" which simulates the processing of the "id" attribute.<br /><br />

<h2>XmlDocument.Load</h2>
I thought the code for XmlDocument.Load was the cleanest and easiest to understand, although I must admit I like XPath. XmlDocument does have some security concerns but that's another post. Here is the code I used to load and search the document:

<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> XmlDocumentReader(<span class="kwrd">string</span> fileName) {
    XmlDocument doc = <span class="kwrd">new</span> XmlDocument();
    doc.Load(fileName);
    XmlNodeList nodes = doc.SelectNodes(<span class="str">"//child"</span>);
    <span class="kwrd">if</span> (nodes == <span class="kwrd">null</span>) {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="str">"invalid data"</span>);
    }
    <span class="kwrd">foreach</span> (XmlNode node <span class="kwrd">in</span> nodes) {
        <span class="kwrd">string</span> id = node.Attributes[<span class="str">"id"</span>].Value;
        ProcessId(id);
    }
}
</pre>
<h2>LINQ to XML</h2>
LINQ to XML was also very easy to read and understand code. I did find that even though LINQ to XML is supposed to use XmlReaders under the covers calling XDocument.Load does read the whole document into memory before returning. So if you are looking for data at the top of middle of a very large document this could be a concern. Here is the code I used to load and search the document:

<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> XDocumentReader(<span class="kwrd">string</span> fileName) {
    XDocument doc = XDocument.Load(fileName);
    <span class="kwrd">if</span> (doc == <span class="kwrd">null</span> | doc.Root == <span class="kwrd">null</span>) {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="str">"invalid data"</span>);
    }
    <span class="kwrd">foreach</span> (XElement child <span class="kwrd">in</span> doc.Root.Elements(<span class="str">"child"</span>)) {
        XAttribute attr = child.Attribute(<span class="str">"id"</span>);
        <span class="kwrd">if</span> (attr == <span class="kwrd">null</span>) {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="str">"invalid data"</span>);
        }
        <span class="kwrd">string</span> id = attr.Value;
        ProcessId(id);
    }
}</pre>
<h2>XmlReader</h2>
XmlReader, specifically XmlTextReader was the hardest to write and understand. With it's quirks of being a forward only reader you need to take what you need while you have it because you can't rewind.

<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> XmlReaderReader(<span class="kwrd">string</span> fileName) {
    <span class="kwrd">using</span> (XmlReader reader = <span class="kwrd">new</span> XmlTextReader(fileName)) {
        <span class="kwrd">while</span> (reader.Read()) {
            <span class="kwrd">if</span> (reader.NodeType == XmlNodeType.Element) {
                <span class="kwrd">if</span> (reader.Name == <span class="str">"child"</span>) {
                    reader.MoveToAttribute(<span class="str">"id"</span>);
                    <span class="kwrd">string</span> id = reader.Value;
                    ProcessId(id);
                }
            }
        }
    }
}</pre>
<h2>The Results</h2>
The following results are in milliseconds for each run. I took the total time to run and divided it by 100.<br />
<br />

<h3>UTF8Encoding</h3>
<table class="resultsTable" border="0" cellpadding="4" cellspacing="0"><tbody><tr><th style="border: 0pt none ;"></th><th>1</th><th>10</th><th>100</th><th>1,000</th><th>10,000</th><th>100,000</th></tr><tr><th>XmlDocument</th><td>0.1567800</td><td>0.1713450</td><td>0.3888620</td><td>1.9816480</td><td>22.8049260</td><td>459.8570340</td></tr><tr><th>XmlReader</th><td class="winner">0.1467460</td><td class="winner">0.1439580</td><td class="winner">0.2300500</td><td class="winner">0.8534400</td><td class="winner">7.5771640</td><td class="winner">76.8635690</td></tr><tr><th>LINQ to XML</th><td>0.1499530</td><td>0.1500640</td><td>0.2778720</td><td>1.4616730</td><td>15.7719020</td><td>208.9360300</td></tr></tbody></table>
<br />

<h3>ASCIIEncoding</h3>
<table class="resultsTable" border="0" cellpadding="4" cellspacing="0"><tbody><tr><th style="border: 0pt none ;"></th><th>1</th><th>10</th><th>100</th><th>1,000</th><th>10,000</th><th>100,000</th></tr><tr><th>XmlDocument</th><td>0.1659350</td><td>0.1922080</td><td>0.3433140</td><td>1.9846330</td><td>22.5484690</td><td>482.8699720</td></tr><tr><th>XmlReader</th><td>0.1376840</td><td class="winner">0.1453730</td><td class="winner">0.2199810</td><td class="winner">0.8768260</td><td class="winner">7.9187380</td><td class="winner">77.7760560</td></tr><tr><th>LINQ to XML</th><td class="winner">0.1345900</td><td>0.1573340</td><td>0.2848420</td><td>1.4889930</td><td>15.1504500</td><td>214.9338990</td></tr></tbody></table>
<br />

<h3>UTF32Encoding</h3>
<table class="resultsTable" border="0" cellpadding="4" cellspacing="0"><tbody><tr><th style="border: 0pt none ;"></th><th>1</th><th>10</th><th>100</th><th>1,000</th><th>10,000</th><th>100,000</th></tr><tr><th>XmlDocument</th><td>0.1672370</td><td>0.1799780</td><td>0.4156250</td><td>2.7188370</td><td>30.6423960</td><td>543.4604540</td></tr><tr><th>XmlReader</th><td>0.1386820</td><td class="winner">0.1503870</td><td class="winner">0.2867400</td><td class="winner">1.4981070</td><td class="winner">14.4428430</td><td class="winner">152.7660780</td></tr><tr><th>LINQ to XML</th><td class="winner">0.1317060</td><td>0.1866610</td><td>0.5385940</td><td>2.3631290</td><td>21.4566290</td><td>274.3280280</td></tr></tbody></table>
<br />
        
<h2>Conclusion</h2>
XmlReader beats LINQ to XML in almost every run except for very small XML documents. What's interesting is how the numbers scale between the encodings. XmlReader is over twice as slow when reading UTF-32 documents verse UTF-8 or ASCII encoded XML, yet LINQ to XML and XmlDocument slowed down by a much smaller amount.

If you need speed when reading XML documents stick with XmlReader. If you need readability and maintainability of your code go with LINQ to SQL or XmlDocument.]]></description>
            <link>http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html</link>
            <guid>http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">.NET</category>
            
            
            <pubDate>Thu, 01 May 2008 11:31:58 -0500</pubDate>
        </item>
        
    </channel>
</rss>
