Infragistics JQuery controls

Xamarin releases cross platform starter kit. Example includes MVVM, SQLite, and more!

  Xamarin has released a cross platform starter kit for iOS, Android, and WinRT.  The application is a field service application that utilizes MVVM, the Xamarin.Mobile library for cross platform access to the camera, SQLite for storage, and much more! You can find the complete source code and other details here at the Xamarin official blog. Buddy James

C# 5.0: INotifyPropertyChanged with the [CallerMemberName] attribute

WPF/Silverlight and the INotifyPropertyChanged interface Greetings and welcome to another post on Today's topic is about an interface that all WPF and Silverlight developers have grown to love.  The INotifyPropertyChanged interface facilitates notifying the data binding mechanisms of WPF and Silverlight of a property value change in your ViewModel to your view.  Here is a simple illustration.   ClassicViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INotifyPropertyChangedExample { public class ClassicViewModel { private string _personName; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get; set { if (value != _personName) _personName = value; //No type safety here. If you make a mistake you will have problems. OnPropertyChanged("PersonName"); } } public void OnPropertyChanged(string property) { if (property == null) throw new ArgumentNullException("property"); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } When calling the method to raise the property changed event, you would need to pass the property name as a string to the handler.  If you made any mistake in typing the property name, you would have to take time to debug your data binding. A new and improved solution C# 5.0 has provided some nifty compiler level attributes to assist with this scenario. The [CallerMemberName] attribute of the System.Runtime.CompilerServices namespace can be used as an optional method parameter.  When a method is called and there is no value specified for the parameter that is decorated with this attribute, you are provided with the name of the member that called the method.  This takes the risk of a typing mishap out of your hands and allows you to rely on the compiler to provide this information to you!  Here is an updated example! ImprovedViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace INotifyPropertyChangedExample { public class ImprovedViewModel : INotifyPropertyChanged { private string _personName; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return _personName; } set { if (value != _personName) _personName = value; OnPropertyChanged(); } } public void OnPropertyChanged([CallerMemberName] string property = null) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } }   As you can see, this is a great little addition to the C# language that will make your life a little easier. I'd like to thank Patrick Steel for his article in MSDN magazine that inspired this article.  Please check out his article for more uses of this and other new attributes and features of the C# 5.0 language. kick it on

