Category Archives: Code

Simulating a Server in .Net (C#)

I recently had a need to simulate an FTP server connection in some unit tests. Rather than developing a full test-server, for this purpose, I could easily simulate an FTP stream by creating it in memory, and then passing that stream to the functions  that expect it:

public Stream CreateTestStream(string text) { byte[] buff = Encoding.ASCII.GetBytes(text); return new MemoryStream(buff, false); }

This function merely accepts text (FTP is text-based after all), and returns a memory stream. I can then use it in a unit test:

[Test] [ExpectedException(typeof(FtpException),"InvalidResponse")] public void FtpResponse_Constructor_BadStream_InvalidCode() { using (Stream s = CreateTestStream("NoErrorCode")) { FtpResponse response = new FtpResponse(s); } }

Setting the minimum Windows version supported (C++)

Recently, I was trying to use the Shell function SHGetFolderPath. Despite including the correct header file (shlobj.h), the compiler wasn’t recognizing it. My code looked like this:

CString strPath; HRESULT hResult = SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath.GetBufferSetLength(MAX_PATH)); strPath.ReleaseBuffer();

What I did was lookup the definition of SHGFP_TYPE_CURRENT in shlobj.h, and found this:

#if (NTDDI_VERSION >= NTDDI_WIN2K) SHSTDAPI_(void) SHFlushSFCache(void); typedef enum { SHGFP_TYPE_CURRENT = 0, // current value for user, verify it exists SHGFP_TYPE_DEFAULT = 1, // default value, may not exist } SHGFP_TYPE; SHFOLDERAPI SHGetFolderPathA(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, __out_ecount(MAX_PATH) LPSTR pszPath); SHFOLDERAPI SHGetFolderPathW(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, __out_ecount(MAX_PATH) LPWSTR pszPath); //etc...

It’s that first line that got me. My DDI version wasn’t >= that of Win2k’s. The solution is to modify the stdafx.h file. Before, it read:

#ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif

That 0x0400 defines Windows 95 as the minimum supported OS. I don’t really care about 9x support, so I changed it to read like this:

#ifndef _WIN32_WINNT //define Windows 2000 as minimum necessary OS #define _WIN32_WINNT 0x0500 #endif

Importance of disposing MailMessage objects

Always, always, always follow the suggested usage patterns of disposable objects. I had a strange problem recently where e-mail messages with attachments weren’t releasing the lock on the files for a long time. I was using the System.Net.Mail namespace, specifically the Attachment and MailMessage classes.

Disposable objects represent resources not directly under control by the CLR–and this includes SMTP connections. By not calling dispose, the mail message was just sitting around, not getting sent. Why this is the case when I explicitly call SmtpClient.Send is unclear. The main symptom of this problem was that files that I attached to the e-mail message were still locked when I tried to delete them immediately after the send.

Something like this will do:

using (MailMessage msg = new MailMessage()) 
{ 
    msg.Attachments.Add(...); 
    client.Send(msg); 
}

Changes in .Net 1.1. and 2.0 E-Mail classes

I recently (re?)learned a harsh lesson at work. We migrated a critical application’s e-mail client code to use System.Net.Mail‘s classes instead of those in the deprecated System.Web.Mail.

After doing this, we immediately had three problems, mostly with the Attachment class:

  1. Our automated test software could no longer read the attachments
  2. Attachments started having names of Directory_Directory_FileName (they were just Filename)
  3. The software could no longer delete the attachment files from disk after they were e-mailed (the file was still in use).

With problem 1, it turned out that the default encoding in the old MailAttachment class was 7Bit and the test program (which I didn’t write) was directly scraping the mail queue (on a Linux system) and reading the encoded text, looking for recognizable tokens. The new class’s default encoding was Base64–gibberish, to this test program. It wouldn’t really matter to our end-users, but the taking the “easy” way out in writing the test program locked us into an encoding. It just so happens, though, that 7Bit encoding is preferable in our circumstances, even for end-users (Base64 adds significant e-mail overhead–some of our users pay by kilobyte).

The 2nd problem took me a little longer to figure out. At first I thought it was a bug in the attachment naming code, but I couldn’t find anything either in code or the file system. It turns out that the name of the file that the Attachment class is giving includes the directory structure in the name–this seems quite odd–I mean, how often do you want a file name like that? So I manually set the ContentDisposition.FileName property to be just the filename.

I still haven’t completely figured out #3. I think it’s because the MailMessage class is locking the file during send, and not releasing it as early as the old class. In any case, I haven’t directly solved the problem, just come up with a semi-elegant workaround.

