<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>Code Capers</title>
    <description>The Ninja Coding Dojo</description>
    <link>http://www.codecapers.com/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 2.6.0.5</generator>
    <language>en-US</language>
    <blogChannel:blogRoll>http://www.codecapers.com/opml.axd</blogChannel:blogRoll>
    <blogChannel:blink>http://www.dotnetblogengine.net/syndication.axd</blogChannel:blink>
    <dc:creator>Michael Ceranski</dc:creator>
    <dc:title>Code Capers</dc:title>
    <geo:lat>0.000000</geo:lat>
    <geo:long>0.000000</geo:long>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/codecapers" /><feedburner:info uri="codecapers" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-sa/3.0/</creativeCommons:license><item>
      <title>A Neat Way to Set the Cursor in WPF</title>
      <description>&lt;p style="margin: 0px 0px 1em; color: #4c4c4c; font-family: Verdana, Arial, sans-serif; font-size: 11px;"&gt;I found this&amp;nbsp;&lt;a style="color: #b10069; text-decoration: initial;" href="http://stackoverflow.com/questions/307004/changing-the-cursor-in-wpf-sometimes-works-sometimes-doesnt" target="_blank"&gt;excellent post on stack overflow&lt;/a&gt;&amp;nbsp;which uses a&amp;nbsp;&lt;a style="color: #b10069; text-decoration: initial;" href="http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx" target="_blank"&gt;Stack&lt;/a&gt;&amp;nbsp;to set and unset the cursor. Normally when you want to set the wait cursor in your application you would use a&amp;nbsp;&lt;strong&gt;try/finally&lt;/strong&gt;&amp;nbsp;block to ensure that the cursor eventually gets set back to the original value:&lt;/p&gt;
&lt;pre class="brush: csharp;" style="color: #4c4c4c; font-size: 11px;"&gt;Mouse.OverrideCursor = Cursors.Wait;
try {
    return Foo.Execute();
}
finally
{
    Mouse.OverrideCursor = null;
}
&lt;/pre&gt;
&lt;p style="margin: 0px 0px 1em; color: #4c4c4c; font-family: Verdana, Arial, sans-serif; font-size: 11px;"&gt;Don't get me wrong here...There is nothing wrong with using a try/finally. However, there is an alternative way to solve the same problem which I personally think is a more elegant and foolproof. So without further ado, here is the OverrideCursor class.&lt;/p&gt;
&lt;pre class="brush: csharp;" style="color: #4c4c4c; font-size: 11px;"&gt;static Stack&amp;lt;Cursor&amp;gt; s_Stack = new Stack&amp;lt;Cursor&amp;gt;();

public OverrideCursor(Cursor changeToCursor) {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
        Mouse.OverrideCursor = changeToCursor;
}

public void Dispose() {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count &amp;gt; 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
        Mouse.OverrideCursor = cursor;
}
&lt;/pre&gt;
&lt;p style="margin: 0px 0px 1em; color: #4c4c4c; font-family: Verdana, Arial, sans-serif; font-size: 11px;"&gt;With the help of this class, we can ditch the try/finally and use this block of code instead:&lt;/p&gt;
&lt;pre class="brush: csharp;" style="color: #4c4c4c; font-size: 11px;"&gt;using (new OverrideCursor(Cursors.Wait)) {
    return Foo.Execute();
}
&lt;/pre&gt;
&lt;p style="margin: 0px 0px 1em; color: #4c4c4c; font-family: Verdana, Arial, sans-serif; font-size: 11px;"&gt;So what is happening here? Well, in the OverrideCursor's constructor the current cursor is pushed on the stack and the cursor is updated to whatever you value you passed in as an argument. Later on when the object is Disposed the original cursor is fetched from the stack and restored. Since the code that launches my dialog is wrapped in a using statement the OverrideCursor instance will be disposed as soon as my form is displayed. Neat Trick!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=8afbsaD834Y:8_A1ky2RWOI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=8afbsaD834Y:8_A1ky2RWOI:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=8afbsaD834Y:8_A1ky2RWOI:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=8afbsaD834Y:8_A1ky2RWOI:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=8afbsaD834Y:8_A1ky2RWOI:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=8afbsaD834Y:8_A1ky2RWOI:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=8afbsaD834Y:8_A1ky2RWOI:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/8afbsaD834Y" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/8afbsaD834Y/post.aspx</link>
      <comments>http://www.codecapers.com/post/A-Neat-Way-to-Set-the-Cursor-in-WPF.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=31f66ce2-d95b-4794-ba6c-fe75b7071d32</guid>
      <pubDate>Fri, 30 Nov 2012 12:17:00 -0100</pubDate>
      <category>dotNet</category>
      <category>Tech</category>
      <category>WPF</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=31f66ce2-d95b-4794-ba6c-fe75b7071d32</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=31f66ce2-d95b-4794-ba6c-fe75b7071d32</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/A-Neat-Way-to-Set-the-Cursor-in-WPF.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=31f66ce2-d95b-4794-ba6c-fe75b7071d32</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=31f66ce2-d95b-4794-ba6c-fe75b7071d32</feedburner:origLink></item>
    <item>
      <title>My First Arduino Robot</title>
      <description>&lt;p&gt;Late last year, I discovered the Arduino. The Arduino is an open-source physical computing platform based on a simple i/o board and a development environment that implements the &lt;a href="http://www.processing.org/"&gt;Processing&lt;/a&gt;/&lt;a href="http://wiring.org.co/"&gt;Wiring&lt;/a&gt; language. The Processing/Wiring language is a simplified version of the C programming language that has extensions to access the underlying hardware. The Arduino can be used to develop stand-alone interactive objects such as robots, led displays or 3D printers like the &lt;a href="http://store.makerbot.com/replicator.html"&gt;MakerBot Replicator&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Since I write software for a living, I am extremely comfortable with the software aspect of the Arduino. However I was a little worried about my lack of electronic skills. Just to give you some background, at the beginning of this project I knew absolutely nothing about electronics. I never used a soldering iron or even held a &lt;a href="http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=multimeter&amp;amp;source=web&amp;amp;cd=1&amp;amp;ved=0CLYBEBYwAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMultimeter&amp;amp;ei=v3_FT6ijLcOI6AG98N3hBg&amp;amp;usg=AFQjCNGPEmB9aLhbJC_SRDs40282n17jaQ" target="_blank"&gt;multimeter&lt;/a&gt;. So its goes without saying that I had a lot to learn. I spent a lot of time reading blogs, watching YouTube videos and I even bought the book “Electronics for Dummies”. I typically try to avoid the Dummy books because I find the title to be self deprecating. However in this case, the title fit. Fortunately, after a couple of fun filled weeks, I learned how to solder, felt comfortable using a multimeter and started to understand the basic concepts. I eventually got to the point where I felt I could build something without electrocuting myself! After some brainstorming I decided to build a robot! &lt;/p&gt;  &lt;p&gt;The first step in building a robot is to pick a chassis. If you are handy, you can build something from scratch or hack apart an existing toy. In my case, I decided to use a chassis that I found on eBay. The kit I purchased was actually the 2WD Mobile Platform from &lt;a href="http://www.dfrobot.com/index.php?route=product/product&amp;amp;path=37&amp;amp;product_id=65" target="_blank"&gt;DFRobot&lt;/a&gt;. Buying a pre-built platform has some advantages. Mainly because the kit comes with 2 motors, mounting hardware, wheels, hookup wire and a platform large enough to attach an Arduino, some shields and a small breadboard. The kit also comes with a toggle switch and a six AA battery holder. If you are a beginner like me, then I would recommend buying a kit because it will save you the time of trying to figure out which parts to buy. Finding parts on sites like &lt;a href="http://www.mouser.com/" target="_blank"&gt;Mouser&lt;/a&gt; or &lt;a href="http://www.digikey.com/" target="_blank"&gt;Digi-Key&lt;/a&gt; can be intimidating for beginners.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=2WD_MobilePlatformKit.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="2WD Mobile Platform Kit" border="0" alt="2WD_MobilePlatformKit" src="http://www.codecapers.com/image.axd?picture=2WD_MobilePlatformKit_thumb.jpg" width="244" height="168" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://www.codecapers.com/image.axd?picture=robot%20chassis.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="robot chassis" border="0" alt="robot chassis" src="http://www.codecapers.com/image.axd?picture=robot%20chassis_thumb.jpg" width="164" height="130" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;While I was waiting for my chassis to arrive, I purchased a &lt;a href="http://www.adafruit.com/products/81" target="_blank"&gt;motor shield kit from Adafruit&lt;/a&gt;. There are a variety of motor shields on the market but I settled on the Adafruit board for a few reasons. First of all it has excellent documentation. If you are a newbie like me, then getting a step by step instruction guide with pictures is very important. Second, I know that the Adafruit team stands behind their products. If I run into any issues I can rest assured that someone will help me out. Finally, the shield comes with a software library and a sample sketch. On top of all that, the hardware and software are open source! If you are going to build a robot then I would highly recommend buying this shield. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=ada_motorshield.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="Adafruit Motorshield" border="0" alt="ada_motorshield" src="http://www.codecapers.com/image.axd?picture=ada_motorshield_thumb.jpg" width="434" height="330" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Once you assemble the motor shield you can simply stack it on top of an Arduino board. The male pins from the motor shield plug directly into the female headers of the Arduino board beneath it. The motor shield will occupy quite a few pins. In the end, you will be left with digital pins 2 and 13 and all of the analog pins. The analog pins are conveniently broken out in the bottom right hand corner. The board also gives you easy access to additional +5 volt and ground connections. In order to make prototyping easier and to increase the reusability of the shield, I soldered a 6 pin female header across each of the three rows in the bottom right hand corner of the PCB. I also ended up placing a 2 pin header across digital pins 0 and 1 which are used for TX (transmit) and RX (receive). The TX and RX pins are used for communication to the Arduino, for example when you upload a sketch to the Arduino or when you are sending serial commands from an external device. As a tip, if you have the RX and TX pins wired to a separate device for processing commands, you will need to disconnect these wires before you can upload any sketches.&lt;/p&gt;  &lt;p&gt;For phase one of my project, I decided to make my robot autonomous. Autonomous means that the robot can drive around without anyone controlling it. In order for this to work, the robot needs to be able to detect and avoid obstacles. In other words, it needs to be able to see. The easiest way to implement this functionality is to use some sort of distance sensor. After a bit of research I decided to use the &lt;a href="http://www.parallax.com/tabid/768/ProductID/92/Default.aspx" target="_blank"&gt;Parallax PING))) Ultrasonic sensor&lt;/a&gt;. There are cheaper distance sensors available but the PING sensor had sample code and I knew it would be easy to use.&lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;a href="http://www.codecapers.com/image.axd?picture=ping_sensor.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="Parallax PING}}} Ultrasonic Sensor" border="0" alt="ping_sensor" src="http://www.codecapers.com/image.axd?picture=ping_sensor_thumb.jpg" width="216" height="137" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The PING sensor was extremely easy to setup. Within minutes of using it, I had the &lt;a href="http://arduino.cc/en/Tutorial/Ping" target="_blank"&gt;sample sketch&lt;/a&gt; working. After I attached it to my robot chassis, I quickly realized that my robot lacked peripheral vision. If an object was not directly in front of the PING sensor the robot would crash into it. I solved this problem by purchasing a &lt;a href="http://www.sparkfun.com/products/10335" target="_blank"&gt;pan and tilt bracket&lt;/a&gt;from Sparkfun. The pan and tit bracket uses two servos which allows for 180 degrees of movement vertically and horizontally. I mounted the PING sensor on top of the bracket and hooked the servo wires to the motor shield. After a little bit of coding, my robot was able to take distance measurements in multiple directions!&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;a href="http://www.codecapers.com/image.axd?picture=pan_tilt_bracket.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="The pan tilt bracket from SFE" border="0" alt="pan_tilt_bracket" src="http://www.codecapers.com/image.axd?picture=pan_tilt_bracket_thumb.jpg" width="195" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Unfortunately, with the addition of the two servos I exceeded the amount of amps that six AA batteries could provide to the motor shield. Six AA batteries will provide you with approximately 9 volts at 1-1.5 amp hours (series gives you more volts but not more amp hours). As a result, I decided to invest in some Lipo batteries. The Lipo batteries are small and light enough for the robot to carry and provide sufficient amperage to drive 2 motors and 2 servos. After doing some price comparisons, I ended up buying my Lipo batteries from &lt;a href="http://www.hobbyking.com" target="_blank"&gt;Hobby King&lt;/a&gt;. I bought one &lt;a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=9165" target="_blank"&gt;1300mAh 2S 20C&lt;/a&gt; battery to run the Arduino and a &lt;a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=8932" target="_blank"&gt;2200mAh 3S 20C&lt;/a&gt; to supply power to the motor shield. I also picked up some &lt;a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=9572" target="_blank"&gt;XT60 connectors&lt;/a&gt; to make it easier to connect and disconnect the batteries. Of course, Lipo batteries are useless without a &lt;a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=8932" target="_blank"&gt;charger&lt;/a&gt; so I threw one of those in my cart too. At the end of the day, I ended up spending more money than I wanted too but since the batteries are rechargeable they can be used on other projects.&lt;/p&gt;  &lt;p&gt;Once I got the robot to work autonomously I quickly got bored of watching it drive aimlessly around the room. So I decided to add a remote control mode. As a starting point, I found an &lt;a href="http://www.instructables.com/id/Androino-Talk-with-an-Arduino-from-your-Android-d/" target="_blank"&gt;instructable&lt;/a&gt; which used a $10 &lt;a href="http://www.dealextreme.com/p/jy-mcu-arduino-bluetooth-wireless-serial-port-module-104299" target="_blank"&gt;Bluetooth adapter&lt;/a&gt; paired with an Android phone as a remote control&lt;a href="http://www.dealextreme.com/p/jy-mcu-arduino-bluetooth-wireless-serial-port-module-104299" target="_blank"&gt;.&lt;/a&gt; Once paired, the BlueTooth module can be used as a virtual serial port. Then it becomes a simple matter of sending and receiving serial commands in order to make the robot move. In the instructable, the author uses a Python script to send commands, but I decided to use a native Android app instead. So I downloaded the &lt;a href="http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=eclipse%20ide&amp;amp;source=web&amp;amp;cd=1&amp;amp;ved=0CGcQFjAA&amp;amp;url=http%3A%2F%2Fwww.eclipse.org%2F&amp;amp;ei=KoXFT_auF4Gq8ASQydigBg&amp;amp;usg=AFQjCNFLDQCqoSDxwm1phYDfj2aJnL2dPA" target="_blank"&gt;Eclipse IDE&lt;/a&gt; and started working my way through the “hello world” Android tutorials. To my surprise, Android development is easy to learn. There is ample documentation and plenty of community support. I also got lucky because the Android SDK includes a BlueTooth Chat application. I ended up using this application as the basis for my remote control app.&lt;/p&gt;  &lt;p&gt;In order to switch the robot between autonomous and remote control mode I added a toggle switch to my robot. The toggle switch controls the power to the BlueTooth adapter. I use one of the analog pins on the Arduino to check if the Bluetooth module is active (HIGH) or inactive (LOW). If the BlueTooth module is active I process serial commands, otherwise I run the autonomous code.&lt;/p&gt;  &lt;h2&gt;The Arduino Code&lt;/h2&gt;  &lt;p&gt;Here is a brief summary of the Arduino code. The full source code is available on &lt;a href="https://bitbucket.org/mceranski/robie" target="_blank"&gt;GitHub&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The Adafruit motor library is really simple to use. Simply add a reference and use the methods to control the speed and direction of the motors. If you are using servos with the motor shield you can leverage the existing Servo library that comes with the Arduino IDE. Here are some examples of the methods I used to control the motors.&lt;/p&gt;  &lt;pre class="brush: cpp;"&gt;void brake()
{
  leftMotor.run(RELEASE);
  rightMotor.run(RELEASE);
}