Implementing a re-sizable composite view user interface using the MVVM pattern, the GridSplitter, and WPF UserControls.

  A composite view user interface In the world of WPF, the Model-View-ViewModel pattern is a great way to separate your UI from your business logic.  This decoupling allows you to easily unit test your code.  When implemented correctly, the MVVM pattern promotes a view agnostic structure which makes switching between different views extremely easy.  A composite view UI is basically a user interface that is made up of multiple independent views.  By independent, I mean that the views should be decoupled and unaware of each other.  In this tutorial, I will show you how to create the following UI.     Existing frameworks There are several existing frameworks that facilitate the implementation of the MVVM pattern and composite view applications.  MVVM Toolkit, MvvMLight, SoPrism, and Prism are a few examples of some of the existing libraries out there.  Prism is probably the most complete and extensive but it also has a large learning curve.  I decided that before I dive into learning the details of Prism, I would benefit by trying to code a composite application by hand.  The User Interface design The previous screen shot shows an application made up of a Window that contains a grid, a listview, and a ContentControl.  The ContentControl and ListView are separated by a GridSplitter control.  This allows the two views to be re-sized.  The ContentControl will have a UserControl injected into the content property as the ListView's selected item is changed. Here is the XAML markup <Window x:Class="OutlookLayoutPresenter.MainWindow" xmlns="" xmlns:x="" xmlns:views="clr-namespace:OutlookLayoutPresenter.Views" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="128*" /> <ColumnDefinition Width="375*" /> </Grid.ColumnDefinitions> <ListView SelectionChanged="lstMenu_SelectionChanged" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MenuDisplayText" x:Name="lstMenu"> </ListView> <ContentControl Grid.Column="1" Content="{Binding Path=Presenter.CurrentView}" x:Name="MainContent"> </ContentControl> <GridSplitter Grid.Column="1" Width="2" HorizontalAlignment="Left" /> </Grid> </Window> As you can see, we have a Grid with two columns.  The column on the left holds a ListView that that is data bound in the code behind.  The ContentControl's content property is also data bound to the Presenter.CurrentView property of our ViewModel.  I chose to implement a presenter object to handle the injection of the UserControl into the ContentControl.  We will start with the codebehind of our view to show how we are setting the DataContext. 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 OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private MainWindowViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainWindowViewModel(); this.DataContext = _viewModel; lstMenu.ItemsSource = _viewModel; } void lstMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { var menuItem = (ViewMenuItems)e.AddedItems[0]; _viewModel.Presenter.DisplayView(menuItem); } } } Note that we have bound our ViewModel to the view's DataContext as well as the ListView's ItemsSource property.  The ViewModel is an ObservableCollection of ViewMenuItem objects.  I created the ViewMenuItem class to contain the region's name and the display text.  The ListView serves as a menu.   Here is the code for the ViewMenuItem class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace OutlookLayoutPresenter { public class ViewMenuItems : INotifyPropertyChanged { private string _regionName; private string _menuDisplayText; public string RegionName { get { return _regionName; } set { if (_regionName == value) return; _regionName = value; OnPropertyChanged("RegionName"); } } public string MenuDisplayText { get { return _menuDisplayText; } set { if (_menuDisplayText == value) return; _menuDisplayText = value; OnPropertyChanged("MenuDisplayText"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } When looking at the ViewModel, please be sure to note the public Presenter property that is used in the data binding of the ContentControl. The ObservableCollection of ViewMenuItem objects builds the ListView menu. Here's the ViewModel's code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; namespace OutlookLayoutPresenter { public class MainWindowViewModel : ObservableCollection<ViewMenuItems> , INotifyPropertyChanged { private IPresenter _presenter; public IPresenter Presenter { get { return _presenter; } set { _presenter = value; OnPropertyChanged("Presenter"); } } public MainWindowViewModel () { this.Add(new ViewMenuItems{RegionName = "RegionOne", MenuDisplayText = "Content One"}); this.Add(new ViewMenuItems{RegionName = "RegionTwo", MenuDisplayText = "Content Two"}); this.Add(new ViewMenuItems{RegionName = "RegionThree", MenuDisplayText = "Content Three"}); this.Presenter = new MainWindowPresenter(); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } All that's left now is the MainWindowPresenter class which will dynamically load one of three user controls based on the ListView's selected item. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Controls; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// This is the presenter class for the main Shell. the purpose of this /// class is to contain all of the UI event handlers for the main shell view. /// </summary> public class MainWindowPresenter : INotifyPropertyChanged, IPresenter { ContentControl _currentView = new ContentControl(); public ContentControl CurrentView { get { return _currentView; } set { _currentView = value; OnPropertyChanged("CurrentView"); } } public void DisplayView(ViewMenuItems item) { switch (item.RegionName.ToUpper()) { case "REGIONONE": this.CurrentView.Content = new ContentOne(); break; case"REGIONTWO": this.CurrentView.Content = new ContentTwo(); break; case "REGIONTHREE": this.CurrentView.Content = new ContentThree(); break; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } There are three user controls that have a different background color and text.  I will show the markup for one of the controls for brevity. <UserControl x:Class="OutlookLayoutPresenter.Views.ContentOne" xmlns="" xmlns:x="" xmlns:mc="" xmlns:d="" mc:Ignorable="d" Background="Blue"> <Grid> <TextBlock FontWeight="Bold" Foreground="White" Text="Content One" /> </Grid> </UserControl>   As you click on each menu item, the content view will change colors and text.  I've included the source code for your reference. (93.27 kb)   This concludes the tutorial.  Thanks for reading! Until next time... Buddy James kick it on      

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="" xmlns:x="" xmlns:viewModel="clr-namespace:WindowsServiceMonitor.ViewModels" Title="MainWindow" SizeToContent="WidthAndHeight" xmlns:mc="" xmlns:d="" 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 (2.92 mb)  I hope you have enjoyed this post and I hope you will check back soon! Thanks! ~/Buddy James     kick it on  

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 (, 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