Monday, December 20, 2010

Enable Blogger Mobile Templates Support for WP7 and Opera Mobile

Blogger recently released a new feature to their Blogger in draft platform that allows the website to automatically detect mobile browsers and render the page using a small-screen friendly template. This fixes a HUGE issue I have been working on for the last few weeks ever since I released the PhraseMeme Scanner application, namely publishing content that will be consumed by both large and small screen devices. Previously I was planning on having two version of the website with one being optimized for mobile and one for desktop, but now I can store all the content on Blogger and use the mobile templates to render for small-screen devices.

The Show mobile template currently works with the default iPhone and Android browsers, but it does not work with the Opera Mobile, Pocket IE, or Windows Phone 7 Internet Explorer browsers. I assume there are other mobile browsers that also don’t work, but there is a simple way to add support for any browser by using JavaScript to redirect users.  Here is the code that I wrote to detect mobile browsers and redirect accordingly:

The templates work by appending a m=1 parameter to the blog URL or (m=0 to force full webpage on mobile devices), so all that the above code has to do is look for that parameter and add it if a mobile device is detected. You can add the above script to your blog using either the blog template or the HTML/Javascript Gadget. Adding it to the blog template will cause it to run before the page is fully loaded, but you should save your current template first to make sure you don’t mess anything up;

I added a feature request for Blogger to support more mobile browsers, but for now the above script should let you start using this amazing feature.

Wednesday, December 8, 2010