void moveForward( int duration = 110 )
{
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
  delay(duration);
}

void moveBackward( int duration = 1000 )
{
  leftMotor.run(BACKWARD);
  rightMotor.run(BACKWARD);
  delay(duration); //amount of time it takes to back up 
}

void turnLeft( int duration = 480)
{
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD); //turns off the motor
  delay(duration);
}

void turnRight( int duration = 480 )
{
  leftMotor.run(BACKWARD);//turns off the motor
  rightMotor.run(FORWARD); 
  delay(duration);
}
&lt;/pre&gt;

&lt;p&gt;For processing serial commands, I leveraged the &lt;a href="http://husks.wordpress.com/2011/05/23/a-minimal-arduino-library-for-processing-serial-commands/"&gt;SerialCommand&lt;/a&gt; library. The library allows you to map incoming commands with methods in your Arduino sketch. For example, if you send the command “F 1000” to the Arduino my code will run the forwardCommand. The library also gives you easy access to the arguments sent with the command. For example the command “F 1000” has two parts. The command is “F” for “Forward” and the argument is 1000. In my case, this means move forward for 1000 milliseconds or 1 second. Here is the code: &lt;/p&gt;

&lt;pre class="brush: cpp;"&gt;void setupSerial()
{
  Serial.begin(9600);
  sCmd.setTerm(';');
  sCmd.addCommand(&amp;quot;F&amp;quot;, forwardCommand );
  sCmd.addCommand(&amp;quot;f&amp;quot;, forwardCommand );
  
  sCmd.addCommand(&amp;quot;B&amp;quot;, backwardCommand );
  sCmd.addCommand(&amp;quot;b&amp;quot;, backwardCommand );
  
  sCmd.addCommand(&amp;quot;L&amp;quot;, turnLeftCommand );
  sCmd.addCommand(&amp;quot;l&amp;quot;, turnLeftCommand );
  
  sCmd.addCommand(&amp;quot;R&amp;quot;, turnRightCommand );
  sCmd.addCommand(&amp;quot;r&amp;quot;, turnRightCommand );
  
  sCmd.addCommand(&amp;quot;?&amp;quot;, showCommands );
  sCmd.setDefaultHandler( unrecognized );
}

