<?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>I Prefer Jim</title>
	<atom:link href="http://www.ipreferjim.com/site/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ipreferjim.com/site</link>
	<description>Developer James Schubert shares his code and his thoughts.</description>
	<lastBuildDate>Sat, 31 Jul 2010 16:01:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Bitwise operations and Flags (C#)</title>
		<link>http://www.ipreferjim.com/site/2010/07/bitwise-operations-and-flags/</link>
		<comments>http://www.ipreferjim.com/site/2010/07/bitwise-operations-and-flags/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 15:57:51 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=303</guid>
		<description><![CDATA[I haven't written anything in a while, so I thought I would finally write about the subject of bitwise operations and the FlagsAttribute.
I mentioned this to one of the developers on my team, and he said that he somewhat understood bit operations but he had never found a reason to use them. 
Here is the [...]]]></description>
			<content:encoded><![CDATA[<p>I haven't written anything in a while, so I thought I would finally write about the subject of bitwise operations and the FlagsAttribute.</p>
<p>I mentioned this to one of the developers on my team, and he said that he somewhat understood bit operations but he had never found a reason to use them. </p>
<p>Here is the code I will use to discuss the operations</p>
<pre class="brush: csharp;">
int a = 57754;
int b = 18782;

int aXORb = a ^ b;
int aORb = a | b;
int aANDb = a &amp; b;
int aNOT = ~a;
int bNOT = ~b;

string spacer = &quot;---------------------------------------------&quot;;
Console.WriteLine(&quot;{0} ({1}) a&quot;, GetBitString(a), a.ToString());
Console.WriteLine(&quot;{0} ({1}) b&quot;, GetBitString(b), b.ToString());
Console.WriteLine(&quot;{0} ({1}) a ^ b&quot;, GetBitString(aXORb), aXORb);
Console.WriteLine(spacer);
Console.WriteLine(&quot;{0} ({1}) a&quot;, GetBitString(a), a.ToString());
Console.WriteLine(&quot;{0} ({1}) b&quot;, GetBitString(b), b.ToString());
Console.WriteLine(&quot;{0} ({1}) a | b&quot;, GetBitString(aORb), aORb);
Console.WriteLine(spacer);
Console.WriteLine(&quot;{0} ({1}) a&quot;, GetBitString(a), a.ToString());
Console.WriteLine(&quot;{0} ({1}) b&quot;, GetBitString(b), b.ToString());
Console.WriteLine(&quot;{0} ({1}) a &amp; b&quot;, GetBitString(aANDb), aANDb);
Console.WriteLine(spacer);
Console.WriteLine(&quot;{0} ({1}) a&quot;, GetBitString(a), a.ToString());
Console.WriteLine(&quot;{0} ({1}) ~a&quot;, GetBitString(aNOT), aNOT);
Console.WriteLine(&quot;{0} ({1}) ~(~a)&quot;, GetBitString(~aNOT), ~aNOT);
Console.WriteLine(spacer);
Console.WriteLine(&quot;{0} ({1}) b&quot;, GetBitString(b), b.ToString());
Console.WriteLine(&quot;{0} ({1}) ~b&quot;, GetBitString(bNOT), bNOT);
Console.WriteLine(&quot;{0} ({1}) ~(~b)&quot;, GetBitString(~bNOT), ~bNOT);

Console.ReadLine();

// And, the GetBitString method
static string GetBitString(int input){
	int sizeInt;
	// Number of bits is bytes * 8
	// I specifically chose 16-bit values to reduce the amount displayed
	unsafe{ sizeInt = (sizeof(ushort) * 8); }

	string output = String.Empty;
	for (; sizeInt &gt;= 0; sizeInt--) {
		output += (input &gt;&gt; sizeInt) &amp; 1;
		if(sizeInt % 4 == 0) { output += &quot; &quot;; }
	}

	return output;
}
</pre>
<p><strong>XOR ( ^ )</strong></p>
<p>From MSDN:</p>
<blockquote><p>
Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.
</p></blockquote>
<p>I think of XOR as a "one-toggle". The logic can be seen as (format is [first] : [second] --> [result] ):</p>
<pre class="brush: plain;">
0 : 1 --&gt; 1
1 : 1 --&gt; 0
1 : 0 --&gt; 1
0 : 0 --&gt; 0
</pre>
<p>As you can see,<span id="more-303"></span> the result only changes when the second value, which I call the toggle, is a 1.</p>
<p>If you were to run the code above, you would receive the following output:</p>
<pre class="brush: plain;">
0 1110 0001 1001 1010  (57754) a
0 0100 1001 0101 1110  (18782) b
0 1010 1000 1100 0100  (43204) a ^ b
</pre>
<p>Compare the values in each column and notice that the result on the third line only toggles if the value in line two is a 1.</p>
<p><strong>OR ( | )</strong></p>
<p>From MSDN:</p>
<blockquote><p>
Binary | operators are predefined for the integral types and bool. For integral types, | computes the bitwise OR of its operands. For bool operands, | computes the logical OR of its operands; that is, the result is false if and only if both its operands are false.
</p></blockquote>
<p>A bitwise-or, in my eyes, collects all bits that are "on" or 1.  The logic can be seen as (format is [first] : [second] --> [result] ):</p>
<pre class="brush: plain;">
0 : 1 --&gt; 1
1 : 1 --&gt; 1
1 : 0 --&gt; 1
0 : 0 --&gt; 0
</pre>
<p>As you can see, whenever there is a 1 in the first or second value, the resulting value is 1.</p>
<p>If you were to run the code above, you would receive the following output:</p>
<pre class="brush: plain;">
0 1110 0001 1001 1010  (57754) a
0 0100 1001 0101 1110  (18782) b
0 1110 1001 1101 1110  (59870) a | b
</pre>
<p>Compare the values in each column and notice that any column containing a 1 results in a 1.</p>
<p><strong>AND ( &#038; )</strong></p>
<p>From MSDN:</p>
<blockquote><p>
Binary &#038; operators are predefined for the integral types and bool. For integral types, &#038; computes the bitwise AND of its operands. For bool operands, &#038; computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.
</p></blockquote>
<p>I like to think of the bitwise-and as a truth-only operation.  Only the bits containing all 1's will result in a one.  This is like saying "If true and false, then false" or "If true and true, then true".   The logic can be seen as (format is [first] : [second] --> [result] ):</p>
<pre class="brush: plain;">
0 : 1 --&gt; 0
1 : 1 --&gt; 1
1 : 0 --&gt; 0
0 : 0 --&gt; 0
</pre>
<p>If you were to run the code above, you would receive the following output:</p>
<pre class="brush: plain;">
0 1110 0001 1001 1010  (57754) a
0 0100 1001 0101 1110  (18782) b
0 0100 0001 0001 1010  (16666) a &amp; b
</pre>
<p>Notice how the result only contains a 1 if all other bits in the column are 1.</p>
<p><strong>NOT ( ~ )</strong></p>
<p>From MSDN:</p>
<blockquote><p>
The ~ operator performs a bitwise complement operation on its operand. Bitwise complement operators are predefined for int, uint, long, and ulong.
</p></blockquote>
<p>The not (or bitwise complement) will give you the opposite value for every bit, but it is a unary operator so you can only use it in assignment and probably doesn't seem like it should be included in a discussion about operations.  I think it's important to understand what happens, though.</p>
<p> The logic can be seen as (format is [value] --> [result] ):</p>
<pre class="brush: plain;">
0  --&gt; 1
1  --&gt; 0
</pre>
<p>If you were to run the code above, you would receive the following output:</p>
<pre class="brush: plain;">
0 1110 0001 1001 1010  (57754) a
1 0001 1110 0110 0101  (-57755) ~a
0 1110 0001 1001 1010  (57754) ~(~a)
---------------------------------------------
0 0100 1001 0101 1110  (18782) b
1 1011 0110 1010 0001  (-18783) ~b
0 0100 1001 0101 1110  (18782) ~(~b)
</pre>
<p>You may wonder why the complement of 18782 would be -18783. The first bit, why you may or may not have noticed sitting rogue in front of the 16 bits in the outputs so far, is a positive/negative bit.  In all of the output so far, the values have been positive.  The complement of a positive value is it's negative minus 1.  We can see that it is minus 1, because all of the 1 bits are flipped until the first 0 is reached (which is how binary increments an integral value).  The positive/negative bit is flipped last, giving you this offset that may seem strange.</p>
<p><strong>Practical(maybe?) application</strong></p>
<p>Using the code to output the bit string from above, let's implement a simple CRUD flag.</p>
<pre class="brush: csharp;">
[Flags]
public enum Permissions
{
	CREATE		= 1 &lt;&lt; 0,
	READ		= 1 &lt;&lt; 1,
	UPDATE		= 1 &lt;&lt; 2,
	DELETE		= 1 &lt;&lt; 3
}

// in your main method
Permissions c = Permissions.CREATE;
Permissions r = Permissions.READ;
Permissions u = Permissions.UPDATE;
Permissions d = Permissions.DELETE;
Permissions crud = Permissions.CREATE ^ Permissions.READ ^ Permissions.UPDATE ^ Permissions.DELETE;

Console.WriteLine(spacer);
Console.WriteLine(&quot;{0} ({1}) Create&quot;, GetBitString((int)c), ((int)c).ToString());
Console.WriteLine(&quot;{0} ({1}) Read&quot;, GetBitString((int)r), ((int)r).ToString());
Console.WriteLine(&quot;{0} ({1}) Update&quot;, GetBitString((int)u), ((int)u).ToString());
Console.WriteLine(&quot;{0} ({1}) Delete&quot;, GetBitString((int)d), ((int)d).ToString());
Console.WriteLine(&quot;{0} ({1}) CRUD&quot;, GetBitString((int)crud), ((int)crud).ToString());
</pre>
<p>To start, we have the Permissions enum marked with the <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx">FlagsAttribute</a>.  Notice that a general naming convention for flags is to pluralize the enum since you can have more than one value at a time (the MSDN examples in the link don't stick to this naming convention 100%).</p>
<p>In the Permissions flag, we shift each bit according to the desired position.  *NOTE* If you don't shift bits here, you will receive an error.</p>
<p>Because an enum is a type which defaults to int values, we'll have to cast to int before passing the enum into the GetBitString method.  Remember, using XOR will toggle all bits.</p>
<p>Here is the output from the above code:</p>
<pre class="brush: csharp;">
0 0000 0000 0000 0001  (1) Create
0 0000 0000 0000 0010  (2) Read
0 0000 0000 0000 0100  (4) Update
0 0000 0000 0000 1000  (8) Delete
0 0000 0000 0000 1111  (15) CRUD
</pre>
<p>Feel free to play around with the operators in the above CRUD variable and see how this could be useful in, for example, a linux environment where file permissions are stored as -rwxr-xr-x.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/07/bitwise-operations-and-flags/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Learning WCF: IIS 7 won&#8217;t start service from web project</title>
		<link>http://www.ipreferjim.com/site/2010/06/learning-wcf-iis-7-wont-start-service-from-web-project/</link>
		<comments>http://www.ipreferjim.com/site/2010/06/learning-wcf-iis-7-wont-start-service-from-web-project/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 04:01:16 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=301</guid>
		<description><![CDATA[I'm following along with code in Learning WCF, attempting to quickly become an expert at building WCF Services from scratch.  In Chapter 1, there is a project called IISHostedService.  After making the quick modifications to the downloaded code, and running the application, IIS 7.0 (Windows 7, 64bit) doesn't serve the services, complaining about [...]]]></description>
			<content:encoded><![CDATA[<p>I'm following along with code in Learning WCF, attempting to quickly become an expert at building WCF Services from scratch.  In Chapter 1, there is a project called IISHostedService.  After making the quick modifications to the downloaded code, and running the application, IIS 7.0 (Windows 7, 64bit) doesn't serve the services, complaining about adding a MIME type.  I thought this was rather fishy, because I've created WCF Services while in school under Windows XP and they ran fine.</p>
<p>It turns out that I didn't have WCF properly setup.  To do so, you have to run</p>
<pre class="brush: plain;">
C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\servicemodelreg -i
</pre>
<p>This will provide the following output (which is everything I was missing):</p>
<pre class="brush: plain;">
Microsoft(R) Windows Communication Foundation Installation Utility
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.4926]
Copyright (c) Microsoft Corporation.  All rights reserved.

Installing: Machine.config Section Groups and Handlers (WOW64)
Installing: Machine.config Section Groups and Handlers
Installing: System.Web Build Provider (WOW64)
Installing: System.Web Compilation Assemblies (WOW64)
Installing: HTTP Handlers (WOW64)
Installing: HTTP Modules (WOW64)
Installing: System.Web Build Provider
Installing: System.Web Compilation Assemblies
Installing: HTTP Handlers
Installing: HTTP Modules
Installing: Protocol node for protocol net.tcp (WOW64)
Installing: TransportConfiguration node for protocol net.tcp (WOW64)
Installing: ListenerAdapter node for protocol net.tcp
Installing: Protocol node for protocol net.tcp
Installing: TransportConfiguration node for protocol net.tcp
Installing: Protocol node for protocol net.pipe (WOW64)
Installing: TransportConfiguration node for protocol net.pipe (WOW64)
Installing: ListenerAdapter node for protocol net.pipe
Installing: Protocol node for protocol net.pipe
Installing: TransportConfiguration node for protocol net.pipe
Installing: Protocol node for protocol net.msmq (WOW64)
Installing: TransportConfiguration node for protocol net.msmq (WOW64)
Installing: ListenerAdapter node for protocol net.msmq
Installing: Protocol node for protocol net.msmq
Installing: TransportConfiguration node for protocol net.msmq
Installing: Protocol node for protocol msmq.formatname (WOW64)
Installing: TransportConfiguration node for protocol msmq.formatname (WOW64)
Installing: ListenerAdapter node for protocol msmq.formatname
Installing: Protocol node for protocol msmq.formatname
Installing: TransportConfiguration node for protocol msmq.formatname
Installing: HTTP Modules (WAS)
Installing: HTTP Handlers (WAS)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/06/learning-wcf-iis-7-wont-start-service-from-web-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fairly Accurate JavaScript Browser Detection</title>
		<link>http://www.ipreferjim.com/site/2010/06/fairly-accurate-javascript-browser-detection/</link>
		<comments>http://www.ipreferjim.com/site/2010/06/fairly-accurate-javascript-browser-detection/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 13:53:19 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=293</guid>
		<description><![CDATA[I use jQuery for almost everything I do in JavaScript.  The only real problem is that jQuery's browser name and version detection doesn't provide exactly what I want.
For instance, if I'm using Google Chrome 6.0.427.0, I wanted a script that would say "Hey, you're using Chrome 6.0.427.0".
I found such a script online and modified [...]]]></description>
			<content:encoded><![CDATA[<p>I use jQuery for almost everything I do in JavaScript.  The only real problem is that jQuery's browser name and version detection doesn't provide exactly what I want.</p>
<p>For instance, if I'm using Google Chrome 6.0.427.0, I wanted a script that would say "Hey, you're using Chrome 6.0.427.0".</p>
<p>I found such a script online and modified it to be a javascript object, so I thought I'd share.  I didn't really do much to modify this code other than changing the comment style and a couple of other things. Below the code, there are link to download.</p>
<p>*browser_detection.js*</p>
<pre class="brush: jscript;">
/**
 * Modifed from the source at http://www.javascripter.net/faq/browsern.htm
 */

function BrowserDetector()
{
  this.init();
}

BrowserDetector.prototype =
{
  nVer: navigator.appVersion,
  nAgt: navigator.userAgent,
  browserName: navigator.appName,
  fullVersion: '' + parseFloat(navigator.appVersion),
  majorVersion: parseInt(navigator.appVersion, 10),
  nameOffset: null,
  verOffset: null,
  ix: null,
  init: function ()
  { /* In MSIE, the true version is after &quot;MSIE&quot; in userAgent */
    if ((this.verOffset = this.nAgt.indexOf(&quot;MSIE&quot;)) != -1)
    {
      this.browserName = &quot;Microsoft Internet Explorer&quot;;
      this.fullVersion = this.nAgt.substring(this.verOffset + 5);
    } /* In Opera, the true version is after &quot;Opera&quot; */
    else if ((this.verOffset = this.nAgt.indexOf(&quot;Opera&quot;)) != -1)
    {
      this.browserName = &quot;Opera&quot;;
      this.fullVersion = this.nAgt.substring(this.verOffset + 6);
    } /* In Chrome, the true version is after &quot;Chrome&quot; */
    else if ((this.verOffset = this.nAgt.indexOf(&quot;Chrome&quot;)) != -1)
    {
      this.browserName = &quot;Chrome&quot;;
      this.fullVersion = this.nAgt.substring(this.verOffset + 7);
    } /* In Safari, the true version is after &quot;Safari&quot; */
    else if ((this.verOffset = this.nAgt.indexOf(&quot;Safari&quot;)) != -1)
    {
      this.browserName = &quot;Safari&quot;;
      this.fullVersion = this.nAgt.substring(this.verOffset + 7);
    } /* In Firefox, the true version is after &quot;Firefox&quot; */
    else if ((this.verOffset = this.nAgt.indexOf(&quot;Firefox&quot;)) != -1)
    {
      this.browserName = &quot;Firefox&quot;;
      this.fullVersion = this.nAgt.substring(this.verOffset + 8);
    } /* In most other browsers, &quot;name/version&quot; is at the end of userAgent */
    else if ((this.nameOffset = this.nAgt.lastIndexOf(' ') + 1) &lt; (this.verOffset = this.nAgt.lastIndexOf('/')))
    {
      this.browserName = this.nAgt.substring(this.nameOffset, this.verOffset);
      this.fullVersion = this.nAgt.substring(this.verOffset + 1);
      if (this.browserName.toLowerCase() == this.browserName.toUpperCase())
      {
        this.browserName = navigator.appName;
      }
    } /* trim the fullVersion string at semicolon/space if present */
    if ((this.ix = this.fullVersion.indexOf(&quot;;&quot;)) != -1)
    {
      this.fullVersion = this.fullVersion.substring(0, this.ix);
    }
    if ((this.ix = this.fullVersion.indexOf(&quot; &quot;)) != -1)
    {
      this.fullVersion = this.fullVersion.substring(0, this.ix);
    }

    this.majorVersion = parseInt('' + this.fullVersion, 10);
    if (isNaN(this.majorVersion))
    {
      this.fullVersion = '' + parseFloat(navigator.appVersion);
      this.majorVersion = parseInt(navigator.appVersion, 10);
    }
  }
}
</pre>
<p>Say you have two DOM elements, called *brower_name* and *browser_version*, you can use this script this way (using jQuery):</p>
<pre class="brush: jscript;">

	jQuery(document).ready(function($){
		var browser_name = $('#browser_name');
		var browser_version = $('#browser_version');

		var browser = new BrowserDetector();
		browser_name.text(browser.browserName);
		browser_version.text(browser.fullVersion);
	});
</pre>
<p>Below are the files:<br />
<a href='http://www.ipreferjim.com/site/wp-content/uploads/2010/06/browser_detection.js'>browser_detection.js [2.6 KB (2670 bytes)]</a><br />
<a href='http://www.ipreferjim.com/site/wp-content/uploads/2010/06/browser_detection.min.js'>browser_detection.min.js [1.7 KB (1758 bytes)]</a><br />
<a href='http://www.ipreferjim.com/site/wp-content/uploads/2010/06/browser_detection.packed.js'>browser_detection.packed.js [1.2 KB (1263 bytes)]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/06/fairly-accurate-javascript-browser-detection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using DataAnnotation attributes to validate Membership password</title>
		<link>http://www.ipreferjim.com/site/2010/06/using-dataannotation-attributes-to-validate-membership-password/</link>
		<comments>http://www.ipreferjim.com/site/2010/06/using-dataannotation-attributes-to-validate-membership-password/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 19:14:59 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=290</guid>
		<description><![CDATA[As a follow-up to my post on DataAnnotations in ASP.NET Web Forms, I'd like to demonstrate yet another custom attribute.  Although ASP.NET offers a CreateUserWizard, if your custom membership provider is way more complicated, you will probably be better off creating a control from scratch.  If you go this route, you'll have to [...]]]></description>
			<content:encoded><![CDATA[<p>As a follow-up to my post on DataAnnotations in ASP.NET Web Forms, I'd like to demonstrate yet another custom attribute.  Although ASP.NET offers a CreateUserWizard, if your custom membership provider is way more complicated, you will probably be better off creating a control from scratch.  If you go this route, you'll have to provide some of the functionality from the CreateUserWizard.  Here is a simple attribute which checks *only* password complexity and builds an ErrorMessage without ever calling the CreateUser method.</p>
<p>This attribute can be added to a password property and validate against the *Default* Membership Provider. </p>
<p>Here is the code:</p>
<pre class="brush: csharp;">

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class MembershipPasswordRequiredAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null || !(value is string) || string.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }

            MembershipSection membershipConfig = (MembershipSection)WebConfigurationManager
                                                                    .GetSection(&quot;system.web/membership&quot;);
            var providerSettings = membershipConfig.Providers[membershipConfig.DefaultProvider];
            string minLength = providerSettings.Parameters[&quot;minRequiredPasswordLength&quot;];
            string minAlpha = providerSettings.Parameters[&quot;minRequiredNonalphanumericCharacters&quot;];

            if (string.IsNullOrEmpty(this.ErrorMessage) &amp;&amp; !string.IsNullOrEmpty(minLength))
            {
                string message = String.Empty;
                message = String.Format(&quot;Password must be at least {0} characters in length&quot;, minLength);
                if (!string.IsNullOrEmpty(minAlpha))
                {
                    message = String.Format(&quot;{0} and contain at least {1} special character&quot;, message,  minAlpha);
                }

                this.ErrorMessage = message;
            }
                /* Validate against your provider and return true or false */
        }
    }
</pre>
<p>Usage:</p>
<pre class="brush: csharp;">
[MembershipPasswordRequired]
internal string Password {get;set;}
</pre>
<p>The cool thing about this attribute is that you can decorate a property without specifying the ErrorMessage and it will build one dynamically from your default membership.  Of course, you can change this up if you're using multiple providers by getting the key of the current provider.  But, the project I'm working on will always only have one provider, so this is how I'll leave it.</p>
<p>A caveat: You can only set the ErrorMessage property once.  If you try to assign to it more than once, you will receive an exception telling you this.</p>
<p>I won't post the code for validating against the provider, because there are a number of ways to do this.  Probably the safest way to do so is to use regex validation and pull that property from the provider's parameters and just return whether the regex matches the string or not.</p>
<p>Anyway, I thought this was a pretty cool usage of DataAnnotations, and hooking it up on a custom CreateUser control was trivial with the DataAnnotation validator (from a few posts ago).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/06/using-dataannotation-attributes-to-validate-membership-password/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript color picker</title>
		<link>http://www.ipreferjim.com/site/2010/05/javascript-color-picker/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/javascript-color-picker/#comments</comments>
		<pubDate>Mon, 31 May 2010 18:00:43 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=288</guid>
		<description><![CDATA[I'm anxiously awaiting the implementation in Google Chrome for HTML5's color chooser:
&#60;input type=&#34;color&#34; /&#62;
In the meantime, I found a nice little javascript color chooser at http://jscolor.com/ written by Jan Odvárko.
The usage is very simple: add the javascript and set the input's class to "color".  I like this flat-style color chooser as opposed to a [...]]]></description>
			<content:encoded><![CDATA[<p>I'm anxiously awaiting the implementation in Google Chrome for HTML5's color chooser:</p>
<pre class="brush: plain;">&lt;input type=&quot;color&quot; /&gt;</pre>
<p>In the meantime, I found a nice little javascript color chooser at <a href="http://jscolor.com/">http://jscolor.com/</a> written by Jan Odvárko.</p>
<p>The usage is very simple: add the javascript and set the input's class to "color".  I like this flat-style color chooser as opposed to a color wheel, because the relationship between colors is easier to see, in my opinion.</p>
<p>Anyway, it's a wonderful script.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/javascript-color-picker/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>System.ComponentModel.DataAnnotations for ASP.NET Web Forms</title>
		<link>http://www.ipreferjim.com/site/2010/05/system-componentmodel-dataannotations-for-asp-net-web-forms/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/system-componentmodel-dataannotations-for-asp-net-web-forms/#comments</comments>
		<pubDate>Thu, 27 May 2010 01:50:19 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=275</guid>
		<description><![CDATA[Although I'm primarily an ASP.NET Web Forms developer, I regularly dabble in new and interesting technologies.  I've toyed with other Microsoft technologies such as ASP.NET MVC and Dynamic Data web sites.
ASP.NET MVC offers an interesting mechanism for validating view models called DataAnnotations.   Examples can be seen here and here.
Some of the more useful attributes [...]]]></description>
			<content:encoded><![CDATA[<p>Although I'm primarily an ASP.NET Web Forms developer, I regularly dabble in new and interesting technologies.  I've toyed with other Microsoft technologies such as ASP.NET MVC and Dynamic Data web sites.</p>
<p>ASP.NET MVC offers an interesting mechanism for validating view models called DataAnnotations.   Examples can be seen <a title="here" href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html" target="_blank">here</a> and <a title="here" href="http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs" target="_blank">here</a>.</p>
<p>Some of the more useful attributes for validation include:</p>
<ul>
<li>RequiredAttribute</li>
<li>RegularExpressionAttribute</li>
<li>RangeAttribute</li>
<li>DataTypeAttribute</li>
</ul>
<p>I recently decided to implement a data validation schema (for lack of a better term) for web forms similar to that of ASP.NET MVC.  This would allow us to maintain validation of a model object via attributes at the class level, instead of dispersing these validation rules through the web form code or any of the business logic layers.  However, there will be occasions where an object's validity depends upon some state or validity of another object.  I've handled this by allowing the validation method to accept any action to be called after the object has been validated.</p>
<p>In order to make a domain object validatable, I'm going to implement the following interface:</p>
<p><strong>IValidatable.cs</strong></p>
<pre class="brush: csharp;">
namespace Validatable
{
    interface IValidatable
    {
        System.Type EntityType { get; set; }
        System.Collections.Generic.List&lt;object&gt; Errors { get; set; }

        /// &lt;summary&gt;
        /// Determine whether the object is valid.  If invalid, errors are added to item.Errors
        /// &lt;/summary&gt;
        /// &lt;returns&gt;true if valid, false if invalid&lt;/returns&gt;
        bool IsValid();

        /// &lt;summary&gt;
        /// Validate this item against a supplied action
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;action&quot;&gt;The action to use for validation&lt;/param&gt;
        void Validate(System.Action action);

        /// &lt;summary&gt;
        /// Validate this object against a Repository.
        /// &lt;example&gt;
        /// Item a = new Item();
        /// a.Validate(new ItemRepository());
        /// &lt;/example&gt;
        /// Note: Repository must have a Validate(T item) method
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;repository&quot;&gt;The Repository to use for validation&lt;/param&gt;
        void Validate(object repository);
    }
}
</pre>
<p>As you can see, this abstract class adds a property accessor for the entity's type, a list of validation errors, an IsValid method, and two Validate methods.</p>
<h2>Validatable&lt;T&gt;</h2>
<p>I'll take the code in chunks, since there is a lot more than I usually post.<br />
First of all, the using directives required for this class are pretty sparse: </p>
<pre class="brush: csharp;">
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
</pre>
<p>The class definition is:</p>
<pre class="brush: csharp;">
   [Serializable]
    public abstract class Validatable&lt;T&gt; : IValidatable where T : class, new()
    { /* class */ }
</pre>
<p>If you're unfamiliar with generic constraints, the <strong>where T : class, new()</strong> above enforces the T passed as  in to be a class and to have a parameterless constructor (<strong>new()</strong>)</p>
<p>The properties can be auto-implemented properties, or they can implement any backing logic you prefer.  The constructor as I have it is:</p>
<pre class="brush: csharp;">
 protected Validatable()
 {
     Errors = new List&lt;object&gt;();
     EntityType = typeof(T);
 }
</pre>
<p>Now for the methods and a slight explanation of each:</p>
<p><strong>IsValid()</strong></p>
<pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
        public virtual bool IsValid()
        {
            Errors = new List&lt;object&gt;();
            PropertyInfo[] props = this.GetType().GetProperties();

            foreach (PropertyInfo property in props)
            {
                foreach (ValidationAttribute va in
                    property.GetCustomAttributes(true).OfType&lt;ValidationAttribute&gt;())
                {
                    var value = property.GetValue(this, null);
                    if (!va.IsValid(value))
                    {
                        Errors.Add(va.ErrorMessage);
                    }
                }
            }

            return Errors.Count &lt;= 0;
        }
</pre>
<p>As a side note, all DataAnnotation attributes inherit from ValidationAttribute.  You can create your own Validation Attributes by inheriting from this class.  This method clears the list of errors and repopulates it by looping over any properties with validation attributes of this object, validates that property's value against the attribute, and adds the ErrorMessage associated with it to the list of Errors.</p>
<p><strong>Validate Methods</strong></p>
<pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
        public virtual void Validate(Action action)
        {
            if (IsValid())
            {
                action();
            }
        }

        public virtual void Validate(object repository)
        {
            MethodInfo method = repository.GetType().GetMethods()
                .Where(x =&gt; x.Name.Equals(&quot;Validate&quot;)).FirstOrDefault();
            if (method != null)
            {
                object[] parameters = new object[] { this };
                Validate(() =&gt; method.Invoke(repository, parameters));
            }
        }
</pre>
<p>These two methods can be changed to throw an exception if the object is invalid.  I'll leave that up to you.  The way these are set up is to allow you to validate the object and perform either some unknown action or call <strong>Validate(T item)</strong> against some other object, arbitrarily called a repository.  In actuality, you could have a Validate method on some other object that takes an object of this type and essentially chain validations.</p>
<p>The simplicity of the Validate(Action action) method is what makes it beautiful.  For instance, you can have an item (a) and cause it save after validation by doing something like:</p>
<pre class="brush: csharp;">
a.Validate(() =&gt; new ItemDAL().Save(a));
</pre>
<p>As you can see, a Save method in your Item's Data Access Layer taking Item as a parameter can be called only when a.IsValid() is true.  Again, there are a number of ways to tweak this and change it to your liking, but I'll leave that up to you.</p>
<h2>DataAnnotationValidator</h2>
<p>Here is the wonderful part about all of this.  You can create a custom validator that validates in a similar way as the Validatable class.  I'll post the code and quickly explain what it does.  I got the idea from this from another blog and tweaked it a little.</p>
<p><strong>DataAnnotationValidator.cs</strong></p>
<pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
// DataAnnotationValidator.cs
namespace Validatable
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [ToolboxData(&quot;&lt;{0}:DataAnnotationValidator runat=\&quot;server\&quot; ControlToValidate=\&quot;[Required]\&quot; Display=\&quot;Dynamic\&quot; Text=\&quot;*\&quot; SourceTypeName=\&quot;[FullyQualifiedTypeName]\&quot; PropertyToValidate=\&quot;[PropertyName]\&quot; /&gt;&quot;)]
    public class DataAnnotationValidator : BaseValidator
    {
        /// &lt;summary&gt;
        /// THe Property that should be checked
        /// &lt;/summary&gt;
        public string PropertyToValidate { get; set; }

        /// &lt;summary&gt;
        /// The object's type
        /// &lt;/summary&gt;
        public string SourceTypeName { get; set; }

        protected override bool EvaluateIsValid()
        {
            Type source = GetValidatedType();
            PropertyInfo property = GetValidatedProperty(source);
            string value = GetControlValidationValue(ControlToValidate);

            foreach (ValidationAttribute va in property
                .GetCustomAttributes(typeof(ValidationAttribute), true)
                .OfType&lt;ValidationAttribute&gt;())
            {
                if (!va.IsValid(value))
                {
                    if (string.IsNullOrEmpty(ErrorMessage))
                    {
                        this.ErrorMessage = va.ErrorMessage;
                    }
                    return false;
                }
            }

            return true;
        }

        private Type GetValidatedType()
        {
            if (string.IsNullOrEmpty(SourceTypeName))
            {
                throw new InvalidOperationException(&quot;Null SourceTypeName can't be validated&quot;);
            }

            Type validatedType = Type.GetType(SourceTypeName);
            if (validatedType == null)
            {
                throw new InvalidOperationException(
                    string.Format(&quot;{0}:{1}&quot;, &quot;Invalid SourceTypeName&quot;, SourceTypeName));
            }

            return validatedType;
        }

        private PropertyInfo GetValidatedProperty(Type source)
        {
            PropertyInfo property = source.GetProperty(PropertyToValidate,
              BindingFlags.Public | BindingFlags.Instance);

            if (property == null)
            {
                throw new InvalidOperationException(
                  string.Format(&quot;{0}:{1}&quot;, &quot;Validated Property Does Not Exists&quot;, PropertyToValidate));
            }
            return property;
        }
    }
}
</pre>
<p>This creates a validator web control which has 'PropertyToValidate' and 'SourceTypeName'.  When a Validator web control is added to a page, it must have ControlToValidate, PropertyToValidate, and SourceTypeName specified or an error will be thrown. The validation method verifies the type and the property, gets the value of the property and finally, much like the Validatable abstract class, it loops over all ValidationAttributes and validates the value against that attribute.  You can use this with multiple attributes, so it doesn't hurt to add this validator to a property-- that just means you can add an attribute in the future and everything is already wired up!  That's pretty cool.</p>
<h2>Example</h2>
<p>As an example, I'm going to create a single page to **input** a Customer object. The customer object is very simple:</p>
<pre class="brush: csharp;">
 public class Customer : Validatable.Validatable&lt;Customer&gt;
    {
        [Required(ErrorMessage=&quot;UserId is Required&quot;)]
        public int UserId { get; set; }

        [DataType(DataType.PhoneNumber, ErrorMessage=&quot;Invalid Phone Number&quot;)]
        public string PhoneNumber { get; set; }

        [RegularExpression(@&quot;(^\d{5}(-\d{4}){0,1}$)&quot;, ErrorMessage=&quot;Invalid Zip Code&quot;)]
        public string ZipCode { get; set; }
    }
</pre>
<p>And the Page in full is collapsed below:</p>
<pre class="brush: xml; collapse: true; light: false; toolbar: true;">
&lt;%@ Page Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;Default.aspx.cs&quot; Inherits=&quot;Example._Default&quot; %&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
    &lt;asp:Label ID=&quot;lblStatus&quot; runat=&quot;server&quot; /&gt;
    &lt;asp:ValidationSummary ID=&quot;ValidationSummary1&quot; runat=&quot;server&quot; /&gt;
    &lt;div&gt;
        &lt;asp:FormView ID=&quot;FormView1&quot; runat=&quot;server&quot; DataSourceID=&quot;srcRepository&quot;
            Width=&quot;119px&quot; AllowPaging=&quot;True&quot;&gt;
            &lt;EditItemTemplate&gt;
                UserId:
                &lt;asp:TextBox ID=&quot;UserIdTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;UserId&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator1&quot; runat=&quot;server&quot; ControlToValidate=&quot;UserIdTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;UserId&quot; ErrorMessage=&quot;Invalid User Identification Number&quot;
                    SourceTypeName=&quot;Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;
                    Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                PhoneNumber:
                &lt;asp:TextBox ID=&quot;PhoneNumberTextBox&quot; runat=&quot;server&quot;
                    Text='&lt;%# Bind(&quot;PhoneNumber&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator2&quot; runat=&quot;server&quot; ControlToValidate=&quot;PhoneNumberTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;PhoneNumber&quot; OnInit=&quot;GetTypeName&quot; SourceTypeName=&quot;Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot; Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                ZipCode:
                &lt;asp:TextBox ID=&quot;ZipCodeTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;ZipCode&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator3&quot; runat=&quot;server&quot; ControlToValidate=&quot;ZipCodeTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;ZipCode&quot; SourceTypeName=&quot;Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot; Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                EntityType:
                &lt;asp:TextBox ID=&quot;EntityTypeTextBox&quot; runat=&quot;server&quot;
                    Text='&lt;%# Eval(&quot;EntityType&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                &lt;asp:LinkButton ID=&quot;UpdateButton&quot; runat=&quot;server&quot; CausesValidation=&quot;True&quot;
                    CommandName=&quot;Update&quot; Text=&quot;Update&quot; /&gt;
                &amp;nbsp;&lt;asp:LinkButton ID=&quot;UpdateCancelButton&quot; runat=&quot;server&quot;
                    CausesValidation=&quot;False&quot; CommandName=&quot;Cancel&quot; Text=&quot;Cancel&quot; /&gt;
            &lt;/EditItemTemplate&gt;
            &lt;InsertItemTemplate&gt;
                UserId:
                &lt;asp:TextBox ID=&quot;UserIdTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;UserId&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator1&quot; runat=&quot;server&quot; ControlToValidate=&quot;UserIdTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;UserId&quot;  OnInit=&quot;GetTypeName&quot;  Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                PhoneNumber:
                &lt;asp:TextBox ID=&quot;PhoneNumberTextBox&quot; runat=&quot;server&quot;
                    Text='&lt;%# Bind(&quot;PhoneNumber&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator2&quot; runat=&quot;server&quot; ControlToValidate=&quot;PhoneNumberTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;PhoneNumber&quot; OnInit=&quot;GetTypeName&quot;  Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                ZipCode:
                &lt;asp:TextBox ID=&quot;ZipCodeTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;ZipCode&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator3&quot; runat=&quot;server&quot; ControlToValidate=&quot;ZipCodeTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;ZipCode&quot; OnInit=&quot;GetTypeName&quot;  Text=&quot;*&quot;/&gt;
                &lt;br /&gt;
                EntityType:
                &lt;asp:TextBox ID=&quot;EntityTypeTextBox&quot; runat=&quot;server&quot;
                    Text='&lt;%# Eval(&quot;EntityType&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                &lt;asp:LinkButton ID=&quot;InsertButton&quot; runat=&quot;server&quot; CausesValidation=&quot;True&quot;
                    CommandName=&quot;Insert&quot; Text=&quot;Insert&quot; /&gt;
                &amp;nbsp;&lt;asp:LinkButton ID=&quot;InsertCancelButton&quot; runat=&quot;server&quot;
                    CausesValidation=&quot;False&quot; CommandName=&quot;Cancel&quot; Text=&quot;Cancel&quot; /&gt;
            &lt;/InsertItemTemplate&gt;
            &lt;ItemTemplate&gt;
                UserId:
                &lt;asp:Label ID=&quot;UserIdTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;UserId&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                PhoneNumber:
                &lt;asp:Label ID=&quot;PhoneNumberTextBox&quot; runat=&quot;server&quot;
                    Text='&lt;%# Bind(&quot;PhoneNumber&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                ZipCode:
                &lt;asp:Label ID=&quot;ZipCodeTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;ZipCode&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                EntityType:
                &lt;asp:Label ID=&quot;EntityTypeLabel&quot; runat=&quot;server&quot;
                    Text='&lt;%# Bind(&quot;EntityType&quot;) %&gt;' /&gt;
                &lt;br /&gt;
                &lt;asp:LinkButton ID=&quot;EditButton&quot; runat=&quot;server&quot; CausesValidation=&quot;False&quot;
                    CommandName=&quot;Edit&quot; Text=&quot;Edit&quot; /&gt;
                &amp;nbsp;&lt;asp:LinkButton ID=&quot;NewButton&quot; runat=&quot;server&quot; CausesValidation=&quot;False&quot;
                    CommandName=&quot;New&quot; Text=&quot;New&quot; /&gt;
            &lt;/ItemTemplate&gt;
        &lt;/asp:FormView&gt;
        &lt;asp:ObjectDataSource ID=&quot;srcRepository&quot; runat=&quot;server&quot;
            DataObjectTypeName=&quot;Example.Customer&quot; InsertMethod=&quot;Save&quot;
            oninserted=&quot;srcRepository_Saved&quot; onupdated=&quot;srcRepository_Saved&quot;
            SelectMethod=&quot;Get&quot; TypeName=&quot;Example.CustomerRepository&quot; UpdateMethod=&quot;Save&quot;&gt;&lt;/asp:ObjectDataSource&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Of particular note here is in the EditTemplate, you'll see </p>
<pre class="brush: xml;">
                  UserId:
                &lt;asp:TextBox ID=&quot;UserIdTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;UserId&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator1&quot; runat=&quot;server&quot; ControlToValidate=&quot;UserIdTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;UserId&quot; ErrorMessage=&quot;Invalid User Identification Number&quot;
                    SourceTypeName=&quot;Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;
                    Text=&quot;*&quot;/&gt;
</pre>
<p>in which the SourceTypeName must be the full Assembly Qualified Name.  This is necessary if the Validatable<T> and DataAnnotationValidator classes are in an external library.  This is a rather tedious property to fill for each validator.  Another way to get around this is to populate the SourceTypeName as seen in the InserItemTemplate, e.g.</p>
<pre class="brush: xml;">
                UserId:
                &lt;asp:TextBox ID=&quot;UserIdTextBox&quot; runat=&quot;server&quot; Text='&lt;%# Bind(&quot;UserId&quot;) %&gt;' /&gt;
                &lt;example:DataAnnotationValidator ID=&quot;DataAnnotationValidator1&quot; runat=&quot;server&quot; ControlToValidate=&quot;UserIdTextBox&quot; Display=&quot;Dynamic&quot;
                    PropertyToValidate=&quot;UserId&quot;  OnInit=&quot;GetTypeName&quot;  Text=&quot;*&quot;/&gt;
</pre>
<p>and the code in the code behind is very simple:</p>
<pre class="brush: csharp;">
        protected void GetTypeName(object sender, EventArgs e)
        {
            DataAnnotationValidator validator = (DataAnnotationValidator)sender;
            validator.SourceTypeName = new Customer().EntityType.AssemblyQualifiedName;
        }
</pre>
<p>Also notice that the first validator (the one with the assembly qualified name) has an ErrorMessage property specified.  Doing this allows you to override  the error message returned from the validated object.  We can do this if the model says "UserId" and you want the user to see this property referred to as "User Identification".  </p>
<h2>Conclusion</h2>
<p>Sometimes dabbling in other technologies can open the door for new and simpler ways of doing things.  I like this example because it allows you to build web applications quickly and easily, while making them maintainable in the future (new validations only have to be added to the model, not to every control where the model must be validated).</p>
<p>For further reference, this project is linked below.  Please download and modify if necessary.<br />
<a href='http://www.ipreferjim.com/site/wp-content/uploads/2010/05/Validatable.zip'>Validatable.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/system-componentmodel-dataannotations-for-asp-net-web-forms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Font-Face generator</title>
		<link>http://www.ipreferjim.com/site/2010/05/font-face-generator/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/font-face-generator/#comments</comments>
		<pubDate>Tue, 18 May 2010 16:13:40 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=268</guid>
		<description><![CDATA[CSS3 allows you to create custom font-faces so a user will see fonts exactly as you'd like them to be seen, without forcing the developer/designer to export all custom fonts as graphics.
Font Squirrel has an excellent utility that will convert your font files to the common formats and generate the stylesheet required to use these [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_270" class="wp-caption alignright" style="width: 310px"><a href="http://www.ipreferjim.com/site/wp-content/uploads/2010/05/fontgenerator.png"><img class="size-medium wp-image-270" title="fontgenerator" src="http://www.ipreferjim.com/site/wp-content/uploads/2010/05/fontgenerator-300x175.png" alt="@font-face Kit Generator at fontsquirrel.com" width="300" height="175" /></a><p class="wp-caption-text">@font-face Kit Generator User Interface</p></div>
<p>CSS3 allows you to create custom font-faces so a user will see fonts exactly as you'd like them to be seen, without forcing the developer/designer to export all custom fonts as graphics.</p>
<p>Font Squirrel has an excellent utility that will convert your font files to the common formats and generate the stylesheet required to use these new font-faces.  That generator can be found <a title="here" href="http://www.fontsquirrel.com/fontface/generator">here</a>.  The generator creates a demo.html file that displays all of your newly created fonts.</p>
<p>As an example, the header text on this site uses a custom font.  Go ahead and view the source and see how it works.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/font-face-generator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding a user&#8217;s local time from UTC offset</title>
		<link>http://www.ipreferjim.com/site/2010/05/finding-a-users-local-time-from-utc-offset/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/finding-a-users-local-time-from-utc-offset/#comments</comments>
		<pubDate>Tue, 04 May 2010 19:47:43 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=264</guid>
		<description><![CDATA[I answered a question over at StackOverflow, and I really liked the answer, so I thought I would share this nifty extension method:


        /// &#60;summary&#62;
        /// Convert a given DateTime object to a user's local time,
      [...]]]></description>
			<content:encoded><![CDATA[<p>I answered a question over at <a href="http://stackoverflow.com/questions/2732526/display-datetime-in-gridview-using-users-time/2732610">StackOverflow</a>, and I really liked the answer, so I thought I would share this nifty extension method:</p>
<pre class="brush: csharp;">

        /// &lt;summary&gt;
        /// Convert a given DateTime object to a user's local time,
        /// taking into account changes in TimeZone rules.
        /// For example, if you were to perform this operation on
        /// a time now, during EST Daylight Saving, and that time falls
        /// outside the scope of Daylight Saving time, the rule will adjust accordingly.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;dateTime&quot;&gt;The DateTime object&lt;/param&gt;
        /// &lt;param name=&quot;offset&quot;&gt;offset from UTC&lt;/param&gt;
        /// &lt;returns&gt;User's local time&lt;/returns&gt;
        public static DateTime ConvertToLocalDateTime(this DateTime dateTime, int offset)
        {
            TimeZoneInfo destinationTimeZone = TimeZoneInfo.GetSystemTimeZones()
               .Where(x =&gt; x.BaseUtcOffset.Hours.Equals(offset)).FirstOrDefault();

            var rule = destinationTimeZone.GetAdjustmentRules().Where(x =&gt;
                x.DateStart &lt;= dateTime &amp;&amp; dateTime &lt;= x.DateEnd)
                .FirstOrDefault();

            TimeSpan baseOffset = TimeSpan.Zero;
            if (rule != null)
            {
                baseOffset -= destinationTimeZone.IsDaylightSavingTime(dateTime) ?
                    rule.DaylightDelta : TimeSpan.Zero;
            }

            DateTimeOffset dto = DateTimeOffset.Parse(dateTime.ToString());
            return new DateTime(TimeZoneInfo
                     .ConvertTimeFromUtc(dateTime,
                            destinationTimeZone).Ticks + baseOffset.Ticks);
        }
</pre>
<p>The summary basically says it all. I ran through a couple of tests with this, I'd like to know if anyone uses this and makes modifications to it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/finding-a-users-local-time-from-utc-offset/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate.Criterion Extensions workaround</title>
		<link>http://www.ipreferjim.com/site/2010/05/nhibernate-criterion-extensions-workaround/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/nhibernate-criterion-extensions-workaround/#comments</comments>
		<pubDate>Mon, 03 May 2010 22:30:50 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Expression]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=257</guid>
		<description><![CDATA[I've been working with Fluent NHibernate for the past month or so, and I realized while writing an NHibernate query that the NHibernate Criterion's Restrictions class isn't very refactor-friendly.  The refactorability of Fluent NHibernate is ultimately why we've decided to use it.  It does take a little longer to set up than some [...]]]></description>
			<content:encoded><![CDATA[<p>I've been working with <a href="http://www.fluentnhibernate.org/">Fluent NHibernate</a> for the past month or so, and I realized while writing an NHibernate query that the NHibernate Criterion's Restrictions class isn't very refactor-friendly.  The refactorability of Fluent NHibernate is ultimately why we've decided to use it.  It does take a little longer to set up than some other ORMs, but in the long-run it's nice to be able to change a property name and refactor.  </p>
<p>... except the property names are hard-coded in the Criteria!  </p>
<p>My workaround for this is to use a bit of static reflection a-la-FNH, and maintain code that is easily refactored.</p>
<p>For instance, I've created a static utility class (Showing the Restrictions.Eq() substitute):</p>
<pre class="brush: csharp;">
  public static class CriterionExtensions
    {
        public static SimpleExpression Eq&lt;T&gt;(
                Expression&lt;Func&lt;T, object&gt;&gt; exp, object value
        )
        {
            var memberExpression = GetMemberExpression(exp);
            string propertyName = ((PropertyInfo)memberExpression.Member).Name;
            if (!string.IsNullOrEmpty(propertyName))
                return Restrictions.Eq(propertyName, value);
            else
                return null;
        }

        private static MemberExpression GetMemberExpression&lt;T&gt;(
                Expression&lt;Func&lt;T, object&gt;&gt; expression
        )
        {
            MemberExpression memberExpression = null;
            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                var body = (UnaryExpression)expression.Body;
                memberExpression = body.Operand as MemberExpression;
            }
            else if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                memberExpression = expression.Body as MemberExpression;
            }
            if (memberExpression == null)
            {
                throw new ArgumentException(&quot;Not a member access&quot;, &quot;member&quot;);
            }
            return memberExpression;
        }
    }
</pre>
<p>And to use this code, you can create an aliased using directive and call it in code:</p>
<pre class="brush: csharp;">
    using Ensure = MyNamespace.Extensions.Criterion.CriterionExtensions;
    /* class declarations and whatnot */
     internal IEnumerable&lt;Product&gt; GetAll(int shelfNumber)
      {
          var session = SessionManager.GetCurrentSession();
          return session.CreateCriteria&lt;Product&gt;()
              .Add(Ensure.Eq&lt;Product&gt;(x =&gt; x.ShelfNumber, shelfNumber))
              .List&lt;Product&gt;();
      }
</pre>
<p>It's pretty simple to use and is easily refactored.  You may be able to add your *extensions* to a namespace: NHibernate.Criterion and call your class Restrictions, but I didn't try this (I don't like mixing namespaces).  Let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/nhibernate-criterion-extensions-workaround/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CopyCat Rails&#8217; Time Extensions</title>
		<link>http://www.ipreferjim.com/site/2010/05/copycat-activesupport-time-extensions/</link>
		<comments>http://www.ipreferjim.com/site/2010/05/copycat-activesupport-time-extensions/#comments</comments>
		<pubDate>Mon, 03 May 2010 21:22:47 +0000</pubDate>
		<dc:creator>jimschubert</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://www.ipreferjim.com/site/?p=254</guid>
		<description><![CDATA[I've become a fan of Ruby's simple syntax.  My favorite thing is the ActiveSupport's Numeric Time Extensions. I'm starting a library of useful extensions, and I'm going to be adding a number of shortcuts to mock these extensions.
For those of you that don't want to follow the link, check out the syntax:

  # [...]]]></description>
			<content:encoded><![CDATA[<p>I've become a fan of Ruby's simple syntax.  My favorite thing is the <a href="http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html">ActiveSupport's Numeric Time Extensions</a>. I'm starting a library of useful extensions, and I'm going to be adding a number of shortcuts to mock these extensions.</p>
<p>For those of you that don't want to follow the link, check out the syntax:</p>
<pre class="brush: ruby;">
  # equivalent to Time.now.advance(:months =&gt; 1)
  1.month.from_now

  # equivalent to Time.now.advance(:years =&gt; 2)
  2.years.from_now

  # equivalent to Time.now.advance(:months =&gt; 4, :years =&gt; 5)
  (4.months + 5.years).from_now
</pre>
<p>Here is what I've gotten so far (it only includes int for now):</p>
<pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
public static class DateExtensionsThatMockRuby
    {
        /// &lt;summary&gt;
        /// Retrieve the number of ticks for x Days.
        /// &lt;example&gt;long ticks = 5.Days();&lt;/example&gt;
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;ticks&lt;/returns&gt;
        public static long Days(this int i)
        {
            return new TimeSpan(i, 0, 0, 0).Ticks;
        }

        /// &lt;summary&gt;
        /// Retrieve the number of ticks for x Hours.
        /// &lt;/summary&gt;
        /// &lt;example&gt;long ticks = 15.Hours();&lt;/example&gt;
        /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;ticks&lt;/returns&gt;
        public static long Hours(this int i)
        {
            return new TimeSpan(0, i, 0, 0).Ticks;
        }

        /// &lt;summary&gt;
        /// Retrieve the number of ticks for x Minutes
        /// &lt;/summary&gt;
        /// &lt;example&gt;long ticks = 97.Minutes();&lt;/example&gt;
        /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;ticks&lt;/returns&gt;
        public static long Minutes(this int i)
        {
            return new TimeSpan(0, i, 0).Ticks;
        }

        /// &lt;summary&gt;
        /// Retrieve the number of ticks for x Seconds
        /// &lt;/summary&gt;
        /// &lt;example&gt;long ticks = 3000.Seconds();&lt;/example&gt;
        /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;ticks&lt;/returns&gt;
        public static long Seconds(this int i)
        {
            return new TimeSpan(0, 0, i).Ticks;
        }

        /// &lt;summary&gt;
        /// Retrieve the number of ticks for x Milliseconds
        /// &lt;/summary&gt;
        /// &lt;example&gt;long ticks = 3000.Milliseconds();&lt;/example&gt;
        /// &lt;param name=&quot;i&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;ticks&lt;/returns&gt;
        public static long Milliseconds(this int i)
        {
            return new TimeSpan(0, 0, 0, 0, i).Ticks;
        }

        /// &lt;summary&gt;
        /// Retrieve a DateTime object from ticks
        /// &lt;example&gt;DateTime dt = 236423690923466.AsDateTime();&lt;/example&gt;
        /// /// &lt;example&gt;DateTime dt = 10.Days().AsDateTime();&lt;/example&gt;
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ticks&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;DateTime&lt;/returns&gt;
        public static DateTime AsDateTime(this long ticks)
        {
            return new DateTime(ticks);
        }

        /// &lt;summary&gt;
        /// Retrieve a DateTime object from ticks
        /// &lt;example&gt;DateTime dt = 236423690923466.AsDateTime(DateTimeKind.Utc);&lt;/example&gt;
        /// /// &lt;example&gt;DateTime dt = 10.Days().AsDateTime(DateTimeKind.Utc);&lt;/example&gt;
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ticks&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;DateTime&lt;/returns&gt;
        public static DateTime AsDateTime(this long ticks, DateTimeKind kind)
        {
            return new DateTime(ticks, kind);
        }
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ipreferjim.com/site/2010/05/copycat-activesupport-time-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
