﻿<?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>Programming By A Tool &#187; Utilities</title>
	<atom:link href="http://byatool.com/category/utilities/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>This is my recorded stumbling through ASP.Net, Framework 3.5, C# 3.0, Ajax, Javascript, and Love.  Stay, learn, destroy.  It's your life.</description>
	<lastBuildDate>Thu, 03 May 2012 17:28:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>ASP.Net MVC: Button Post Is Losing QueryString Values And Getting Paramters From A URL</title>
		<link>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/</link>
		<comments>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 14:43:18 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[QueryString]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=838</guid>
		<description><![CDATA[I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they&#8217;d have to admit [...]]]></description>
			<content:encoded><![CDATA[<p>I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they&#8217;d have to admit they actually came up with that f-ing slogan in the first place. It&#8217;s a win/win situation for me.</p>
<p>So one of the things I&#8217;ve run into with MVC is this situation&#8230; Say I have a form and a button, and the form has an action that looks like this:</p>
<pre>  &lt;<span style="color: #800000;">form</span> <span style="color: #ff0000;">action</span><span style="color: #0000ff;">="/Tools/AddTool/1?redirect=/Tools/ViewTool/1"</span> <span style="color: #ff0000;">method</span><span style="color: #0000ff;">="post"</span>&gt;
    &lt; <span style="color: #ff0000;">button</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="submit"</span>&gt;GO!&lt;/<span style="color: #800000;">button</span>&gt;
  &lt;/<span style="color: #800000;">form</span>&gt;</pre>
<p>Really simple. The idea is that I want to post to the AddTool action, do some stuff, then have the action redirect back to the ViewTool action. Seems like it should be easy right? Well not so much. Because when you view the ActionParameters (<a href="http://byatool.com/index.php/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/">Like in this example</a>) for the &#8220;redirect&#8221; key, it finds the key but loses the value. This may result in a failure if have an attribute making sure it exists or possiblly you just have it set to a default that&#8217;s useless like a fourth foot. Either way, not good.</p>
<p>Now I haven&#8217;t figured out the reason for this (Don&#8217;t act so surprised, you aren&#8217;t a very good actor), but I have figured out a way around it. Basically for the form to keep the values, you need to add hidden values. I know, it&#8217;s a pain. Good thing I have a method that makes it easier. Also, this post is a prerequisite for a method I have for creating buttons&#8230; but that in the future.  ITS A TEASER! THIS POST IS A TEASER!  THERE I SAID IT!  CAN I GO NOW?</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> CreateHiddenValuesFromUrl(<span style="color: #008080;">String</span> baseUrl)
{
  <span style="color: #008080;">StringBuilder</span> html = <span style="color: #0000ff;">new</span> <span style="color: #008080;">StringBuilder</span>();

  <span style="color: #0000ff;">if</span>(!<span style="color: #008080;">String</span>.IsNullOrEmpty(baseUrl))
  {
    <span style="color: #008000;">//Have to find the ? to know where to begin</span>
    <span style="color: #008080;">Int32</span> indexOfQuestionMark = baseUrl.IndexOf(<span style="color: #800000;">'?'</span>);

    <span style="color: #008000;">//If the question mark exists and there is something after it, keep going
</span>    <span style="color: #0000ff;">if</span> (indexOfQuestionMark &gt; -1 &amp;&amp; baseUrl.Length &gt;= indexOfQuestionMark + 1)
    {
      <span style="color: #008000;">//Get everything AFTER the ?, something I didn't think of first time around
</span>      <span style="color: #008000;">//Caused many test failures and much shame to my family.
</span>      <span style="color: #008080;">String</span> request = baseUrl.Substring(indexOfQuestionMark + 1);

      <span style="color: #008000;">//Cut up the string by the &amp; since every parameter after the first
</span>      <span style="color: #008000;">//is divided by &amp;.. I know, Duh.
</span>      <span style="color: #008080;">String</span>[] splitList = request.Split(<span style="color: #800000;">'&amp;'</span>);

      <span style="color: #008000;">//Go through the list of possible request items
</span>      <span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> requestItem <span style="color: #0000ff;">in</span> splitList)
      {
        <span style="color: #008080;">String</span>[] splitItem = requestItem.Split(<span style="color: #800000;">'='</span>);
        <span style="color: #008000;">//This is to make sure the parameter actually has a value to send in
</span>        <span style="color: #008000;">//the hidden values.  I supposed you could create an empty hidden
</span>        <span style="color: #008000;">//value to preserve the parameter, but remember the parameter
</span>        <span style="color: #008000;">//isn't being lost from the form action, just the value
</span>        <span style="color: #0000ff;">if</span> (splitItem.Length == 2 &amp;&amp; !<span style="color: #008080;">String</span>.IsNullOrEmpty(splitItem[1]))
        {
          <span style="color: #008000;">//Create a hidden input with the key name and the value
</span>          html.Append(<span style="color: #800000;">"&lt;input type=\"hidden\" name=\""</span> + splitItem[0] + <span style="color: #800000;">"\" value=\""</span> + splitItem[1] + <span style="color: #800000;">"\" &gt;"</span>);
        }
      }
    }
  }

  <span style="color: #0000ff;">return</span> html.ToString();
}</pre>
<p>And it&#8217;s just that simple. Mind you I could probably make this an extension method for the HtmlHelper, but I don&#8217;t really use it for that.</p>
<p>Next up will be more razzle and dazzle using this to make an optional image button. I bet you can&#8217;t wait. I know I can.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Create a link method&#8230; ie JUST GIVE ME THE STUPID URL</title>
		<link>http://byatool.com/utilities/asp-net-mvc-create-a-link-method-ie-just-give-me-the-stupid-url/</link>
		<comments>http://byatool.com/utilities/asp-net-mvc-create-a-link-method-ie-just-give-me-the-stupid-url/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 20:54:17 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=737</guid>
		<description><![CDATA[One thing that kind of annoys me is the situation where you just want a url, but you don&#8217;t want one of the prepackaged links using: Html.RouteLink Or Html.ActionLink Mostly because you want to be able to create your own html and you only want the created url. Well turns out there&#8217;s a method for [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that kind of annoys me is the situation where you just want a url, but you don&#8217;t want one of the prepackaged links using:</p>
<pre>   Html.RouteLink
Or
   Html.ActionLink</pre>
<p>Mostly because you want to be able to create your own html and you only want the created url. Well turns out there&#8217;s a method for this: The RouteUrl method on the UrlHelper class. Down side is that it&#8217;s not static and takes a few lines to use, so not cool UI design side. Well here&#8217;s a method that uses that method and gives you a method to exact a method of victory. I think that sentence had promise, but fell short of complete failure.</p>
<p>Anyways, here it is&#8230; The &#8220;Just give me the stupid url&#8221; method, CreateUrl for short.</p>
<pre>        public static String CreateUrl
        (
          <span style="color: #008080;">RequestContext</span> context,
          <span style="color: #008080;">RouteCollection</span> routeCollection,
          <span style="color: #008080;">String</span> routeName,
          <span style="color: #008080;">String</span> controller,
          <span style="color: #008080;">String</span> action,
          <span style="color: #008080;">RouteValueDictionary</span> routeValues
        )
        {
            <span style="color: #008000;">//Create the helper
</span>            <span style="color: #008080;">UrlHelper</span> neededHelper = new <span style="color: #008080;">UrlHelper</span>(context, routeCollection);

            <span style="color: #008000;">//get the route to check what it is holding at far
</span>            <span style="color: #008000;">//as defaults go
</span>            <span style="color: #0000ff;">var</span> neededRoute = (<span style="color: #008080;">Route</span>)routeCollection[routeName];

            <span style="color: #008000;">//this might be overkill honestly.  Basically in case the
</span>            <span style="color: #008000;">//Route contains the "controller" key only then add it to the
</span>            <span style="color: #008000;">//values for the route.  Otherwise just ignore.  It's possible
</span>            <span style="color: #008000;">//someone might pass in a controller/action but the route
</span>            <span style="color: #008000;">//doesn't take them. At which point you'll</span>
<span style="color: #008000;">            //be showing the "Aw maaaaan" face.</span>

<span style="color: #0000ff;">            if</span> (!<span style="color: #008080;">String</span>.IsNullOrEmpty(controller) &amp;&amp; neededRoute.Defaults.ContainsKey(<span style="color: #800000;">"controller"</span>))
            {
                routeValues.Add(<span style="color: #800000;">"controller"</span>, controller);
            }

            <span style="color: #0000ff;">if</span> (!<span style="color: #008080;">String</span>.IsNullOrEmpty(action) &amp;&amp; neededRoute.Defaults.ContainsKey(<span style="color: #800000;">"action"</span>))
            {
                routeValues.Add(<span style="color: #800000;">"action"</span>, action);
            }

            <span style="color: #008000;">//And then the call to create the url string.
</span>            <span style="color: #0000ff;">return</span> neededHelper.RouteUrl(routeName, routeValues);
        }</pre>
<p>And in use View side:</p>
<pre>  <span style="color: #0000ff;">&lt;</span><span style="color: #ff0000;">a href=</span><span style="color: #0000ff;">"</span>
  <span style="color: #ff9900;">&lt;</span><span style="color: #ff9900;">%</span>
  CreateUrl
  (
    Html.ViewContext.RequestContext,
    Html.RouteCollection,
    GeneralConstants.RouteDefault,
    <span style="color: #800000;">"SomeController"</span>,
    <span style="color: #800000;">"SomeAction"</span>,
    new <span style="color: #008080;">RouteValueDictionary</span> { { <span style="color: #800000;">"id"</span>, 1 } }
  )
  <span style="color: #ff9900;">%</span><span style="color: #ff9900;">&gt;</span><span style="color: #0000ff;">"</span>
  <span style="color: #0000ff;">&gt;</span>
  Something is linked
  <span style="color: #0000ff;">&lt;/</span><span style="color: #ff0000;">a</span><span style="color: #0000ff;">&gt;</span></pre>
<p>Now mind you I did use a link there so it seems like a silly example. However, you can do many other things now that you just have the url itself.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/asp-net-mvc-create-a-link-method-ie-just-give-me-the-stupid-url/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 4</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-4/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-4/#comments</comments>
		<pubDate>Fri, 08 May 2009 20:08:11 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Paging]]></category>
		<category><![CDATA[WebControl]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=640</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls Now onto the fourth part of this epic saga that George Washington once called, &#8220;The most astounding exercise in futility&#8221; Ok so let&#8217;s say you have a grid, items to fill [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>Now onto the fourth part of this epic saga that George Washington once called, &#8220;The most astounding exercise in futility&#8221;</p>
<p>Ok so let&#8217;s say you have a grid, items to fill it with, and four buttons. Each button has a direction, say one back, all the way back, one forward, all the way forward. No big deal. Now you want them to page correctly when used. After all, it&#8217;s always a bonus when things go right. First you need to set the CommandArguments on the buttons themselves to whatever page they are responsible for.</p>
<pre><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> SetAndBind(<span style="color: #008080;">Int32</span> pageNumber)
{
  <span style="color: #008080;">Int32</span> realPage;
  <span style="color: #008080;">Int32</span> totalCount;

  <span style="color: #008080;">IList&lt;ToolItem&gt;</span> inviteList =
    ToolClass
    .GetSomeTools(<span style="color: #800000;">"Sean"</span>, 20, pageNumber, <span style="color: #0000ff;">out</span> realPage, <span style="color: #0000ff;">out</span> totalCountOfPages);

  btnFullBack.CommandArgument = Convert.ToString(0);
  btnOneBack.CommandArgument = Convert.ToString(realPage - 1);
  btnOneForward.CommandArgument = Convert.ToString(realPage + 1);
  btnFullForward.CommandArgument = Convert.ToString(totalCountOfPages);

  BindGrid(inviteList);
}</pre>
<p>First off, GetSomeTools is just a method that is the same as I presented in the third installment of this epic saga that George Washington once called, &#8220;The most astounding exercise in futility&#8221;. If you&#8217;ve been reading up to this point, then you&#8217;ll know that. If not, you might have some reading to do.</p>
<p>So, here&#8217;s a simple method used to get the info we need (using the page number) and set the buttons. As seen before, realPage is the actual possible page (In case someone passed in page 21 when there are only 20 pages) and totalCountOfPages gives us how many possible pages there are. This makes setting the button CommandArguments cake. Now for the button event:</p>
<pre>  <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> btnPaging_Click(<span style="color: #008080;">Object</span> sender, <span style="color: #008080;">EventArgs</span> e)
  {
    SetAndBind(Convert.ToInt32(((<span style="color: #008080;">Button</span>)sender).CommandArgument));
  }</pre>
<p>And then you just set all the click events to that:</p>
<pre>  btnFullBack.Click += btnPaging_Click;
  btnOneBack.Click += btnPaging_Click;
  btnOneForward.Click += btnPaging_Click;
  btnFullForward.Click += btnPaging_Click;</pre>
<p>And boom, you&#8217;re pretty much set.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 3</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/#comments</comments>
		<pubDate>Fri, 08 May 2009 14:30:50 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Skip]]></category>
		<category><![CDATA[Take]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=635</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to Linq, the Entity Framework, and well that&#8217;s it I think.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList&lt;ToolItem&gt;</span> GetSomeTools(<span style="color: #008080;">String</span> name, <span style="color: #008080;">Int32</span> numberToShow, <span style="color: #008080;">Int32</span> pageNumber, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> realPage, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> totalCountOfPages)
{
  <span style="color: #008000;">//EntityContext.Context is just a </span><a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching"><span style="color: #008000;">singletonish version</span></a><span style="color: #008000;"> of the
  //Entities class.  Most people would use
  //  using (ToolEntities context = new ToolEnties())
</span>  <span style="color: #008080;">Int32</span> totalCount = EntityContext.Context.ToolItems
		   .Count(item =&gt; item.Name == name);
  <span style="color: #008000;">//This is the method from the first post of this series
  //Just getting the count of pages based on numberToShow and
  //item totalCount</span>
  totalCountOfPages = TotalCountOfPages(totalCount, numberToShow);
  <span style="color: #008000;">//This is the method from the second post of this series
  //Basically getting the best possible page if the page number
  //is higher than the totalCountOfPages or lower than 0</span>
  realPage = GetRealPage(totalCountOfPages, pageNumber);

  returnValue = EntityContext.Context.ChatRooms
			  .Where(item =&gt; item.Name == name )
			  .OrderBy(item =&gt; item.Name)
			  .Skip(numberToShow * realPage)
			  .Take(numberToShow)
			  .ToList();

  <span style="color: #0000ff;">return</span> returnValue.ToList();
}</pre>
<p>Really simple yes? It follows like this:</p>
<p>Say I&#8217;m on page 1, which for this would be zero or pageNumber &#8211; 1. So I want to grab the first 20 items from the database. Well that means I want to start at 0 and grab 20. Now if you want this all to be done with some kind of conditional thing that either handles the first page or the other pages, you actually want to skip the same way no matter what the page number is. This is taken care of by numberToShow * realPage since even at 0 this works. After all 0 * anything is 0 and therefore you will be Skipping 0 items. So in other words, you&#8217;re at the start. Next you want to Take the amount of items you need, which is 20. Next time around you&#8217;ll start at 20 Skip(numberToShow 20 * realPage 1) and take the next 20. Nice thing is, even if you say Take 20 and there are only 2 left, it doesn&#8217;t care. It will just grab those two.</p>
<p>And there you have it, how to page with the Entity Framework and minimal amount of work. I know I hate taking other people&#8217;s methods (Like the TotalCountOfPages and GetRealPage methods), don&#8217;t know why. So sorry if I am forcing you to do so. However, the two methods I gave are semi important to this.</p>
<p>You might wonder why realPage and totalCountOfPages, well this is useful stuff when knowing what page is next for paging controls.  Next post I&#8217;ll show those off but I&#8217;ll warn you, they are nothing spectacular.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 2</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-2/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-2/#comments</comments>
		<pubDate>Thu, 07 May 2009 14:25:26 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=626</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls So in part one I posted the method to find the total count of pages you&#8217;ll need so that you don&#8217;t go too far while paging. Now it&#8217;s about trying to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>So in part one I posted the method to find the total count of pages you&#8217;ll need so that you don&#8217;t go too far while paging. Now it&#8217;s about trying to get the best possible page number despite what&#8217;s passed in.</p>
<p>Here&#8217;s the situation, when you are paging up or down, you want to make sure you don&#8217;t go lower than 0 or higher than whatever the total count of pages is. Sometimes though, things go wrong. They go very wrong. It&#8217;s possible that your ui design will allow for any number to be passed in as the page number (Too many reasons this could happen to bother with). Say you have only 10 possible pages but the number 12 gets passed in. Well you either allow it to grab a non existant page 12 or you have a method to determine the best possible choice at this point (10). Turns out it&#8217;s idiot simple&#8230; what? Were you expecting anything different?</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> Int32 GetRealPage(Int32 totalCountOfPages, Int32 pageNumber)
{
  <span style="color: #008000;">//pageNumber and totalCountOfPages have to be above 0 or problems
</span>  <span style="color: #0000ff;">if</span> (pageNumber &gt; 0 &amp;&amp; totalCountOfPages &gt; 0)
  {
    <span style="color: #008000;">//If page number is higher than the possible count of pages,</span>
    <span style="color: #008000;">//then you just need the total count to be the new page number...</span>
    <span style="color: #008000;">//but there's one more step</span>
    pageNumber = totalCountOfPages &lt; pageNumber ? totalCountOfPages : pageNumber;
    <span style="color: #008000;">//If by chance the pageNumber now is the same as totalCountOfPages</span>
    <span style="color: #008000;">//(Meaning it was larger than totalCountOfPages originally)</span>
    <span style="color: #008000;">//1 has to be subtracted to make sure it's inline with a 0 based system where</span>
    <span style="color: #008000;">//page 1 is actually 0.  This will make more sense when using skip and take in</span>
    <span style="color: #008000;">//the next post.</span>
    pageNumber = totalCountOfPages != pageNumber ? pageNumber : totalCountOfPages - 1;
  }
  <span style="color: #0000ff;">else</span>
  {
    pageNumber = 0;
  }

  <span style="color: #0000ff;">return</span> pageNumber;
}</pre>
<p>Ok so I&#8217;m going to claim this is amazing stuff, but it will come in handy with the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 1</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/#comments</comments>
		<pubDate>Wed, 06 May 2009 13:41:44 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=620</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls So something I&#8217;ve been doing a lot of lately is making quite possibly the best thing ever: String cheese wrapped in turkey bacon. But when I&#8217;m not doing that, I am [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>So something I&#8217;ve been doing a lot of lately is making quite possibly the best thing ever: String cheese wrapped in turkey bacon. But when I&#8217;m not doing that, I am working with a lot of ListViews and the entity framework. Now I know there are &#8220;built in&#8221; paging controls but I just haven&#8217;t liked what I&#8217;ve seen. So I took it upon myself one day to develop a repeatable system for paging. Say you have users and a bunch of invites that are attached to the users. You want to show a list of invites for a particular user, but you want a ListView that doesn&#8217;t show every invite&#8230; ie you need a pager. Well just so happens I have a solution, but as always you should consult a doctor before use.</p>
<p>First off you need a method to get the total count of pages meaning what the ceiling is when you page upwards. After all, if you go over the possible count of pages, you&#8217;ll just get no items returned and look kind of dumb.</p>
<p>There are three situations you have to look out for: You have less items that the required items per page (Say 10 rows but you display 20 row per page), you have a perfect division (20 rows and 20 row per page or 40 rows and 20 rows per page, ect), you have an uneven division (21 rows and 20 rows  per page). First two are easy, third isn&#8217;t hard exactly but there are some catches.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">Int32</span> TotalCountOfPages(Int32 rowCount, Int32 neededPageSize)
{
<span style="color: #008080;">  Int32</span> returnValue;
<span style="color: #0000ff;">  if</span>(rowCount &gt; 0)
  {
    <span style="color: #0000ff;">if</span> (rowCount &lt;= neededPageSize)
    {
      returnValue = 1;
    }
    <span style="color: #0000ff;">else</span>
    {
      <span style="color: #0000ff;">if</span> ((rowCount % neededPageSize) == 0)
      {
        returnValue = rowCount / neededPageSize;
      }
      <span style="color: #0000ff;">else</span>
      {
        <span style="color: #008080;">Decimal</span> convertedPageSize =
         Convert.ToDecimal(neededPageSize);
        <span style="color: #008080;">Decimal</span> convertedRowCount =
         Convert.ToDecimal(rowCount);
        <span style="color: #008080;">Decimal</span> resultRounded =
          Math.Round(convertedRowCount / convertedPageSize);
        <span style="color: #008080;">Decimal</span> resultNonRounded =
          convertedRowCount / convertedPageSize;

        <span style="color: #0000ff;">if</span> (resultRounded &lt; resultNonRounded)
        {
           returnValue =
            Convert.ToInt32(resultRounded + 1);
        }
        <span style="color: #0000ff;">else</span>
        {
           returnValue =
            Convert.ToInt32(resultRounded);
        }
      }
    }
  }
<span style="color: #0000ff;">  else
</span>  {
    returnValue = 0;
  }
  <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>Ok so first off, I assume this one is pretty obvious:</p>
<pre><span style="color: #0000ff;">  if</span>(rowCount &gt; 0)</pre>
<p>If there aren&#8217;t any rows, the there can&#8217;t be a page count.</p>
<p>Next take care the less rows than being shown per page:</p>
<pre>  <span style="color: #0000ff;">if</span> (rowCount &lt;= neededPageSize)
  {
    returnValue = 1;
  }</pre>
<p>Simple enough. Now for the second part, a perfect division between rows and rows to show:</p>
<pre> <span style="color: #0000ff;">if</span> ((rowCount % neededPageSize) == 0)
 {
    returnValue = rowCount / neededPageSize;
 }</pre>
<p>Basically, for those who don&#8217;t know mod or the % operator, that means there is no remainder. If there were, the result of rowCount % neededPageSize would not be 0 since Mod basically means &#8220;Give me what&#8217;s left over when I divide something by something else.&#8221;</p>
<p>Ok, this is where it gets a little messy as I have yet to find a good way to round a number up since, far as I know, there&#8217;s no way to do it with the .Net lib&#8217;ary. So, I had to come up with something clever&#8230; and when that failed I came up with this:</p>
<pre> <span style="color: #008080;">Decimal</span> convertedPageSize =
    Convert.ToDecimal(neededPageSize);
 <span style="color: #008080;">Decimal</span> convertedRowCount =
    Convert.ToDecimal(rowCount);
  <span style="color: #008080;">Decimal</span> resultRounded =
    Math.Round(convertedRowCount / convertedPageSize);
  <span style="color: #008080;">Decimal</span> resultNonRounded =
    convertedRowCount / convertedPageSize;

  <span style="color: #0000ff;">if</span> (resultRounded &lt; resultNonRounded)
  {
      returnValue =
          Convert.ToInt32(resultRounded + 1);
  }
  <span style="color: #0000ff;">else</span>
  {
     returnValue =
       Convert.ToInt32(resultRounded);
  }</pre>
<p>Ok so what&#8217;s going on here? First off, because trying to divide an integer by an integer gives me an integer, I had to covert some stuff to decimal. Why is that? When I divide them, I need to know if the number after the decimal is between 1 and 1.5 since Math.Round will round down in that case killing my ability to tell if I have enough pages.</p>
<p>Example: 19 rows and 10 per page will give me a 1.9 which Round will make 2. This is perfect since I need two pages to show the 19 rows. What if I have 14 rows and 10 per page? I get 1 from rounding. Uh oh. I really need two pages.</p>
<p>How do I get around this? Get the rounded version and the unrounded version. From there I know that if the unrounded version is greater than the rounded version I need an extra page.</p>
<p>So 14 rows / 10 per page = 1.4 unrounded and 1 rounded. 1.4 &gt; 1, so that 1 page isn&#8217;t going to do it. I need to add one more page. Now if it 19 rows/10 per page I&#8217;ll get 1.9 unrounded and 2 rounded. 2 pages is exactly what I need and I don&#8217;t have to add anything.</p>
<p>Next post I&#8217;ll show the next needed method: How to tell if the page number being sent in (From the pager/UI) is actually valid. If not, then grab the last possible amount of records.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Duck Typing my way to a Universal String Convert</title>
		<link>http://byatool.com/utilities/duck-typing-my-way-to-a-universal-string-convert/</link>
		<comments>http://byatool.com/utilities/duck-typing-my-way-to-a-universal-string-convert/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 14:48:15 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=94</guid>
		<description><![CDATA[So being the beacon of ignorance in the fog of brilliance, I had no idea what Duck Typing was. In short it&#8217;s the idea of assuming a class&#8217;s type based on the methods it holds. Say you have 5 different classes, none of which share an inheritance tree. Now let&#8217;s say you have a method [...]]]></description>
			<content:encoded><![CDATA[<p>So being the beacon of ignorance in the fog of brilliance, I had no idea what Duck Typing was.  In short it&#8217;s the idea of assuming a class&#8217;s type based on the methods it holds. </p>
<p>Say you have 5 different classes, none of which share an inheritance tree.  Now let&#8217;s say you have a method that takes in any object and uses the SeanIsAwsome method on the object.  You could make sure that every object sent in has that method by using an interface that all the objects sent in share.</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> SomeMethod(<span style="color: #33cccc;">ISeanRules</span> inParameter)</pre>
<p>What if you want to send in a bunch of objects that don&#8217;t share the same interface/base class? Well you base it on what methods the class holds. If the class has the SeanIsAwsome method, then you call it. If not, well you could throw an exception, do nothing, go jogging, eat bacon, ect. That part is up to you.</p>
<p>The problem was that I wanted to create a universal convert that would take in a string and convert it to the 8 billion (ballpark figure) value types in C#. Now what I wanted to do is use the famous TryParse method so my first hope was that TryParse was a method on an interface they all shared. Yeah no. So next thought was to use the Duck Typing principle and say, &#8220;Hey jackass, you have a TryParse method? Yeah? Good. Use it.&#8221; &#8216;Course I had to find a way to do that. Turns out it wasn&#8217;t too bad.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">class</span> ConvertFromString
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> T? ConvertTo&lt;T&gt;(<span style="color: #0000ff;">this</span> <span style="color: #33cccc;">String</span> numberToConvert) <span style="color: #0000ff;">where</span> T : <span style="color: #0000ff;">struct</span>
  {
    T? returnValue = null;

    <span style="color: #33cccc;">MethodInfo</span> neededInfo = GetCorrectMethodInfo(<span style="color: #0000ff;">typeof</span>(T));
    if (neededInfo != null &amp;&amp; !numberToConvert.IsNullOrEmpty())
    {
      T output = <span style="color: #0000ff;">default</span>(T);
      <span style="color: #0000ff;">object</span>[] paramsArray = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">object</span>[2] { numberToConvert, output };
      returnValue = <span style="color: #0000ff;">new</span> T();

      <span style="color: #0000ff;">object</span> returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

      <span style="color: #0000ff;">if</span> (returnedValue <span style="color: #0000ff;">is</span> <span style="color: #33cccc;">Boolean</span> &amp;&amp; (<span style="color: #33cccc;">Boolean</span>)returnedValue)
      {
        returnValue = (T)paramsArray[1];
      }
      <span style="color: #0000ff;">else</span>
      {
        returnValue = <span style="color: #0000ff;">null</span>;
      }
    }

    <span style="color: #0000ff;">return</span> returnValue;
  }
}</pre>
<p>A whaaaa?</p>
<p>Ok this might look odd, but it&#8217;s really simple. If it doesn&#8217;t look odd then chances are you&#8217;re smarter than me and you shouldn&#8217;t be here anyhow. First part is simple:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> T? ConvertTo&lt;T&gt;(<span style="color: #0000ff;">this</span> <span style="color: #33cccc;">String</span> numberToConvert) <span style="color: #0000ff;">where</span> T : <span style="color: #0000ff;">struct</span></pre>
<p>Due to this being a extension method (Opps forgot to tell you that part) I have to declare this static method in a static class. Basically I am taking in a string and returning a nullable version of whatever type I specific in the call.</p>
<pre>    T? returnValue = <span style="color: #0000ff;">null</span>;

    <span style="color: #33cccc;">MethodInfo</span> neededInfo = GetCorrectMethodInfo(<span style="color: #0000ff;">typeof</span>(T));</pre>
<p>Remember that MethodInfo method I had explained in the last post? The next part you might remember too, but I&#8217;m not betting on it.</p>
<pre>    <span style="color: #0000ff;">if</span> (neededInfo != <span style="color: #0000ff;">null</span> &amp;&amp; !numberToConvert.IsNullOrEmpty())
    {
      T output = <span style="color: #0000ff;">default</span>(T);
      <span style="color: #0000ff;">object</span>[] paramsArray = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">object</span>[2] { numberToConvert, output };
      returnValue = <span style="color: #0000ff;">new</span> T();

      <span style="color: #0000ff;">object</span> returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);</pre>
<p>Ok so I have the method info, now I have to create the list of parameters to send in with the invoke. Pretty straight forward. If things went well, returnedValue should be a boolean. However, just incase:</p>
<pre>    <span style="color: #0000ff;">if</span> (returnedValue is <span style="color: #33cccc;">Boolean</span> &amp;&amp; (<span style="color: #33cccc;">Boolean</span>)returnedValue)
    {
      returnValue = (T)paramsArray[1];
    }
    <span style="color: #0000ff;">else</span>
    {
      returnValue = <span style="color: #0000ff;">null</span>;
    }</pre>
<p>So if the returnValue is true and boolean, then the tryParse was successful. With that in mind, I still have to get the converted value. If it had not been successful than I am just going to return null since this is just meant for converting and not for whether or not it could be. It is just assumed that if it&#8217;s null, then it could not be converted at this time.</p>
<p>And now for the use:</p>
<pre>  <span style="color: #0000ff;">decimal</span>? converted = someString.ConvertTo&lt;<span style="color: #0000ff;">decimal</span>&gt;()</pre>
<p>An boom, you have a universal convert. YAY!</p>
<pre>  <span style="color: #0000ff;">using</span> System;
  <span style="color: #0000ff;">using</span> System.Reflection;</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/duck-typing-my-way-to-a-universal-string-convert/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert Enum to Dictionary: Another Silly Method</title>
		<link>http://byatool.com/utilities/another-silly-method-just-for-you/</link>
		<comments>http://byatool.com/utilities/another-silly-method-just-for-you/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 18:22:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enumeration]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/14/another-silly-method-just-for-you/</guid>
		<description><![CDATA[So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this: public static IDictionary&#60;String, Int32&#62; ConvertEnumToDictionary&#60;K&#62;() { if (typeof(K).BaseType != typeof(Enum)) { throw new InvalidCastException(); } return Enum.GetValues(typeof(K)).Cast&#60;Int32&#62;().ToDictionary(currentItem =&#62; Enum.GetName(typeof(K), currentItem)); } [...]]]></description>
			<content:encoded><![CDATA[<p>So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">IDictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Int32</span>&gt; ConvertEnumToDictionary&lt;K&gt;()
{
 <span style="color: #3333ff;">if</span> (<span style="color: #3333ff;">typeof</span>(K).BaseType != <span style="color: #3333ff;">typeof</span>(<span style="color: #00cccc;">Enum</span>))
 {
   <span style="color: #3333ff;">throw</span> <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">InvalidCastException</span>();
 }

 <span style="color: #3333ff;">return</span> <span style="color: #00cccc;">Enum</span>.GetValues(<span style="color: #3333ff;">typeof</span>(K)).Cast&lt;<span style="color: #00cccc;">Int32</span>&gt;().ToDictionary(currentItem =&gt; <span style="color: #00cccc;">Enum</span>.GetName(<span style="color: #3333ff;">typeof</span>(K), currentItem));
}</pre>
<p>As you might see, pretty simple.</p>
<p>Ok so ToDictionary is kind of odd looking maybe, but really isn&#8217;t that big of a deal. Basically it assumes the items in the list are the value, but you need to tell it what the key is. In this case, the int values for the enum are the value for the dictionary where the name that matches said int value will become the key for the dictionary.</p>
<p>So basically, get the values for the enum. Turn that into an IEnumerable list of Int32, create a Dictionary from that.</p>
<p>USINGS!!111</p>
<pre> <span style="color: #3333ff;">using</span> System;
 <span style="color: #3333ff;">using</span> System.Collections.Generic;
 <span style="color: #3333ff;">using</span> System.Linq;</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/another-silly-method-just-for-you/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Yeah SessionTryParse</title>
		<link>http://byatool.com/utilities/yeah-sessiontryparse/</link>
		<comments>http://byatool.com/utilities/yeah-sessiontryparse/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 17:06:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[TryParse]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/24/yeah-sessiontryparse/</guid>
		<description><![CDATA[So I got tired of seeing If Session["SomeKey"] != null&#8230; blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I&#8217;m bad like that. Not a Bad Enough Dude to Save the President, but bad. public static Boolean SessionTryParse&#60;K&#38;gt;(HttpSessionState session, String key, out K itemToSet) where K [...]]]></description>
			<content:encoded><![CDATA[<p>So I got tired of seeing If Session["SomeKey"] != null&#8230; blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I&#8217;m bad like that. Not a Bad Enough Dude to Save the President, but bad.</p>
<pre> <span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">Boolean</span> SessionTryParse&lt;K&amp;gt;<span style="color: #00cccc;">(HttpSessionState </span>session, <span style="color: #00cccc;">String </span>key, <span style="color: #3333ff;">out </span>K itemToSet) <span style="color: #3333ff;">where </span>K : <span style="color: #3333ff;">class</span>
 {
     itemToSet = <span style="color: #3333ff;">null</span>;

     <span style="color: #3333ff;">if</span> (session[key] != <span style="color: #3333ff;">null</span>)
     {
        itemToSet = session[key] <span style="color: #3333ff;">as</span> K;
     }

     <span style="color: #3333ff;">return</span> itemToSet != <span style="color: #3333ff;">null</span>;
 }</pre>
<p>And for structures&#8230; which I have to cheat and only allow them to be nullable.</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">Boolean</span> SessionTryParse&lt;K&gt;(<span style="color: #00cccc;">HttpSessionState</span> session, <span style="color: #00cccc;">String </span>key, <span style="color: #3333ff;">out </span>K? itemToSet) <span style="color: #3333ff;">where </span>K : <span style="color: #3333ff;">struct</span>
{
     itemToSet = <span style="color: #3333ff;">null</span>;

     <span style="color: #3333ff;">if </span>(session[key] != <span style="color: #3333ff;">null </span>&amp;&amp; session[key] <span style="color: #3333ff;">is</span> K)
     {
        itemToSet = (K)session[key];
     }

     <span style="color: #3333ff;">return</span> itemToSet != <span style="color: #3333ff;">null</span>;
}</pre>
<p>The idea is simple, pull in the Session, the needed Session key, and something to throw the value in. After that, just check to see if the Session + Key is null and if Session + Key is the same type of said something. That&#8217;s how it&#8217;s done Detroit greater metropolitan area style&#8230; punk.</p>
<p>USE THIS:</p>
<pre>   <span style="color: #3333ff;">using</span> System;
   <span style="color: #3333ff;">using</span> System.Web.SessionState;</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/yeah-sessiontryparse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert a String to a Number String With Linq&#8230; YAY</title>
		<link>http://byatool.com/utilities/quick-linq-thing-string-to-number-string/</link>
		<comments>http://byatool.com/utilities/quick-linq-thing-string-to-number-string/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 19:22:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/17/quick-linq-thing-string-to-number-string/</guid>
		<description><![CDATA[Really stupid little thing I came up with today&#8230; but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing. public static String CreateNumberOnlyString(String textToCheck) { String returnText; var queryForIntegers = from currentChar in textToCheck where [...]]]></description>
			<content:encoded><![CDATA[<p>Really stupid little thing I came up with today&#8230; but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">String </span>CreateNumberOnlyString(<span style="color: #00cccc;">String </span>textToCheck)
{
  <span style="color: #00cccc;">String </span>returnText;

  <span style="color: #3333ff;">var </span>queryForIntegers = <span style="color: #3333ff;">from </span>currentChar <span style="color: #3333ff;">in </span>textToCheck
                         <span style="color: #3333ff;">where </span>Char.IsNumber(currentChar)
                         <span style="color: #3333ff;">select </span>currentChar;

  returnText = <span style="color: #3333ff;">new </span>String(queryForIntegers.ToArray());

  <span style="color: #3333ff;">return </span>returnText;
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/quick-linq-thing-string-to-number-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guard Clause Method</title>
		<link>http://byatool.com/utilities/guard-clause-method/</link>
		<comments>http://byatool.com/utilities/guard-clause-method/#comments</comments>
		<pubDate>Thu, 10 Jul 2008 20:26:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Exception]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/10/guard-clause-method/</guid>
		<description><![CDATA[So I was introduced to the idea of a &#8220;guard clause&#8221; in methods when I started my latest job. The idea is to make sure that all the passed in parameters of a method are, for example, not null. If they are, just throw an exception. This is what I have been doing: if(someField == [...]]]></description>
			<content:encoded><![CDATA[<p>So I was introduced to the idea of a &#8220;guard clause&#8221; in methods when I started my latest job. The idea is to make sure that all the passed in parameters of a method are, for example, not null. If they are, just throw an exception. This is what I have been doing:</p>
<pre><span style="color: #3333ff;">if</span>(someField == <span style="color: #3333ff;">null</span>)
{
<span style="color: #3333ff;">throw new</span> ArgumentNullException();
}</pre>
<p>Well just recently I was somewhat schooled in the idea of removing if statements and creating simple methods in their steed. Now this isn&#8217;t always a need, but in complex (ie annoying) nested ifs, it might help to clean things up. So in light of this, I came up with this method:</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Collections.Generic;
<span style="color: #3333ff;">using</span> System.Reflection;

<span style="color: #3333ff;">private void</span> ThrowExceptionIfNull&lt;TException, TObject&gt;(TObject objectToCheck, <span style="color: #00cccc;">String</span> message)
<span style="color: #3333ff;">where</span> TException : <span style="color: #00cccc;">Exception </span>
<span style="color: #3333ff;">where</span> TObject : <span style="color: #3333ff;">class</span>
{
  <span style="color: #3333ff;">if</span>(objectToCheck == <span style="color: #3333ff;">null</span>)
  {
      TException exception;

      exception = <span style="color: #00cccc;">Activator</span>.CreateInstance&lt;TException&gt;();
      <span style="color: #009900;">//Set the message field on System.Exception since the property is Get only</span>
      <span style="color: #3333ff;">if</span>(message != <span style="color: #3333ff;">null</span>)
      {
          <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">FieldInfo</span>&gt; fieldInfoList;
<span style="color: #00cccc;">           FieldInfo </span>neededInfo;

          fieldInfoList = <span style="color: #3333ff;">new</span> <span style="color: #3333ff;">List</span>&lt;<span style="color: #00cccc;">FieldInfo</span>&gt;(<span style="color: #3333ff;">typeof</span>(<span style="color: #00cccc;">Exception</span>).GetFields(<span style="color: #00cccc;">BindingFlags</span>.Instance | <span style="color: #00cccc;">BindingFlags</span>.NonPublic | <span style="color: #00cccc;">BindingFlags</span>.Public));
          neededInfo = fieldInfoList.Find(currentItem =&gt; <span style="color: #00cccc;">String</span>.Compare(currentItem.Name, <span style="color: #cc0000;">"_message"</span>) == 0);
          <span style="color: #009900;">//make sure that the message field is still called _message, otherwise</span>
<span style="color: #009900;">           //forget the message.</span>
<span style="color: #3333ff;">           if</span>(neededInfo != <span style="color: #3333ff;">null</span>)
          {
              neededInfo.SetValue(exception, message);
          }
      }
      <span style="color: #3333ff;">throw </span>exception;
  }
}</pre>
<p>And the use:</p>
<pre>ThrowExceptionIfNull&lt;<span style="color: #00cccc;">ArgumentNullException</span>, <span style="color: #00cccc;">String</span>&gt;(someParameter, "someParameter");</pre>
<p>Couple things to keep in mind:</p>
<ul>
<li>This uses reflection to find the message field since there is no set accessor to the Message property. This could be dangerous if Microsoft decides to rename the _message field.</li>
<li>The use of reflection would usually include the caching of the field info since you don&#8217;t want to keep using reflection for the same class every time. In this case, you&#8217;re throwing an exception so everything is done anyhow. The cost advantage of a cache is pointless.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/guard-clause-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Random String of Specified Length with Enumerable</title>
		<link>http://byatool.com/utilities/random-string-of-specified-length-with-enumerable/</link>
		<comments>http://byatool.com/utilities/random-string-of-specified-length-with-enumerable/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 16:30:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/06/26/random-string-of-specified-length-with-enumerable/</guid>
		<description><![CDATA[using System; using System.Collections.Generic; using System.Linq; using System.Text; public static String RandomString(Int32 length) { Random randomGenerator; String returnValue; randomGenerator = new Random(); returnValue = new string(Enumerable.Range(0, length).Select(i =&#62; (char)('A' + randomGenerator.Next(0, 25))).ToArray()); return returnValue; } What this does: Enumerable.Range basically says, &#8220;Give me a collection of numbers from the first parameter to the second&#8221;, or [...]]]></description>
			<content:encoded><![CDATA[<pre><strong>
<span style="color: #33cccc;">using</span> System;
<span style="color: #33cccc;">using</span> System.Collections.Generic;
<span style="color: #33cccc;">using</span> System.Linq;
<span style="color: #33cccc;">using</span> System.Text;

<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #33cccc;">String</span> RandomString(<span style="color: #33cccc;">Int32</span> length)
{
 <span style="color: #33cccc;">Random</span> randomGenerator;
 <span style="color: #33cccc;">String</span> returnValue;

  randomGenerator = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">Random</span>();

  returnValue = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">string</span>(<span style="color: #33cccc;">Enumerable</span>.Range(0, length).Select(i =&gt; (<span style="color: #0000ff;">char</span>)(<span style="color: #ff0000;">'A'</span> + randomGenerator.Next(0, 25))).ToArray());

 <span style="color: #0000ff;">return</span> returnValue;
}
</strong></pre>
<p>What this does:</p>
<p>Enumerable.Range basically says, &#8220;Give me a collection of numbers from the first parameter to the second&#8221;, or in this case from 0 to length.</p>
<p>Select basically is a method that takes in an anonymous method (Lamdba expression in this case), goes through each of the items in the collection, and runs the anonymous method for every item in the collection. Not exactly sure what Select does specifically, but it is most likely something like this: (roughish psuedo code)</p>
<pre><strong>
<span style="color: #33cccc;">public</span> <span style="color: #0000ff;">static</span> Array Select(<span style="color: #33cccc;">Func</span> func))
{

 <span style="color: #33cccc;">Array</span> returnValue;

 <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">Int32</span> currentItem <span style="color: #0000ff;">in</span> Items)
 {
    returnValue.Add(func());
 }

 return returnValue;

}
</strong></pre>
<p>Where Func is:</p>
<pre><strong>
<span style="color: #0000ff;">public</span> <span style="color: #33cccc;">Char</span> Func()
{
 return  (<span style="color: #0000ff;">char</span>)(<span style="color: #ff0000;">'A'</span> + randomGenerator.Next(0, 25);
}
</strong></pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/random-string-of-specified-length-with-enumerable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

