<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Mike Stall's .NET Debugging Blog</title><link>http://blogs.msdn.com/b/jmstall/</link><description>Notes on Managed Debugging, ICorDebug, and random .NET stuff</description><dc:language>en-US</dc:language><generator>Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><item><title>Reflection vs. Metadata</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/08/06/reflection-vs-metadata.aspx</link><pubDate>Mon, 06 Aug 2012 21:21:26 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10337301</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10337301</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/08/06/reflection-vs-metadata.aspx#comments</comments><description>&lt;p&gt;Here are some old notes I had about Reflection vs. the raw IMetadata Import interfaces. They’re from a while ago (before CLR 4.0 was shipped!), but still relevant. Better to share late than never!&lt;/p&gt;  &lt;p&gt;Quick reminder on the two APIs I’m comparing here:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Reflection is the managed API (System.Type and friends) for reading metadata. The CLR’s implementation is built on top of the CLR loader, and so it’s geared towards a “live” view of the metadata.&amp;#160; This is what everybody uses because it’s just so easy. The C# typeof() keyword gives you a System.Type and you’re already into the world of reflection. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ms230172.aspx"&gt;IMetaDataImport&lt;/a&gt; is an unmanaged COM-classic API which is much lower level. ILDasm is built on IMetadataImport. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The executive summary is that the &lt;i&gt;IMetadata APIs are a file format decoder &lt;/i&gt;and returns raw information. The &lt;i&gt;Reflection APIs are a much higher abstraction level &lt;/i&gt;that include the metadata and other information in the PE file, fusion, CLR loader, and present a high-level type-system object model. &lt;/p&gt;  &lt;p&gt;This difference means that while Reflection and Metadata are conceptually similar, there are things in &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2008/05/23/stuff-in-reflection-that-s-not-in-metadata.aspx"&gt;Reflection that aren’t in the metadata&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2008/03/15/things-in-metadata-that-are-missing-in-reflection.aspx"&gt;things in the metadata that aren’t exposed in reflection&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;This is not an exhaustive list. &lt;/p&gt;  &lt;h1&gt;Differences because Reflection can access the loader&lt;/h1&gt;  &lt;p&gt;&lt;b&gt;Reflection explicitly does eager assembly loading&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;The only input to IMetaDataImport is the actual bits in a file. It is a purely static API.&lt;/p&gt;  &lt;p&gt;In contrast, reflection is a veneer over the CLR loader and thus can use the CLR Loader, fusion, assembly resolution, and policy from current CLR bindings as input.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;In my opinion, that’s the most fundamental difference between them, and the root cause of many other differences&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;This means that reflection can use assembly resolution, and that causes many differences with raw IMetadataImport:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;auto resolving a TypeRef and TypeSpecs to a TypeDef. You can't even retrieve the original typeRef/TypeSpec tokens from the reflection APIs (the metadata tokens it gives back are for the TypeDefs). Same for MethodDef vs. MemberRef.&lt;/li&gt;    &lt;li&gt;Type.GetInterfaces() - it returns interfaces from the base type.&lt;/li&gt;    &lt;li&gt;Type.GetGenericArguments() - as noted here already.&lt;/li&gt;    &lt;li&gt;random APIs like: Type.IsClass, IsEnum, IsValueType - these check the base class, and thus force resolution.&lt;/li&gt;    &lt;li&gt;determining if a MemberRef token is a constructor or a method because they have different derived classes (see below).&lt;/li&gt;    &lt;li&gt;representing illegal types (&amp;quot;Foo&amp;amp;&amp;amp;&amp;quot;). Reflection is built on the CLR Loader, which eagerly fails when loading an illegal type. (See below.)&lt;/li&gt;    &lt;li&gt;Assembly.GetType(string name) will automatically follow &lt;a href="http://blogs.msdn.com/thottams/archive/2006/11/17/typeforwarding-typeforwardedto-attribute-in-runtime-compilerservices.aspx"&gt;TypeForwarders&lt;/a&gt;, which will cause assembly loading. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The practical consequence is that a tool like ILDasm can use IMetaDataImport to inspect a single assembly (eg, Winforms.dll) without needing to do assembly resolution. Whereas a reflection-based tool would need to resolve the assembly references.&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Different inputs&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;While Reflection is mostly pure and has significant overlap with the metadata, there is no barrier to prevent runtime input sources from leaking through the system and popping up in the API.&amp;#160; Reflection exposes things not in the PE-file, such as:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;additional interfaces injected onto arrays by the CLR loader&amp;#160; (see &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2008/05/23/stuff-in-reflection-that-s-not-in-metadata.aspx"&gt;here&lt;/a&gt;). &lt;/li&gt;    &lt;li&gt;Type.get_Guid - if the guid is not represented in the metadata via a Guid attribute, reflection gets the guid via a private algorithm buried within the CLR.&amp;#160; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&lt;b&gt;Generics + Type variables + GetGenericArguments()&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;In Reflection, calling GetGenericArguments() on a open generic type returns the System.Type objects for type-variables. Whereas in metadata, this would be illegal. You could at best get the generic argument definitions from the type definition.&lt;/p&gt;  &lt;p&gt;In reflection, if you pass in Type variables to Type.MakeGenericType(), you can get back a type-def. Whereas in metadata, you'd still have a generic type. Consider the following snippet:&lt;/p&gt;  &lt;div class="csharpcode"&gt;   &lt;pre class="alt"&gt;var t = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Q2&amp;lt;&amp;gt;); &lt;span class="rem"&gt;// some generic type Q2&amp;lt;T&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;var a1 = t.GetGenericArguments(); &lt;span class="rem"&gt;// {&amp;quot;T&amp;quot;}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre class="alt"&gt;var t2 = t.MakeGenericType(a1); &lt;/pre&gt;

  &lt;pre&gt;Debug.Assert(t.Equals(t2)); &lt;/pre&gt;

  &lt;pre class="alt"&gt;Debug.Assert(t2.Equals(t)); &lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;In other words, metadata has 2 distinct concepts:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The generic type arguments in the type definition (see IMDI2::EnumGenericParams)&lt;/li&gt;

  &lt;li&gt;The generic type arguments from a type instantiation (as retrieved from a signature blob, see CorElementType.GenericInsantiation=0x15).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
  &lt;p&gt;In reflection, these 2 concepts are unified together under the single Type.GetGenericArguments() API. Answering #1 requires type resolution whereas #2 can be done on a type-ref. This means that in reflection, you can't check for generic arguments without potentially doing resolution.&lt;/p&gt;

  &lt;p&gt;&lt;b&gt;PE-files&lt;/b&gt;&lt;/p&gt;
&lt;/p&gt;

&lt;p&gt;Reflection exposes interesting data in the PE-file, regardless of whether it's stored in the metadata or rest of the PE-file.&lt;/p&gt;

&lt;p&gt;Metadata is just the metadata blob within the PE file. It's somewhat arbitrary what's in metadata vs. not. Metadata can have RVAs to point to auxiliary information, but the metadata importer itself can't resolve those RVAs.&lt;/p&gt;

&lt;p&gt;Interesting data in the PE but outside of the metadata:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;the entry point token is in CorHeaders outside of the metadata. &lt;/li&gt;

  &lt;li&gt;Method bodies (including their exception information) are outside the metadata.&amp;#160; &lt;/li&gt;

  &lt;li&gt;RVA-based fields (used for initializing constant arrays)&lt;/li&gt;

  &lt;li&gt;embedded resources&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;b&gt;File management&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;It is possible to set policy on AppDomain that will require Assembly.Load to make a shadow copy of an assembly before it's loaded and open that copy instead of assembly in the original location. This policy allows user to specify where shadow copies should be created. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;Failure points&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;IMetadataImport only depends on the bits in the file, so it has few failure points after opening. In contrast, Reflection has many dependencies, each of which can fail. Furthermore, there is no clear mapping between a reflection API and the services it depends on, so many reflection APIs can randomly fail at random points. &lt;/p&gt;

&lt;p&gt;Also, IMetadataImport allows representing invalid types, whereas Reflection will eagerly fail. For example, it is illegal to have a by-ref to a by-ref, (eg, &amp;quot;Foo&amp;amp;&amp;amp;&amp;quot;). Such a type can still be encoded in the metadata file format via ildasm, and IMetaDataImport will load it and provide the signature bytes. However, Reflection will eagerly fail importing because the CLR Loader won't load the type. &lt;/p&gt;

&lt;p&gt;Detecting failures requires eagerly resolving types, so there is a tension between making Reflection a deferred API vs. keeping the eager-failure semantics. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;COM-Interop&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Reflection represents types at runtime, like COM-interop objects. Whereas metadata only provides a static typing. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;Loader-added interfaces on arrays&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;In .Net 2.0, generic interfaces are added for arrays at runtime. So this expression &amp;quot;typeof(int[]).GetInterfaces()&amp;quot; returns a different result on .NET 2.0 vs. .NET 1.1; even if it's an identical binary. I mentioned this example in more detail &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2008/05/23/stuff-in-reflection-that-s-not-in-metadata.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;Differences in Object model&lt;/h1&gt;

&lt;p&gt;Reflection deliberately tries to be a higher level friendly managed API, and that leads to a bunch of differences&lt;/p&gt;

&lt;p&gt;&lt;b&gt;MemberInfo.ReflectedType property&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Reflection has a &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.reflectedtype.aspx"&gt;ReflectedType&lt;/a&gt; property which is set based on how an item is queried. So the same item, queried from different sources, will have a different ReflectedType property, and thus compare differently. This property is entirely a fabrication of the reflection object model and does not correspond to the PE file or metadata.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Different object models for Type&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;The raw metadata format is very precise and represents types in a variety of distinct ways:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;TypeDef&lt;/li&gt;

  &lt;li&gt;TypeRef&lt;/li&gt;

  &lt;li&gt;TypeSpec, Signature blobs&lt;/li&gt;

  &lt;li&gt;builtins (&amp;quot;I4&amp;quot;) &lt;/li&gt;

  &lt;li&gt;arrays,&lt;/li&gt;

  &lt;li&gt;modifiers (pointer, byref)&lt;/li&gt;

  &lt;li&gt;Type variables (!0, !!0)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These are all unique separate entities with distinct properties which in the metadata model, conceptually do not share a base class. In contrast, Reflection unifies these all into a single common System.Type object. So in reflection, you can't find out if your class’s basetype is a TypeDef or a TypeRef.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Psuedo-custom attributes&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Reflection exposes certain random pieces of metadata as faked-up custom attribute instead of giving it a dedicated API the way IMetaDataImport does. &lt;/p&gt;

&lt;p&gt;These &amp;quot;pseudo custom attributes&amp;quot; (PCAs) show up in the list of regular custom attributes with no special distinction. This means that requesting the custom attributes in reflection may return custom attributes not specified in the metadata. Since different CLR implementations add different PCAs, this list could change depending on the runtime you bind against. &lt;/p&gt;

&lt;p&gt;Some examples are the &lt;a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx"&gt;Serialization&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.typeforwardedtoattribute.aspx"&gt;TypeForwardedTo&lt;/a&gt; attributes. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;Custom Attributes&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;To get an attribute name in reflection, you must do CustomAttributeData.Constructor.DeclaringType.FullName.&lt;/p&gt;

&lt;p&gt;This is a cumbersome route to get to the custom attribute name because it requires creating several intermediate objects (a ConstructorInfo and a Type), which may also require additional resolution. The raw IMetadataImport interfaces are much more streamlined. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;ConstructorInfo vs. MethodInfo&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Metadata exposes both Constructors and MethodInfos as tokens of the same type (mdMethodDef). Reflection exposes them as separate classes which both derive from MemberBase. This means that in order to create a reflection object over a MemberDef token, you must do some additional metadata resolution to determine whether to allocate a MemberInfo or a ConstructorInfo derived class. This has to be determine when you first allocate the reflection object and can't be deferred, so it forces eager resolution again.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Type Equivalence and Assignability&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Reflection exposes a specific policy for type equivalence, which it inherits from the CLR loader. Metadata just exposes the raw properties on a type and requires the caller to determine if types are equivalent. &lt;/p&gt;

&lt;p&gt;For example, Reflection has the Type.IsAssignableFrom API, which may invoke the CLR Loader and Fusion, as well as CLR-host version specific Type Unification policies (such as no-PIA support) to determine if types are considered equal. The CLR does not fully specify the behavior of &lt;a href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx"&gt;Type.IsAssignableFrom&lt;/a&gt;,.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Case sensitivity matching&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Metadata string APIs are case sensitive. Reflection string APIs often take a &amp;quot;ignoreCase&amp;quot; flag to facilitate usage with case insensitive languages, like VB.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10337301" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Reflection/">Reflection</category></item><item><title>Converting between Azure Tables and CSV</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/08/03/converting-between-azure-tables-and-csv.aspx</link><pubDate>Sat, 04 Aug 2012 01:02:14 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10336792</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10336792</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/08/03/converting-between-azure-tables-and-csv.aspx#comments</comments><description>&lt;p&gt;I published a nuget package (&lt;a href="https://nuget.org/packages/CsvTools.azure"&gt;CsvTools.Azure&lt;/a&gt;) to easily read/write CSVs to azure blobs and tables.&amp;#160; It builds on the &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/03/24/opensource-csv-reader-on-nuget.aspx"&gt;CSV reader&lt;/a&gt;, also on Nuget (see &lt;a href="https://nuget.org/packages/CsvTools"&gt;CsvTools&lt;/a&gt;) and GitHub (&lt;a title="https://github.com/MikeStall/DataTable" href="https://github.com/MikeStall/DataTable"&gt;https://github.com/MikeStall/DataTable&lt;/a&gt; ).&lt;/p&gt;  &lt;p&gt;Azure Tables are very powerful, but can be tricky to use. I wanted something that:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;handled basic scenarios, such as uploading a CSV file to an Azure table with strongly typed columns, and downloading an Azure table as a CSV that I could then open in Excel.&amp;#160; &lt;/li&gt;    &lt;li&gt;Was easy to use and could accomplish most operations in a single line.&lt;/li&gt;    &lt;li&gt;Could still be type-safe.&lt;/li&gt;    &lt;li&gt;Had intelligent defaults. If you didn’t specify a partition key, it would infer one. If the defaults weren’t great, you could go back and improve them.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The &lt;a href="https://nuget.org/packages/CsvTools.azure"&gt;CsvTools.Azure&lt;/a&gt; nuget package adds extension methods for DataTable, contained in the core &lt;a href="https://nuget.org/packages/CsvTools"&gt;CsvTools&lt;/a&gt; package.&amp;#160; These extension methods save a DataTable to an Azure blob or table, and can read a DataTable from an azure blob or table. &lt;/p&gt;  &lt;h1&gt;Examples with Azure Blobs&lt;/h1&gt;  &lt;p&gt;Writing to and from blobs is easy, since blobs resemble the file system.&amp;#160; Here’s an example to write a data and read it back from blob storage.&lt;/p&gt;  &lt;pre class="code"&gt;        &lt;span style="color: blue;"&gt;var &lt;/span&gt;dt = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.Read(&lt;span style="color: rgb(163, 21, 21);"&gt;@&amp;quot;c:\temp\test.csv&amp;quot;&lt;/span&gt;);

        &lt;span style="color: green;"&gt;// Write and Read from blobs
        &lt;/span&gt;dt.&lt;font style="background-color: rgb(255, 255, 0);"&gt;SaveToAzureBlob&lt;/font&gt;(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;testcontainer&amp;quot;&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;test.csv&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromBlob = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.&lt;font style="background-color: rgb(255, 255, 0);"&gt;ReadAzureBlob&lt;/font&gt;(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;testcontainer&amp;quot;&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;test.csv&amp;quot;&lt;/span&gt;); &lt;span style="color: green;"&gt;// read it back
&lt;/span&gt;&lt;span style="color: green;"&gt;
&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;These code snippets assume a sample CSV at c:\temp\test.csv:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;name, species, score
      &lt;br /&gt;Kermit, Frog , 10

      &lt;br /&gt;Ms. Piggy, Pig , 50

      &lt;br /&gt;Fozzy, Bear , 23&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;Examples with Azure Tables&lt;/h1&gt;

&lt;p&gt;The scenarios I find interesting with Csv and Azure Tables are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Ingress: Uploading a CSV as an azure table. I successfully uploaded a 3 million row CSV into Azure using this package. While CSVs don’t support indexing, once in Azure, you can use the standard table query operators (such as lookup by row and partition key)&lt;/li&gt;

  &lt;li&gt;Egress: download an Azure table to a CSV. I find this can be useful for pulling down a local copy of things like logs that are stored in azure tables.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179338.aspx"&gt;Azure Tables&lt;/a&gt; have some key differences from a CSV file:&lt;/p&gt;

&lt;table border="0" cellspacing="0" cellpadding="2" width="551"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign="top" width="133"&gt;&amp;nbsp;&lt;/td&gt;
      &lt;strong&gt;&lt;/strong&gt;

      &lt;td valign="top" width="216"&gt;&lt;strong&gt;Azure Tables&lt;/strong&gt;&lt;/td&gt;
      &lt;strong&gt;&lt;/strong&gt;

      &lt;td valign="top" width="200"&gt;&lt;strong&gt;CSV&lt;/strong&gt; &lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="133"&gt;special columns and indexing&lt;/td&gt;

      &lt;td valign="top" width="216"&gt;every row in an Azure Tables has a Partition and Row key. These keys combine to form a unique index and have several other key properties documented on MSDN. &lt;/td&gt;

      &lt;td valign="top" width="200"&gt;No unique keys for indexing, and no mandated columns.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="133"&gt;Schema?&lt;/td&gt;

      &lt;td valign="top" width="216"&gt;Each row can have its own schema. &lt;/td&gt;

      &lt;td valign="top" width="200"&gt;All rows have the same schema. A CSV is conceptually a 2d array of strings. &lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="133"&gt;Typing&lt;/td&gt;

      &lt;td valign="top" width="216"&gt;The “columns” in an Azure Tables are strongly typed. &lt;/td&gt;

      &lt;td valign="top" width="200"&gt;CSVs are all strings&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="133"&gt;naming&lt;/td&gt;

      &lt;td valign="top" width="216"&gt;table and column names are restricted. See &lt;a href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179338.aspx"&gt;naming rules&lt;/a&gt; on msdn. &lt;/td&gt;

      &lt;td valign="top" width="200"&gt;No naming restriction on columns.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;Practically, this means when “uploading” a CSV to an Azure Table, we need to provide the types of the columns (or just default to everything being strings). When “downloading” an Azure Table to a CSV, we assume all rows in the table have the same schema. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Uploading a CSV to an Azure Table&lt;/h2&gt;

&lt;p&gt;Here’s an example of uplaoding a datatable as an Azure table:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// will fabricate partition and row keys, all types are strings
&lt;/span&gt;dt.SaveToAzureTable(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals&amp;quot;&lt;/span&gt;); 
&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;And then the resulting azure table, as viewed via &lt;a href="http://azurestorageexplorer.codeplex.com/"&gt;Azure Storage Explorer&lt;/a&gt;. You can see the single line only supplied a) an incoming data table, b) a target name for the azure table to be created. So it picked intelligent defaults for the partition and row key, and all columns are typed as string.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/0268.image_5F00_3F83DA1E.png"&gt;&lt;img style="display: inline; background-image: none;" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/2337.image_5F00_thumb_5F00_20F1259D.png" width="453" height="111" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/4478.image_5F00_0069E5EB.png"&gt;&lt;img style="margin: 0px; display: inline; background-image: none;" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/1667.image_5F00_thumb_5F00_592F9CB5.png" width="196" height="145" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;We can pass in an Type[] to provide stronger typing for the columns. In this case, we’re saving the “score” column as an int. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// provide stronger typing
&lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;columnTypes = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Type&lt;/span&gt;[] { &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;), &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;), &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;int&lt;/span&gt;) };
dt.SaveToAzureTable(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;, &lt;font style="background-color: rgb(255, 255, 0);"&gt;columnTypes&lt;/font&gt;);
&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/1665.image_5F00_4AF123C5.png"&gt;&lt;img style="margin: 0px; display: inline; background-image: none;" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/0601.image_5F00_thumb_5F00_188D5046.png" width="238" height="172" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;How is the partition and row key determined when uploading?&lt;/h3&gt;

&lt;p&gt;Every entity in an azure table needs a Partition and Row Key. &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If the CSV does not have columns named PartitionKey or RowKey, then the library will fabricate values. The partition key will be a constant (eg, everything gets put on the same partition), and the RowKey is just a row counter. &lt;/li&gt;

  &lt;li&gt;If the csv has a column for PartitionKey or RowKey, then those will be used. &lt;/li&gt;

  &lt;li&gt;One of the overloads to SaveToAzureTable takes a function that can compute a partition and row key per row. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here’s an example of the 3rd case, where a user provided function computes the partition and row key on the fly for each row. &lt;/p&gt;

&lt;pre class="code"&gt;dt.SaveToAzureTable(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals3&amp;quot;&lt;/span&gt;, columnTypes, &lt;br /&gt;  (index, row) =&amp;gt; &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ParitionRowKey &lt;/span&gt;{ PartitionKey = &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;, RowKey = row[&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;name&amp;quot;&lt;/span&gt;] });
&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Downloading an Azure Table as a CSV&lt;/h2&gt;

&lt;p&gt;Here we can download an Azure table to a CSV in a single line. &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromTable = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.ReadAzureTableLazy(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;);
&lt;/pre&gt;


&lt;p&gt;The convention in the CsvTools packages is that methods ending in “Lazy” are streaming, so this can handle larger-than-memory tables.&lt;/p&gt;

&lt;p&gt;We can then print it out to the console (or any stream) or do anything else with the table. For example, to just dump the table to the console, do this:&lt;/p&gt;

&lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dataFromTable.SaveToStream(&lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.Out); &lt;span style="color: green;"&gt;// print to console&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;And it prints:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;PartitionKey,RowKey,Timestamp,name,species,score
      &lt;br /&gt;1,00000000,2012-08-03T21:04:08.1Z,Kermit,Frog,10

      &lt;br /&gt;1,00000001,2012-08-03T21:04:08.1Z,Ms. Piggy,Pig,50

      &lt;br /&gt;1,00000002,2012-08-03T21:04:08.103Z,Fozzy,Bear,23&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice that the partition key, row key, and timestamp are included as columns in the CSV.&lt;/p&gt;

&lt;p&gt;Of course, once we have a DataTable instance, it doesn’t matter that it came from an Azure Table. We can use any of the normal facilities in CsvTools to operate on the table.&amp;#160; For example, we could use the &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/05/19/strong-binding-for-csv-reader.aspx"&gt;strong binding&lt;/a&gt; to convert each row to a class and then operate on that:&amp;quot;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// Read back from table as strong typing 
&lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromTable = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.ReadAzureTableLazy(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;);
&lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal&lt;/span&gt;&amp;gt; animals = dataFromTable.RowsAs&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal&lt;/span&gt;&amp;gt;();
&lt;span style="color: blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;row &lt;span style="color: blue;"&gt;in &lt;/span&gt;animals)
{
    &lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;{0},{1},{2}%&amp;quot;&lt;/span&gt;, row.name, row.species, row.score / 100.0);
}
  &lt;/pre&gt;
&lt;/blockquote&gt;


&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// Class doesn't need to derive from TableContext
&lt;/span&gt;&lt;span style="color: blue;"&gt;class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public string &lt;/span&gt;name { &lt;span style="color: blue;"&gt;get &lt;/span&gt;;&lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue;"&gt;public string &lt;/span&gt;species { &lt;span style="color: blue;"&gt;get &lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue;"&gt;public int &lt;/span&gt;score { &lt;span style="color: blue;"&gt;get &lt;/span&gt;;&lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
}
&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Full sample&lt;/h1&gt;

&lt;p&gt;Here’s the full sample.&lt;/p&gt;

&lt;p&gt;This is a C# 4.0 console application (Client Profile), with a Nuget package reference to &lt;a href="https://nuget.org/packages/CsvTools.azure"&gt;CsvTools.Azure&lt;/a&gt;, and it uses a dummy csv file at c:\temp\test.csv (see above). &lt;/p&gt;

&lt;p&gt;When you add the nuget reference to &lt;a href="https://nuget.org/packages/CsvTools.azure"&gt;CsvTools.Azure&lt;/a&gt;, Nuget’s dependency management will automatically bring down references to &lt;a href="https://nuget.org/packages/CsvTools"&gt;CsvTools&lt;/a&gt; (the core CSV reader that implements DataTable) and even the azure storage libraries. I love Nuget. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Collections.Generic;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Linq;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Text;

&lt;span style="color: blue;"&gt;using &lt;/span&gt;DataAccess;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;Microsoft.WindowsAzure;

&lt;span style="color: blue;"&gt;class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;static &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;CloudStorageAccount &lt;/span&gt;Account()
    {
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;CloudStorageAccount&lt;/span&gt;.DevelopmentStorageAccount;
    }

    &lt;span style="color: blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue;"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;dt = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.Read(&lt;span style="color: rgb(163, 21, 21);"&gt;@&amp;quot;c:\temp\test.csv&amp;quot;&lt;/span&gt;);

        &lt;span style="color: green;"&gt;// Write and Read from blobs
        &lt;/span&gt;dt.SaveToAzureBlob(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;testcontainer&amp;quot;&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;test.csv&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromBlob = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.ReadAzureBlob(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;testcontainer&amp;quot;&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;test.csv&amp;quot;&lt;/span&gt;); &lt;span style="color: green;"&gt;// read it back
        &lt;/span&gt;dataFromBlob.SaveToStream(&lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.Out); &lt;span style="color: green;"&gt;// print to console

        // Write and read from Tables

        // will fabricate partition and row keys, all types are strings
        &lt;/span&gt;dt.SaveToAzureTable(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals&amp;quot;&lt;/span&gt;);

        &lt;span style="color: green;"&gt;// provide stronger typing
        &lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;columnTypes = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Type&lt;/span&gt;[] { &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;), &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;), &lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue;"&gt;int&lt;/span&gt;) };
        dt.SaveToAzureTable(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;, columnTypes);

        {
            &lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;get an Azure table and print to console:&amp;quot;&lt;/span&gt;);
            &lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromTable = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.ReadAzureTableLazy(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;);
            dataFromTable.SaveToStream(&lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.Out); &lt;span style="color: green;"&gt;// print to console
            &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.WriteLine();
        }

        {
            &lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;Demonstrate strong typing&amp;quot;&lt;/span&gt;);
            &lt;span style="color: green;"&gt;// Read back from table as strong typing 
            &lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;dataFromTable = &lt;span style="color: rgb(43, 145, 175);"&gt;DataTable&lt;/span&gt;.New.ReadAzureTableLazy(Account(), &lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;animals2&amp;quot;&lt;/span&gt;);
            &lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal&lt;/span&gt;&amp;gt; animals = dataFromTable.RowsAs&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal&lt;/span&gt;&amp;gt;();
            &lt;span style="color: blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;row &lt;span style="color: blue;"&gt;in &lt;/span&gt;animals)
            {
                &lt;span style="color: rgb(43, 145, 175);"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;{0},{1},{2}%&amp;quot;&lt;/span&gt;, row.name, row.species, row.score / 100.0);
            }
        }

        &lt;span style="color: green;"&gt;// Write using a row and parition key        

    &lt;/span&gt;}

    &lt;span style="color: green;"&gt;// Class doesn't need to derive from TableContext
    &lt;/span&gt;&lt;span style="color: blue;"&gt;class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Animal
    &lt;/span&gt;{
        &lt;span style="color: blue;"&gt;public string &lt;/span&gt;name { &lt;span style="color: blue;"&gt;get &lt;/span&gt;;&lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
        &lt;span style="color: blue;"&gt;public string &lt;/span&gt;species { &lt;span style="color: blue;"&gt;get &lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;score { &lt;span style="color: blue;"&gt;get &lt;/span&gt;;&lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
    }
}


&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10336792" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Azure/">Azure</category><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/csv/">csv</category></item><item><title>Strong binding for CSV reader</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/05/19/strong-binding-for-csv-reader.aspx</link><pubDate>Sat, 19 May 2012 15:33:44 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10307361</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10307361</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/05/19/strong-binding-for-csv-reader.aspx#comments</comments><description>&lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;I updated my &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/03/24/opensource-csv-reader-on-nuget.aspx"&gt;open source CSV reader&lt;/a&gt; to provide parsing rows back into strongly typed objects. You can get it from Nuget as &lt;a href="http://nuget.org/packages/CsvTools"&gt;CsvTools&lt;/a&gt; 1.0.6.&lt;/p&gt;  &lt;p&gt;For example, suppose we have a CSV file “test.csv” like so:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;name, species, favorite fruit, score         &lt;br /&gt;&lt;/strong&gt;Kermit, Frog, apples, 18%        &lt;br /&gt;Ms. Piggy, Pig, pears, 22%        &lt;br /&gt;Fozzy, Bear, bananas, 19.4%&lt;/font&gt;      &lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You can open the CSV and read the rows with loose typing (as strings): &lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.Read(&lt;span style="color: #a31515"&gt;@&amp;quot;c:\temp\test.csv&amp;quot;&lt;/span&gt;);
IEnumerable&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; rows = &lt;span style="color: blue"&gt;from &lt;/span&gt;row &lt;span style="color: blue"&gt;in &lt;/span&gt;dt.Rows &lt;span style="color: blue"&gt;select &lt;/span&gt;row[&lt;span style="color: #a31515"&gt;&amp;quot;Favorite Fruit&amp;quot;&lt;/span&gt;];&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;But it’s very convenient to use strongly-typed classes. We can define a strongly-typed class for the CSV:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Fruit
&lt;/span&gt;{
    apples,
    pears,
    bananas,
}
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Name { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Species { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Fruit &lt;/span&gt;FavoriteFruit { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public double &lt;/span&gt;Score { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;We can then read via the strongly-typed class as:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.Read(&lt;span style="color: #a31515"&gt;@&amp;quot;c:\temp\test.csv&amp;quot;&lt;/span&gt;); 
&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;[] entries = dt.RowsAs&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;().ToArray(); &lt;span style="color: green"&gt;// read all entries
&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;We can also use linq expressions like:&lt;/p&gt;

&lt;p&gt;IEnumerable&amp;lt;&lt;span style="color: #2b91af"&gt;Fruit&lt;/span&gt;&amp;gt; x = &lt;span style="color: blue"&gt;from &lt;/span&gt;row &lt;span style="color: blue"&gt;in &lt;/span&gt;dt.RowsAs&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;() &lt;span style="color: blue"&gt;select &lt;/span&gt;row.FavoriteFruit; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are the parsing rules?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Parsing can get arbitrarily complex. This uses some simple rules that solved the scenarios I had. &lt;/p&gt;

&lt;p&gt;The parser looks at each property on the strong type, and matches that to a column from the CSV. Since property names are going to be restricted to C# identifiers, whereas row names can have arbitrary characters (and thus be invalid C# identifiers), the matching here is flexible. It will match properties to columns just looking at the alphanumeric characters. So the “FavoriteFruit” property matches to “Favorite Fruit” field name.&lt;/p&gt;

&lt;p&gt;To actually parse the row value from a string to the target type, T, it uses the following rules:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;if T is already a string, just return the value&lt;/li&gt;

  &lt;li&gt;special case doubles parsing to allow the percentage sign. (Parse 50% as .50).&lt;/li&gt;

  &lt;li&gt;if T has a TryParse(string, out T) method, then invoke that.&amp;#160; I found TryParse to be significantly faster than invoking a TypeConverter.&lt;/li&gt;

  &lt;li&gt;Else use a TypeConverter. This is a general and extensible hook. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Errors are ignored. The rationale here is that if I have 3 million rows of CSV data, I don’t want to throw an exception on reading just because one row has bad data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Under the hood&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;DataTable.RowsAs&amp;lt;T&amp;gt;() uses expression trees to build a strongly typed dynamic method of Func&amp;lt;Row, T&amp;gt;. I originally uses reflection to enumerate the properties, and then find the appropriate parsing technique, and set the value on the strong type. Switching to pre-compiled methods was about a 10x perf win. &lt;/p&gt;

&lt;p&gt;In this case, the generated method looks something like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EnumParser
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;const int &lt;/span&gt;columnIndex_Name = 0;
    &lt;span style="color: blue"&gt;const int &lt;/span&gt;columnIndex_species = 1;

    &lt;span style="color: #2b91af"&gt;TypeConverter &lt;/span&gt;_convertFavoriteFruit = &lt;span style="color: #2b91af"&gt;TypeDescriptor&lt;/span&gt;.GetConverter(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Fruit&lt;/span&gt;));
    &lt;span style="color: blue"&gt;const int &lt;/span&gt;columnIndex_Fruit = 2;

    &lt;span style="color: blue"&gt;const int &lt;/span&gt;columnIndex_Score = 3;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry &lt;/span&gt;Parse(&lt;span style="color: #2b91af"&gt;Row &lt;/span&gt;r)
    {
        &lt;span style="color: #2b91af"&gt;Entry &lt;/span&gt;newObj = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;();
        newObj.FavoriteFruit = (&lt;span style="color: #2b91af"&gt;Fruit&lt;/span&gt;) _convertFavoriteFruit.ConvertFrom(r.Values[columnIndex_Fruit]);
        newObj.Name = r.Values[columnIndex_Name];
        newObj.Species = r.Values[columnIndex_species];
        newObj.Score = ToDouble(r.Values[columnIndex_Score]);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;newObj;
    }    
}&lt;/pre&gt;


&lt;p&gt;The parse method is a Func&amp;lt;Row, Entry&amp;gt; which can be invoked on each row. It’s actually a closure so that it can capture the TypeConverters and only do the lookup once. The mapping between property names and column names can also be done upfront and captured in the columnIndex_* constants.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10307361" width="1" height="1"&gt;</description></item><item><title>Per-controller configuration in WebAPI</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/05/11/per-controller-configuration-in-webapi.aspx</link><pubDate>Fri, 11 May 2012 17:50:18 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10304323</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10304323</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/05/11/per-controller-configuration-in-webapi.aspx#comments</comments><description>&lt;p&gt;We’ve just added support for WebAPI to provide per-controller-type configuration. WebAPI has a &lt;strong&gt;HttpConfiguration&lt;/strong&gt; object that provides configuration such as:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;route table&lt;/li&gt;    &lt;li&gt;Dependency resolver for specifying services&lt;/li&gt;    &lt;li&gt;list of Formatters, ModelBinders, and other parameter binding settings.&lt;/li&gt;    &lt;li&gt;list of message handlers, &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;However, a specific controller may need its own specific services. And so we’ve added &lt;a href="http://aspnetwebstack.codeplex.com/SourceControl/changeset/changes/fcfc9f49f96a"&gt;per-controller-type configuration&lt;/a&gt;. In essence, a controller type can have its own “shadow copy” of the global config object, and then override specific settings.&amp;#160; This is automatically applied to all controller instances of the given controller-type. (This supersedes the HttpControllerConfiguration attribute that we had in Beta)&lt;/p&gt;  &lt;p&gt;Some of the scenarios we wanted to enable here:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A controller may have its own specific list of Formatters, for both reading and writing objects. &lt;/li&gt;    &lt;li&gt;A controller may have special dynamic actions that aren’t based on reflecting over C# methods, and so may need its own private action selector. &lt;/li&gt;    &lt;li&gt;A controller may need its own IActionValueBinder. For example, you might have an HtmlController base class that has a &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx"&gt;MVC-style parameter binder&lt;/a&gt; that handles FormUrl data.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In all these cases, the controller is coupled to a specific service for basic correct operation, and these services really are private implementation of the controller that shouldn’t conflict with settings from other controllers.&amp;#160; Per-controller config allows multiple controllers to override their own services and coexist peacefully in an app together. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;How to setup per-controller config&lt;/strong&gt;?&lt;/p&gt;  &lt;p&gt;We’ve introduced the IControllerConfiguration interface:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;IControllerConfiguration
&lt;/span&gt;{
&lt;span style="color: blue;"&gt;    void &lt;/span&gt;Initialize(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpControllerSettings &lt;/span&gt;controllerSettings, &lt;br /&gt;                    &lt;span style="color: rgb(43, 145, 175);"&gt;HttpControllerDescriptor &lt;/span&gt;controllerDescriptor);
}
&lt;/pre&gt;


&lt;p&gt;WebAPI will look for attributes on the controller that implement that interface, and then invoke them when initializing the controller-type. This follows the same inheritance order as constructors, so attributes on the base type will be invoked first. &lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;controllerSettings&lt;/strong&gt; object specifies what things on the configuration can be overriden for a controller. This provides static knowledge of what things on a configuration can and can’t be specified for a controller. Obviously, things like message handlers and routes can’t be specified for a per-controller basis.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;HttpControllerSettings
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public &lt;/span&gt;MediaTypeFormatterCollection Formatters { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }
    &lt;span style="color: blue;"&gt;public &lt;/span&gt;ParameterBindingRulesCollection ParameterBindingRules { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }
    &lt;span style="color: blue;"&gt;public &lt;/span&gt;ServicesContainer Services { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }        
}
&lt;/pre&gt;

&lt;p&gt;So an initialization function can change the services, formatters, or &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx"&gt;binding rules&lt;/a&gt;. Then WebAPI will create a new shadow HttpConfiguration object and apply those changes. Things that are not changes will still fall through to the global configuration. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s an example. Suppose we have our own controller type, and we want it to only use a specific formatter and IActionValueBinder. &lt;/p&gt;

&lt;p&gt;First, we add a config attribute:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;&lt;font style="background-color: rgb(255, 255, 0);"&gt;AwesomeConfig&lt;/font&gt;&lt;/span&gt;]
&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;AwesomeController &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ApiController
&lt;/span&gt;{
    [&lt;span style="color: rgb(43, 145, 175);"&gt;HttpGet&lt;/span&gt;]
    &lt;span style="color: blue;"&gt;public string &lt;/span&gt;Action(&lt;span style="color: blue;"&gt;string &lt;/span&gt;s)
    {
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;&amp;quot;abc&amp;quot;&lt;/span&gt;;
    }
}
&lt;/pre&gt;

&lt;p&gt;That attribute implementss the IControllerConfiguration:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;&lt;font style="background-color: rgb(255, 255, 0);"&gt;AwesomeConfig&lt;/font&gt;Attribute &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;Attribute&lt;/span&gt;, &lt;span style="color: rgb(43, 145, 175);"&gt;IControllerConfiguration
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Initialize(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpControllerSettings &lt;/span&gt;controllerSettings, &lt;br /&gt;                           &lt;span style="color: rgb(43, 145, 175);"&gt;HttpControllerDescriptor &lt;/span&gt;controllerDescriptor)
    {
        controllerSettings.Services.Replace(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;IActionValueBinder&lt;/span&gt;), &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;AwesomeActionValueBinder&lt;/span&gt;());
        controllerSettings.Formatters.Clear();
        controllerSettings.Formatters.Add(&lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;AwesomeCustomFormatter&lt;/span&gt;());
    }
}
&lt;/pre&gt;
This will clear all the default formatters and add our own AwesomeCustomFormatter. It will also the IActionValueBinder to our own AwesomeActionValueBinder.&amp;#160; It also will not affect any other controllers in the system.

