Infragistics WPF controls

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  


WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.

    WPF Validation for mere mortals I've recently jumped on the WPF bandwagon and I've fallen in love with this technology.  XAML is a fascinating animal indeed.  The declarative nature of the language leaves much to be explored.  There are many ways to solve the same problem.  On my quest for knowledge, I've been researching the intrinsic validation functionality of WPF.  Unfortunately, most every example I've ran across on blog posts and codeproject.com have been a bit too complex for my blood.  I find often that you need learn other subjects before you can begin to understand how the validation works.  Don't get me wrong, the examples are really nice.  However, when I'm learning something, I want a straight to the point example of the topic at hand.  It's with this idea in mind that I bring you a simple tutorial on WPF validation. I will be illustrating this example using the MVVM (Model-View-ViewModel) Pattern.   Click here to download the entire source WPFMVVMValidation.zip (74.08 kb)  Consider the following code  The view MainWindow.xaml <Window x:Class="ExceptionValidation.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewModel="clr-namespace:ExceptionValidation" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> <TextBlock>Enter total amount</TextBlock> <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> <Binding.ValidationRules> <ExceptionValidationRule></ExceptionValidationRule> </Binding.ValidationRules> </Binding> </TextBox> <Button Content="Button" Height="28" Name="button1" Width="84" /> </StackPanel> </Window>     The viewmodel MainWindowViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { class MainWindowViewModel : ObservableCollection<Product> { public MainWindowViewModel() { Add(new Product { TotalAmount = 3 }); } } }   The model Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { public class Product : INotifyPropertyChanged , IDataErrorInfo { public event PropertyChangedEventHandler PropertyChanged; private int _totalAmount = 5; public int TotalAmount { get { return _totalAmount; } set { _totalAmount = value; OnPropertyChanged("TotalAmount"); } } public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } } } A brief introduction to MVVM  As you can see, we have a XAML view, a viewmodel class, and a model.  The Model is a representation of an object's data.  In this instance, we are modeling a Product.  The viewmodel is an object that handles the change notification between properties in the model and elements on the view.  XAML properties, events, and bindings have the ability to tunnel (down the tree) as well as bubble (up the tree).   Binding the ViewModel to the view. In order to bind the ViewModel to the view, we must make it accessible to the view via XAML.  To accomplish this, we first have to import the namespace in which the viewmodel exists.  Examine the following code. xmlns:viewModel="clr-namespace:ExceptionValidation" Here is the equivalent in c# using ExceptionValidation; Once we've imported the namespace for use, we then need to define our MainWindowViewModel as a Resource of the current window. <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> This allows us to declare an instance of the MainWindowViewModel class by using the associated Key "mainViewModel". Binding the ViewModel As stated before the ViewModel acts as a "go between" for the View and the Model.  In order for the view model to communicate with our XAML view, we will bind the ViewModel to the StackPanel's DataContext. <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> XAML's ability to tunnel properties down from parent to child will allow each element inside the stack panel to make use of the DataContext binding that we've just setup using the Window resource's key mainViewModel. ObservableCollection<T> The viewmodel inherits from ObservableCollection<Product>.  The ObservableCollection<T> generic class represents a collection that can be utilized by WPF databinding.  This is possible because the ObservableCollection<T> class raises an event when items are added and removed from the collection. INotifyPropertyChanged The model implements the INotifyPropertyChanged interface.  This interface provides an event in which to fire any time a model property is changed.  This event notifies the bound element in the view that the property has changed. public event PropertyChangedEventHandler PropertyChanged;   public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } }   IDataErrorInfo The magic behind WPF validation comes from the implementation of the IDataErrrorInfo interface.  The interface implements the following members.  The this[columnName] indexer implements the logic of the validation rule. //Not used by WPF public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } The following XAML code binds the TotalAmount property of the first Product in the viewmodel's internal collection to the Text property of the TextBox element.  The ValidatesOnDataErrors attribute tells the textbox binding to raise an event when there is a valadation error.  When the event is raised, the bound element's template is changed to a new visual style that places a Red rectangle around the border of the TextBox.  When the error is corrected, the original template is restored.  Binding.ValidatesOnDataErrors <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> </Binding> </TextBox> In the provided example, if you enter a value greater than 10 into the text box and tab out of the textbox, you will see that an error is raised causing the red outline around the textbox.  If you correct the error by replacing the value with a number less than 10, the red outline will disappear. This concludes my tutorial on WPF validation.  This is the very basic of validation methods.  There are many other advanced tutorials on the subject.  My next tutorial will involve utilizing custom validation attributes from the System.ComponentModel namespace to handle WPF view validation. Thanks for 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