Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, September 22, 2017

Making a Modal Dialog with C# and WPF

Copyright © 2017, Steven E. Houchin. All rights reserved.

For a unit test program I'm developing to validate a new library API, I created a window to show some attributes of an object. I wanted that window to display as follows:

  • normal modal dialog
  • centered on parent window
  • not shown in taskbar
  • can be resized
  • can be minimized

I'm using .NET Framework 4, C# and WPF on a Windows 10 system.

Here are some observations about how to properly set up a dialog as I describe above.

First, to show as a modal dialog, I call the Window class's ShowDialog method to open and show the dialog from the parent Window class:


    // Create the Detail View Controller object
    IDetailViewControl view_controller =
            app.MakeDetailViewController();

    // Create the Detail View Object, passing in this
    // Window class as a parent
    MyDetailView detail =
            new MyDetailView(myDataObject, view_controller, this);
                
    // Show the Detail dialog
    detail.ShowDialog();

Second, to center the dialog on its parent window, the MyDetailView dialog class's constructor sets its Owner property to the Window object passed by the caller:


    public partial class MyDetailView : Window
    {
        public MyDetailView (MyData dataObject,
                             IDetailViewControl controller,
                             Window owner)
        {
            this.Owner = owner;   // set parent window as owner
            InitializeComponent();

            // other constructor initialization
        }
    }



Note that, in the above code, the parent Window code could have set itself as Owner using the 'detail' object before calling ShowDialog, but I chose to have the dialog take care of that. Finally, to complete a centered dialog when open, the dialog Window's XAML properties must specify:

    WindowStartupLocation="CenterOwner"

Third, I set the dialog Window's XAML property to not show in the taskbar:

    ShowInTaskbar="False"

Set to False, it means this dialog will not show in the taskbar, but Restoring the parent window from the taskbar brings the MyDetailView dialog to the top with it.

Lastly, I set the dialog Window's XAML property so it can be resized and minimized:

    ResizeMode="CanResize"

The ResizeMode setting can instead be set to CanMinimize if resizing isn't desired. The CanResize value implies CanMinimize, since minimizing and maximizing is assumed to be part of any resize operation.

So, with the WPF Window implemented this way, it acts like a classic modal dialog we're all accustomed to.

Monday, August 28, 2017

Design Pattern example: Singleton and Observer (Part III)

Copyright © 2017, Steven E. Houchin. All rights reserved.

In my last two postings on this subject, I outlined a Logger class used by my Parser class for logging errors.  In this article, I show a more sophisticated approach for the application to register and unregister as an interested Observer with Logger, so it is notified when an error message is posted to Logger.

First, the Observer class must derive from the ILoggerObserver interface:

///
/// Interface to be implemented by objects who wish to
/// observe changes on the Logger object's data.
///
public interface ILoggerObserver
{
    void didAddLogMessage(string message);
}


In my original posting, I showed the following code snippet showing the Observer register and unregister sequence:


public class MyParser : ILoggerObserver
{
    ...

    public void MyParseLogic()
    {
        // Register to log any parsing errors
        Logger log = Logger.Instance;
        log.Attach(this);

        // Parse my data file
        Parser p = new Parser(my_file_path_to_be_parsed);
        p.Parse(); // will call the same Logger instance

        log.Detach(this); // resign as a Logger observer

        ...
    }

    /// Implement the ILoggerObserver interface
    public void didAddLogMessage(string message)
    {
        // Output the message to a TextBlock control or
        // pop up a Message Box.
        ...
    }

} // end class MyParser

Note that before parsing is done, the MyParser class calls Logger's Attach method to register as an observer, and after finishing with the parsing, calls Detach to unregister. But I later came up with a better design so Detach can be done automatically. I accomplish this by taking advantage of the .NET IDisposable interface.

I created a new container class named LoggerObserverDisposer, derived from IDisposable. Its only job is to call Logger's Detach for the Observer when it's being disposed by .NET. The target Observer object is provided to its constructor and remembered for when the Detach is done.

Here is that new Disposer class:


/// Container class for an observer, which terminates its observing
/// when out of scope.
public class LoggerObserverDisposer : IDisposable
{
    protected ILoggerObserver _observer = null;
    public LoggerObserverDisposer(ILoggerObserver observer)
    {
        // Remember the observer object to be disposed
        _observer = observer;
    }

