Infragistics JQuery 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="" 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  

.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 /// </summary> public class CodeProjectArticle : Article { public CodeProjectArticle() { } /// <summary> /// This would normally contain any calls to post the article to the 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 = "" }; 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 = "" }; //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 (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  

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 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 (74.08 kb)  Consider the following code  The view MainWindow.xaml <Window x:Class="ExceptionValidation.MainWindow" xmlns="" xmlns:x="" 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  

Learning ILAsm, the backbone of .NET

Who cares about ILAsm or x86 assembly language anyway? I'm sure a lot of you are wondering why anyone would care about learning ILAsm.  It's not like you ever see it unless you disassemble an application.  ILasm or MSIL is the human readable translation of Microsoft .NET intermediate language.  ILAsm is a lot like classic assembly language.  It is a low level programming language that allows you to write programs one instruction at a time with a very minimal syntax.  I've explained the benefits of learning assembly language in my previous post, Why Learn Assembly Language.  In a nutshell, if you learn .NET at the low level of IL, you will have an understanding of what makes any .NET language tick.  You will have the knowledge to disassemble any .NET binary and debug your software at the instruction level.   This post is my first tutorial on writing code in ILAsm.  I hope you'll join me and become proficient in this language of kings.  You will have an edge over the competition and it will change the way you look at high level coding.  Enough talking, let us code! How to compile ILasm If you are a .NET developer, you most likely have an ILasm compiler on your computer which by the way is appropriately named ILasm.exe.  Simply launch the Visual Studio Command Prompt, navigate to the folder that you create your IL files and issue the following command. ilasm.exe is fine if you like to write code in notepad and drop out to a command prompt to write your code.  I myself prefer an IDE.  Visual Studio is an amazing IDE but for some reason the people over at Microsoft didn't see it fit to add support for ILasm into the product.  Never fear!  There is a free, open source alternative that is nearly identical to Visual Studio and it allows you to create and compile IL projects with syntax highlighting that works on Linux, Windows, and Mac OSX!  What is this application you ask? MonoDevelop   "Hello... World?" I know, I know, it's a tired, worn out cliche but far be it from me to interrupt the order of the programming gods and illustrate a programming language without starting with the infamous "Hello World!" example. //import the mscorlib assembly to give us access to Console and other basic classes .assembly extern mscorlib{} //define our assembly .assembly HelloAssembly { //define the version of this assembly .ver 1:0:0:0 } //define the executable module .module helloworld.exe //defin our main method .method static void main() cil managed { //set up the stack. In ILAsm, all values are placed on the stack and then manipulated. //here we will allocate memory for one value to be on the stack at a given time .maxstack 1 //define the main entry point to the application .entrypoint //load the emphamis phrase on the stack ldstr "Hello ILAsm!" //print the string from the stack to the console call void [mscorlib]System.Console::WriteLine(string) //return to end the program ret } If you have never seen asm or ILasm, I can imagine how strange this code snippet may look.  As I've stated before, ILasm is a very cryptic, low level language.  Let's breakdown the application. We start by importing the mscorlib library which contains much of the base .NET classes.  As the comments state, this library gives us access to the System.Console object.   Next, we define the assembly for our program.  All .NET executables are called assemblies.  Here we name our assembly as well as set a version number.  After we define our assembly, we define the executable module.  This is required in any ILasm application.   Now it's time to define our main method that performs the loading and printing of the string.  We start by defining the maxstack, that is, the maximum number of values that can be held in memory at a given time.  In ILAsm, you push values on the stack, perform operations on the values or use them as parameters to methods.  Since we have a maxstack of one, that means we can have only one piece of data to work with at any given time.  We use ldstr to load a string onto the stack.  If we were to load another string on the stack directly after the first ldstr call, the application will simply push the first value out of memory and the new string will be available to access. Finally, we call the WriteLine method on the System.Console object and we tell it to use the current string on the stack as it's input source.   So now you can load a string onto the stack and display it.  It's pretty interesting, although very limited as well.  How about we work with more than one value?  Let's try adding two numbers! Sum it up //reference to mscorlib .assembly extern mscorlib {} //define our assembly .assembly MiniCalculator { //the assembly version number .ver 1:0:0:0 } //create the required module .module MiniCalculator.exe //define our main method .method static void main() cil managed { //we plan to work with two integers this time .maxstack 2 //the main entry point to our application .entrypoint //load a string of instructions on the stack ldstr "OK. Class is in session. Who can tell the class what is the sum of 2 + 2? That's right, the answer is " //display the instructions to the user call void [mscorlib]System.Console::Write (string) //put the number 2 on the stack. Currently the previously loaded string, and the //number 2 are both on the stack. ldc.i4 2 //when we move another integer to the stack, this pushes the string off //now we have two instances of the number 2 on the stack ldc.i4 2 //add will add the two numbers on the stack and store the result add //lets tell the computer to look for an int on the stack and print it to the console call void [mscorlib]System.Console::Write (int32) //return to exit the application ret } We start the application as before by importing mscorlib, defining our assembly and module, and creating the method to perform our work.  We then load a string on the stack and use Console's WriteLine method to display the string.  We then load two integers onto the stack, pushing the string off of the stack.  We call add whichs adds the two integers and stores the result on the stack.  We use Console's WriteLine once again to display the answer. This concludes part one of my ILasm tutorial series. Please check back soon for my next installment in which we will tackle data types, loops, and classes! Until next time.. ~/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