void showCommands()
{
  Serial.println( &amp;quot;Hello Master. I am awaiting your commands.&amp;quot; );
  Serial.println( &amp;quot;------------------------------------------&amp;quot; );
  Serial.println( &amp;quot;Commands must be terminated with a semi-colon:&amp;quot; );
  Serial.println( &amp;quot;\tMove (F)orward - F &amp;lt;# of steps&amp;gt;&amp;quot;);
  Serial.println( &amp;quot;\tMove (B)ackward - B &amp;lt;# of steps&amp;gt;&amp;quot;);
  Serial.println( &amp;quot;\tTurn (R)ight - R &amp;lt;value&amp;gt;&amp;quot;);
  Serial.println( &amp;quot;\tTurn (L)eft - L &amp;lt;value&amp;gt;&amp;quot;);
}

void unrecognized(const char *command)
{
  Serial.println(&amp;quot;Huh?&amp;quot;);
}
&lt;/pre&gt;

&lt;p&gt;Here is the code that uses conditional logic to determine whether the robot is in autonomous or remote control mode:&lt;/p&gt;

&lt;pre class="brush: cpp;"&gt;void loop()
{   
  //check if we are using the bluetooth module, if so listen for commands only
  if( digitalRead(btPin) == HIGH ) { 
    sCmd.readSerial();
    return;
  }
  
  //do autononmous functions ....
}
&lt;/pre&gt;

&lt;h2&gt;The Android App – Remote Control&lt;/h2&gt;

&lt;p&gt;Here is a brief summary of the Android code. The full source code is available on &lt;a href="https://bitbucket.org/mceranski/robieremote" target="_blank"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=image_26.png"&gt;&lt;img style="display: inline; background-image: none;" title="The Android Remote Control App" border="0" alt="image" src="http://www.codecapers.com/image.axd?picture=image_thumb_26.png" width="222" height="363" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The UI is pretty simple. It’s basically just a joystick, a few labels and a connection dialog which allows you to choose which BlueTooth device to connect to. For the joystick I used the &lt;a href="http://code.google.com/p/mobile-anarchy-widgets/"&gt;Mobile Anarchy Widgets&lt;/a&gt;. At this point, my app still needs quite a bit of work. However, the basic concept is proven and its just a matter of adding some trim and polish.&lt;/p&gt;

&lt;p&gt;Here is the chunk of code that creates the virtual serial connection:&lt;/p&gt;

&lt;pre class="brush: java;"&gt;String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
String deviceName = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);         
try {
    Method m = device.getClass().getMethod(&amp;quot;createRfcommSocket&amp;quot;, new Class[] {int.class});
    socket = (BluetoothSocket) m.invoke(device, 1);
    socket.connect();
    txtHeader.setText(&amp;quot;connected to device: &amp;quot; + deviceName );
    outputStream = socket.getOutputStream();
    //InputStream inputStream = socket.getInputStream();                
} catch (Exception e) {
    txtHeader.setText(&amp;quot;connection failed: &amp;quot; + e.getMessage() );
}
&lt;/pre&gt;

&lt;p&gt;When the joystick is moved, a event handler is called. I then look at the location of the joystick and send the appropriate command to the Arduino. I also added a little bit of code to control how often a command is sent. If you send too many commands at once you can overflow the serial port and the app will crash.&lt;/p&gt;

&lt;pre class="brush: java;"&gt;private JoystickMovedListener _listener = new JoystickMovedListener() {

Date lastSent = new Date();

@Override
public void OnMoved(int pan, int tilt) {
    txtX.setText(Integer.toString(pan));
    txtY.setText(Integer.toString(tilt));

    if( socket == null || outputStream == null ) return;
    
    //only send a message once a second
    long diff = new Date().getTime() - lastSent.getTime();
    if( diff &amp;lt; 500 ) return;
    lastSent = new Date();
    
    String command = getCommand( pan, tilt );
    if( command.length() == 0 ) return;
    
    byte[] bytes = command.getBytes();
    try {
        outputStream.write(bytes);
        outputStream.flush();
    } catch (IOException e) {                
        e.printStackTrace();
    }                            
}

public String getCommand( int x, int y )
{
    if( ( x &amp;gt;= -3 &amp;amp;&amp;amp; x &amp;lt;= 3 ) &amp;amp;&amp;amp; y &amp;gt; 3 )
        return &amp;quot;B 1000;&amp;quot;;
    
    if( ( x &amp;gt;= -3 &amp;amp;&amp;amp; x &amp;lt;= 3 ) &amp;amp;&amp;amp; y &amp;lt; -3 )
        return &amp;quot;F 1000;&amp;quot;;
    
    if( ( y &amp;gt;= -3 &amp;amp;&amp;amp; y &amp;lt;= 3 ) &amp;amp;&amp;amp; x &amp;lt; -3 )
        return &amp;quot;L 1000;&amp;quot;;
    
    if( ( y &amp;gt;= -3 &amp;amp;&amp;amp; y &amp;lt;= 3 ) &amp;amp;&amp;amp; x &amp;gt; 3 )
        return &amp;quot;R 1000;&amp;quot;;
    
    return &amp;quot;&amp;quot;;
}

@Override
public void OnReleased() {
    txtX.setText(&amp;quot;released&amp;quot;);
    txtY.setText(&amp;quot;released&amp;quot;);
}

public void OnReturnedToCenter() {
    txtX.setText(&amp;quot;stopped&amp;quot;);
    txtY.setText(&amp;quot;stopped&amp;quot;);
};
&lt;/pre&gt;

&lt;h2&gt;Introducing “Robie” the Robot&lt;/h2&gt;

&lt;p&gt;Here is a video of “Robie” the Robot (my kids named him) running in autonomous mode. This video was taken prior to adding the remote control capabilities.&lt;/p&gt;

&lt;p&gt;&lt;object style="height: 390px; width: 640px"&gt;&lt;param name="movie" value="http://www.youtube.com/v/0EH9TZQCuMY?version=3&amp;amp;feature=player_embedded"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;param name="allowScriptAccess" value="always"&gt;&lt;embed src="http://www.youtube.com/v/0EH9TZQCuMY?version=3&amp;amp;feature=player_embedded" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360"&gt;&lt;/object&gt;&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;One of the best things about building this robot was that my kids are now interested in electronics. They love to ask me questions about how the robot works and they are extremely curious about the projects that I have sitting on my workbench. For years I have tried to get them interested in engineering but I could never find the right project to motivate them to learn. However, the Arduino seems to have a special appeal towards makers and even children. As proof, here is a picture that my daughter Noelle drew of her and I working on “Robie”. &lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=Noelles_Drawing_of_Robie.jpg"&gt;&lt;img style="display: inline; background-image: none;" title="Noelles_Drawing_of_Robie" border="0" alt="Noelles_Drawing_of_Robie" src="http://www.codecapers.com/image.axd?picture=Noelles_Drawing_of_Robie_thumb.jpg" width="244" height="184" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since I started working with the Arduino I have really gained confidence in my ability as a maker. In the past, when something electronic would break around the house I would either throw it away or send it out for repair. Nowadays, I attempt to fix things myself. Once you consider yourself a maker, you start to think differently. After all, &lt;em&gt;&lt;a href="http://blog.makezine.com/2006/12/01/the-makers-bill-of-rights/" target="_blank"&gt;“If You Can’t Open It, You Don’t Own It”&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=rlkqhEbP8-8:6PKZBkSxBcg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=rlkqhEbP8-8:6PKZBkSxBcg:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=rlkqhEbP8-8:6PKZBkSxBcg:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=rlkqhEbP8-8:6PKZBkSxBcg:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=rlkqhEbP8-8:6PKZBkSxBcg:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=rlkqhEbP8-8:6PKZBkSxBcg:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=rlkqhEbP8-8:6PKZBkSxBcg:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/rlkqhEbP8-8" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/rlkqhEbP8-8/post.aspx</link>
      <comments>http://www.codecapers.com/post/My-First-Arduino-Robot.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=35d4a7e3-92fe-41d2-a61c-2c046554e6bc</guid>
      <pubDate>Thu, 24 May 2012 19:08:00 -0100</pubDate>
      <category>Arduino</category>
      <category>Programming</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=35d4a7e3-92fe-41d2-a61c-2c046554e6bc</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=35d4a7e3-92fe-41d2-a61c-2c046554e6bc</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/My-First-Arduino-Robot.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=35d4a7e3-92fe-41d2-a61c-2c046554e6bc</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=35d4a7e3-92fe-41d2-a61c-2c046554e6bc</feedburner:origLink></item>
    <item>
      <title>Using PowerShell to Publish a NuGet Package</title>
      <description>&lt;p&gt;At my employer we have a &lt;a href="http://www.codecapers.com/post/How-to-Set-Up-a-Local-NuGet-Gallery.aspx" target="_blank"&gt;local NuGet server&lt;/a&gt; to host all of our internal packages. Occasionally, I’ll be working on a project and realize that I need to tweak something in one of&amp;#160; my NuGet packages. Initially, I got into the habit of&amp;#160; opening up a second instance of Visual Studio, making the necessary changes and using the NuGet web interface to re-upload the package. I quickly realized that manually uploading the package was too time consuming. Therefore, I started looking for a way to automate the process instead. Eventually that led me to the &lt;a href="http://technet.microsoft.com/en-us/library/bb978526.aspx" target="_blank"&gt;PowerShell&lt;/a&gt; script you see below.&lt;/p&gt;  &lt;pre class="brush: text;"&gt;$nugetServer = &amp;quot;https://&amp;lt;your nuget server here&amp;gt;&amp;quot;
$apiKey = &amp;quot;&amp;lt;your api key here&amp;gt;&amp;quot;
$packageName = &amp;quot;&amp;lt;your package name here&amp;gt;&amp;quot;

$latestRelease = nuget list $packageName
$version = $latestRelease.split(&amp;quot; &amp;quot;)[1];

$versionTokens = $version.split(&amp;quot;.&amp;quot;)
$buildNumber = [System.Double]::Parse($versionTokens[$versionTokens.Count -1]) 
$versionTokens[$versionTokens.Count -1] = $buildNumber +1
$newVersion = [string]::join('.', $versionTokens)
echo $newVersion

get-childitem | where {$_.extension -eq &amp;quot;.nupkg&amp;quot;} | foreach ($_) {remove-item $_.fullname}
nuget pack -Version $newVersion
$package = get-childitem | where {$_.extension -eq &amp;quot;.nupkg&amp;quot;}
nuget push -Source $nugetServer $package $apiKey&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;The script needs a few variables defined in order for it to run. The first variable ($nugetServer) is the URL of the NuGet Server. The second variable ($apiKey) is your personal API key. You can get your API key by logging into your NuGet Server with a browser. After you log in, click on your username in the upper right hand corner. This will take you to your account page. On the bottom of the “My Account” page there is a box which you can click on to make your API key visible. Finally the last variable ($packageName) is the name of the package you are uploading. This can be easily acquired by looking at your project properties and copying the Assembly name from the Application tab. &lt;/p&gt;

&lt;p&gt;Depending on how your machine is configured you may have the option to &lt;strong&gt;&lt;em&gt;Run with PowerShell&lt;/em&gt;&lt;/strong&gt; on your context menu. If not, you can take a look at &lt;a href="http://blog.aggregatedintelligence.com/2011/11/i-wanted-ability-to-right-click-on-ps1.html" target="_blank"&gt;this blog post&lt;/a&gt; in order to configure it manually. Alternatively you can use the following command instead. &lt;/p&gt;

&lt;pre class="brush: text;"&gt;powershell.exe &amp;quot;&amp;lt;path to the script&amp;gt;\publish.ps1&amp;quot;&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;If you have any problems running the script then please refer to the following &lt;a href="http://technet.microsoft.com/en-us/library/ee176949.aspx" target="_blank"&gt;TechNet article&lt;/a&gt; or send me a question and I’ll be glad to help. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=tjGPkpmiS5A:AKMDoj7EZ4M:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=tjGPkpmiS5A:AKMDoj7EZ4M:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=tjGPkpmiS5A:AKMDoj7EZ4M:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=tjGPkpmiS5A:AKMDoj7EZ4M:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=tjGPkpmiS5A:AKMDoj7EZ4M:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=tjGPkpmiS5A:AKMDoj7EZ4M:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=tjGPkpmiS5A:AKMDoj7EZ4M:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/tjGPkpmiS5A" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/tjGPkpmiS5A/post.aspx</link>
      <comments>http://www.codecapers.com/post/Using-PowerShell-to-Publish-a-NuGet-Package.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=afde101e-03b6-4488-9f7f-aeb9de6fedff</guid>
      <pubDate>Mon, 07 May 2012 12:26:46 -0100</pubDate>
      <category>dotNet</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=afde101e-03b6-4488-9f7f-aeb9de6fedff</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=afde101e-03b6-4488-9f7f-aeb9de6fedff</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/Using-PowerShell-to-Publish-a-NuGet-Package.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=afde101e-03b6-4488-9f7f-aeb9de6fedff</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=afde101e-03b6-4488-9f7f-aeb9de6fedff</feedburner:origLink></item>
    <item>
      <title>jQuery + CSS3 Media Queries = Dynamic UX</title>
      <description>&lt;p&gt;I have been working on a project where I render an HTML table to display some information about a project. When the table is displayed on a wide monitor I can comfortably fit about 10-15 columns. However, when viewing the same page on a screen with less real-estate things get crowded. Most people would probably address this problem by creating a mobile version of the site. In many cases this is the proper solution if you really want to tailor the user experience for the device. However, in my case I just wanted to toggle the visibility of some of the columns in the table based on the screen size and I really did not want to get into the hassle of maintaining a separate mobile interface. Therefore I came up with a solution based on jQuery and CSS Media Queries. Below is a screenshot that shows how columns are being toggled on and off based on the width of the browser.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=css_media_queries.png"&gt;&lt;img style="background-image: none; margin: 0px 10px 0px 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="css_media_queries" src="http://www.codecapers.com/image.axd?picture=css_media_queries_thumb.png" border="0" alt="css_media_queries" width="617" height="346" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So let me start this tutorial by showing you the markup that I used to generate the HTML table. If you are not a MVC/Razor developer then this part of the tutorial may not be useful to you. However I wanted to include this extra step because the Razor grid&amp;rsquo;s Html Helper has some limitations which I addressed with jQuery.&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;@{ 
    var grid = new WebGrid( 
        canPage: true,
        rowsPerPage: Model.PagingInfo.PageSize,       
        ajaxUpdateContainerId: "container",
        ajaxUpdateCallback: "gridLoaded"
    );
    
    grid.Bind(Model.Data, rowCount: Model.PagingInfo.TotalItems, autoSortAndPage: false);    
       
    &amp;lt;div id="container"&amp;gt;
        @grid.GetHtml(
            tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            htmlAttributes: new { id = "grid", page = Model.PagingInfo.PageNumber },
            columns: grid.Columns(
                grid.Column("Title", "Title"),
                grid.Column("StartDate", "Start"),
                grid.Column("EndDate", "End"),
                grid.Column("PercentComplete", "%"),

                grid.Column("Status", "Status", style: "xtra"),
                grid.Column("Notes", "Notes", style: "xtra"),
                grid.Column("MetaData", "MetaData", style: "xtra"),
                grid.Column("MoreMetaData1", "More MetaData", style: "xtra"),
                grid.Column("EvenMoreMetaData1", "Even More MetaData", style: "xtra")
            )
        )
    &amp;lt;/div&amp;gt;     
}&lt;/pre&gt;
&lt;p&gt;As you can see, the razor grid allows you to specify styles for each column (&lt;strong&gt;TD&lt;/strong&gt;), so I added the style class "xtra" to the fields that I want to hide when the screen with is 800 pixels or less. Unfortunately the&lt;strong&gt; &lt;/strong&gt;(&lt;strong&gt;TH&lt;/strong&gt;) columns can not be styled directly with the Html Helper. Therefore I needed a way to apply the &amp;ldquo;xtra&amp;rdquo; class to the headers that correspond with each column. This was very easy to do with jQuery:&lt;/p&gt;
&lt;pre class="brush: js;"&gt;$("#grid tbody tr:first td.xtra").each(function (index,td) {                
    $('#grid thead th').eq($(td).index()).addClass("xtra");                
});&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The snippet above uses a selector to get at the first row of the table. It then loops through all of the columns in that row that have the "xtra" style applied to it. Then for each column it finds the corresponding header and adds the "xtra" style to it. This is important because if we did not apply the style to the headers then our CSS below would only hide the columns and not the headers.&lt;/p&gt;
&lt;p&gt;Now let's move on to adding the CSS media queries to our style sheet. If you are unfamiliar with media queries then here is a quick definition that I found on the &lt;a href="http://www.w3.org/TR/css3-mediaqueries/" target="_blank"&gt;W3C site&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Media queries extend the functionality of media types by allowing more precise labeling of style sheets. A media query consists of a media type and zero or more expressions that check for the conditions of particular media features. Among the media features that can be used in media queries are &amp;lsquo;width&amp;rsquo;, &amp;lsquo;height&amp;rsquo;, and &amp;lsquo;color&amp;rsquo;. By using media queries, presentations can be tailored to a specific range of output devices without changing the content itself.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;So in simple terms, we can have sections in our style sheet that only apply when the screen is a certain size. In my particular case I decided to hide the columns&amp;nbsp; with the &amp;ldquo;xtra&amp;rdquo; style applied to them whenever the screen width is less than 800 pixels:&lt;/p&gt;
&lt;pre class="brush: css;"&gt;@media screen and (max-width:800px) { 
  .webGrid .xtra { display: none;}  
  .webGrid .xtra &amp;gt; th { display: none;}    
}&lt;/pre&gt;
&lt;p&gt;Keep in mind that you can also do things like adjust fonts, remove background images and hide navigation panels. This can help make the user experience better when dealing with smaller screens. Although this trick is not a replacement for a well crafted mobile interface it certainly gives you a quick way to make your site look good on smaller screens.&lt;/p&gt;
&lt;p&gt;Happy Coding!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=1E9Rt1gbAU8:0wqg4FBPFzg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=1E9Rt1gbAU8:0wqg4FBPFzg:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=1E9Rt1gbAU8:0wqg4FBPFzg:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=1E9Rt1gbAU8:0wqg4FBPFzg:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=1E9Rt1gbAU8:0wqg4FBPFzg:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=1E9Rt1gbAU8:0wqg4FBPFzg:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=1E9Rt1gbAU8:0wqg4FBPFzg:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/1E9Rt1gbAU8" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/1E9Rt1gbAU8/post.aspx</link>
      <comments>http://www.codecapers.com/post/jQuery-CSS3-Media-Queries-Dynamic-UX.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=0b183f13-a38f-4da3-968a-05141df5a3d5</guid>
      <pubDate>Wed, 18 Apr 2012 17:27:00 -0100</pubDate>
      <category>jQuery</category>
      <category>MVC</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=0b183f13-a38f-4da3-968a-05141df5a3d5</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=0b183f13-a38f-4da3-968a-05141df5a3d5</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/jQuery-CSS3-Media-Queries-Dynamic-UX.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=0b183f13-a38f-4da3-968a-05141df5a3d5</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=0b183f13-a38f-4da3-968a-05141df5a3d5</feedburner:origLink></item>
    <item>
      <title>INotifyPropertyChanged with Compile Time Checking</title>
      <description>&lt;p&gt;&lt;span style="background-color: #ffff99;"&gt;Update: An anonymous reader left a great tip! &lt;em&gt;&lt;strong&gt;".NET 4.5 gives you the new Caller Info attributes, which would remove the need to actually pass in the name of the property, if you're raising the notification from withing the property itself."&lt;/strong&gt;&lt;/em&gt; For more details&amp;nbsp;&lt;a title="Caller Info Attributes" href="http://bartwullems.blogspot.com/2012/02/c-5-caller-info-attributes.html" target="_blank"&gt;read this blog post&lt;/a&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Once you start doing WPF MVVM development you will quickly grow tired of implementing the INotifyPropertyChanged interface. So in order to preserve my sanity, I create a base class which implements the INotifyPropertyChanged interface. The first version of my class was defined as:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}&lt;/pre&gt;
&lt;p&gt;This is about as basic as an implementation of INotifyPropertyChanged can get. To use it, you just implement the class and call RaisePropertyChanged. Here is an example:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class MyViewModel : NotifyPropertyChangedBase
{
    private string _name;
    public string Name {
      get{ return _name; }
      set{ 
       _name = value;
       RaisePropertyChanged("Name");
      }
    }
}&lt;/pre&gt;
&lt;p&gt;After using this version of the code for a couple of days I quickly realized that using a lambda to get the property name would be less error prone than using a string. So in version 2 of the code, I added lambda support.&lt;/p&gt;
&lt;p&gt;By the way, the ExtractPropertyName method you see below, was copied verbatim from the &lt;a href="http://compositewpf.codeplex.com/" target="_blank"&gt;Prism&lt;/a&gt; project. &lt;a href="http://compositewpf.codeplex.com/" target="_blank"&gt;Prism&lt;/a&gt; and &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVM Light Toolkit&lt;/a&gt; both take care of wrapping the INotifyPropertyChanged interface.&amp;nbsp; I personally do not use either framework because I feel that they are both too bloated for my purposes. After a bit of contemplation, I ended up building my own MVVM framework, which I have packaged up and placed on my private NuGet server. However, if you are new to .NET or MVVM then I would suggest starting with a framework first. In any case, here is the updated code:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;protected void RaisePropertyChanged&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyExpression)
{
    var propertyName = ExtractPropertyName(propertyExpression);
    RaisePropertyChanged(propertyName);
}