    public void Dispose()
    {
        Dispose(true);  // call our Dispose method below
        // prevent redundant Dispose during garbage collection
        GC.SuppressFinalize(this); 
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Get the Logger object
            Logger logger = Logger.Instance;

            // Make operation atomic
            Monitor.Enter(logger);
            if (_observer != null)
            {
                // Remove the observer from Logger
                logger.Detach(_observer);
                _observer = null;
            }
            Monitor.Exit(logger);
        }
    }
}   // end class LoggerObserverDisposer


Previously, here is what Logger's Attach method looked like:


    /// Add an Observer object to the list of those
    /// to be notified of changes.
    public void Attach(ILoggerObserver observer)
    {
        if (null != observer)
        {
            // Add this observer to the list, but just once
            Detach(observer);
            _observers.Add(observer);
        }
    }


Now, it is changed to make use of our new LoggerObserverDisposer class. Attach returns a new LoggerObserverDisposer instance for the Observer, but only if requested by the caller.


    /// Add an Observer object to the list of those to be notified
    /// of changes, and return a Disposer object for the observer,
    /// if requested.
    /// 
    /// Params:
    /// "observer" - The Observer object to add to the list.
    /// "doMakeDisposer" - true to return a Disposer object.
    /// Returns: A Disposer object, if requested, or null
    public LoggerObserverDisposer Attach(ILoggerObserver observer,
                                       bool doMakeDisposer = false)
    {
        if (null != observer)
        {
            // Add this observer to the list
            Detach(observer);
            _observers.Add(observer);
        }

        // Return an object the caller can include in a
        // 'using' statement so the observer is automatically
        // removed when the Disposer goes out of scope
        return (doMakeDisposer) ?
                new LoggerObserverDisposer(observer) : null;
    }


Finally, the MyParser class changes to use this new version of Logger's Attach, but never needs to explicitly call Detach:

    public void MyParseLogic()
    {
        // Register to log any parsing errors
        Logger log = Logger.Instance;
        using (logger.Attach(this, true))
        {
            // Parse my data file
            Parser p = new Parser(my_file_path_to_be_parsed);
            p.Parse(); // will call the same Logger instance
        }

        ...
    }

The changed code takes advantage of the C# "using" statement, which expects an IDisposable-derived object. When the "using" block goes out of scope, that object's Dispose method is called. In our case, the new Attach method returns a LoggerObserverDisposer object (rather than void as before), which remains in scope throughout the "using", even though I never assign it to a variable. Thus, LoggerObserverDisposer::Dispose is called when the "using" block loses scope, which in turn calls Logger's Detach for the Observer MyParser class.

This logic saves the programmer from having to remember to manually Detach, and possibly leave a dangling Observer that has since been destroyed.

Monday, August 21, 2017

Design Pattern example: Singleton and Observer (Part II)

Copyright © 2017, Steven E. Houchin. All rights reserved.


In my previous post on this subject, I introduced a class named Logger, which is used by my parser class to log parsing errors. It is implemented using the Singleton design pattern. The Logger class also uses the Observer design pattern where other interested objects can register with Logger to be notified when new messages are logged.

This article shows the notification logic used by Logger.  But first, a quick review of Logger:

public class Logger : object
{
    // The Singleton instance
    protected static Logger _instance;

    // List of Observer objects to be notified of
    // changes to the log
    protected List(lt)ILoggerObserver(gt) _observers;

    /// Hidden constructor
    private Logger()
    {
         _observers = new List(lt)ILoggerObserver(gt)();
    }

    ...

    /// Add an Observer object to the list of those
    /// to be notified of changes.
    public void Attach(ILoggerObserver observer)
    {
        if (null != observer)
        {
            // Add this observer to the list, but just once
            Detach(observer);
            _observers.Add(observer);
        }
    }

    /// Remove an Observer object from the list.
    public void Detach(ILoggerObserver observer)
    {
        if (null != observer)
            _observers.Remove(observer);
    }

    ...

    public void LogError(string msg)
    {
        // ... do something to log the error somewhere ...
    }
}

Objects wishing to be notified must implement the abstract interface Logger calls:

///
/// Interface to be implemented by objects who wish to
/// observe changes on the Logger object's data.
///
public interface ILoggerObserver
{
    void didAddLogMessage(string message);
}

