<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PeterKellner.net &#187; Reflection</title>
	<atom:link href="http://peterkellner.net/category/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://peterkellner.net</link>
	<description>Microsoft Focussed, JavaScript (ExtJS, SenchaTouch &#38; Windows 8 Metro)</description>
	<lastBuildDate>Tue, 07 Feb 2012 21:14:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Returning JsonResult From ASP.NET MVC 2.0 Controller and Unit Testing</title>
		<link>http://peterkellner.net/2010/05/14/unit-test-jsonresult-aspnet-mvc-reflection/</link>
		<comments>http://peterkellner.net/2010/05/14/unit-test-jsonresult-aspnet-mvc-reflection/#comments</comments>
		<pubDate>Sat, 15 May 2010 04:19:31 +0000</pubDate>
		<dc:creator>Peter Kellner</dc:creator>
				<category><![CDATA[ASP.NET 3.5]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://peterkellner.net/2010/05/14/unit-test-jsonresult-aspnet-mvc-reflection/</guid>
		<description><![CDATA[   * I’m adding this comment after the post has been written to let anyone coming here know of another great post that goes further to explain no only what I’ve done here, but also two other ways including Mock and using Json Serialization.&#160; The Post is written by Ashic Mahtab, aka “HeartattacK” [...]]]></description>
			<content:encoded><![CDATA[<blockquote>   <p>* I’m adding this comment after the post has been written to let anyone coming here know of another great post that goes further to explain no only what I’ve done here, but also two other ways including Mock and using Json Serialization.&#160; The Post is written by <a href="http://www.heartysoft.com/page/about.aspx">Ashic Mahtab</a>, aka “<a href="http://forums.asp.net/members/HeartattacK.aspx">HeartattacK</a>” on the forums.&#160; His well written and informative article is here:&#160; <a href="http://www.heartysoft.com/post/2010/05/25/ASPNET-MVC-Unit-Testing-JsonResult-Returning-Anonymous-Types.aspx">ASP.NET MVC – Unit Testing JsonResult Returning Anonymous Types</a>.</p> </blockquote>  <p>This post will show how to return a simple Json result from an <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=c9ba1fe1-3ba8-439a-9e21-def90a8615a9&amp;displaylang=en">ASP.NET MVC 2.0</a> web project.&#160; It will show how to test that result inside a unit test and essentially pick apart the Json, just like a JavaScript (or other client) would do.&#160; It seems like it should be very simple (and indeed, once you see the answer it is), however there are lots of length discussions on the forums about this with all kinds of positives and negatives.&#160; The one I based my solution on is from Stack Overflow and is <a href="http://stackoverflow.com/questions/482363/should-my-mvc-controller-really-know-about-json">here</a>..&#160; My personal length discussion that did not really yield a satisfactory answer is <a href="http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/552b6dda-5e98-4012-8df2-70a845aab680/">here</a>.</p>  <p>If you follow my method, you’ll be able to unit test a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult.aspx">JsonResult</a> created by an <a href="http://www.asp.net/(S(d35rmemuuono1wvm1gsp2n45))/mvc">MVC asp.net web application</a>. </p> <span id="more-1316"></span>  <h2>Controller Side (Server)</h2>  <p>Let’s get started. First thing we need to do is have a controller that return a JsonResult.&#160; Below is the one I’m currently working on.&#160; Let me show the code, then explain it.</p>  <p>&#160;</p>  <div id="codeSnippetWrapper">   <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> ActionResult Get(FormCollection form)<br />       {<br />           var query = <span style="color: #0000ff">new</span> FolderPairQuery();<br />           <span style="color: #0000ff">if</span> (form[<span style="color: #006080">&quot;query&quot;</span>] != <span style="color: #0000ff">null</span>)<br />           {<br />               query = form[<span style="color: #006080">&quot;query&quot;</span>].FromJson&lt;FolderPairQuery&gt;();<br />           }<br /><br />           <span style="color: #0000ff">if</span> (form[<span style="color: #006080">&quot;start&quot;</span>] != <span style="color: #0000ff">null</span> &amp;&amp; form[<span style="color: #006080">&quot;limit&quot;</span>] != <span style="color: #0000ff">null</span>)<br />           {<br />               query.Start = Convert.ToInt32(form[<span style="color: #006080">&quot;start&quot;</span>]);<br />               query.Limit = Convert.ToInt32(form[<span style="color: #006080">&quot;limit&quot;</span>]);<br />           }<br /><br />           var results = FolderPairManager.I.Get(query);<br />           <span style="color: #0000ff">return</span> Json(<span style="color: #0000ff">new</span><br />                           {<br />                               success = <span style="color: #0000ff">true</span>,<br />                               rows = results,<br />                               total = query.OutputTotal<br />                           }, JsonRequestBehavior.AllowGet);<br />       }</pre>
</div>

<div>&#160;</div>

<p>This code is actually part of the file FolderPairController.cs.&#160; It returns an ActionResult (which in this case is JsonResult that derives from ActionResult).&#160; All the way to the return statement is just stuff that I do in my code to pull apart the passed in Request variables and process them.&#160; I only leave them in for context.&#160; It does not matter how you get your “results” and “total”, it just matters that you do. Then, the return statement is the part that is of interest.&#160; It’s basically returning an anonymous class which is actually a JsonResult.&#160; In System.Web.Mvc.Controller.cs, you will see that Json is defined as:</p>

<p>&#160;</p>

<div>
  <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">protected</span> <span style="color: #0000ff">internal</span> JsonResult Json(<span style="color: #0000ff">object</span> data, JsonRequestBehavior behavior);</pre>
</div>

<div>&#160;</div>

<div>&#160;</div>

<div>The first parameter is “object data” which means it can be anything, and in our case, it is an anonymous object.</div>

<div>&#160;</div>

<h2>Unit Test Side (Client)</h2>

<div>&#160;</div>

<div>So now, let’s take a look at the unit test itself.&#160; Again, let me show the code, then explain it.</div>

<div>&#160;</div>

<div id="codeSnippetWrapper">
  <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">[TestMethod]<br /><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> InsertControllerTest()<br />{<br />    var pairName = <span style="color: #0000ff">string</span>.Format(<span style="color: #006080">&quot;FolderPair {0}&quot;</span>, <br />        (<span style="color: #0000ff">new</span> Random().Next(1, 10000)));<br />    var folderPairResults =<br />        <span style="color: #0000ff">new</span> List&lt;FolderPairResult&gt;()<br />            {<br />                <span style="color: #0000ff">new</span> FolderPairResult<br />                    {<br />                        ActionTypeId = 1,<br />                        CheckFileContent = <span style="color: #0000ff">true</span>,<br />                        ActiveForRunAll = <span style="color: #0000ff">true</span>,<br />                        ExcludeHiddenFiles = <span style="color: #0000ff">true</span>,<br />                        ExcludeReadOnly = <span style="color: #0000ff">true</span>,<br />                        ExcludeSystemFiles = <span style="color: #0000ff">true</span>,<br />                        FolderPairName = pairName,<br />                        LeftFolder = <span style="color: #006080">&quot;left&quot;</span>,<br />                        RightFolder = <span style="color: #006080">&quot;right&quot;</span>,<br />                        SaveOverWrittenRecycleBin = <span style="color: #0000ff">true</span>,<br />                        UsersId = 1<br />                    }<br />            };<br /><br /><br /><br />    <span style="color: #0000ff">string</span> jsonInsert = JsonConvert.SerializeObject(folderPairResults);<br /><br />    var form =<br />        <span style="color: #0000ff">new</span> FormCollection<br />            {<br />                {<span style="color: #006080">&quot;data&quot;</span>, jsonInsert}<br />            };<br /><br /><br />    <span style="color: #0000ff">using</span> (var controller = <span style="color: #0000ff">new</span> FolderPairController())<br />    {<br /><br />        controller.Insert(form);<br />    }<br /><br />    <span style="color: #008000">// verify it got inserted.</span><br />    var queryObj = <span style="color: #0000ff">new</span> FolderPairQuery { FolderPairName = pairName };<br />    <span style="color: #0000ff">string</span> json = JsonConvert.SerializeObject(queryObj);<br />    var formGet =<br />        <span style="color: #0000ff">new</span> FormCollection()<br />            {<br />                {<span style="color: #006080">&quot;query&quot;</span>, json}<br />            };<br /><br />    <span style="color: #0000ff">using</span> (var controller = <span style="color: #0000ff">new</span> FolderPairController())<br />    {<br />        var jsonResult1 = controller.Get(formGet) <span style="color: #0000ff">as</span> JsonResult;<br />        Assert.IsNotNull(jsonResult1,<span style="color: #006080">&quot;jsonResult1 is null which is bad&quot;</span>);<br />       <br />       <br />            List&lt;FolderPairResult&gt; folderPairResults1 =<br />                (List&lt;FolderPairResult&gt;)<br />                (jsonResult1.Data.GetType().GetProperty(<span style="color: #006080">&quot;rows&quot;</span>)).GetValue(jsonResult1.Data, <span style="color: #0000ff">null</span>);<br />            <span style="color: #0000ff">bool</span> success =<br />                (<span style="color: #0000ff">bool</span>)<br />                (jsonResult1.Data.GetType().GetProperty(<span style="color: #006080">&quot;success&quot;</span>)).GetValue(jsonResult1.Data, <span style="color: #0000ff">null</span>);<br />            <span style="color: #0000ff">int</span> total =<br />                (<span style="color: #0000ff">int</span>)<br />                (jsonResult1.Data.GetType().GetProperty(<span style="color: #006080">&quot;total&quot;</span>)).GetValue(jsonResult1.Data, <span style="color: #0000ff">null</span>);<br /><br />            Assert.IsTrue(folderPairResults1.Count == 1, <span style="color: #006080">&quot;Not one item returned&quot;</span>);<br />            Assert.IsTrue(folderPairResults1[0].FolderPairName.Equals(pairName),<br />                <span style="color: #006080">&quot;Wrong pairname returned&quot;</span>);<br />    }<br />}</pre>

  <br /></div>

<div>Up to the line “// verify it got inserted”, we simply are adding the record to the database in our unit test.&#160; I won’t go into detail about that in this post since it is not really the purpose here.&#160; I’m really just trying to show how to extract from the JsonResult the values that are returned from the server.</div>

<div>&#160;</div>

<div>So, notice the line “var jsonResult1 = controller.Get(formGet) as JsonResult;”.&#160; This line simply calls the controller’s get method with the appropriate query parameters and returns us a JsonResult.&#160; Now, let’s look at how to get the data out of that.&#160; It’s really quite simple using reflection.&#160; Each of the following three lines pulls the data out so that at the end, we have our typed data for rows,total and count.</div>

<div>&#160;</div>

<div>Hopefully, this will help you.&#160; Like I said in the beginning, there are lots of ways to do this.&#160; This just shows one that works for me.</div>

<div>&#160;</div>

<div>
  <br /></div>]]></content:encoded>
			<wfw:commentRss>http://peterkellner.net/2010/05/14/unit-test-jsonresult-aspnet-mvc-reflection/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using Reflection in C# to Figure Out if an Integer List Has Values</title>
		<link>http://peterkellner.net/2009/06/01/csharp-reflection-integer-list-generic/</link>
		<comments>http://peterkellner.net/2009/06/01/csharp-reflection-integer-list-generic/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 19:04:31 +0000</pubDate>
		<dc:creator>Peter Kellner</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://peterkellner.net/2009/06/01/csharp-reflection-integer-list-generic/</guid>
		<description><![CDATA[ So, I’ve struggled some with this and did not have much help with searching.   Here is the problem.  You have a declaration that looks like this:             1: public partial class CompanyQuery   {

      [...]]]></description>
			<content:encoded><![CDATA[<p> So, I’ve struggled some with this and did not have much help with searching. </p>  <p>Here is the problem.</p>  <p>You have a declaration that looks like this:</p>  <div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">   <div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">     <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> public partial class CompanyQuery   {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span>       public List<span style="color: #0000ff">&lt;</span><span style="color: #800000">int</span><span style="color: #0000ff">&gt;</span> CompanyTypeIds { get; set; }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span> }</pre>
  </div>
</div>

<p>Then, you need to figure out if CompanyTypeIds is populated using reflection.</p>
<span id="more-314"></span>

<p>Here is the code:</p>

<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
  <div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">
    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> CompanyQuery query = new CompanyQuery;</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span> query.CompanyTypeIds = new List<span style="color: #0000ff">&lt;</span><span style="color: #800000">int</span><span style="color: #0000ff">&gt;</span> {1,2,3,4}</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>&#160; </pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span> foreach (var info in typeof(CompanyQuery).GetProperties())</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>            {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>                 object[] attributes = info.GetCustomAttributes(typeof(ForceNoCompileColumnAttribute), true);</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>                 if (attributes.Length <span style="color: #0000ff">&gt;</span> 0)</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>                 {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>                     object value = info.GetValue(query, null);</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span>                     if (value != null &amp;&amp; value.GetType() == (new List<span style="color: #0000ff">&lt;</span><span style="color: #800000">int</span><span style="color: #0000ff">&gt;</span>()).GetType())</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  11:</span>                     {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  12:</span>                         if (((List<span style="color: #0000ff">&lt;</span><span style="color: #800000">int</span><span style="color: #0000ff">&gt;</span>)value).Count <span style="color: #0000ff">&gt;</span> 0)</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  13:</span>                         {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  14:</span>                             forceNoCompile = true;</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  15:</span>                         }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  16:</span>                     }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  17:</span>                     else if (value != null)</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  18:</span>                     {</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  19:</span>                         forceNoCompile = true;</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  20:</span>                     }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  21:</span>                 }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  22:</span>            }</pre>

    <pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060">  23:</span>&#160; </pre>
  </div>
</div>

<p>That’s basically it.</p>

<p>Hope this helps.</p>]]></content:encoded>
			<wfw:commentRss>http://peterkellner.net/2009/06/01/csharp-reflection-integer-list-generic/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Method.Invoke to avoid a lengthy Case Statement in C# (Using Reflection)</title>
		<link>http://peterkellner.net/2009/04/09/reflection-method-parameters-casestatement-dotnet/</link>
		<comments>http://peterkellner.net/2009/04/09/reflection-method-parameters-casestatement-dotnet/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 22:02:56 +0000</pubDate>
		<dc:creator>Peter Kellner</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://peterkellner.net/2009/04/09/reflection-method-parameters-casestatement-dotnet/</guid>
		<description><![CDATA[ So, I asked the following question in at http://forums.asp.net/t/1408631.aspx    The problem is, I’ve got 30 methods that all have the same signature, but have different implementations.&#160; Mike Banavige (the lead moderator at the forums) suggested I look at the following article on reflection:&#160; http://www.csharphelp.com/archives/archive200.html.&#160; Turns out, that helped my solve my [...]]]></description>
			<content:encoded><![CDATA[<p> So, I asked the following question in at <a title="http://forums.asp.net/t/1408631.aspx" href="http://forums.asp.net/t/1408631.aspx">http://forums.asp.net/t/1408631.aspx</a></p>  <p><a href="http://peterkellner.net/FilesForWebDownload/Usi.InvoketoavoidalengthyCaseStatementin_FDB3/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://peterkellner.net/FilesForWebDownload/Usi.InvoketoavoidalengthyCaseStatementin_FDB3/image_thumb.png" width="693" height="274" /></a></p>  <p>The problem is, I’ve got 30 methods that all have the same signature, but have different implementations.&#160; Mike Banavige (the lead moderator at the forums) suggested I look at the following article on reflection:&#160; <a href="http://www.csharphelp.com/archives/archive200.html">http://www.csharphelp.com/archives/archive200.html</a>.&#160; Turns out, that helped my solve my problem exactly.&#160; Rather than go through a lengthy line by line explanation, I’m going to post some of my before and after code.&#160; It’s pretty clear what is happening, but I thought it would be nice to show a real example.</p> <span id="more-287"></span>  <p>Before Code:</p>  <div class="csharpcode">   <pre class="alt"> <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> AddTemplateCode(<span class="kwrd">string</span> templateNumber, <span class="kwrd">int</span> indent, ICollection&lt;<span class="kwrd">string</span>&gt; newLines,FullMeta fullMetal)</pre>

  <pre>        {</pre>

  <pre class="alt">            <span class="kwrd">int</span> iTemplateNumber = Convert.ToInt32(templateNumber);</pre>

  <pre>            var sb = <span class="kwrd">new</span> StringBuilder(indent);</pre>

  <pre class="alt">            sb.Append(<span class="str">' '</span>, indent);</pre>

  <pre>            <span class="kwrd">string</span> indentString = sb.ToString();</pre>

  <pre class="alt">&#160;</pre>

  <pre>&#160;</pre>

  <pre class="alt">             <span class="rem">// be nice to get rid of this ugly case statement.  Using it because I want to have a way to separate</span></pre>

  <pre>             <span class="rem">// methods associated with groups of methods.  that is, put Template11-15 in a separate file later.</span></pre>

  <pre class="alt">            <span class="kwrd">switch</span> (iTemplateNumber)</pre>

  <pre>            {</pre>

  <pre class="alt">                <span class="kwrd">case</span> 11:</pre>

  <pre>                    {</pre>

  <pre class="alt">                        Template11(newLines, indentString,fullMetal);</pre>

  <pre>                        <span class="kwrd">break</span>;</pre>

  <pre class="alt">                    }</pre>

  <pre>                <span class="kwrd">case</span> 12:</pre>

  <pre class="alt">                    {</pre>

  <pre>                        Template12(newLines, indentString,fullMetal);</pre>

  <pre class="alt">                        <span class="kwrd">break</span>;</pre>

  <pre>                    }</pre>

  <pre class="alt">                <span class="kwrd">case</span> 13:</pre>

  <pre>                    {</pre>

  <pre class="alt">                        Template13(newLines, indentString, fullMetal);</pre>

  <pre>                        <span class="kwrd">break</span>;</pre>

  <pre class="alt">                    }</pre>

  <pre>                <span class="kwrd">case</span> 14:</pre>

  <pre class="alt">&lt;This goes on and on and on and on&gt;</pre>
</div>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>Then, After, following the sample above:</p>

<div class="csharpcode">
  <pre class="alt"> <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> AddTemplateCode(<span class="kwrd">string</span> templateNumber, <span class="kwrd">int</span> indent, ICollection&lt;<span class="kwrd">string</span>&gt; newLines,FullMeta fullMetal)</pre>

  <pre>        {</pre>

  <pre class="alt">             </pre>

  <pre>            <span class="kwrd">int</span> iTemplateNumber = Convert.ToInt32(templateNumber);</pre>

  <pre class="alt">            var sb = <span class="kwrd">new</span> StringBuilder(indent);</pre>

  <pre>            sb.Append(<span class="str">' '</span>, indent);</pre>

  <pre class="alt">            <span class="kwrd">string</span> indentString = sb.ToString();</pre>

  <pre>&#160;</pre>

  <pre class="alt">&#160;</pre>

  <pre>&#160;</pre>

  <pre class="alt">            var processTemplate = <span class="kwrd">new</span> ProcessTemplateDynamic();</pre>

  <pre>            processTemplate.DoIt(iTemplateNumber, newLines, indentString, fullMetal);</pre>

  <pre class="alt">&#160;</pre>

  <pre>&lt;Then the <span class="kwrd">class</span> with DoIt <span class="kwrd">in</span> it...&gt;</pre>

  <pre class="alt">&#160;</pre>

  <pre><span class="kwrd">using</span> System;</pre>

  <pre class="alt"><span class="kwrd">using</span> System.Collections.Generic;</pre>

  <pre><span class="kwrd">using</span> System.Reflection;</pre>

  <pre class="alt">&#160;</pre>

  <pre><span class="kwrd">namespace</span> ThreePLogicAccessCodeGen.Code</pre>

  <pre class="alt">{</pre>

  <pre>    <span class="kwrd">public</span> <span class="kwrd">class</span> ProcessTemplateDynamic</pre>

  <pre class="alt">    {</pre>

  <pre>        <span class="kwrd">internal</span> <span class="kwrd">void</span> DoIt(<span class="kwrd">int</span> iTemplateNumber, ICollection&lt;<span class="kwrd">string</span>&gt; newLines, <span class="kwrd">string</span> indentString, FullMeta fullMetal)</pre>

  <pre class="alt">        {</pre>

  <pre>            <span class="rem">// Template11(newLines, indentString, fullMetal);</span></pre>

  <pre class="alt">            <span class="kwrd">string</span> templateMethodName = String.Format(<span class="str">&quot;Template{0}&quot;</span>, iTemplateNumber);</pre>

  <pre>            var userParameters = <span class="kwrd">new</span> <span class="kwrd">object</span>[3];</pre>

  <pre class="alt">            userParameters[0] = newLines;</pre>

  <pre>            userParameters[1] = indentString;</pre>

  <pre class="alt">            userParameters[2] = fullMetal;</pre>

  <pre>&#160;</pre>

  <pre class="alt">            <span class="kwrd">try</span></pre>

  <pre>            {</pre>

  <pre class="alt">                Type thisType = GetType();</pre>

  <pre>                MethodInfo theMethod = thisType.GetMethod(templateMethodName);</pre>

  <pre class="alt">&#160;</pre>

  <pre>                <span class="rem">// that we have in this class that we don't want called.</span></pre>

  <pre class="alt">                <span class="kwrd">if</span> (theMethod == <span class="kwrd">null</span> || (!CheckMethod(theMethod)))</pre>

  <pre>                {</pre>

  <pre class="alt">                    <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="kwrd">string</span>.Format(<span class="str">&quot;[e] Command &lt;{0}&gt; not supported.&quot;</span>, templateMethodName));</pre>

  <pre>                }</pre>

  <pre class="alt">                <span class="rem">// Invoke the Method!</span></pre>

  <pre>                theMethod.Invoke(<span class="kwrd">this</span>, userParameters);</pre>

  <pre class="alt">            }</pre>

  <pre>            <span class="kwrd">catch</span> (ArgumentNullException e)</pre>

  <pre class="alt">            {</pre>

  <pre>                <span class="rem">// This exception is from the user entering in a null string on the command line</span></pre>

  <pre class="alt">                <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="str">&quot;[e] Please enter in a non-null string. (&quot;</span> + e.Message + <span class="str">&quot;)&quot;</span>);</pre>

  <pre>            }</pre>

  <pre class="alt">            <span class="kwrd">catch</span> (TargetParameterCountException e)</pre>

  <pre>            {</pre>

  <pre class="alt">                <span class="rem">// This exception is thrown when the method is not passed the right number of parameters</span></pre>

  <pre>                <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="kwrd">string</span>.Format(<span class="str">&quot;[e] Command &lt;{0}&gt; requires parameters. ({1})&quot;</span>,</pre>

  <pre class="alt">                                                             templateMethodName, e.Message));</pre>

  <pre>            }</pre>

  <pre class="alt">            <span class="kwrd">catch</span> (Exception e)</pre>

  <pre>            {</pre>

  <pre class="alt">                <span class="rem">// All other exceptions!</span></pre>

  <pre>                <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="kwrd">string</span>.Format(<span class="str">&quot;[e] General Exception:\n{0}&quot;</span>, e));</pre>

  <pre class="alt">            }</pre>

  <pre>        }</pre>

  <pre class="alt">&#160;</pre>
</div>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>Well, looking at it, seems maybe the Case statement is better, but the nice thing now is that each time I add a new template, I don’t have to make another case statement.&#160; That combined with it’s easier to make typos when you have a case statement so I’m sticking with my new solution here.</p>

<p>Hope this Helps!</p>]]></content:encoded>
			<wfw:commentRss>http://peterkellner.net/2009/04/09/reflection-method-parameters-casestatement-dotnet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced)
Database Caching 2/11 queries in 0.057 seconds using disk

Served from: peterkellner.net @ 2012-02-10 04:20:52 -->
