Archive for December 2008

New Year

Everybody is posting reflections this time of the year. I guess I’m no exception, I started blogging this year, pretty late in the game. That is everybody have blogs now a days, I have to admit I was resisting it. I have actually been doing my sons blog for 9 years now and waiting for him to take it over. I have noticed how I tend to post code a lot of the time when I’m coding. Maybe helps somebody out at least it’s a good snippet repository for myself.

The last day of the year is a bit special for me, back home we would go to these huge bonfires. Not to forget at midnight in Iceland the sky lights up with fireworks. Everybody and I mean everybody shoots up fireworks, it’s perfectly legal. Here is a picture from tonight

C# file download from URL

It used to take some code to download a file from a URL over http connection. Today it’s fairly easy only couple of lines of code just using the .net libs. As you can see below.

using System.Net;
// Downloads a file from URL, saves locally
public static void getFileFromUrl( string psUrl, string psFileName )
{
    try
    {
        WebClient Client = new WebClient();
        Client.DownloadFile(psUrl, psFileName);
    }
    catch (Exception ex)
    {
        Console.WriteLine( “Err=” + ex );
    }
}

C# http authenticate

Sometimes URL requests are authenticated by the server your running against. For example if you want to update your Twitter status. Let’s take a look how we can do that easy.

using System.Net;
try
{
    string sURL = “http://twitter.com/statuses/update.xml?status=” + sText;
    // Create the web request
    HttpWebRequest request = WebRequest.Create(sURL) as HttpWebRequest;

    // Add authentication to request
    request.Credentials = new NetworkCredential(“myaccount”, “mypassword”);
    request.PreAuthenticate = true;
    request.Method = “POST”;

    // Get response
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            // Console application output
            StringBuilder body = new StringBuilder(reader.ReadToEnd());
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

C# Embed wave file

Here is a simple way to embed wav file or any other resource in a C# application. Just add the file and set it’s property “Build Action” to “Embedded Resource”. Then at run time extract the resource and use it in your application.

// this will show you all available resource
//string[] resNames = a.GetManifestResourceNames();

// extract the wav file
Stream mstrWaveFile = Assembly.GetExecutingAssembly().GetManifestResourceStream(WAVE_RESOURCE);
SoundPlayer player = new SoundPlayer(mstrWaveFile);
// and play it
player.Play();

Ignite Boulder 2

I didn’t make it too the first Ignite Boulder, but made sure I could make it out last night. Although running late as I had to chainsaw down a 11+ foot xMas tree before leaving. On top of that I had no idea where the Atlas building is located on the CU campus. You guessed it google maps to the rescue, ate dinner while driving there and made it just in time.

As expected the night was a lot of fun, Andrew Hyde keeps it lively and fun. Not to forget about Jeremy Tanner aka Penguin, he even threw a shoe at one of the speakers !

The house was packed probably around 200 + 2 dogs, yes that’s allowed in Boulder. Jam packed and everybody in good humor. I didn’t even get a seat, did I mention I was late ? Ignite gave $579 if I saw it correctly to a local charity from contributions, good job. 14 presenters anything from what happens when it snows in Washington DC to social and so on.

Watch the IgniteBoulder website for the videos, they should be posted in the next couple of days.

Image from URL in C#

Here is how you can retrieve a image from a webserver. You only need to know the specific URL, the function does the rest and returns Image object.

// Get image from the given Url
// returns the image or null if not found
public static Image getUrlImage(string psUrl)
{
    WebResponse result = null;
    Image rImage = null;
   
    try
    {
        WebRequest request = WebRequest.Create(psUrl);
        byte[] rBytes;

        // Get the content
        result = request.GetResponse();
        Stream rStream = result.GetResponseStream();

        // Bytes from address
        using( BinaryReader br = new BinaryReader(rStream))
        {
            // Ask for bytes bigger than the actual stream
            rBytes = br.ReadBytes(1000000);
            br.Close();
        }
        // close down the web response object
        result.Close();

        // Bytes into image
        using( MemoryStream imageStream = new MemoryStream(rBytes, 0, rBytes.Length))
        {
            imageStream.Write(rBytes, 0, rBytes.Length);
            rImage = Image.FromStream(imageStream, true);
            imageStream.Close();
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine( “error=” + ex );
    }
    finally
    {
        if (result != null) result.Close();
    }

    return rImage;
}