Infragistics ASP.NET controls

Introducing System.Threading.Tasks namespace. Exploring Action<>, Task<>, and the BusyIndicator.

Introduction The Microsoft .NET framework class library has provided many classes to facilitate complex programming tasks.  Topics like I/O, database management, and sockets were once incredibly tough to implement in languages like C, C++ and VB6.  When .NET was released, it brought with it many classes that abstracted these complex concepts and allowed the developer to concentrate on the business task at hand.  Multithreading is a way of providing asynchronous code execution and is an advanced concept that the framework has greatly simplified.  The System.Threading namespace The System.Threading namespace contains classes to abstract the complexities of multithreaded programming away from the developer.  Multithreading allows you to spawn worker threads to accomplish a unit of code execution.  System.Threading includes classes for synchronizing thread activities as well as accessing shared data .  These classes include; Mutex, Monitor, Interlocked, AutoResetEvent and more.   At the heart of the System.Threading namespace is the System.Threading.Thread class.  This class represents an asynchronous thread of code execution.  The Thread class accepts a delegate to specify a method that returns void and is to be executed independently in regards to the thread that spawned it.  This was one of the first methods of asynchronous programming that was offered to .NET developers. Here's an example using System; using System.Threading; namespace AnsycThread { class Program { delegate void LongRunningComputation(); private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.ReadKey(); } public static void Main(string[] args) { LongRunningComputation codeBlock = LongRunningMethod; Thread spawnedWorker = new Thread(new ThreadStart(codeBlock)); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } This code is not very complicated, especially when compared to the same take written in a language like C or C++.  The System.Threading namespace has been around since the first release of the .NET framework. Enter the System.Threading.Tasks.Task class With .NET 4 came the System.Threading.Tasks namespace.  The idea of a Thread is a low level concept.  To think in terms of processes, threads, and thread management is to think at the level a computers processor.  The Task class was created to abstract these machine level ideas away from the developer so that we could achieve the same solutions that multithreading offers but from the viewpoint of task and workflows instead of threads and processors.  Much like the System.Threading.Thread class, the Task class is simply an asynchronous operation represented by a delegate.  However, there are some key differences.  For instance, there is a generic Taks<T> where T represents the return type of the delegate.  The Task class also handles a lot of the manual aspects of multithreaded programming such as picking a thread from the thread pool, as well as optimization with multicore/multiprocessor systems.  The System.Threading.Tasks namespace event offers functionality to support parallelism, but I'm getting ahead of myself. We are going to examine an example that makes use of the Task class as well as the System.Action class. The System.Action class represents a delegate that takes no arguments and returns void.  There is a generic version of the Action class as well.  It greatly simplifies the syntax of delegates. Consider the following example which is essentially the same as the prior example, except this example uses the Task and Action classes instead of Thread and delegate. namespace AnsycTask { class Program { private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.WriteLine("Press a key"); Console.ReadKey(); } public static void Main(string[] args) { Action codeBlock = LongRunningMethod; var spawnedWorker = new Task(codeBlock); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } Accessing the UI from another thread using Dispatcher.BeginInvoke As you can see, multithreaded programming and allow you to complete multiple computing tasks simultaneously.  One of the draw backs of this approach is the fact that you can't directly access controls that were instantiated on the UI thread from your Tasks or Threads.  This is where the System.Windows.Dispatcher class can help.  When you call the BeginInvoke method of the Dispatcher class, it allows you to execute an asynchronous delegate on the same thread that the Dispatcher is associated.  I've included an example that uses the Task, Action, and Dispatcher classes in a WPF application.   This example will execute a Task when the user clicks a button.  The task will open a text file and read the contents of the file.  We use the ContinueWith method of the Task object to specify another Task to run when the first task has completed.  In the ContinueWith Task, we will use the Dispatcher class to set the IsBusy property on a BusyIndicator object.  The BusyIndicator class comes from the WPF Extended toolkit.   Here's the example.. <Window x:Class="FileReadBusyIndicator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:extToolkit="clr-namespace:Xceed.Wpf.Toolkit;assembly=WPFToolkit.Extended" Title="MainWindow" Height="350" Width="525"> <extToolkit:BusyIndicator x:Name="busyIndicator"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="78*" /> <RowDefinition Height="78*" /> <RowDefinition Height="106*" /> <RowDefinition Height="50*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Content="Load File" Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="118,9,0,0" Name="btnLoadFile" VerticalAlignment="Top" Width="75" Click="btnLoadFile_Click" /> <TextBlock Height="45" HorizontalAlignment="Left" Margin="32,15,0,0" Name="txtDescription" Text="Click the button below to asynchrnously load the contents of the text file specified in the textbox." VerticalAlignment="Top" Grid.ColumnSpan="2" Width="390" /> <TextBlock x:Name="txtContents" Grid.Row="1" ScrollViewer.CanContentScroll="True" Height="183" HorizontalAlignment="Left" Margin="6,0,0,0" Text="rwaraadsadsdsasdafsdfsdafsdaf" VerticalAlignment="Top" Width="491" Grid.ColumnSpan="2" Grid.RowSpan="2"> </TextBlock> </Grid> </extToolkit:BusyIndicator> </Window> And for the codebehind using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading.Tasks; using Microsoft.Practices.Unity; using System.IO; using System.ComponentModel; using System.Threading; using System.Windows.Threading; using Xceed.Wpf.Toolkit; namespace FileReadBusyIndicator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private void LongRunningMethod() { //Add a long running computation here for (var loopCounter = 0; loopCounter < 100; loopCounter++) { using (var streamReader = new StreamReader(@"c:\development\openme.txt")) { var contents = streamReader.ReadToEnd(); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtContents.SetValue(TextBlock.TextProperty, contents); }, null); } } } public MainWindow() { InitializeComponent(); } private void btnLoadFile_Click(object sender, RoutedEventArgs e) { busyIndicator.IsBusy = true; Action readFile = LongRunningMethod; var spawnedWorker = new Task(readFile); var completedTask = new Action<Task>((t) => { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { busyIndicator.SetValue(BusyIndicator.IsBusyProperty, false); }, null); }); spawnedWorker.ContinueWith(completedTask); spawnedWorker.Start(); } } } As you can see, the button's click event handler sets the BusyIndicator's IsBusy property to true which will show the ProgressBar.  Next the event handler will create a Task and set it to execute an action that points to a method to read the contents of a file.  The method will use the Dispatcher class to set the TextProperty dependency property of a textbox to the contents of the text file.  When the task completes its execution, it will proceed to execute the task specified in the ContinueWith method which uses the Dispatcher class to set the BusyIndicator's IsBusyProperty dependency property's value to false, causing the ProgressBar to be hidden. You can download the source to the example projects here AsyncTaskExample.zip (352.19 kb). This concludes my introduction to the System.Threading.Tasks namespace. Thanks for reading. ~/Buddy James   kick it on DotNetKicks.com    


How to keep your WPF UI responsive and report progress during a long running task. C# and asynchronous multithreading.

    The problem Have you ever had to execute a bit of code that took an extremely long time to complete?  If so, I'm sure you've noticed that your user interface becomes unresponsive.  You can't use any controls on the form until the process completes.  This is extremely problematic and makes for a poor user experience. The cause This problem is because you have executed a synchronous block of code on the same thread as the user interface.  The user interface will not be able to respond to any user action until the synchronous method has completed. Let's look at an example that illustrates the execution of a synchronous method executing on the user interface thread. The example   This example is very simple.  It's a WPF application with two buttons.   One of the buttons will start a long running for loop and the other button opens a MessageBox and displays a message to let you know that the UI is active. When you click the button to start the long running process, try to click the other button.   You will notice that you are unable to click the button to show the message box.   Here's the MainWindow.xaml markup <Window x:Class="SynchronousExecution.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid Width="111" Height="118"> <Button Content="Start Process" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnStartProcess" VerticalAlignment="Top" Width="89" Click="btnStartProcess_Click" /> <Button Content="Try to click me" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="btnTryMe" VerticalAlignment="Top" Width="89" Click="btnTryMe_Click" /> </Grid> </Window>   And here is the code behind MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; namespace SynchronousExecution { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnStartProcess_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Starting the long process. Try to click the button below."); for (var loopCounter = 0; loopCounter < 500; loopCounter++) { Thread.Sleep(100); } MessageBox.Show("The process has ended."); } private void btnTryMe_Click(object sender, RoutedEventArgs e) { MessageBox.Show("User interface is responding!"); } } } Download  SynchronousExecution.zip (52.38 kb) The solution The solution to this problem is to spawn a new thread to execute the long running task.  By placing the execution on a seperate thread, this leaves the main UI thread free to interact with the user's input. Reporting progress  If you execute a long running task, you usually want to let your users know about the progress of the task.  A control to assist with this is the progressbar control.   The WPF progress bar control inherits from the RangeBase class.  The control contains the following properties to control how the progress is displayed to the user. Minimum The minimum value of the Value property. Maximum The maximum value of the Value property. SmallChange The value in which the Value property is incremented. Value The current value position between the Minimum and Maximum property. Multithreading concerns Multithreading is a complex topic and is beyond the scope of this article.  However, there are a few concerns that you must be aware of if you plan to access values on the UI thread from the worker thread. The System.Windows.Threading.Dispatcher object is used to execute code on the UI thread from the executing worker thread.  The Dispatcher object has the BeginInvoke method which will execute an asynchronous delegate on the thread in which the dispatcher object was created.  So by using the dispatcher object from the user interface code you are able to access the user interface controls from your worker thread. We'll take a look at another example that will bring all of these concepts together to illustrate executing a long running task on a seperate thread with a progress bar that updates the user interface via the Dispatcher object. The example The example is a WPF application.  The main window contains the following controls; lstRandomValues A ListBox control that will hold random values that are generated during the long running process. The pupose of this control is to illustrate the responsiveness of the user interface during the long running process. prgProgress A ProgressBar control that will illustrate the progress of the long running task. The ProgressBar is hidden by default. It's shown when the long running process begins and is hidden again when the process has ended or is canceled. txtProgress A TextBox control that displays the long running process percentage of completion. btnCancel A Button control that will cancel the long running process and in turn hide the progress bar and progress textbox. btnInteract A Button control that will launch a MessageBox to illustrate the responsiveness of the UI while the long running process is executing. btnBegin A Button control that will begin the long running process. And here is the code  Window1.xaml <Window x:Class="RandomNameSpace.ViewModels.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="400" Width="400"> <!-- Parent Grid --> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox Grid.Row="0" Grid.Column="0" Name="lstRandomValues" Grid.ColumnSpan="2" /> <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" x:Name="bdrProgress" Visibility="Hidden" Background="Azure" CornerRadius="10" BorderBrush="DarkGray" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel> <Grid Margin="5"> <ProgressBar x:Name="prgProgress" Width="200" Height="20" Minimum="0" Maximum="1" /> <TextBlock x:Name="txtProgress" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right" Margin="3" Click="btnCancel_Click" /> </StackPanel> </Border> <Button Grid.Row="1" Grid.Column="1" x:Name="btnInteract" HorizontalAlignment="Center" Content="Interact with UI" Click="btnInteract_Click" Height="23.96" /> <Button Grid.Row="1" Grid.Column="0" x:Name="btnBegin" HorizontalAlignment="Left" Content="Start Long Process" Click="btnBegin_Click" Height="23.96" Margin="35,33.27,0,33.27" /> </Grid> </Grid> </Window> Window1.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; using System.Windows.Threading; namespace RandomNameSpace.ViewModels { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { private bool IsCanceled = false; private RandomViewModel _viewModel; public RandomViewModel ViewModel { get { return _viewModel; } set { _viewModel = value; } } public Window1() { InitializeComponent(); PrepareViewModel(); } private void PrepareViewModel() { ViewModel = new RandomViewModel(); this.lstRandomValues.DisplayMemberPath = "Value"; this.lstRandomValues.DataContext = ViewModel; this.lstRandomValues.ItemsSource = ViewModel; } private void btnBegin_Click(object sender, RoutedEventArgs e) { BeginProcess(); } private void btnInteract_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Interaction!"); } private void btnCancel_Click(object sender, RoutedEventArgs e) { CancelProcess(); } public void BeginProcess() { bdrProgress.Visibility = System.Windows.Visibility.Visible; DisableBeginButton(); Action StartLoop; StartLoop = () => DoLongRunningProcess(); Thread t; t = new Thread(StartLoop.Invoke); t.Start(); } public void CancelProcess() { this.IsCanceled = true; Thread.Sleep(1500); ClearListBox(); EnableBeginButton(); } private void ClearListBox() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.Clear(); }, null); } private void DoLongRunningProcess() { for (var loopCounter = 0.0; loopCounter < 1.0; loopCounter = loopCounter + .1) { if (!IsCanceled) { //add a random number to the viewmodel collection to be bound to the listview Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.AddValue(1564); }, null); UpdateProgressBar(loopCounter); Thread.Sleep(2000); } else { break; } } IsCanceled = false; ClearListBox(); MessageBox.Show("Completed"); EnableBeginButton(); HideProgressBar(); } private void EnableBeginButton() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, true); }, null); } private void DisableBeginButton() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, false); }, null); } private void UpdateProgressBar(double value) { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.prgProgress.SetValue(ProgressBar.ValueProperty, value); }, null); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtProgress.SetValue(TextBlock.TextProperty, (value * 100).ToString()); }, null); } private void HideProgressBar() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.bdrProgress.SetValue(Border.VisibilityProperty, Visibility.Collapsed); }, null); } } }   RandomValue.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace RandomNameSpace.ViewModels { public class RandomValue : INotifyPropertyChanged { private int _value; public int Value { get { return _value; } set { if (_value != value) _value = value; OnPropertyChanged("Value"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } RandomViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace RandomNameSpace.ViewModels { public class RandomViewModel : ObservableCollection<RandomValue> { public RandomViewModel() : base() {} public void AddValue(int value) { Random rnd = new Random(); var calculatedValue = (value * rnd.Next(3000)); this.Add(new RandomValue { Value = (calculatedValue) }); } } } Here is the entire solution for download.  WPFAsyncProgressBarMVVM.zip (77.39 kb)   This concludes the article.  Thank you for taking the time to read it! Until next time... ~/Buddy James kick it on DotNetKicks.com    


How to list local Windows System Services and their dependencies using WPF DataBinding and MVVM

The example I wrote this example in an effort to monitor the Windows Services that are installed on my system at any given time.  I decided to kill two birds with one stone and learn a bit about MVVM, DataBinding, and WPF in the process.  I'll start by showing you a class diagram of the solution.  I'll follow with providing all of the source code snippets for your review.  Finally, I'll explain the application and provide a link for you to download the complete solution. Malware and Windows Services I've learned that Malware as well as viruses often disguise themselves as "normal" Windows services to take advantage of automatic/delayed starting capabilities.  Windows services are also an ideal place for degenerates to place their malicious code because most of your typical Windows users don't take a second look here for problems. Windows Services And here is a screen shot of the application that I wrote to explore the many facets of WPF databinding. As you can see, the application simply lists all Windows service names, Display names, and their dependent services.  The goal was to perform a google search when double clicking a service (you can add this if you like, it's probably about 3 lines of code).  I thought I could easily google suspicious looking services to find any problematic applications.  The ServiceController[] array The .NET framework class library contains an object that describes a Windows Service and it's called the ServiceController.  I decided that I would create a wrapper around this ServiceContoller array with my own object so that I could implement ObservableCollection<> as well as INotifyPropertyChanged to make the collection of objects play nice with WPF's DataBinding.  Here is a class diagram that illustrates the entire application.                   And here's the code.... WindowsService.cs (a wrapper to ServiceController) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; namespace WindowsServiceMonitor { /// <summary> /// The purpose of this class is to serve as a wrapper class to the /// ServiceController. This class provides propertychange notification /// to allow databinding with WPF. /// </summary> public class WindowsService : INotifyPropertyChanged { #region "private members" private string _serviceName; private string _displayName; private WindowsServiceCollection _dependentServices; #endregion #region "INotifyPropertyChanged event" /// <summary> /// Facilities property change notification and WPF databinding /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// This method is called when any property is changed /// </summary> /// <param name="info"></param> protected void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } #endregion #region "Public constructors" /// <summary> /// Overloaded constructor /// </summary> /// <param name="serviceName">The short name of the service</param> /// <param name="displayName">The friendly display name of the service</param> /// <param name="dependentServices">An observable collection of windows services</param> public WindowsService(string serviceName, string displayName, WindowsServiceCollection dependentServices) { _serviceName = serviceName; _displayName = displayName; _dependentServices = dependentServices; } /// <summary> /// Default constructor /// </summary> public WindowsService() { } #endregion #region "Public Properties" /// <summary> /// The short name of the service /// </summary> public string ServiceName { get { return _serviceName; } set { _serviceName = value; OnPropertyChanged("ServiceName"); } } /// <summary> /// The friendly display name of the service /// </summary> public string DisplayName { get { return _displayName; } set { _displayName = value; OnPropertyChanged("DisplayName"); } } /// <summary> /// An observable collection of windows services /// </summary> public WindowsServiceCollection DependentServices { get { return _dependentServices; } set { _dependentServices = value; OnPropertyChanged("DependentServices"); } } /// <summary> /// override the object tostring method to return the service name /// </summary> /// <returns></returns> public override string ToString() { return _serviceName; } #endregion } } WindowsServiceCollection.cs (A wrapper to ServiceController[] which inherits ObservableCollection<>) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.ServiceProcess; using System.Text; namespace WindowsServiceMonitor { /// <summary> /// A WPF friendly collection of WindowsService objects /// </summary> public class WindowsServiceCollection : ObservableCollection<WindowsService> { /// <summary> /// Default constructor /// </summary> public WindowsServiceCollection() : base() { } /// <summary> /// Add all windows services to this collection object /// </summary> /// <param name="windowsServices">The current windows service</param> public void LoadServices(ServiceController[] windowsServices) { try { //loop through each root level service dependency foreach (ServiceController service in windowsServices) { //create a new WPF friendly windows service object WindowsService windowsService; windowsService = new WindowsService(); //Set the service properties windowsService.ServiceName = service.ServiceName; windowsService.DisplayName = service.DisplayName; try { //recursivley build the service depdencies WindowsServiceCollection.BuildDependentServiceHierarchy(windowsService, service.DependentServices); } catch (InvalidOperationException exception) { //I've received unable to open ___ service on the computer //I'll use an empty catch until i research the issue. var operationExceptionMessage = exception.Message; } catch (Exception exception) { var generalExceptionMessage = exception.Message; } //add the WPF friendly service to this Observable service collection Add(windowsService); } } catch (Exception ex) { var message = ex.Message; } } /// <summary> /// recursivley build the service depdencies /// </summary> /// <param name="service">the WFP friendly windows service wrapper</param> /// <param name="dependentServices">The collection of windows service dependencies</param> /// <returns></returns> public static void BuildDependentServiceHierarchy(WindowsService service, ServiceController[] dependentServices) { //if we don't have a valid service object if (service == null) //alert the caller throw new NullReferenceException("Invalid service object."); //loop through each dependent service foreach (ServiceController dependentService in dependentServices) { WindowsService dependentServiceWrapper = new WindowsService(dependentService.ServiceName, dependentService.DisplayName, new WindowsServiceCollection()); //build the current service's dependencies WindowsServiceCollection.BuildDependentServiceHierarchy(dependentServiceWrapper, dependentService.DependentServices); //if the depdent services collection has yet to be created if (service.DependentServices == null) //create a new observable collection of dependent services service.DependentServices = new WindowsServiceCollection(); //add the depdency to the wrappers dependents collection service.DependentServices.Add(dependentServiceWrapper); } } } } ServiceMonitorViewModel.cs (This is the ViewModel and it basically loads all ServiceContoller classes and builds the corresponding WindowsServiceCollections and serves the data to the WPF MainWindow view via DataBinding.) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.ServiceProcess; using System.Windows.Data; namespace WindowsServiceMonitor.ViewModels { public class ServiceMonitorViewModel { private ServiceController[] _serviceControllers; private WindowsServiceCollection _observableServices; public ServiceMonitorViewModel() { this.LoadSystemServices(); this.ObservableWindowsServices = new WindowsServiceCollection(); this.ObservableWindowsServices = _observableServices; //this.ObservableWindowsServices.Source = _observableServices; } public WindowsServiceCollection ObservableWindowsServices { get; set; } private void LoadSystemServices() { _serviceControllers = ServiceController.GetServices(); _observableServices = new WindowsServiceCollection(); _observableServices.LoadServices(_serviceControllers); } } } And finally we have MainWindow.xaml which is our WPF view. <Window x:Class="WindowsServiceMonitor.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewModel="clr-namespace:WindowsServiceMonitor.ViewModels" Title="MainWindow" SizeToContent="WidthAndHeight" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"> <Window.Resources> <viewModel:ServiceMonitorViewModel x:Key="WindosServicesViewModel"/> <Style TargetType="ListBoxItem"> <Setter Property="FontFamily" Value="Verdana" /> <Setter Property="FontSize" Value="12"></Setter> <Setter Property="Padding" Value="10"></Setter> </Style> <DataTemplate x:Key="DetailTemplate"> <Border Margin="20" BorderBrush="Aqua" BorderThickness="1" Padding="8"> <Grid ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" > <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Service Name:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=ServiceName}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Display Name:"/> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=DisplayName}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="Dependents:"/> <ListBox Name="lstDependentServices" Grid.Row="2" Grid.Column="1" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=DependentServices}" DisplayMemberPath="DisplayName" /> </Grid> </Border> </DataTemplate> </Window.Resources> <DockPanel> <StackPanel> <TextBlock>Windows Services</TextBlock> <ListBox Name="lstServices" HorizontalAlignment="Stretch" Height="300" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Center" VerticalAlignment="Stretch" DataContext="{Binding Source={StaticResource WindosServicesViewModel}}" ScrollViewer.VerticalScrollBarVisibility="Auto" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ObservableWindowsServices}"/> <TextBlock Grid.Row="0" Grid.Column="0" Text="Service Properties" /> <ContentControl DataContext="{Binding Source={StaticResource WindosServicesViewModel}}" Content="{Binding ObservableWindowsServices}" ContentTemplate="{StaticResource DetailTemplate}" /> </StackPanel> </DockPanel> </Window> And that about wraps it up.  Please note that each WindowsServiceCollection contains a WindowsServiceCollection of dependent windows services.  Also notice the many different uses of WPF databinding.  We bind the root level WindowsServiceCollection to a ListView and we bind  some TextBlocks to it's selection so that way when the user clicks to select a service, we can display a details view of the specified service. That's pretty much all there is to it.  I can say that I learned a lot by writing this application and I had a lot of fun as well. Here is a link to the entire solution for you to download WindowsServiceMonitor.zip (2.92 mb)  I hope you have enjoyed this post and I hope you will check back soon! Thanks! ~/Buddy James     kick it on DotNetKicks.com  


.NET Design Patterns : The decorator pattern. Adding new behavior to your existing objects.

  .NET Design Patterns series: Part 1 The Decorator pattern   A brief introduction to software design patterns Hello and welcome to my first article in a series on design patterns.  A design pattern is simply a documented solution to a common software design problem.  This idea is extremely useful in the world of software development.  When designing and writing code, chances are whatever your task may be, someone has already accomplished what you've been tasked to do.  In fact, many developers have probably accomplished the task at hand.  Why reinvent the wheel?  There are many benefits to practicing and using design patterns. Industry standards Design patterns are deeply ingrained in the world of software development.  As such, you can look at tried and tested design patterns as "best practices".  If you practice and understand solutions that are accepted by the software development community, your software solutions will improve as a result. Efficient Communication Design patterns are defined and described using a unified set of terms.  As you practice design patterns, you will master these terms and in effect, you will be able to communicate much more effiecently with other developers.  You will spend less time trying to describe a potential design when you understand how to describe the concepts clearly by using a unified terminology.  As a result, other junior developers on your team will be more likely to try to learn design patterns which will make your overall team more efficient. Brief history of design patterns Kent Beck and Ward Cunningham began experimentation with design patterns in the context of computer science in the year 1987.  Most of the works on design patterns have been based on their works. Popular books on design patterns Design Patterns: Elements of Reusable Object-Oriented Software Patterns of Enterprise Application Architecture. Pattern-Oriented Software Architecture, Volume 1: A System of Patterns Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects Pattern #1: The Decorator pattern, Adding new behavior to existing objects I've decided to start this series with patterned called the Decorator pattern.  I suppose it's best to start with the formal definition of the pattern. The Decorator Pattern attaches additional responsibilities to an object dynamically.  Decorators provide a flexible alternative to subclass for extending functionality. Too much inheritance can be a bad thing  Inheritance is an important part of object oriented design.  However, just like anything else, too much subclassing can be a bad thing.  The idea behind a great object oriented application is to design your objects with change and reuse in mind.  If you find yourself creating 20+ subclasses of an abstract class, you may want to step back and look at your design.  With each new subclass that you design, there's a another class that you must maintain and change.  Remember, to always design your classes to be Open for extension, closed for modification.  This makes for easier maintienence and flexible designs. The Decorator pattern allows you to add behavior to existing classes at run time through object composition.  This means we create a class to "decorate" another class with new functionality.  The class to be decorated would be passed into the decorator object's constructor and the reference would be stored as a field.  This process can be repeated to achieve new functionality when calling the common contract of the class to be decorated. The article example Imagine the idea of an article.  There are many different types of articles.  There are news paper articles, blog articles, code project articles, magazine articles.  The list goes on and on.  In the age of electronic articles, it would be handy to write an article class and provide a post method.  The post method would contain any external site API calls required to publish the article to it's destination.  When posting an article, you may want to accomplish other tasks at the same time, such as advertise the article.  Perhaps you'd like to advertise your new article via Twitter.   OOP Principals: Open for extension and closed for modification You could add the code to tweet your new article right into your the article base class, however, this would go against our Object Oriented design princiapl "Open for extension, closed for modification".  Wouldn't it be better to add this new behavior to our articles at run time?  The decorator pattern allows us to do just that!   Examine the following class diagram.  And here is the code.. Article.cs   using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// Defines the methods and properties required for an article to be posted on the web. /// </summary> public abstract class Article { #region "properties" public string Title { get; set; } public string Url { get; set; } public string Body { get; set; } public string Author { get; set; } #endregion #region "methods" /// <summary> /// Provides a method to "Post" the article to it's destination. /// </summary> public abstract void Post(); #endregion } } Decorator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// This interface takes an /// </summary> public abstract class Decorator : Article { //Holds a reference to the componoent to be decorated //in this case an article. protected Article _article; /// <summary> /// A emthod to provide the article to be extended. /// </summary> /// <param name="article">The article in which to add new behavior</param> public void SetArticle(Article article) { _article = article; } /// <summary> /// Implementation of the base classes' post method which calls the /// referenced article's post method as well. /// </summary> public override void Post() { if (_article != null) { _article.Post(); } } } } CodeProjectArticle.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// Represents an article to be posed to codeproject.com /// </summary> public class CodeProjectArticle : Article { public CodeProjectArticle() { } /// <summary> /// This would normally contain any calls to post the article to the codeproject.com automatically /// </summary> public override void Post() { Console.WriteLine("Posting the article {0} to {1}", this.Title, this.Url); Console.WriteLine(); } } } Tweetable.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// This interface takes an /// </summary> public class Tweetable : Decorator { //Holds a reference to the componoent to be decorated //in this case an article. protected Article _article; public Tweetable(){ } /// <summary> /// A emthod to provide the article to be extended. /// </summary> /// <param name="article">The article in which to add new behavior</param> public Tweetable(Article article) { _article = article; } /// <summary> /// Implementation of the base classes' post method which calls the /// referenced article's post method as well. /// </summary> public override void Post() { base.Post(); if (_article != null) { _article.Post(); } TweetArticle(); } public void TweetArticle() { if (_article != null) { Console.WriteLine("Tweeting about your recent article posting entitled {0}", _article.Title); Console.WriteLine(); } } } } BlogPost.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { public class BlogPost : Tweetable { protected Article _article; public BlogPost() { } public BlogPost(Article article) { _article = article; } public override void Post() { base.Post(); Console.WriteLine("Posting a personal blog called {0} to my personal blog site {1}.", this.Title, this.Url); Console.WriteLine(); } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { public class Program { public static void Main(string[] args) { //Create an instance of our code project article CodeProjectArticle codeProjectArticle = new CodeProjectArticle { Title = "Code Project Article: Why learn Assembly language?", Author = "Buddy James", Body = "All of the article's body would go here.", Url = "http://www.codeproject.com/Articles/89460/Why-Learn-Assembly-Language" }; codeProjectArticle.Post(); BlogPost personalBlogPost = new BlogPost { Title = "The Decorator pattern. How to extend the behavior of your existing objects", Author = "Buddy James", Body = "All of the article's contents would go here.", Url = "http://www.refactorthis.net" }; //Lets post a tweet when we post our blog article Tweetable TweetBlogPost = new Tweetable(personalBlogPost); TweetBlogPost.Post(); Console.ReadLine(); } } } I've attached the entire solution so that you can see how it works.  You can download the solution Here DecoratorPatternApplication.zip (78.94 kb)   Notice that the post and tweet methods contain calls to Console.WriteLine().  Obviously in a real scenario these methods would contain calls to actually "post" or "publish" the  article. I hope you've enjoyed my first of many articles on design patterns. Thanks and keep reading! ~/Buddy James kick it on DotNetKicks.com  


About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List