&lt;p&gt;Setting a service on the controller here has higher precedence than setting services in the dependency resolver or in the global configuration.&lt;/p&gt;

&lt;p&gt;The initialization function can also inspect incoming configuration and modify it. For example, it can append a formatter or binding rule to an existing list. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What happens under the hood?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This initialization function is invoked when WebAPI is first creating the HttpControllerDescriptor for this controller type. It’s only invoked once per controller type. WebAPI will then apply the controllerSettings and create a new HttpConfiguration object. There are some optimizations in place to make this efficient:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If there’s no change, it shares the same config object and doesn’t create a new one. &lt;/li&gt;

  &lt;li&gt;The new config object reuses much of the original one. There are several copy-on-write optimization in place. For example, if you don’t touch the formatters, we avoid allocating a new formatter collection. 
    &lt;br /&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then the resulting configuration is used for future instances of controller. Calling code still just gets a HttpConfiguration instance and doesn’t need to care whether that instance was the global configuration or a per-controller configuration. So when the controller asks for formatters or an IActionValueBinder here, it will automatically pull from the controller’s config instead of the global one. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10304323" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>WebAPI Parameter binding under the hood</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx</link><pubDate>Fri, 11 May 2012 05:25:12 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10304099</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10304099</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx#comments</comments><description>&lt;p&gt;I wrote about &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx"&gt;WebAPI’s parameter binding&lt;/a&gt; at a high level before. Here’s what’s happening under the hood. The most fundamental object for binding parameters from a request in WebAPI is a &lt;strong&gt;HttpParameterBinding&lt;/strong&gt;. This binds a single parameter. The binding is created upfront and then is invoked across requests. This means the binding must be determined from static information such as the parameter’s name, type, or global config.&amp;#160; A parameter binding has a reference to the HttpParameterDescriptor, which provides static information about the parameter from the action’s signature.&lt;/p&gt;  &lt;p&gt;Here’s the key method on HttpParameterBinding:&amp;#160; &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task ExecuteBindingAsync(&lt;br /&gt;    ModelMetadataProvider metadataProvider, &lt;br /&gt;    HttpActionContext actionContext, &lt;br /&gt;    CancellationToken cancellationToken);&lt;/pre&gt;


&lt;p&gt;This is invoked on each request to perform the actual binding. It takes in the action context (which has the incoming request) and then does the binding and populates the result in the argument dictionary hanging off action context. This method returns a Task in case the binding needs to do an IO operation like read the content stream.&amp;#160; &lt;/p&gt;

&lt;h3&gt;Examples of bindings&lt;/h3&gt;

&lt;p&gt;WebAPI has two major parameter bindings: ModelBindingParameterBinder or FormatterParameterBinder.&amp;#160; The first uses model binding, and generally assembles the parameter from the URI. The second uses the MediaTypeFormatters to read the parameter from the content stream. &lt;/p&gt;

&lt;p&gt;Ultimately, these are both just derived classes from HttpParameterBinding. Once WebAPI gets the binding, it just invokes the ExecuteBindingAsync method&amp;#160; and doesn’t care about the parameter’s type, it’s name, whether it had a default value, whether it was model binding vs. formatters, etc. &lt;/p&gt;

&lt;p&gt;However, you can always add your own. For example, suppose you want to bind action parameters of type IPrincipal to automatically go against the thread’s current principal. Clearly, this does touch the content stream or need the facilities from model binding. You could create a custom binding like so:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="rem"&gt;// Example of a binder&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PrincipalParameterBinding : HttpParameterBinding
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; PrincipalParameterBinding(HttpParameterDescriptor p) : &lt;span class="kwrd"&gt;base&lt;/span&gt;(p) { }
 
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, &lt;br /&gt;                                    HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            IPrincipal p = Thread.CurrentPrincipal;
            SetValue(actionContext, p);
&lt;br /&gt; 
            var tsc = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;();
            tsc.SetResult(&lt;span class="kwrd"&gt;null&lt;/span&gt;);
            &lt;span class="kwrd"&gt;return&lt;/span&gt; tsc.Task;
        }
    }
&lt;/pre&gt;


&lt;p&gt;The binding really could do anything. You could have custom bindings that go and pull values from a database. &lt;/p&gt;

&lt;p&gt;Normally, you wouldn’t need to plug your own HttpParameterBinding. Most scenarios could be solved by plugging a simpler interface, like adding a formatter or model binder. &lt;/p&gt;

&lt;h3&gt;Who determines the binding?&lt;/h3&gt;

&lt;p&gt;This is ultimately determined by the &lt;strong&gt;IActionValueBinder&lt;/strong&gt;, which is a pluggable service. Here’s the order that the DefaultActionValueBinder looks in to get a binding. (I described an alternative binder &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx"&gt;here&lt;/a&gt; which has MVC like semantics.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Look for a ParameterBindingAttribute&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The highest precedence is to use a &lt;strong&gt;ParameterBindingAttribute&lt;/strong&gt;, which can be places on a parameter site or a parameter type’s declaration.&amp;#160; This lets you explicitly set the binding for a parameter.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = &lt;span class="kwrd"&gt;true&lt;/span&gt;, AllowMultiple = &lt;span class="kwrd"&gt;false&lt;/span&gt;)]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ParameterBindingAttribute : Attribute
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; HttpParameterBinding GetBinding(HttpParameterDescriptor parameter);
    }&lt;/pre&gt;


&lt;p&gt;The virtual function here hints that this is really the base class of a hierarchy. [FromBody] and [ModelBinder] attributes both derive from [ParameterBinding]. [FromUri] derives from [ModelBinder] and just invokes model binding and constrains the inputs to be from the URI.&lt;/p&gt;

&lt;p&gt;In our example, we could create our own custom attribute to provide PrincipalParameterBindings. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Look at the ParamterBinding Rules in the Configuration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The HttpConfiguration has a collection of binding rules. This is checked if there is no ParameterBinding attribute.&amp;#160; Here are some examples of setting some binding rules for certain types. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;            HttpConfiguration config = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpConfiguration();
 
            ParameterBindingRulesCollection pb = config.ParameterBindingRules;
&lt;pre class="csharpcode"&gt;            pb.Insert(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(IPrincipal), param =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; PrincipalParameterBinding(param)); &lt;span class="rem"&gt;// custom binder against request&lt;/span&gt;
            pb.Insert(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Location), param =&amp;gt; param.BindWithModelBinding(&lt;span class="kwrd"&gt;new&lt;/span&gt; LocationModelBinder())); 
            pb.Insert(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;), param =&amp;gt; param.BindWithFormatter(&lt;span class="kwrd"&gt;new&lt;/span&gt; CustomMediaFormatter()));
&lt;/pre&gt;&lt;/pre&gt;


&lt;p&gt;The first rule says that all IPrincipal types should be bound using our IPrincipal binder above. &lt;/p&gt;

&lt;p&gt;The second rule says that all Location types should be bound using Model Binding, and specifically use the LocationModelBinder&amp;#160; (which would implement IModelBinder).&lt;/p&gt;

&lt;p&gt;The third rule says that all strings should be bound with the formatters. &lt;/p&gt;

&lt;p&gt;Rules are executed in order and work against exact type matches.&lt;/p&gt;

&lt;p&gt;The binding rules actually operate on a ParameterDescriptor. The Insert() methods above are just using a helper that filters based on the parameter’s type. So you could add a rule that binds on a parameter’s name, or even if the par&lt;/p&gt;

&lt;p&gt;Setting rules lets your config describe how types should be bound, and alleviates needing to decorate every callsite with an attribute. &lt;/p&gt;

&lt;p&gt;The configuration has some default entries in the parameter binding rules collection:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;bind the cancellation token&lt;/li&gt;

  &lt;li&gt;bind the HttpRequestMessage&amp;#160; (without this rule, HttpRequestMessage would be seen as a complex object and so we’d naturally try to read it from the body using a formatter)&lt;/li&gt;

  &lt;li&gt;prevent accidentally binding any class derived from HttpContent. (This is trying to protect users from accidentally having a formatter try to bind)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since these are just regular entries in the rule collection, you can supersede them by inserting a broader rule in front of them. Or you can clear the collection completely.&amp;#160; &lt;/p&gt;

&lt;p&gt;The rules here are extremely flexible and can solve several scenarios:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Allow you to override WebAPI’s behavior for special types like cancellation token, HttpContent, or HttpRequestMessage. For example, if you did want the HttpContent to bind against the Request.Content, you could add a rule for that. Or if you had multiple cancellation tokens floating around and wanted to bind them by name, you could add a rule for that too. &lt;/li&gt;

  &lt;li&gt;Specify whether a type should use model binding or formatter by default.&amp;#160; Maybe you have a complex type that should always use model binding (eg, Location in the above example). Just adding a formatter doesn’t mean that a type automatically uses it. Afterall, you could add a formatter and model binder for the same type. And some formatters and model binders eagerly claim to handle all types (eg, JSON.Net thinks it can handle anything, even a wacky type like a delegate or COM object). Same for model binding. So WebAPI needs a hint, and parameter binding rules can provide that hint. &lt;/li&gt;

  &lt;li&gt;Create a binding rule once that applies globally, without having to touch up every single action signature. &lt;/li&gt;

  &lt;li&gt;Create binding rules that require rich type information. For example, you could create a “TryParse” rule that looks if a parameter type has a “bool TryParse(string s, out T)” method, and if so, binds that parameter by invoking that method. &lt;/li&gt;

  &lt;li&gt;Instead of binding by type, bind by name, and coerce the value to the given parameter type. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Fallback to a default policy &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If there is no attribute, and there is no rule that claims the parameter descriptor, than the default binder falls back to its default policy. That’s basically simple types are model bound against the URI, and complex types are read from the body using formatters. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10304099" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>Excel on Azure</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/04/24/excel-on-azure.aspx</link><pubDate>Tue, 24 Apr 2012 06:06:25 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10297004</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10297004</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/04/24/excel-on-azure.aspx#comments</comments><description>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;I amended my open-source &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/03/24/opensource-csv-reader-on-nuget.aspx"&gt;CsvTools&lt;/a&gt; with an Excel reader. Once I read the excel worksheet into a datatable, I can use all the data table operators from the core CsvTools, including enumeration, Linq over the rows, analysis, mutation, and saving back out as a CSV. So this gives be a Linq-to-Excel on Azure experience, which ought to win a buzzword bingo contest!&lt;/p&gt; &lt;p&gt;The excel reader uses the OpenXml SDK, and so it can run on Azure.&amp;nbsp; This is useful because Excel as a COM-object doesn’t run on servers, and so I couldn’t upload excel files to my ASP.Net projects without really fighting the security settings. With OpenXml, it’s easy since you’re just reading XML.&lt;/p&gt; &lt;p&gt;Here’s a little azure MVC test page that demonstrates uploading a xlsx file and displaying the contents in azure:&lt;/p&gt;&lt;iframe style="width: 666px; height: 354px" src="http://test52132.cloudapp.net"&gt;&lt;/iframe&gt; &lt;p&gt;(side note: deploying MVC to Azure is super easy, courtesy of &lt;a href="http://www.asp.net/mvc/tutorials/deployment-to-windows-azure/walkthrough-hosting-an-aspnet-mvc-application-on-windows-azure"&gt;this great tutorial&lt;/a&gt;).&lt;/p&gt; &lt;p&gt;I also need to give a shout-out for &lt;a href="http://nuget.org/"&gt;Nuget&lt;/a&gt;! The dependency management here was great. I have one Nuget package for the core &lt;a href="https://nuget.org/packages/CsvTools"&gt;CsvTools&lt;/a&gt; (which is just the CSV reader with no dependencies) , and another package &lt;a href="https://nuget.org/packages/CsvTools.Excel"&gt;CsvTools.Excel&lt;/a&gt; (which has a dependency on CsvTools and the OpenXml SDK). &lt;/p&gt; &lt;p&gt;The excel reader is an extension method exposed off “DataTable.New”, so it’s easily discoverable. &lt;/p&gt; &lt;p&gt;Here’s a sample excel sheet, foo.xlsx:&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/8880.image_5F00_61F979CE.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/8473.image_5F00_thumb_5F00_21C36054.png" width="169" height="128"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;And then the code to read it from C#:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;private static void &lt;/span&gt;TestExcel()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;dt = &lt;font style="background-color: #ffff00"&gt;&lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.ReadExcel&lt;/font&gt;(&lt;span style="color: #a31515"&gt;@"c:\temp\foo.xlsx"&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;names = &lt;span style="color: blue"&gt;from &lt;/span&gt;row &lt;span style="color: blue"&gt;in &lt;/span&gt;dt.Rows &lt;span style="color: blue"&gt;where int&lt;/span&gt;.Parse(row[&lt;span style="color: #a31515"&gt;"age"&lt;/span&gt;]) &amp;gt; 10 &lt;span style="color: blue"&gt;select &lt;/span&gt;row[&lt;span style="color: #a31515"&gt;"Name"&lt;/span&gt;];
    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;name &lt;span style="color: blue"&gt;in &lt;/span&gt;names)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(name);
    }            
}
&lt;/pre&gt;
&lt;p&gt;This example just reads the first worksheet in the workbook, which is the common case for my usage scenarios where people are using excel as a CSV format.&amp;nbsp; It prints:&lt;/p&gt;
&lt;table border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;pre&gt;Ed
John