protected string ExtractPropertyName&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyExpression) {
    if (propertyExpression == null) {
        throw new ArgumentNullException("propertyExpression");
    }

    var memberExpression = propertyExpression.Body as MemberExpression;
    if (memberExpression == null) {
        throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
    }

    var property = memberExpression.Member as PropertyInfo;
    if (property == null) {
        throw new ArgumentException("The member access expression does not access a property.", "propertyExpression");
    }

    if (!property.DeclaringType.IsAssignableFrom(this.GetType())) {
        throw new ArgumentException("The referenced property belongs to a different type.", "propertyExpression");
    }

    var getMethod = property.GetGetMethod(true);
    if (getMethod == null) {
        // this shouldn't happen - the expression would reject the property before reaching this far
        throw new ArgumentException("The referenced property does not have a get method.", "propertyExpression");
    }

    if (getMethod.IsStatic) {
        throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
    }

    return memberExpression.Member.Name;
}        &lt;/pre&gt;
&lt;p&gt;With the lambda version of RaisePropertyChanged in place, I can now get compile time checking. Compile time checking is great if you have fat fingers or if you do a lot of refactoring. Let&amp;rsquo;s take a look at our updated ViewModel:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class MyViewModel : NotifyPropertyChangedBase
{
    private string _name;
    public string Name {
      get{ return _name; }
      set{ 
       _name = value;
       RaisePropertyChanged(() =&amp;gt; Name);
      }
    }
}&lt;/pre&gt;
&lt;p&gt;I also added an overloaded version of the RaisePropertyChanged method so I could raise multiple properties using a single method call. This is useful when you have two of more related properties.&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;protected virtual void RaisePropertyChanged(params string[] propertyNames) {
    foreach( var property in propertyNames ) {
        RaisePropertyChanged(property);
    }
}&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;Unfortunately, I could not figure out how to make an overloaded method that takes multiple lambdas. Because the type that represents "T" needs to be different for each expression I struggled to find any syntactical sugar that would make it work. To clarify the problem, I made an overloaded version of the method that takes two lambda expressions. You will notice that T and X are different types. T may be an integer and X may be an observable collection.&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;protected void RaisePropertyChanged&amp;lt;T,X&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; one, Expression&amp;lt;Func&amp;lt;X&amp;gt;&amp;gt; two ) 
    RaisePropertyChanged(one);            
    RaisePropertyChanged(two);            
}&lt;/pre&gt;
&lt;p&gt;With this method you could use the following syntax. Of course, with my sample method above you are limited to two parameters only:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;RaisePropertyChanged( () =&amp;gt; CountryId, () =&amp;gt; States );&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;If you have a solution for making an overloaded method with params and lambdas then please leave a comment.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Moving on...The classic example of two related properties are Country and State. When you change the value of the country drop down, you want the corresponding states or provinces to appear. Here is an example:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class AddressViewModel : NotifyPropertyChangedBase
{
     private Address Model { get; private set; }
     
     public AddressViewModel( Address model )
     {
         Model = model;
     }

     public int Country
     {
         get { return Model.CountryId; }
         set
         {
             Model.CountryId = value;
             RaisePropertyChanged( () =&amp;gt; CountryId);
             RaisePropertyChanged( () =&amp;gt; States);
         }
     }

     public ObservableCollection&amp;lt;Country&amp;gt; Countries {
         ...
     }

     public ObservableCollection&amp;lt;State&amp;gt; States
     {
         ...
     } 

     public int StateId
     {
         ...
     }
}&lt;/pre&gt;
&lt;p&gt;To summarize, if you find yourself implementing INotifyPropertyChanged a lot then I would highly recommend moving that functionality into a base class. In addition, using the lambda version of the RaisePropertyChanged event can provide you with compile time checking which is always a great thing to have!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=_DKK6lYlDsk:w-utTXdHN6o:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=_DKK6lYlDsk:w-utTXdHN6o:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=_DKK6lYlDsk:w-utTXdHN6o:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=_DKK6lYlDsk:w-utTXdHN6o:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=_DKK6lYlDsk:w-utTXdHN6o:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=_DKK6lYlDsk:w-utTXdHN6o:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=_DKK6lYlDsk:w-utTXdHN6o:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/_DKK6lYlDsk" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/_DKK6lYlDsk/post.aspx</link>
      <comments>http://www.codecapers.com/post/INotifyPropertyChanged-with-Compile-Time-Checking.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=849fdd91-fc4c-41a7-89a9-192a8e8f2131</guid>
      <pubDate>Tue, 27 Mar 2012 19:34:00 -0100</pubDate>
      <category>MVVM</category>
      <category>Tech</category>
      <category>WPF</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=849fdd91-fc4c-41a7-89a9-192a8e8f2131</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=849fdd91-fc4c-41a7-89a9-192a8e8f2131</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/INotifyPropertyChanged-with-Compile-Time-Checking.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=849fdd91-fc4c-41a7-89a9-192a8e8f2131</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=849fdd91-fc4c-41a7-89a9-192a8e8f2131</feedburner:origLink></item>
    <item>
      <title>EF Code First - Tips and Tricks</title>
      <description>&lt;p&gt;These days I do all of my development work with EF code first.&amp;nbsp;One of the cool things about EF is its ability to drop and recreate the database when the models change. This is great when you are trying to associate your source code with a particular revision of the database schema. However, dropping and recreating a database on a production or staging environment can have some serious repercussions. Therefore, I like to put some safeguards in place to make sure that this only happens under the right conditions.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Please keep in mind that the newest version of EF has migration support! So you can alter the database instead of dropping and recreating it. However, if you use the DropRecreateDatabaseIfModelChanges feature of EF then you may find the following tip useful.&lt;/p&gt;
