Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

WMI (Windows Management Instrumentation) in C#

without comments

In my previous post, I had written about ManagementEventWatcher with some WMI querries. In this post we will try to figure out what this WMI is.

WMI stands for Windows Management Instrumentation. Its a set of functionalities provided by the OS (Windows) for the applications to control / manage the administrative tasks (check this out for a formal definition).

For example, if you wanna retrieve information about the CDROM drive on a machine, you can write some simple queries in c# and get that job done.

Using WMI in C#

Its fairly simple  in C# to use WMI infrastructure services. C# comes with a class called, ManagementObjectSearcher with which we can query for any information. Lets take the fore mentioned example, the CDROM example. To get information about the CDROM,

  1. Create a WqlObjectQuery object with the query statement, SELECT * FROM Win32_CDROMDrive

    WqlObjectQuery aWMIQuery = new WqlObjectQuery("SELECT * FROM WIN32_CDROMDrive");
  2. Create an object of ManagementObjectSearcher and assign the created query to this object
    ManagementObjectSearcher aManagementObjectSearcher = new ManagementObjectSearcher();
    aManagementObjectSearcher.Query = aWMIQuery;
  3. Run the query by calling the Get method in the ManagementObjectSearcher
    aManagementObjectSearcher.Get();
  4. The Get() method returns a ManagementObjectCollection. Iterate thru’ it to get the reults of the query. Each ManagementObject’s Properties field (ManagementObject.Properties) will contain a PropertiesDataCollection. Iterate thru’ this for additional results on the query
    foreach (ManagementObject aObject in aObjectSearcher.Get())
    {
      Console.WriteLine(aObject.Properties.ToString());
      foreach (PropertyData aProperty in aObject.Properties)
      {
        Console.Write("\t");
        Console.WriteLine(aProperty.Name + "----->" + aProperty.Value);
      }
      Console.WriteLine();
    }
  5. Change the query according to your need. You can query USB Drive information, Hard Disks, Processes and so on. Check out the MSDN for the list of WMI classes

Written by sudarsanyes

June 25th, 2009 at 2:26 pm

ManagementEventWatcher and WqlEventQuery in c#

with one comment

Yesterday, I was searching for some kind of snippet that will throw some notification when the system starts / stops some processes, thats when I came to know about the ManagementEventWatcher in c#.

ManagementEventWatcher allows us to subscribe for specific events and notifies us when those events occur.

For example, in the fore mentioned example, we need to create a ManagementEventWatcher for the events related to the spawning of processes. This is done using the WqlEventQuery class.