&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;There&amp;nbsp; are also some other overloads to give the whole list of worksheets.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MutableDataTable&lt;/span&gt;&amp;gt; ReadExcelAllSheets(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DataTableBuilder &lt;/span&gt;builder, &lt;span style="color: blue"&gt;string &lt;/span&gt;filename);
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MutableDataTable&lt;/span&gt;&amp;gt; ReadExcelAllSheets(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DataTableBuilder &lt;/span&gt;builder, &lt;span style="color: #2b91af"&gt;Stream &lt;/span&gt;input);
&lt;/pre&gt;&lt;/pre&gt;&lt;pre class="code"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;The reader is intended for Excel workbooks that represent tabular data and is not hardened against weird or malformed input.&lt;/p&gt;
&lt;p&gt;Anyway, I’m finding this useful for some experiments, and sharing in case somebody else finds it useful too.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;(Now I just need to throw in a WebAPI parameter binding for DataTables, use WebAPI’s query string support, and add some data table Azure helpers and I will be the buzzword bingo champion!) &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10297004" width="1" height="1"&gt;</description></item><item><title>How to create a custom value provider in WebAPI</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/04/23/how-to-create-a-custom-value-provider-in-webapi.aspx</link><pubDate>Mon, 23 Apr 2012 17:29:50 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10296690</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10296690</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/04/23/how-to-create-a-custom-value-provider-in-webapi.aspx#comments</comments><description>&lt;p&gt;Here’s how you can easily customize WebAPI parameter binding to include values from source other than the url.&amp;#160; The short answer is that you add a custom &lt;em&gt;ValueProvider &lt;/em&gt;and use Model Binding, just like in MVC. &lt;/p&gt;  &lt;p&gt;ValueProviders are used to provide values for simple types &lt;em&gt;and match on parameter name.&lt;/em&gt;&amp;#160; ValueProviders serve up raw pieces of information and feed into the Model Binders. Model Binders compose that information (eg, building collections or complex types) and do type coercion (eg, string to int, &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/20/how-to-bind-to-custom-objects-in-action-signatures-in-mvc-webapi.aspx"&gt;invoke type converters&lt;/a&gt;, etc).&amp;#160; &lt;/p&gt;  &lt;p&gt;Here’s a custom value provider that extracts information from the request headers.&amp;#160; in this case, our action will get the &lt;strong&gt;userAgent&lt;/strong&gt; and &lt;strong&gt;host&lt;/strong&gt; from the headers. This doesn’t interfere with other parameters, so you can still get the id from the&amp;#160; query string as normal and read the body. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ValueProviderTestController : ApiController
    {
        [HttpGet]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; GetStuff(&lt;font style="background-color: rgb(255, 255, 0);"&gt;&lt;span class="kwrd"&gt;string&lt;/span&gt; userAgent&lt;/font&gt;, &lt;font style="background-color: rgb(255, 255, 0);"&gt;&lt;span class="kwrd"&gt;string&lt;/span&gt; host&lt;/font&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt; id)
        {   
            &lt;span class="rem"&gt;// userAgent and host are bound from the Headers. id is bound from the query string. &lt;/span&gt;
            &lt;span class="rem"&gt;// This just echos back. Do something interesting instead.&lt;/span&gt;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(
&lt;span class="str"&gt;@&amp;quot;User agent: {0},
host: {1}
id: {2}&amp;quot;&lt;/span&gt;, userAgent, host, id);
        }
    }&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;So when I run it and hit it from a browser, I get a string back like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;User agent: &lt;font style="background-color: rgb(255, 255, 0);"&gt;Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)&lt;/font&gt;,

    &lt;br /&gt;host: &lt;font style="background-color: rgb(255, 255, 0);"&gt;localhost:8080&lt;/font&gt;

    &lt;br /&gt;id: 45&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Note that the client needs to set the headers in the request. Browsers will do this. But if you just call directly with HttpClient.GetAsync(), the headers will be empty. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;We define a HeaderValueProviderFactory class (source below), which derives from ValueProviderFactory and supplies model binding with the information from the header. &lt;/p&gt;

&lt;p&gt;We need to register the header value provider.&amp;#160; We can do it globally in the config, like so:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;            &lt;span class="rem"&gt;// Append our custom valueprovider to the list of value providers.&lt;/span&gt;
            config.Services.Add(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(ValueProviderFactory), &lt;span class="kwrd"&gt;new&lt;/span&gt; HeaderValueProviderFactory());&lt;/pre&gt;


&lt;p&gt;Or we can do it just on a specific parameter without touching global config by using the [ValueProvider] attribute, like so:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    public object GetStuff([ValueProvider(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(HeaderValueProviderFactory))] &lt;span class="kwrd"&gt;string&lt;/span&gt; userAgent)&lt;/pre&gt;


&lt;p&gt;The [ValueProvider] attribute just derives from the [ModelBinder] attribute and says “use the default model binding, but supply these value providers”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What’s happening under the hood&lt;/strong&gt;? For refresher reading, see &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx"&gt;How WebAPI does parameter binding&lt;/a&gt;. In this case, it sees the parameter is a simple type (string), and so it will bind via Model Binding. Model binding gets a list of value providers (either from the attribute or the configuration), and then looks at the name of the parameter (userAgent, host, id) from that list.&amp;#160; Model Binding will also do composition and coercion. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Sources&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://aspnetwebstack.codeplex.com/SourceControl/list/changesets"&gt;WebAPI is an open source project&lt;/a&gt; and some of this may need the post-beta source. For example, service resolver has been cleaned up since beta, so it’s now easier to add new services. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here’s the source for a test client: &lt;/strong&gt;It includes a loop so that you can hit the service from a browser. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; TestHeaderValueProvider()
        {
            &lt;span class="kwrd"&gt;string&lt;/span&gt; prefix = &lt;span class="str"&gt;&amp;quot;http://localhost:8080&amp;quot;&lt;/span&gt;;
            HttpSelfHostConfiguration config = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpSelfHostConfiguration(prefix);
            config.Routes.MapHttpRoute(&lt;span class="str"&gt;&amp;quot;Default&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;{controller}/{action}&amp;quot;&lt;/span&gt;);

            &lt;span class="rem"&gt;// Append our custom valueprovider to the list of value providers.&lt;/span&gt;
            config.Services.Add(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(ValueProviderFactory), &lt;span class="kwrd"&gt;new&lt;/span&gt; HeaderValueProviderFactory());
            
            HttpSelfHostServer server = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            &lt;span class="kwrd"&gt;try&lt;/span&gt;
            {
                &lt;span class="rem"&gt;// HttpClient will make the call, but won't set the headers for you. &lt;/span&gt;
                HttpClient client = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpClient();
                var response = client.GetAsync(prefix + &lt;span class="str"&gt;&amp;quot;/ValueProviderTest/GetStuff?id=20&amp;quot;&lt;/span&gt;).Result;

                &lt;span class="rem"&gt;// Browsers will set the headers. &lt;/span&gt;
                &lt;span class="rem"&gt;// Loop. You can hit the request via: http://localhost:8080/Test2/GetStuff?id=40&lt;/span&gt;
                &lt;span class="kwrd"&gt;while&lt;/span&gt; (&lt;span class="kwrd"&gt;true&lt;/span&gt;)
                {
                    Thread.Sleep(1000);
                    Console.Write(&lt;span class="str"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
                }
            }
            &lt;span class="kwrd"&gt;finally&lt;/span&gt;
            {
                server.CloseAsync().Wait();
            &lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here’s the full source for the provider.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Globalization;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http.Headers;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Reflection;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.Controllers;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.ValueProviders;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Basic
{
    &lt;span class="rem"&gt;// ValueProvideFactory. This is registered in the Service resolver like so:&lt;/span&gt;
    &lt;span class="rem"&gt;//    config.Services.Add(typeof(ValueProviderFactory), new HeaderValueProviderFactory());&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HeaderValueProviderFactory : ValueProviderFactory
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; IValueProvider GetValueProvider(HttpActionContext actionContext)
        {
            HttpRequestHeaders headers = actionContext.ControllerContext.Request.Headers;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HeaderValueProvider(headers);
        }
    }

    &lt;span class="rem"&gt;// ValueProvider for extracting data from headers for a given request message. &lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HeaderValueProvider : IValueProvider
    {
        &lt;span class="kwrd"&gt;readonly&lt;/span&gt; HttpRequestHeaders _headers;

        &lt;span class="kwrd"&gt;public&lt;/span&gt; HeaderValueProvider(HttpRequestHeaders headers)
        {
            _headers = headers;
        }

        &lt;span class="rem"&gt;// Headers doesn't support property bag lookup interface, so grab it with reflection.&lt;/span&gt;
        PropertyInfo GetProp(&lt;span class="kwrd"&gt;string&lt;/span&gt; name)
        {
            var p = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(HttpRequestHeaders).GetProperty(name, &lt;br /&gt;                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
            &lt;span class="kwrd"&gt;return&lt;/span&gt; p;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; ContainsPrefix(&lt;span class="kwrd"&gt;string&lt;/span&gt; prefix)
        {
            var p = GetProp(prefix);
            &lt;span class="kwrd"&gt;return&lt;/span&gt; p != &lt;span class="kwrd"&gt;null&lt;/span&gt;;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; ValueProviderResult GetValue(&lt;span class="kwrd"&gt;string&lt;/span&gt; key)
        {
            var p = GetProp(key);
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (p != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
            {
                &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt; = p.GetValue(_headers, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
                &lt;span class="kwrd"&gt;string&lt;/span&gt; s = &lt;span class="kwrd"&gt;value&lt;/span&gt;.ToString(); &lt;span class="rem"&gt;// for simplicity, convert to a string&lt;/span&gt;
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ValueProviderResult(s, s, CultureInfo.InvariantCulture);
            }
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;; &lt;span class="rem"&gt;// none&lt;/span&gt;
        }
    }
}&lt;/pre&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10296690" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>How to bind to custom objects in action signatures in MVC/WebAPI</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/04/20/how-to-bind-to-custom-objects-in-action-signatures-in-mvc-webapi.aspx</link><pubDate>Fri, 20 Apr 2012 21:30:14 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10295971</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10295971</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/04/20/how-to-bind-to-custom-objects-in-action-signatures-in-mvc-webapi.aspx#comments</comments><description>&lt;p&gt;MVC provides several ways for binding your own arbitrary parameter types.&amp;#160; I’ll describe some common MVC ways and then show how this applies to WebAPI too. You can view this as a MVC-to-WebAPI migration guide.&amp;#160; (Related reading: &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx"&gt;How WebAPI binds parameters&lt;/a&gt; )&lt;/p&gt;  &lt;p&gt;Say we have a complex type, Location, which just has an X and Y. And we want to create that by invoking a Parse(string) function.&amp;#160; The question then becomes: &lt;strong&gt;how do I wire up my custom Parse(string) function into WebAPI’s parameter binding system&lt;/strong&gt;?&lt;/p&gt;  &lt;p&gt;Query string: &lt;em&gt;/?loc=123,456&amp;#160;&amp;#160; &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;And then this action gets invoked and the parameter is bound from the query string:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; MyAction(Location loc) &lt;br /&gt;        {
            &lt;span class="rem"&gt;// expect that loc.X = 123, loc.Y = 456&lt;br /&gt;&lt;/span&gt;        }&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Here’s the C# code for the my Location class, plus the essential parse function:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="rem"&gt;// A complex type&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Location
    {        
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; X { get; set; }
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Y { get; set; }

        &lt;span class="rem"&gt;// Parse a string into a Location object. &amp;quot;1,2&amp;quot; --&amp;gt; Loc(X=1,Y=2)&lt;/span&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Location TryParse(&lt;span class="kwrd"&gt;string&lt;/span&gt; input)
        {
            var parts = input.Split(&lt;span class="str"&gt;','&lt;/span&gt;);
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (parts.Length != 2)
            {
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;
            }

            &lt;span class="kwrd"&gt;int&lt;/span&gt; x,y;
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt;.TryParse(parts[0], &lt;span class="kwrd"&gt;out&lt;/span&gt; x) &amp;amp;&amp;amp; &lt;span class="kwrd"&gt;int&lt;/span&gt;.TryParse(parts[1], &lt;span class="kwrd"&gt;out&lt;/span&gt; y))
            {
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Location { X = x, Y = y };                
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; ToString()
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0},{1}&amp;quot;&lt;/span&gt;, X, Y);
        }
    }&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Option Fail: what if I do nothing?&lt;/h3&gt;

&lt;p&gt;If you just define a Location class, but don’t tell WebAPI/MVC about the parse function, it won’t know how to bind it. It may make a best effort, but the Location parameter will be empty. &lt;/p&gt;

&lt;p&gt;In WebAPI, we’ll see Location is a complex type, assume it’s coming from the request’s body and so try to invoke a Formatter on it.&amp;#160; WebAPI will search for a formatter that matches the content type and claims to handle the Location type. The formatter likely won’t find anything in the body and leave the parameter empty. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Option #1: Manually call the parse function&lt;/h3&gt;

&lt;p&gt;You can always take the string in the action signature and manually call the parse function yourself.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; MyAction1(&lt;span class="kwrd"&gt;string&lt;/span&gt; loc)
        {
            Location loc2 = &lt;strong&gt;&lt;font style="background-color: rgb(255, 255, 0);"&gt;Location.TryParse&lt;/font&gt;&lt;/strong&gt;(loc); &lt;span class="rem"&gt;// explicitly convert string&lt;/span&gt;
            &lt;span class="rem"&gt;// now use loc2 ... &lt;/span&gt;
        }&lt;/pre&gt;

&lt;p&gt;You can still do this in WebAPI, exactly as is. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does WebAPI do under the hood&lt;/strong&gt;? In WebAPI, the string parameter is seen as a simple type, and so it uses model binding to pull ‘loc’ from the query string. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Option #2: Use a TypeConverter to make the complex type be simple&lt;/h3&gt;

&lt;p&gt;Or we can do it with a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx"&gt;TypeConverter&lt;/a&gt;. This just teachers the model binding system about where to find the Parse() function for the given type. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; LocationTypeConverter : TypeConverter
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (sourceType == &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;))
            {
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;
            }
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.CanConvertFrom(context, sourceType);
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; ConvertFrom(ITypeDescriptorContext context, &lt;br /&gt;           System.Globalization.CultureInfo culture, &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;value&lt;/span&gt; &lt;span class="kwrd"&gt;is&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;)
            {
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;strong&gt;&lt;font style="background-color: rgb(255, 255, 0);"&gt;Location.TryParse&lt;/font&gt;&lt;/strong&gt;((&lt;span class="kwrd"&gt;string&lt;/span&gt;) &lt;span class="kwrd"&gt;value&lt;/span&gt;);
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.ConvertFrom(context, culture, &lt;span class="kwrd"&gt;value&lt;/span&gt;);
        }
    }&lt;/pre&gt;


&lt;p&gt;And then add the appropriate attribute to the Location’s type declaration:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;   [TypeConverter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(LocationTypeConverter))]
&lt;span class="kwrd"&gt;   public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Location
   {  ... }
&lt;/pre&gt;


&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Now in both MVC and WebAPI, your action will get called and the Location parameter is bound:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; MyAction(Location loc)        
{
   &lt;span class="rem"&gt;// use loc&lt;/span&gt;
}&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;What does WebAPI do under the hood? &lt;/strong&gt;The presence of a TypeDescriptor that converts from string means that WebAPI classifies this a “simple type”. Simple types use model binding. WebAPI will get ‘loc’ from the query string by matching the parameter name, see the parameter’s type is “Location” and then invoke the TypeConverter to convert from string to Location. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Option #3: Use a custom model binder&lt;/h3&gt;

&lt;p&gt; Another way is to use a custom model binder. This essentially just teachers the model binding system about the Location parse function. There are two key parts here: 
  &lt;br /&gt;&amp;#160; a) defining the model binder and 

  &lt;br /&gt;&amp;#160; b) wiring it up to the system so that it gets used. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part a) Writing a custom model binder:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s in MVC:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; LocationModelBinder : IModelBinder
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            &lt;span class="kwrd"&gt;string&lt;/span&gt; key = bindingContext.ModelName;
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (val != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
            {
                &lt;span class="kwrd"&gt;string&lt;/span&gt; s = val.AttemptedValue &lt;span class="kwrd"&gt;as&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;;
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (s != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
                {
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;strong&gt;&lt;font style="background-color: rgb(255, 255, 0);"&gt;Location.TryParse&lt;/font&gt;&lt;/strong&gt;(s);
                }
            }
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;
        }
    }&lt;/pre&gt;


&lt;p&gt;Of course, once you’ve written a custom model binder, you can do a lot more with it than just call a Parse() function. But that’s another topic…&lt;/p&gt;

&lt;p&gt;Defining a custom model binder is very similar in WebAPI. We still have a correpsonding IModelBinder interface, and the design pattern is the same, but its signature is slightly different:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)&lt;/pre&gt;


&lt;p&gt;MVC takes in a controller context, whereas WebAPI takes in an actionContext (which has a reference to a controller context). And MVC returns the object for the model, whereas WebAPI&amp;#160; returns a bool and sets the model result on the binding context. (As a reminder, WebAPI and MVC share design patterns, but have different types. So while you can often cut and paste code between them, you may need to touch up namespaces)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part B) now we need to wire up the model binder. &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In both MVC and WebAPI, there are 3 places you can do this.&lt;/p&gt;

&lt;p&gt;1) The highest precedence location is the one closest to the parameter. Just add a [ModelBinder] attribute on the parameter’s signature&lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;  MyAction2(
            &lt;strong&gt;[ModelBinder(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(LocationModelBinder))]
&lt;/strong&gt;            Location loc) &lt;span class="rem"&gt;// Use model binding to convert&lt;/span&gt;
        {
            &lt;span class="kwrd"&gt;&lt;span class="rem"&gt;// use loc...&lt;/span&gt;
&lt;/span&gt;        }&lt;/pre&gt;

&lt;p&gt;This is the same as WebAPI. (In WebAPI, this was only supported after beta, so if you’re pre-RTM, you’ll need the &lt;a href="http://aspnetwebstack.codeplex.com/SourceControl/list/changesets"&gt;latest sources&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;2) add a [ModelBinder] attribute on the type’s declaration.&amp;#160; &lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;strong&gt;[ModelBinder(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(LocationModelBinder))]&lt;br /&gt;       &lt;/strong&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Location { ... }&lt;/pre&gt;


&lt;p&gt;Same as WebAPI, like #1. &lt;/p&gt;

&lt;p&gt;3) Change it in a global config setting&lt;/p&gt;

&lt;p&gt;In MVC, this is in the global.asax file. An easy way is just like so:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;       ModelBinders.Binders.Add(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Location), &lt;span class="kwrd"&gt;new&lt;/span&gt; LocationModelBinder());            &lt;/pre&gt;