&lt;h2&gt;Safeguarding from an Accidental Drop/Recreate&lt;/h2&gt;
&lt;p&gt;In wrap the code that sets up the EF Context initializer with the following helper method which determines whether or not I am in development mode. For me, development mode means I have the debugger attached or I am working with a local SQL instance:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;static bool InDevelopmentMode {
    get {    
        if (System.Diagnostics.Debugger.IsAttached) return true;
        if (Environment.UserName.ToUpper().Contains("&amp;lt;YOUR ID HERE&amp;gt;")) return true;    

        var connectionString = ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString;
        var csb = new SqlConnectionStringBuilder(connectionString);
        return csb.DataSource.Equals("."); //shorthand for localhost                
    }
}&lt;/pre&gt;
&lt;p&gt;Now we can leverage the method to conditionally execute the DB initializer:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;if (InDevelopmentMode) {
    Database.SetInitializer(new MyContextInitializer()); //Register the EF context initializer
} &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Disabling EF Migrations&lt;/h2&gt;
&lt;p&gt;As I mentioned earlier, the latest version of EF has migration support. By default, migrations will be enabled. If you want to disable it you can do the following:&lt;/p&gt;
&lt;h3&gt;Create a Migrations Configuration class&lt;/h3&gt;
&lt;pre class="brush: csharp;"&gt;using System.Data.Entity.Migrations;

