none
Create and call a function with C#

    Question

  • Hello

    I am new to C# programming and am playing around with the info available in WMI.

    The code below works but I would like to call it from a function.  What is the best way to do that?

    SelectQuery wmi_Service = new SelectQuery("Select * from Win32_Service");
    ManagementObjectSearcher wmi_service_search = new ManagementObjectSearcher(wmi_Service);
    Console.WriteLine("Service Information");
    foreach (ManagementObject wmi_service_obj in wmi_service_search.Get())
    {
    Console.WriteLine("______________________________________________________________");
    Console.WriteLine("Caption: " + wmi_service_obj.GetPropertyValue("Caption").ToString());
    Console.WriteLine("Description: " + wmi_service_obj.GetPropertyValue("Description").ToString());
    Console.WriteLine("Path Name: " + wmi_service_obj.GetPropertyValue("PathName").ToString());
    Console.WriteLine("Process ID: " + wmi_service_obj.GetPropertyValue("ProcessId").ToString());
    Console.WriteLine("State: " + wmi_service_obj.GetPropertyValue("State").ToString());
    Console.WriteLine("Start Name: " + wmi_service_obj.GetPropertyValue("StartName").ToString());

    I would like to have a function for each item in WMI that I am interested.  There would be one for processes, services, and a number of other items.

    What is the best way to approach this?

    Thank you

    Wednesday, August 10, 2011 4:26 PM

Answers

  • E.g.

    namespace ConsoleApplication1
    {
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Management;
      using System.Text;
    
      internal class Program
      {
        static void Main(string[] args)
        {
          const string Query = "Select * from Win32_Service";
          var serviceObjects =
            from managementObject in GetManagementObjectCollection(Query).Cast<ManagementObject>()
            select new ServiceObject(managementObject);
          PrintList(serviceObjects);
          Console.ReadLine();
        }
    
        private static ManagementObjectCollection GetManagementObjectCollection(string query)
        {
          SelectQuery selectQuery = new SelectQuery(query);
          ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(selectQuery);
          ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
          return managementObjectCollection;
        }
    
        private static void PrintList(IEnumerable<ServiceObject> serviceObjects)
        {
          Console.WriteLine("Service Information");
          foreach (ServiceObject serviceObject in serviceObjects)
          {
            Console.WriteLine(serviceObject.ToString());
          }
        }
      }
    
      public class ServiceObject
      {
        public string Caption { get; set; }
        public string Description { get; set; }
        public string PathName { get; set; }
        public string ProcessID { get; set; }
        public string State { get; set; }
        public string StartName { get; set; }
        public bool IsValid { get; set; }
    
        public ServiceObject(ManagementObject managementObject)
        {
          try
          {
            this.Caption = managementObject.GetPropertyValue("Caption").ToString();
            this.Description = managementObject.GetPropertyValue("Description").ToString();
            this.PathName = managementObject.GetPropertyValue("PathName").ToString();
            this.ProcessID = managementObject.GetPropertyValue("ProcessId").ToString();
            this.State = managementObject.GetPropertyValue("State").ToString();
            this.StartName = managementObject.GetPropertyValue("StartName").ToString();
            this.IsValid = true;
          }
          catch
          {
            this.IsValid = false;
          }
        }
    
        public override string ToString()
        {
          StringBuilder result = new StringBuilder();
          result.AppendLine("---");
          if (this.IsValid)
          {
            result.AppendLine(string.Format("Caption: {0}", this.Caption));
            result.AppendLine(string.Format("Description: {0}", this.Description));
            result.AppendLine(string.Format("Path Name: {0}", this.PathName));
            result.AppendLine(string.Format("Process ID: {0}", this.ProcessID));
            result.AppendLine(string.Format("State: {0}", this.State));
            result.AppendLine(string.Format("Start Name: {0}", this.StartName));
          }
          else
          {
            result.AppendLine("Invalid");
          }
    
          return result.ToString();
        }
      }
    }
    


    Microsoft MVP Office Access
    https://mvp.support.microsoft.com/profile/Stefan.Hoffmann
    • Marked as answer by digitalgun Tuesday, August 16, 2011 3:25 PM
    Tuesday, August 16, 2011 10:59 AM

All replies

  • On 8/10/2011 12:26 PM, digitalgun wrote:
    > Hello
    >
    > I am new to C# programming and am playing around with the info available
    > in WMI.
    >
    > The code below works but I would like to call it from a function. What
    > is the best way to do that?
    >
    > SelectQuery wmi_Service = new SelectQuery("Select * from Win32_Service");
    > ManagementObjectSearcher wmi_service_search = new
    > ManagementObjectSearcher(wmi_Service);
    > Console.WriteLine("Service Information");
    > foreach (ManagementObject wmi_service_obj in wmi_service_search.Get())
    > {
    > Console.WriteLine("______________________________________________________________");
    > Console.WriteLine("Caption: " +
    > wmi_service_obj.GetPropertyValue("Caption").ToString());
    > Console.WriteLine("Description: " +
    > wmi_service_obj.GetPropertyValue("Description").ToString());
    > Console.WriteLine("Path Name: " +
    > wmi_service_obj.GetPropertyValue("PathName").ToString());
    > Console.WriteLine("Process ID: " +
    > wmi_service_obj.GetPropertyValue("ProcessId").ToString());
    > Console.WriteLine("State: " +
    > wmi_service_obj.GetPropertyValue("State").ToString());
    > Console.WriteLine("Start Name: " +
    > wmi_service_obj.GetPropertyValue("StartName").ToString());
    >
    > I would like to have a function for each item in WMI that I am
    > interested. There would be one for processes, services, and a number of
    > other items.
    >
    > What is the best way to approach this?
    >
    > Thank you
    >
     private string ReturnPropertyValue(string strPropName, wmi as
    wmi_service_obj)
     
    {
        return  wmi.GetProperty(strPropName).Tostring();
    }
     string state = ReturnPropertyValue("State", wm_service_obj);
     
    Wednesday, August 10, 2011 4:36 PM
  • That was quick.  Thanks.  I will have to play around with this.  I have read where people were adding a new item - Class into their projects.  Should I do that with this?  Or should it be placed elsewhere in the project?

    FYI - I am not a programmer so if there is a better forum for these types of questions please let me know.

     

    Thanks!

    Wednesday, August 10, 2011 5:21 PM
  • On 8/10/2011 1:21 PM, digitalgun wrote:
    > That was quick. Thanks. I will have to play around with this. I have
    > read where people were adding a new item - Class into their projects.
    > Should I do that with this? Or should it be placed elsewhere in the project?
     
    Yeah you can do that an make it a static class with static methods of
    functions.
     
     
    Or you can just create the function with the current class you have the
    original code and just use it form within the class.
     
    The key here is to pass the wmi object into the function and use the
    object in the function along with passing the string of the field you
    want, which makes it dynamic.
    >
    > FYI - I am not a programmer so if there is a better forum for these
    > types of questions please let me know.
    >
    > Thanks!
    >
     
     
    Wednesday, August 10, 2011 5:58 PM
  • Hello,

    I think we can use reflection tech to print WMI object properties and opt the proper properties which we want in my project. I suggest you can check this blog about using reflection in C# to print WMI object properties. http://blogs.msdn.com/b/saveenr/archive/2005/12/07/501369.aspx I hope this can help you enlarge your experience.

    Please feel free to let me know if you have any question.

    Thanks,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, August 11, 2011 3:47 AM
  • Please search for Microsoft.Build.Engine if you are looking to create, compile and use code on the fly. There is also CSharpCodeDomProvider which does similar things.

     

    Thanks,

    Viral.


    MCTS - WPF, WinForms, Sql Server 2008
    Thursday, August 11, 2011 10:10 AM
  • That looks like what I am interested in doing.  It also provides a good example.  Thanks.

    Only issues I have is that when I walk through the article I get these errors.

    Microsoft.Build.Evaluation.ProjectCollection

    C:\Users\Administrator\Documents\Visual Studio 2010\Projects\wmi\wmi\service.CS(1236,25): error CS0246: The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)
    C:\Users\Administrator\Documents\Visual Studio 2010\Projects\wmi\wmi\service.CS(1238,42): error CS0246: The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)
    C:\Users\Administrator\Documents\Visual Studio 2010\Projects\wmi\wmi\service.CS(1198,21): error CS0246: The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)
    C:\Users\Administrator\Documents\Visual Studio 2010\Projects\wmi\wmi\service.CS(1200,38): error CS0246: The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)  I wonder if something has changed since this article was written several years ago.  The body of the code would compile fine but the code built by  Mgmtclassgen.exe
    is what generates the dreaded squiggly lines and the above errors.

    Thursday, August 11, 2011 4:23 PM
  • As an FYI, in C# we don't say "Functions". That is a VB terminology. We simple call them "Methods". VB differentiates between Subroutines and Functions. C# usually just say methods for both. One returning a value and a void.
    John Grove, MCC - Senior Software Engineer
    Thursday, August 11, 2011 4:30 PM
  • Thanks John!  Methods it is...

    Does anyone have some sample code that would take the code in my first post and convert it to something that could be used as a method? 

    I think a good example would go a long way to getting me started.  Maybe an example of some other operation would help too.  Something that shows the method and how to call it...something related to coding for the OS.

    BTW - I have ordered some C# books to help but in my experience a lot of the books don't actually focus on doing anything with Windows.  For me to stay interested I think I need to play around with some code that actually interests me.  Hope that makes sense.

    Thanks

    Thursday, August 11, 2011 6:20 PM
  • Actually John I agree with you but what do we call these: http://msdn.microsoft.com/en-us/library/bb549151.aspx

    Seems like the Era of no functions in C# was shot with these new forms of delegates which acutally have the name of Function..


    JP
    Thursday, August 11, 2011 6:39 PM
  • Try it yourself:

    Step 1: Create a class that holds the data you want.  Like this... 

    class WMIObjectData {
    
    	public string Caption {get;set;}
    	public sring Description {get;set;}
    	public string PathName {get;set;}
    	etc.}
    

    Step 2) In the current foreach loop do this:  
    WMIObjectData objData = new WMIObejctData();
    objData.Caption = wmi_service_obj.GetPropertyValue("Caption").ToString();
    objData.Description = wmi_service_obj.GetPropertyValue("Description").ToString();
    objData.PathName = wmi_service_obj.GetPropertyValue("PathName").ToString());
     ...  
    list.add(objdata)

    Step 3) The line before the foreach do this:
    List<WMIObjectData> list = new List<WMIObjectData>();

    After you iterate through everything simply return the list from the method like this:  
    return list;
    

    Step 4) Put all the code in a new method like this:  
    public List<WMIObjectData> GetWMIData(){
    
    }

     


    JP
    Thursday, August 11, 2011 6:50 PM
  • On 8/11/2011 2:20 PM, digitalgun wrote:
     
    > BTW - I have ordered some C# books to help but in my experience a lot of
    > the books don't actually focus on doing anything with Windows. For me to
    > stay interested I think I need to play around with some code that
    > actually interests me. Hope that makes sense.
    >
     
     
    You get a Windows Desktop solution to work with N-Tier, then you have
    learned a lot. There is an MVP solution for Windows based solutions in
    the link below.
     
     
    What is MVP?
     
     
    Also in the show below, it shows you haw to make MVP work with Windows UI.
     
     
    Design Patterns Bootcamp: Model View * Patterns
     
    Here is a Windows desktop solution.
     
     
    Make it work using the following:
     
    1) Windows forms based
    2) use MVP with a Service layer
    3) Business Logic Layer
    4) Data Access Layer
    5) use ADO.NET Entity Framework
     If you do that, then you have a good concept of what is happening with
    .NET because .NET is an OOP language solution. It's not about how well
    you know C# per say. It's about do you understand OOP.
     
     
     
    Thursday, August 11, 2011 7:05 PM
  • Actually John I agree with you but what do we call these: http://msdn.microsoft.com/en-us/library/bb549151.aspx

    Seems like the Era of no functions in C# was shot with these new forms of delegates which acutally have the name of Function..


    JP

    The point is, is that every "function" is a method. Every "subroutine" is a method. The real distinction is that in C# a method is attached to a class. Since it is an OO language, you can't have functions, which stand alone (outside of classes) as they did in early VB. But VB carried this over from its older syntax. Most experienced developers never call methods "subroutines" or "functions" UNLESS they came from a VB background.

    Note here that no where does Microsoft call methods in C# subroutines or functions but rather methods.

    BTW, Func and Action (Note, not "Subroutine") are simply generic delegates that were introduced in the .NET framework version 3.5. They provide delegates with generic parameters that can be used for many purposes, including passing lambda expressions to method parameters. But it is not a "naming" syntax for how methods are called but generic delegates for specific purposes.


    John Grove, MCC - Senior Software Engineer

    Thursday, August 11, 2011 8:03 PM
  • This is closest to what I want.  Thanks.  Still it isn't working for me.  Ugh...  I have gremlins in my machine or something.  Now the code in my orginal post gives me squiggly lines on SelectQuery.  I still have all of the same using statements which include system.management and s

    ystem.Diagnostics I am about ready to tap out!

     

    Thursday, August 11, 2011 11:38 PM
  • Squiggly lines means a coding or syntax error.  Click on the symbol, "SelectQuery", that is displaying the sqiggly line and let your mouse hover over it.  Intellisense should open up a message balloon telling you what the problem is.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Friday, August 12, 2011 12:00 AM
  • Yeah.  I know.  :)  It says that the type or namespace name SelectQuery couldnt be found.  That would be okay if I didnt just have it working earlier in the day.

    I think i have all of the correct using statements.

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

     

    Friday, August 12, 2011 3:02 PM
  • System.Management is the correct namespace.  But, I suspect that you have a syntax error, which would mean that you have other errors.  Do a build and fix the first one in the list.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Friday, August 12, 2011 10:21 PM
  • Note here that no where does Microsoft call methods in C# subroutines or functions but rather methods.


    The C# specification uses the word "function" for two things:

    1) Function members

    That is the collective name of any member containing executable code: methods, properties, events...

    2) Anonymous functions

    Either a lambda expression, or an anonymous method expression.

    Tuesday, August 16, 2011 10:19 AM
  • C:\Users\Administrator\Documents\Visual Studio 2010\Projects\wmi\wmi\service.CS(1236,25): error CS0246: The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)
    Add a reference to System.Management.dll to your project.
    Tuesday, August 16, 2011 10:20 AM
  • E.g.

    namespace ConsoleApplication1
    {
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Management;
      using System.Text;
    
      internal class Program
      {
        static void Main(string[] args)
        {
          const string Query = "Select * from Win32_Service";
          var serviceObjects =
            from managementObject in GetManagementObjectCollection(Query).Cast<ManagementObject>()
            select new ServiceObject(managementObject);
          PrintList(serviceObjects);
          Console.ReadLine();
        }
    
        private static ManagementObjectCollection GetManagementObjectCollection(string query)
        {
          SelectQuery selectQuery = new SelectQuery(query);
          ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(selectQuery);
          ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
          return managementObjectCollection;
        }
    
        private static void PrintList(IEnumerable<ServiceObject> serviceObjects)
        {
          Console.WriteLine("Service Information");
          foreach (ServiceObject serviceObject in serviceObjects)
          {
            Console.WriteLine(serviceObject.ToString());
          }
        }
      }
    
      public class ServiceObject
      {
        public string Caption { get; set; }
        public string Description { get; set; }
        public string PathName { get; set; }
        public string ProcessID { get; set; }
        public string State { get; set; }
        public string StartName { get; set; }
        public bool IsValid { get; set; }
    
        public ServiceObject(ManagementObject managementObject)
        {
          try
          {
            this.Caption = managementObject.GetPropertyValue("Caption").ToString();
            this.Description = managementObject.GetPropertyValue("Description").ToString();
            this.PathName = managementObject.GetPropertyValue("PathName").ToString();
            this.ProcessID = managementObject.GetPropertyValue("ProcessId").ToString();
            this.State = managementObject.GetPropertyValue("State").ToString();
            this.StartName = managementObject.GetPropertyValue("StartName").ToString();
            this.IsValid = true;
          }
          catch
          {
            this.IsValid = false;
          }
        }
    
        public override string ToString()
        {
          StringBuilder result = new StringBuilder();
          result.AppendLine("---");
          if (this.IsValid)
          {
            result.AppendLine(string.Format("Caption: {0}", this.Caption));
            result.AppendLine(string.Format("Description: {0}", this.Description));
            result.AppendLine(string.Format("Path Name: {0}", this.PathName));
            result.AppendLine(string.Format("Process ID: {0}", this.ProcessID));
            result.AppendLine(string.Format("State: {0}", this.State));
            result.AppendLine(string.Format("Start Name: {0}", this.StartName));
          }
          else
          {
            result.AppendLine("Invalid");
          }
    
          return result.ToString();
        }
      }
    }
    


    Microsoft MVP Office Access
    https://mvp.support.microsoft.com/profile/Stefan.Hoffmann
    • Marked as answer by digitalgun Tuesday, August 16, 2011 3:25 PM
    Tuesday, August 16, 2011 10:59 AM
  • Any update? We've not heard from yours a couple of time. Would you mind letting us know other members' suggestions helped you solve you concern?

    Welcome to let us know if you have any question.

    Thanks,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, August 16, 2011 11:21 AM
  • Thanks for the help everyone!    I am sure this will do the trick!  Sorry for the delay.  I am unable to work on this project this week.

     

    Tuesday, August 16, 2011 3:27 PM