Learn to Code with Code Year

I’ve had many folks ask me how to get started coding over the years. There are so many resources available that it is sometimes difficult to point them in a single direction. Newcomers can easily be frustrated by having too many choices or by the girth of many programming books.

A great resource for anyone who is interested in programming, but needs help, is here. If you know someone intimidated by programming, or anyone who just wants to learn how to program on their own, there are unlimited resources on the Internet. The Code Academy is a shining example. It has interactive lessons with instant feedback, tips, help, and progress tracking. They will even award you with achievement badges. After you join the site, you’ll get a welcome email letting you know a lesson a week is going to be on your agenda.

You can skip the schedule and jump right in. Well, what are you waiting for? Get coding!

http://www.codecademy.com/

The Art of Coding without Coding (WMI Part 1)

One of the great things about using the Systems.Management namespace is all of the information you can retrieve.  Adding a reference to the Systems.Management namespace into your program will allow your application to query Windows Management Instrumentation(WMI).  Even the most seasoned veteran can’t remember all of the specific classes and namespaces, and beginners need help with query syntax.

Thanks for Chris Scoville at Microsoft, there is a tool that will generate complete WMI query code for your application, the WMI Code Creator.   Additionally, the application has a built in namespace browser that displays all the properties and methods of a class. 

Using the WMI Code Creator

The greatest thing about the WMI Code Creator for new programmers is that it generates a complete code block that can be pasted directly into your code editor, but you may get more than you want.  Using the Code Language menu item, choose the appropriate language.  For Visual Basic .NET, the application will generate code for a namespace and public class.  If you are wanting just the basic code to attach to a function or event within your application, you probably wont need the entire code block.  For example, suppose you want to use WMI to retrieve a list of printers on the local computer, and populate a listbox with those printers.  I’ll walk through this procedure step by step.

  • Create a new Windows Forms application using the New, Project, menu.
  • Drag a Button and a ListBox to the form from the toolbox
  • Start the WMI Code Creator if it isn’t running and choose Visual Basic .NET from the Code Language Menu
  • The NameSpace combo box should default to "root\CIMV2".  If it doesn’t, choose it from the dropdown list.
  • Select WIN32_Printer from the Classes dropdown.
  • Select Name from the properties list, you should now have the following code displayed in the WMI Code Creator Window:
Imports System
Imports System.Management
Imports System.Windows.Forms

Namespace WMISample

    Public Class MyWMIQuery

        Public Overloads Shared Function Main() As Integer

            Try
                Dim searcher As New ManagementObjectSearcher( _
                    "root\CIMV2", _
                    "SELECT * FROM Win32_Printer") 

                For Each queryObj As ManagementObject in searcher.Get()

                    Console.WriteLine("-----------------------------------")
                    Console.WriteLine("Win32_Printer instance")
                    Console.WriteLine("-----------------------------------")
                    Console.WriteLine("Name: {0}", queryObj("Name"))
                Next
            Catch err As ManagementException
                MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
            End Try
        End Function
    End Class
End Namespace

While this code is indeed complete, it contains a definition of a namespace and public class that we will not be needing for our example. 

  • Select the Try/End Try block of code and copy it to the clipboard.
  • Return to Visual Basic 2008 Express and doubleclick on button1.  It should open the code editor inside the Button1_Click event.
  • Paste in the code you copied from the WMI Code Creator.  Your Button1_Click event should now look like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
                "root\CIMV2", _
                "SELECT * FROM Win32_Printer")

            For Each queryObj As ManagementObject In searcher.Get()

                Console.WriteLine("-----------------------------------")
                Console.WriteLine("Win32_Printer instance")
                Console.WriteLine("-----------------------------------")
                Console.WriteLine("Name: {0}", queryObj("Name"))
            Next
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
        End Try
    End Sub

Before we continue, we need to get rid of all the red squigglies.  Your project doesn’t have any references to things such as ManagementObjectSearcher.

  • Choose Project, Add Reference from the menu.  Scroll down to System.Management and select it.  Click OK.
  • Above the line in your code that says "Public Class Form 1" add the following Imports System.Management
  • The Error List window (if visible) should now be clear, and the red squigglies should be gone.
  • See the four Console.Writeline statements?  We will not be using those, but take note of the last one.   
  • Delete the four Console.Writeline statements from the code.
  • Inside the For…Next block where you removed the Console.Writeline statements, insert the following entry
ListBox1.Items.Add(queryObj("Name"))

Your entire application code should look like the following example:

Imports System.Management
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
                "root\CIMV2", _
                "SELECT * FROM Win32_Printer")

            For Each queryObj As ManagementObject In searcher.Get()

                ListBox1.Items.Add(queryObj("Name"))

            Next
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
        End Try
    End Sub
End Class
  • Hit F5 or click the run button to see it in action, mine looks like this

printerlist

That’s it.  You just created a simple application that displays a list of printers on the local machine.  Not very useful and the information is already viewable from the built in capabilities of the operating system, but this is just an example of how the WMI Code Creator can help you develop your applications more quickly while minimizing the amount of code you have to create.  This barely touches the surface of WMI but you can see how easily it is to quickly create a simple application with the minimal amount of coding.  The article in this series will extend this program and make it more useful.  Check back soon.

You can download the WMI Code Creator for free from Microsoft.  I won’t try to link it here since stuff gets moved around all the time.  Google it, should be the first or second hit.