&lt;p&gt;In WebAPI, registration is on the HttpConfiguration object. Web API strictly goes through the service resolver. WebAPI does have a gotcha that you need to register custom model binders at the front because the default list has MutableObjectModelBinder which zealously claims all types and so would shadow your custom binder if it were just appended to the end.
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;            
            config.Services.Insert(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(System.Web.Http.ModelBinding.ModelBinderProvider), &lt;br /&gt;                  0, &lt;span class="rem"&gt;// Insert at front to ensure other catch-all binders don’t claim it first&lt;br /&gt;&lt;/span&gt;                  &lt;span class="kwrd"&gt;new&lt;/span&gt; LocationModelBinderProvider()); 
&lt;/pre&gt;


&lt;p&gt;And then in WebAPI, you still need to add an empty [ModelBinder] attribute on the parameter to tell WebAPI to look in the model binders instead of trying to use&amp;#160; a formatter on it.&lt;/p&gt;

&lt;p&gt;The [ModelBinder] doesn’t need to specify the binder type because you provided it in the config object. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;  MyAction2([ModelBinder] Location loc) &lt;span class="rem"&gt;// Use model binding to convert&lt;/span&gt;
        {
            &lt;span class="rem"&gt;// use loc...&lt;/span&gt;
        }&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;What does WebAPI do under the hood? &lt;/strong&gt;In all 3 cases, WebAPI sees a [ModelBinder] attribute associated with the parameter (either on the Parameter or on the Parameter’s Type’s declaration). The model binder attribute can either supply the binder directly (as in cases #1 and #2) or fetch the binder from the config (case #3). WebAPI then invokes that binder to get a value for the parameter. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;/pre&gt;


&lt;h3&gt;Other places to hook?&lt;/h3&gt;

&lt;p&gt;WebAPI is very extensible and you could try to hook other places too, but the ones above are the most common and easiest for this scenario. But for completeness sake, I’ll mention a few other options, which I may blog about more later:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;For example, you could hook the IActionValueBinder (here’s an example of an &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx"&gt;MVC-style parameter binder&lt;/a&gt;), IHttpActionInvoker (to populate right before invoking the action), or even populate parameters through a filter.&lt;/li&gt;

  &lt;li&gt;By default, complex types try to come from the body, and the body is read via Formatters. So you could also try to provide a custom formatter. However, that’s not ideal because in our example, we wanted data from the query string and Formatters can’t read the query string. &lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10295971" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>MVC Style parameter binding for WebAPI</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx</link><pubDate>Thu, 19 Apr 2012 00:42:01 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10295166</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10295166</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx#comments</comments><description>&lt;p&gt;I described earlier &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx"&gt;how WebAPI binds parameters&lt;/a&gt;. The entire parameter binding behavior is determined by the IActionValueBinder interface and can be swapped out. The default implementation is DefaultActionValueBinder. &lt;/p&gt;  &lt;p&gt;Here’s another IActionValueBinder that provides MVC parameter binding semantics. This lets you do things that you can’t do in WebAPI’s default binder, specifically:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;ModelBinds everything, including the body. Assumes the body is FormUrl encoded&lt;/li&gt;    &lt;li&gt;This means you can do MVC scenarios where a complex type is bound with one field from the query string and one field from the form data in the body.&lt;/li&gt;    &lt;li&gt;Allows multiple parameters to be bound from the body. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h3&gt;Brief description of IActionValueBinder&lt;/h3&gt;  &lt;p&gt;Here’s what IActionValueBinder looks like:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IActionValueBinder
    {
        HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor);
    }&lt;/pre&gt;

&lt;p&gt;This is called to bind the parameters. It returns a&amp;#160; HttpActionBinding object, which is a 1:1 with an ActionDescriptor. It can be cached across requests. The interesting method on that binding object is:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;    public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)&lt;/pre&gt;


&lt;p&gt;This will execute the bindings for all the parameters, and signal the task when completed. This will invoke model binding, formatters, or any other parameter binding technique. The parameters are added to the actionContext’s parameter dictionary.&lt;/p&gt;

&lt;p&gt;You can hook IActionValueBinder to provide your own binding object, which can have full control over binding the parameters. This is a bigger hammer than adding formatters or custom model binders. &lt;/p&gt;

&lt;p&gt;You can hook up an IActionValueBinder either through the service resolver of the HttpControllerConfiguration attribute on a controller. &lt;/p&gt;

&lt;h3&gt;Example usage:&lt;/h3&gt;

&lt;p&gt;Here’s a an example usage. Suppose you have this code on the server. This is using the HttpControllerConfiguration attribute, and so all of the actions on that controller will use the binder. However, since it’s per-controller, that means it can still peacefully coexist with other controllers on the server.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Customer
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; name { get; set; }
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; age { get; set; }
    }

    &lt;font style="background-color: rgb(255, 255, 0);"&gt;[HttpControllerConfiguration(ActionValueBinder=&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(MvcActionValueBinder))]
&lt;/font&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MvcController : ApiController
    {
        [HttpGet]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Combined(Customer item)
        {
        }
    }&lt;/pre&gt;


&lt;p&gt;And then here’s the client code to call that same action 3 times, showing the fields coming from different places. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; TestMvcController()
        {
            HttpConfiguration config = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpConfiguration();
            config.Routes.MapHttpRoute(&lt;span class="str"&gt;&amp;quot;Default&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;{controller}/{action}&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;&amp;quot;Home&amp;quot;&lt;/span&gt; });

            HttpServer server = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpServer(config);
            HttpClient client = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpClient(server);

            &lt;span class="rem"&gt;// Call the same action. Action has parameter with 2 fields. &lt;/span&gt;

            &lt;span class="rem"&gt;// Get one field from URI, the other field from body&lt;/span&gt;
            {
                HttpRequestMessage request = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = &lt;span class="kwrd"&gt;new&lt;/span&gt; Uri(&lt;span class="str"&gt;&amp;quot;http://localhost:8080/Mvc/Combined?age=10&amp;quot;&lt;/span&gt;),
                    Content = FormUrlContent(&lt;span class="str"&gt;&amp;quot;name=Fred&amp;quot;&lt;/span&gt;)
                };

                var response = client.SendAsync(request).Result;
            }

            &lt;span class="rem"&gt;// Get both fields from the body&lt;/span&gt;
            {
                HttpRequestMessage request = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = &lt;span class="kwrd"&gt;new&lt;/span&gt; Uri(&lt;span class="str"&gt;&amp;quot;http://localhost:8080/Mvc/Combined&amp;quot;&lt;/span&gt;),
                    Content = FormUrlContent(&lt;span class="str"&gt;&amp;quot;name=Fred&amp;amp;age=11&amp;quot;&lt;/span&gt;)
                };

                var response = client.SendAsync(request).Result;
            }

            &lt;span class="rem"&gt;// Get both fields from the URI&lt;/span&gt;
            {
                var response = client.GetAsync(&lt;span class="str"&gt;&amp;quot;http://localhost:8080/Mvc/Combined?name=Bob&amp;amp;age=20&amp;quot;&lt;/span&gt;).Result;
            }
        }&lt;/pre&gt;


&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;static&lt;/span&gt; HttpContent FormUrlContent(&lt;span class="kwrd"&gt;string&lt;/span&gt; content)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(content, Encoding.UTF8, &lt;span class="str"&gt;&amp;quot;application/x-www-form-urlencoded&amp;quot;&lt;/span&gt;);
        }&lt;/pre&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;The MvcActionValueBinder:&lt;/h3&gt;

&lt;p&gt;Here’s the actual code for the binder. Under 100 lines.&amp;#160; (Disclaimer: this requires the latest sources. I verified against &lt;a href="http://aspnetwebstack.codeplex.com/SourceControl/changeset/changes/87e88d0446a2"&gt;this change&lt;/a&gt;. I had to fix an issue that allowed ValueProviderFactory.GetValueProvider to return null).&lt;/p&gt;

&lt;p&gt;Notice that it reads the body once per request, creates a per-request ValueProvider around the form data, and stashes that in request-local-storage so that all of the parameters share the same value provider. This sharing is essential because the body can only be read once. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;// Example of MVC-style action value binder.&lt;/span&gt;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Specialized;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Globalization;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http.Formatting;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Threading;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Threading.Tasks;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.Controllers;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.ModelBinding;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.ValueProviders;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.ValueProviders.Providers;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Basic
{    
    &lt;span class="rem"&gt;// Binder with MVC semantics. Treat the body as KeyValue pairs and model bind it. &lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MvcActionValueBinder : DefaultActionValueBinder
    {
        &lt;span class="rem"&gt;// Per-request storage, uses the Request.Properties bag. We need a unique key into the bag. &lt;/span&gt;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Key = &lt;span class="str"&gt;&amp;quot;5DC187FB-BFA0-462A-AB93-9E8036871EC8&amp;quot;&lt;/span&gt;;

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor)
        {
            MvcActionBinding actionBinding = &lt;span class="kwrd"&gt;new&lt;/span&gt; MvcActionBinding();
                                    
            HttpParameterDescriptor[] parameters = actionDescriptor.GetParameters().ToArray();
            HttpParameterBinding[] binders = Array.ConvertAll(parameters, p =&amp;gt; DetermineBinding(actionBinding, p));

            actionBinding.ParameterBindings = binders;
                        
            &lt;span class="kwrd"&gt;return&lt;/span&gt; actionBinding;            
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; HttpParameterBinding DetermineBinding(MvcActionBinding actionBinding, HttpParameterDescriptor parameter)
        {
            HttpConfiguration config = parameter.Configuration;

            var attr = &lt;span class="kwrd"&gt;new&lt;/span&gt; ModelBinderAttribute(); &lt;span class="rem"&gt;// use default settings&lt;/span&gt;
            
            ModelBinderProvider provider = attr.GetModelBinderProvider(config);
            IModelBinder binder = provider.GetBinder(config, parameter.ParameterType);

            &lt;span class="rem"&gt;// Alternatively, we could put this ValueProviderFactory in the global config.&lt;/span&gt;
            List&amp;lt;ValueProviderFactory&amp;gt; vpfs = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;ValueProviderFactory&amp;gt;(attr.GetValueProviderFactories(config));
            vpfs.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; BodyValueProviderFactory());

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ModelBinderParameterBinding(parameter, binder, vpfs);
        }   

        &lt;span class="rem"&gt;// Derive from ActionBinding so that we have a chance to read the body once and then share that with all the parameters.&lt;/span&gt;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;font style="background-color: rgb(255, 255, 0);"&gt;MvcActionBinding&lt;/font&gt; : HttpActionBinding
        {                
            &lt;span class="rem"&gt;// Read the body upfront , add as a ValueProvider&lt;/span&gt;
            &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                HttpRequestMessage request = actionContext.ControllerContext.Request;
                HttpContent content = request.Content;
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (content != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
                {
                    FormDataCollection fd = content.ReadAsAsync&amp;lt;FormDataCollection&amp;gt;().Result;
                    &lt;span class="kwrd"&gt;if&lt;/span&gt; (fd != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
                    {
                        NameValueCollection nvc = fd.ReadAsNameValueCollection();

                        IValueProvider vp = &lt;span class="kwrd"&gt;new&lt;/span&gt; NameValueCollectionValueProvider(nvc, CultureInfo.InvariantCulture);

                        request.Properties.Add(Key, vp);
                    }
                }
                        
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.ExecuteBindingAsync(actionContext, cancellationToken);
            }
        }

        &lt;span class="rem"&gt;// Get a value provider over the body. This can be shared by all parameters. &lt;/span&gt;
        &lt;span class="rem"&gt;// This gets the values computed in MvcActionBinding.&lt;/span&gt;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; BodyValueProviderFactory : ValueProviderFactory
        {
            &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; IValueProvider GetValueProvider(HttpActionContext actionContext)
            {
                &lt;span class="kwrd"&gt;object&lt;/span&gt; vp;
                actionContext.Request.Properties.TryGetValue(Key, &lt;span class="kwrd"&gt;out&lt;/span&gt; vp);
                &lt;span class="kwrd"&gt;return&lt;/span&gt; (IValueProvider)vp; &lt;span class="rem"&gt;// can be null                &lt;/span&gt;
            }
        }
    }
}

&lt;/pre&gt;


&lt;p&gt;--&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10295166" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Sample+Code/">Sample Code</category><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>How WebAPI does Parameter Binding</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx</link><pubDate>Mon, 16 Apr 2012 21:33:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10294262</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10294262</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx#comments</comments><description>&lt;p&gt;Here’s an overview of how WebAPI binds parameters to an action method.&amp;#160; I’ll describe how parameters can be read, the set of rules that determine which technique is used, and then provide some examples. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;[&lt;strong&gt;update&lt;/strong&gt;] Parameter binding is ultimately about taking a HTTP request and converting it into .NET types so that you can have a better action signature.&amp;#160; &lt;/p&gt;  &lt;p&gt;The request message has everything about the request, including the incoming URL with query string, content body, headers, etc.&amp;#160; Eg, without parameter binding, every action would have to take the request message and manually extract the parameters, kind of like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public object&lt;/span&gt; MyAction(HttpRequestMessage request)
{
        &lt;span class="rem"&gt;// make explicit calls to get parameters from the request object&lt;/span&gt;
        &lt;span class="kwrd"&gt;int&lt;/span&gt; id = &lt;span class="kwrd"&gt;int&lt;/span&gt;.Parse(request.RequestUri.ParseQueryString().Get(&lt;span class="str"&gt;&amp;quot;id&amp;quot;&lt;/span&gt;)); &lt;span class="rem"&gt;// need error logic!&lt;/span&gt;
        Customer c = request.Content.ReadAsAsync&amp;lt;Customer&amp;gt;().Result; &lt;span class="rem"&gt;// should be async!&lt;/span&gt;
        &lt;span class="rem"&gt;// Now use id and customer&lt;/span&gt;
}
  &lt;/pre&gt;
  &lt;/blockquote&gt;

&lt;p&gt;That’s ugly, error prone, repeats boiler plate code, is missing corner cases, and hard to unit test. You want the action signature to be something more relevant like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public object&lt;/span&gt; MyAction(&lt;span class="kwrd"&gt;int&lt;/span&gt; id, Customer c) { }&lt;/pre&gt;
  &lt;/blockquote&gt;

&lt;p&gt;So how does WebAPI convert from a request message into real parameters like id and customer?&lt;/p&gt;

&lt;h3&gt;Model Binding vs. Formatters&lt;/h3&gt;

&lt;p&gt;There are 2 techniques for binding parameters: Model Binding and Formatters. In practice, WebAPI uses model binding to read from the query string and Formatters to read from the body.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(1) Using Model Binding:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ModelBinding is the same concept as in MVC, which has been written about a fair amount (such as &lt;a href="http://msdn.microsoft.com/en-us/library/dd410405.aspx"&gt;here&lt;/a&gt;). Basically, there are “ValueProviders” which supply pieces of data such as query string parameters, and then a model binder assembles those pieces into an object. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(2) Using Formatters:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Formatters (see the MediaTypeFormatter class) are just traditional serializers with extra metadata such as the associated content type. WebAPI gets the list of formatters from the HttpConfiguration, and then uses the request’s content-type to select an appropriate formatter. WebAPI has some default formatters. The default JSON formatter is &lt;a href="http://json.codeplex.com/"&gt;JSON.Net&lt;/a&gt;. There is an Xml formatter and a FormUrl formatter that uses JQuery’s syntax.&lt;/p&gt;

&lt;p&gt;The key method is MediaTypeFormatter.ReadFromStreayAsync, which looks :&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; Task&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; ReadFromStreamAsync(&lt;br /&gt;    Type type, &lt;br /&gt;    Stream stream, &lt;br /&gt;    HttpContentHeaders contentHeaders, &lt;br /&gt;    IFormatterLogger formatterLogger)&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;Type is the parameter type being read, which is passed to the serializer. Stream is the request’s content stream. The read function then reads the stream, instantiates an object, and returns it. &lt;/p&gt;

&lt;p&gt;HttpContentHeaders are just from the request message. IFormatterLogger is a callback interface that a formatter can use to log errors while reading (eg, malformed data for the given type). &lt;/p&gt;

&lt;p&gt;Both model binding and formatters support validation and log rich error information.&amp;#160; However, model binding is significantly more flexible. &lt;/p&gt;

&lt;h3&gt;When do we use which?&lt;/h3&gt;

&lt;p&gt;Here are the basic rules to determine whether a parameter is read with model binding or a formatter:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type. &lt;strong&gt;“Simple types” uses model binding.&lt;/strong&gt; Complex types uses the formatters. A “simple type” includes: &lt;a href="http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx"&gt;primitives&lt;/a&gt;, TimeSpan, DateTime, Guid, Decimal, String, or something with a TypeConverter that converts from strings.&lt;/li&gt;

  &lt;li&gt;You can use a [FromBody] attribute to specify that a parameter should be from the body. &lt;/li&gt;

  &lt;li&gt;You can use a [ModelBinder] attribute on the parameter or the parameter’s type to specify that a parameter should be model bound. This attribute also lets you configure the model binder.&amp;#160; [FromUri] is a derived instance of [ModelBinder] that specifically configures a model binder to only look in the URI. &lt;/li&gt;

  &lt;li&gt;The body can only be read once.&amp;#160; So if you have 2 complex types in the signature, at least one of them must have a [ModelBinder] attribute on it. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It was&amp;#160; a key design goal for these rules to be static and predictable. &lt;/p&gt;

&lt;h3&gt;Only one thing can read the body&lt;/h3&gt;

&lt;p&gt;A key difference between MVC and WebAPI is that MVC buffers the content (eg, request body). This means that MVC’s parameter binding can repeatedly search through the body to look for pieces of the parameters. Whereas in WebAPI, the request body (an HttpContent) may be a read-only, infinite, non-buffered, non-rewindable stream. &lt;/p&gt;

&lt;p&gt;That means that parameter binding needs to be very careful about not reading the stream unless it’s guaranteeing to bind a parameter.&amp;#160; The action body may want to read the stream directly, and so WebAPI can’t assume that it owns the stream for parameter binding.&amp;#160; Consider this example action:&lt;/p&gt;&amp;#160;&amp;#160;&amp;#160; &lt;pre class="csharpcode"&gt;        &lt;span class="rem"&gt;// Action saves the request’s content into an Azure blob &lt;/span&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; Task PostUploadfile(&lt;span class="kwrd"&gt;string&lt;/span&gt; destinationBlobName)
        {
            &lt;span class="rem"&gt;// string should come from URL, we’ll read content body ourselves.&lt;/span&gt;
            Stream azureStream = OpenAzureStorage(destinationBlobName); &lt;span class="rem"&gt;// stream to write to azure&lt;/span&gt;
            return &lt;span class="kwrd"&gt;this&lt;/span&gt;.Request.Content.CopyToStream(azureStream); &lt;span class="rem"&gt;// upload body contents to azure. &lt;/span&gt;
        }&lt;/pre&gt;


