<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" 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:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/c4f.Rob-Miles/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/c4f.Rob-Miles/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/c4f.Rob-Miles/Posts</link>
    <language>en</language>
    <pubDate>Thu, 23 May 2013 12:19:48 GMT</pubDate>
    <lastBuildDate>Thu, 23 May 2013 12:19:48 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>2</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Controlling Your Festive Lights with the .NET Micro Framework</title>
      <description><![CDATA[
<table class="" cellspacing="0" cellpadding="2" width="470" border="0">
<tbody>
<tr>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Author:</strong></td>
<td class="" valign="top" width="363">Rob Miles: <a href="http://www.robmiles.com">
www.robmiles.com</a> </td>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Download:</strong></td>
<td class="" valign="top" width="363"><a title="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/festivelights1.0.zip" href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/festivelights1.0.zip">Download</a></td>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Software:</strong></td>
<td class="" valign="top" width="363">Visual Studio 2008 Express Edition or better,
<br>
<a href="http://www.microsoft.com/netmf/about/gettingstarted.mspx">.NET Micro Framework 3.0</a></td>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Hardware:</strong></td>
<td class="" valign="top" width="363"><a href="http://www.digi.com/products/embeddedsolutions/digiconnectme.jsp">Digi Connect-ME</a>
<br>
<a href="http://www.ghielectronics.com/embeddedmaster.php">GHI Electronics Embedded Master</a>
<br>
<a href="http://devicesolutions.net/Products/Tahoe.aspx">Devices Solutions Tahoe II
</a></td>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Time Required:</strong></td>
<td class="" valign="top" width="363">3 hours</td>
</tr>
<tr>
<td class="" valign="top" width="105"><strong>Cost:</strong></td>
<td class="" valign="top" width="363">30 dollars for lights plus the .NET Micro Framework device</td>
</tr>
</tbody>
</table>
<p>The Micro Framework is one of the newest kids on the .NET block, but it does something really rather wonderful. It brings embedded development within the reach of any C# programmer. If you know C# and love Visual Studio, you can now get started building
 hardware and controlling it with your software. Moreover, it lets developers achieve one of their most cherished dreams, to control their festive lights using programs that they have written. This project shows you how to do just that and adds an extra magical
 feature, in that you can make all your festive lights flash red whenever I, Rob Miles, make a new post on that most famous of blogs,
<a href="http://www.robmiles.com">www.robmiles.com</a>. </p>
<p>Actually, you can modify the code so that you can make your lights do most anything in response to an event that happens on the web. You could signal home that you are running late, send the weather forecast to your Christmas tree or explore any number of
 communication options. You might decide that this is so useful that you leave your decorations up all year round.</p>
<p>If you just want to play with the .NET Micro Framework and get a feel for how easy it is to create software for tiny devices you don't actually need to use any extra hardware at all. The project comes with a complete emulation of the lights display so that
 you can run the whole thing on your computer and learn how hardware and software can be made to work together without burning your fingers with a soldering iron.</p>
<p>However building the hardware will give you an understanding of how some simple electronic components can be controlled from C# and even how serial and parallel data transfer works. It is also great fun.</p>
<p>To get started you will need some hardware and some software. Let's take each in turn.</p>
<h1>Hardware</h1>
<h2>Processor Hardware</h2>
<p>The .NET Micro Framework lets you run C# programs on tiny embedded devices. There are a number of these available today, and they are getting progressively cheaper. You can base this project on any.NET Micro Framework device that has a network port and three
 or more output ports. The ones I'd recommend are:</p>
<ul>
<li>Digi Connect-ME: <a href="http://www.digi.com/products/embeddedsolutions/digiconnectme.jsp">
http://www.digi.com/products/embeddedsolutions/digiconnectme.jsp</a> </li><li>GHI Electronics Embedded Master: <a href="http://www.ghielectronics.com/embeddedmaster.php">
http://www.ghielectronics.com/embeddedmaster.php</a> </li><li>Devices Solutions Tahoe II: <a href="http://devicesolutions.net/Products/Tahoe.aspx">
http://devicesolutions.net/Products/Tahoe.aspx</a> </li></ul>
<p>I built the project for Digi Connect board but the code can be customised for any of the above platforms. The beauty of the .NET Micro Framework is that you hardly need to change your program even if the underlying hardware is completely replaced. The only
 thing you will have to do is adjust the code to target different output pins. I'll flag this part of the program up when we get to it.</p>
<p>The project as supplied runs on a special emulator that runs on the PC and behaves like a .NET Micro Framework device with lights connected, so you can get started exploring the code right away.</p>
<h2>Lights</h2>
<p>I'm keeping things deliberately low voltage for this project. This means that kids of all ages can have a go at building the hardware without messing around with mains. The lights that I used were supplied as lines of twenty leds wired up as four strands
 of five leds each. All the leds in each strand were the same colour. The lights were fitted with a little battery box which held three AA batteries and a tiny controller. To get my display I simply removed the battery box and connected the strands to my hardware.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image.png"><img title="image" height="226" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb.png" width="324" border="0"></a>&nbsp;
<br>
<strong>Figure 1: My Battery Powered Lights</strong></p>
<p>You can do the same with any low power lighting kit that you wish to use. The drivers that I'm using can handle around 500 milliamps of continuous current and so you can connect a fair number of lights to each strand.
</p>
<h2>Buying the Lights</h2>
<p>The lights I used can be bought in the UK from Lights4Fun: www.lights4fun.co.uk and are called &quot;C-LED-4.5-M 20 Multi Coloured Battery Operated LED Fairy Lights&quot;. They are supplied with a battery box and controller that you can remove to connect to the Darlington
 drivers. I used an old 5 volt mobile phone charger to power the lights. If you search eBay for &quot;led christmas lights battery&quot; you should find plenty of suppliers.</p>
<h2>Driver Hardware</h2>
<p>We can't connect a .NET Micro Framework device directly to our lights. There are two reasons for this:</p>
<ol>
<li>The Micro Framework device will not be able to switch the amount of current that we need to drive the lights themselves.
</li><li>The Micro Framework device will not have enough outputs to control all the lights that we want to use.
</li></ol>
<p>This means that we need to make some hardware that goes between the processor and our lights. I actually don't see this as a problem. Making hardware is great fun, seeing something that you've built spring into life is very nice. The hardware we are going
 to use will provide a means by which we can control many hundreds of lights from a single Micro Framework board if we wish. It also has the ability to switch reasonable amounts of current, so you can use quite large numbers of lights if you wish. We are going
 to use two semiconductor components, a CD4094 Shift Register/Latch and a ULN2803 Octal Darlington Driver. A pair of these chips will allow us to control 8 outputs. If you want to control more outputs you simply get more chips and chain them together. For my
 version of the project I just used one of each chip, you can use as many as you like.The shift registers and Darlington amplifiers can be obtained in the UK from Maplin:
<a href="http://www.maplin.co.uk">www.maplin.co.uk</a>. The chip numbers and part numbers as are as follows: QW54J 4094 Shift Register, QY79L ULN2803A Darlington Driver. In the US you can obtain the components and breadboard from Digi-Key:
<a href="http://www.digikey.com">www.digikey.com</a>. </p>
<h2>Serial and Parallel Data</h2>
<p>You might be wondering how we can use just three output lines to control lots of lights. We are going to do this by using the three output lines to provide a
<i>serial</i> data stream which is converted by our hardware into <i>parallel</i> data that can be used to control our lights. This is a fundamental principle of digital electronics and is how, amongst many other things, computer networks transfer data.</p>
<p>We are going to use three signals which are called <b>clock</b>, <b>data</b> and
<b>latch</b>. Each of these can be set high (a voltage is present) or low (no voltage is present) by the .NET Micro Framework device under the control of our software. The signals are connected to the clock, data and latch inputs of our CD4094 shift register
 so that the program can talk to it.</p>
<p>The clock line triggers the shift register to do two things:</p>
<ol>
<li>Shift all the bits along to make room. </li><li>Sample the value of the data input and store this value in the space that was created.
</li></ol>
<p>To get a feel for how this works, take a look at Figure 2 below. It shows a shift register with a pattern of bits in it. The pattern is
<b>01100001</b>. Note that although this represents a number; it can also be regarded as a pattern of 0s and 1s in the shift register itself. The value 0 means 0 volts and the value 1 means some volts. These are the signals that will be used to control our
 lights. I'm going to call them 0 and 1 from now on. The Shift Register has Clock, Data and Latch signals connected and they are all set to 1. We can ignore the latch part of the chip for now.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_3.png"><img title="image" height="251" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_3.png" width="500" border="0"></a>
</p>
<p><strong>Figure 2: A shift register and latch with some data in it</strong></p>
<p>When the clock signal changes from 1 to 0 this causes the shift register to perform the two steps described above. First the data is shifted along to the right. Note that this means that there is an &quot;empty&quot; location at the start of the register, and that
 the right most bit in the register &quot;falls off&quot; the register and disappears. Figure 3 shows how this works.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_4.png"><img title="image" height="236" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_4.png" width="500" border="0"></a>
</p>
<p><strong>Figure 3: Shifting along the values in the shift register</strong></p>
<p>Once the shift has finished the shift register can copy the data signal into the empty bit at the left as shown in Figure 4 below.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_5.png"><img title="image" height="251" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_5.png" width="500" border="0"></a>
<strong><br>
Figure 4: Storing the new data bit</strong></p>
<p>By repeating this process 8 times a program can load a new pattern of 8 bits into the shift register. Then it is time to latch the new value to control the lights. This is the point at which the lights will appear to change. When the latch value is changed
 from 0 to 1 this causes the chip to copy the value in the Shift Register into the latch, as shown in Figure 5 below.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_6.png"><img title="image" height="251" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_6.png" width="500" border="0"></a>
</p>
<p><strong>Figure 5: Copying the shift register pattern into the latch.</strong></p>
<p>The latch is required so that the lights will not flicker as the new patterns are shifted into position. Each of the bits in the latch is connected to an output pin on the CD4094 which is used to switch a particular light colour on or off.</p>
<p>We need to create some C# that will provide the appropriate sequence of signals. It turns out that using the .NET Micro Framework to achieve this is actually very easy. The
<b>displayByte</b> method below sends an 8 bit value into a shift register and then latches it into the output. If you read through the code you can see how the clock, data and latch values are all set to true (high) or false (low) to first clock the data out
 and then trigger the latch to display the pattern on the lights. The input is an 8 bit byte value and the program uses a mask to pick out the value of each bit in turn and set the data output accordingly.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> displayByte(<span class="kwrd">byte</span> <span class="kwrd">value</span>)
{
    latchPort.Write(<span class="kwrd">false</span>);
    clockPort.Write(<span class="kwrd">false</span>);

    <span class="kwrd">byte</span> mask = 1;

    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; 8; i&#43;&#43;)
    {
        <span class="kwrd">if</span> ((<span class="kwrd">value</span> &amp; mask) &gt; 0)
        {
            dataPort.Write(<span class="kwrd">true</span>);
        }
        <span class="kwrd">else</span>
        {
            dataPort.Write(<span class="kwrd">false</span>);
        }
        clockPort.Write(<span class="kwrd">true</span>);
        clockPort.Write(<span class="kwrd">false</span>);
        mask &lt;&lt;= 1;
    }
    latchPort.Write(<span class="kwrd">true</span>);
    latchPort.Write(<span class="kwrd">false</span>);
}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The <b>dataPort</b>, <b>clockPort</b> and <b>latchPort</b> variables are instances of the .NET Micro Framework class
<b>OutputPort</b>, which provides a method called <b>Write</b> which can be used to control the state of the output signal. We will consider how these are created a little later in the article.</p>
<p>The sample code for this project comes with a software emulator of the CD4094 which shows how it works. Figure 6 below shows that a new pattern is in the process of being shifted into the shift register, while the lights retain the previous one in the latch.
 The Clock and Data signals are high and the next statement will drop the Clock signal to add the next bit into the new pattern.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_7.png"><img title="image" height="303" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_7.png" width="264" border="0"></a>
</p>
<p><strong>Figure 6: The light emulator</strong></p>
<p>This figure also shows that I have two bits in the pattern controlling a strand of each colour. You can single step through the displayByte method above and watch it perform this output.</p>
<p>You can use this technique every time you want to control a large number of outputs using a small number of output pins. The CD4094 has &quot;daisy chain&quot; inputs and outputs so that the devices can be connected in sequence. If I used two devices I could control
 16 bits, with three I could control 24 and so on. This would require only minimal changes to the software.</p>
<h2>Output Driver</h2>
<p>The CD4094 device will produce a signal output, but it is not really powerful enough to drive things like lights. To do this we need an amplifier and the ULN2803 Octal Darlington Driver is perfect for this. It is packaged as a single chip which contains
 8 pairs of transistors. Each transistor pair is wired in a &quot;Darlington&quot; configuration and can be used as a switch which is controlled by on output from the CD4094. When the transistors are turned on they allow current to pass through them and this will cause
 the lamps to light. The lights that I bought used a &quot;pull down&quot; arrangement to make them light up. All of the light emitting diode (LED) lamps had one end wired to a common line that was connected to the positive supply. To make the a chain of LEDs light the
 other end that controls that chain needed to be pulled down to the ground level. This is a common arrangement with lights like these. The ULN2803 driver has the transistors wired in an arrangement that allows it to pull signals low in this way. Figure 7 shows
 how this arrangement works. The resistor shown is actually wired into each LED in the set of lights that I used.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_8.png"><img title="image" height="201" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_8.png" width="226" border="0"></a>
<br>
<strong>Figure 7: Lighting the LEDs</strong></p>
<h5>Complete Circuit</h5>
<p>The complete circuit shown in Figure 8 simply links each output of the CD4094 shift register to an input on the ULN2803 Darlington Driver. Note that there is no reason to link any particular bit with any other, the diagram shown is one which will translate
 most easily to a prototype &quot;breadboard&quot;.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_9.png"><img title="image" height="260" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_9.png" width="500" border="0"></a>
<br>
<strong>Figure 8: The Complete Circuit</strong></p>
<p>The diagram just shows four lights connected to OUT1 from pin 18 of the ULN2803, the other 7 channels are connected in exactly the same way. Some of the pins can be left unconnected. Pins 9 and 10 of the CD4094 are only required if you are connecting multiple
 shift registers together and the common connection on pin 10 of the ULN2803 is not required. The Latch, Data and Clock signals on the CD4094 are connected to the output signals from the Micro Framework device.
</p>
<p>Figure 9 shows the completed circuit built up on a prototype breadboard. The chip on the left is the CD4094 and the one on the right is the ULN2803.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_10.png"><img title="image" height="331" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9149635/image_thumb_10.png" width="484" border="0"></a>
<strong><br>
Figure 9: The Completed Circuit</strong></p>
<p>The red wires carry the positive voltage from the power supply, which is connected to the top left of the circuit. The green wires are ground. Other coloured wires are used for signals. The Clock, Latch and Data signals are brought out to a connector which
 will fit a Digi-ME prototyping board.</p>
<h2>Selecting Lights</h2>
<p>Each bit in the value sent to the <b>displayByte</b> method and then into the shift register will be mapped to a particular chain of lights. The mapping of these is not particularly important, since you can use program constants to represent particular values.
 I wired the red signals to output pins 4 and 8. To light up just the red lights I used the value 0x88 which is the appropriate bit pattern. I then set up constants for all the other colors:</p>
<pre class="csharpcode"><span class="kwrd">const</span> <span class="kwrd">byte</span> GREEN = 0x11;
<span class="kwrd">const</span> <span class="kwrd">byte</span> BLUE = 0x22;
<span class="kwrd">const</span> <span class="kwrd">byte</span> YELLOW = 0x44;
<span class="kwrd">const</span> <span class="kwrd">byte</span> RED = 0x88;</pre>
<h2>Setting Up the Hardware</h2>
<p>The .NET Micro Framework provides a set of classes that can be used to represent the hardware in a system. The program uses instances of the
<b>OutputPort</b> class to represent the output pins. These are created in the method that sets up the hardware:</p>
<pre class="csharpcode"><span class="kwrd">const</span> Cpu.Pin clockPin = Cpu.Pin.GPIO_Pin0;
<span class="kwrd">const</span> Cpu.Pin dataPin = Cpu.Pin.GPIO_Pin1;
<span class="kwrd">const</span> Cpu.Pin latchPin = Cpu.Pin.GPIO_Pin2;

<span class="kwrd">static</span> OutputPort clockPort;
<span class="kwrd">static</span> OutputPort dataPort;
<span class="kwrd">static</span> OutputPort latchPort;

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> setupOutputs()
{
    clockPort = <span class="kwrd">new</span> OutputPort(clockPin, <span class="kwrd">false</span>);
    dataPort = <span class="kwrd">new</span> OutputPort(dataPin, <span class="kwrd">false</span>);
    latchPort = <span class="kwrd">new</span> OutputPort(latchPin, <span class="kwrd">false</span>);
}</pre>
<p>In this version of the hardware I have connected pin 0 of the processor to the clock, pin 1 to the data and pin 2 to the latch. If you use different pins you can change the settings above.</p>
<h1>Software</h1>
<p>Now that we have working hardware we can consider how the software is to work. Note that this version of the program works correctly but lacks exception handlers that would make it truly robust. I've left these out to simplify the explanation. To make sense
 of this description you will need to have a copy of the program itself available for reference.</p>
<p>You can develop the code using Visual Studio 2008 Express edition, which you can download from
<a href="http://www.microsoft.com/express/">http://www.microsoft.com/express/</a>
</p>
<p>The software is written for the .NET Micro Framework 3.0 which you can download from
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9356ed6f-f1f0-43ef-b21a-4644dd089b4a&amp;displaylang=en">
http://www.microsoft.com/downloads/details.aspx?FamilyID=9356ed6f-f1f0-43ef-b21a-4644dd089b4a&amp;displaylang=en</a>
</p>
<h2>Reading the Blog</h2>
<p>The program reads the RSS feed from a blog and looks for the <b>&lt;pubDate&gt;</b> value. This contains the date when the feed was last updated. Whenever this date changes the lights must flash red for a few seconds before resuming a random display. Users of
 the full .NET Framework can use the <b>HTTPRequest</b> class to build a <b>GET</b> command to be sent to a server. Unfortunately the .NET Micro Framework does not support this, so we have to access the web feed using socket based communication. This part of
 the program is heavily based on the <b>SocketClient</b> example supplied with the .NET Micro Framework.</p>
<pre class="csharpcode"><span class="rem">// This method requests a page from the specified server.</span>
<span class="kwrd">private</span> <span class="kwrd">static</span> String GetWebPage(String server, <span class="kwrd">string</span> webPage)
{
    <span class="kwrd">const</span> Int32 c_httpPort = 80;
    <span class="kwrd">const</span> Int32 c_microsecondsPerSecond = 1000000;

    <span class="rem">// Create a socket connection to the specified server and port.</span>
    <span class="kwrd">using</span> (Socket serverSocket = ConnectSocket(server, c_httpPort))
    {
        <span class="rem">// Send request to the server.</span>
        String request = <span class="str">&quot;GET &quot;</span>&#43; webPage &#43; 
             <span class="str">&quot; HTTP/1.1\r\nHost: &quot;</span> &#43; server &#43; 
             <span class="str">&quot;\r\nConnection: Close\r\n\r\n&quot;</span>;
        Byte[] bytesToSend = Encoding.UTF8.GetBytes(request);
        serverSocket.Send(bytesToSend, bytesToSend.Length, 0);

        <span class="rem">// Allocate a buffer to receive HTML chunks</span>
        Byte[] buffer = <span class="kwrd">new</span> Byte[1024];

        <span class="rem">// 'page' refers to the HTML data as it is built up.</span>
        String page = String.Empty; 

        <span class="rem">// Wait up to 30 seconds for initial data </span>
        <span class="rem">// Will throw exception if connection closed</span>
        DateTime timeoutAt = DateTime.Now.AddSeconds(30);
        <span class="kwrd">while</span> (serverSocket.Available == 0 &amp;&amp; 
               DateTime.Now &lt; timeoutAt)
        {
            System.Threading.Thread.Sleep(100);
        }

        <span class="rem">// Poll for data until 30 second time out</span>
        <span class="rem">// Returns true for data and connection closed</span>
        <span class="kwrd">while</span> (serverSocket.Poll(30 * c_microsecondsPerSecond,
                                 SelectMode.SelectRead))
        {
            <span class="rem">// Zero all bytes in the re-usable buffer</span>
            Array.Clear(buffer, 0, buffer.Length);

            <span class="rem">// Read a buffer-sized HTML chunk</span>
            Int32 bytesRead = serverSocket.Receive(buffer);

            <span class="rem">// If 0 bytes in buffer, then connection is closed, </span>
            <span class="rem">// or we have timed out</span>
            <span class="kwrd">if</span> (bytesRead == 0)
                <span class="kwrd">break</span>;

            <span class="rem">// Append the chunk to the string</span>
            page &#43;= <span class="kwrd">new</span> String(Encoding.UTF8.GetChars(buffer));
        }

        <span class="kwrd">return</span> page;   <span class="rem">// Return the complete string</span>
    }
}</pre>
<p>This method is called to fetch the journal RSS feed from my blog:</p>
<pre class="csharpcode"><span class="kwrd">string</span> address = <span class="str">&quot;www.robmiles.com&quot;</span>;
<span class="kwrd">string</span> name = <span class="str">&quot;/journal/rss.xml&quot;</span>;

<span class="kwrd">string</span> html = GetWebPage(address, name);</pre>
<p>You can use it to download from any RSS feed or page on the web. It will throw an exception if the page cannot be read. This version of my program does not perform exception handling however.</p>
<h2>Getting the Published Date</h2>
<p>The date is held in the form:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">pubDate</span><span class="kwrd">&gt;</span>Wed, 05 Nov 2008 22:38:52 &#43;0000<span class="kwrd">&lt;/</span><span class="html">pubDate</span><span class="kwrd">&gt;</span></pre>
<p>It would be enough just to record this content and check for changes in the text, but I decided that I might want to use the date information in a later version of the program and so I created some small helper methods to read numbers from the input string
 and a larger method to read the publish date itself:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> DateTime getRecentPubDate(<span class="kwrd">string</span> html, <span class="kwrd">string</span> startTag)
{
    <span class="kwrd">int</span> index = html.IndexOf(startTag) ;

    <span class="kwrd">if</span> (index &lt; 0) 
        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Missing tag &quot;</span> &#43; startTag);

    index &#43;= startTag.Length;

    <span class="rem">// spin past the name of the day</span>
    <span class="kwrd">while</span> (index &lt; html.Length &amp;&amp; html[index] != <span class="str">','</span>) index&#43;&#43;;
    <span class="kwrd">if</span> (index == html.Length) 
        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Short publish date&quot;</span>);

    <span class="kwrd">int</span> dayValue = getInt(html, <span class="kwrd">ref</span> index, <span class="str">' '</span>);

    <span class="kwrd">string</span> monthName = getString(html, <span class="kwrd">ref</span> index, <span class="str">' '</span>);
    <span class="kwrd">int</span> monthValue = getMonth(monthName);

    <span class="kwrd">int</span> yearValue = getInt(html, <span class="kwrd">ref</span> index, <span class="str">' '</span>);
    <span class="kwrd">int</span> hourValue = getInt(html, <span class="kwrd">ref</span> index, <span class="str">':'</span>);
    <span class="kwrd">int</span> minuteValue = getInt(html, <span class="kwrd">ref</span> index, <span class="str">':'</span>);
    <span class="kwrd">int</span> secondValue = getInt(html, <span class="kwrd">ref</span> index, <span class="str">' '</span>);

    <span class="kwrd">return</span> <span class="kwrd">new</span> DateTime(yearValue, monthValue, dayValue, 
                        hourValue, minuteValue, secondValue);
}</pre>
<p>The main body of the program uses this method to extract the date out of the RSS feed. When a new date is found it is time to update the lights.</p>
<h2>Lights and Threads</h2>
<p>My first version of the program flashed the lights for a while and then checked to see if a new blog post had been made. This worked OK, but the process of loading the RSS feed from the server and checking the dates can take a few seconds, which meant that
 the flashing lights would freeze every now and then. This did not look very good, and so I decided to use two threads instead. One is in charge of flashing the lights in a random pattern and the other loads the RSS feed from my blog and checks the date of
 the most recent publication. </p>
<p>Note that the threading I am using is exactly the same as threading in the full .NET Framework.
</p>
<h2>Thread Communication</h2>
<p>The two threads communicate by means of a single boolean variable which is set to true when the blog alert is to take place. The display thread reads this flag and flashes the lights red if it is time to alert.
</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> alert = <span class="kwrd">false</span>;

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> flasher()
{
    setupOutputs();

    <span class="kwrd">while</span> (<span class="kwrd">true</span>)
    {
        randomDisplay(400, 10);
        <span class="kwrd">if</span> (alert)
        {
            alert = <span class="kwrd">false</span>;
            flashRed(600, 20);
        }
    }
}</pre>
<p>The methods <b>randomDisplay</b> and <b>flashRed</b> do exactly what you would expect. Each of them gets two numbers to control the lights. The first number gives the delay in milliseconds between flashes (a few hundred milliseconds giving best results).
 The second gives the number of times that the lights should be flashed before the method finishes.
<b>RandomDisplay</b> displays random colors, whereas <b>flashRed</b> is simply flashes the red lights. The
<b>alert</b> flag is cleared before the red lights are flashed so that the system will resume normal display after the alert.</p>
<p>The second thread in the system performs the blog download and date test behaviour. This all happens inside the
<b>Main</b> method:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
    flashThread = <span class="kwrd">new</span> System.Threading.Thread(flasher);

    flashThread.Start();

    <span class="kwrd">string</span> address = <span class="str">&quot;www.robmiles.com&quot;</span>;
    <span class="kwrd">string</span> name = <span class="str">&quot;/journal/rss.xml&quot;</span>;

    String html = GetWebPage(address, name);

    DateTime lastUpdate = getRecentPubDate(html, <span class="str">&quot;&lt;pubDate&gt;&quot;</span>);

    Debug.Print(<span class="str">&quot;Initial Update Value : &quot;</span> &#43; lastUpdate.ToString());

    <span class="kwrd">while</span> (<span class="kwrd">true</span>)
    {
        System.Threading.Thread.Sleep(10000);

        html = GetWebPage(address, name);

        DateTime blogUpdate = getRecentPubDate(html, <span class="str">&quot;&lt;pubDate&gt;&quot;</span>);

        <span class="kwrd">if</span> (!blogUpdate.Equals(lastUpdate))
        {
            Debug.Print(<span class="str">&quot;Updated at : &quot;</span> &#43; blogUpdate.ToString());
            lastUpdate = blogUpdate;
            alert = <span class="kwrd">true</span>;
        }
    }
}</pre>
<p>To reduce the load on the network the system only checks the blog feed every 10 seconds.</p>
<h1>Future Work</h1>
<p>The program itself works fine, but the error handling is not wonderful. Although some of the methods used throw exceptions these are not caught anywhere, causing the blog reading thread to terminate. This does not stop the lights flashing, but it does mean
 that there will be no more alerts. However, it is not too hard to create a version which contains proper error handling and even flashes the lights different colors to indicate the alarm conditions. I have created a version that flashes the lights yellow every
 now and then if the network connection fails. There is also considerable scope for reading other web based sources and changing the output accordingly. Feel free to do all these things and make sure that you have fun.</p>
<h2>Thanks</h2>
<p>Thanks go to Ian Mitchell of Ormston Technology (<a href="http://www.ormtec.co.uk/">http://www.ormtec.co.uk/</a>) for doing such a great job of hardware design and build.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Rob-Miles/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:90ff2e0eefa3449089ad9e7600cda780">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Controlling-Your-Festive-Lights-with-the-NET-Micro-Framework</comments>
      <itunes:summary>





Author:
Rob Miles: 
www.robmiles.com 


Download:
Download


Software:
Visual Studio 2008 Express Edition or better,

.NET Micro Framework 3.0


Hardware:
Digi Connect-ME

GHI Electronics Embedded Master

Devices Solutions Tahoe II



Time Required:
3 hours


Cost:
30 dollars for lights plus the .NET Micro Framework device



The Micro Framework is one of the newest kids on the .NET block, but it does something really rather wonderful. It brings embedded development within the reach of any C# programmer. If you know C# and love Visual Studio, you can now get started building
 hardware and controlling it with your software. Moreover, it lets developers achieve one of their most cherished dreams, to control their festive lights using programs that they have written. This project shows you how to do just that and adds an extra magical
 feature, in that you can make all your festive lights flash red whenever I, Rob Miles, make a new post on that most famous of blogs,
www.robmiles.com.  
Actually, you can modify the code so that you can make your lights do most anything in response to an event that happens on the web. You could signal home that you are running late, send the weather forecast to your Christmas tree or explore any number of
 communication options. You might decide that this is so useful that you leave your decorations up all year round. 
If you just want to play with the .NET Micro Framework and get a feel for how easy it is to create software for tiny devices you don&#39;t actually need to use any extra hardware at all. The project comes with a complete emulation of the lights display so that
 you can run the whole thing on your computer and learn how hardware and software can be made to work together without burning your fingers with a soldering iron. 
However building the hardware will give you an understanding of how some simple electronic components can be controlled from C# and even how serial and parallel data transfer works. It is also great fun.</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Controlling-Your-Festive-Lights-with-the-NET-Micro-Framework</link>
      <pubDate>Fri, 28 Nov 2008 01:58:46 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Controlling-Your-Festive-Lights-with-the-NET-Micro-Framework</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9149635_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9149635_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Rob Miles</dc:creator>
      <itunes:author>Rob Miles</itunes:author>
      <slash:comments>6</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Controlling-Your-Festive-Lights-with-the-NET-Micro-Framework/RSS</wfw:commentRss>
      <category>.NET Micro Framework</category>
      <category>Hardware</category>
      <category>Robotics</category>
      <category>Home Automation</category>
      <category>Holiday</category>
      <category>.NET Microframework</category>
      <category>hardwarehacks</category>
    </item>
  <item>
      <title>Rob&#39;s Image Shrinker</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellpadding="1" cellspacing="0" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">In this article, we will create an application to resize images to desired size.</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">Rob Miles</div>
<div class="entry_company"><a href="http://www.crazyworldofrobmiles.com/">Crazy World(tm) of Rob Miles</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://msdn.com/express/">Visual Studio Express Editions</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b>
<ul>
<li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_CSharp.msi">C# Download</a>
</li><li><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/253791_Rob_27sImageShrinker_VB.zip">VB Download</a>
</li></ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>Devices like Smartphones, Pocket PCs, and Sony Playstation Portables are very useful for carrying pictures around. The problem is that modern cameras take pictures that are far bigger than a mobile device requires. A large number of megapixels makes a picture
 great for printing or viewing on a large display, but it just makes things difficult when you use a small device. Such high-resolution picture files take a long time to load and use up lots of file space.
</p>
<p>Many graphics programs, for example Microsoft Digital Image Pro 10, have bulk edit features, so that you can resize a whole bunch of pictures. If you have a portable media center, you can use Media Player 10 to resize the images as they are transferred.
 However, what you really want is a program that will resize your pictures and transfer them all at once. So I've written one, and we can explore how it works.
</p>
<p>Getting started is easy, whether you just want to use the program or play with the code. I've supplied a user manual in case all you want to do is use the program.
</p>
<h4>Working with the Application</h4>
<p>I've created the project in Visual C# 2005 Express edition. Open up the appropriate project file and you will be in business. If you have not got Visual Studio you can get hold of a copy for free from
<a href="http://msdn.microsoft.com/vstudio/express/visualcsharp/">http://msdn.microsoft.com/vstudio/express/visualcsharp/</a>.
</p>
<p>The initial download is quite small, but the installation will fetch around 300 MB of code.
</p>
<p>Once you have Visual Studio on your machine, you can open up the appropriate directory and select the solution file. In the next sections, we are going to consider each part of the program in detail. The examples as given are not exactly as in the source
 code, but we want to be able to concentrate on the important aspects of each part of the development.
</p>
<h4>Setting the Destination for the Images</h4>
<p>I set the destination by using a <b>FolderBrowserDialog</b>. This allows the user to find a directory where the image files are to be transferred. I've set the option so that the user can also create a new directory in which to place the images:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">outputDirDialog = <span class="kwrd">new</span> System.Windows.Forms.FolderBrowserDialog();<br>outputDirDialog.Description = <span class="str">&quot;Select Destination&quot;</span>;<br>outputDirDialog.ShowNewFolderButton = <span class="kwrd">true</span>;<br>outputDirDialog.ShowDialog();</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">If</span> outputDirDialog <span class="kwrd">Is</span> <span class="kwrd">Nothing</span> <span class="kwrd">Then</span><br>    outputDirDialog = <span class="kwrd">New</span> System.Windows.Forms.FolderBrowserDialog()<br>    outputDirDialog.Description = <span class="str">&quot;Select Destination&quot;</span><br>    outputDirDialog.ShowNewFolderButton = <span class="kwrd">True</span><br><span class="kwrd">End</span> <span class="kwrd">If</span><br>outputDirDialog.ShowDialog()</pre>
<p>I use the <b>ShowDialog</b> method so that the rest of my program pauses while the user selects the destination using this dialog:
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_1.gif">
</p>
<p><b>Figure 1. Browsing for a destination</b> </p>
<p>If the user opens up the My Computer tree, they can then find all the drive letters, including any for memory devices. Note that the program must also handle the situation where the user does not select a folder but clicks the &quot;Cancel&quot; button instead. In
 this situation the length of the resulting path will be 0, and so we display an appropriate message:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">if</span> (outputDirDialog.SelectedPath.Length == 0)<br>{<br>    statusLabel.Text = <span class="str">&quot;No destination selected&quot;</span>;<br>    <span class="kwrd">return</span>;<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">If</span> outputDirDialog.SelectedPath.Length = 0 <span class="kwrd">Then</span><br>    statusLabel.Text = <span class="str">&quot;No destination selected&quot;</span><br>    <span class="kwrd">Return</span><br><span class="kwrd">End</span> If</pre>
<p>We use a label at the bottom of the form to send messages to the user. </p>
<h4>Getting the Source Images</h4>
<p>Once we know where to put the files, we now need to select some files for transfer. The
<b>OpenFileDialog</b> is fine for this, since it can be configured to allow the user to select multiple files. The dialog can also show thumbnails of each image, so the user can easily see which files are to be transferred.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">sourceFilesDialog = <span class="kwrd">new</span> OpenFileDialog();<br>sourceFilesDialog.Multiselect = <span class="kwrd">true</span>;<br>sourceFilesDialog.Title = <span class="str">&quot;Select files to shrink&quot;</span>;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">sourceFilesDialog = <span class="kwrd">New</span> OpenFileDialog()<br>sourceFilesDialog.Multiselect = <span class="kwrd">True</span><br>sourceFilesDialog.Title = <span class="str">&quot;Select files to shrink&quot;</span></pre>
<p>This code creates the dialog and configures it to allow multiple files to be selected. Now we can configure it to show only image files for transfer:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">sourceFilesDialog.Filter = <br>    <span class="str">&quot;Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*&quot;</span>;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">sourceFilesDialog.Filter = <span class="str">&quot;Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|&quot;</span> _<br>    &amp; <span class="str">&quot;All files (*.*)|*.*&quot;</span></pre>
<p>The filter string looks rather complicated, but is really quite simple. Elements in the string are separated by the vertical bar character. Each filter is expressed as a pair of items, a description string followed by a list of filter expressions. It looks
 a bit clearer if I write it as:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="str">&quot;Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|&quot;</span> &#43;<br><span class="str">&quot;All files (*.*)|*.*&quot;</span></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="str">&quot;Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|&quot;</span> _<br>    &amp; <span class="str">&quot;All files (*.*)|*.*&quot;</span></pre>
<p>The top filter lets the user select image files that are Bitmap, JPEG, or GIF images. The second line lets the user select all the files. For each line the vertical bar splits off the text to appear in front of the user from a list of file extensions that
 apply to that selection </p>
<p>When the user selects the top filter, only file names matching Bitmap, JPEG, or GIF images are shown. When the bottom filter is selected, all files are shown.
</p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_2.gif">
</p>
<p><b>Figure 2. The filter in use</b> </p>
<p>Note that just because a file has a particular extension does not necessarily mean that it contains a particular type of file; our program must make sure that an invalid file content does not cause problems. We can address this later.
</p>
<p>Users can select as many files as they like from a directory, or even use CTRL&#43;A to select all of them. When they click the &quot;Open&quot; button, the dialog completes, and the files can then be processed and transferred into the destination device.
</p>
<h4>Doing the Processing</h4>
<p>The <b>OpenFileDialog</b><code> </code>returns a list of file names as an array of strings. The program must now open each file, load the bitmap from it, resize this into a bitmap of the required dimensions, and then save the bitmap in the destination directory.
 The method <b>processFiles</b> is in charge of all this.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">processFiles(sourceFilesDialog.FileNames, outputDirDialog.SelectedPath);</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">processFiles(sourceFilesDialog.FileNames, outputDirDialog.SelectedPath)</pre>
<p>This method is passed an array of file names and a destination path for the outputs. It must then work its way through the files and scale and save each one in turn.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> processFiles(<span class="kwrd">string</span>[] FileNames, <span class="kwrd">string</span> outputPath)<br>{<br>    Bitmap dest = <span class="kwrd">new</span> Bitmap(size.width, size.height);<br>    <span class="kwrd">foreach</span> (<span class="kwrd">string</span> filename <span class="kwrd">in</span> FileNames)<br>    {<br>        Bitmap image;<br>        <span class="kwrd">try</span><br>        {<br>            image = <span class="kwrd">new</span> Bitmap(filename);<br>        }<br>        <span class="kwrd">catch</span><br>        {<br>            MessageBox.Show(<span class="str">&quot;Error loading bitmap : &quot;</span> &#43; filename);<br>            <span class="kwrd">continue</span>;<br>        }<br>        scaleBitmap(dest,image);<br>        <span class="kwrd">string</span> destFilename = outputPath &#43; <span class="str">@&quot;\&quot; &#43; <br>            System.IO.Path.GetFileNameWithoutExtension(filename) &#43; &quot;</span>.jpg<span class="str">&quot;;<br>        try<br>        {<br>            dest.Save(destFilename, System.Drawing.Imaging.ImageFormat.Jpeg);<br>        }<br>        catch<br>        {<br>            MessageBox.Show(&quot;</span>Error saving bitmap : &quot; &#43; destFilename);<br>            <span class="kwrd">return</span>;<br>        }<br>    }<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> processFiles(<span class="kwrd">ByVal</span> FileNames <span class="kwrd">As</span> <span class="kwrd">String</span>(), <span class="kwrd">ByVal</span> outputPath <span class="kwrd">As</span> <span class="kwrd">String</span>)<br>    <span class="kwrd">Dim</span> dest <span class="kwrd">As</span> Bitmap = <span class="kwrd">New</span> Bitmap(Size.Width, Size.Height)<br>    <span class="kwrd">For</span> <span class="kwrd">Each</span> filename <span class="kwrd">As</span> <span class="kwrd">String</span> <span class="kwrd">In</span> FileNames<br>        <span class="kwrd">Dim</span> image <span class="kwrd">As</span> Bitmap<br>        <span class="kwrd">Try</span><br>            image = <span class="kwrd">New</span> Bitmap(filename)<br>        <span class="kwrd">Catch</span><br>            MessageBox.Show(<span class="str">&quot;Error loading bitmap : &quot;</span> &amp; filename, <span class="str">&quot;Bitmap Load&quot;</span>)<br>            Continue <span class="kwrd">For</span><br>        <span class="kwrd">End</span> <span class="kwrd">Try</span><br>        scaleBitmap(dest, image)<br>        <span class="kwrd">Dim</span> destFilename <span class="kwrd">As</span> <span class="kwrd">String</span> = outputPath &amp; <span class="str">&quot;\&quot;</span> _<br>            &amp; System.IO.Path.GetFileNameWithoutExtension(filename) &amp; <span class="str">&quot;.jpg&quot;</span><br>        <span class="kwrd">Try</span><br>            dest.Save(destFilename, System.Drawing.Imaging.ImageFormat.Jpeg)<br>        <span class="kwrd">Catch</span><br>            MessageBox.Show(<span class="str">&quot;Error saving bitmap : &quot;</span> &amp; destFilename, <span class="str">&quot;Bitmap Save&quot;</span>)<br>            <span class="kwrd">Return</span><br>        <span class="kwrd">End</span> <span class="kwrd">Try</span><br>    <span class="kwrd">Next</span><br><span class="kwrd">End</span> Sub</pre>
<p><b></b>This method works through each of the file names, creates a bitmap from each file, calls the
<b>scaleBitmap</b> method to scale it, and then saves the result back to disk. </p>
<p>Note that I have put an exception handler around the creation of the bitmap from a file. If the load fails, a message is displayed and the method moves on to the next image. There is also a try catch construction around the save operation. However, if the
 save fails this usually means that the next save will probably fail too, because the output device might be full. For this reason, when the save call fails the method returns rather than continues.
</p>
<h4>Scaling the Bitmap</h4>
<p>Scaling the bitmap is quite easy. There are draw methods that can be used to draw a rectangle from one image into another. By manipulating the sizes of the source and destinations, we can resize the image to fit on our device. The only difficulty is that
 we have to handle the aspect ratios of the source and destination, so that we don't clip off any parts of the image. This is exactly the same problem that you get when watching an old TV program on a widescreen TV or vice versa. The resize method must make
 the picture fit on the screen and insert empty space around it as required:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">private</span> Rectangle srcRect = <span class="kwrd">new</span> Rectangle();<br><span class="kwrd">private</span> Rectangle destRect = <span class="kwrd">new</span> Rectangle();<br><br><span class="kwrd">private</span> <span class="kwrd">void</span> scaleBitmap ( Bitmap dest, Bitmap src )<br>{<br>    destRect.Width = dest.Width;<br>    destRect.Height = dest.Height;<br>    <span class="kwrd">using</span> (Graphics g = Graphics.FromImage(dest))<br>    {<br>        Brush b = <span class="kwrd">new</span> SolidBrush(backgroundColor);<br>        g.FillRectangle(b, destRect);<br>        srcRect.Width = src.Width;<br>        srcRect.Height = src.Height;<br>        <span class="kwrd">float</span> sourceAspect = (<span class="kwrd">float</span>)src.Width / (<span class="kwrd">float</span>)src.Height;<br>        <span class="kwrd">float</span> destAspect = (<span class="kwrd">float</span>)dest.Width / (<span class="kwrd">float</span>)dest.Height;<br>        <span class="kwrd">if</span> (sourceAspect &gt; destAspect)<br>        {<br>            <span class="rem">// wider than high heep the width and scale the height</span><br>            destRect.Width = dest.Width;<br>            destRect.Height = (<span class="kwrd">int</span>)((<span class="kwrd">float</span>)dest.Width / sourceAspect);<br>            destRect.X = 0;<br>            destRect.Y = (dest.Height - destRect.Height) / 2;<br>        }<br>        <span class="kwrd">else</span><br>        {<br>            <span class="rem">// higher than wide – keep the height and scale the width</span><br>            destRect.Height = dest.Height;<br>            destRect.Width = (<span class="kwrd">int</span>)((<span class="kwrd">float</span>)dest.Height * sourceAspect);<br>            destRect.X = (dest.Width - destRect.Width) / 2;<br>            destRect.Y = 0;<br>        }<br>        g.DrawImage(src, destRect, srcRect, System.Drawing.GraphicsUnit.Pixel);<br>    }<br>}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> srcRect <span class="kwrd">As</span> Rectangle = <span class="kwrd">New</span> Rectangle()<br><span class="kwrd">Private</span> destRect <span class="kwrd">As</span> Rectangle = <span class="kwrd">New</span> Rectangle()</pre>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> scaleBitmap(<span class="kwrd">ByVal</span> dest <span class="kwrd">As</span> Bitmap, <span class="kwrd">ByVal</span> src <span class="kwrd">As</span> Bitmap)<br>    destRect.Width = dest.Width<br>    destRect.Height = dest.Height<br>    Using g <span class="kwrd">As</span> Graphics = Graphics.FromImage(dest)<br>        <span class="kwrd">Dim</span> b <span class="kwrd">As</span> Brush = <span class="kwrd">New</span> SolidBrush(backgroundColor)<br>        g.FillRectangle(b, destRect)<br>        srcRect.Width = src.Width<br>        srcRect.Height = src.Height<br>        <span class="kwrd">Dim</span> sourceAspect <span class="kwrd">As</span> <span class="kwrd">Single</span> = src.Width / src.Height<br>        <span class="kwrd">Dim</span> destAspect <span class="kwrd">As</span> <span class="kwrd">Single</span> = dest.Width / dest.Height<br>        <span class="kwrd">If</span> sourceAspect &gt; destAspect <span class="kwrd">Then</span><br>            <span class="rem">' wider than high</span><br>            destRect.Width = dest.Width<br>            destRect.Height = (dest.Width / sourceAspect)<br>            destRect.X = 0<br>            destRect.Y = (dest.Height - destRect.Height) / 2<br>        <span class="kwrd">Else</span><br>            <span class="rem">' higher than wide</span><br>            destRect.Height = dest.Height<br>            destRect.Width = ((dest.Height * sourceAspect))<br>            destRect.X = (dest.Width - destRect.Width) / 2<br>            destRect.Y = 0<br>        <span class="kwrd">End</span> <span class="kwrd">If</span><br>        g.DrawImage(src, destRect, srcRect, System.Drawing.GraphicsUnit.Pixel)<br>    <span class="kwrd">End</span> Using<br><span class="kwrd">End</span> Sub</pre>
<p>Resizing images is actually quite easy. The <b>DrawImage</b> method can be supplied with source and destination rectangles. The method above decides which way the source needs to be scaled and then adjusts the size and position of the destination rectangle
 to suit. The call of <b>DrawImage</b> at the bottom of the method is the part that does the actual work. Note that the rectangles that we use to size the source and destination are declared outside the method. This is so that we do not end up creating and
 destroying new rectangles for each image that we scale. Since all we really want to do is change the dimensions of them each time we use them, there is no need to keep making new ones.
</p>
<h4>Managing the Size</h4>
<p>The user needs to be able to select from a range of possible widths and heights, depending on the target device. The best screen component for doing this is the
<b>ComboBox</b>, with a list of items from which the user picks one. </p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_3.gif">
</p>
<p><b>Figure 3. Selecting the output format</b> </p>
<p>The best way to manage this is to create a special class that holds the size information. We can then supply an array of instances of this type to the
<b>ComboBox</b> and it will let the user pick one.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> OutputSize<br>{<br>    <span class="kwrd">public</span> <span class="kwrd">int</span> width;<br>    <span class="kwrd">public</span> <span class="kwrd">int</span> height;<br>    <span class="kwrd">string</span> name;<br>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> ToString()<br>    {<br>        <span class="kwrd">return</span> name &#43; <span class="str">&quot;  &quot;</span> &#43; width.ToString() &#43; <span class="str">&quot; x &quot;</span> &#43; height.ToString();<br>    }<br>    <span class="kwrd">public</span> OutputSize(<span class="kwrd">string</span> inName, <span class="kwrd">int</span> inWidth, <span class="kwrd">int</span> inHeight)<br>    {<br>        name = inName;<br>        width = inWidth;<br>        height = inHeight;<br>    }<br>}<br></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Class</span> OutputSize<br>    <span class="kwrd">Public</span> width <span class="kwrd">As</span> <span class="kwrd">Integer</span><br>    <span class="kwrd">Public</span> height <span class="kwrd">As</span> <span class="kwrd">Integer</span><br>    <span class="kwrd">Private</span> name <span class="kwrd">As</span> <span class="kwrd">String</span><br>    <span class="kwrd">Public</span> <span class="kwrd">Overloads</span> <span class="kwrd">Overrides</span> <span class="kwrd">Function</span> ToString() <span class="kwrd">As</span> <span class="kwrd">String</span><br>        <span class="kwrd">Return</span> name &amp; <span class="str">&quot;  &quot;</span> &amp; width.ToString() &amp; <span class="str">&quot; x &quot;</span> &amp; height.ToString()<br>    <span class="kwrd">End</span> <span class="kwrd">Function</span><br>    <span class="kwrd">Public</span> <span class="kwrd">Sub</span> <span class="kwrd">New</span>(<span class="kwrd">ByVal</span> inName <span class="kwrd">As</span> <span class="kwrd">String</span>, <span class="kwrd">ByVal</span> inWidth <span class="kwrd">As</span> <span class="kwrd">Integer</span>, _<br>            <span class="kwrd">ByVal</span> inHeight <span class="kwrd">As</span> <span class="kwrd">Integer</span>)<br>        name = inName<br>        width = inWidth<br>        height = inHeight<br>    <span class="kwrd">End</span> <span class="kwrd">Sub</span><br><span class="kwrd">End</span> Class</pre>
<p>The <b>OutputSize</b> type contains a name property to identify it as well as height and width values. The
<b>ToString</b> method that it exposes provides the text shown in the <b>ComboBox</b>. The width and height properties are made public so that they can be used by methods in other classes. Finally, it has a constructor that lets us set up all the values. We
 can now create an array of instances of this class which can be used to configure the
<b>ComboBox</b>:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">private</span> OutputSize[] resolutionSettings = <span class="kwrd">new</span> OutputSize[] {<br>    <span class="kwrd">new</span> OutputSize ( <span class="str">&quot;Pocket PC&quot;</span>, 640, 480 ),<br>    <span class="kwrd">new</span> OutputSize ( <span class="str">&quot;QVGA&quot;</span>, 320, 240 ),<br>    <span class="kwrd">new</span> OutputSize ( <span class="str">&quot;PSP&quot;</span>, 480, 272 ),<br>    <span class="kwrd">new</span> OutputSize ( <span class="str">&quot;Smartphone&quot;</span>, 176, 180)<br>};</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> resolutionSettings <span class="kwrd">As</span> OutputSize() = <span class="kwrd">New</span> OutputSize() { _<br>        <span class="kwrd">New</span> OutputSize(<span class="str">&quot;Pocket PC&quot;</span>, 640, 480), _<br>        <span class="kwrd">New</span> OutputSize(<span class="str">&quot;QVGA&quot;</span>, 320, 240), _<br>        <span class="kwrd">New</span> OutputSize(<span class="str">&quot;PSP&quot;</span>, 480, 272), _<br>        <span class="kwrd">New</span> OutputSize(<span class="str">&quot;Smartphone&quot;</span>, 176, 180)}</pre>
<p>If you want to add other sizes to the program these can just be slotted into the array and will be picked up and used automatically. Adding the settings to the
<b>ComboBox</b> is achieved very easily:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">resolutionComboBox.DataSource = resolutionSettings;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">resolutionComboBox.DataSource = resolutionSettings</pre>
<p>This is a very powerful feature of Windows forms. The <b>ComboBox</b> just pulls in the settings and populates its selections with the values in the array. When we want to get the present selection, we just have to get it and cast it to the actual type that
 we know is in there:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">OutputSize size = resolutionComboBox.SelectedItem <span class="kwrd">as</span> OutputSize;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Dim</span> size <span class="kwrd">As</span> OutputSize = <span class="kwrd">TryCast</span>(resolutionComboBox.SelectedItem, OutputSize)</pre>
<p><b></b>We can now use the <b><code>width</code></b> and <b><code>height</code></b> properties of the
<b>size</b> instance to control the scaling. </p>
<h4>Setting the Background Color</h4>
<p>I let the user select the background color that is used to fill around images when their aspect ratio is not quite right. This color is stored as a member of the form:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode"><span class="kwrd">private</span> Color backgroundColor = Color.White;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">Private</span> backgroundColor <span class="kwrd">As</span> Color = Color.White</pre>
<p><b></b>Initially it is set to white, but the user can select different colors according to taste. I use the
<b>ColorDialog</b> dialog to allow the user to do this:</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">backColorDialog = <span class="kwrd">new</span> ColorDialog();<br>backColorDialog.SolidColorOnly = <span class="kwrd">true</span>;<br>backColorDialog.Color = backgroundColor;<br>backColorDialog.ShowDialog();</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode"><span class="kwrd">If</span> backColorDialog <span class="kwrd">Is</span> <span class="kwrd">Nothing</span> <span class="kwrd">Then</span><br>        backColorDialog = <span class="kwrd">New</span> ColorDialog()<br>        backColorDialog.SolidColorOnly = <span class="kwrd">True</span><br>    <span class="kwrd">End</span> <span class="kwrd">If</span><br>backColorDialog.Color = backgroundColor<br>backColorDialog.ShowDialog()</pre>
<p>This dialog lets the user select a color: </p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_4.gif">
</p>
<p><b>Figure 4. Selecting a color</b> </p>
<p>Once the user has selected the color, they can use it as the background for the image that is drawn as the background in the
<b>scaleBitmap</b> method. </p>
<h4>Previewing the Images</h4>
<p>The user will want to see the images previewed as each is transferred. This is easily achieved by using a
<b>PictureBox</b> component on the application form. We set the background color of the
<b>PictureBox</b> to the selected background so that the previewed image looks as much like the transferred one as possible. The image on the
<b>PictureBox</b> is set from the scaled image.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">previewPictureBox.Image = dest;</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><b>Visual Basic</b></p>
<pre class="csharpcode">previewPictureBox.Image = dest</pre>
<p>The only other thing that we have to do with the <b>PictureBox</b> is to make sure that its
<b>SizeMode</b> property is set to <b><code>Zoom</code></b>, so that the preview image will fill the preview window exactly.
</p>
<h4>Showing the Progress</h4>
<p>Another useful touch is a progress bar. If a large number of files are being transferred, the user will appreciate being given some indication of how far through the transfer the program has reached. We can calculate the amount of progress by dividing the
 number of files transferred so far by the total number of files that have been selected. This will give us a fraction we can multiply by 100 to generate a percentage value for the progress bar size.</p>
<p><b>Visual C#</b> <br>
</p>
<pre class="csharpcode">loadProgressBar.Value = (<span class="kwrd">int</span>)(100 * ((<span class="kwrd">float</span>)fileCount / (<span class="kwrd">float</span>)noOfFiles));</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h4><b>Visual Basic</b></h4>
<pre class="csharpcode">loadProgressBar.Value = (100 * (fileCount / noOfFiles))</pre>
<p><b>Deadlock Difficulties</b></p>
<p>The program works well as it is, but it does have one problem. Sometimes the image transfer takes quite a while to complete. During this process, the error tracking provided by Visual Studio might decide that the program has stopped. It then throws an exception
 that causes the program to fail. Turning this exception off is not difficult; we need to find the &quot;Exceptions&quot; item (on the &quot;Debug&quot; menu item) and then set clear the &quot;Thrown&quot; box next to the
<b>ContextSwitchDeadlock</b> exception, so that the dialog appears as below: </p>
<p><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/910075/ImageShrinker_5.gif">
</p>
<p><b>Figure 5. Turning off the ContextSwitchDeadlock exception</b> </p>
<p>Once we have done this, the program will run correctly, even with very large transfers.
</p>
<h4>The Completed Program</h4>
<p>The completed program works well. I have successfully transferred 127 pictures onto my Playstation Portable in a single go and I've found that I get lots more pictures on the machine — all 127 fitted into 3.7 MB. However, there are a number of enhancements
 you might like to consider. </p>
<h4>Automatic Playstation Portable Detection</h4>
<p>The Playstation Portable has a very distinctive file arrangement on its storage device. In fact you must put your pictures into the \PSP\PHOTO directory or they will not be displayed (use the path in Figure 1 as an example). It would be possible for the
 program to be made to check through each of the drives on the system, automatically find a PSP device, and configure itself appropriately.
</p>
<h4>Drag-and-Drop Image Transfer</h4>
<p>Rather than pick the images from a file dialog, the program could be made to accept files that are dropped onto the form. It could then scale and transfer those.
</p>
<h4>Automatic Landscape/Portrait Rotation</h4>
<p>The Smartphone has a portrait format display: It is higher than it is wide, which is in contrast to most pictures (which are landscape). This means that the program as written will not make the best use of the screen. It would be useful if pictures could
 be rotated as they are transferred, so that they fill as much of the display as possible. Alternatively the user could be given the option for all Smartphone pictures to be rotated before transfer, so that they can be shown to best effect.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Rob-Miles/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:5bbc88146c3344e395ea9e7600dbb342">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Robs-Image-Shrinker</comments>
      <itunes:summary>



&amp;nbsp;
In this article, we will create an application to resize images to desired size.



Rob Miles
Crazy World(tm) of Rob Miles

Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Visual Studio Express Editions
Hardware: 
Download: 

C# Download
VB Download







Devices like Smartphones, Pocket PCs, and Sony Playstation Portables are very useful for carrying pictures around. The problem is that modern cameras take pictures that are far bigger than a mobile device requires. A large number of megapixels makes a picture
 great for printing or viewing on a large display, but it just makes things difficult when you use a small device. Such high-resolution picture files take a long time to load and use up lots of file space.
 
Many graphics programs, for example Microsoft Digital Image Pro 10, have bulk edit features, so that you can resize a whole bunch of pictures. If you have a portable media center, you can use Media Player 10 to resize the images as they are transferred.
 However, what you really want is a program that will resize your pictures and transfer them all at once. So I&#39;ve written one, and we can explore how it works.
 
Getting started is easy, whether you just want to use the program or play with the code. I&#39;ve supplied a user manual in case all you want to do is use the program.
 
Working with the Application
I&#39;ve created the project in Visual C# 2005 Express edition. Open up the appropriate project file and you will be in business. If you have not got Visual Studio you can get hold of a copy for free from
http://msdn.microsoft.com/vstudio/express/visualcsharp/.
 
The initial download is quite small, but the installation will fetch around 300 MB of code.
 
Once you have Visual Studio on your machine, you can open up the appropriate directory and select the solution file. In the next sections, we are going to consider each part of the program in detail. The examples as given are not exactly as in the source
 code, but we want to be abl</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Robs-Image-Shrinker</link>
      <pubDate>Tue, 31 Oct 2006 11:41:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Robs-Image-Shrinker</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/910075_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/910075_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Rob Miles</dc:creator>
      <itunes:author>Rob Miles</itunes:author>
      <slash:comments>9</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Robs-Image-Shrinker/RSS</wfw:commentRss>
    </item>    
</channel>
</rss>