Using Windows Management Instrumentation - It's Easy

Add Comment | Dec 04, 2008

Want to know what Services or/and Processes are running currently on your PC? In one of my previous project I implemented small diagnostic utility which showed what processes and services are running on host box. Here is the example how to obtain this information.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
 
namespace ManagementInstrumentation
{
    class Program
    {
       
        static void Main(string[] args)
        {
            ListServices();
            Console.ReadLine();
            ListProcesses();
            Console.ReadLine();
        }
 
 
        private static void ListServices()
        {
            ManagementScope scope = newManagementScope();
            System.Management.ObjectQuery query = new ObjectQuery("select * from Win32_Service");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            foreach(ManagementBaseObject o in searcher.Get())
            {
                Console.WriteLine("Service {0} is started = {1}", o["Name"], o["Started"]);
                foreach (var prop in o.Properties)
                {
                    Console.WriteLine("{0} = {1}", prop.Name, prop.Value);
                }
            }
        }
 
 
        private static void ListProcesses()
        {
 
            ManagementScope scope = new ManagementScope();
            System.Management.ObjectQuery query = new ObjectQuery("select * from Win32_Process");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            foreach (ManagementBaseObject o in searcher.Get())
            {
                Console.WriteLine("Properties for Process {0}", o["Name"]);
                foreach (var prop in o.Properties)
                {
                    Console.WriteLine("{0} = {1}", prop.Name, prop.Value);
                }
               
            }
        }
        //In this method I want to list just running services
        //I'm using LINQ query to select started services
        private static void ListRunningServices()
        {
            ManagementScope scope = new ManagementScope();
            System.Management.ObjectQuery query = new ObjectQuery("select * from Win32_Service");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            var services = searcher.Get();
 
            var started = fromManagementBaseObject s in services
                          fromPropertyData p in s.Properties
                          where p.Name == "Started" && p.Value.ToString().ToLower() == "true"
                          select s;
            foreach (var o in started)
            {
                Console.WriteLine("Service {0} is started ", o["Name"]);
            }
        }
    }
}
 

 

//Happy Coding

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Singleton Design Pattern in C#

2 Comments | Nov 12, 2008

/* The Singleton pattern assures that there is one and only one instance
of a class, and provides a global
point of access to it. There are any number of cases in programming
where you need to make sure that there can be one and only one
instance of a class. For example, your system can have only one
web service manager, or a single point of access to a
database.
The easiest way to make a class that can have only one instance is to
embed a static variable inside the class that A static
variable is one for which there is only one instance, no matter how
many instances there are of the class. To prevent instantiating the class
more than once, we make the constructor private so an instance can
only be created from within the static method of the class.
Read-only property Instance check if static variable _instance is initialized,
if not property will return the new instance od Singleton class, otherwise the
existing instance will be returned.
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
    public sealed class Singleton
    {
        private static Singleton _instance;

        private Singleton()
        {/* no code */}

        public static Singleton Instance
        {
            get
            {
                if(_instance == null)
                {
                    _instance = new Singleton();
                }
                return _instance;
            }
        }

        public static void SomeMethod()
        {
            //Do some job
        }
    }
  
}

//The Test case for this Singleton Class

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Singleton inst = Singleton.Instance;

            Console.WriteLine("Singleton ID is {0}", inst.GetHashCode().ToString());

            Singleton inst2 = Singleton.Instance;

            Console.WriteLine("Singleton ID is {0}", inst2.GetHashCode().ToString());

            Debug.Assert(inst.GetHashCode() == inst2.GetHashCode(), "ID is not the Same!");
            Console.ReadLine();
        }
    }
}


//If you will run this quick test you will that every time the property Insance is called it returns the same object.

//Happy Coding!!!
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to Debug Windows Service

One Comment | Oct 29, 2008

Sometimes windows service debugging is really tricky. Usually , during development, developer should implement some test harness application with UI to run and test functionality being developed. But when it comes to debug real windows service which hosts the objects which do the real job - it's a headache.

 Amazingly, in NET platform there is a simple and straightforward way to debug a windows service.

 Consider the following code sample:

using System.ServiceProcess;
namespace MyService
{
 public partial class MyService : ServiceBase
 {
    public MyService()
    {
         InitializeComponent();
    }
  protected override void OnStart(string[] args) 
   {
        System.Diagnostics.Debugger.Launch(); //This will launch a debugger
        //Do the real job MyWorker.Start();
    }
 }
}

 

After you installed and launched the service , you will be prompted to use Visual Studio to attach to the process. Click "Attach" button and Visual Studio will pop up and here you go.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Factory Design Pattern

One Comment | Oct 28, 2008

Today I will show how to implement factory design pattern in NET platform.
One type of pattern that we see again and again in OO programs is the Factory pattern.
A Factory pattern is one that returns an instance of one of several possible classes, depending on the data provided to it.
Consider the following C# code sample:

using System;
using System.Runtime.Remoting;
namespace Factory
{
 /// /// implements factory design pattern ///
 public static class WorkerFactory
 {
  private static string _asmName = "MyAssembly.";
  
  //returns new worker object
  public static void CreateWorker(out MyType mytypeobject, string strtype) // this method takes 2 arguments: 1-st for the object you want to instantiate and the second one for type name.
  {
   MyType sys = null;
   mytypeobject = null;
   string fullname = _asmName+strtype;
   try {
     ObjectHandle handle = System.Activator.CreateInstance(_asmName, fullname); //this method takes assembly name and type name to create an instance of the object
     MyType sys = (MyType)handle.Unwrap(); //You need to cast it to particular kind of the object
    }
    catch
    {
     throw new ApplicationException("Worker Factory can not create and object from assembly "+_asmName+" with name "+ns+".");
    }
    finally
    {
     if(sys != null) mytypeobject = sys;
    }
   }
  }
 }

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati