C# Code Snippet: Download a File Over HTTP

This code snippet was adapted from one of Jim Wilson’s excellent “How Do I?” tutorials. It works with .NET Framework 2.0 (including the .NET Compact Framework CF 2.0 SP2), and I’ve successfully tested it on a Windows CE 4.2 device. You will probably want to add a bit more error handling:

/// 
/// Download a file from a URL to a local folder on a windows mobile device
/// Note: Don't forget that mobile folders do not start with a drive letter.
/// 
/// e.g. http://www.someaddress/downloads/
/// e.g. filetodownload.exe
/// e.g. \temp\
/// 
public static long FromHttp(string uri, string filename, string localFolder)
{
    long totalBytesRead = 0;
    const int blockSize = 4096;
    Byte[] buffer = new Byte[blockSize];
 
    if (!Directory.Exists(localFolder))
    {
        Directory.CreateDirectory(localFolder);   
    }
 
    try
    {
        HttpWebRequest httpRequest = 
  (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));
        httpRequest.Method = "GET";
        // if the URI doesn't exist, an exception will be thrown here...
        using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                using (FileStream localFileStream = 
   new FileStream(Path.Combine(localFolder, filename), FileMode.Create))
                {
                    int bytesRead;
                    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytesRead += bytesRead;
                        localFileStream.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        // You might want to handle some specific errors : Just pass on up for now...
        throw;
    }
 
    return totalBytesRead;
}
 
Comments welcome.

A Few Useful Links for .NET Compact Framework Targeted Mobile Development

OpenNETCF have a free community edition of their extension library:
http://www.opennetcf.com/Home/tabid/36/Default.aspx
(among other things, contains a useful FileSystemWatcher which is missing from CF 2.0 SP2)

This Microsoft site has a few great tip and tricks:
http://msdn2.microsoft.com/en-us/netframework/bb495180.aspx

.NET Compact Framework Team
http://blogs.msdn.com/netcfteam/

Chris Tacke’s SDF Samples
http://blog.opennetcf.org/ctacke/CategoryView,category,SDF%20Samples.aspx

Neil Cowburn’s blog:
http://blog.opennetcf.com/ncowburn/

Jim Wilson’s Blog
http://www.pluralsight.com/blogs/jimw/

Peter Foot’s Blog:
http://www.peterfoot.net/CategoryView,category,NETCF.aspx

Mike Hall’s Blog:
http://blogs.msdn.com/mikehall/

Also, Issue 14 of the Architecture Journal has a mobile device focus:
http://www.msarchitecturejournal.com/pdf/Journal14.pdf

Make: The Best of: 75 projects from the pages of MAKE

Move over MacGyver! The Geeks are coming! Here are 75 of the best projects from the first 10 volumes of O’Reilly’s DIY MAKE magazine. In The Best of MAKE (380 pages) , editors Mark Frauenfelder and Gareth Branwyn have selected a varied assortment of projects and tips that are not only fun to work on, but also have practical applications. Even if you are not a dab hand with electronics and a soldering iron you will almost certainly find something of interest. In fact, you do not actually need to build any of these projects to enjoy this book.

The range of projects is quite varied in terms of complexity, split across the following chapters:
  1. Tools
  2. Electronics
  3. Microcontrollers
  4. Toys & Games
  5. Robots
  6. Music
  7. Flight & Projectiles
  8. Photography & Video
  9. Cars & Engines
Starting with a description of the tools that are handy to have available, Chapter 1 prepares the groundwork for what you will need to get started on these DIY projects. The following 8 chapters are a roller coaster ride through the pages of Make.
If I had to pick a top 5 projects, my favourites would have to be the Jam Jar Jet, Urban Camouflage, Pinball Resurrected , VCR Cat Feeder and the robot mouse.
I liked this book so much that I bought my brother a copy for xmas! It has even re-ignited my interest in a bit of electronics tinkering. Highly recommended. One thing to note; the Amazon cover photo shows “150 Projects” but it is actually 75.

[BTW, If you like this book, you should also check out Making Things Talk which has a distinctly embedded electronics flavor, and goes deeper into the topic of microcontrollers and programming.]

Disclosure: The Perth .NET User Group is a member of the O’Reilly User Group and Professional Association Program. O’Reilly make copies of their books available for user group libraries, and the copy reviewed here was kindly donated by O’Reilly.

Developing for the Symbol MC1000 with CF 2.0 SP2

My foray into mobile development, after a hiatus of several years, got off to a very slow start with the Symbol MC1000! The previous project had targeted a Telxon device which is now discontinued and if I recall correctly had a 1MHz(!) processor, just 1MB of non-volatile RAM for both code and data, ran a cut down version of DOS, had absolutely no integrated debugging experience and was entirely developed in C with only minimal library support. It was an enjoyable, if not protracted, challenge building a disconnected warehouse inventory application for that device, which required good performance and usability.

The Symbol MC1000 is a much more modern affair, with an Intel XScale 312 MHz processor, running Windows CE 4.2, 32MB of RAM and 32MB of flash ROM.

After a few Google searches I discovered that I would be able to target the Compact Framework 2.0 SP2 and use C# in Visual studio 2005 (SP1) to develop and debug the new application. Joy!

I’m almost embarrassed (*blush*) to admit that it took me a while to get the right version of the Compact Framework installed! I got it into my head that an “Intel XScale processor” meant I needed the x86 version of the Compact Framework. It doesn’t! It needs the ARM version. The Symbol web site could certainly benefit from better usability and content. Thank goodness for forums and the people who give up their time to answer questions on them. It seems everyone I have mentioned this to after the fact thought it was obvious, so it must be common knowledge in this sphere.

So what about the debugging experience? It is great! Just install Microsoft’s ActiveSync 4.5 and the other downloads listed below and you will be off to a flying start.

I’m currently running Compact Framework 2.0 SP2 in RAM: I haven’t quite figured out the Platform Builder route to installing it into ROM, and the Symbol site is pretty quiet on the whole matter. Small steps…

Helpful links:
Mark Prentice blog has this very useful post:
Developing .NET Compact Framework applications for Windows CE 4.2 Devices

Downloads:
.NET Compact Framework 2.0 Service Pack 2 Redistributable
ActiveSync 4.5
Symbol Mobility Developer Kit v1.6 for .NET
Windows Mobile 5.0 SDK for Pocket PC

Perth .NET User Group meeting: ASP.NET MVC with Michael Minutillo

Join us at the Perth .NET Community of Practice, February 7th to hear Michael Minutillo present on Microsoft’s ASP.NET MVC framework. In this session, Michael will give an introduction to this new Microsoft technology. ASP.NET MVC is a presentation framework being developed by Microsoft to provide an alternative to Web Forms for web-application development. Leveraging the well-known Model View Controller design pattern it enables developers to create robust, maintainable web sites.

TOPIC: ASP.NET MVC with Michael Minutillo
DATE: 7th February, 5:30pm
VENUE: Excom, Level 2, 23 Barrack Street, Perth
COST: Free. All Welcome.

MVC is a framework methodology that separates an application’s implementation into three component roles: models, views, and controllers. One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

I will be giving away a few goodies: a Resharper license, a copy of the book “The ASP.NET Anthology” and a few T-shirts. If you want a seat, try to arrive early!

Perth SQL Server User Group meeting with Rob Farley

Next week is shaping up to be a good one, with 2 user group talks happening (see my previous post for details of Scott Hollier’s talk). Both events should not be missed!

Rob Farley (MVP) is in Perth and he has kindly agreed to give a presentation at the SQL Server User Group, Tuesday 4th Dec, 5:30pm.

TOPIC: New SQL Server 2008 features and TSQL language features
DATE: Tuesday Dec 4th, 5:30pm
VENUE: Excom, Level 2, 23 Barrack Street, Perth
COST: Free. All Welcome.

Rob Farley, a mentor/trainer with Solid Quality Learning Pty Ltd, has been consulting in IT since completing a Computer Science degree with first class honours in 1997. He currently lives in Adelaide, but has also worked in consultancies in Melbourne and London. He heads up the Adelaide SQL Server User Group, sits on the South Australian Branch Executive Committee of the Australian Computer Society and holds several Microsoft certifications including MCSD, MCDBA, MCTS, MCPD and MCITP. He is a Microsoft Certified Trainer and is a recipient of the Microsoft MVP Award for SQL Server

Perth .NET User Group meeting: The Disability Divide with Dr Scott Hollier

Join us at the Perth .NET Users Group, December 6th, to hear Dr Scott Hollier present on the Disability Divide. People with disabilities, and in particular people who are blind or vision impaired, are not embracing computing and Internet-related technologies at the same rate as the able-bodied population. This presentation will explain the reasons behind the disability divide and how software developers can significantly improve the independence of people with disabilities.

TOPIC: Accessibilty and the Disability Divide with Dr Scott Hollier
DATE: Dec 6th, 5:30pm
VENUE: Excom, Level 2, 23 Barrack Street, Perth
COST: Free. All Welcome.

Scott, a published author in the field, has recently completed a PhD titled ‘The Disability Divide: an examination into the needs of computing and Internet-related technologies by people who are blind or vision impaired’. He has an undergraduate Computer Science degree and six years experience in the Information Technology industry. Scott, who is legally blind, is a Researcher for Employment and Equity, at the Association for the Blind of WA.

Whoops! Almost forgot. On Tuesday, December 4th 5:30pm (same venue), Rob Farley will be talking about some of the new SQL Server 2008 features and a few of his favourite (and useful) TSQL language features.

Visual Studio 2008 Training Kit

You’ve probably already seen this by now – Microsoft have made the Visual Studio 2008 Training Kit available as a download (it was previously offered to ISVs only). It contains 20 hands-on labs, 28 presentations, and 20 scripted demos. The technologies covered in the kit include: LINQ, C# 3.0, VB 9, WCF, WF, WPF, Windows CardSpace, Silverlight, ASP.NET Ajax, .NET Compact Framework 3.5, VSTO 3.0, Visual Studio Team System, and Team Foundation Server.

Kindle: If Only Santa Knew About These!

Earlier in the year I joked with Cheryl Martinez, who coordinates Apress’s user group affilliation program, about the possibility of someone finding a decent electronic solution to hard copy books. Well, it seems Amazon may well have done just that with the release of the Kindle. According to the blurb, Kindle is a “portable reading device with the ability to wirelessly download books, blogs, magazines, and newspapers”. It’s not the first device to try and capture this huge market; Sony has had one out for some time which retails for around US100 less than the Kindle.It apparently sold out in the first 5.5 hours, but is it just hype or has someone finally found the design sweetspot like the Apple iPod did?Whilst I haven't got my grubby paws on one, it seems it might succeed where others have failed due to the fact that it works more like a portable media reader, with the ability to wirelessly download content such as blogs, newspapers over the 3G network, in addition to storing and displaying electronic books.After reading through only a portion of the huge number of of highly polarised comments (a good thing according to <a href="http://headrush.typepad.com/">Kathy Sierra</a>) over at Amazon, it seems the negative points are:1) Books are DRM'ed and in a third party propietry format.2) Price: US400.
3) Network coverage (I suspect here in backwater Perth, this might be a big issue).
4) Black and White screen: seems a strange design choice.
5) Book availability: obviously this would hopefully grow quickly as the product matures?

The killer for me is the DRM issue. If I buy a paper book, I expect to be able to read it anytime between now and either it or me crumbles into dust!. I do not want to pay for something that will become unreadable at some point in time (although with technology books becoming out of date very quickly this is not an issue for what would be its main use for me).

Wonder if they have thought of including an automatic speech translator, turning print into audio books?