&lt;p&gt;The parameter is a simple type, and so it’s pulled from the query string. Since there are no complex types in the action signature, webAPI never even touches the request content stream, and so the action body can freely read it. &lt;/p&gt;

&lt;h3&gt;Some examples&lt;/h3&gt;

&lt;p&gt;Here are some examples of various requests and how they map to action signatures. &lt;/p&gt;

&lt;p&gt;/?id=123&amp;amp;name=bob 
  &lt;br /&gt;void Action(int id, string name) // both parameters are simple types and will come from url&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;/?id=123&amp;amp;name=bob 
  &lt;br /&gt;void Action([FromUri] int id, [FromUri] string name) // paranoid version of above. &lt;/p&gt;

&lt;p&gt;void Action([FromBody] string name); // explicitly read the body as a string. &lt;/p&gt;

&lt;p&gt;public class Customer {&amp;#160;&amp;#160; // a complex object 
  &lt;br /&gt;&amp;#160; public string Name { get; set; } 

  &lt;br /&gt;&amp;#160; public int Age { get; set; } 

  &lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;/?id=123 
  &lt;br /&gt;void Action(int id, Customer c) // id from query string, c is a complex object, comes from body via a formatter.&lt;/p&gt;

&lt;p&gt;void Action(Customer c1, Customer c2) // error! multiple parameters attempting to read from the body &lt;/p&gt;

&lt;p&gt;void Action([FromUri] Customer c1, Customer c2) // ok, c1 is from the URI and c2 is from the body &lt;/p&gt;

&lt;p&gt;void Action([ModelBinder(MyCustomBinder)] SomeType c) // Specifies a precise model binder to use to create the parameter. &lt;/p&gt;

&lt;p&gt;[ModelBinder(MyCustomBinder)] public class SomeType { } // place attribute on type declaration to apply to all parameter instances 
  &lt;br /&gt;void Action(SomeType c) // attribute on c’s declaration means it uses model binding. &lt;/p&gt;

&lt;h3&gt;Differences with MVC&lt;/h3&gt;

&lt;p&gt;Here are some differences between MVC and WebAPI’s parameter binding:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;MVC only had model binders and no formatters. That’s because MVC would model bind over the request’s body (which it commonly expected to just be FormUrl encoded), whereas WebAPI uses a serializer over the request’s body. &lt;/li&gt;

  &lt;li&gt;MVC buffered the request body, and so could easily feed it into model binding. WebAPI does not buffer the request body, and so does not model bind against the request body by default.&lt;/li&gt;

  &lt;li&gt;WebAPI’s binding can be determined entirely statically based off the action signature types. For example, in WebAPI, you know statically whether a parameter will bind against the body or the query string. Whereas in MVC, the model binding system would search both body and query string.&lt;/li&gt;
&lt;/ol&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10294262" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>ASP.Net WebAPI</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/03/30/asp-net-webapi.aspx</link><pubDate>Sat, 31 Mar 2012 03:48:12 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10289603</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10289603</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/03/30/asp-net-webapi.aspx#comments</comments><description>&lt;p&gt;I recently joined the ASP.Net team and have been working on &lt;a href="http://www.asp.net/web-api"&gt;WebAPI&lt;/a&gt;, which is a new .NET MVC-like framework for building HTTP web services. (This is certainly a change of pace from my previous life in the world of compilers and debuggers, but I’m having a blast ) &lt;/p&gt;  &lt;p&gt;ScottGu gave a nice overview of WebAPI &lt;a href="http://weblogs.asp.net/scottgu/archive/2012/02/23/asp-net-web-api-part-1.aspx"&gt;here&lt;/a&gt; and just announced that &lt;a href="http://weblogs.asp.net/scottgu/archive/2012/03/27/asp-net-mvc-web-api-razor-and-open-source.aspx"&gt;WebAPI&amp;#160; has gone open source&lt;/a&gt; on Codeplex with GIT.&amp;#160; It’s nice to be able to check in a feature and then immediately blog about it. &lt;/p&gt;  &lt;p&gt;A discussion forum for WebAPI is &lt;a href="http://forums.asp.net/1246.aspx/1?ASP+NET+Web+API"&gt;here&lt;/a&gt;. The codeplex site is &lt;a href="http://aspnetwebstack.codeplex.com/"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10289603" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WebAPI/">WebAPI</category></item><item><title>OpenSource CSV Reader on Nuget</title><link>http://blogs.msdn.com/b/jmstall/archive/2012/03/24/opensource-csv-reader-on-nuget.aspx</link><pubDate>Sat, 24 Mar 2012 16:31:26 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10287211</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10287211</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2012/03/24/opensource-csv-reader-on-nuget.aspx#comments</comments><description>&lt;p&gt;I did some volunteer work a few years ago that required processing lots of CSV files. So I solved the problems by writing a C# CSV reader, which I wanted to share here. The basic features here are:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;be easy to use&lt;/li&gt;    &lt;li&gt;read and write CSV files (and support tab and “|” delimiters too)&lt;/li&gt;    &lt;li&gt;create CSV files around IEnumerable&amp;lt;T&amp;gt;, dictionaries, and other sources. &lt;/li&gt;    &lt;li&gt;Provide a “linq to CSV” experience &lt;/li&gt;    &lt;li&gt;provide both in-memory mutable tables and streaming over large data sources (thank you polymorphism!)&lt;/li&gt;    &lt;li&gt;provide basic analysis operations like histogram, join, find duplicates, etc. The operations I implemented were driven entirely by the goals I had for my volunteer work. &lt;/li&gt;    &lt;li&gt;Read from Excel&lt;/li&gt;    &lt;li&gt;Work with Azure. (This primarily means no foolish dependencies, and support TextReader/TextWriter instead of always hitting the file system)&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;I went ahead and put it on github&amp;#160; at &lt;a title="https://github.com/MikeStall/DataTable" href="https://github.com/MikeStall/DataTable"&gt;https://github.com/MikeStall/DataTable&lt;/a&gt;. And it’s available for download via &lt;a href="http://nuget.org/"&gt;Nuget&lt;/a&gt; (see “CsvTools”).&amp;#160; It’s nice to share, and maybe somebody else will find this useful. But selfishly, I’ve used this library for quite a few tasks over the years and putting it on Github and Nuget also makes it easier for me to find for future projects. &lt;/p&gt;  &lt;p&gt;There are the obvious disclaimers here that this was just a casual side project I did as a volunteer, and so use as is. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Step 1: Install “CsvTools” via Nuget:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;When you right click on the project references node, just select “Add Library Package Reference”. That will bring up the nuget dialog which will search the online repository for packages. Search for “&lt;strong&gt;CsvTools&lt;/strong&gt;” and then you can instantly install it. It’s built against CLR 4.0, but has no additional dependencies. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/6840.image4_5F00_661A541D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-40-72-metablogapi/7178.image4_5F00_thumb_5F00_6C612AAB.png" width="614" height="408" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Example 1: Loading from a CSV file&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Here’s a CSV at: c:\temp\test.csv&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;name, species        &lt;br /&gt;Kermit, Frog         &lt;br /&gt;Ms. Piggy, Pig         &lt;br /&gt;Fozzy, Bear &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To open and print the contents of the file:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue"&gt;using &lt;/span&gt;DataAccess; &lt;span style="color: green"&gt;// namespace that Csv reader lives in

&lt;/span&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #2b91af"&gt;DataTable &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.ReadCsv(&lt;span style="color: #a31515"&gt;@&amp;quot;C:\temp\test.csv&amp;quot;&lt;/span&gt;);

        &lt;span style="color: green"&gt;// Query via the DataTable.Rows enumeration.
        &lt;/span&gt;&lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Row &lt;/span&gt;row &lt;span style="color: blue"&gt;in &lt;/span&gt;dt.Rows)
        {
            &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(row[&lt;span style="color: #a31515"&gt;&amp;quot;name&amp;quot;&lt;/span&gt;]);
        }        
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;There are a bunch of extension methods hanging off “DataTable.New” to provide different ways of loading a table. ReadCsv will load everything into memory, which allows mutation operations (see below).&amp;#160; But this also supports streaming operations via the methods with “lazy” in their name, such as ReadLazy().&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2: Creating a CSV from an IEnumerable&amp;lt;T&amp;gt; and saving back to a file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s creating a table from an IEnumerable&amp;lt;T&amp;gt;, and then saving that back to a TextWriter (in this case, Console.Out).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;vals = &lt;span style="color: blue"&gt;from &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(1, 10) &lt;span style="color: blue"&gt;select new &lt;/span&gt;{ N = i, NSquared = i * i };
&lt;span style="color: #2b91af"&gt;DataTable &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.FromEnumerable(vals);
dt.SaveToStream(&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.Out);  &lt;/pre&gt;
  &lt;/blockquote&gt;


&lt;p&gt;
  &lt;br /&gt;Which produces this CSV:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Consolas"&gt;N,NSquared
      &lt;br /&gt;1,1

      &lt;br /&gt;2,4

      &lt;br /&gt;3,9

      &lt;br /&gt;4,16

      &lt;br /&gt;5,25

      &lt;br /&gt;6,36

      &lt;br /&gt;7,49

      &lt;br /&gt;8,64

      &lt;br /&gt;9,81

      &lt;br /&gt;10,100&lt;/font&gt;

    &lt;br /&gt;&lt;/p&gt;
&lt;/blockquote&gt;


&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 3: Mutations &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;DataTable is actually an abstract base class. There are two primary derived classes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;MutableDataTable,, which loads everything into memory, stores it in column major order, and provides mutation operations. &lt;/li&gt;

  &lt;li&gt;streaming data table, which provides streaming access over a rows. This is obviously row major order, and doesn’t support mutation. The streaming classes are non-public derived classes of DataTable. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Most of the builder functions that load in memory actually return the derived MutableDataTable object anyways. A MutableDataTable is conceptually a giant 2d string array stored in column major order. So adding new columns or rearranging columns is cheap. Adding rows is expensive. Here’s an example of some mutations:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
{
    &lt;span style="color: #2b91af"&gt;&lt;strong&gt;MutableDataTable&lt;/strong&gt; &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.ReadCsv(&lt;span style="color: #a31515"&gt;@&amp;quot;C:\temp\test.csv&amp;quot;&lt;/span&gt;);

    &lt;span style="color: green"&gt;// Mutations
    &lt;/span&gt;dt.ApplyToColumn(&lt;span style="color: #a31515"&gt;&amp;quot;name&amp;quot;&lt;/span&gt;, originalValue =&amp;gt; originalValue.ToUpper());
    dt.RenameColumn(oldName:&lt;span style="color: #a31515"&gt;&amp;quot;species&amp;quot;&lt;/span&gt;, newName: &lt;span style="color: #a31515"&gt;&amp;quot;kind&amp;quot;&lt;/span&gt;);
    
    
    &lt;span style="color: blue"&gt;int &lt;/span&gt;id = 0;
    dt.CreateColumn(&lt;span style="color: #a31515"&gt;&amp;quot;id#&amp;quot;&lt;/span&gt;, row =&amp;gt; { id++; &lt;span style="color: blue"&gt;return &lt;/span&gt;id.ToString(); });

    dt.GetRow(1)[&lt;span style="color: #a31515"&gt;&amp;quot;kind&amp;quot;&lt;/span&gt;] = &lt;span style="color: #a31515"&gt;&amp;quot;Pig!!&amp;quot;&lt;/span&gt;; &lt;span style="color: green"&gt;// update in place by row
    &lt;/span&gt;dt.Columns[0].Values[2] = &lt;span style="color: #a31515"&gt;&amp;quot;Fozzy!!&amp;quot;&lt;/span&gt;; &lt;span style="color: green"&gt;// update by column

    // Print out new table
    &lt;/span&gt;dt.SaveToStream(&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.Out);        
}&lt;/pre&gt;

&lt;p&gt;Produces and prints this table:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Consolas"&gt;name,kind,id#
      &lt;br /&gt;KERMIT,Frog,1

      &lt;br /&gt;MS. PIGGY,Pig!!,2

      &lt;br /&gt;Fozzy!!,Bear,3&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;There’s a builder function, DataTable.New.GetMutableCopy, which produces a mutable copy from an arbitrary DataTable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 4: Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I needed some basic analysis functions, like join, histogram, select duplicates, sample, and where. These sit as static methods in the Analyze class.&lt;/p&gt;

&lt;p&gt;Here’s an example of creating a table with random numbers, and then printing the histogram:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
{   
    &lt;span style="color: green"&gt;// Get a table of 1000 random numbers
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Random &lt;/span&gt;r = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Random&lt;/span&gt;();
    &lt;span style="color: #2b91af"&gt;DataTable &lt;/span&gt;dt = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.FromEnumerable(
        &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(1, 1000) 
        &lt;span style="color: blue"&gt;select &lt;/span&gt;r.Next(1, 10));

    &lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;,&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;[] hist = &lt;span style="color: #2b91af"&gt;Analyze&lt;/span&gt;.AsHistogram(dt, columnIdx: 0);
    
    &lt;span style="color: green"&gt;// Convert the tuple[] to a table for easy printing
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DataTable &lt;/span&gt;histTable = &lt;span style="color: #2b91af"&gt;DataTable&lt;/span&gt;.New.FromTuple(hist, 
        columnName1: &lt;span style="color: #a31515"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;,
        columnName2: &lt;span style="color: #a31515"&gt;&amp;quot;frequency&amp;quot;&lt;/span&gt;);
    histTable.SaveToStream(&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.Out);
}&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;Produces this result:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Consolas"&gt;value,frequency
      &lt;br /&gt;9,151

      &lt;br /&gt;8,124

      &lt;br /&gt;2,118

      &lt;br /&gt;7,110

      &lt;br /&gt;3,107

      &lt;br /&gt;5,104

      &lt;br /&gt;1,101

      &lt;br /&gt;6,99

      &lt;br /&gt;4,86&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10287211" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Sample+Code/">Sample Code</category><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/random+-net/">random .net</category></item><item><title>Pyvot for Excel</title><link>http://blogs.msdn.com/b/jmstall/archive/2011/11/09/pyvot-for-excel.aspx</link><pubDate>Wed, 09 Nov 2011 17:57:30 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235450</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10235450</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2011/11/09/pyvot-for-excel.aspx#comments</comments><description>&lt;p&gt;I’m thrilled to see the availability of &lt;a href="http://pytools.codeplex.com/wikipage?title=Pyvot"&gt;Pyvot&lt;/a&gt;, a python package for manipulating tabular data in excel. This is part of the &lt;a href="http://pytools.codeplex.com/"&gt;Python Tools for Visual Studio&lt;/a&gt; (PTVS) ecosystem. &lt;/p&gt;  &lt;p&gt;Check out the codeplex site at &lt;a title="http://pytools.codeplex.com/wikipage?title=Pyvot" href="http://pytools.codeplex.com/wikipage?title=Pyvot"&gt;http://pytools.codeplex.com/wikipage?title=Pyvot&lt;/a&gt; or the tutorial on &lt;a href="http://packages.python.org/Pyvot/tutorial.html"&gt;python.org&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Excel does expose an object model through COM, but it’s tricky to use.&amp;#160; Pyvot provides a very simple python programming experience that focuses on your data instead of Excel COM object trivia. Here are some of my favorite examples:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Easy to send python data into excel, manipulate it in excel, and then send it back to python. &lt;/li&gt;    &lt;li&gt;if you ask for a column in Excel’s object model, it will give you back the entire Excel column, including the one million empty cells. Wheras Pyvot will just give you back the data you used. &lt;/li&gt;    &lt;li&gt;Pyvot will recognize column header names from tables. &lt;/li&gt;    &lt;li&gt;Pyvot makes it easy to compute new columns and add them to your table. &lt;/li&gt;    &lt;li&gt;Pyvot makes it easy to connect to an existing excel workbook, even if the workbook has not even been saved to a file. (This involved scanning down the running object table, and doing smart name matching). This allows you to use excel as a scratchpad for python. &lt;/li&gt;    &lt;li&gt;Pyvot works naturally with Excel’s existing auto-filters. This enables a great scenario where you can start with data in python, send it to excel and manipulate it with excel auto filters (sort it, remove bad values, etc), and then pull the cleaned data back into python. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Some other FAQs:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;em&gt;What can’t Pyvot do&lt;/em&gt;? Pyvot is really focused on tabular data. Excel becomes a Datatable viewer for Python. However Pyvot is not intended to be a full excel automation solution. &lt;/li&gt;    &lt;li&gt;&lt;em&gt;How does Pyvot compare to VBA&lt;/em&gt;? a) Pyvot is just Python and so you can use vast existing Python libraries. b) Also, VBA is embedded in a single excel workbook and is hard to share across workbooks. Pyvot is about real Python files that live outside of the workbook and can be shared and managed under source control.&amp;#160; c) VBA uses the excel object model, whereas Pyvot provides a much simpler experience for tabular data. &lt;/li&gt;    &lt;li&gt;&lt;em&gt;How does Pyvot compare to an Excel-addin&lt;/em&gt;? a) Pyvot runs entirely out-of-process, so you don’t need to worry about it crashing Excel on you.&amp;#160; b) Excel-addins, like VBA, use the excel object model. c) Excel addins need to be installed. Pyvot is just loose python files that don’t interfere with your excel installation.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Anyway, if you need to excel goodness, especially filters, check out &lt;a href="http://pytools.codeplex.com/wikipage?title=Pyvot"&gt;Pyvot&lt;/a&gt; and &lt;a href="http://pytools.codeplex.com/"&gt;PTVS&lt;/a&gt;. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235450" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Python/">Python</category></item><item><title>Python Tools for VS</title><link>http://blogs.msdn.com/b/jmstall/archive/2011/09/20/python-tools-for-vs.aspx</link><pubDate>Tue, 20 Sep 2011 18:16:05 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10214200</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10214200</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2011/09/20/python-tools-for-vs.aspx#comments</comments><description>&lt;p&gt;I’ve been having a great time using &lt;a href="http://pytools.codeplex.com/" target="_blank"&gt;Python Tools for VS&lt;/a&gt;.&amp;#160; It’s a free download that provides CPython language support in Visual Studio 2010. The intellisense is pretty good (especially for a dynamic language!) and the debugger is useful to have. Having a good IDE is changing the way I view the language. Check out the &lt;a href="http://pytools.codeplex.com/" target="_blank"&gt;homepage&lt;/a&gt; for a long list of features it supports. One other perk is that because it’s using the VS 2010 shell, it works with my favorite VS 2010 editor extensions. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10214200" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Python/">Python</category></item><item><title>Windows Phone 7</title><link>http://blogs.msdn.com/b/jmstall/archive/2010/12/12/windows-phone-7.aspx</link><pubDate>Mon, 13 Dec 2010 03:24:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10103857</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=10103857</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2010/12/12/windows-phone-7.aspx#comments</comments><description>&lt;p&gt;I recently got the newly released &lt;a href="http://www.microsoft.com/windowsphone"&gt;Windows Phone 7&lt;/a&gt; (the &lt;a href="http://www.samsung.com/us/mobile/cell-phones/SGH-I917ZKAATT"&gt;Samsung Focus&lt;/a&gt;). So far, I love it! This is my first smart-phone.&amp;#160; It’s nice to join the 21st century. &lt;/p&gt;  &lt;p&gt;I’m also poking around with how to write apps for it. It was easy to download C# Express and WP7 tools and get started with the emulator. &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;I started with ScottGu’s blog announcing the &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/09/16/windows-phone-7-developer-tools-released.aspx"&gt;release of WP7 Dev tools&lt;/a&gt;. You can download the tools &lt;a href="http://go.microsoft.com/fwlink/?LinkId=185584"&gt;here&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;I did the &lt;a href="http://msdn.microsoft.com/en-us/library/ff402526(v=VS.92).aspx"&gt;“My first WP7 app” tutorial&lt;/a&gt;, which shows hosting a web browser control. It worked flawlessly in the emulator. &lt;/li&gt;    &lt;li&gt;I also looked at Scott’s blog on &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx"&gt;writing a Twitter app&lt;/a&gt;.&lt;/li&gt;    &lt;li&gt;This is a nice &lt;a href="http://msdn.microsoft.com/en-us/library/ff402535(v=VS.92).aspx"&gt;MSDN summary of basic tasks&lt;/a&gt;.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;WP7 user apps are written in WPF (or XNA). I never really needed WPF when writing debugging stacks, so I’m feeling the pain from the learning curve here. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10103857" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/WP7/">WP7</category></item><item><title>Speaking at Lake County .NET User’s Group</title><link>http://blogs.msdn.com/b/jmstall/archive/2009/09/09/speaking-at-lake-county-net-user-s-group.aspx</link><pubDate>Wed, 09 Sep 2009 22:16:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9892937</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9892937</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2009/09/09/speaking-at-lake-county-net-user-s-group.aspx#comments</comments><description>&lt;p&gt;I’ll be &lt;a href="http://www.lcnug.org/events/09-09-08/LCNUG_September_24_C_4_0-4248649912.aspx" target="_blank"&gt;speaking&lt;/a&gt; at the &lt;a href="http://www.lcnug.org/Home.aspx" target="_blank"&gt;Lake County .NET User’s Group&lt;/a&gt; (LCNUG) near Chicago, Illinois on September 24th.&amp;#160; I’ll be talking about new features in C# 4.0, including named and optional parameters, dynamic support, scripting, office interop and No-PIA (Primary-Interop-Assemblies) support.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;The permalink for the event is &lt;a href="http://www.lcnug.org/events/09-09-08/LCNUG_September_24_C_4_0-4248649912.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;If you’re in the area, swing on by! &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9892937" width="1" height="1"&gt;</description></item><item><title>Writing a CLR Debugger in Python</title><link>http://blogs.msdn.com/b/jmstall/archive/2009/09/08/writing-a-clr-debugger-in-python.aspx</link><pubDate>Wed, 09 Sep 2009 06:13:19 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9892924</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9892924</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2009/09/08/writing-a-clr-debugger-in-python.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://devhawk.net"&gt;Harry Pierson&lt;/a&gt; has written an excellent set of blog entries about writing a managed debugger in &lt;a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython"&gt;IronPython&lt;/a&gt;. He builds on the ICorDebug managed wrappers that we ship in &lt;a href="http://blogs.msdn.com/jmstall/archive/2005/11/08/mdbg_linkfest.aspx"&gt;Mdbg&lt;/a&gt; and explains many of the concepts for how to write a debugger, such as managing breakpoints.&amp;#160; &lt;/p&gt;  &lt;p&gt;Read more about them &lt;a href="http://devhawk.net/CategoryView,category,Debugger.aspx"&gt;here&lt;/a&gt;.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9892924" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/MDbg/">MDbg</category></item><item><title>ICustomQueryInterface and CLR V4</title><link>http://blogs.msdn.com/b/jmstall/archive/2009/07/09/icustomqueryinterface-and-clr-v4.aspx</link><pubDate>Fri, 10 Jul 2009 03:02:25 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9827872</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9827872</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2009/07/09/icustomqueryinterface-and-clr-v4.aspx#comments</comments><description>&lt;p&gt;CLR V4 fixes an issue with COM-interop that’s been bothering me for a while. The problem is that unless you’re using a PIA, &lt;em&gt;you can often have either your caller &lt;u&gt;or&lt;/u&gt; callee be managed code, but not both&lt;/em&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;You can import the same COM-classic interface into managed code multiple times, and two components can naturally end up with two different .NET types representing the same single COM-classic interface. Furthermore, the types can be imported with different managed signatures because of things like [PreserveSig] attributes and different ways to marshal data types.&lt;/p&gt;  &lt;p&gt;(PIAs are supposed to alleviate that by providing a single unified definition, but then getting multiple components to agree on that unified definition is its own problem. CLR V4 added support for to avoid requiring PIAs. see &lt;a href="http://blogs.msdn.com/mshneer/archive/2008/10/28/better-eventing-support-in-clr-4-0-using-nopia-support.aspx"&gt;NoPia&lt;/a&gt;. )&lt;/p&gt;  &lt;p&gt;When managed code calls a COM interface that is implemented by managed code (Managed –&amp;gt; Native –&amp;gt; Managed), the CLR detects that the COM-object is really a managed implementation and creates a direct managed call (Managed –&amp;gt; Managed). So if your caller and callee are bound to different .NET types for the interface, the CLR won’t realize it’s a COM-interface call and will just fail on the .NET type mismatch.&lt;/p&gt;  &lt;p&gt;CLR V4 fixes this by adding the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.icustomqueryinterface.getinterface(VS.100).aspx"&gt;ICustomQueryInterface&lt;/a&gt; that lets a managed object really act as if it’s native code when being called through COM-interop.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Where I hit this…&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I hit this as I was writing debugger code in Managed. We had a managed application (&lt;a href="http://blogs.msdn.com/jmstall/archive/2005/11/08/mdbg_linkfest.aspx"&gt;MDbg&lt;/a&gt;) that used COM-interop to call into a native implementation of ICorDebug. That worked great (managed calling native). Later, we had some cases of creating a managed implementation of certain ICorDebug interfaces. But that failed from Mdbg because they had different COM-interop import definitions for ICorDebug. &lt;/p&gt;  &lt;p&gt;This also just naturally starts showing up as people are porting more and more of their legacy systems to managed code. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Code sample demonstrating the problem&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Say you have a COM-classic interface IFoo, imported by 2 different components:&lt;/p&gt;  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;ComImport&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;InterfaceType&lt;/span&gt;(1), &lt;span style="color: #2b91af"&gt;ComConversionLoss&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;FC3E287D-D659-4E1D-81D5-9D29398C7237&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IFoo1
&lt;/span&gt;{
    [&lt;span style="color: #2b91af"&gt;PreserveSig&lt;/span&gt;]
    &lt;span style="color: blue"&gt;int &lt;/span&gt;Thing(&lt;span style="color: blue"&gt;int &lt;/span&gt;x);
}

[&lt;span style="color: #2b91af"&gt;ComImport&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;InterfaceType&lt;/span&gt;(1), &lt;span style="color: #2b91af"&gt;ComConversionLoss&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;FC3E287D-D659-4E1D-81D5-9D29398C7237&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IFoo2
&lt;/span&gt;{        
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Thing(&lt;span style="color: blue"&gt;int &lt;/span&gt;x);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Now suppose you have a class C1 that implements IFoo1. IFoo1 and IFoo2 represent the same COM interface and have the same GUID, so you’d like to be able to use them interchangeably. However, they’re 2 different .NET types. typeof(IFoo1) != typeof(IFoo2).&lt;/p&gt;

&lt;p&gt;Ideally, you’d like the following snippet to succeed and call Thing(5) and Thing(3) on the object instance obj.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Hi!&amp;quot;&lt;/span&gt;);

    &lt;span style="color: blue"&gt;object &lt;/span&gt;obj = &lt;span style="color: blue"&gt;new &lt;/span&gt;C1();
    obj = GetRCW(obj); // get a COM object for C1

    IFoo1 f1 = (IFoo1)obj;
    IFoo2 f2 = (IFoo2)obj; // Fails!!! obj is really a C1, and can’t cast to a IFoo2
    f1.Thing(5);
    f2.Thing(3);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Run that and you get an invalid cast exception because it can’t cast C1 to a IFoo2. It doesn’t understand that IFoo2 and IFoo1 are the same interface..&lt;/p&gt;

&lt;table border="1"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;
        &lt;pre&gt;&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\TEMP&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;b.exe&lt;/span&gt;&lt;/i&gt;
Hi!

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'ConsoleApplication4.C1' to type 'ConsoleApplication4.IFoo2'.
   at ConsoleApplication4.Program.Main(String[] args)&lt;/pre&gt;
      &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ICustomQueryInterface to the rescue. &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;CLR 4 allows an object to hook ICustomQueryInterface and have fine grain control over QI calls. The CLR detects that C1 is really a managed object because of a QI for a secret interface, &lt;a href="http://msdn.microsoft.com/en-us/library/ms404390.aspx"&gt;IManagedObject&lt;/a&gt;. C1 can intercept this QI call and fail it (by returning CustomQueryInterfaceResult.Failed), and thus look like a native object.&amp;#160; It passes all other QI calls through to the RCW’s QI handling (via returning CustomQueryInterfaceResult.NotHandled)&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Collections.Generic;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Linq;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Text;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Runtime.InteropServices;

&lt;span style="color: blue"&gt;namespace &lt;/span&gt;ConsoleApplication4
{
    [&lt;span style="color: #2b91af"&gt;ComImport&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;InterfaceType&lt;/span&gt;(1), &lt;span style="color: #2b91af"&gt;ComConversionLoss&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;FC3E287D-D659-4E1D-81D5-9D29398C7237&amp;quot;&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IFoo1
    &lt;/span&gt;{
        [&lt;span style="color: #2b91af"&gt;PreserveSig&lt;/span&gt;]
        &lt;span style="color: blue"&gt;int &lt;/span&gt;Thing(&lt;span style="color: blue"&gt;int &lt;/span&gt;x);
    }

    [&lt;span style="color: #2b91af"&gt;ComImport&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;InterfaceType&lt;/span&gt;(1), &lt;span style="color: #2b91af"&gt;ComConversionLoss&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;FC3E287D-D659-4E1D-81D5-9D29398C7237&amp;quot;&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IFoo2
    &lt;/span&gt;{        
        &lt;span style="color: blue"&gt;void &lt;/span&gt;Thing(&lt;span style="color: blue"&gt;int &lt;/span&gt;x);
    }


    &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1 &lt;/span&gt;: IFoo1, ICustomQueryInterface
    {

        &lt;span style="color: blue"&gt;static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;IID_IMarshal = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;00000003-0000-0000-C000-000000000046&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;IID_IManagedObject = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;C3FCC19E-A970-11d2-8B5A-00A0C9B7C9C4&amp;quot;&lt;/span&gt;);

        CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(&lt;span style="color: blue"&gt;ref &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;iid, &lt;span style="color: blue"&gt;out &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IntPtr &lt;/span&gt;ppv)
        {
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(iid == IID_IMarshal ||
                iid == IID_IManagedObject
                )
            {
                ppv = &lt;span style="color: #2b91af"&gt;IntPtr&lt;/span&gt;.Zero;
                &lt;span style="color: blue"&gt;return &lt;/span&gt;CustomQueryInterfaceResult.Failed;
            }

            ppv = &lt;span style="color: #2b91af"&gt;IntPtr&lt;/span&gt;.Zero;
            &lt;span style="color: blue"&gt;return &lt;/span&gt;CustomQueryInterfaceResult.NotHandled;
        }



        &lt;span style="color: blue"&gt;#region &lt;/span&gt;IFoo1 Members

        &lt;span style="color: blue"&gt;public int &lt;/span&gt;Thing(&lt;span style="color: blue"&gt;int &lt;/span&gt;x)
        {
            &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Inside C1={0}&amp;quot;&lt;/span&gt;, x);
            &lt;span style="color: blue"&gt;return &lt;/span&gt;0;
        }

        &lt;span style="color: blue"&gt;#endregion
    &lt;/span&gt;}


   
    &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
    &lt;/span&gt;{
        &lt;span style="color: green"&gt;// Convert it to a RCW
        &lt;/span&gt;&lt;span style="color: blue"&gt;static object &lt;/span&gt;GetRCW(&lt;span style="color: blue"&gt;object &lt;/span&gt;o)
        {
            &lt;span style="color: #2b91af"&gt;IntPtr &lt;/span&gt;ip = &lt;span style="color: #2b91af"&gt;IntPtr&lt;/span&gt;.Zero;
            &lt;span style="color: blue"&gt;try
            &lt;/span&gt;{
                ip = &lt;span style="color: #2b91af"&gt;Marshal&lt;/span&gt;.GetIUnknownForObject(o);
                &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Marshal&lt;/span&gt;.GetObjectForIUnknown(ip);
            }
            &lt;span style="color: blue"&gt;finally
            &lt;/span&gt;{
                &lt;span style="color: #2b91af"&gt;Marshal&lt;/span&gt;.Release(ip);
            }
        }

        &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
        {
            &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Hi!&amp;quot;&lt;/span&gt;);

            &lt;span style="color: blue"&gt;object &lt;/span&gt;c1 = &lt;span style="color: blue"&gt;new &lt;/span&gt;C1();
            &lt;span style="color: blue"&gt;object &lt;/span&gt;obj = GetRCW(c1);

            &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(c1.GetType().FullName); &lt;span style="color: green"&gt;// ConsoleApplication4.C1
            &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(obj.GetType().FullName); &lt;span style="color: green"&gt;// System.__ComObject

            &lt;/span&gt;IFoo1 f1 = (IFoo1)obj;
            IFoo2 f2 = (IFoo2)obj;
            f1.Thing(5);
            f2.Thing(3);
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;We call GetRCW() to convert the object to a Runtime Callable Wrapper (RCW) so that the CLR will actually do COM-interop dispatch. You can observe the GetType() calls on c1 vs. obj.&lt;/p&gt;

&lt;p&gt;Notice now both calls via Thing(5) and Thing(3) succeed. And they’re even going through different import signatures.&lt;/p&gt;

&lt;table border="1"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;
        &lt;pre&gt;&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\TEMP&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;a.exe&lt;/span&gt;&lt;/i&gt;
Hi!
ConsoleApplication4.C1
System.__ComObject
Inside C1=5
Inside C1=3&lt;/pre&gt;
      &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Thanks to Paul Harrington (a dev on the Visual Studio Platform team) and Misha Shneerson&amp;#160; for pointing me at the new functionality and code snippet for C1.GetInterface()&amp;#160; Misha has a lot more information about CLR V4 COM-interop advances on his blog at &lt;a title="http://blogs.msdn.com/mshneer/" href="http://blogs.msdn.com/mshneer/"&gt;http://blogs.msdn.com/mshneer/&lt;/a&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&amp;#160;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9827872" width="1" height="1"&gt;</description></item><item><title>Virtual code execution via IL interpretation</title><link>http://blogs.msdn.com/b/jmstall/archive/2009/05/21/virtual-code-execution-via-il-interpretation.aspx</link><pubDate>Fri, 22 May 2009 03:10:32 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9634517</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9634517</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2009/05/21/virtual-code-execution-via-il-interpretation.aspx#comments</comments><description>&lt;p&gt;As Soma announced, &lt;a href="http://blogs.msdn.com/somasegar/archive/2009/05/18/visual-studio-2010-and-net-fx-4-beta-1-ships.aspx"&gt;we just shipped VS2010 Beta1&lt;/a&gt;. This includes &lt;a href="http://blogs.msdn.com/rmbyers/archive/2008/10/30/clr-4-0-advancements-in-diagnostics.aspx"&gt;dump debugging support for managed code&lt;/a&gt; and a very cool bonus feature tucked in there that I’ll blog about today. &lt;/p&gt; &lt;p&gt;Dump-debugging (aka post-mortem debugging) is very useful and a long-requested feature for managed code.&amp;nbsp; The downside is that with a dump-file, you don’t have a live process anymore, and so &lt;a href="http://blogs.msdn.com/jmstall/archive/tags/FuncEval/default.aspx"&gt;property-evaluation&lt;/a&gt; won’t work. That’s because property evaluation is implemented by hijacking a thread in the debuggee to run the function of interest, commonly a ToString() or property-getter. There’s no live thread to hijack in post-mortem debugging.&lt;/p&gt; &lt;p&gt;We have a mitigation for that in VS2010. In addition to loading the dump file, &lt;strong&gt;we can also interpret the IL opcodes of the function and simulate execution &lt;/strong&gt;to show the results in the debugger.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Here, I’ll just blog about the end-user experience and some top-level points. I’ll save the technical drill down for future blogs.&lt;/p&gt; &lt;p&gt;Consider the following sample:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Collections.Generic;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Linq;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Text;
&lt;span style="color: blue"&gt;using &lt;/span&gt;System.Reflection;

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Point 
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;int &lt;/span&gt;m_x;
    &lt;span style="color: blue"&gt;int &lt;/span&gt;m_y;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Point(&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: blue"&gt;int &lt;/span&gt;y)
    {
        m_x = x;
        m_y = y;
    }
    &lt;span style="color: blue"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;String&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;"({0},{1})"&lt;/span&gt;, &lt;span style="color: blue"&gt;this&lt;/span&gt;.X, &lt;span style="color: blue"&gt;this&lt;/span&gt;.Y);
    }

    &lt;span style="color: blue"&gt;public int &lt;/span&gt;X
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;m_x;
        }
    }
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Y
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;m_y;
        }
    }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; dict = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
        dict[5] = &lt;span style="color: #a31515"&gt;"Five"&lt;/span&gt;;
        dict[3] = &lt;span style="color: #a31515"&gt;"three"&lt;/span&gt;;

        &lt;span style="color: #2b91af"&gt;Point &lt;/span&gt;p = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Point&lt;/span&gt;(3, 4);
                
    }

    &lt;span style="color: blue"&gt;public static int  &lt;/span&gt;Dot(&lt;span style="color: #2b91af"&gt;Point &lt;/span&gt;p1, &lt;span style="color: #2b91af"&gt;Point &lt;/span&gt;p2)
    {
        &lt;span style="color: blue"&gt;int &lt;/span&gt;r2 = p1.X * p2.X + p1.Y * p2.Y;
        &lt;span style="color: blue"&gt;return &lt;/span&gt;r2;
    }

}

&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&amp;nbsp;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Suppose you have a dump-file from a thread stopped at the end of Main() (See newly added menu item “Debug | Save Dump As …”; load dump-file via “File | Open | File …”).&lt;/p&gt;
&lt;p&gt;Normally, you could see the locals (dict, p) and their raw fields, but you wouldn’t be able to see the properties or ToString() values. So it would look something like this:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_6.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_thumb_2.png" width="563" height="148"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;But with the interpreter, you can actually simulate execution. With the IL interpreter, here’s what it looks like in the watch window:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_thumb.png" width="409" height="181"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;Which is exactly what you’d expect with live-debugging.&amp;nbsp; (In one sense, “everything still works like it worked before” is not a gratifying demo…)&lt;/p&gt;
&lt;p&gt;The ‘*’ after the values are indications that they came from the interpreter.&amp;nbsp; Note you still need to ensure that property-evaluation is enabled in “Tools | options | Debugging”:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_8.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_thumb_3.png" width="356" height="45"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How does it work?&lt;br&gt;&lt;/strong&gt;The Interpreter gets the raw IL opcodes via ICorDebug and then simulates execution of those opcodes. For example, when you inspect “p.X” in the watch window, the debugger can get the raw IL opcodes:&lt;/p&gt;
&lt;p&gt;.method public hidebysig specialname instance int32 &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; get_X() cil managed&lt;br&gt;{&lt;br&gt;&amp;nbsp; // Code size&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 12 (0xc)&lt;br&gt;&amp;nbsp; .maxstack&amp;nbsp; 1&lt;br&gt;&amp;nbsp; .locals init ([0] int32 CS$1$0000)&lt;br&gt;&amp;nbsp; IL_0000:&amp;nbsp; nop&lt;br&gt;&amp;nbsp; IL_0001:&amp;nbsp; ldarg.0&lt;br&gt;&amp;nbsp; IL_0002:&amp;nbsp; &lt;strong&gt;ldfld&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int32 Point::m_x&lt;/strong&gt;&lt;br&gt;&amp;nbsp; IL_0007:&amp;nbsp; stloc.0&lt;br&gt;&amp;nbsp; IL_0008:&amp;nbsp; br.s&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_000a&lt;br&gt;&amp;nbsp; IL_000a:&amp;nbsp; ldloc.0&lt;br&gt;&amp;nbsp; IL_000b:&amp;nbsp; ret&lt;br&gt;} // end of method Point::get_X 
&lt;p&gt;And then translate that ldfld opcode into a ICorDebug field fetch the same way it would fetch “p.m_x”. The problem gets a lot harder then that (eg, how does it interpret a newobj instruction?) but that’s the basic idea.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other things it can interpret&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;The immediate window is also wired up to use the interpreter when dump-debugging. Here are some sample things that work. Again, note the ‘*’ means the results are in the interpreter and the debuggee is not modified.&lt;/p&gt;
&lt;p&gt;&lt;u&gt;Simulating new objects&lt;/u&gt;:&lt;br&gt;? new Point(10,12).ToString()&lt;br&gt;"(10,12)"*&lt;br&gt;&lt;br&gt;&lt;u&gt;Basic reflection&lt;/u&gt;:&lt;br&gt;? typeof(Point).FullName&lt;br&gt;"Point"*&lt;br&gt;&lt;br&gt;&lt;u&gt;Dynamic method invocation&lt;/u&gt;:&lt;br&gt;? typeof(Point).GetMethod("get_X").Invoke(new Point(6,7), null)&lt;br&gt;0x00000006*&lt;/p&gt;
&lt;p&gt;&lt;u&gt;Calling functions, and even mixing debuggee data (the local variable ‘p’) with interpreter generated data (via the ‘new’ expression)&lt;/u&gt;:&lt;br&gt;? Dot(p,new Point(10,20))&lt;br&gt;110*&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It even works for Visualizers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Notice that it can even load the Visualizer for the Dictionary (dict) and show you the contents as a pretty array view rather than just the raw view of buckets. Visualizers are their own dll,&amp;nbsp; and we can verify that the dll is not actually loaded into the debuggee. For example, the Dictionary visualizer dll is&amp;nbsp; Microsoft.VisualStudio.DebuggerVisualizers.dll, but that’s not in the module list:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_4.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jmstall/WindowsLiveWriter/SafecodeexecutionviaanILinterpreter_99B5/image_thumb_1.png" width="351" height="217"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;That’s because the interpreter has virtualized loading the visualizer dll into its own “virtual interpreter” space and not the actual debuggee process space. That’s important because in a dump file, you can’t load a visualizer dll post-mortem.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other issues&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;There are lots of other details here that I’m skipping over, like: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The interpreter is definitely not bullet proof. If it sees something it can’t interpreter (like a pinvoke or dangerous code), then it simply aborts the interpretation attempt.&lt;/li&gt;
&lt;li&gt;The intepreter is recursive, so it can handle functions that call other functions. (Notice that ToString call get_X.)&lt;/li&gt;
&lt;li&gt;How does it deal with side-effecting operations? &lt;/li&gt;
&lt;li&gt;How does it handle virtual dispatch call opcodes?&lt;/li&gt;
&lt;li&gt;How does it handle ecalls?&lt;/li&gt;
&lt;li&gt;How does it handle reflection&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other advantages&lt;/strong&gt;?&lt;/p&gt;
&lt;p&gt;There are other advantages of IL interpretation for function evaluation, mainly that it addresses the ”&lt;a href="http://blogs.msdn.com/jmstall/archive/2005/03/23/400794.aspx"&gt;func-eval is evil&lt;/a&gt;” problems by essentially degenerating dangerous func-evals to safe field accesses.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It is provably safe because it errs on the side of safety. The interpreter is completely non-invasive (it operates on a dump-file!).&lt;/li&gt;
&lt;li&gt;No accidentally executing dangerous code. &lt;/li&gt;
&lt;li&gt;Side-effect free func-evals. This is a natural consequence of it being non-invasive.&lt;/li&gt;
&lt;li&gt;Bullet proof func-eval abort. &lt;/li&gt;
&lt;li&gt;Bullet proof protection against recursive properties that stack-overflow.&lt;/li&gt;
&lt;li&gt;It allows func-eval to occur at places &lt;a href="http://blogs.msdn.com/jmstall/archive/2005/11/15/funceval-rules.aspx"&gt;previously impossible&lt;/a&gt;, such as in dump-files, when the thread is in native code, retail code, or places where there is no thread to hijack.&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Closing thoughts&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We realize that the interpreter is definitely not perfect. That’s part of why we choose to have it active in dump-files but not replace func-eval in regular execution. For dump-file scenarios, it took something that would have been completely broken and made many things work.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9634517" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/ICorDebug/">ICorDebug</category><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/FuncEval/">FuncEval</category></item><item><title>MVP Summit 2009</title><link>http://blogs.msdn.com/b/jmstall/archive/2009/02/27/mvp-summit-2009.aspx</link><pubDate>Fri, 27 Feb 2009 22:45:56 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9449473</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9449473</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2009/02/27/mvp-summit-2009.aspx#comments</comments><description>&lt;p&gt;For those going to the &lt;a href="http://www.mvpsummit2009.com/public/technicaleducation.aspx "&gt;2009 MVP Summit&lt;/a&gt;, I’ll be one of the speakers at the breakout sessions on March 2nd on Microsoft’s Main campus.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9449473" width="1" height="1"&gt;</description></item><item><title>Managed Dump debugging support for Visual Studio and ICorDebug</title><link>http://blogs.msdn.com/b/jmstall/archive/2008/11/01/managed-dump-debugging-support-for-visual-studio-and-icordebug.aspx</link><pubDate>Sat, 01 Nov 2008 19:51:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9028315</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=9028315</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2008/11/01/managed-dump-debugging-support-for-visual-studio-and-icordebug.aspx#comments</comments><description>&lt;p&gt;This is the longest I've gone without blogging, but our &lt;a href="http://www.microsoftpdc.com/"&gt;PDC&lt;/a&gt; announcements have stuff way too cool to stay quiet about. &lt;/p&gt; &lt;p&gt;If you saw &lt;a href="http://www.microsoftpdc.com/"&gt;PDC&lt;/a&gt;, you've head that the CLR Debugging API, &lt;strong&gt;ICorDebug, will support dump-debugging&lt;/strong&gt;. This enables any ICorDebug-based debugger (including Visual Studio and MDbg) to debug dump-files of .NET applications. The coolness goes well beyond that, but dump-debugging is just the easiest feature to describe. &lt;/p&gt; &lt;p&gt;This was not an overnight feature, and required some major architectural changes to be plumbed through the entire system.&amp;nbsp; Specifically, when dump-debugging, there's no 'live' debuggee, so you can't rely on a &lt;a href="http://blogs.msdn.com/jmstall/archive/2004/10/13/241828.aspx"&gt;helper-thread&lt;/a&gt; running in the debuggee process to service debugging requests anymore, so you need a completely different model. &lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/rmbyers/"&gt;Rick Byers&lt;/a&gt; has an excellent description of the &lt;a href="http://blogs.msdn.com/rmbyers/archive/2008/10/27/icordebug-re-architecture-in-clr-4-0.aspx"&gt;ICorDebug re-architecture in CLR 4.0&lt;/a&gt;.&amp;nbsp; He also describes some of the &lt;a href="http://blogs.msdn.com/rmbyers/archive/2008/10/30/clr-4-0-advancements-in-diagnostics.aspx"&gt;other advancements in the CLR Tools API space&lt;/a&gt;. Go read them.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9028315" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/ICorDebug/">ICorDebug</category></item><item><title>Updated MSDN forums</title><link>http://blogs.msdn.com/b/jmstall/archive/2008/06/10/updated-msdn-forums.aspx</link><pubDate>Tue, 10 Jun 2008 07:41:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8588669</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=8588669</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2008/06/10/updated-msdn-forums.aspx#comments</comments><description>&lt;p&gt;The MSDN forums are updated and have a new look and feel. It's at a new link too:&amp;nbsp; &lt;a title="http://forums.msdn.microsoft.com/en-US/netfxtoolsdev/threads/" href="http://forums.msdn.microsoft.com/en-US/netfxtoolsdev/threads/"&gt;http://forums.msdn.microsoft.com/en-US/netfxtoolsdev/threads/&lt;/a&gt;&amp;nbsp; (the old link still forwards).&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8588669" width="1" height="1"&gt;</description></item><item><title>Stuff in Reflection that's not in Metadata</title><link>http://blogs.msdn.com/b/jmstall/archive/2008/05/23/stuff-in-reflection-that-s-not-in-metadata.aspx</link><pubDate>Fri, 23 May 2008 08:01:33 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8536681</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=8536681</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2008/05/23/stuff-in-reflection-that-s-not-in-metadata.aspx#comments</comments><description>&lt;p&gt;Previously, I mentioned some things in &lt;a href="http://blogs.msdn.com/jmstall/archive/2008/03/15/things-in-metadata-that-are-missing-in-reflection.aspx"&gt;Metadata that aren't exposed in Reflection&lt;/a&gt;.&amp;nbsp; Here's an opposite case. &lt;/p&gt; &lt;p&gt;While metadata represents static bits on disk, Reflection operates in a live process with access to the CLR's loader. So reflection can represent things the CLR loader and type system may do that aren't captured in the metadata.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;For example, an array T[] may implement interfaces, but which set of interfaces is not captured in the metadata. So consider the following code that prints out the interfaces an int[] implements:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;using&lt;/span&gt; System;

&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Foo
&lt;/span&gt;{
    &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main()
    {
        &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Hi"&lt;/span&gt;);
        &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(43,145,175)"&gt;Environment&lt;/span&gt;.Version);
        &lt;span style="color: rgb(43,145,175)"&gt;Type&lt;/span&gt;[] t2 = &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;[]).GetInterfaces();
        &lt;span style="color: rgb(0,0,255)"&gt;foreach&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;Type&lt;/span&gt; t &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; t2)
        {
            &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(t.FullName);
        }
        &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"done"&lt;/span&gt;);
    }
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Compile it once for v1.0. Then run the same binary against v1 and v2.&amp;nbsp; It's the same file (and therefore same metadata) in both cases. &lt;br&gt;The V1 case is inconsistent because it doesn't show any interfaces, it should at least show a few builtins like IEnumerable (typeof(IEnumerable).IsAssignableFrom(typeof(int[])) == True). But in the v2 case, you see reflection showing the interfaces, particularly the new 2.0 generic interfaces, that the CLR's type system added to the the array. So the V2 list is not the same as the V1 list, but this difference is not captured in the metadata. &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;table border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;pre&gt;&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\temp&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe t.cs&lt;/span&gt;&lt;/i&gt;
Microsoft (R) Visual C# .NET Compiler version 7.10.6001.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.


&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\temp&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;t.exe&lt;/span&gt;&lt;/i&gt;
Hi
1.1.4322.2407
done

&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\temp&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;set COMPLUS_VERSION=v2.0.50727&lt;/span&gt;&lt;/i&gt;

&lt;b&gt;&lt;span style="color: rgb(0,0,160)"&gt;C:\temp&amp;gt;&lt;/span&gt;&lt;/b&gt;&lt;i&gt;&lt;span style="color: rgb(164,0,0)"&gt;t.exe&lt;/span&gt;&lt;/i&gt;
Hi
2.0.50727.1433
System.ICloneable
System.Collections.IList
System.Collections.ICollection
System.Collections.IEnumerable
System.Collections.Generic.IList`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Collections.Generic.ICollection`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
done

&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8536681" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jmstall/archive/tags/Compilers+_2600_amp_3B00_+Languages/">Compilers &amp;amp; Languages</category></item><item><title>Nice MSDN URLs</title><link>http://blogs.msdn.com/b/jmstall/archive/2008/05/19/nice-msdn-urls.aspx</link><pubDate>Mon, 19 May 2008 23:46:34 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8519674</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=8519674</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2008/05/19/nice-msdn-urls.aspx#comments</comments><description>&lt;p&gt;I noticed that MSDN finally has nice URLs for the BCL. (Or perhaps that should be "I finally noticed that ...", depending on how long this has been)&lt;/p&gt; &lt;p&gt;So instead of:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/1009fa28.aspx"&gt;http://msdn.microsoft.com/en-us/library/1009fa28.aspx&lt;/a&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;You can do:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx"&gt;http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx&lt;/a&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;For overloaded methods, it takes you to the disambiguation page. &lt;/p&gt; &lt;p&gt;This actually makes it a lot easier to find BCL APIs when you know the name. Now most of the time, I can just type the name right into the URL. And I have a higher confidence that this link won't get broken. &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8519674" width="1" height="1"&gt;</description></item><item><title>The price of complexity</title><link>http://blogs.msdn.com/b/jmstall/archive/2008/04/23/the-price-of-complexity.aspx</link><pubDate>Wed, 23 Apr 2008 08:03:37 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8418126</guid><dc:creator>Mike Stall - MSFT</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jmstall/rsscomments.aspx?WeblogPostID=8418126</wfw:commentRss><comments>http://blogs.msdn.com/b/jmstall/archive/2008/04/23/the-price-of-complexity.aspx#comments</comments><description>&lt;p&gt;My house was haunted. One of the lights would randomly go on or off and random times without anybody fiddling the switch. &lt;/p&gt; &lt;p&gt;The previous owner of our house had installed fancy dimmer light switches. On a whim, we replaced one of the fancy switches with a simple on/off switch.&amp;nbsp; As we took the old fancy switch out, we noticed that it had capacitors, a circuit board, resistors, even a microchip! That's a lot of different things to break down. &lt;/p&gt; &lt;p&gt;The new simple switch worked great, and the associated light no longer randomly toggles. So I conclude the fancy light switch was the problem. &lt;/p&gt; &lt;p&gt;Furthermore, the dimmer switches were more complicated to use because they had some fancy pressure touch thing: a quick fast press would toggle the light; a soft press would dim the light. It took us a while to get used to them. &lt;/p&gt; &lt;p&gt;When I was at Home Depot, the fancy switches were $40; whereas the simple on/off switches were ~$3.&amp;nbsp; The old simple switches throughout our house are still working; and we never really needed the dimming features for the fancy switches. &lt;/p&gt; &lt;p&gt;&lt;em&gt;So the fancy switches were more expensive, harder to use, and haunted&lt;/em&gt;. Overall, not an ideal tradeoff for our needs. We'll stick with the simple on/off switches.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;em&gt;I think the same things applies to software design&lt;/em&gt;. You can build complicated software with lots of features, but that also means more places where it could break down. If a simple solution does the trick, it may not only be cheaper to build, but easier to use and cheaper to maintain in the long run.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8418126" width="1" height="1"&gt;</description></item></channel></rss>