﻿<?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; Dynamic</title>
	<atom:link href="http://byatool.com/tag/dynamic/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>F#: Creating your own mocks using Object Expressions&#8230; Wow</title>
		<link>http://byatool.com/f/f-creating-your-own-mocks-using-object-expressions-wow/</link>
		<comments>http://byatool.com/f/f-creating-your-own-mocks-using-object-expressions-wow/#comments</comments>
		<pubDate>Sun, 13 Nov 2011 15:57:22 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Expression]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=2365</guid>
		<description><![CDATA[This just in from the &#8220;Wow, I can&#8217;t believe how easy this is&#8221; update desk: You can roll your own mocks &#8220;dynamically&#8221;, even when mocking an interface. No, this isn&#8217;t too good to be true. No that weird tingling isn&#8217;t from your bullsh@# meter going off. (But you really should get that tingling checked by [...]]]></description>
			<content:encoded><![CDATA[<p>This just in from the &#8220;Wow, I can&#8217;t believe how easy this is&#8221; update desk:</p>
<p>You can roll your own mocks &#8220;dynamically&#8221;, even when mocking an interface. No, this isn&#8217;t too good to be true. No that weird tingling isn&#8217;t from your bullsh@# meter going off. (But you really should get that tingling checked by a doctor) This is F#. And this isn&#8217;t SPARTA!!! AHRHARHARHRAhRHARHR SO FUNAY!11</p>
<p>Say you have a test method that wants to call a method Validate on the Validator : IValidator class. Here is the IValidator class:</p>
<pre>  <span style="color: #0000ff;">type</span> <span style="color: #008080;">IValidator</span>&lt;'a, 'b&gt; =
    <span style="color: #0000ff;">abstract</span> AddValidationMethod : ('a -&gt; <span style="color: #008080;">MethodResult</span>&lt;'b&gt;) -&gt; <span style="color: #008080;">IValidator</span>&lt;'a, 'b&gt;</pre>
<p><em>(Side note: the &#8216;a and &#8216;b are just F#&#8217;s generic notation. Generic members are preceeded by a &#8216;)</em></p>
<p>Somewhere in your code this IValidator is called by someone, say a controller action:</p>
<pre>  <span style="color: #0000ff;">member</span> <span style="color: #0000ff;">public</span> x.LoginPost(userName:<span style="color: #008080;">String</span>, password:<span style="color: #008080;">String</span>) =
    <span style="color: #0000ff;">let</span> loginModel = <span style="color: #0000ff;">new</span> <span style="color: #008080;">LoginModel</span>(userName, password)
    <span style="color: #0000ff;">let</span> result = x.ControllerValidator.Validate(loginModel)</pre>
<p>And of course you would have a controller definition look like this:</p>
<pre>  <span style="color: #0000ff;">type</span> <span style="color: #008080;">MainController</span>(validator:IValidator&lt;<span style="color: #008080;">LoginModel</span>, <span style="color: #008080;">LoginModel</span>&gt;) =
    <span style="color: #0000ff;">inherit</span> Controller()
      <span style="color: #0000ff;">member</span> <span style="color: #0000ff;">private</span> x.ControllerValidator <span style="color: #0000ff;">with</span> <span style="color: #0000ff;">get</span>() = validator</pre>
<p>So you are set up for mocking.</p>
<p>There are three way, but if you&#8217;re already bored (And I assume you are) then just go to 3.</p>
<p><strong>1) Mock the IValidator</strong></p>
<p>As you can imagine, this could be obnoxious to mock up as the AddValidationMethod is adding a method that takes in &#8216;a and a MethodResult&lt;&#8217;a&gt; and then returns an IValidator&lt;&#8217;a, &#8216;b&gt;. Can it be done? I would asssume so, but there is another way.</p>
<p><strong>2) Create a new class (Class file) that implements IValidator.</strong></p>
<p>This is the most simple way of doing it. You just make a class that implements IValidator and just pass back what you want. Problem is: This isn&#8217;t very reusable as it is now a static class.</p>
<p><strong>3) Create a class on the fly.</strong></p>
<p>And this is the good stuff. F# allows the creation of a class (That implements an interface) &#8220;inline&#8221;&#8230; not sure what word I&#8217;m looking for so just go with it.</p>
<pre>  <span style="color: #0000ff;">let</span> validatorWithFalseReturn =
    {
      <span style="color: #0000ff;">new</span> <span style="color: #008080;">IValidator</span>&lt;'a, 'b&gt; <span style="color: #0000ff;">with</span>
        <span style="color: #0000ff;">member</span> x.AddValidationMethod(methodToAdd:('a -&gt; MethodResult&lt;'b&gt;)) =
          <span style="color: #0000ff;">new</span> <span style="color: #008080;">Validator</span>&lt;'a, 'b&gt;() :&gt; <span style="color: #008080;">IValidator</span>&lt;'a, 'b&gt;

        <span style="color: #0000ff;">member</span> x.Validate(model:'a) =
          (<span style="color: #0000ff;">new</span> <span style="color: #008080;">MethodResult</span>&lt;'b&gt;()).AddErrorMessage(<span style="color: #800000;">""</span>)
    }

    <span style="color: #0000ff;">let</span> mainController = <span style="color: #0000ff;">new</span> MainController(validatorWithFalseReturn)</pre>
<p>(Side note: you might see the :&gt; notation. This is basically the same as (SomeInterface)SomeClass in C#.)</p>
<p>As you can see, I created a new type and set it into the instantiated controller. As you can imagine, you could create a method that takes in a method to set AddValidation to. This has some really great potential like rolling your own mocking system.</p>
<p>So <a href="http://byatool.com/f/f-duck-typing-with-generic-constraints-and-why-you-will-be-speechless">once again</a> F# <a href="http://byatool.com/f/f-and-using-strings-for-method-and-classtype-names/">is looking</a> to be an amazing language.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/f/f-creating-your-own-mocks-using-object-expressions-wow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F#: Duck typing with generic constraints and why you will be speechless</title>
		<link>http://byatool.com/f/f-duck-typing-with-generic-constraints-and-why-you-will-be-speechless/</link>
		<comments>http://byatool.com/f/f-duck-typing-with-generic-constraints-and-why-you-will-be-speechless/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 17:01:01 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Generics]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=2359</guid>
		<description><![CDATA[So I&#8217;ve been working on a validation design that basically allows validation methods to be added to a list and then run. A small part of it: member x.Validate(valueToCheck:'a) = methodList &#124;&#62; Seq.map (fun (methodToRun) -&#62; methodToRun(valueToCheck)) &#124;&#62; Seq.reduce (fun(outer) inner -&#62; outer.MergeResults(inner)) What this is saying is take a list of methods, run them [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been working on a validation design that basically allows validation methods to be added to a list and then run. A small part of it:</p>
<pre>    <span style="color: #0000ff;">member</span> x.Validate(valueToCheck:'a) =
      methodList
      |&gt; <span style="color: #339966;">Seq</span>.map (<span style="color: #0000ff;">fun</span> (methodToRun) -&gt; methodToRun(valueToCheck))
      |&gt; <span style="color: #339966;">Seq</span>.reduce (<span style="color: #0000ff;">fun</span>(outer) inner -&gt; outer.MergeResults(inner))</pre>
<p>What this is saying is take a list of methods, run them and make a list of their results, then merge the results into one. While I won&#8217;t get into what the results are (And I almost typed that as resluts which makes me think there is a refurbishing factory for sluts.) just know that each result can merge with another and combine values.</p>
<p>The biggest problem I was running into was a way to allow any method to be added and let the method decide what it needs to run correctly. In C# this can be done easily with dynamic:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> MethodResult ValidatePasswordExistence(dynamic modelToCheck)
  {
    <span style="color: #0000ff;">var</span> returnResult = <span style="color: #0000ff;">new</span> <span style="color: #339966;">MethodResult</span>();
    <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">string</span>.IsNullOrEmpty(modelToCheck.Password))
    {
      returnResult = returnResult.AddErrorMessage(<span style="color: #339966;">UserError</span>.PasswordIsNullOrEmpty);
    }

    <span style="color: #0000ff;">return</span> returnResult;
  }</pre>
<p>The use of a dynamic parameter means that all validation methods can have the same signature which makes it really easy to send the same class into any method in the list. The problem with F# is there is no ready way to use dynamic and I&#8217;m not sure it should be. F# is heavily based on typing and dynamic kind of goes in the opposite direction. So I thought my ship was sunk, that is if I had a ship to sink and said ship hand&#8217;t sunk already.</p>
<p>Thanks to some help from <a href="http://stackoverflow.com/questions/8095512/f-member-constraints-to-help-create-seemingly-dynamic-types">the O</a>, i was able to get past this not only without dynamic, but a way to strongly type any object coming into the method:</p>
<pre>  <span style="color: #0000ff;">let</span> <span style="color: #0000ff;">inline</span> UserNameExists (userModel) =
    <span style="color: #0000ff;">let</span> userName = (^a : (<span style="color: #0000ff;">member</span> UserName : <span style="color: #0000ff;">String</span> <span style="color: #0000ff;">with</span> <span style="color: #0000ff;">get</span>) (userModel))

    <span style="color: #0000ff;">let</span> result =
      <span style="color: #0000ff;">match</span> userName <span style="color: #0000ff;">with</span>
        | <span style="color: #0000ff;">null</span> -&gt; (<span style="color: #0000ff;">new</span> MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | "" -&gt; (<span style="color: #0000ff;">new</span> MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | _ -&gt; <span style="color: #0000ff;">new</span> MethodResult()

    result</pre>
<p>The important part is the second line. This line basically says that anything coming into the method as userModel has to have a property of UserName. One of the dangerous issues with dynamic is there are no compile time checks to make sure that any object going in will have the property or method you need it to. This isn&#8217;t true of F#. You not only get to pass in any object you want (That has what is required by the check) but you get complile time errros if you try to pass in an object that doesn&#8217;t fit the requirements.</p>
<p>Yup, that&#8217;s right. You&#8217;re speechless.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/f/f-duck-typing-with-generic-constraints-and-why-you-will-be-speechless/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Validator: Build Rules and Messages Dynamically</title>
		<link>http://byatool.com/lessons/jquery-validator-build-rules-and-messages-dynamically/</link>
		<comments>http://byatool.com/lessons/jquery-validator-build-rules-and-messages-dynamically/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 15:20:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery Validator]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1907</guid>
		<description><![CDATA[Ok so here&#8217;s your typical code for the jQuery Validator: jQuery(ELEMENT_FORM).validate({ errorLabelContainer: ELEMENT_ERROR_DIV, wrapper: 'div', rules: { textboxEmailAddress: { required: true, email: true } }, messages: { textboxEmailAddress: { required: ERROR_EMAIL_ADDRESS_REQUIRED } }, .... As you can see, the elements like &#8220;textboxEmailAddress&#8221; are hard coded in there which means if that name changes in the [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so here&#8217;s your typical code for the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Validator</a>:</p>
<pre>  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: <span style="color: #800000;">'div'</span>,
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....</pre>
<p>As you can see, the elements like &#8220;textboxEmailAddress&#8221; are hard coded in there which means if that name changes in the markup, this breaks.  So the question is: How do I script the rules and messages so that I don&#8217;t have to hard code the element names?</p>
<p>Sorry was just waiting for you to finish you question.  Ok, here&#8217;s the answer and it has to do with how great Javascript is as a language.  (And oddly enough a trick I got from Python)</p>
<pre>  <span style="color: #0000ff;">var</span> validationRules = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Object</span>();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  <span style="color: #0000ff;">var</span> validationMessages = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Object</span>();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

  jQuery(ELEMENT_FORM).validate({
            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: <span style="color: #800000;">'div'</span>,
            rules: validationRules,
            messages: validationMessages,
            ....</pre>
<p>Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere.  How does this work?  Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:</p>
<pre>  someObject[<span style="color: #800000;">'somePropertyName'</span>] = <span style="color: #800000;">'hi'</span>;</pre>
<p>is just like:</p>
<pre>  someObject.somePropertyName = <span style="color: #800000;">'hi'</span>;</pre>
<p>In fact I&#8217;m pretty sure the <a href="http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx"> new Dynamic keyword</a> in C# works in the same manor.</p>
<p>Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree&#8230; to a point.  The constant does two things:</p>
<p>1) Removes a &#8220;magic string&#8221; from your code.</p>
<p>2) Makes it really easy to update that string if the element name/id is changed in the HTML.  Having only to look at one place to replace is a lot easier than 1+ places.</p>
<p>So there, smarty pants.  What you gots to say now?</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/jquery-validator-build-rules-and-messages-dynamically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Property Merge for Python Objects</title>
		<link>http://byatool.com/lessons/simple-property-merge-for-python-objects/</link>
		<comments>http://byatool.com/lessons/simple-property-merge-for-python-objects/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 18:57:11 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1904</guid>
		<description><![CDATA[Not sure if this is useful to other people, but then again if I cared that would make me human. So here&#8217;s a quick way to merge two objects in python: def mergeObjectProperties(objectToMergeFrom, objectToMergeTo): """ Used to copy properties from one object to another if there isn't a naming conflict; """ for property in objectToMergeFrom.__dict__: [...]]]></description>
			<content:encoded><![CDATA[<p>Not sure if this is useful to other people, but then again if I cared that would make me human.</p>
<p>So here&#8217;s a quick way to merge two objects in python:</p>
<pre><span style="color: #0000ff;">def</span> mergeObjectProperties(objectToMergeFrom, objectToMergeTo):
    """
    Used to copy properties from one object to another if there isn't a naming conflict;
    """
    <span style="color: #0000ff;">for</span> property <span style="color: #0000ff;">in</span> objectToMergeFrom.__dict__:
        <span style="color: #008000;">#Check to make sure it can't be called... ie a method.</span>
        <span style="color: #008000;">#Also make sure the objectobjectToMergeTo doesn't have a property of the same name.</span>
        <span style="color: #0000ff;">if</span> <span style="color: #0000ff;">not</span> callable(objectToMergeFrom.__dict__[property]) <span style="color: #0000ff;">and</span> <span style="color: #0000ff;">not</span> hasattr(objectToMergeTo, property):
            setattr(objectToMergeTo, property, getattr(objectToMergeFrom, property))

    <span style="color: #0000ff;">return</span> objectToMergeTo</pre>
<p>This is a good example of how the whole dynamic addition of properties happens in Python.  The objects in this example have a __dict__ property that is basically where the property/method/other stuff information is held in dictionary form.  What does this mean?  It means that if you use the setattr method you can then later call the property like you would normally.</p>
<pre>  setattr(someObject, <span style="color: #800000;">'someProperty'</span>, <span style="color: #800000;">'some value'</span>)

  someObject.someProperty == 'some value</pre>
<p>Knowing this is important as it allows you to really do some fun dynamic stuff that a lot of other languages just don&#8217;t allow.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/simple-property-merge-for-python-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Upload Image to Database and Show Image &#8220;Dynamically&#8221; Using a View</title>
		<link>http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/</link>
		<comments>http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 13:00:28 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Image]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=881</guid>
		<description><![CDATA[Oddly enough this came about from me wanting to do this, figuring it out, and then deciding not to bother with it. So there&#8217;s a possibility this will happen to you too. Well that&#8217;s not completely true. The first half where I was uploading and showing from a database, but showing an image through a [...]]]></description>
			<content:encoded><![CDATA[<p>Oddly enough this came about from me wanting to do this, figuring it out, and then deciding not to bother with it. So there&#8217;s a possibility this will happen to you too. Well that&#8217;s not completely true. The first half where I was uploading and showing from a database, but showing an image through a view to mimic the .ashx functionality of WebForms is still pretty useful.</p>
<p><strong>Saving the Image</strong></p>
<p>First off, here&#8217;s the look of the table:</p>
<pre><img class="alignnone size-full wp-image-883" title="Table" src="http://byatool.com/wp-content/uploads/2009/09/Table.PNG" alt="Table" width="357" height="172" /></pre>
<p>So pretty simple table. Most important parts are the ImageData and ContentType. Why? Well let&#8217;s look at the action needed to save the image:</p>
<pre>[<span style="color: #008080;">AcceptVerbs</span>(<span style="color: #008080;">HttpVerbs</span>.Post)]
<span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> Upload(<span style="color: #008080;">PhotoForSingleItem</span> photo)
{
  <span style="color: #008000;">//PhotoForSingleItem is just a class that has properties</span>
  <span style="color: #008000;">// Name and Alternate text.  I use strongly typed Views and Actions</span>
  <span style="color: #008000;">//  because I'm not a fan of using string to get the posted data from the</span>
  <span style="color: #008000;">//  FormCollection.  That just seems ugly and unreliable to me.</span>

  <span style="color: #008000;">//PhotoViewImage is just a Entityframework class that has</span>
  <span style="color: #008000;">// String Name, String AlternateText, Byte[] ActualImage,</span>
  <span style="color: #008000;">//  and String ContentType</span>
  <span style="color: #008080;">PhotoViewImage</span> newImage = <span style="color: #0000ff;">new</span> <span style="color: #008080;">PhotoViewImage</span>();
  <span style="color: #008080;">HttpPostedFileBase</span> file = Request.Files["OriginalLocation"];
  newImage.Name = photo.Name;
  newImage.Alt = photo.AlternateText;

  <span style="color: #008000;">//Here's where the ContentType column comes in handy.  By saving</span>
  <span style="color: #008000;">//  this to the database, it makes it infinitely easier to get it back</span>
  <span style="color: #008000;">//  later when trying to show the image.</span>
  newImage.ContentType = file.ContentType;

  <span style="color: #008080;">Int32</span> length = file.ContentLength;
  <span style="color: #008000;">//This may seem odd, but the fun part is that if</span>
  <span style="color: #008000;">//  I didn't have a temp image to read into, I would</span>
  <span style="color: #008000;">//  get memory issues for some reason.  Something to do</span>
  <span style="color: #008000;">//  with reading straight into the object's ActualImage property.</span>
  <span style="color: #0000ff;">byte</span>[] tempImage = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[length];
  file.InputStream.Read(tempImage, 0, length);
  newImage.ActualImage = tempImage ;

  newImage.Save();

  <span style="color: #008000;">//This part is completely optional.  You could redirect on success</span>
  <span style="color: #008000;">// or handle errors ect.  Just wanted to keep this simple for the example.</span>
  <span style="color: #0000ff;">return</span> View();
}</pre>
<p>And here&#8217;s the mark up to get this ball a rollin&#8217;:</p>
<pre>&lt;<span style="color: #800000;">form</span> <span style="color: #ff0000;">method</span><span style="color: #0000ff;">="post"</span> <span style="color: #ff0000;">enctype</span><span style="color: #0000ff;">="multipart/form-data"</span> <span style="color: #ff0000;">action</span><span style="color: #0000ff;">="Photo/Upload"</span>&gt;
  &lt;<span style="color: #800000;">div</span>&gt;
    &lt;<span style="color: #800000;">span</span>&gt;
     Name:
   &lt;/<span style="color: #800000;">span</span>&gt;
   &lt;<span style="color: #800000;">span</span>&gt;
     &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="text"</span> <span style="color: #ff0000;">id</span><span style="color: #0000ff;">="Name"</span> <span style="color: #ff0000;">name</span><span style="color: #0000ff;">="Name"</span> /&gt;
   &lt;/<span style="color: #800000;">span</span>&gt;
  &lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span>&gt;
    &lt;<span style="color: #800000;">span</span>&gt;
      Alternate Text:
    &lt;/<span style="color: #800000;">span</span>&gt;
    &lt;<span style="color: #800000;">span</span>&gt;
     &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="text"</span> <span style="color: #ff0000;">id</span><span style="color: #0000ff;">="AlternateText"</span> <span style="color: #ff0000;">name</span><span style="color: #0000ff;">="AlternateText"</span> /&gt;
    &lt;/<span style="color: #800000;">span</span>&gt;
  &lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span>&gt;
    &lt;<span style="color: #800000;">span</span>&gt;
      Image
    &lt;/<span style="color: #800000;">span</span>&gt;
    &lt;<span style="color: #800000;">span</span>&gt;
      &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="file"</span> <span style="color: #ff0000;">id</span><span style="color: #0000ff;">="OriginalLocation"</span> <span style="color: #ff0000;">name</span><span style="color: #0000ff;">="OriginalLocation"</span> /&gt;
    &lt;/<span style="color: #800000;">span</span>&gt;
  &lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span>&gt;
    &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="submit"</span> <span style="color: #ff0000;">value</span><span style="color: #0000ff;">="Upload"</span> /&gt;
  &lt;/<span style="color: #800000;">div</span>&gt;
&lt;/<span style="color: #800000;">form</span>&gt;</pre>
<p>Biggest thing to notice in the markup is the enctype=&#8221;multipart/form-data&#8221;. This is a must to upload images. It was something I was missing originally and annoyed the hell out of me.</p>
<p><strong>Showing the Image</strong></p>
<p>So now that we have a we to upload the image, how the hell do you use it? Well that&#8217;s not too hard. It just involves a new type of result, an action, and an img element.</p>
<p>So the first thing you need is an image result, and in using my superior intellect I came up with such a thing. And by superior intellect I mean I used <a href="http://stackoverflow.com/questions/636179/how-to-use-generic-handlers-ashx-in-asp-net-mvc">StackOverflow</a>. Oddly enough though, it&#8217;s actually the second post that I got it from and I changed it a little. However, it was very useful.</p>
<pre><span style="color: #0000ff;">using</span> System.Web;
<span style="color: #0000ff;">using</span> System.Web.Mvc;
<span style="color: #0000ff;">using</span> System.IO;

<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">ImageResult</span> : <span style="color: #008080;">ActionResult</span>
{
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> ContentType { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">byte</span>[] ImageBytes { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> SourceFilename { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

  <span style="color: #008000;">//This is used for times where you have a physical location</span>
  <span style="color: #0000ff;">public</span> ImageResult(<span style="color: #008080;">String</span> sourceFilename, <span style="color: #008080;">String</span> contentType)
  {
    SourceFilename = sourceFilename;
    ContentType = contentType;
  }

  <span style="color: #008000;">//This is used for when you have the actual image in byte form</span>
  <span style="color: #008000;">//  which is more important for this post.</span>
  <span style="color: #0000ff;">public</span> ImageResult(<span style="color: #0000ff;">byte</span>[] sourceStream, <span style="color: #008080;">String</span> contentType)
  {
    ImageBytes = sourceStream;
    ContentType = contentType;
  }

  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> ExecuteResult(<span style="color: #008080;">ControllerContext</span> context)
  {
    <span style="color: #0000ff;">var</span> response = context.HttpContext.Response;
    response.Clear();
    response.Cache.SetCacheability(<span style="color: #008080;">HttpCacheability</span>.NoCache);
    response.ContentType = ContentType;

    <span style="color: #008000;">//Check to see if this is done from bytes or physical location</span>
    <span style="color: #008000;">//  If you're really paranoid you could set a true/false flag in</span>
    <span style="color: #008000;">//  the constructor.</span>
    <span style="color: #0000ff;">if</span> (ImageBytes != null)
    {
      <span style="color: #0000ff;">var</span> stream = <span style="color: #0000ff;">new</span> <span style="color: #008080;">MemoryStream</span>(ImageBytes);
      stream.WriteTo(response.OutputStream);
      stream.Dispose();
    }
    <span style="color: #0000ff;">else</span>
    {
      response.TransmitFile(SourceFilename);
    }
  }
}</pre>
<p>And here&#8217;s how you use the actual result.</p>
<pre>[<span style="color: #008080;">AcceptVerbs</span>(<span style="color: #008080;">HttpVerbs</span>.Get)]
<span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> ShowPhoto(Int32 id)
{
  <span style="color: #008000;">//This is my method for getting the image information</span>
  <span style="color: #008000;">// including the image byte array from the image column in</span>
  <span style="color: #008000;">// a database.</span>
  <span style="color: #008080;">PhotoViewImage</span> image = <span style="color: #008080;">PhotoViewImage</span>.GetById(id);
  <span style="color: #008000;">//As you can see the use is stupid simple.  Just get the image bytes and the</span>
  <span style="color: #008000;">//  saved content type.  See this is where the contentType comes in real handy.</span>
  <span style="color: #008080;">ImageResult</span> result = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ImageResult</span>(image.ActualImage, image.ContentType);

  <span style="color: #0000ff;">return</span> result;
}</pre>
<p>And the markup would go a little sumthin&#8217; like dis:</p>
<pre>  &lt;<span style="color: #800000;">img</span> <span style="color: #ff0000;">src</span><span style="color: #0000ff;">="/Photo/ShowPhoto/1"</span> <span style="color: #ff0000;">alt</span><span style="color: #0000ff;">=""</span> /&gt;</pre>
<p>And now you too can upload an image to a database, show it, and then decide just to physically host the images anyway. Next post will be about how to use this with jQuery and asynchronously. I bet you can&#8217;t wait!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>jQuery Slide Menu&#8230;  Another Cause I Can Experiment</title>
		<link>http://byatool.com/ui/jquery-slide-menu-another-cause-i-can-experiment/</link>
		<comments>http://byatool.com/ui/jquery-slide-menu-another-cause-i-can-experiment/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 17:00:41 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Menu]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=827</guid>
		<description><![CDATA[So for no real reason at all I had it in my mind that I wanted to make a horizontal menu with jQuery that would work like that weird scrolling menu thing that Macs have. No idea what it&#8217;s called. So basically I don&#8217;t need it, have no reason for it, but damnit I&#8217;m going [...]]]></description>
			<content:encoded><![CDATA[<p>So for no real reason at all I had it in my mind that I wanted to make a horizontal menu with jQuery that would work like that weird scrolling menu thing that Macs have.  No idea what it&#8217;s called.  So basically I don&#8217;t need it, have no reason for it, but damnit I&#8217;m going to make it happen and I did it with only 3 things from <a href="http://www.jquery.com">jquery.com</a>; 1.3.2, ui 1.7.2, and jquery.timer . Now this is still rough in the sense it has no real styling but it works tried and true functionality wise.</p>
<p>The main idea is that there are two scroll arrows, one on each side, and X amount of divs. Now at the start, a certain amount of divs are hidden (global variable). When hovering over the left pager, for example, it causes one on the right to hide while one on the left appears giving the feeling of the items sliding.</p>
<p><a href="http://www.byatool.com/Hosted/LiveDemos/SlideMenu/SlideMenu.htm">EXAMPLE HERE!!11</a></p>
<p>The markup is simple, a holder with x number of elements that are &#8220;menuitems&#8221; and two pager divs.</p>
<pre>&lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="mainHolder"</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="leftPager green floatLeft"</span>&gt;&lt;&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft blue"</span>&gt;1&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft red"</span>&gt;2&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft yellow"</span>&gt;3&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft blue"</span>&gt;4&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft red"</span>&gt;5&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft yellow"</span>&gt;6&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="menuItem floatLeft blue"</span>&gt;7&lt;/<span style="color: #800000;">div</span>&gt;
  &lt;<span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="rightPager green floatLeft"</span>&gt;&gt;&lt;/<span style="color: #800000;">div</span>&gt;
&lt;/<span style="color: #800000;">div</span>&gt;</pre>
<p>I think from the classes you can tell what you need to know about them.</p>
<p>First thing we need from jQuery is methods to find various elements in the container when paging.</p>
<pre><span style="color: #008000;">//When using the left pager, it's important to find the first visible element
</span><span style="color: #008000;">//then find the item before it so that it can be shown.</span>
<span style="color: #0000ff;">function</span> getNextInLineBack(menuItems)
{
  <span style="color: #0000ff;">var</span> oneBefore = <span style="color: #0000ff;">null</span>;

  <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; menuItems.length; loopCounter++)
  {
    <span style="color: #0000ff;">if</span>(jQuery(menuItems[loopCounter]).is(<span style="color: #ff0000;">":visible"</span>) &amp;&amp; loopCounter &gt; 0)
    {
      oneBefore = jQuery(menuItems[loopCounter - 1 ]);
      <span style="color: #0000ff;">break</span>;
    }
  }

  <span style="color: #0000ff;">return</span> oneBefore;
}

<span style="color: #008000;">//Find the first visible element from the beginning.
</span><span style="color: #008000;">//This will be needed when paging right since it will have to be hidden</span>
<span style="color: #0000ff;">function</span> getFirstVisible(menuItems)
{
  <span style="color: #0000ff;">var</span> firstVisible = <span style="color: #0000ff;">null</span>;

  <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; menuItems.length; loopCounter++)
  {
    <span style="color: #0000ff;">if</span>(jQuery(menuItems[loopCounter]).is(<span style="color: #ff0000;">":visible"</span>) &amp;&amp; loopCounter &lt; menuItems.length - maximumToShow)
    {
        firstVisible = menuItems[loopCounter];
        <span style="color: #0000ff;">break</span>;
    }
  }
  <span style="color: #0000ff;">return</span> firstVisible;
} 

<span style="color: #008000;">//Get the last possible visible item
</span><span style="color: #008000;">/</span><span style="color: #008000;">/If the item is in an index less than the maximum number to show, then null is returned since there has to be no more or less than the maximumToShow.
</span><span style="color: #0000ff;">function</span> getLastVisible(menuItems)
{
  <span style="color: #0000ff;">var</span> lastVisible = <span style="color: #0000ff;">null</span>;
  <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = menuItems.length - 1; loopCounter &gt; maximumToShow - 1; loopCounter--)
  {
    <span style="color: #0000ff;">if</span>(jQuery(menuItems[loopCounter]).is(<span style="color: #ff0000;">":visible"</span>))
    {
      lastVisible = menuItems[loopCounter];
      <span style="color: #0000ff;">break</span>;
    }
  }

  <span style="color: #0000ff;">return</span> lastVisible;
}

<span style="color: #008000;">//Find the first visible from the end
</span><span style="color: #008000;">//Pretty simple, this will be important when paging left since this</span>
<span style="color: #008000;">//will be the next item to be hidden</span>
<span style="color: #0000ff;">function</span> getNextInLineFront(menuItems)
{
  <span style="color: #0000ff;">var</span> lastOne = <span style="color: #0000ff;">null</span>;

  <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = menuItems.length-1; loopCounter &gt; -1; loopCounter--)
  {
    <span style="color: #0000ff;">if</span>(jQuery(menuItems[loopCounter]).is(<span style="color: #ff0000;">":visible"</span>))
    {
      lastOne = menuItems[loopCounter + 1];
      <span style="color: #0000ff;">break</span>;
    }
  }

  <span style="color: #0000ff;">return</span> lastOne;
}</pre>
<p>Next is a method that is just used to stop having to repeat the same thing over and over when needing a list of all the menu items.</p>
<pre><span style="color: #0000ff;">function</span> getMenuItems(mainHolder)
{
  <span style="color: #0000ff;">return</span> jQuery(mainHolder).children(<span style="color: #ff0000;">".menuItem"</span>);
}</pre>
<p>Next is the method to handle what item to show and what item to hide when the pager has the mouse over it. Instead of having methods for the right and left pager, I just ended up having the methods for finding the item to hide and show sent through as parameters.</p>
<pre><span style="color: #0000ff;">function</span> showHideOnHover(pager, timer, getHideMethod, getShowMethod)
{
  <span style="color: #008000;">//This is just candy for changing the color of the pager when the mouse</span>
  <span style="color: #008000;">//is over it</span>
  jQuery(pager).removeClass(<span style="color: #ff0000;">"green"</span>);
  jQuery(pager).addClass(<span style="color: #ff0000;">"orange"</span>);

  <span style="color: #008000;">//Remember those methods I passed through, well here they</span>
  <span style="color: #008000;">//are in use.  I'm using them to get the item to hide and the item</span>
  <span style="color: #008000;">//to show along with the list of items.</span>
  <span style="color: #0000ff;">var</span> menuItems = getMenuItems(jQuery(pager).parent());
  <span style="color: #0000ff;">var</span> hide = getHideMethod(menuItems);
  <span style="color: #0000ff;">var</span> show = getShowMethod(menuItems);

  <span style="color: #008000;">//If neither is null, then go ahead and show/hide</span>
  <span style="color: #008000;">//If either one is null, something isn't right and the timer</span>
  <span style="color: #008000;">//needs to be stopped.... timer??  Well I'll get to that</span>
  <span style="color: #008000;">//next.</span>
  <span style="color: #0000ff;">if</span>(show != <span style="color: #0000ff;">null</span> &amp;&amp; hide != <span style="color: #0000ff;">null</span>)
  {
    jQuery(hide).hide( <span style="color: #ff0000;">"slide"</span>, { direction: <span style="color: #ff0000;">"right"</span> } , 0);
    jQuery(show).show( <span style="color: #ff0000;">"slide"</span>, { direction: <span style="color: #ff0000;">"left"</span> } , 100);
  }
  else
  {
    timer.stop();
  }
}</pre>
<p>Now for the method above the last one, this one involves the timer passed in the last method. This method actually sets the mouseover/mouseout events (aka hover). When mouseover, the timer is created and the showHideOnHover method is called every 500 units, that&#8217;s we&#8217;ll call tools, (Not sure how much that is, seems like a half second) after the first time it&#8217;s called. On mouseout, the timer is stopped, nulled out, and the pager changes it&#8217;s color.</p>
<pre><span style="color: #0000ff;">function</span> setPager(pager, hideMethod, showMethod)
{
  <span style="color: #008000;">//Making the timer variable "global" to the events so that I know
</span>  <span style="color: #008000;">//I have the same timer for both mouseover and mouseout.</span>
  <span style="color: #0000ff;">var</span> newTimer;
  pager.hover
  (
    <span style="color: #008000;">//Mouseover method
</span>    function()
    {
      var first = true;
      <span style="color: #008000;">//This sets the timer, consequently starting the method for the first time.
</span>      <span style="color: #008000;">//Why timer doesn't have a start method I don't know.  Ask jquery.com.
</span>      <span style="color: #008000;">//The first thing is just so that the first time around it runs right away,
</span>      <span style="color: #008000;">//then each call afterwards comes every 500 tools.
</span>      newTimer = jQuery.timer
                      (
                         0, <span style="color: #008000;">//First time through, runs after 0 tools.</span>
                         function(timer)
                         {
                           showHideOnHover(pager, timer, hideMethod, showMethod);
                           <span style="color: #008000;">//If this is the first time through, reset</span>
                           <span style="color: #008000;">//timer to run every 500 tools.</span>
                           <span style="color: #0000ff;">if</span>(first)
                           {
                              timer.reset(500);
                              first = <span style="color: #0000ff;">false</span>;
                           }
                         }
                       );
    },

    <span style="color: #008000;">//Mouseout method
</span>    <span style="color: #0000ff;">function</span>()
    {
      <span style="color: #008000;">//mouse is done, stop the timer</span>
      newTimer.stop();
      newTimer = <span style="color: #0000ff;">null</span>;
      jQuery(pager).addClass(<span style="color: #ff0000;">"green"</span>);
      jQuery(pager).removeClass(<span style="color: #ff0000;">"orange"</span>)
    }
  );
}</pre>
<p>Now for the method above the one&#8230; above. This is used to set the children of the passed in holder.</p>
<pre><span style="color: #0000ff;">function</span> setChildrenDivs(mainHolder)
{
  <span style="color: #008000;">//Get the items for the holder
</span>  <span style="color: #0000ff;">var</span> menuItems = getMenuItems(mainHolder);

  <span style="color: #008000;">//Hide all the items after the first X items (maximumToShow)</span>
  <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; menuItems.length; loopCounter++)
  {
    if(loopCounter &gt; maximumToShow - 1)
    {
      jQuery(menuItems[loopCounter]).hide();
    }
  }

  <span style="color: #008000;">//set the pagers.</span>
  setPager(jQuery(mainHolder).children(<span style="color: #ff0000;">".leftPager"</span>), getLastVisible, getNextInLineBack);
  setPager(jQuery(mainHolder).children(<span style="color: #ff0000;">".rightPager"</span>),getFirstVisible, getNextInLineFront);
}</pre>
<p>FINALLY THE END! This is the document.ready method used to set this whole joke in motion. maximumToShow is just how many items to show at a time and is global.</p>
<pre><span style="color: #0000ff;">var</span> maximumToShow = 5;

jQuery(document).ready
(
  <span style="color: #0000ff;">function</span>()
  {
    <span style="color: #008000;">//Find every holder on the page and set everything in motion.
</span>    <span style="color: #0000ff;">var</span> mainHolders = jQuery(<span style="color: #ff0000;">".mainHolder"</span>);
    <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; mainHolders.length; loopCounter++)
    {
      setChildrenDivs(mainHolders[loopCounter]);
    }
  }
);</pre>
<p>Why the timer? If you haven&#8217;t figured that out yet, well it&#8217;s because I had issues with how to get the menu to keep doing it&#8217;s thing as long as the user had his/her mouse over a pager. I didn&#8217;t want this to be a click menu because, let&#8217;s be honest, that would be much easier. So as is, the timer is started the moment the mouse is over a pager and hides/shows an item. Then every 500 tools the mouse is over the pager, it continues the hide/show until it runs out of items to show/hide. (End of the list)</p>
<p>Uhg that&#8217;s annoying to type out even with cut and paste so <a href="http://www.iamwebproject.com/BAT/SlideMenu.zip">I will host it here</a>.</p>
<p>I suppose the next part of this would have the items blow up or something when hovering over them but that should be much easier than this was.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/jquery-slide-menu-another-cause-i-can-experiment/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC:  Attributes and Semi Dynamic Check for Request Parameters</title>
		<link>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/</link>
		<comments>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 00:46:59 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=803</guid>
		<description><![CDATA[If I were self involved I would say something silly like IN THIS AWESOME POST but I&#8217;m not. However in this post that is awesome I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere&#8230; Sorry lost [...]]]></description>
			<content:encoded><![CDATA[<p>If I were self involved I would say something silly like <a href="http://byatool.com/index.php/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/">IN THIS AWESOME POST</a> but I&#8217;m not. However in <a href="http://byatool.com/index.php/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/">this post that is awesome</a> I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere&#8230; Sorry lost my track of thought. Watching the begining of Transformers&#8230; You know the part where it could have been good.</p>
<p>Anyway, I figured I&#8217;d add another debatable use for an attribute, the CheckForGivenRequest one. Basically in the other post I had something that was specific it was checking for, this is used if you are checking for a request parameter but you don&#8217;t want to make an attribute for each and every one of them.</p>
<pre>  <span style="color: #008000;">//This is so you can use it many times on the same method</span>
  <span style="color: #008000;">//I know, I know... duh</span>
  [<span style="color: #008080;">AttributeUsage</span>(<span style="color: #008080;">AttributeTargets</span>.Method, AllowMultiple = <span style="color: #0000ff;">true</span>)]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">CheckForGivenRequestAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
  {
    <span style="color: #008000;">//The constructor to set what should be looked for
</span>    <span style="color: #008000;">//Default amount is what it should be set if not there</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">CheckForGivenRequestAttribute</span>(<span style="color: #008080;">String</span> requestParameterName, <span style="color: #008080;">Object</span> defaultAmount)
    {
      DefaultAmount = defaultAmount;
      RequestParameterName = requestParameterName;
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);
      <span style="color: #008000;">//Check the extra request parameters (ie &amp;someId=1) for if it exists
</span>      <span style="color: #008000;">//If it doesn't exist, then add it</span>
      <span style="color: #0000ff;">if</span> (!filterContext.ActionParameters.ContainsKey(RequestParameterName))
      {
        filterContext.ActionParameters.Add(RequestParameterName, <span style="color: #0000ff;">null</span>);
      }

      <span style="color: #008000;">//If it's null set to the default
</span>      filterContext.ActionParameters[RequestParameterName] =
         filterContext.ActionParameters[RequestParameterName] ?? DefaultAmount;
    }

    <span style="color: #008000;">//Just the properties, nothing to see here.  Go away...</span>
    <span style="color: #0000ff;">private</span> Object DefaultAmount { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">private</span> String RequestParameterName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>And then the use of it:</p>
<pre>  [<span style="color: #008080;">CheckForGivenRequestAttribute</span>(<span style="color: #800000;">"someStupidId"</span>, 1)]
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> INeedAnExample(<span style="color: #008080;">Int32</span> someStupidId)
  {
    ...
  }</pre>
<p>Now you might ask why not make that attiribute generic to avoid boxing.</p>
<p><strong>Why not make that attribute generic to avoid boxing?</strong></p>
<p>Glad you asked. Turns out that you can&#8217;t make attributes generic. Aparrently <a href="http://stackoverflow.com/questions/294216/why-does-c-forbid-generic-attribute-types">it&#8217;s somwhat debatable why</a> but not possible at the time being. Besides, the ActionParameters collection is &lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">Object</span>&gt; anyhow, so at some point any stuct would be boxed anyhow.</p>
<p>On a side note, I never noticed this before, but when one of the non descript Autobots crashes near a pool, some kid is there to ask if he is the Tooth Fairy?  Seriously?  Are kids really that dumb?  Cause every picture I&#8217;ve seen of the Tooth Fairy has been a 20 foot tall metal thing with no discernible features.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Slide and Pairing a Div&#8217;s Hover With a Div&#8217;s Slide</title>
		<link>http://byatool.com/ui/jquery-slide-and-pairing-a-divs-hover-with-a-divs-slide/</link>
		<comments>http://byatool.com/ui/jquery-slide-and-pairing-a-divs-hover-with-a-divs-slide/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 19:19:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=749</guid>
		<description><![CDATA[So this could be filed under &#8220;I did it because I can&#8221; (which is a really good mantra in science&#8230;) and am not sure I&#8217;ll use it but it is useful in the concept. LIVE EXAMPLE HERE The idea is to set the hover on one div to show/hide another div WITHOUT having to use [...]]]></description>
			<content:encoded><![CDATA[<p>So this could be filed under &#8220;I did it because I can&#8221; (which is a really good mantra in science&#8230;) and am not sure I&#8217;ll use it but it is useful in the concept.</p>
<p><a href="http://www.byatool.com/Hosted/LiveDemos/SlideOnHover/SlideOnHover.htm">LIVE EXAMPLE HERE</a></p>
<p>The idea is to set the hover on one div to show/hide another div WITHOUT having to use some kind of id/name trick (as in setting the id to &#8220;divHide1&#8243;) and to have it be completely self setting in the .ready method. Why would this be at all useful? Say you want to roll through a list of things and generate the divs, but want to defer the jQuery until the page has loaded. And you don&#8217;t want to have to resort to:</p>
<pre>    <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">div</span> <span style="color: #ff0000;">id</span>="someDiv&lt;%= someId %&gt;"<span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span>div<span style="color: #0000ff;">&gt;</span></pre>
<p>like structure where you parse some identifier from the id property. Mostly because you have no idea how many someDiv1s there could be on the page. It could be a highly reused name (someDiv) and that could lead to a mess.</p>
<p>Also the reason &#8216;cuz. If you have any more questions of why after that answer, well you&#8217;re just being annoying.</p>
<p>Anywho, here&#8217;s the actual html for structure.</p>
<pre>   <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="mainDiv"</span><span style="color: #0000ff;">&gt;</span>
      <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="showDiv"</span> <span style="color: #ff0000;">id</span><span style="color: #0000ff;">="oneTop"&gt;</span>
        Kaneda?
      <span style="color: #0000ff;">&lt;</span><span style="color: #0000ff;">/</span><span style="color: #800000;">div</span><span style="color: #0000ff;">&gt;</span>
      <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="slideDiv"</span> <span style="color: #ff0000;">id</span><span style="color: #0000ff;">="one"&gt;</span>
        What do you see?!
      <span style="color: #0000ff;">&lt;</span><span style="color: #0000ff;">/</span><span style="color: #800000;">div</span><span style="color: #0000ff;">&gt;</span>
    <span style="color: #0000ff;">&lt;</span><span style="color: #0000ff;">/</span><span style="color: #800000;">div</span><span style="color: #0000ff;">&gt;</span>
    <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">div</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="clear"</span><span style="color: #0000ff;">&gt;&lt;</span><span style="color: #0000ff;">/</span><span style="color: #800000;">div</span><span style="color: #0000ff;">&gt;</span></pre>
<p>Now I get that this isn&#8217;t off a foreach, but it doesn&#8217;t take much to figure out that it&#8217;s easily made into a loop if you just loop it over and over. Why? Because first there are no ids or names so that you can&#8217;t have two of the same name and also because that chunk is self contained.</p>
<p>So what is going on there? Simple, you have a parent container that holds a div to hold and a div to hover over and the other that will be shown/hidden.</p>
<p>Here&#8217;s the styles involved just incase you care:</p>
<pre>    <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">style</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="text/css"&gt;</span>
        <span style="color: #800000;">.clear
</span>        {
        	<span style="color: #ff0000;">clear</span>:<span style="color: #0000ff;">both</span>;
        }

        <span style="color: #800000;">.leftDiv</span>
        {
        	<span style="color: #ff0000;">float</span>:<span style="color: #0000ff;">left</span>;
        }

        <span style="color: #800000;">.mainDiv</span>
        {
        	<span style="color: #ff0000;">margin</span>:<span style="color: #0000ff;">5px</span>;
        	<span style="color: #ff0000;">height</span>:<span style="color: #0000ff;">200px</span>;
        }

        <span style="color: #800000;">.rightDiv</span>
        {
        	<span style="color: #ff0000;">float</span>:<span style="color: #0000ff;">left</span>;
        }

        <span style="color: #800000;">.showDiv</span>
        {
        	<span style="color: #ff0000;">float</span>:<span style="color: #0000ff;">left</span>;
        	<span style="color: #ff0000;">margin-right</span>:<span style="color: #0000ff;">5px</span>;
        	<span style="color: #ff0000;">height</span>:<span style="color: #0000ff;">200px</span>;
        	<span style="color: #ff0000;">background-color</span>:<span style="color: #0000ff;">Silver</span>;
        }

        <span style="color: #800000;">.slideDiv</span>
        {
        	<span style="color: #ff0000;">background-color</span>:<span style="color: #0000ff;">Teal</span>;
        	<span style="color: #ff0000;">height</span>:<span style="color: #0000ff;">200px</span>;
        	<span style="color: #ff0000;">position</span>:<span style="color: #0000ff;">absolute</span>;
        	<span style="color: #ff0000;">float</span>:<span style="color: #0000ff;">left</span>;
        	<span style="color: #ff0000;">z-index</span>:<span style="color: #0000ff;">100</span>;
        }
    <span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">style</span><span style="color: #0000ff;">&gt;</span></pre>
<p>That doesn&#8217;t entirely matter, but it does to show the div &#8220;sliding&#8221; over another div. Kind of a little somethin&#8217; somethin&#8217; I threw in at no extra cost. Now for the jQuery:</p>
<p>First the method for setting the mouse over and out events for the show div, we turn to .hover:</p>
<pre>    <span style="color: #0000ff;">function</span> setHover(currentSlideDiv, currentStableDiv)
    {
      currentStableDiv.hover
      (
        <span style="color: #008000;">//first parameter is the method for showing the div on mouse over
</span>        <span style="color: #0000ff;">function</span>()
        {
          if (currentSlideDiv.is(<span style="color: #800000;">":hidden"</span>))
          {
            currentSlideDiv.show(<span style="color: #800000;">"slide"</span>, { direction: <span style="color: #800000;">"left"</span> }, 100);
          }
        },
        <span style="color: #008000;">//second parameter is the method for hiding the div on mouse out
</span>        <span style="color: #0000ff;">function</span>()
        {
          if (currentSlideDiv.is(<span style="color: #800000;">":visible"</span>))
          {
            currentSlideDiv.hide(<span style="color: #800000;">"slide"</span>, { direction: <span style="color: #800000;">"left"</span> }, 100);
          }
        }
      );
    };</pre>
<p>Now for the method that actually uses these:</p>
<pre>    <span style="color: #008000;">//This is used to take in one of the main divs and set all the
</span>    <span style="color: #008000;">//show and slide divs within.</span>
    <span style="color: #0000ff;">function</span> setChildrenDivs(mainDiv)
    {
      <span style="color: #008000;">//get all the show and slide dvis within the main div
</span>      <span style="color: #0000ff;">var</span> mainChildrenStableDiv = jQuery(mainDiv).children(<span style="color: #800000;">".showDiv"</span>);
      <span style="color: #0000ff;">var</span> mainChildrenSlide = jQuery(mainDiv).children(<span style="color: #800000;">".slideDiv"</span>);

      <span style="color: #008000;">//loop through the list of show divs</span>
      <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; mainChildrenStableDiv.length; loopCounter++)
      {
        <span style="color: #008000;">//Get the show div and it's corresponding slide div using the
</span>        <span style="color: #008000;">//two lists and the current counter.</span>
        <span style="color: #0000ff;">var</span> currentStableDiv = jQuery(mainChildrenStableDiv[loopCounter]);
        <span style="color: #0000ff;">var</span> currentSlideDiv = jQuery(mainChildrenSlide[loopCounter]);

         <span style="color: #008000;">//This is to make sure the slide is where it should be.
</span>         <span style="color: #008000;">//to the right of the show div.</span>
         <span style="color: #0000ff;">var</span> containerPosition = jQuery(currentStableDiv).position();
         jQuery(currentSlideDiv).css({ left: containerPosition.left + currentStableDiv.width() });
        <span style="color: #008000;">//Set the mouse over and the mouse out on the show div</span>
        setHover(currentSlideDiv, currentStableDiv);
      }
    }</pre>
<p>Now the final touch, the .ready method:</p>
<pre>    jQuery(document).ready
    (
      <span style="color: #0000ff;">function</span>()
      {
        <span style="color: #008000;">//hide all the slide divs
</span>        jQuery(<span style="color: #800000;">".slideDiv"</span>).hide();

        <span style="color: #008000;">//find all the parent divs
</span>        <span style="color: #0000ff;">var</span> mainDivs = jQuery(<span style="color: #800000;">".mainDiv"</span>);

        <span style="color: #008000;">//set the children</span>
        for (var loopCounter = 0; loopCounter &lt; mainDivs.length; loopCounter++)
        {
          setChildrenDivs(mainDivs[loopCounter]);
        }
      }
    );</pre>
<p>And boom, now you have multiple show/hide (Slide in this instance). Now if I could just find a use for it&#8230;</p>
<p>Oh yeah and you&#8217;ll need <a href="http://jquery.com/">jQuery 1.3.2</a> and <a href="http://jqueryui.com/">jQuery ui 1.7.2</a> to use this.  At least those are the versions I know this works with.</p>
<p><strong>Update:  Due to popular demand&#8230; one person&#8230; <a href="http://www.byatool.com/Hosted/LiveDemos/SlideOnHover.zip">Source can be found here.</a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/jquery-slide-and-pairing-a-divs-hover-with-a-divs-slide/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</title>
		<link>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/</link>
		<comments>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 17:11:19 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[.Net Issues]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=731</guid>
		<description><![CDATA[So in typical tool fashion I posted this little gem without realizing a glaring error&#8230; the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this: Expression&#60;Func&#60;K, IComparable&#62;&#62; orderBy The problem comes in when the entire [...]]]></description>
			<content:encoded><![CDATA[<p>So in typical tool fashion I posted this <a href="http://byatool.com/index.php/c/entity-framework-reusable-paging-method/">little gem</a> without realizing a glaring error&#8230; the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this:</p>
<pre>    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;K, <span style="color: #008080;">IComparable</span>&gt;&gt; orderBy</pre>
<p>The problem comes in when the entire expression is run, meaning when Entity Frame work takes:</p>
<pre>    context.Select(selectMethod).Where(whereClause).OrderBy(orderBy).ToList();</pre>
<p>and creates SQL out of it. Entity Framework doesn&#8217;t really know how to handle IComparable as it has not primitive/sql type to match to it. Why it can&#8217;t see the underlying type of say DateTime, no idea, but this is life.</p>
<p>So this should be an easy fix, right? Eh&#8230; yeah. First I thought instead of IComparable I could just convert to some kind of primitive type so that the EF could be on it&#8217;s merry. Not so much. Turns out this probably isn&#8217;t possible.</p>
<p>Well thanks to a push from <a href="http://stackoverflow.com/users/137624/ben-m">Ben M</a> at <a href="http://stackoverflow.com/questions/1145847/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primit">The O Flow</a> I got to thinking about how to attack this. Instead of sending in an expression for the order by, why not send in a method that would take in a query and tell it how to order itself. Sounds hard right? (If not then you&#8217;re obviously too cool for this school) Well it&#8217;s not, just a different way to think about it.</p>
<p>Right off the bat, the change to the method signature would look like this:</p>
<p>Old order by parameter signature:</p>
<pre>    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;K, <span style="color: #008080;">IComparable</span>&gt;&gt; orderBy</pre>
<p>New order by parameter signature:</p>
<pre>    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">IQueryable</span>&lt;T&gt;, <span style="color: #008080;">IOrderedQueryable</span>&lt;T&gt;&gt; orderBy</pre>
<p>So what does that mean? It means that I am going to supply the method with a method that will take in a query and return an ordered query&#8230; well not ordered yet per se but the blueprint on how to order when that time comes around. Now here&#8217;s how that&#8217;s used:</p>
<p>First you need the query:</p>
<pre>    <span style="color: #0000ff;">var</span> initialQuery = query
    .Where
    (
        somethingEqualsSomething
    );</pre>
<p>Then you apply the orderby method, and in the case of the original paging method, the paging too:</p>
<pre>    <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();</pre>
<p>So overall, doesn&#8217;t look too much different. Just instead of supplying the OrderBy method with a Func, you give a method that creates an ordered query.</p>
<p>How would you use this? Remember the signature was (whereClause, selectClause, orderBy, pageNumber, numberToShow, realPage, totalCountOfPages)</p>
<pre>    Tools.GetListForGrid
    (
      tool =&gt; tool.EntityId == userId,
      tool =&gt; <span style="color: #0000ff;">new</span> { Name = tool.Name },  <span style="color: #008000;">//Select Clause, I'll get to that next
      </span>toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),  <span style="color: #008000;">//OrderBy</span>
      ...
    )</pre>
<p>Two things you might notice. One would be the OrderBy signature:</p>
<pre>   toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),</pre>
<p>What the hell? Remember the method you are sending takes in a query and returns an ordered query. toolOuter is your query, toolOuter.OrderBy(toolInner =&gt; toolInner .Name) is your blueprint (IOrderedQueryable) on how it should be queried.</p>
<p>Second thing is that when I showed how to use the OrderBy method above:</p>
<pre>    <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();</pre>
<p>I didn&#8217;t include the select clause. Partially because I didn&#8217;t want to complicate it yet, partially because it has it&#8217;s own issue. If you&#8217;re like me, you use the <a href="http://byatool.com/index.php/lessons/beyond-the-wall/">select clause a lot</a>. Why? Because it limits the amount of information you take from the database. Say if you are trying to fill a drop down list, why select an entire Tool object (Which could have a ton of mapped properties) when all you need is Id and Name? Seems silly. That&#8217;s where the Select clause comes in. Now the issue is where to put the order by. You would think after the select clause, since you want to sort on only what you are selecting. Problem is, with paging that gets screwed up. The way sql server &#8220;pages&#8221; is that it selects twice.</p>
<p>Select all the things that match this where clause.<br />
Select a certain number of items from that starting at X.</p>
<p>The first select creates a dataset with row numbers, and the second one selects the items based on those row numbers. IE take 5 starting at row 5. Now the way the EF handles the order by is to grab the info you need from the Select (Ordered by something&#8230; you don&#8217;t get to choose) and THEN order and grab. As you can guess this may not give the needed results. So how can this be solved? Order before the select as witnessed in the new and improved method:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList</span>&lt;K&gt; <span style="color: #000000;">GetListForGrid</span>&lt;T, K&gt;
(
    <span style="color: #0000ff;">this</span> ObjectQuery&lt;T&gt; query,
    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, <span style="color: #008080;">Boolean</span>&gt;&gt; somethingEqualsSomething,
    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, K&gt;&gt; selectClause,
    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">IQueryable</span>&lt;T&gt;, <span style="color: #008080;">IOrderedQueryable</span>&lt;T&gt;&gt; orderBy,
    <span style="color: #008080;">Int32</span> pageNumber,
    <span style="color: #008080;">Int32</span> numberToShow,
    <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: #008080;">IList</span>&lt;K&gt; returnValue;

    <span style="color: #008080;">Int32</span> totalItemCount =
        query
        .Count
        (
          somethingEqualsSomething
        );

    totalCountOfPages = Methods.TotalCountOfPages(totalItemCount, numberToShow);
    realPage = Methods.GetRealPage(totalCountOfPages, pageNumber);

    <span style="color: #0000ff;">var</span> initialQuery =
      query
      .Where
      (
        somethingEqualsSomething
      );

   <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Select
      (
        selectClause
      )
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

      <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>And usage:</p>
<pre>    Tools.GetListForGrid
    (
       tool =&gt; tool.Id == userId,
       tool =&gt; new { Name = tool.Name },  <span style="color: #008080;"><span style="color: #008000;">//Select Clause</span>
</span>       toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),  <span style="color: #008000;">//OrderBy</span>
       pageNumber,
       amountToShow,
       out realPage,
       out totalCountOfPages
    );</pre>
<p>Now this one actually works with Entity Framework and not just Linq to objects like the last one.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC, jQuery, JSon, and paging&#8230;  how&#8217;s that for a SOE title?</title>
		<link>http://byatool.com/ui/aspnet-mvc-jquery-json-and-paging-hows-that-for-a-soe-title/</link>
		<comments>http://byatool.com/ui/aspnet-mvc-jquery-json-and-paging-hows-that-for-a-soe-title/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 15:44:11 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=721</guid>
		<description><![CDATA[One of the things I&#8217;ve come to realize is how easy it easy to do a lot of things with these three buzzwords. In fact, I&#8217;m pretty convinced it&#8217;s so easy that it&#8217;s actually complex and I am a genius. Not buying it? Neither am I. So for an experiement the other day I decided [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things I&#8217;ve come to realize is how easy it easy to do a lot of things with these three buzzwords. In fact, I&#8217;m pretty convinced it&#8217;s so easy that it&#8217;s actually complex and I am a genius. Not buying it? Neither am I.</p>
<p>So for an experiement the other day I decided to try my hand at some sort of dynamic grid using jQuery&#8217;s ajax fun and JSon. Just so happens that this works really well with MVC&#8217;s REST like makeup. Don&#8217;t know what REST is? On a very tool level, it&#8217;s using a url and a command to tell the server what to do. So something like:</p>
<p>www.byatool.com/users/dostuff</p>
<p>Could mean either get all users (if using get) or create a user (If using post). And yes that is probably a ridiculously simplistic view so I&#8217;d suggest consulting the <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">Wikitruth</a>. In an MVC sense this would be:</p>
<p>Controller: Users<br />
Action: dostuff</p>
<p>Now most likely your Get All Users action isn&#8217;t going to the same as your Add A User action, but it was just a stupid example ok?</p>
<p>However, with jQuery what this means is you have a simple url that it can call and get information from, making it incredibly easy to set up a dynamic grid.</p>
<p>So first off, lets say I have a Forum controller with an action of IndexJquery&#8230; yeah I know cheesy name, but it gets the job done. Basically the method IndexJquery would have to take in a page number and optionally (And for this example) how many items to show along with a sort. With that it should return a JSon &#8220;object&#8221; that will be in this example holds first page, last page, next page, previous page, sortBy, and some kind of list of stuff. (For the two people actually reading this, comment if you want the c# code. It&#8217;s really just basic MVC stuff.)</p>
<p>The markup for this is pretty simple. I have a div to hold the grid, four directional divs that work as buttons (First, Previous, Next, Last), and two div &#8220;butons&#8221; for how many items to show.</p>
<pre>    &lt;div&gt;
        &lt;div id="divHolder"&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;div id="divFirstPage" class="divLink floatLeft"&gt;
            &lt;&lt;
        &lt;/div&gt;
        &lt;div id="divPreviousPage" class="divLink floatLeft"&gt;
            &lt;
        &lt;/div&gt;
        &lt;div id="divNextPage" class="divLink floatLeft"&gt;
            &gt;
        &lt;/div&gt;
        &lt;div id="divLastPage" class="divLink floatLeft"&gt;
            &gt;&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="clear"&gt;&lt;/div&gt;
    &lt;div&gt;
        &lt;div id="divAmountToShowOne" class="divLink floatLeft"&gt;
            1
        &lt;/div&gt;
        &lt;div id="divAmountToShowFive" class="divLink floatLeft"&gt;
            5
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="clear"&gt;&lt;/div&gt;</pre>
<p>As you can see exactly as advertised.</p>
<p>Ready for the call? It&#8217;s waaaaay hard:</p>
<pre>        <span style="color: #0000ff;">function</span> getGrid(pageNumberIn, amountToShowIn, sortByIn)
        {
            jQuery.getJSON
            (
               <span style="color: #008000;">//This is the url for the information I need
</span>               <span style="color: #800000;">"http://www.someurl.com/Forum/IndexJquery/"</span>,
               <span style="color: #008000;">//this is the construction of the "object" to send... really this just
               //means that I have a method somewhere looking for pageNumber,
               //amountToShow, and sortBy</span>
               {
                   pageNumber: pageNumberIn,
                   amountToShow: amountToShowIn,
                   sortBy: sortByIn
               },
               <span style="color: #008000;">//This is the method to call once this ajax transaction has completed...
</span>               <span style="color: #008000;">//transaction may not be the best word.  Basically it has to be a method
</span>               <span style="color: #008000;">//that takes in the result from the getJSon call
</span>               returned
            );
        }</pre>
<p>Next would be the script to actually create the grid. Looks verbose, but most likely thats because I didn&#8217;t refactor much.</p>
<pre>    <span style="color: #0000ff;">function</span> returned(jsonObject)
    {
        <span style="color: #008000;">//Have to remove all the previous click event handlers since because
</span>        <span style="color: #008000;">//this is all client side, there's no "refresh" and therefore the object
</span>        <span style="color: #008000;">//is still in memory.  So even though I might call the method to get the
</span>        <span style="color: #008000;">//information, the "objects" are still in memory.</span>
        jQuery(<span style="color: #800000;">"#divFirstPage"</span>).unbind(<span style="color: #800000;">"click"</span>);
        jQuery(<span style="color: #800000;">"#divLastPage"</span>).unbind(<span style="color: #800000;">"click"</span>);
        jQuery(<span style="color: #800000;">"#divNextPage"</span>).unbind(<span style="color: #800000;">"click"</span>);
        jQuery(<span style="color: #800000;">"#divPreviousPage"</span>).unbind(<span style="color: #800000;">"click"</span>);
        jQuery(<span style="color: #800000;">"#divAmountToShowOne"</span>).unbind(<span style="color: #800000;">"click"</span>);
        jQuery(<span style="color: #800000;">"#divAmountToShowFive"</span>).unbind(<span style="color: #800000;">"click"</span>);

        <span style="color: #008000;">//Ok so now that the event is not being listened to, set up the listeners</span>
        <span style="color: #008000;">//The idea is to call that getGrid method and pass in the values straight</span>
        <span style="color: #008000;">//off the previously returned json object.  Using jQuery's easy .click method
</span>        <span style="color: #008000;">//makes this so simple.
</span>        jQuery(<span style="color: #800000;">"#divFirstPage"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(jsonObject.FirstPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery(<span style="color: #800000;">"#divPreviousPage"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(jsonObject.PreviousPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery(<span style="color: #800000;">"#divNextPage"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(jsonObject.NextPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery(<span style="color: #800000;">"#divLastPage"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(jsonObject.LastPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery(<span style="color: #800000;">"#divAmountToShowOne"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(0, 1, jsonObject.SortBy); })
        jQuery(<span style="color: #800000;">"#divAmountToShowFive"</span>).click(<span style="color: #0000ff;">function</span>() { getGrid(0, 5, jsonObject.SortBy); })

        <span style="color: #008000;">//Again since this is client side, the divHolder "object" still is holding
</span>        <span style="color: #008000;">//the previous results.  These have to be cleared.
</span>        jQuery(<span style="color: #800000;">"#divHolder"</span>).children().remove();

        <span style="color: #008000;">//Create the table and loop through the list.
</span>        <span style="color: #0000ff;">var</span> mytable = document.createElement(<span style="color: #800000;">"table"</span>);
        <span style="color: #0000ff;">var</span> mytablebody = document.createElement(<span style="color: #800000;">"tbody"</span>);

        <span style="color: #0000ff;">for</span> (loopCounter = 0; loopCounter &lt; jsonObject.ListForViewing.length; loopCounter++)
        {
           <span style="color: #0000ff;">var</span> currentItem = something.ListForViewing[loopCounter];
           <span style="color: #0000ff;">var</span> mycurrent_row = document.createElement(<span style="color: #800000;">"tr"</span>);

           <span style="color: #0000ff;">var</span> mycurrent_cell = document.createElement(<span style="color: #800000;">"td"</span>);
           <span style="color: #0000ff;">var</span> currentText = document.createTextNode(currentItem.ForumName);
           mycurrent_cell.appendChild(currentText);
           mycurrent_row.appendChild(mycurrent_cell);

           mytablebody.appendChild(mycurrent_row);
        }

        mytable.appendChild(mytablebody);
        <span style="color: #008000;">//Don't forget to add the table to the div!!11
</span>        jQuery(<span style="color: #800000;">"#divHolder"</span>).append(mytable);
        <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span>;
    }</pre>
<p>And boom. So easy even a ca&#8230; tool can do it. Now if you want this grid to come preloaded, it&#8217;s pretty easy:</p>
<pre>
    jQuery(document).ready
    (
        <span style="color: #0000ff;">function</span> setPage()
        {
            getGrid(0, 10, null);
        }
    )</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/aspnet-mvc-jquery-json-and-paging-hows-that-for-a-soe-title/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery: Add a Pop Up Div to a Link Dynamically</title>
		<link>http://byatool.com/ui/556/</link>
		<comments>http://byatool.com/ui/556/#comments</comments>
		<pubDate>Mon, 16 Mar 2009 14:50:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=556</guid>
		<description><![CDATA[So as an exercise to learn more about jQuery, I decided to redo this little gem using jQuery. Have to say though only technically XHTML compliant, it worked out much better and with less code. So the idea is to have something really easy for non programmers (You know, lesser people) to be able to [...]]]></description>
			<content:encoded><![CDATA[<p>So as an exercise to learn more about jQuery, I decided to redo this <a href="http://byatool.com/index.php/ui/add-a-pop-up-div-to-a-link-dynamically">little gem</a> using jQuery. Have to say though only technically XHTML compliant, it worked out much better and with less code. So the idea is to have something really easy for non programmers (You know, lesser people) to be able to have a pop up comment added to some chunk of text on a web site. What I came up with before was ok but kind of annoying since it looked like this:</p>
<pre>&lt;<span style="color: #800000;">a</span> <span style="color: #ff0000;">onclick</span><span style="color: #0000ff;">="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');"</span> <span style="color: #ff0000;">href</span><span style="color: #0000ff;">="www.byatool.com"</span>&gt;word.&lt;<span style="color: #800000;">/a</span>&gt;</pre>
<p>Kind of annoying since I would have to explain that &#8217;1&#8242; is the name and it has to be unique for every one of <a class="showItLink" href="http://www.byatool.com" xmlns:comment="Hahaha... yeah they'll make them unique.  Really.  People aren't lazy.">these</a>, this isn&#8217;t really understood by those people, and well it just seems more complicated then it needs to be. So what if I told you it could look like this?</p>
<pre>&lt;<span style="color: #800000;">a</span> <span style="color: #ff0000;">href</span><span style="color: #0000ff;">="http://www.byatool.com"</span> <span style="color: #ff0000;">class</span><span style="color: #0000ff;">="showItLink"</span> <span style="color: #ff0000;">xmlns:comment</span><span style="color: #0000ff;">="hihihi"</span>&gt;HI&lt;<span style="color: #800000;">/a</span>&gt;</pre>
<p>Gorsh, that seems even better and it works in both IE and Firefox&#8230; which might be a first for this site and anything javascript. First let&#8217;s get the css out of the way, shall we?</p>
<pre>    .<span style="color: #800000;">showItLink</span>
    {
    }

    .<span style="color: #800000;">postComment</span>
    {
        <span style="color: #ff0000;">background-color</span>:<span style="color: #0000ff;">Gray</span>;
        <span style="color: #ff0000;">border-color</span>:<span style="color: #0000ff;">Black</span>;
        <span style="color: #ff0000;">border-style</span>:<span style="color: #0000ff;">dotted</span>;
        <span style="color: #ff0000;">border-width</span>:<span style="color: #0000ff;">thin</span>;
        <span style="color: #ff0000;">color</span>:<span style="color: #0000ff;">White</span>;
        <span style="color: #ff0000;">margin-right</span>:<span style="color: #0000ff;">3px</span>;
        <span style="color: #ff0000;">padding</span>:<span style="color: #0000ff;">3px</span>;
        <span style="color: #ff0000;">position</span>:<span style="color: #0000ff;">absolute</span>;
        <span style="color: #ff0000;">text-decoration</span>:<span style="color: #0000ff;">none</span>;
        <span style="color: #ff0000;">z-index</span>:<span style="color: #0000ff;">50</span>;
    }</pre>
<p>Most of the is just for looks, but like the older example I&#8217;ve called upon the power of <a href="http://byatool.com/index.php/ui/jquery-position-absolute-and-how-to-make-it-all-work">position:absolute</a> and z-index well that&#8217;s just pulling it in front of everything else.</p>
<p>Next part will be the actual code, and if you take the method <a class="showItLink" href="http://www.byatool.com" xmlns:comment="ANOTHER PLUG AHHHHH!!!11">from</a> <a href="http://byatool.com/index.php/ui/jquery-position-absolute-and-how-to-make-it-all-work">THE POSITION ABSOLUTE POST</a></p>
<pre>    <span style="color: #0000ff;">function</span> SetTopAndLeft(parentContainer, elementToSet)
    {
        <span style="color: #0000ff;">var</span> containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }</pre>
<p>and add in a simple span creation method:</p>
<pre>    <span style="color: #0000ff;">function</span> CreateDiv(innerText, cssClass)
    {
        <span style="color: #0000ff;">var</span> spanToAdd;

        spanToAdd = document.createElement(<span style="color: #ff0000;">'span'</span>);
        spanToAdd.className = cssClass;
        spanToAdd.innerHTML = innerText;

        <span style="color: #0000ff;">return</span> spanToAdd;
    }</pre>
<p>you&#8217;re ready for the actual fun part&#8230; making sure something pops up when the link is clicked.</p>
<pre>jQuery(document).ready  <span style="color: #008000;">//Everything inside this will load as soon as the DOM is loaded and before the page contents are loaded.</span><a href="http://www.learningjquery.com/2006/09/introducing-document-ready"><span style="color: #008000;">*</span></a>
(
    <span style="color: #0000ff;">function</span>()  //this is the start of an anonymous method
    {
        jQuery(<span style="color: #800000;">".showItLink"</span>).click <span style="color: #008000;">//find all things with the .showItLink class and assign the click event to the next anonymous method
        </span>(
            <span style="color: #0000ff;">function</span>(event) <span style="color: #008000;">//this is the start of an anonymous method for the click event</span>
            {
                <span style="color: #0000ff;">var</span> containerPosition;
                <span style="color: #0000ff;">var</span> createdSpan;
                <span style="color: #0000ff;">var</span> comment;

                comment = jQuery(this).attr(<span style="color: #800000;">"xmlns:comment"</span>);  <span style="color: #008000;">//Get the value from the comment attribute on the link.</span>
                createdSpan = jQuery(this).children(<span style="color: #800000;">".postComment"</span>); <span style="color: #008000;">//Find a possible span already attached to the link if it exists.  The span is of class 'postComment'</span>

                <span style="color: #0000ff;">if</span> (createdSpan.length == 0)  <span style="color: #008000;">//span doesn't exist</span>
                {
                    createdSpan= CreateDiv(comment, <span style="color: #800000;">"postComment"</span>);  <span style="color: #008000;">//create the span</span>
                    jQuery(this).append(createdSpan);  <span style="color: #008000;">//Add the span to the link</span>
                    jQuery(this).children(<span style="color: #800000;">".postComment"</span>).hide();  <span style="color: #008000;">//Make sure the new span is hidden
</span>                }
                SetTopAndLeft(this, createdSpan);  <span style="color: #008000;">//Set the position of the span</span>
                jQuery(createdDiv).toggle();  <span style="color: #008000;">//This will hide if it's showing, show if it's hidden... kind of nice huh?</span>

                event.preventDefault();  <span style="color: #008000;">//Equivalent to false.  Need this for Firefox.</span>
            }
        );
    }
);</pre>
<p>And boom you have something that works. Hooray.</p>
<p>Couple things of note:</p>
<p>.Hide &#8211; At first I though this would screw up my class for the span by removing the current class and adding display:none. Turns out it doesn&#8217;t harm the original class. Kind of nice.</p>
<p>.Toggle() &#8211; This is really nice. It will hide if it is showing and show if hidden. Stupid easy to use and is pretty effective. Just like .Hide, the class of the element is not harmed.</p>
<p>$ versus jQuery &#8211; Some people might notice that I am not using the short hand $ for my jQuery calls. Turns out that it might be safer this way. There are other javascript libraries that use the $ short hand like prototype. I ran into this with <a class="showItLink" href="http://byatool.com" xmlns:comment="Go figure...">WordPress </a>since it uses both jQuery and Prototype and blocks jQuery from using $ since it could conflict with other libraries. Weeeee!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/556/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQuery, Position : Absolute, and How to Make It All Work</title>
		<link>http://byatool.com/ui/jquery-position-absolute-and-how-to-make-it-all-work/</link>
		<comments>http://byatool.com/ui/jquery-position-absolute-and-how-to-make-it-all-work/#comments</comments>
		<pubDate>Fri, 13 Mar 2009 20:39:59 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=549</guid>
		<description><![CDATA[This is a really quick one but when I was taking my cheesy pop up and reworking it using JQuery (After Andre the Annoying wouldn&#8217;t shut up about it), I ran into a fun problem: position:absolute wasn&#8217;t working like it should. You know &#8220;absolute is positioned at the specified coordinates relative to its containing block.&#8221;. [...]]]></description>
			<content:encoded><![CDATA[<p>This is a really quick one but when I was taking <a href="http://byatool.com/index.php/ui/add-a-pop-up-div-to-a-link-dynamically">my cheesy pop up</a> and reworking it using <a href="http://docs.jquery.com/Main_Page">JQuery</a> (After Andre the Annoying wouldn&#8217;t shut up about it), I ran into a fun problem: position:absolute wasn&#8217;t working like it should. You know &#8220;absolute is positioned at the specified coordinates relative to its containing block.&#8221;. Meaning it should at worst show up within it&#8217;s container, where ever that is. Now IE is fine with that and the thing was showing up well:</p>
<pre><img title="absolutepositionie" src="http://byatool.com/wp-content/uploads/2009/03/absolutepositionie.png" alt="absolutepositionie" width="247" height="49" /></pre>
<p>Firefox? Not so much:</p>
<pre><img title="absolutepositionfirefox" src="http://byatool.com/wp-content/uploads/2009/03/absolutepositionfirefox.png" alt="absolutepositionfirefox" width="280" height="70" /></pre>
<p>Well&#8230; turns out JQuery pretty much does it for me. With a simple method, you can set one element&#8217;s position relative to a parent&#8217;s position:</p>
<pre>    <span style="color: #0000ff;">function</span> SetTopAndLeft(parentContainer, elementToSet)
    {
        <span style="color: #0000ff;">var</span> containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }</pre>
<p>Really simple, you get the position of the parent container and you set the child element&#8217;s top and left to it. Or in this case, I have it just off since hiding the parent container could be problematic. (Say if the parent container is a link AND NOW YOU CAN&#8217;T FIND IT TO CLICK ON IT AND THINGS HAPPEN BAD THINGS AND THE WORLD EXPLODES BECAUSE OF YOU!)</p>
<p>And boom, you can for once be a winner just like me.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/jquery-position-absolute-and-how-to-make-it-all-work/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Add a Pop Up Div to a Link Dynamically</title>
		<link>http://byatool.com/ui/add-a-pop-up-div-to-a-link-dynamically/</link>
		<comments>http://byatool.com/ui/add-a-pop-up-div-to-a-link-dynamically/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 19:30:36 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=523</guid>
		<description><![CDATA[Sometimes in life you have to ask &#8220;should I do this&#8221;, this is not one of those times. The idea is simple, click on a link and a div appears over the link with some kind of message in it. Kind of like being able to add a pop up note to a word. If [...]]]></description>
			<content:encoded><![CDATA[<p>    Sometimes in life you have to ask &#8220;should I do this&#8221;, this is not one of those times. The idea is simple, click on a link and a div appears over the link with some kind of message in it. Kind of like being able to add a pop up note to a <a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a> If you are absolutely amazed by that, don&#8217;t be afraid. Most likely you&#8217;ll die soon from forgetting to breathe. However, if you are just slightly curious as to why and how, keep reading.</p>
<p>    So why did I do this? Well it started with the idea of having something simple for a blog that has multiple authors: What if other authors could add notes to someone&#8217;s post in the post. Well the idea of using some kind of text change (Like italics) sounded lame. I wanted something easy that could be replicated quickly and wouldn&#8217;t be visible unless needed. Thus the onClick idea. Now the next problem I had was the class needed for the style sheet. As you can see, when the div is shown, it doesn&#8217;t displace any of the items on the page. This is because I am using position:absolute and a high z-index. This allows for the div to lay on top of other things and not touch them. Problem with absolute is that it basicaly plants the div in relation to it&#8217;s parent container. Now that whole parent container thing seems to be up for interpretation when you are talking about browsers. Each seems to deal with it the way it sees fit.</p>
<p>    Originally I had it as a div that would contain this new div. This was a pain in the -ss. In IE it showed up over the div, FireFox not so much. So the next thought was to create a div to hold the div that held the div. Something that isn&#8217;t exactly &#8220;user friendly&#8221; to be sure. Then it hit me, maybe I could put this in a link. After all, people who are viewing the blog would understand it&#8217;s something they can click on (Provided I don&#8217;t screw with the link styles too much) and it&#8217;s easy for non coders to copy and paste.</p>
<p>So on to the promised land. First I&#8217;ll just get the CSS out of the way since it&#8217;s absolutely needed but needs little explanation:</p>
<pre>.<span style="color: #ff0000;">hidePostComment</span>
{
    <span style="color: #0000ff;">visibility</span>:hidden;
    <span style="color: #0000ff;">position</span>: absolute;
    <span style="color: #0000ff;">z-index</span>:-100;
}

.<span style="color: #ff0000;">showPostComment</span>
{
    <span style="color: #0000ff;">background-color</span>:Gray;
    <span style="color: #0000ff;">border-color</span>:Black;
    <span style="color: #0000ff;">border-style</span>:dotted;
    <span style="color: #0000ff;">border-width</span>:thin;
    <span style="color: #0000ff;">color</span>:White;
    <span style="color: #0000ff;">margin-right</span>:3px;
    <span style="color: #0000ff;">padding</span>:3px;
    <span style="color: #0000ff;">position</span>:absolute;
    <span style="color: #0000ff;">text-decoration</span>:none;
    <span style="color: #0000ff;">visibility</span>:visible;
    <span style="color: #0000ff;">width</span>:100px;
    <span style="color: #0000ff;">z-index</span>:10;
}</pre>
<p>.hidePostComment</p>
<p>    As you can see, I&#8217;ve screwed with the z-index, visibility, and position. Position I&#8217;ve already explained, and I think you can understand why visibility is hidden with this class. However, z-index might not be something you know about. Basically,z-index tells the browser where an item is in a vertical sense. When you look at a browser, there are actually a lot of layers regardless of the 2nd appearance. The z-index is used to bring something forward or backward. If I want the div to be behind say the text I am typing right now, it has to be at a z-index lower than the text. I used -100 in the example just to make sure it&#8217;s behind anything. It&#8217;s really an arbitrary number though. A positive number would make the div appear in front of the text (And in that case the text would not show up since it would be &#8220;behind&#8221; the div) which is what I did with the visibility class.</p>
<p>.showPostComment</p>
<p>    Mostly just a bunch of visual changes like border and background color. However, you will also notice the the position is still absolute and that the z-index is now 10. (positive) The div will now effectively be &#8220;in front&#8221; of the link when it shows up giving it the pop up look. One Note: I had to add in text-decoration:none since the div is attached to the link and IE wants to drag the underline with the pop up causing the text to up with an underline. Kind of odd but no big deal.</p>
<p>Now for the code:</p>
<pre><span style="color: #0000ff;">function</span> BuildSelectableSpanForPost(spanName, parentElement, innerText)
{
    <span style="color: #0000ff;">var</span> divToAdd;
    <span style="color: #0000ff;">var</span> parentContainer;
    <span style="color: #008000;">//check to see if the parentElement is actually an element or string.  If string, use it
    //to find the element.
</span>    <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">typeof</span> parentElement == <span style="color: #ff0000;">'string'</span>)
    {
        parentContainer = document.getElementById(parentElement);
    }
    <span style="color: #0000ff;">else</span>
    {
        parentContainer = parentElement;
    }
    <span style="color: #008000;">//Create the div
    //set the name (The name must unique since there could be a million "pop ups" per page
    //set the id
    //set the text for the div which is what we want to show up in the pop up</span>
    divToAdd = document.createElement(<span style="color: #ff0000;">'span'</span>);
    divToAdd.setAttribute(<span style="color: #ff0000;">'name'</span>, spanName);
    divToAdd.id = spanName;
    divToAdd.innerHTML = innerText;

    <span style="color: #008000;">//Add the div to whatever element that was found.  For this post it will be a link
    //but it doesn't really matter.</span>
    parentContainer.appendChild(divToAdd);

    <span style="color: #0000ff;">return</span> divToAdd;
}</pre>
<p>So there is the building of the pop up div. Here&#8217;s the method to be called by the onclick event:</p>
<pre><span style="color: #0000ff;">function</span> ShowCommentForPost(postName, parentElement, innerText)
{
    <span style="color: #0000ff;">var</span> divName;
    <span style="color: #0000ff;">var</span> createdDiv;
    <span style="color: #0000ff;">var</span> parentContainer;

    <span style="color: #008000;">//Same as before
</span>    <span style="color: #0000ff;">if</span> (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    <span style="color: #0000ff;">else</span>
    {
        parentContainer = parentElement;
    }
    <span style="color: #008000;">//See if the pop up div  already exists.  If it does, then don't create again
    //I didn't have this before and it would create a new div everytime
    //That's what some might call a surprise feature</span>
    divName = 'comment' + postName;
    createdDiv = document.getElementById(divName);
    <span style="color: #008000;">//Ooops, the div didn't exist, create it and add the hide class</span>
    <span style="color: #0000ff;">if</span> (createdDiv == <span style="color: #0000ff;">null</span>)
    {
        createdDiv = BuildSelectableSpanForPost(divName, parentContainer, innerText);
        <span style="color: #008000;">//this is a method found on </span><a href="http://byatool.com/index.php/ui/add-remove-or-replace-a-css-class-using-javascript"><span style="color: #008000;">this post</span></a>
        ClassHandler.AddClass(createdDiv, 'hidePostComment');
    }

    <span style="color: #008000;">//this is a method based off </span><a href="http://byatool.com/index.php/ui/add-remove-or-replace-a-css-class-using-javascript"><span style="color: #008000;">this post</span></a>
<span style="color: #008000;">    //As you can guess it will show or hide depending on which class it already has.</span>
    ShowHideElementBasedOnCss(createdDiv);

    <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span>;
}</pre>
<p>To start, there is the code to create the actual div.</p>
<p>Now for the actual use:</p>
<pre><span style="color: #800000;">&lt;a</span> <span style="color: #ff0000;">onclick</span><span style="color: #0000ff;">="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');"</span> <span style="color: #ff0000;">href</span><span style="color: #0000ff;">="www.byatool.com"</span><span style="color: #800000;">&gt;</span>word.<span style="color: #800000;">&lt;/a&gt;</span></pre>
<p>    Pretty easy to actually use right? The actual location doesn&#8217;t really matter since it the method will always return false and therefore the link will never redirect.  Also, you&#8217;ll see that I put 1 as the name sent in.  The name sent in doesn&#8217;t matter what it is, but for every link it has to be different.  If you are using this in a blog situation where there could be multiple blog posts in one page, I would suggest the name sent in would be the title and an increasing number.</p>
<p>    If you got to this point and feel robbed of five minutes in your life, well just be happy this post robbed me of 15 minutes of mine.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/add-a-pop-up-div-to-a-link-dynamically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Add, Remove, or Replace a CSS Class Using Javascript</title>
		<link>http://byatool.com/ui/add-remove-or-replace-a-css-class-using-javascript/</link>
		<comments>http://byatool.com/ui/add-remove-or-replace-a-css-class-using-javascript/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 21:02:04 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=525</guid>
		<description><![CDATA[Now honestly, I think the all famous Prototype has something for this, but if you aren&#8217;t using the all famous Prototype&#8230; well you&#8217;re screwed. Until now. This is the idea, you want show or hide something on a click of it. &#60;div onclick="HideOrShowMe();"&#62; YAYAAYAYAY! &#60;/div&#62; Annoying thing is trying to keep up with whether it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Now honestly, I think the all famous Prototype has something for this, but if you aren&#8217;t using the all famous Prototype&#8230; well you&#8217;re screwed. Until now.</p>
<p>This is the idea, you want show or hide something on a click of it.</p>
<pre>    &lt;div onclick="HideOrShowMe();"&gt;
      YAYAAYAYAY!
    &lt;/div&gt;</pre>
<p>Annoying thing is trying to keep up with whether it&#8217;s hidden or not. Now there are ways to do this for sure, but if you had them you wouldn&#8217;t be here&#8230; or you just love idiotic banter. Either way, you&#8217;re here.</p>
<p>To start, get a class going:</p>
<pre>    if (<span style="color: #0000ff;">typeof</span> ClassHandler != <span style="color: #ff0000;">'object'</span>)
    {
      ClassHandler = <span style="color: #0000ff;">new</span> Object();
    }</pre>
<p>Normal declaration. Yeehaw. Now we need a method to check for the class:</p>
<pre>ClassHandler.CheckForClass = <span style="color: #0000ff;">function</span>(element, nameOfClass)
{
    <span style="color: #0000ff;">var</span> returnValue = <span style="color: #0000ff;">false</span>;

    <span style="color: #008000;">//Check to see if the element variable is a string or (hopefully) a control.
    //If it is a string, get the control that belongs to that id.
</span>    <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">typeof</span> element == <span style="color: #ff0000;">'string'</span>)
    {
        element = document.getElementById(element);
    }

    <span style="color: #008000;">//next you use a regular expression to check the className property for
    //  the class you want.  If it finds a match, you're good to go.</span>
    <span style="color: #0000ff;">if</span> (element.className != <span style="color: #ff0000;">''</span>)
    {
        returnValue = <span style="color: #0000ff;">new</span> RegExp(<span style="color: #ff0000;">'\\b'</span> + nameOfClass + <span style="color: #ff0000;">'\\b'</span>).test(element.className);
    }

    <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>Ok so now you have a method to check if it&#8217;s there&#8230; but what about if you want to replace the old one with a new one? Well that could be broken into two methods first (Both that are useful). First one is the removal of the old class:</p>
<pre>ClassHandler.RemoveClass = <span style="color: #0000ff;">function</span>(element, nameOfClass)
{
    <span style="color: #0000ff;">var</span> returnValue = <span style="color: #0000ff;">false</span>;

    <span style="color: #008000;">//You know the drill
</span>    <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">typeof</span> element == <span style="color: #ff0000;">'string'</span>)
    {
        element = document.getElementById(element);
    }

    <span style="color: #008000;">//Hey cool, I just used the CheckForClass method
</span>    <span style="color: #0000ff;">if</span> (ClassHandler.CheckForClass(element, nameOfClass))
    {
        <span style="color: #008000;">//Real simple, replace the old
        //But you have to check if the nameOfClass exists with a preceding space
        //If it does, then you replace that with a space, other wise just replace
        //the nameOfClass with a space.
</span>        element.className = element.className.replace((element.className.indexOf(<span style="color: #ff0000;">' '</span> + nameOfClass) &gt;= 0 ? <span style="color: #ff0000;">' '</span> + nameOfClass : nameOfClass),<span style="color: #ff0000;">''</span>);
        returnValue = true;
    } 

    <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>And now you&#8217;ll have to add in the new one.</p>
<pre>ClassHandler.AddClass = function(element, nameOfClass)
{
    <span style="color: #0000ff;">var</span> returnValue = <span style="color: #0000ff;">false</span>;
    <span style="color: #008000;">//lalalala</span>
    <span style="color: #0000ff;">if</span> (typeof element == <span style="color: #ff0000;">'string'</span>)
    {
        element = document.getElementById(element);
    }
    <span style="color: #008000;">//If className already has a value, precede the nameOfClass with a space
    // otherwise just add it in.
</span>    <span style="color: #0000ff;">if</span> (!ClassHandler.CheckForClass(element, nameOfClass))
    {
        element.className += (element.className ?  <span style="color: #ff0000;">'  '</span>  :  <span style="color: #ff0000;">''</span>) + nameOfClass;
        returnValue = true;
    } 

    <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>Now for the replace:</p>
<pre>ClassHandler.ReplaceClass = function(element, classToRemove, classToAdd)
{
    <span style="color: #0000ff;">var</span> returnValue = <span style="color: #0000ff;">false</span>;

    <span style="color: #008000;">//african elephants only have four teeth for chewing their food.
</span>    <span style="color: #0000ff;">if</span> (typeof element == <span style="color: #ff0000;">'string'</span>)
    {
        element = document.getElementById(element);
    }

    <span style="color: #008000;">//Remove the old one
    //Add the new one
</span>    if(ClassHandler.CheckForClass(element, classToRemove))
    {
        ClassHandler.RemoveClass(element, classToRemove);
        ClassHandler.AddClass(element, classToAdd);
        returnValue = <span style="color: #0000ff;">true</span>;
    }

    <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>Now you might be thinking, &#8220;Tool, why don&#8217;t you just use the replace method in the replace method.&#8221; Well I suppose you could, but this way you have two other methods at your disposal for future use. Up to you really, part of this was because I actually needed those methods and the title says &#8220;Add, Remove, or Replace&#8221;. I can&#8217;t go against the title. I don&#8217;t have that kind of strength.</p>
<p>Usage? Well there are couple ways you can do this.</p>
<pre>    if(ClassHandler.CheckForClass(<span style="color: #ff0000;">'someDiv'</span>, <span style="color: #ff0000;">'hide'</span>))
    {
       ClassHandler.ReplaceClass(<span style="color: #ff0000;">'someDiv'</span>, <span style="color: #ff0000;">'hide'</span>, <span style="color: #ff0000;">'show'</span>);
    }
    else
    {
       ClassHandler.ReplaceClass(<span style="color: #ff0000;">'someDiv'</span>, <span style="color: #ff0000;">'show'</span>, <span style="color: #ff0000;">'hide'</span>);
    }</pre>
<p>or this:</p>
<pre>    if(!ClassHandler.ReplaceClass(<span style="color: #ff0000;">'someDiv'</span>, <span style="color: #ff0000;">'hide'</span>, <span style="color: #ff0000;">'show'</span>))
    {
       ClassHandler.ReplaceClass(<span style="color: #ff0000;">'someDiv'</span>, <span style="color: #ff0000;">'show'</span>, <span style="color: #ff0000;">'hide'</span>));
    }</pre>
<p>And other ways to be sure. Now I&#8217;m not saying this is the best way to do it, just a decent way&#8230; although looking back on this I wonder if I could clean up the regex stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/add-remove-or-replace-a-css-class-using-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ConfigurationManager And AppSettings&#8230; A Wrapper Class Story</title>
		<link>http://byatool.com/c/configurationmanager-and-appsettings-a-wrapper-class-story/</link>
		<comments>http://byatool.com/c/configurationmanager-and-appsettings-a-wrapper-class-story/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 19:00:48 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=387</guid>
		<description><![CDATA[You can file this under &#8220;Do I really need this?&#8221; but for now I kind of like it. That, however, may change in the next hour. The idea is simple, create a class that uses the ConfigurationManager AppSettings NameValueCollection (Triple Combo!) but only presents properties that represent the keys in the .config file. This way [...]]]></description>
			<content:encoded><![CDATA[<p>You can file this under &#8220;Do I really need this?&#8221; but for now I kind of like it. That, however, may change in the next hour.</p>
<p>The idea is simple, create a class that uses the ConfigurationManager AppSettings NameValueCollection (Triple Combo!) but only presents properties that represent the keys in the .config file. This way there is no guessing of how the key is spelled or that that type returned is converted to something it should be. (Say you have a numeric value in the .config file) Now this doesn&#8217;t seem like a big deal, but I&#8217;m not happy with something that is just simple like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> SomeKey
    {
       <span style="color: #0000ff;">get</span>
       {
          <span style="color: #0000ff;">return</span> System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[<span style="color: #800000;">"SomeKey"</span>];
       }
    }</pre>
<p>Oh no, that&#8217;s just not good enough. Call it divine intervention. Call it spontaneous brilliance. Call it whatever the guy that invented the corn dog had. But what I came up with is far better. (And by better I mean more complex)</p>
<p>Remember, the idea isn&#8217;t to have to grab just the value from System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings but also to have it be typed on the way back. Now we know this to be true: I am awesome. What we also know to be true is that the value held in the appSettings area of the .config file is going to correspond to a value type but is going to be read in as a string. If you&#8217;ve read some of my posts (Which I assume you haven&#8217;t), you might have stumbled <a href="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert" target="_new">upon this little gem</a> and know that I already have something to convert from a string to pretty much any value type. (Those having a TryParse method) So the converting part is already done, but what about the getting?</p>
<pre>    <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">static</span> T? GetValueFromConfiguration&lt;T&gt;(<span style="color: #008080;">String</span> key) <span style="color: #0000ff;">where</span> T : <span style="color: #0000ff;">struct</span>
    {
      T? returnValue = <span style="color: #0000ff;">null</span>;
      <span style="color: #0000ff;">if</span> (System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key] != <span style="color: #0000ff;">null</span>)
      {
        returnValue = System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key]
                           .ConvertTo&lt;T&gt;(); <span style="color: #008000;">//MY AWSOME CONVERTTO METHOD!!11</span>
      }

      <span style="color: #0000ff;">return</span> returnValue;
    }</pre>
<p>Ok so you can see, this is really simple. I check to see if the key exists, get the value from the .config file, and convert to whatever I said it should. In use this would be:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">DateTime</span>? TestDate
    {
       <span style="color: #0000ff;">get</span>
       {
          <span style="color: #0000ff;">return</span> GetValueFromConfiguration&lt;<span style="color: #008080;">DateTime</span>&gt;(<span style="color: #800000;">"TestDate"</span>);
        }
      }</pre>
<p>Now you might have noticed something about this&#8230; yes besides the fact that it&#8217;s Mentos fresh. First, the method returns nullable versions. The reason for doing this is you really don&#8217;t know what the value will be in the .config file. Say this was an integer and you returned just a normal integer. (Non nullable) What would you set the value to? Sure you could do minimum value but COULD mean that there was a value in the .config file. This is more of a design choice though.</p>
<p>Second is that the method doesn&#8217;t cover strings. This is an ouch due to how nullables and strings work. You can&#8217;t return a nullable string since string doesn&#8217;t fit in the non nullable value category. This is a real pain but easily overcome with a non generic overload:</p>
<pre>    <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> GetValueFromConfiguration(<span style="color: #008080;">String</span> key)
    {
      <span style="color: #008080;">String</span> returnValue = <span style="color: #0000ff;">null</span>;

      if (System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key] != <span style="color: #0000ff;">null</span>)
      {
        returnValue = System.Configuration
                           .<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key];
       }
       <span style="color: #0000ff;">return</span> returnValue;
    }</pre>
<p>See? Easy way to side step the problem. There might be a better way to handle that, but not sure at this point. Something to revisit I suppose. Oh and here&#8217;s the whole class for the hell of it:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">BaseConfigurationManager</span>
    {
       <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">const</span> <span style="color: #008080;">String</span> SOME_KEY = <span style="color: #800000;">"SomeKey"</span>;

       <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">static</span> T? GetValueFromConfiguration&lt;T&gt;(<span style="color: #008080;">String</span> key) <span style="color: #0000ff;">where</span> T : <span style="color: #0000ff;">struct</span>
       {
         T? returnValue = <span style="color: #0000ff;">null</span>;

         <span style="color: #0000ff;">if</span> (System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key] != <span style="color: #0000ff;">null</span>)
         {
           returnValue = System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key]
                         .ConvertTo&lt;T&gt;();
         }

         <span style="color: #0000ff;">return</span> returnValue;
       }

       <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> GetValueFromConfiguration(<span style="color: #008080;">String</span> key)
       {
         <span style="color: #008080;">String</span> returnValue = <span style="color: #0000ff;">null</span>;

         <span style="color: #0000ff;">if</span> (System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key] != <span style="color: #0000ff;">null</span>)
         {
           returnValue = System.Configuration.<span style="color: #008080;">ConfigurationManager</span>.AppSettings[key];
         }

       <span style="color: #0000ff;">return</span> returnValue;
     }

     <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> SomeKey
     {
       <span style="color: #0000ff;">get</span>
       {
         <span style="color: #0000ff;">return</span> GetValueFromConfiguration(SOME_KEY);
       }
     }

    }</pre>
<p>Oddly enough I spelled &#8220;spontaneous brilliance&#8221; correctly the first time around but thought &#8220;numeric&#8221; had a silent &#8216;b&#8217;. Go figure. Should have finished middle school.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/configurationmanager-and-appsettings-a-wrapper-class-story/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