namespace MyApp.Domain.DataContext {
    public sealed class MigrationConfiguration : DbMigrationsConfiguration&amp;lt;MyContext&amp;gt; {
        public MigrationConfiguration() {
            AutomaticMigrationsEnabled = false;
        }
    }
}&lt;/pre&gt;
&lt;h3&gt;Bootstrap it!&lt;/h3&gt;
&lt;p&gt;For web apps this would add this code to the Global.asax.cs and in WPF apps you would do this in App.xaml.cs...&lt;/p&gt;
&lt;pre class="brush: csharp;" style="height: 25px;"&gt;new DbMigrator(new MigrationConfiguration()); //migrations are disabled   &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Happy Coding!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=mCkf_VR5Hi0:7BlOhF_e_SM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=mCkf_VR5Hi0:7BlOhF_e_SM:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=mCkf_VR5Hi0:7BlOhF_e_SM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=mCkf_VR5Hi0:7BlOhF_e_SM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=mCkf_VR5Hi0:7BlOhF_e_SM:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=mCkf_VR5Hi0:7BlOhF_e_SM:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=mCkf_VR5Hi0:7BlOhF_e_SM:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/mCkf_VR5Hi0" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/mCkf_VR5Hi0/post.aspx</link>
      <comments>http://www.codecapers.com/post/EF-Code-First-Tips-and-Tricks.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=a992985d-dd09-4e87-a4ee-a87f889011ca</guid>
      <pubDate>Tue, 13 Mar 2012 18:31:00 -0100</pubDate>
      <category>dotNet</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=a992985d-dd09-4e87-a4ee-a87f889011ca</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=a992985d-dd09-4e87-a4ee-a87f889011ca</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/EF-Code-First-Tips-and-Tricks.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=a992985d-dd09-4e87-a4ee-a87f889011ca</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=a992985d-dd09-4e87-a4ee-a87f889011ca</feedburner:origLink></item>
    <item>
      <title>Using Self Referencing Tables With Entity Framework</title>
      <description>&lt;p&gt;Since EF was released I have been a fan. However, every once in a while I&amp;rsquo;ll run into a table design situation that I am not sure how to handle with EF. This week, I needed to setup a self-referencing table in order to store some hierarchical data. A self referencing table is a table where the primary key on the table is also defined as a foreign key. Sounds a little confusing right?&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s clarify the solution with an example. Let&amp;rsquo;s say I am building an application where I have a list of categories and subcategories. One of my top level categories is &amp;ldquo;Programming Languages&amp;rdquo; and under programming languages I have to subcategories which are &amp;ldquo;C#&amp;rdquo; and &amp;ldquo;Java&amp;rdquo;. In order to store this data I can use a single table with the following structure:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=image_23.png"&gt;&lt;img style="background-image: none; margin: 0px 10px 0px 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; border-width: 0px;" src="http://www.codecapers.com/image.axd?picture=image_thumb_23.png" border="0" alt="" width="337" height="77" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The actual data would look like this:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=image_24.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.codecapers.com/image.axd?picture=image_thumb_24.png" border="0" alt="image" width="374" height="111" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Just to clarify, a top level category will have a null value for the ParentId field. For all child categories the ParentId field is used as to represent its parent&amp;rsquo;s primary key value. As a programmer you may want to think about the ParentId field as a pointer. To complete the example lets take a look at the SQL used to create the table.&lt;/p&gt;