Now, let's look at the implementation of the LogError method. It needs to notify the observers that a message has been logged, so:


    public void LogError(string msg)
    {
        if ((null == msg) || (0 == msg.Length))
           return;

        // Prepend an identifier prefix, then notify observers
        Notify(@"[Error] " + msg);
    }

    ///
    /// Notify all observers of the logged message.
    ///
    protected void Notify(string message)
    {
        foreach (ILoggerObserver observer in _observers)
        {
            // Notify the Observer of the logged message
            observer.didAddLogMessage(message);
        }
    }


Above, we have given substance to the LogError method, which in turn calls the Notify method to do the actual work of notifying the observer objects. The observer objects each implement the didAddLogMessage method, where the message reaches it's ultimate destination, such as a log file or a UI control. With the Notify method separated out like this, the class can easily be enhanced to add LogWarning and LogInfo methods, which prepend a different prefix to show the message's severity.

In a follow-up posting, I'll show an improved way to attach and detach an observer object from the Logger class.

Friday, July 21, 2017

Design Pattern example: Singleton and Observer (Part I)

Copyright © 2017, Steven E. Houchin. All rights reserved.

I've lately been developing a parser library for a certain standard file format used for data interchange between some programs.  At various points in the parsing process, my code detects errors, and I wanted a mechanism to log those errors.  The parser consists of a gaggle of classes (in C#) that encapsulate various data structures, any of which may generate errors or warnings about file format issues.  I certainly didn't want to pass a reference to a logger object as a parameter to every method in every class to accomplish the error logging.

Thinking about the functionality of logging errors, multiple instances of a logger object didn't make sense.  So, I designed a logger class based upon the Singleton design pattern, where one instance of the class is created at first use, and that same instance is retained for subsequent uses:


public class Logger : object
{
    // The Singleton instance
    protected static Logger _instance;

    /// Hidden constructor
    private Logger()
    {
    }

    /// Get the only instance of the class
    public static Logger Instance
    {
        get
        {
            // Get the only instance, creating new if necessary
            if (_instance == null)
            {
                _instance = new Logger();
            }
            return _instance;
        }
    }
        
    public static void Free()
    {
        // Free the only instance when done with the parser
        _instance = null;
    }

    public void LogError(string msg)
    {
        // ... do something to log the error somewhere ...
    }
} // end class Logger

The parser library methods simply get a reference to Logger's class instance like this:

   
    Logger log = Logger.Instance;
    log.LogError("Parse error.");

Each call to the Logger's Instance property returns the same object instance, no matter where in the code it is called.

My next design task was to decide how and where to log the error message itself.  Ultimately, I decided the Logger class shouldn't be burdened with the detail of "where" to log the error. What if App1 wants the library to log to a file, and App2 wants the log rendered to the UI?  At first, I just dumped the messages into an ArrayList, and the parent App would pull them out at its leisure at a later time.  But that was inelegant and didn't notify the App of the error in real time.

The key word I just used there is "notify."  That idea implies a callback, and that brought to mind the Observer design pattern, for which notification is a central part of the concept. For example, Object-A's state changes via some event, and it notifies Object-B of the change. In Observer, though, notifications may also be sent to Objects C and D and E.  So, Objects B through E must register as interested observers with Object-A, and unregister when no longer interested.

To implement Observer, my Logger class needed a callback interface for the observers, registration/deregistration methods, and a structure of some kind to keep track of each observer.

First, the callback interface:


///
/// Interface to be implemented by objects who wish to
/// observe changes on the Logger object's data.
///
public interface ILoggerObserver
{
    void didAddLogMessage(string message);
}

Each of the observer classes must derive from the above ILoggerObserver interface and implement the didAddLogMessage method, which allows the observer to do whatever it wishes to log the message.

Next, a List to keep track of the observer registrations:


public class Logger : object
{
    // The Singleton instance
    protected static Logger _instance;

    // List of Observer objects to be notified of
    // changes to the log
    protected List(lt)ILoggerObserver(gt) _observers;

    /// Hidden constructor
    private Logger()
    {
         _observers = new List(lt)ILoggerObserver(gt)();
    }

    ...

}

Of course, the (lt) and (gt) above are really < and > that don't render well in the HTML code snippet above.

Now, we need the registration/deregistration methods in the Logger class.  These will be made more sophisticated in a follow-on posting.

    /// Add an Observer object to the list of those
    /// to be notified of changes.
    public void Attach(ILoggerObserver observer)
    {
        if (null != observer)
        {
            // Add this observer to the list, but just once
            Detach(observer);
            _observers.Add(observer);
        }
    }

    /// Remove an Observer object from the list.
    public void Detach(ILoggerObserver observer)
    {
        if (null != observer)
            _observers.Remove(observer);
    }

So, finally, the user's parser code initializes logging by registering as an Observer, and calls the parser:

public class MyParser : ILoggerObserver
{
    ...

    public void MyParseLogic()
    {
        Logger log = Logger.Instance;
        log.Attach(this); // become a Logger observer

        Parser p = new Parser(my_file_path_to_be_parsed);
        p.Parse(); // will call the same Logger instance

        log.Detach(this); // resign as a Logger observer

        ...
    }

    /// Implement the ILoggerObserver interface
    public void didAddLogMessage(string message)
    {
        // Output the message to a TextBlock control or
        // pop up a Message Box.
        ...
    }

} // end class MyParser

With follow on postings, I'll show the Logger's notification logic, and a better way to unregister as an observer.

Monday, October 24, 2011

Computing the viewport size within a WPF Border control

Copyright © 2011, Steven E. Houchin. All rights reserved.

I have a WPF application that renders a photo bitmap inside a System.Windows.Controls.Image control that is contained within a System.Windows.Controls.Border. If the photo bitmap is too large for the app window (either in the horizontal or vertical direction), I set the Image's corresponding size attribute(s) to 'Auto' (i.e. Double.NaN) within the Image's SizeChanged event handler. If the bitmap is smaller than the app window, I set the Image's size to the actual fixed size of the bitmap, so it doesn't get scaled.

But, that left a problem when I resized the app window smaller: a fixed-size Image was truncated by the border when the window shrank smaller than the photo's bitmap size. And, because the Image's width/height weren't set to Auto, its SizeChanged event wasn't firing.

However, the Border's SizeChanged event was firing. So, I added that handler for the Border control, planning to set the Image's proper width/height after resize.  That left another problem in this new event handler: how to calculate whether or not the Image control's width/height should be Auto or fixed.  Put another way, what was the size of the viewport inside the Border control where the Image would be rendered?

The Border's SizeChanged event handler is passed a SizeChangedEventArgs parameter that provides the new width/height of the Border control. The size available to the Image control inside that will clearly be smaller, but by how much? Here is the algorithm in C# that I came up with (keep in mind that a negative BorderThickness means the border is drawn outside the control's drawing area):

// Calculate the Border control's new viewport
// size within the drawn border where the Image control
// is rendered (add in any padding and non-negative
// border thickness).
Size viewport = new Size();
viewport.Width = e.NewSize.Width -
    (border.Padding.Left + border.Padding.Right) -
    ((border.BorderThickness.Left > 0) ?
        border.BorderThickness.Left : 0) -
    ((border.BorderThickness.Right > 0) ?
        border.BorderThickness.Right : 0);
viewport.Height = e.NewSize.Height -
    (border.Padding.Top + border.Padding.Bottom) -
    ((border.BorderThickness.Top > 0) ?
        border.BorderThickness.Top : 0) -
    ((border.BorderThickness.Bottom > 0) ?
        border.BorderThickness.Bottom : 0);
This viewport variable now holds the size available for the Image control inside the border. Now, all I have to do is determine if the Image needs to be scaled down in the viewport or set to a fixed size. One thing I discovered is that the Image's Margin value must be taken into account, since it is also rendered inside the viewport along with the photo bitmap. The code to determine the right sizing, in this case for the width is:

// Calculate the image's real width to determine if
// scaling is needed
double imageWidth = _bitmapActualSize.Width +
    image.Margin.Left + image.Margin.Right;
if (viewport.Width > imageWidth)
{
    // Restrict the Image control's width to the
    // bitmap's actual width
    image.Width = _bitmapActualSize.Width;
}
else if (viewport.Width < imageWidth)
{
    if (Double.NaN != image.Width)
    {
        // Set the Image control's width to 'Auto' so
        // it will scale down to fit
        image.Width = Double.NaN;
    }
}
The same calculation is done for the Image height immediately after. This results in the proper change to the photo bitmap size just at the right time.

Thursday, August 11, 2011