Windows Phone Barcode Library (Silverlight C# ZXing Port)

I have been working on a Barcode Scanning application for Windows Phone 7 for about 3 months now, but none of my efforts would have been possible without the prior work done by Google on the open source ZXing (“Zebra Crossing”) barcode scanning library. This library is released under the Apache License v2.0 and has spurred development of many different barcode scanners on many different platforms. The idea for PhraseMeme Scanner came when I saw there weren’t any good scanners available for Windows Phone 7 and then stumbled across the partial C# port of ZXing. Through a bit of testing I was able to modify the library to support Silverlight and Window Phone 7, and decided I would help push the library into a well maintained and supported state in the Silverlight world.

While the primary purpose for updating the library is to build the "Best barcode scanning app available" I also want to give back to the community and help others create great windows phone or Silverlight apps. ZXing has their own Google Code project, but that site is mainly devoted to Android or Java development, so I decided to store the code on Codeplex to get it some .Net love. This also means that I can use Mecurial instead of SVN/CVS, which so far has been a great experience and should be very helpful if anyone else decides to contribute patches or new features to the library.

So without further ado, please check out the Windows Phone 7 Silverlight ZXing Barcode Scanning Library based on the csharp ZXing port created by Suraj Supekar at revision 1202 in the SVN repository. Let me know what you think, and happy coding!

Update 3/11/2011: It looks like the project is getting a lot of interest from developers with over 6,000 page views and 750 total downloads in the last few months. This is probably due to the various tweets on twitter and a blog post from Rudi Grobler about reading barcodes on WP7 using the Silverlight ZXing port. That blog post was mentioned on This Week in Channel 9, which totally made my day even if it was only talked about for 40 seconds and never even mentioned my name. Still… pretty wicked cool

Smile with tongue out

Monday, October 4, 2010

VPS/VM vs Dedicated vs Cloud Servers: Hosting options and cost comparisons

I usually talk about Code on this blog, but eventually that code is going to have to run somewhere so I thought I would outline some of the different server options that are available. While there are free or low cost options for hosting simple or small websites, if you are using ASP.NET, PHP, or Java to create a dynamic website or if you are looking for a file or application server then you are going to have to pay for the resources that you use (bandwidth, hardware, software, etc). The price/performance ratio can vary greatly depending on what type of server you purchase. There are a lot of different configurations, but here are some of my recommendations.

First, what not to do:

While in certain cases it may be appropriate, my recommendation is to steer clear of two specific hosting options: Shared web hosting and Do-It-Yourself hosting. Shared hosting refers to the $5 a month plans offered by Godaddy, Yahoo, and thousands of “resellers” that use a control panel like Plesk or cPanel to divide up a single server into hundreds of small websites. These servers are often over-sold and under-powered, and you will only get FTP and control panel access, so you will have to rely on your hosting provider to make any advanced configuration changes or perform troubleshooting steps for you. If you cannot afford any of the other options then Shared Hosting might be a good way to start, but keep in mind that you get what you pay for and will  probably out-grow it very quickly.

As for Do-It-Yourself hosting, this is simply a case of economies of scale: You wouldn’t start a wheat farm just to make a sandwich, so why build and maintain your own servers? Unless you are a corporation with a full IT department, it is not in your best interest to setup and maintain your own web or application servers outside of your personal testing/development environment. Servers are more or less a commodity nowadays, so while you could setup a computer in a closet of your office and use it to host your company website, you then have to worry about what happens when the power goes out or when your Internet connection goes down. Setting up and maintaining a reliable network with redundant paths and uninterrupted power takes a considerable amount of time and money. I highly suggest that you outsource this effort to a 3rd party and focus your energy on improving your website or application instead. And in terms of running your own Email and Calendaring server, you really, REALLY should look at paying Google, Microsoft, or someone else to provide these services for you if at all possible.

Virtual Private Server / Virtual Machine:

It use to be that when looking for a hosting provider you were either stuck with shared hosting or a dedicated server. Now there are many other options, most of which are based on server virtualization. While it may sound similar to Shared Hosting, VPS or VM hosting options can provide guaranteed resources and an isolated execution environment in which you have full control of the server. The hosting provider will purchase high-end server hardware and then use a hypervisor to divide that server up into multiple virtual machines for different customers (usually 2-24 depending on the size of the VMs). Each VM gets a certain percentage of the CPU, Memory, and Disk Space and will function as its own server. From my experience VPS or VM hosting provides the best bang for your buck at around $20-$120 a month (see Choosing a Hosting Provider below).

Dedicated Servers:

Some applications require significant horsepower, in which case a dedicated server is usually a requirement. You can purchase standardized “cookie-cutter” servers from most hosting providers, or you can also get a custom quote if you need to have a specific type of RAID setup or maximize RAM size or CPU speeds. Until recently I have primarily worked with dedicated servers that usually run anywhere from $100 to $1000 a month, so they are only viable in business environments that can justify the cost of the server. You also may have the option to rent, lease or purchase the server, but if you are purchasing you must factor in the time and costs for replacing failed hardware components in the future. Also if you work with sensitive information such as credit cards or medical records then you may require a dedicated server to meet Payment Card Industry (PCI), Health Insurance Portability and Accountability Act (HIPAA) or various other federal regulations.

Cloud IaaS and PaaS Servers:

Cloud hosting is the new hot term, but a lot of the time it means the same thing as VPS or VM Hosting except you pay by the hour instead of by the month. There are typically 3 types of “Cloud Computing”: IaaS, PaaS, and SaaS. For the most part Infrastructure as a Service (IaaS) is exactly the same as VPS or VM hosting just with a fancy API and pay-by-the-hour terms. Software as a Service (SaaS) doesn’t really have servers in the sense that you usually are riding on top of another application (Ex: Google Apps or Salesforce). Platform as a Service (PaaS) still uses Virtual Machines, but the platform is designed to help you scale your application horizontally across multiple nodes. Amazon Web Services (AWS) has some PaaS products, but their EC2 product fits more into the IaaS category (you have to scale-out your code to work on multiple servers on your own). Windows Azure, Rackspace Cloud Sites and Google App Engine are examples of PaaS, but they each have different programing models so you have to build your application around their platform. PaaS is designed to scale to meet your traffic needs and use multiple server nodes to provide better reliability, but this also means you will play a higher cost if you are running a 24x7x365 application. For instance, running two small web roles in Windows Azure to create a high availability website would cost $0.12*2*24*30 = $172.80 a month.

Choosing a Hosting Provider:

So now that you have an idea of the different types of hosting, all you have to do is find a hosting provider that offers a solution that meets your needs. I have worked with ASP.NET websites of various sizes for the last 5-10 years and can highly recommend the following companies based on my experience with them:
  • Offers all types of hosting ranging from shared to dedicated to virtual machines and custom quotes. Their VPS product is very affordable starting at $35 per month for a Win 2003 server or $20 per month for a Linux server. They also have great rates on dedicated servers starting at around $70-$80 a month. I had a server with them for about 10 years and they have always had great support and great prices.
  • Recently I moved my Windows server over to a VPS hosted at AccuWebHosting. They are not as large as, but they offer some of the the best rates on VPS servers starting at $23 per month for Windows or $16.50 per month for Linux. While not as powerful as a dedicated server the VPS servers work great for light web or application servers.
  • Offers fully managed dedicated servers and colocation services with “Fanatical Support”. They are a premium provider and cost a bit more than their competitors (starting around $500-$600 a month for a mid-range server), but if your application is mission critical you can feel comfortable turning over the keys to them and they will make sure your servers remain online and operational. Also Rackspace is the only vendor I have ever been able to get to sign a HIPAA compliant Business Associate Agreement (BAA).
  • Originally called Mosso it was rebranded in July 2009 and offers Cloud CDN, Website, and Server solutions. They have managed servers starting at less than $100 a month, so if you want “Fanatical Support” without the high costs this might be a good place to start.
  • Amazon EC2: EC2 is the most mature of the online cloud providers and offers the most pricing options including Spot and Reserved instances. If you envision scaling out to hundreds of servers it is well worth your time to check out EC2. Their Simple Storage Service (S3) is also one of the best storage providers as it offers two price points depending on the level of durability that you require.
  • Windows Azure: Designed for high reliability and easier development, Azure is worth looking into if you are starting a new Microsoft .NET project that will require multiple servers. They are the new kid on the block, having been officially released in February 2010, but their use of Roles instead of servers means an application can be easily scaled up or down as needed. Also SQL Azure is a great way to create a hosted MS SQL database, as you pay $10 per GB per month, which combined with $0.15/GB/Month for blob storage means you should be able to store all your data and images/files for relatively cheap and support a large number of simultaneous users. Check out an introduction to Windows Azure for more information and watch the Cloud Cover show on Channel 9 for great coverage.
I hope this helps as you look at designing or scaling out your application or website. If you have questions I highly suggest asking them on one of the StackExchange websites such as or There are usually lots of great people there willing to help answer questions.

Sunday, September 19, 2010

Localization and Globalization in WP7 Applications Using Resource Files

I’ve been watching the progress of Windows Phone 7 for a while now and recently started developing a few applications that I hope to release to the marketplace when it opens later this year. One of the apps I have been working on uses .NET Resource files to allow label and button text to be translated into other languages. While the idea is simple the implementation was a bit more complicated than what I was expecting, so I thought I would post some details here to help guide others.

First off, if you are not familiar with .NET Resource files, I suggest watching this video on Globalization and Localization from the Windows Phone 7 in 7 training series, which gives a great overview of what each of the terms mean. In my case I was most interested in localization using separate resource files for each language, which was not covered in the video but is covered in the MSDN Windows Phone documentation linked to at the end of the video. This documentation was very helpful for setting up the resource files and creating a LocalizedStrings class, but after that they only provided one method of setting up the data binding for XAML objects. They also did not elaborate on some of the other options you can use when setting up localization resource files.

After a few tries and a bit of Google-fu I was able to get things setup how I wanted by adding these additional steps:

  1. I created all the Resource files and the LocalizedStrings class in a Localization folder to keep things organized. It use to be that the .RESX files had to be in a special Resource folder in Visual Studio, but with 2010 they can be stored anywhere you want. If you have a large application you would probably want to have multiple folders with their own set of resource files (ex: one for each UI page or section of your application). In this case you would still have a single LocalizedStrings class, but inside that class there would be public properties for multiple resource files (ex: MainPageResources, SettingsPageResources, etc…) instead of just one Localizedresources property. 
  2. The above articles specifically reference the en-US and es-ES cultures, but .NET also supports using just en or es for culture-invariant language specification, which is usually better if all you need is localization without currency or date/time format conversions. You can in fact create a general fr file that includes French translations and use that same file to support both France (fr-FR) and Canada (fr-CA) cultural variants. See MSDN for more information about the Hierarchical Organization of Resource Files and see this list for all of the specific languages and cultures supported by Silverlight.
  3. The MSDN article shows you how to setup the files and create the LocalizedStrings class, but they then assume that you know how to use that class for data binding. Visual Studio 2010 and Silverlight handle data binding differently than Winforms, and it gets even more confusing since XAML also has it’s own definition of Resources that are different then the .NET resources we just created. Silverlight also uses the term Resource to refer to files that use the the Build Action of "Content”, as these files get wrapped up into the .XAP file similar to how files with Build Action of "Resource” get embedded into the .Dll assembly (ex: loading an image from content or resource files). I found that instead of using the Text="{Binding Path=resourceFile.resourceName, Source={StaticResource Localizedresources }}" XAML syntax it was easier to use the following steps:
    1. Open your primary XAML page (usually MainPage.xaml) in the Visual Studio designer
    2. Open the properties for the PhoneApplicationPage and set the DataContext to be Application.Resources –> LocalizedStrings. NOTE: if you already are using a DataContext object, then you should integrate the LocalizedStrings class into that object so that it has localization support.
    3. Once the Page’s DataContext has been set you can change the data binding for any control on the page by simply selecting the property (ex: text, checked, etc), selecting “Apply Data Binding…”, and setting the Path to Localizedresources.BtnText or whatever the name of the desired resource value is.
  4. If you want to change the text in the Application Bar you have to jump through a few hoop because it is not actually a Silverlight control and does not support data binding. Instead you have to create or update the Application Bar at runtime.
I hope this helps!

Friday, September 10, 2010

Excel 2010 Regular Expressions: Manually installing Morefunc 5 Add-in

I came across a need to use regular expressions in a spreadsheet today. Usually in this case I would look at using a more powerful tool such as Resolver One, which I have added into my toolbox and used for many side projects, but in this case I was stuck using Excel for legacy reasons. Sadly even the latest version of Excel 2010 does not have built in support for Regular Expressions so you either have to drop into VBA code and write your own Regex functions or install an add-on that has pre-built functions. This blog post brought me to a nice free add-on for Excel called Morefunc which has a bunch of Regex functions, but it doesn’t work right out of the box with Excel 2010. After installing it I had to follow these instructions to manually add the Morefunc.xll, Morefunc11.xla, and Morefunc12.xlam files from the “C:\Program Files\Morefunc” folder. Once I did that and allowed macros on the spreadsheet then the new functions showed up under the Morefunc category and under the Functions section of the Formula ribbon group. Since I didn’t see these instructions posted anywhere else I figured I would post them here so that others could find them.


Monday, June 14, 2010

Powershell Backup All Databases Locally and to Amazon S3

Previously I had posted a Powershell script that would use 7Zip to compress and encrypt a folder and then send it to Amazon S3. This script could have many uses, but in my case it was designed to fulfill the need for off site storage of compressed database backups. While it did all the heavy lifting of getting the data encrypted, compressed and uploaded to S3 I left the creation of the database backup folder as an exercise for the user to complete.

I now have a working system that I would like to share in case anyone was unable to create the backup folder using Powershell. There were a few hiccups that I found, such as not being able to use the Start-Transcript method in a SQL Agent Job and having my MSDB data file triple in size after 3 months of backups, but after working out those issues the script provides a very cost effective method of creating both local and offsite database backups with 1 week or 1 month retention. Currently I have it running on a server with about 100 databases ranging in size from 7MB to 700MB with daily full backups and hourly differential backups being sent to Amazon S3 and stored with 1 month retention for about $5 a month. The total raw backup size is 2.2GB per full backup set and 100-400MB for each differential backup set, but the script gets about 10:1 compression so the daily storage on S3 is about 500MB total for all of the full and differential backups.

You will need to modify the settings in both the psBackupAllDBtoAmazonS3.ps1 and ps7ZiptoAmazonS3.ps1 files to get this to work on your server, but once you do you can sit back and let the scripts do it’s magic. You can set it to run as a scheduled task, but we chose to run it as an SQL Agent Job so that our server monitoring software would notify us if there were any issues with the script.

Friday, April 16, 2010

Lap Around .NET 4 with Scott Hanselman

Things were slow at the office today, so I used the free time to catch up on some of the recorded sessions from DevDays 2010. Scott Hanselman’s overview of the new features in .NET 4 is one of the best presentation I have seen about .NET 4 so far. How many presentations include 14,000 generations of monkeys trying to write Shakespeare? Here is the synopsis:

In this session, Scott Hanselman gives a deep and broad tour of the .NET 4 release, with a focus on making your development experience easier. See lots of demos (and very few slides) showcasing the key new features in the .NET Framework 4 including MEF, improvements in ASP.NET, threading, multi-core and parallel extensions, additions to the base classes, changes and additions to the CLR and DLR, what's new for the languages (Visual Basic and C#), and of course, what's new in Windows Presentation Foundation and System.Web. Come and see how all these new features and capabilities improve your overall .NET experience!


Sunday, March 14, 2010

TED Fullscreen Video Multiple Monitor Userscript: Yay!

I like to think that I can hack out JavaScript as good as any web developer, but occasionally I still fall into rookie mistakes. For instance, I totally forgot to test my last userscript for fixing Slashdot articles while zooming in anything but my default browser (Google Chrome). In theory it should have worked with Greasemonkey, but when I tried testing it today using Firefox it failed miserably. Luckily with a few code changes I was able to update the script and get it to work with both Firefox and Google Chrome as well as fix a huge bug when visiting Slashdot’s main page as a non-registered user (another thing I probably should have tested!).

Considering that it was my first attempt at a user script I am not too upset and will chalk it up to experience. Tonight my plans for the evening fell apart, so I decided to try and fix a big pet peeve of mine: no multiple monitor support for video players on certain websites. Maybe I am the only one that thinks this is a problem, but I hate it when websites have a Flash or Silverlight video player embedded onto their page and don’t have an option to enlarge the video or open it in a pop-out window. Most people do fine using the fullscreen mode built into the player, but both Silverlight and Flash fail at fullscreen with multiple monitors since they will exit fullscreen as soon as you try and click on something outside the video (for security purposes apparently). This means you can either stop multi-tasking and only watch the video or you have to settle for a small video player that is absolutely tiny on anything larger than 1024 resolution width. For instance: here is a video that a friend brought to my attention as viewed on a 1600x900 LCD TV.


That is a lot of white space going to waste, and while the fullscreen mode works I often watch videos on the LCD TV while browsing the web on a projector connected to the same computer and end up switching in and out of fullscreen mode multiple times. I’ve had this same problem before with Channel9 and fixed it using a bookmarklet, but that actually requires clicking a link in my favorites every time I loaded a video, which was less than ideal. Now that Chrome supports userscripts I am working on converting some of the bookmarklets that I have into userscripts, and since I already have a working solution for Channel9 I thought that I would try creating one for next.

So if you ever watch TED videos on a machine with multiple monitors then today is your lucky day.  This userscript will enable multiple monitor fullscreen video for any page that uses the TED.Com flash player. Videos that are embedded from YouTube currently are not supported, but YouTube already lets you increase the width of the player, open it in a pop-out window, or even use the browser’s zoom feature to resize the video so that shouldn’t be a problem. And this time I did do some basic testing in both Firefox and Chrome so hopefully it will work as advertised.


Friday, March 5, 2010

Slashdot Zoom Fix: a Greasemonkey and Chrome compatible userscript

One of my top ten visited websites is probably Http:// who’s headline is “News for nerds, stuff that matters”. The site usually posts over 20 stories a day covering technology, math, physics, and computer related topics, which help me keep informed and entertained. One problem that I often have is that the text size is very hard to read when using a high resolution monitor or when using the projector that I have setup on a media center computer at home. Usually this is easy to solve, since one of the 11 buttons on my mouse is mapped to the CTRL button and can be combined with the scroll wheel to zoom in and out on web pages quickly. However in this case there are boxes on the right hand side of the screen that also enlarge when the page is zoomed, causing the text width to be smaller and more difficult to read. Here is an article on Slashdot normal and zoomed:

Slashdot Normal
Slashdot Zoomed

The site is designed using CSS and for some reason the advertisement and “Interviews” box will get bigger when the page is zoomed, shrinking the width of the textbox significantly. If you are a registered user Slashdot will not display the ad but will still have a side panel on the right that grows larger when you try and zoom in. I initially created a bookmarklet that could be used to remove the side panel by clicking on a link in my favorites to inject some javascript into the webpage to alter the CSS classes, but that still required that I manually click the button every time that I visit he website.

I planned on making a Google Chrome Extension, but recently Chrome announce that they now will automatically convert Greasemonkey scripts into Chrome Extensions. This means you can write a cross-browser compatible script that can run in Firefox, Chrome or any other browser that supports Greasemonkey scripts. It only took a few minutes to convert the bookmarklet into a userscript, and I posted it on so that anyone can use it. The script will automatically remove the sidebar so that zooming works much better. You can even change the script to automatically zoom a specified amount, however I left this off by default since the right amount highly depends on the width of your screen. Here are the results:

Slashdot Fix Zoom User Script  
Slashdot Fix Zoom User Script (zoomed)


Hopefully someone else will find this useful. I have a few other bookmarklets that I use and will probably convert into userscripts soon, as well as a few new ones that I want to work on when I get some free time.

Friday, February 19, 2010

Powershell, 7-Zip, Amazon S3 Upload Script with AES-256 Encryption

I recently was tasked with finding a way to store some backup files from our server in a secure and reliable off-site location. After talking with our hosting provider, who wanted around $600 a month for off-site tape rotation, we decided to look at using Amazon Simple Storage Service (Amazon S3) to store the files in the cloud instead. We needed a way to automate the upload process and make sure that the data was encrypted, so I spent a few days working on a Powershell script (using the excellent PowerGui Script Editor) that uses 7-zip to create a .7z archive with AES-256 encryption and then send it up to Amazon S3 using the Amazon Web Services SDK for .NET. Here is the script:

It seems to work pretty well so far, taking about 5-10 minutes to zip and encrypt 1GB of SQL Backups down to 100MB and then upload it to Amazon S3. From there we can use tools like CloudBerry S3 Explorer to browse or download files when needed. The monthly costs to keep data on Amazon S3 is $0.150 per GB, with $0.10 per GB transfer in and $0.150 per GB transfer out. With a 1 week backup retention and minimal data-out transfers we expect to pay around around $10 to $20 a month and should be able to access it much quicker than if we were using off-site tape storage. Cloud computing FTW!
UPDATE 6/14/2010: I just posted the script used to create the Database backup folder.

Friday, February 12, 2010

Parallel ForEach file processing in IronPython: Get some TPL love in IPY!

I recently have started playing around with the Task Parallel Library (TPL) that will be shipping in .NET 4, which lets you easily spread a workload across multiple cores using a simple Parallel.ForEach statement. I have a few IronPython scripts that I want to convert to start using multiple threads, so I thought I would try using the .NET 3.5 version of the TPL from inside of IronPython. It turns out that the TPL works just fine, but writing thread safe code in IronPython can be tricky. First off, the System.Threading.Interlocked class does not work on IronPython integers because python integers are immutable. That really sucks, because it means that the only way to change a global integer value in a thread safe manner is to use locks or the System.Threading.Monitor class. One interesting workaround is to use a python list instead of an integer. Appending a value to a list is an atomic operation, so instead of calling Interlocked.Add you can just append all the values to an empty list an use sum to return the aggregate value or len() to get the number of items in the list (emulating incrementing a variable). It is a bit of a hack, but sometimes easier that using locks. Also, you have to remember that the print statement is not thread safe, so instead you should use something like System.Text.StringBuilder to buffer your print statements and then print them once you are back to a single thread code section.

Below is a small sample script that I wrote to test processing a large number of text files using IronPython. It will search through all files in a given directory that match a given pattern (ie: *.txt) and return the total number of files and lines. It will also search for a given tolken inside each file and return the total number of matches. This is a task that is very easy to run on multiple cores and is a perfect fit for the Parallel.ForEach method. By default it will search your temporary files folder, which on my workstation had 69 .txt files with a total of 469,286 lines. The single threaded version took about 2.3 seconds to run and the multi-threaded version took between 0.8 and 1.0 seconds. The workload was spread across 8 cores, which caused a 2x improvement in speed, even thought this example is still primarily bound by the drive IO speed. Still it shows how using the TPL can greatly increase performance for common tasks.

Saturday, February 6, 2010

TPL and Parallel.ForEach in .Net 3.5 using Reactive Extensions for .NET (Rx)

The next version of the .Net framework and Visual Studio both have some pretty cool features to help programmers work with multiple cores, which is great but doesn’t help the majority of us that are stuck with .Net 3.5 for the foreseeable future. Luckily Erik Meijer and the Cloud Programability Team have back ported the Parallel Extensions Framework (PFX) to .Net 3.5 and Silverlight 3 as part of the Reactive Extensions for .NET (Rx). Rx adds the IObservable<T> and IObserver<T> interfaces, which are the mathematical duality of the IEnumerable<T> and IEnumerator<T> and provide tools for doing Reactive Programming. There are many different ways to use Rx, but internally they all use the Task Parallel Library (TPL) as the “special sauce” to automate processing tasks across multiple threads.

Parallel.ForEach is a part of the TPL that can be used to unroll an outer loop and have it run across multiple threads. Take the following example. This is standard single threaded code that loops through a collection of 2 card Texas Holdem starting hands and evaluates all possible 7 card hands that include those two cards:

There are over 2 million hands in the inner loop, which gets run once for each of the possible starting hands in the outer loop. There are 12 offsuit starting hands and 4 suited starting hands with an Ace and a King, which means that the outer loop would run 16 times, however those 16 executions are separate and could easily be run across multiple threads. That is where Parallel.ForEach comes in. Here is the same code, which will automatically be scheduled across multiple threads:

The bulk of the code is the same, with the only changes being that the inner block gets converted into a Lambda Expression (could have also used a delegate) and instead of incrementing lCount in the inner loop we increment a local loop variable and then atomically add it to the global value. We could have used System.Threading.Interlocked.Increment to atomically increment lCount inside the inner loop, but this adds a lot of unneeded locks that slow down all the threads. Keeping a local copy of the values and only locking once at the end provides much better performance.

And with those few small changes we are able to start using multiple threads, which on my local machine with 4 cores and 8 threads ended up decreasing the processing time from 1.55 seconds to 0.67 seconds and more than doubling the number of hands processed per second from 16,420,998 to 37,816,595.

If you want to start using the TPL you can download it here and add a reference to the System.Threading.dll located in the “C:\Program Files (x86)\Microsoft Reactive Extensions\Redist\DesktopV2” folder. And while you are at it you might as well play around with Rx too!


Wednesday, January 20, 2010

VS2010 Parallel Computing Features Tour: Wow!

Microsoft Visual Studio 2010 and .NET Framework 4.0 are in beta 2 right now and should be available in a few months, but after watching videos about the features of C# 4.0 and the features of Visual Studio 2010 I don’t know how much longer I can wait! I just finished watching a video about the parallel computing features in VS2010 and I seriously am drooling over the multi-core programming tools available in the next release! C# 4.0 was introduced by Anders Hejlsberg at PDC 2008, but it is great to see it finally coming to fruition. And with .NET 4 splitting the download into Client and Full profiles it now can be downloaded and installed on most machines at about half the size (30-40MB vs 70-160MB for .NET 3.5).

Blog.TheG2.Net - Your guide to life in the Internet age.