So first we start off writing the WqlEventQuery. This class helps us in constructing WMI event queries. For getting a notification when a process is started or stopped, we shall write a query as follows,

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("SELECT * FROM
Win32_ProcessStartTrace");

or

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");

The above query shall be used to subscribe for WMI events for Win32 process creation.

Now that we have created a query, we need to use the ManagementEventWatcher to assign this query so that we can start listening for the subscribed events. So we create an object of the ManagementEventWatcher for the query that we formed earlier.

ManagementEventWatcher aWatcher = new ManagementEventWatcher(aProcessCreationQuery);

After creating an object of the ManagementEventWatcher, we need to subscribe for the events that willbe raised by the watcher. So we go for,

aWatcher.EventArrived += new EventArrivedEventHandler(ProcessStarted);

Thats it. All we have to do now is just trigger the watcher. We do this by calling,

aWatcher.Start();

This is an asynchronous call and the reply comes thru’ the event, EventArrived. So whenever the OS spawns a process, the event will be raised.

WqlEventQuery might have solved the fore mentioned problem, but I really don’t know how effective it is. If I get to know about them more, I will post it in here.

Written by sudarsanyes

June 25th, 2009 at 7:55 am

WrapPanel in WPF

without comments

In my previous post I had written about StackPanel. One big disadvantage with the StackPanel was with the wrapping part. It cannot wrap controls / contents when it overflows. Thats why we have the WrapPanel. This is StackPanel + Wrap enabled. The following example may help you understand this better.

Consider that you have a stack panel with 7 buttons arranged in a horizontal fashion and if your window’s width is smaller than the sum of seven button’s width, then this how it looks

<Window x:Class="LayoutsTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel Orientation="Horizontal">
        <Button Content="Button1" VerticalAlignment="Center" />
        <Button Content="Button2" VerticalAlignment="Center" />
        <Button  Content="Button3" VerticalAlignment="Center" />
        <Button  Content="Button4" VerticalAlignment="Center" />
        <Button  Content="Button5" VerticalAlignment="Center" />
        <Button  Content="Button6" VerticalAlignment="Center" />
        <Button  Content="Button7" VerticalAlignment="Center" />
    </StackPanel>
</Window>

A close substitute for this problem will be a WrapPanel.

<Window x:Class="LayoutsTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <WrapPanel Orientation="Horizontal">
        <Button Content="Button1" VerticalAlignment="Center" />
        <Button Content="Button2" VerticalAlignment="Center" />
        <Button  Content="Button3" VerticalAlignment="Center" />
        <Button  Content="Button4" VerticalAlignment="Center" />
        <Button  Content="Button5" VerticalAlignment="Center" />
        <Button  Content="Button6" VerticalAlignment="Center" />
        <Button  Content="Button7" VerticalAlignment="Center" />
    </WrapPanel>
</Window>

Although this solves the Wrap problem of the stack panel, still we cannot place two controls paralle to each other using this panel.

Written by sudarsanyes

June 7th, 2009 at 7:00 am

Posted in C#, Controls, UI, WPF

Tagged with , , , ,

DockPanel in WPF

without comments

As the name says you can dock your controls in to either Top, Left, Right or Bottom of the panel. Placing a control to a location can be done using the Dock property with the values Left, Top, Right and Bottom.

ln1:    <DockPanel>
ln2:        <Button DockPanel.Dock="Top" Content="Button1" />
ln3:        <Button DockPanel.Dock="Bottom" Content="Button2" />
ln4:        <Button DockPanel.Dock="Left" Content="Button3" />
ln5:        <Button DockPanel.Dock="Right" Content="Button4" />
ln6:        <Button Content="Button5" />
ln7:    </DockPanel>

This will dock the button1 to the top of the container, button2 to the bottom and so on.

The order in which we dock the controls matters in here. If we move ln4 to ln3 and ln3 to ln4, the layout will look different.

If you dock a control to a location, the control will remain docked to that location irrespective to the size of the container. Take a look at the schreenshot shown below (with the container maximised).

Although this allows us to fix some controls to any edge of the container, we cannot position controls explicitly using this panel.

Written by sudarsanyes

June 7th, 2009 at 12:29 am

Posted in C#, Controls, UI, WPF

Tagged with , , , ,

StackPanel (Layout) in WPF

with one comment

Like .Net 2.0, WPF provides a set of layouts that allows the users to easily place the controls in to it. Lets look in to it, one by one comparing with the net 2.0 version of it.

StackLayout

This was called as FlowLayout in .net 2. Controls that are added in to this layout will be automatically aligned either in a vertical or in a horizontal fashion. This alignment depends on the value of Orientaion property. The value can either be Vertical or Horizontal.

Vertical Orientation

    <StackPanel Orientation="Vertical">
        <Button Content="Button1" />
        <Button  Content="Button2" />
    </StackPanel>

Horizontal Orientation

    <StackPanel Orientation="Horizontal">
        <Button Content="Button1" />
        <Button  Content="Button2" />
    </StackPanel>

If you notice the screenshots, you will find that the width of the button is automatically controlled by the WPF framework. Thats why the buttons are stretched. But if you wanna control the width, you can play with the HorizontalAlignment property of the control. The default alignment is Stretched. Specifying a width for the control along with the HorizontalAlignment property allows you to have total control on the size and location of the control.

<StackPanel Orientation="Vertical">
  <Button Content="Button1" />
  <Button Content="Button2" HorizontalAlignment="Left" />
  <Button  Content="Button3" HorizontalAlignment="Right" />
  <Button  Content="Button4" HorizontalAlignment="Center" />
  <Button  Content="Button5" HorizontalAlignment="Stretch" />
</StackPanel>

We can see this layout in action in loads of places. For example, the search tool that comes with windows has employed this layout.

Although this layout lets the us relax on alignments, we cannot place two controls parallel to each other (this layout is not intented to do so. we have another layout for this, GridLayout). Also this layout cannot wrap controls when the controls overflow (again this layout is not intented to do so. we have another layout for this, WrapPanel).

Written by sudarsanyes

June 6th, 2009 at 4:13 pm

Posted in C#, Controls, UI, WPF

Tagged with , , , ,

Creating a single instance application in C#, WPF

without comments

Some time you might want the user to run only one instance of the application. Its pretty easy to do so in C#. This is acheived using a Mutex. A mutex is used to restrict the usage of common resources in concurrent proragmming. C# provides a class called System.Threading.Mutex with which we can control the number of instances of an application that should be running. Just add the following snippet to the App.xaml.cs file (code behind file of App.xaml)

class App : Application
{
private Mutex myMutex;
...
protected override void OnStartup(StartupEventArgs theArgs)
{
bool aIsNewInstance = false;
myMutex = new Mutex(true, "Foo.SingletonApp", out aIsNewInstance);  //Creates a mutex for the application
if(!aIsNewInstance)
{
App.Current.Shutdow();  //Shutdown when a new mutex with the same name is created
}
}
}

How this works

The creation of a mutex in here takes three parameters. First one is to give the ownership of this mutex to the calling thread. Second one is the unique name given for this mutex (remember this is a unique name). Third one is an out parameter that returns
true — if there are no mutex with this name and if the new mutex is successfully created
fase — if there is already a mutex with this name.
That why we check for !aIsNewInstance in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the application.

Written by sudarsanyes

May 24th, 2009 at 3:46 pm

WPF Application creation, an insight — part2

with one comment

Before I can start with part2, a small highlights from part1.

  • All the WPF applications are an object of System.Windows.Application running as a process
  • Visual Studio allows the users to relax from the creation and running of the System.Windows.Application object if you specify the BuildAction as Application Definition
  • Specifying the StartupUri attribute in the App.xaml with a window class allows the developer not to write snippets that will show the top level window

Accessing Application object from window classes

As soon as the Application object is created, it would be set to the Current property of itself. As this property is a static property, any window classes can access the instance of app that is running. Also the application object, as mentioned earlier, shall hold the instances of all the top level windows. So we can even access these top level window object from any class thru’ the Current.Windows property.

class Window1
{
public Window1()  //constructor
{
foreach(Window aTopLevelWindow in App.Current.Windows as Window)
{
MessageBox.Show(aTopLevelWindow.Title);
}
}
}

Shutting down the Application object

While running an Application object is done thru’ Run(), we can shut down the app thru’ Shutdown(). For example, if you want to provider a custom close button in your window, you can close the application (terminate the entire process) using the following snippet,

class Window1
{
...
public void ExplicitShutDown()  //Some method which will explicity shutdown the Application object
{
App.Current.Shutdown();  //Where App is the name of the Application class
}
}

This is called as an explicit shutdown.

Application Events

Here are some of the events of the Application object that can be of great use when you program.

  • Startup — Invoked after the Application object is created and run. You can show your top level windows in here
  • Activated and Deactivated — Invoked when one of the top level windows of the Application object is activated and deactivated will be called when another Application object’s top level window gets activated
  • Session Ending — Invoked when windows session ends either by a shutdown call or a restart call
  • Exit — Invoked when the Application.Shutdown() is called

Hope these two posts helped you in understanding how a WPF application gets instantiated. From my next post I will start writing about controls.

Written by sudarsanyes

May 24th, 2009 at 2:05 pm

Posted in C#, General Programming, WPF

Tagged with , ,

WPF Application creation, an insight — part 1

without comments

Creating a WPF application is really a piece of cake if you have Visual Studio with out. All you have to do is,

  • Start Visual Studio ( >= 2008)
  • Create New Project (project type, WPF Application)
  • Hurrah, we have a WPF application now. Go on, edit your Window1.xaml and press F5 to see your WPF application in action

WHERE ?

Simple isn’t it ?? But there are a series of where questions to be asked in here.

  1. Where is the main function (entry point for the WPF application) ?
  2. How did Visual Studio found out that Window1 is my top level window (parent window) ?
  3. From where did it create the instance of Window1 to show it on the screen ?
  4. *

Lets try to figure out the answers now.

1. Where is the main method ? Answer is fairly simple. Visual Studio has created the main function for the application during the run time. If you notice the solution explorer, there will be two xaml files. App.xaml and Window1.xaml (by default). If you open the properties of App.xaml, one of the settings would be Build Action. This would be set to Application Definition, meaning the WPF application’s start point is this class.

2 and 3. Where is the instance of Window1 ? For this, we need to explore the App.xaml file. As mentioned in the previous inference, App.xaml has been made as the start point thru’ properties, so we need to explore the this file for the startup windows. If you see the code (xaml code),

<Application x:Class="Foo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>


</Application.Resources>
</Application>

the application tag has an attribute called StartupUri whose value is Window1. This means that when the class App is getting instantiated and when the it is run, it should automatically create an instance of Window1.xaml class (as mentioned in the StartupUri attribute) and show it.

But WHY ?

So now that we have found answers for where, we still have a set of why questions to be answered

  1. Why do we need an App.xaml file, can I run my application without it ?
  2. Why did Visual Studio create the main method ? Why can’t I do it ?
  3. Can I show my Window1 myself ? I don’t want Visual Studio to do that
  4. *

Lets figure out the answers now,

1. Can I run my application without App.xaml file ? No. Its not possible.

2. Why did Visual Studio create the main method ? For this we need to understand how the WPF application works. Every WPF application is nothing but an instance of the System.Windows.Application class. To run a WPF application, first we need to create an instance of this class manually. This should be done inside the main method. As the App.xaml has the entry point, it should create an object of the System.Windows.Application and it needs to call Run in that code behind file (App.xaml.cs).

System.Windows.Application myApp = new System.Windows.Application();
myApp.Run(); //Will run the application

Doing so will run the applicaiton. But still we will not be able to see any windows on the screen.

If you notice, the App.xaml class will be of type Application and not Window unlike the Window1.xaml file. Check out the root tag of App.xaml file.

3. Can I show my Window1 myself ? After creating an instance of System.Windows.Application class, we can create an object of the window class (top level window) in the main method and then call Show on it.

Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen

Atlast, your main method should look something like this,

class Program
[STAThread] //.net norms for com
static void Main()
{
System.Windows.Application myApp = new System.Windows.Application();
Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen
myApp.Run(); //Will run the application
}

Visual Studio didn’t want its users to mess with all these things. So most of these are done automatically leaving the users just to bother about their application and its user interfaces. Anyways its nice to know about these when you write a WPF application.

In the next post, I will write about System.Windows.Application class

Written by sudarsanyes

May 23rd, 2009 at 10:43 am

Posted in C#, General Programming, WPF

Tagged with , ,

UI designing, guidelines

without comments

Browsing about UI guideline, I got a superb link. Its a must read for UI designers. Also take up the quiz when you are done with the link.

Written by sudarsanyes

May 15th, 2009 at 8:58 am

DataContracts and WCF

without comments

Since its very long since I blogged, thought I would write about DataContracts in C#. DataContracts is a part of WCF (A.K.A Windows Communication Foundation). If you are writing an application in C# (.NET) that needs to communicate with a server, how do you do it ?? Thats where WCF and DataContracts comes in to picture.

DataContracts are a common agreement between the client and the server there by allowing them to share the data without sharing the actual type represented by the data. In other words, if the client and server needs to communicate, they needn’t share the same type, rather they need to share the DataContracts.

Soon I will get a sample that explains this concept clearly. Meanwhile, peek in to MSDN’s definition of DataContracts.

Written by sudarsanyes

April 24th, 2009 at 9:37 am

Posted in C#, General Programming

Tagged with ,