&lt;pre class="brush: sql;"&gt;CREATE TABLE [dbo].[Categories] (
    [CategoryId] [int] IDENTITY(1,1) NOT NULL,    
    [Name] [nvarchar](255) NOT NULL,    
    [ParentId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
    [CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Categories]  WITH CHECK ADD  CONSTRAINT [Category_Parent] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Categories] ([CategoryId])
GO

ALTER TABLE [dbo].[Categories] CHECK CONSTRAINT [Category_Parent]
GO&lt;/pre&gt;
&lt;p&gt;Upon examining the SQL, you should have noticed that the CategoryId is the primary key on the table and the ParentId field is a foreign key which points back to the CategoryId field. Since we have a key referencing a another key on the same table we can classify this this as a self-referencing table. Now that we fully understand what a self-referencing table is, we can move forward to the Entity Framework code. To get started we first need to create a simple C# object to represent the Category table. Of course, keep in mind that if you are using &lt;span style="text-decoration: underline;"&gt;EF Code first&lt;/span&gt; you do not need to create the table or database ahead of time. I only showed the table first because I wanted to better illustrate what a self referencing table is.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
}&lt;/pre&gt;
&lt;p&gt;So far the Category class is very simple. However, we really want to add a few more properties in order to make this class useful. For example, if you are a child category you really want to be able to use dot notation to get the name of the parent category (e.g. subCategory.Parent.Name). Using EF, we will create a virtual property named Parent. By making the property virtual we are letting EF know that when this property is accessed we want to load some data. Based on your configuration settings and the code you use to retrieve your data (whether or not you used DbSet.Include), EF will &lt;a href="http://en.wikipedia.org/wiki/Lazy_loading" target="_blank"&gt;lazy load&lt;/a&gt; or eager load this data.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }
}&lt;/pre&gt;
&lt;p&gt;Finally, we also want a property called Children so we can use dot notation to enumerate over the child categories. Once again, here is the modified class:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection&amp;lt;Category&amp;gt; Children { get; set; }
}&lt;/pre&gt;
&lt;p&gt;The final step is to let EF know how these properties are related to one another. This can be done using &lt;a href="http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx" target="_blank"&gt;EF's fluent API&lt;/a&gt;. If you are new to EF and are unaware of the fluent API then you may want to &lt;a href="http://vincentlauzon.wordpress.com/2011/04/06/entity-framework-4-1-override-conventions-2/" target="_blank"&gt;read this article&lt;/a&gt; first.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class CommodityCategoryMap : EntityTypeConfiguration&amp;lt;Category&amp;gt; {
    public CommodityCategoryMap() {
        HasKey(x =&amp;gt; x.CategoryId);

        Property(x =&amp;gt; x.CategoryId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(x =&amp;gt; x.Name)
            .IsRequired()
            .HasMaxLength(255);

        HasOptional(x =&amp;gt; x.Parent)
            .WithMany(x =&amp;gt; x.Children)
            .HasForeignKey(x =&amp;gt; x.ParentId)
            .WillCascadeOnDelete(false);
    }
}&lt;/pre&gt;
&lt;p&gt;Hopefully you paid careful attention to the last section of code where we state the a Category has an optional Parent property. In database speak, this simply means that the ParentID field is nullable. The code also states that if a Category object can have zero or many children. In order to specify that a record is a child, we&amp;nbsp; leverage the ParentId field to hold the primary key value of the parent record. As I mentioned earlier, if you are a programmer its easier to think of the ParentId field as a pointer. Finally, I disabled the cascade on delete option. This step is optional and probably based on your own personal preferences. If you enable cascade on delete and you delete a category that has 100 children then you will effectively remove 101 records. For whatever reason this scares me a little bit. Perhaps, my short career as a DBA caused me to not trust people with large volume delete statements. However, you may decide differently depending on your circumstances.&lt;/p&gt;
&lt;p&gt;Hopefully, this short EF tutorial will help you if you are working through a scenario where you need to capture and manipulate hierarchical data. If you have any questions please leave a comment.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Zsx32s-Aohg:KD8yinUoM0g:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Zsx32s-Aohg:KD8yinUoM0g:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Zsx32s-Aohg:KD8yinUoM0g:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=Zsx32s-Aohg:KD8yinUoM0g:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Zsx32s-Aohg:KD8yinUoM0g:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=Zsx32s-Aohg:KD8yinUoM0g:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Zsx32s-Aohg:KD8yinUoM0g:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/Zsx32s-Aohg" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/Zsx32s-Aohg/post.aspx</link>
      <comments>http://www.codecapers.com/post/Using-Self-Referencing-Tables-With-Entity-Framework.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=f05129e8-4ce5-4419-8654-d7555d4e8dac</guid>
      <pubDate>Mon, 13 Feb 2012 06:00:00 -0100</pubDate>
      <category>dotNet</category>
      <category>SQL</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=f05129e8-4ce5-4419-8654-d7555d4e8dac</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=f05129e8-4ce5-4419-8654-d7555d4e8dac</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/Using-Self-Referencing-Tables-With-Entity-Framework.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=f05129e8-4ce5-4419-8654-d7555d4e8dac</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=f05129e8-4ce5-4419-8654-d7555d4e8dac</feedburner:origLink></item>
    <item>
      <title>How to Set Up a Local NuGet Gallery</title>
      <description>&lt;p&gt;First of all you may be wondering, why do I want my &lt;u&gt;own&lt;/u&gt; local &lt;a href="http://nuget.codeplex.com/wikipage?title=Getting%20Started" target="_blank"&gt;Nuget&lt;/a&gt; Gallery? Well, here are two reasons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Having your own NuGet server is perfect for when you need share modules with other people on your team but you do not necessarily want to make them available for public consumption. &lt;/li&gt;    &lt;li&gt;If you are a consultant then having your own personal NuGet Gallery may be a handy way to keep your libraries and utilities accessible to you when you are on the road. This is an great way to utilize your home &lt;a href="http://www.o2.co.uk/broadband/" target="_blank"&gt;broadband&lt;/a&gt; connection. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Last year I wrote an article about how to &lt;a href="http://www.codecapers.com/post/Building-a-Nuget-Server-with-gold-plating.aspx" target="_blank"&gt;Build a NuGet Server with gold plating&lt;/a&gt;. At the time, there were two methods for hosting your own NuGet feed. The first option was to install the &lt;a href="http://orchard.codeplex.com/" target="_blank"&gt;Orchard&lt;/a&gt;-based NuGet Gallery. I personally stayed away from this option because setting up an entire CMS just to host a few small NuGet packages seemed like overkill to me. The second option was to create an empty ASP.NET MVC site and install a few NuGet packages &lt;a href="http://haacked.com/archive/2011/03/31/hosting-simple-nuget-package-feed.aspx" target="_blank"&gt;from Phil Haack&lt;/a&gt; that turned your empty website into a NuGet server. I call the second option the recursive NuGet server because you install NuGet packages which in turn help you to create a NuGet server. Anyway, if you compare the features of the Orchard Nuget Gallery to the recursive NuGet server, you will instantly notice that the Orchard version had a lot more functionality. Unfortunately, at the time I still could not justify setting up an entire CMS just to get a few small features. &lt;/p&gt;  &lt;p&gt;Eventually someone on the NuGet team realized that having the gallery so tightly coupled with Orchard was probably not a good idea. So sometime late last year, the NuGet gallery was removed from Orchard which made the setup process a lot less complex. Unfortunately the documentation page for &lt;a href="http://docs.nuget.org/docs/contribute/setting-up-a-local-gallery" target="_blank"&gt;Setting Up a Local NuGet Gallery&lt;/a&gt; has not been updated yet and still reflects the steps for creating the Orchard-based gallery. Since I recently setup a NuGet server at the office I decided to document the new steps in order to save you some trouble.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Download the latest source from &lt;a href="https://github.com/NuGet/NuGetGallery" target="_blank"&gt;GitHub&lt;/a&gt;. I just grabbed the &lt;a href="https://github.com/NuGet/NuGetGallery/zipball/master" target="_blank"&gt;zip file&lt;/a&gt; since I do not have a &lt;a href="http://code.google.com/p/tortoisegit/downloads/list" target="_blank"&gt;Git client&lt;/a&gt; on my machine. &lt;/li&gt;    &lt;li&gt;Extract the zip file and navigate to the Website subdirectory. Locate the web.config file and open it up in your favorite editor. Inside the web.config you will want to change the following options:      &lt;ol&gt;       &lt;li&gt;Modify the configuration/connectionStrings/NuGetGallery key so it points to your locally hosted SQL Server. &lt;/li&gt;        &lt;li&gt;Change the appSettings/GalleryOwnerEmail to the email address of the person who is going to administer the site. &lt;/li&gt;        &lt;li&gt;Change the appSettings/Configuration:SiteRoot to reflect the domain name you are going to use for the site. &lt;/li&gt;     &lt;/ol&gt;   &lt;/li&gt;    &lt;li&gt;Run the Build-Solution.ps1 script using Powershell in the root directory. This will compile the website and assemble the binaries. &lt;/li&gt;    &lt;li&gt;Open up your IIS Manager      &lt;ol&gt;       &lt;li&gt;Create a new application pool. The pool should use the 4.0 framework and use an integrated pipeline. Please pay careful attention to the Identity of the pool because you will need to grant this account permissions to your SQL Server. &lt;/li&gt;        &lt;li&gt;Create a new website. Set the site’s physical path to point at the Website directory. Also make sure the site uses the application pool that you created in the previous step. &lt;u&gt;Do not start the website yet&lt;/u&gt;. &lt;/li&gt;     &lt;/ol&gt;   &lt;/li&gt;    &lt;li&gt;Open up SQL Server Management Studio      &lt;ol&gt;       &lt;li&gt;Grant db_creator to the identity of the application pool you created earlier. The account needs db_creator because the first time you run the applicaton, the Entity Framework context initializer will run. If no database exists yet then it will create the database for you. After, the database is created you can trim back the permissions to db_datareader and db_datawriter. This tends to make your DBA happy. &lt;/li&gt;     &lt;/ol&gt;   &lt;/li&gt;    &lt;li&gt;Start your website and launch the browser of your choice. In the browser, navigate to the NuGet server. It may take a second or two for the page to appear because the database needs to get created during the first run. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;If you followed the steps properly then you should see the following page:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.codecapers.com/image.axd?picture=image_25.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.codecapers.com/image.axd?picture=image_thumb_25.png" width="644" height="390" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=MdaJv0oBJk8:TSGO8MmAYq0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=MdaJv0oBJk8:TSGO8MmAYq0:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=MdaJv0oBJk8:TSGO8MmAYq0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=MdaJv0oBJk8:TSGO8MmAYq0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=MdaJv0oBJk8:TSGO8MmAYq0:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=MdaJv0oBJk8:TSGO8MmAYq0:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=MdaJv0oBJk8:TSGO8MmAYq0:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/MdaJv0oBJk8" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/MdaJv0oBJk8/post.aspx</link>
      <comments>http://www.codecapers.com/post/How-to-Set-Up-a-Local-NuGet-Gallery.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=9d72827e-96e3-430c-b24c-a350c9e8d5c8</guid>
      <pubDate>Mon, 06 Feb 2012 12:50:51 -0100</pubDate>
      <category>Tech</category>
      <category>dotNet</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=9d72827e-96e3-430c-b24c-a350c9e8d5c8</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=9d72827e-96e3-430c-b24c-a350c9e8d5c8</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/How-to-Set-Up-a-Local-NuGet-Gallery.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=9d72827e-96e3-430c-b24c-a350c9e8d5c8</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=9d72827e-96e3-430c-b24c-a350c9e8d5c8</feedburner:origLink></item>
    <item>
      <title>Getting Started With The Arduino</title>
      <description>&lt;p&gt;As an engineer, I constantly feel the need to learn new things in order to keep the &lt;a href="http://www.codinghorror.com/blog/2009/03/sharpening-the-saw.html" target="_blank"&gt;"saw sharp"&lt;/a&gt;. Since I write code for a living, I often feel dissatisfied by the notion that everything I create is "virtual". The only way to interact with the things that I create are with a keyboard and mouse. The thought of this often makes me wonder if I would have been happier in a profession where I built things with my hands. People tend to appreciate things more that they can hold and physically interact with. So naturally, this led me to the idea of "How can I make software take on a more physical presence?". Of course I immediately thought of robotics, so I typed the term "robotics" into Google and I discovered the term "Physical Computing". According to Wikipedia, the definition of physical computing is:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Physical computing, in the broadest sense, means building interactive physical systems by the use of software and hardware that can sense and respond to the analog world. While this definition is broad enough to encompass things such as smart automotive traffic control systems or factory automation processes, it is not commonly used to describe them. In the broad sense, physical computing is a creative framework for understanding human beings' relationship to the digital world. In practical use, the term most often describes handmade art, design or DIY hobby projects that use sensors and microcontrollers to translate analog input to a software system, and/or control electro-mechanical devices such as motors, servos, lighting or other hardware.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Immediately after reading about physical computing I was intrigued by the idea so I decided to learn more about the different kinds of microcontroller that are available on the market. Of course, since I am a .NET Developer I already knew about the &lt;a href="http://netduino.com/"&gt;Netduino&lt;/a&gt;. The Netduino is a microcontroller that runs the .NET micro framework and you can use Visual Studio to create sketches. Although this sounded cool I decided that 40+ hours a week in Visual Studio is more than enough for me. Therefore, I opted to go with the Arduino platform instead. The Arduino programming language is a implementation of &lt;a href="http://en.wikipedia.org/wiki/Wiring_(development_platform)" target="_blank"&gt;Wiring&lt;/a&gt;, a physical computing platform, which is based on the &lt;a href="http://processing.org/" target="_blank"&gt;Processing multimedia programming environment&lt;/a&gt;. With the combination of some basic electronics skills and the Arduino you can create almost anything. If you search online you will find all kinds of Arduino based projects which include clocks, weather stations, robots and even 3d printers! To make a long story short I ended up ordering the &lt;a href="http://www.sparkfun.com/products/10173" target="_blank"&gt;SparkFun inventor's kit&lt;/a&gt;. The kit includes an Arduino Uno R3, some basic components and a step-by-step guide on how to use each one. If you are starting from scratch like me and you have no prior experience with electronics then I strongly recommend buying a kit. The manual that comes with the SparkFun Kit is very well done and of course there are a large community of Arduino developers willing to help if you get stuck.&lt;/p&gt;
