Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Design & Architecture » Separating the user interface from your working code

Separating the user interface from your working code

Your application’s user interface may be a Windows Form, a Web Form, or maybe just a command line. This article is about separating the user interface from the rest of your application’s code.

Technologies: .NET Compact Framework, Windows Forms,Visual C# .NET
Total downloads : 207
Total page views :  6901
Rating :
 4/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
UISeparation.zip
 
ArticleAd
Become a Sponsor



Introduction

Your application's user interface may be a Windows Form, a Web Form, or maybe just a command line.  This article is about separating the user interface from the rest of your application's code. 

Here are some reasons this is a good idea:

  1. User interfaces become interchangable.  A Windows Form version, a web version, and a command line version of the same application can share the same working code.
  2. You can easily create a special user interface to use as a test driver to exercise your code.
  3. Good object oriented design involves structuring your code into sets of interacting classes.  With many Windows Forms applications, the form code itself can get quite large.  Pulling the working code out of the form can make your application easier to understand and work on. 

The Engine Class

The first thing to do is move your working code into a class I often name Engine, unless I can think of a better name.  This class has methods to respond to all the UI events, and completely separates all the application's funtionality from the UI.  Put this class in a separate library project, along with all the other classes it uses, and then reference the library from each UI project.  Your UI projects should contain only UI code.

Information flows two ways between the UI and the Engine class.

  • UI to Engine - UI events call the corresponding Engine class methods directly.  
  • Engine to UI - Things get a little trickier.  The first idea that comes to mind is to give the engine a reference to the form and call methods on it directly.  But notice that to describe this, I had to use the word "form".  Already, I've made an assumption that will not always be true.  What's needed is something to represent the UI in a generic way to the engine so it can make calls to it.  An interface will work nicely.

Let's see some code

This demonstration project implements an imaginary process of listing the machine names on a network.  To keep things simple, it doesn't actually scan the network, it just makes up names:  Machine1, Machine2, etc. 

This is the interface definition the Engine class will use to send information back to the UI to report progress events.

public interface IUI

{

    void Started();

    void Progress(string progress);

    void Complete();

}

Here's the Engine class.  There is a static interface property that will be set to point to the class that implements the interface.

public class Engine

{

    static IUI _iui;

 

    static bool _cancel;

 

    public static IUI Iui

    {

          set { Engine._iui = value; }

    }

 

    public static void ScanNetwork()

    {

        _iui.Started();

 

        _cancel = false;

 

        for (int i = 1; i < 15;i++)

        {

            if (_cancel) break;

 

            _iui.Progress("Machine" + i.ToString());

 

           }

 

        _iui.Complete();

    }

}

The ScanNetwork method will be called by the UI when the ScanNetwork button is clicked.  See the calls to the interface to report progress.

The Form1 class inherits from IUI and defines the interface methods.

public partial class Form1 : Form, IUI

{

    public Form1()

    {

        InitializeComponent();

        Engine.Iui = this;

    }

 

    private void buttonScanNetwork_Click(object sender, EventArgs e)

    {

        Engine.ScanNetwork();

    }

 

    private void buttonCancel_Click(object sender, EventArgs e)

    {

        Engine.Cancel();

    }

 

    public void Started()

    {

        listBoxMachines.Items.Clear();

        labelStatus.Text = "Started";

    }

 

    public void Progress(string progress)

    {

        listBoxMachines.Items.Add(progress);

    }

 

    public void Complete()

    {

        labelStatus.Text = "Complete";

    }

}

The Engine.Iui property is set to point to the class that implements the IUI interface.  In this case it's the form class, but when writing a console application I create a separate class.

This code will work as it is, but there's a problem.  In this example the imaginary network scan occurs instantly.  In real life it takes time, and the user will have to wait for the whole scan to complete before the machine names will appear in the list.  There is a line with a Sleep call in the project code that you can uncomment to see what I mean.

The machine names should be added to the list as they are found (or made up in this case) so the user can see progress.  It would also be nice to have a way to cancel the potentially time consuming scan.  To keep the UI "alive", the scanning process needs to run on a separate thread.  There's more than one way to do this, but here's a way that's quick and easy.

Adding a background worker

From the Visual Studio toolbox, drag a BackgroundWorker component onto the form.  In the Properties pane for the BackGroundWorker, select the Events view and double click the DoWork event to create an  event handler.  The event handler code should call Engine.Scan 

private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)

{

    Engine.ScanNetwork();

}

Call RunWorkerAsync from the buttonScanNetwork_Click event

private void buttonScanNetwork_Click(object sender, EventArgs e)

{

    listBoxMachines.Items.Clear();

    backgroundWorker1.RunWorkerAsync();

}

There's a restriction that form control methods and properties can only be accessed from the thread that created them.  The way around the restriction is to use Invoke, and the code below shows how.

Create the method that will manipulate the control and define a delegate with the same signature.

public delegate void UpdateStatusCallback(string status);

 

public void UpdateStatus(string status)

{

    labelStatus.Text = status;

}

This helper method simplifies the task of creating an object array with one string in it to supply as a parameter for theh Invoke calls.

private object[] StringToObjectArray(string str)

{

    object[] args = new object[1];

    args[0] = str;

    return args;

}

All that's left is to fill in the implementor for the IUI Started method.  The project code does this for the other methods as well.

public void Started()

{

    UpdateStatusCallback callback

        = new UpdateStatusCallback(this.UpdateStatus);

    labelStatus.Invoke(callback, StringToObjectArray("Started"));

}

Adding a command line interface

We've explored the details of implementing a Windows Forms interface for the Engine class.  Because of the necessity to keep the GUI alive, this is the most complicated UI to implement.

The included solution code has a Console application that implements a command line interface for the Engine class, and it's very simple.

Conclusion

I've shown an easy way to get the flexibility of interchangable user interfaces and, at the same time, add structure to your code.  Next time someone asks "can we make a web version?" you'll be ready to go.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
roger bruvold

I’ve been developing software for twenty years with C, C++, and now C#.  My latest creation is a software visualization program called LumiCode which is written entirely in C#.

I believe good software design is easier to achieve if we can actually see the design, and I enjoy developing tools for that purpose.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
UISeparation.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Re: Goodozi12/28/2008
The beginings of MVC.
Reply | Email | Delete | Modify | 
Nice onemhbcedu6/11/2009
Nice one
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved