Category Archives: Code

.Net Deprecation

A useful attribute in .Net is Obselete. When you mark a method with this the compiler will flag any line that accesses the method (or property, or whatever) with a warning (error is optional).

I recently used it for a framework that sits between a database and applications–I wanted to faithfully reflect the database design (since it’s too dangerous to change that), but I want to be warned away from using cetain functionality unless necessary.

Example:

[Obsolete(“You shouldn’t be calling this method!”)]
public void MyMethod()
{

}

Main()
{
    this.MyMethod();
}

The compiler will then say:

warning CS0618: [class…].MyMethod’ is obsolete: ‘You shouldn’t be calling this method!’

Benefits of using “as” in C#

The “as” keyword is very useful in managed code because it solves a very common problem.

Suppose you have this:

object o;


string s = (string)o;

but what if o is null? Then you will get a NullReferenceException. Sometimes this is ok, but often if o is null, you want s to be null as well.

Enter ‘as’. as is like a typecast that will return null if needed.

Your code would then be:

string s = o as string;

This is why you can’t use ‘as’ with value types (int, bool, structs, etc.)–they can’t take on the value of null in the first place. With .Net 2.0, however, the rules change…

Detecting database connection

I have a service that’s absolutely critical to business functions that relies on both Exchange and SQL Server. The problem is that the service’s existing code has a number of places where a failure to connect to the database will result in a dummy, “bad” value being returned from the data access layer. The business layer doesn’t know if the bad values came from bad input data or no database connection, and it assumes the former. This leads to data loss for the customer.

I see three possible solutions for this:

  1. Have an exception for when the database is inaccessible. This is complicated because it changes the code flow, which would not be easy. Every place it tries to access the database would have to handle the exception. I would also have to develop a mechanism to reprocess the data later.
  2. Have a known “bad” value that means database couldn’t be accessed. This is tricky (if not impossible) and would significantly decrease the readability of the code.
  3. Detect whether the database is alive or not before attempting any processing. This avoids the problem of reattempting processing at a later time. It allows more of the code to stay as is (thus fewer chances of new bugs).

I went with 3 because it is also conceptually closer to what should happen. If the database is unavailable, the service can’t possibly do any meaningful work so it should just stop until the database comes back up.

The code to detect a database disconnect is very simple:

static bool IsDatabaseAlive()
{
    SqlConnection connection = null;
    try
    {
        
string strConnection = ConfigurationSettings.AppSettings[“ConnectionString”];
        
using(connection = new SqlConnection(strConnection))
         {
             
connection.Open();
             
return (connection.State != ConnectionState.Open);
          }
     }
    
catch
    
{
         
return false;
     }
}

 

I run this code before running through the processing loops. If the database is alive I go ahead and process.  

Macros are evil

I’m innocently developing a device context class for my LFC framework and I want a method called SelectPen. All of a sudden I’m getting very weird linker errors about how SelectPen is not defined.

It turns out that SelectPen is a macro defined in windowsx.h as an alias for SelectObject.

#define SelectPen(hdc, hpen) ((HPEN)SelectObject((hdc), (HGDIOBJ)(HPEN)(hpen))) Very annoying.Very annoying.Very annoying.

Simple Customization of a Collection Class

I needed a simple array of strings today, and I needed to be able to return it via a property. I could use a simple array, but that has some significant drawbacks. I could use an ArrayList, but the indexer returns an object, which would force the application to always cast it. I decided to derive a class from ArrayList and change the indexer. Something like this would work:

public class EmailList : System.Collections.ArrayList
{
public void Add(string email) { base.Add(email); }
public new string this[int index] {
    get { return (string)base[index]; }
    set { base[index] = value; }
  }
}

Notice the “new” keyword for the indexer. This tells the compiler to override the indexer provided by the base class. Now, whatever classes use this class can get a string back from the array list without having to cast it every time. There are other things you can do to customize this collection, but it’s a good start.

Creating an Object-Oriented Framework from an existing API

One of my personal goals this year is to go through Petzold’s book on Programming Windows. During that 1500+ page journey I’m creating a framework class library for my personal use while developing Windows applications. This way I can simultaneously learn the intricacies of Win32 while at the same time developing a framework library that is different than MFC or .Net. Why would I want to do that? Well… MFC isn’t exactly lightweight and it has some performance issues. But aside from that, it’s just fun!

When embarking on something ambitious like this, however, you immediately comes across issues you need to solve, such as how to map an essentially flat API like Win32 into an object-oriented hierarchy of reusable classes. Win32 was, after all, designed before object oriented programming became popular.

There are some patterns that you can use to recognize opportunities for classes and inheritance.

1) Some parameters show up a lot, often as the first argument to a function. All of the GDI functions, for example, take a handle to a device context. This pattern is much like the implicit this parameter in OO programming. A device context is a good candidate for being wrapped into a class, with the GDI functions as members. Most window manipulation functions take as an argument a handle in the form of HWND. Window is another candidate for a class. There are other examples, but these two are good starting places for creating the class hierarchy.

2) There are many variables that are often typecast to other types. Think GDI handles such as HPEN, HBRUSH, and HBITMAP. GDI functions such as SelectObject return a generic HGDIOBJECT which is usually cast to the appropriate HPEN or what-have-you. Fundamentally, these are all the same basic data type–just interpreted differently. This situation is a good candidate for inheritance and polymorphism.

You can also look at other framework libraries for ideas, but this idea is not as attractive, because the point is to develop something original through the learning process, and if those frameworks provided exactly what you wanted, why bother creating a new one anyway? On the other hand, much can be learned by examining proven techniques.

Another big issue you need to deal with in developing a framework library is messaging, but I’ll deal with that in a later post.

ArgumentNullException and ArgumentException

Does it strike anyone else as ironic that ArgumentException and ArgumentNullException have mismatched argument ordering? The parameter name is first for the null version, but second for the other one. Uggh… this makes it awkward to remember if you use both. ArgumentOutOfRangeException follows the example of ArgumentNullException.

I can see no obvious reason for the discrepancy. In all three cases, the constructors are exactly the same. In fact, MSDN explicitly says that the behavior is the same.

SM_SECURE

In the system metrics that you can retrieve with GetSystemMetrics, one of the available options is SM_SECURE.

The only explanation provided is “Nonzero if security is present; otherwise, 0.” What does that mean? On my computer, the value is 0. There are a few different ways security can be “present” in my mind–what specifically are they talking about here?

Google, MSN, MSDN yield no useful information.

A Debugging Exercise

A few weeks ago I had an interesting debugging problem. A program we develop had a memory leak in it that Visual Studio was catching when it ended. The trace text was something like this:

Detected memory leaks!
Dumping objects ->
{292300} normal block at 0x05590040, 2771928 bytes long.
Data: <> FF FF FF 00 FF FF FF 00 FF FF FF 00 FF FF FF 00
{292294} normal block at 0x05110040, 2613312 bytes long.
Data: <> FF FF FF 00 FF FF FF 00 FF FF FF 00 FF FF FF 00

Visual Studio 2003 is often pretty good at telling you where a memory leak occured, giving you a source code file and line number of where the memory allocation originated. In the case above, I don’t have that. There are two relatively easy ways of solving this.

The first method is to examine the data that isn’t being freed. In this case, I have two large objects of about 2.5 MB each. That’s pretty big–there aren’t too many (if any) individual objects in the software that are that large. So it could be an array. The data begins with a repeated pattern {FF FF FF 00}. Definitely looks like an array of 4-byte segments. Applying a little knowledge of the application itself–it displays large bitmaps–and we realize that the memory comes from an array of RGB values.

Another way to investigate this is to set a breakpoint on the memory allocation that isn’t being freed. The number in braces {292300} is the memory allocation number in debug mode in Visual C++. In order for this technique to work, you must first ensure that the number is the same each time. In my case, the memory leak would happen if I just opened and closed the program (because an image is always being drawn) without doing anything else.

First, set a breakpoint at the beginning of the program (or any place definitely before the memory leak). Start the program and when it breaks, enter the following into the watch window:

{,,msvcr71d.dll}_crtBreakAlloc

And for the value enter 292300.

If you continue the execution, the program will break on the 292,300th memory allocation. It will stop in the memory allocator, and you can then look at your stack frame and see exactly where the memory allocation is taking place.

MSDN has a great article about this.

In my problem it was for a set of memory blocks being used as working space for resizing and smoothing bitmaps. They were allocated once during execution and thus did not really provide a long-term threat. This leads to a possible third solution:

Ignore. All memory is reclaimed once the program exits. Nobody would ever do that, though…. would they?

…of course not…