&lt;p&gt;&lt;img title="=&amp;quot;The" src="http://www.codecapers.com/image.axd?picture=2012%2f1%2fSIK.jpg" alt="The SparkFun Inventors Kit" /&gt;&lt;/p&gt;
&lt;p&gt;After you make it through all the tutorials in the kit you will probably lay awake at night just thinking of the possibilities. In addition, you will probably drop some cash because on a bigger breadboard, a multimeter and a soldering station. Anyways, just to whet your appetite here are some examples of things that you can do with an Arduino:&lt;/p&gt;
&lt;p&gt;RGB LEDs controlled by an Arduino and sequenced with Flash.&lt;/p&gt;
&lt;p&gt;
&lt;object style="height: 390px; width: 640px;" width="640" height="360"&gt;
&lt;param name="movie" value="http://www.youtube.com/v/caSJI7QkxDM?version=3&amp;amp;feature=player_detailpage" /&gt;
&lt;param name="allowFullScreen" value="true" /&gt;
&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed type="application/x-shockwave-flash" width="640" height="360" src="http://www.youtube.com/v/caSJI7QkxDM?version=3&amp;amp;feature=player_detailpage" allowfullscreen="true" allowscriptaccess="always"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/p&gt;
&lt;p&gt;Arduino Robot using a Adafruit motor shield, 2x Sharp IR sensors, one PING sensor and an XPAL XP8000 battery.&lt;/p&gt;
&lt;p&gt;
&lt;object style="height: 390px; width: 640px;" width="640" height="360"&gt;
&lt;param name="movie" value="http://www.youtube.com/v/R8vPu7YpqlI?version=3&amp;amp;feature=player_detailpage" /&gt;
&lt;param name="allowFullScreen" value="true" /&gt;
&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed type="application/x-shockwave-flash" width="640" height="360" src="http://www.youtube.com/v/R8vPu7YpqlI?version=3&amp;amp;feature=player_detailpage" allowfullscreen="true" allowscriptaccess="always"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/p&gt;
&lt;p&gt;And finally, a &lt;a href="http://wiki.makerbot.com/thingomatic" target="_blank"&gt;3D Printer&lt;/a&gt; from MakerBot. Yes, I said 3D Printer! Apparently, this uses a Arduino MEGA under the covers.&lt;br /&gt; 
&lt;object style="height: 390px; width: 640px;" width="640" height="360"&gt;
&lt;param name="movie" value="http://www.youtube.com/v/OzvCqc2jTX8?version=3&amp;amp;feature=player_detailpage" /&gt;
&lt;param name="allowFullScreen" value="true" /&gt;
&lt;param name="allowScriptAccess" value="always" /&gt;&lt;embed type="application/x-shockwave-flash" width="640" height="360" src="http://www.youtube.com/v/OzvCqc2jTX8?version=3&amp;amp;feature=player_detailpage" allowfullscreen="true" allowscriptaccess="always"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/p&gt;
&lt;p&gt;In the upcoming months you can expect to see some Arduino and electronics based articles appearing on my blog. Perhaps even an article about how I built my first robot!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=C5kDDGHfVLM:o-gU22iKBUU:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=C5kDDGHfVLM:o-gU22iKBUU:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=C5kDDGHfVLM:o-gU22iKBUU:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=C5kDDGHfVLM:o-gU22iKBUU:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=C5kDDGHfVLM:o-gU22iKBUU:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=C5kDDGHfVLM:o-gU22iKBUU:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=C5kDDGHfVLM:o-gU22iKBUU:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/C5kDDGHfVLM" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/C5kDDGHfVLM/post.aspx</link>
      <comments>http://www.codecapers.com/post/Getting-Started-With-The-Arduino.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=5f976e71-1736-4eae-949a-4b7bcbd26fc3</guid>
      <pubDate>Tue, 31 Jan 2012 09:21:00 -0100</pubDate>
      <category>Arduino</category>
      <category>Tech</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=5f976e71-1736-4eae-949a-4b7bcbd26fc3</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=5f976e71-1736-4eae-949a-4b7bcbd26fc3</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/Getting-Started-With-The-Arduino.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=5f976e71-1736-4eae-949a-4b7bcbd26fc3</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=5f976e71-1736-4eae-949a-4b7bcbd26fc3</feedburner:origLink></item>
    <item>
      <title>Getting Assembly Information Using Reflection</title>
      <description>&lt;p&gt;I recently took over a WPF application that needed a little bit of refactoring. One of the places that had a lot of repeated code was the about screen. By using reflection a bunch of properties were being created to display things like the assembly title, version, description and etcetera. The original code looked like this:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;public string AssemblyDescription
{
    get
    {
        object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
        if (attributes.Length == 0)
        {
            return &amp;quot;&amp;quot;;
        }
        return ((AssemblyDescriptionAttribute)attributes[0]).Description;
    }
}

public string AssemblyProduct
{
    get
    {
        object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
        if (attributes.Length == 0)
        {
            return &amp;quot;&amp;quot;;
        }
        return ((AssemblyProductAttribute)attributes[0]).Product;
    }
}&lt;/pre&gt;

&lt;p&gt;You may have noticed that this code does not follow the &lt;a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself" target="_blank"&gt;DRY&lt;/a&gt; principle. In case you arent familiar with the term, DRY stands for Don't repeat yourself. In otherwords, if you repeat the same code multiple times then you should try to refactor it into a more generic method. &lt;/p&gt;

&lt;p&gt;After analyzing the code you may notice that both of the property getters do the same thing. First, it gets a handle to the current assembly. Next, the GetCustomAttributes method is called to get an object array which contains all the attribute values for a given type. Finally, a little bit of conditional logic is used to emit a value. Using the power of generics and some reflection we can easily build an extension method that will eliminate the redundant code. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Warning: If you are not familiar with generics, reflection and lambda statements then the following code may cause your brain to explode&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public static TAttribute[] GetAttributes&amp;lt;TAttribute&amp;gt;(this Assembly assembly) where TAttribute : Attribute {
    return assembly.GetCustomAttributes(typeof(TAttribute), false) as TAttribute[];
}

public static object GetFirstAttributeValue&amp;lt;TAttribute&amp;gt;(
    this Assembly assembly,
    Expression&amp;lt;Func&amp;lt;TAttribute, object&amp;gt;&amp;gt; propertyLambda) where TAttribute : Attribute {
    Type type = typeof(TAttribute);

    var attributeValues = assembly.GetAttributes&amp;lt;TAttribute&amp;gt;();
    if (attributeValues.Length == 0)
        throw new ArgumentException(&amp;quot;No values found&amp;quot;);

    var member = propertyLambda.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException(string.Format(&amp;quot;Expression '{0}' refers to a method, not a property.&amp;quot;, propertyLambda));

    var propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
        throw new ArgumentException(string.Format(&amp;quot;Expression '{0}' refers to a field, not a property.&amp;quot;, propertyLambda));

    if (type != propInfo.ReflectedType &amp;amp;&amp;amp; !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(&amp;quot;Expresion '{0}' refers to a property that is not from type {1}.&amp;quot;, propertyLambda, type));

    var firstValue = attributeValues[0];
    return propInfo.GetValue(firstValue, null);
}&lt;/pre&gt;

&lt;p&gt;The code above basically takes the lambda statement, makes sure its a property expression and then uses reflection to get the value of the object. By the way, I do not take credit for writing the reflection code, most of it was borrowed from this &lt;a href="http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression" target="_blank"&gt;stackoverflow post&lt;/a&gt;. In any case, with the help of the extension method above we can now simplify our code as:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;private Assembly Assembly { get; set; }

public AboutViewModel()
{
    Assembly = Assembly.GetExecutingAssembly();
}

public string AssemblyDescription {
    get {
        return Assembly.GetFirstAttributeValue&amp;lt;AssemblyDescriptionAttribute&amp;gt;(x =&amp;gt; x.Description).ToString();
    }
}

public string AssemblyProduct {
    get {
        return Assembly.GetFirstAttributeValue&amp;lt;AssemblyProductAttribute&amp;gt;(x =&amp;gt; x.Product).ToString();
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see, the code is much cleaner. Also take notice that I cached the call to Assembly.GetExecutingAssembly() in a private variable. This helps with performance and also cleans up the code a little. &lt;/p&gt;

&lt;p&gt;Happy Coding!&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Fr1EkCfueUY:pfNguhf3V3o:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Fr1EkCfueUY:pfNguhf3V3o:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Fr1EkCfueUY:pfNguhf3V3o:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=Fr1EkCfueUY:pfNguhf3V3o:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Fr1EkCfueUY:pfNguhf3V3o:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?i=Fr1EkCfueUY:pfNguhf3V3o:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/codecapers?a=Fr1EkCfueUY:pfNguhf3V3o:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/codecapers?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/codecapers/~4/Fr1EkCfueUY" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/codecapers/~3/Fr1EkCfueUY/post.aspx</link>
      <comments>http://www.codecapers.com/post/Getting-Assembly-Information-Using-Reflection.aspx#disqus_thread</comments>
      <guid isPermaLink="false">http://www.codecapers.com/post.aspx?id=6f077a96-9eaf-4467-b1d0-0a219cbe6c29</guid>
      <pubDate>Tue, 03 Jan 2012 17:37:47 -0100</pubDate>
      <category>MVVM</category>
      <category>dotNet</category>
      <category>WPF</category>
      <dc:publisher>mikeceranski</dc:publisher>
      <pingback:server>http://www.codecapers.com/pingback.axd</pingback:server>
      <pingback:target>http://www.codecapers.com/post.aspx?id=6f077a96-9eaf-4467-b1d0-0a219cbe6c29</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.codecapers.com/trackback.axd?id=6f077a96-9eaf-4467-b1d0-0a219cbe6c29</trackback:ping>
      <wfw:comment>http://www.codecapers.com/post/Getting-Assembly-Information-Using-Reflection.aspx#disqus_thread</wfw:comment>
      <wfw:commentRss>http://www.codecapers.com/syndication.axd?post=6f077a96-9eaf-4467-b1d0-0a219cbe6c29</wfw:commentRss>
    <feedburner:origLink>http://www.codecapers.com/post.aspx?id=6f077a96-9eaf-4467-b1d0-0a219cbe6c29</feedburner:origLink></item>
  </channel>
</rss>
