RSS Feed

Practical Programming: Hidden Talents

Posted on Tuesday, May 12, 2009 in Practical Programming

by Peter Jones

This edition of Practical Programming covers a set of three useful classes / namespaces from the .NET Framework that you probably aren’t familiar with (yet).

Let’s make some noise: System.Media

Producing sound from a computer is something you may have learned in Programmer Playschool and promptly forgot (like me), but it is a useful little feature to add to all types of software, not just desktop games. Playing a system sound or other sound files is very useful in monitoring environments where the users are not seated in front of a computer 24×7 (for example, in server rooms or manufacturing environments).

System.Media is a namespace that contains three useful classes for playing system sounds and .wav files. System sounds are defined in the Sounds applet of the Windows Control Panel.

What MSDN says:

The System.Media namespace contains classes for playing sound files and accessing sounds provided by the system.

The following classes are included in this namespace:

  • A SoundPlayer class for loading and playing sounds in various file formats.
  • A SystemSound class for representing and playing a system sound.
  • A SystemSounds class that retrieves sounds associated with a set of Windows operating system sound-event types.

Playing a System sound couldn’t be easier:

SystemSounds.Asterisk.Play();

This will play the .wav file associated with the asterisk system sound. SystemSounds is a simple wrapper for the five most common sounds – asterisk, beep, question, exclamation and hand.

If you have your own attention-grabbing, eardrum-busting sound file then you can play this just as easily:

string filename = "houston-we-have-a-problem.wav";
SoundPlayer sp = new SoundPlayer(filename);

Loading of large .wav file can take a while so, thoughtfully, Microsoft added support for loading a sound file asynchronously.

static SoundPlayer _player;

static void Main(string[] args)
{
  string filename = "houston-we-have-a-problem.wav";
  _player = new SoundPlayer();
  _player.LoadCompleted += 
          new AsyncCompletedEventHandler(sp_LoadCompleted);
  _player.SoundLocation = filename;
  _player.LoadAsync();
  Console.ReadLine();
}

static void sp_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
  if (e.Error == null)
  {
    _player.Play();
  }
  else
  {
    Console.WriteLine("Could not load sound: " + e.Error.Message);
  }
}

This simple C# console application will play the sound file after it is loaded. Not only will the loading of the sound occur asynchronously, but the player will also play the .wav file in a new thread.

Additionally, the player can load a wave file from various sources such as a URL, application resources, or a stream.

Brain the size of a planet? MemoryFailPoint

In these multi-gigabyte days it’s not often that an application runs out of memory – virtual or otherwise – but there are few things more frustrating to a user than an ‘Insufficient Memory’ exception. Applications that don’t handle these exceptions can potentially corrupt system data (and possibly damage your career!).

Thankfully, there is a simple solution: MemoryFailPoint.

What MSDN says:

Check for sufficient memory resources prior to execution.

MemoryFailPoint throws an InsufficientMemoryException prior to your operation beginning, rather than an OutOfMemoryException at some unpredictable point during the operation. Here’s the actual program that is used to launch the Space Shuttle Microsoft (j/k).

const int MB_MEMORY_REQUIRED = 2048; // 2 gig

try
{
  securePayload();
  alertMedia();
  loadCrew();
  int countDown = 10
  beginCountdown();
  while (countDown > 0)
  {
    Console.WriteLine(countDown);
    if (countDown == 3)
      ignition();
    Thread.Sleep(1000);
    countDown–;
  }

  Console.ForegroundColor = ConsoleColor.Yellow;
  Console.WriteLine("B L A S T O F F ! ! !");
}
catch (OutOfMemoryException mex)
{
  Console.WriteLine("Not enough free memory to lauch shuttle.");
  Console.WriteLine("Please try again later.");
}

Hopefully, the real NASA application is a little more complicated than this, but you could imagine a situation where running out of available memory just after ignition could be somewhat problematic. It’s better to know before you begin that your countdown is likely to fail. Adding a MemoryFailPoint around the critical code will help with this:

try
{
  using (MemoryFailPoint mfp = new MemoryFailPoint(MB_MEMORY_REQUIRED))
  {
    …
  }
}
catch (InsufficientMemoryException mex)
{
  Console.WriteLine("Not enough free memory to lauch shuttle.");
  Console.WriteLine("Please try again later.");
}

When using MemoryFailPoint for more realistic purposes, you can make intelligent decisions about the execution path. For example, fast sorting algorithms can use more memory than slower but less resource hungry versions.

Secret Squirrel - System.Security.SecureString

What MSDN says:

Represents text that should be kept confidential. The text is encrypted for privacy when being used, and deleted from computer memory when no longer needed.

This sounds like something useful to do, and indeed it is! To use a SecureString you need to append characters to it like so:

string password = "Password";

using (SecureString sPassword = new SecureString())
{
  foreach (char ch in password) sPassword.AppendChar(ch);
  // do something with the secure string
}

Clearly, this would be a tad pointless! The unsecure password is right there in clear text for all to see (and discover). To understand this, you need to understand show strings in the .NET Framework work.

Strings are immutable. That is, once you create a string in memory, it can’t change – it can only be replaced. For example:

string somestring = "fred";
// do something
somestring = "bob";

Looking at this you might think that there is some chunk of memory somewhere that starts off as "fred" and later becomes "bob". This is not the case. In actuality, both "fred" and "bob" will be in memory somewhere within the process space of the application. Every time you change a string, a new copy of the string is made and the old one is left for later cleanup by the garbage collector. A sniffer type application on a compromised machine could read through your unprotected memory quite easily.

So, when should you use SecureString? There are a few places in the framework that require a SecureString but the best time to use this is anywhere in your application that you prompt for something you don’t want to risk exposing to unauthorized users or processes.

SecureString should be used in conjunction with other secure mechanisms such as an encrypted configuration file or database record, SSL/TLS for web applications to network transport, etc.

References:

B# .NET Blog -

.NET Security Blog - http://blogs.msdn.com/shawnfa/archive/2004/05/27/143254.aspx

—–

Peter Jones is a 25 year veteran (vintage?) programmer and Microsoft MVP (ASP.NET) from New Zealand. He currently works for Intergen - a leading Microsoft Gold Partner. Peter has worked on and created systems for many industries such as Telecommunications, Manufacturing, Government, Education and more. He cut his programming teeth on dBase 3, Clipper 5 and C before moving to Windows development tools such as Visual Basic, Delphi and .NET. Currently he is working with content management systems (SharePoint and EPiServer) in Sydney, Australia. You can contact Peter and read his occasionally updated blog at http://jonesie.net.nz.

Bring on the comments

  1. Richard says:

    “Strings are imputable” [1] (accusable; culpable; chargeable with fault)

    No, strings are “immutable”. [2] (unable to be changed without exception)

    [1] http://en.wiktionary.org/wiki/imputable
    [2] http://en.wiktionary.org/wiki/immutable

`