Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Contents tagged with .NET best practices

  • Google Search API fails sporadically with "502 Bad Gateway"

    I heard about Google's web service interface to the search database back when it was released, but today was my first attempt to use it.  I'm trying to learn python, but the SOAP toolkits for python seem to be in a state of flux so I switched back to C# rather than figure out which python libraries to download. 

  • Checking if an application is already running

    Many Windows Forms applications only allow a single instance to run at a time. The following snippet is a clean way to check if your process is already running:

    static public bool AlreadyRunning()
    {
        string processName = Process.GetCurrentProcess().ProcessName;
        Process[] processes = Process.GetProcessesByName(processName);
        return (processes.Length > 1);
    }

  • Implementing Equals in C#

    While working on refactorings, I often notice domain objects that implement Equals incorrectly.  Below is a sample implementation of Equals.  The key points are that Equals should not throw an exception if obj is null or of the wrong type.  Also note the different patterns for comparing reference and value members.  See pages 154-160 of Richter's excellent Applied Microsoft .NET Framework Programming for more details, including different patterns for reference or value objects:

  • Implementing IDisposable

    Classes that need explicit destruction semantics or wrap managed resource usually implement IDisposable to allow for predictable destruction outside of garbage collection.  As I was just reminded by a defect in my code, all classes that implement IDisposable must provide a finalizer (C# uses destructor syntax: ~MyClass) to handle freeing resources when Dispose is not called.  Additionally, the Dispose method should call should call the GC.SuppressFinalize method for the object it is disposing.  From MSDN, "If the object is currently on the finalization queue, GC.SuppressFinalize prevents its Finalize method from being called."
     
     
     

  • Debug only methods in C#/.NET

     
    In Steve Maguire's Writing Solid Code, he encourages writing Debug only code that double checks complex logic.  For example, Excel uses a highly optimized evaluation method.  In the Debug build, there is another method that evaluates the same arguments and the two results are compared to ensure that the optimizations haven't broken the intent of the code.
     
    Writing Debug only code is a powerful technique, but can break the Release mode build.  For example, debug only methods are often defined as follows:
    #ifdef DEBUG
    private void DoDebugChecks()    {}
    #endif
     
    Then each call to DoDebugChecks needs to be wrapped in #ifdef blocks.  Forget one, and the release mode build breaks.  C# offers a better solution: the Conditional attribute.
     
    [Conditional("DEBUG")]
    private void DoDebugChecks()     {}
     
    This indicates to the compiler that DoDebugChecks is only executed in builds where DEBUG is true.  The compiler automatically compiles out all references during the build.  Two comments:
    1. I wish the .NET team had provided a [DebugOnly] attribute that gives the same functionality.  I'm a stickler for compile time checks, and so I worry about someone mistyping DEBUG and creating a very hard to find defect.
    2. Debug only methods are great, but make sure they do not alter the state of the application.  Just like in Debug.Asserts, make sure there aren't any side effects, or the release build will behave differently than expected.

  • Delegate and Event signatures

    I'm designing the events and delegates that will be used in a real-time stock quoting application.  All my delegates and events will be operating in a single process, so I'm leaning towards the following:
     
    // Instrument is a stock, Tick Message has the details of the real-time quote
    public delegate void TickArrivedHandler(Instrument sender, TickMessage tick);
     
    // The Instrument publishes an OnTickArrived event so subscribers can ask to be notified when a new tick (quote) arrives
    public event TickArrivedHandler OnTickArrived;
     
    However, this conflicts with Microsoft's conventions for declaring events (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconeventnamingguidelines.asp):
     
    The guidelines say, "Specify two parameters named sender and e. The sender parameter represents the object that raised the event. The sender parameter is always of type object, even if it is possible to use a more specific type."   I'd rather have more specific types passed in to the delegate so the subscriber can interrogate the Instrument object without a downcast, or worse, a series of "is" checks followed by downcasts.  Having the check for the right type done at compile seems better than having the client doing a downcast or switch on the type at runtime.
     
    The MS guidelines also say, "The state associated with the event is encapsulated in an instance of an event class named e. Use an appropriate and specific event class for the e parameter type."  Juval Lowy contradicts this in his excellent "Programming .NET Components" book.  He suggests defining the delegate to take the base EventArgs class, and "the subscriber should downcast the generic EventArgs to the specific argument class" (p. 106)  I don't want my subscribers downcasting, so I'd prefer to pass the data the subscriber needs.
     
    Thoughts?

    Ted