Finding IWin32Window in WPF

Copyright © 2011, Steven E. Houchin

I'm developing a WPF desktop application (C# and .NET 3.5) that needs to pop up a dialog window allowing the user to browse for a folder.  .NET provides a convenient (and bland) dialog that does this: System.Windows.Forms.FolderBrowserDialog. To pop up this dialog as modal from my app, I must call its ShowDialog method. Since I want it to be a child of my main window, I need to pass it the parent window, which should be straightforward given the "owner" parameter to the method in question:

DialogResult ShowDialog(System.Windows.Forms.IWin32Window owner);

The problem is, the would-be parent window of that dialog is of type System.Window, not IWin32Window, so "this.Owner" won't match the datatype of ShowDialog's "owner" parameter.  So, given that I have a WPF System.Window-derived parent class, where do I obtain an IWin32Window object?

Well, it turns out I have to write a tiny bit of code for it. Specifically, I must implement the IWin32Window interface on the parent window's class:

public partial class Main : Window,
    System.Windows.Forms.IWin32Window
{
...
   #region IWin32Window implementation
   IntPtr System.Windows.Forms.IWin32Window.Handle
   {
      get
      {
         return ((HwndSource)
             PresentationSource.FromVisual(this)).Handle;
      }
   }
   #endregion
...
}

With the IWin32Window.Handle property now implemented in the parent class, I can simply call ShowDialog(this). Note that you must also include a "using System.Windows.Interop" for this to work.


Wednesday, May 14, 2008

Accessing Attributes in AssemblyInfo.cs

Copyright © 2008, Steven E. Houchin
For a new C# .NET application, an AssemblyInfo.cs file is automatically created. It contains empty attributes that can be used to describe the assembly. These attributes are queried by Windows when the Properties of an executable are examined from Windows Explorer. They are also useful within the application itself to set the string in the title bar and for populating an About dialog. For example, I set the following values for one of my applications (with names changed to protect confidentiality):

[assembly: AssemblyTitle("My Application")]
[assembly: AssemblyCompany("Forest Park Lab")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright © 2004-2008, Forest Park Lab.")]
[assembly: AssemblyTrademark("My Product ™ is a trademark of Forest Park Lab.")]

Setting these values doesn't make them automatically available to your application code. In order to access them, I have a piece of boilerplate code I include in the AssemblyInfo.cs file to make these attributes readily accessible. I define an "AssemblyInfo class" as follows:

using System.Reflection;
using System.Runtime.CompilerServices;

public class AssemblyInfo
{
   private AssemblyTitleAttribute  _title = null;
   private AssemblyCopyrightAttribute _copyright = null;
   private AssemblyProductAttribute _product = null;
   private string    _version;

   public AssemblyInfo()
   {
      System.Reflection.Assembly assembly =
      System.Reflection.Assembly.GetExecutingAssembly();
      // get the version string
      _version = assembly.GetName().Version.ToString();

      // get other desired attributes
      object[] attributes = assembly.GetCustomAttributes(false);
      for (int i = 0; i < attributes.Length; i ++)
      {
         if (_title == null)
         {
            _title = attributes[i]
               as AssemblyTitleAttribute;
            if (_title != null)
               continue;
         }
         if (_copyright == null)
         {
            _copyright = attributes[i]
               as AssemblyCopyrightAttribute;
            if (_copyright != null)
               continue;
         }
         if (_product == null)
         {
            _product = attributes[i]
               as AssemblyProductAttribute;
            if (_product != null)
               continue;
         }
      }
   }
   public string Title  { get { return _title.Title; } }
   public string Product  { get { return _product.Product; } }
   public string Copyright  { get { return _copyright.Copyright; } }
   public string Version  { get { return _version; } }
}

The way this code works is that it fetches all of the customizable attributes from the assembly (GetCustomAttributes()) into an array of objects. It then loops through each object and attempts to cast it (using the C# "as" operator) to one of the desired attribute types. If the cast fails, the result is null. Otherwise, the object is remembered as a property within the AssemblyInfo class for later access by the application.
To make use of these attributes in the application, simply create an instance of the AssemblyInfo class and access the properties, as follows:

AssemblyInfo appInfo = new AssemblyInfo();
// set the title in title bar
this.Text = appInfo.Title;
// set the product name
this.lblProduct.Text = appInfo.Product;