Lessons:

  1. Don’t assume default settings are the same across framework upgrades.
  2. Build unit tests to test the assumed stuff–even the stuff controlled by the framework. Don’t assume it’s doing exactly what you want with default settings.
  3. Most importabtly, if your functionality depends on specific settings, then explicitly specify them–don’t ever leave them to chance.

Thankfully, these were relatively easy to diagnose and caused minimal to moderate impact.

Why you shouldn’t catch System.Exception

There are probably many reasons, but my favorite is that, if you are resorting to catching anything at all, you probably don’t understand the code well.

For example, in complicated parsing of text, it is often easier to just put a huge try {…} catch (Exception ex) {…} around the entire thing, rather than take the time necessary to understand how your code works, and where exactly things could go wrong.

It is much better to go through the code line-by-line and prove to yourself that that there are only a few places of possible unknown exception behavior. Obviously, exceptions are meant to catch things you can’t reliably predict, but in most code, there are large areas of things like string manipulation, arithmetic, or other simple procedures, that will not throw an exception. It makes sense to delineate these areas, and surround only the trouble spots with try-catch.

For example, look at this fragment:

string strDelimiters = ":, ;"; 
try 
{ 
    string[] tempStrings = message.Split(strDelimiters.ToCharArray()); 
    string[] subStrings = new string[tempStrings.Length]; 
    int numSubStrings = 0; 
    //remove empty substrings 
    for (int i=0;i<tempStrings.Length;i++) 
    { 
        if (tempStrings[i] != null && tempStrings[i].Length > 0) 
        { 
            subStrings[numSubStrings] = tempStrings[i]; 
            numSubStrings++; 
        } 
    } 
...

 There is no reason to surround this with a try {} catch{} block. Doing so lets you off the hook of digging into this and realizing how bad it is, especially with .Net 2.0. 🙂

Visual Studio 2003 and 2005 Default Keyboard Shortcuts Cheat Sheet

My first book, C# 4.0 How-To is now shipping! If you like tips you can use, check it out!

I wanted to have a quick-reference sheet available to help me learn the Visual Studio keyboard commands. Surprisingly, I couldn’t find a handy printable reference. So I made one. It doesn’t contain ALL the shortcuts. For that, you can go to the online reference or this code that prints out all of your existing shortcuts.

If you just want a two-page reference sheet, handy to print front-to-back, to help you learn the shortcuts, download the PDF I created.

A screen shot of it…

Visual Studio 2003 & 2005 Default Keyboard Shortcuts Screenshot

Queue multiple GUI updates into a single update event (C# .Net)

I’m writing a simple utility that involves scanning a hard disk and updating a display with the latest status. There are potentially many, many, many, many, MANY changes that happen to the display in very quick succession and sending an update event which triggers a screen refresh for every single state change would be an enormous bottleneck.

I implemented a simple queueing scenario where all the updated objects are queued for up to 200ms before being batched into a single event. The GUI can then update the display for every changed object all at once.

First, the queue:

private DateTime lastUpdateSent = DateTime.MinValue; //queue updated folders to limit the number of screen updates List<FolderObject> updatedFoldersQueue = new List<FolderObject>();

A simple list. Then I have a function which is called to handle the actual event generation:

private void FireUpdate(FolderObject folder) { if (this.OnFolderUpdated!=null) { try { if (!folder.Dirty) { folder.Dirty = true; updatedFoldersQueue.Add(folder); } TimeSpan diff = DateTime.Now - lastUpdateSent; if (diff.TotalMilliseconds > 200){ FolderUpdatedEventArgs args = new FolderUpdatedEventArgs(updatedFoldersQueue); int numFolders = updatedFoldersQueue.Count; //reinitialize queue updatedFoldersQueue = new List<FolderObject>(numFolders); OnFolderUpdated(this, args); Thread.Sleep(0); lastUpdateSent = DateTime.Now; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); } } }

The folder.Dirty flag merely prevents a folder from being queued twice. The TimeSpan diff is the important bit. By checking the time difference between now and the last updated time, we can ensure that updates only get sent as often as the display–and our eyes–can handle them. The Thread.Sleep(0) ensures that the GUI thread gets a chance to draw–this is supposed to be interactive, after all.

Don’t use CArchive with native C++ type bool

I recently ran into an issue where I was trying to serialize a bool variable from a CArchive object.

Archiving it out, with this code, works fine:

//CArchive ar;
bool bFill;
ar << bFill;

But this code:

ar >> bFill

has problems. It compiles fine under Visual Studio 2003, but errors out under Visual C++ 6 with this error:

C2679: binary ‘>>’
: no operator defined which takes a right-hand operand of type ‘bool’
(or there is no acceptable conversion)

Very weird. There is some explanation here.

My resolution? Use BOOL instead. Sure, it’s actually an int and takes 4 bytes, not 1, but that’s a not a big deal in this case. And it’s more clear than using BYTE.

Simple Command Mapping Infrastructure in .Net

Unlike MFC, .Net does not offer a built-in framework for message handling in WinForm applications. MFC developers, for better or worse, have a rather large mechanism that automatically maps command messages from menus, toolbars, and windows into the classes that want them.

.Net has no such all-encompassing framework, though some 3rd-party frameworks exist (perhaps I’ll go over some in a a future entry).

The lack of a built-in application framework gives developers more freedom by not locking them into a certain mind set, but it also means that you have to develop your own framework or do everything from scratch in every application.

Short of developing an entire framework, there are some practices you can follow in .Net (and any GUI application, for that matter) to ease management of commands.

I’ll talk about one possibility that I recently chose to implement in a small WinForms application. First of all, let’s look at the overall architecture I’m aiming for:

It’s roughly a Model-View-Controller (MVC) architecture. What I want to do is almost completely isolate the GUI layer from knowledge of how the program actually works. The breakdown of responsibility is as follows:

  1. GUI – contains menus, status bar, views, panels, toolbars, etc. and routes messages from them to the controller via command objects.
  2. Controller – coordinates views, reports, and GUI.
  3. ReportGenerator – the “model” in this architecture. Generates and stores the actual data that will be presented.
  4. Views – Does the drawing for the report in different ways.

With this architecture, the GUI is restricted to doing only a few things, all of them related to the state of the GUI:

  1. Receiving events from toolbar buttons, etc.
  2. Setting menu/button states based on general program state (i.e., report running, idle)
  3. Changing the current view based on a request from controller.
Command Objects

A popular way to handle commands from toolbars and menus is to use the Command design pattern. The advantages to this pattern are numerous, but as far as isolating the GUI from implementation details, they allow us to put all the work required to get things done into command objects and the controller.

Here’s a sample design for commands. As you can see, it’s exceedingly simple.

An interface defines the basic functionality: Execute(). The concrete base classes are created with parameters that tell it the information it needs to know. When the user selects a command in the GUI, the GUI must then run the associated command.

For example, here’s a command that merely changes the current view:

class ChangeViewCommand : ICommand
{
private ViewType viewType;

public ChangeViewCommand(ViewType view)
{
this.viewType = view;
}

#region ICommand Members

public void Execute()
{
DiskViewController.Controller.SetCurrentView(viewType);
}

#endregion
}

When the command is created, it is initialized with the view type. When it’s executed, it merely calls the controller to do the work. The amount of work that is done in the controller versus command objects really depends on the application and individual commands. In this specific case, it might not seem like it’s doing a lot, but it would be easy to add Undo support, logging, coordination among multiple classes, or any other requirement for a command. In addition, the benefit of using command objects even in simple cases like this will become clear shortly.

Associating GUI objects with Command objects

Many applications use menus as well as toolbars with duplicate functionality. There are also keyboard shortcuts that can invoke the same command. An easy way in .Net to associate the GUI with command objects is to use a hash table. The keys consist of the menu and toolbar objects, and the values are the command objects.

//declaration:
private Dictionary<object, ICommand> commandMap = new Dictionary<object, ICommand>();

//toolbar
commandMap[toolStripButtonPie] = new ChangeViewCommand(ViewType.Pie);
commandMap[toolStripButton3DPie] = new ChangeViewCommand(ViewType.Pie3D);
commandMap[toolStripButtonStart] = new StartCommand(controller);
commandMap[toolStripButtonStop] = new StopCommand(controller);

//menu
commandMap[pieToolStripMenuItem] = commandMap[toolStripButtonPie];
commandMap[Pie3DToolStripMenuItem] = commandMap[toolStripButton3DPie];
commandMap[startAnalysisDriveToolStripMenuItem] = commandMap[toolStripButtonStart];
commandMap[stopAnalysisToolStripMenuItem] = commandMap[toolStripButtonStop];

 You can see that some commands take the controller as argument–an option to discovering it from a static class variable. Also notice that commands from menu objects can reuse the same object that is associated with the toolbar button.

In order to run the commands, the GUI needs only respond to OnClick events from menus and toolbars and in many cases, the same delegate can be assigned to many of the menu items:

private void OnCommand(object sender, EventArgs e)
{
    if (commandMap.ContainsKey(sender))
    {
        ICommand cmd = commandMap[sender];
        if (cmd != null)
        {
              cmd.Execute();
              //could also do controller.RunCommand(cmd);
        }
    }
    else
    {
        throw new NotImplementedException();
    }
}

In conclusion, using the techniques presented here you can easily split your program into manageable chunks, with each layer doing only what it needs to.