Access firewall information and check firewall status using the dynamic keyword in C#

[firewall]

This advanced firewall example comes from Special Guest Blogger John Mueller. John is a prolific author who’s written more than 86 books on all sorts of topics including operating systems, working with the command-line, Python, Visual Basic, and of course C#.

More examples similar to this one appear in John’s book Professional Windows 7 Development Guide (Wrox, 2011).

(It turns out that you can’t do this in Visual Basic because there isn’t apparently an equivalent keyword. See the Microsoft forum post Dynamic Keyword equivalent in VB.Net?)

There are a number of ways to interact with the Windows Firewall. In the past, developers would often use Component Object Model (COM)-based code. You can see an example of such code at Managed classes to view/manipulate the Windows Firewall. It doesn’t take long to figure out that using COM-based code is time consuming and error prone. You have to write a lot of code to accomplish most tasks with the Windows Firewall using this approach, but it does admittedly work with older versions of the .NET Framework.

Fortunately, C# 4.0 provides a better approach using the dynamic keyword. In this case, you can interact with the Windows Firewall much as you would using VBScript. The technique is simple and relatively straightforward, despite not looking very much like standard C# code you’ve used in the past. To test this out for yourself, create a Windows Forms application and add a Check (btnCheck) button to it. You don’t need to add any special references or using statements. The following listing shows the code you need to create the Access Firewall example.

Creating firewall access using the dynamic keyword

private void btnCheck_Click(object sender, EventArgs e)
{
    // Create the firewall type.
    Type FWManagerType = Type.GetTypeFromProgID("HNetCfg.FwMgr");

    // Use the firewall type to create a firewall manager object.
    dynamic FWManager = Activator.CreateInstance(FWManagerType);

    // Check the status of the firewall.
    MessageBox.Show("The firewall is turned on: " + 
        Convert.ToString(
            FWManager.LocalPolicy.CurrentProfile.FirewallEnabled));
}

As previously mentioned, this code really does look like something you’d create using VBScript, rather than C#, but it works extremely well. The code begins by creating a new Type, FWManagerType, defined using the Type.GetTypeFromProgID() constructor with HNetCfg.FwMgr as the object to create.

Now that the code has a Type to use, it can use it to create an instance of the object defined by that Type using the Activator.CreateInstance() constructor. Just in case you’ve never seen the Activator class before, you can read more about it at Microsoft’s web page Activator Class. At this point, the example has access to the firewall manager using the FWManager object that’s described merely as type dynamic. Something that’s interesting is that you can view the FWManager object in the debugger and see all of the properties it supports, which makes writing additional code easier.

The code displays a simple on/off indicator in this case for the Windows Firewall using a message box. Of course, you’re wondering where to obtain the list of objects to access the on/off state of the Windows Firewall. One such place is at Windows Firewall Tools and Settings. However, you’ll find a wealth of VBScript examples on the Internet that will give you additional information that you can apply directly to your C# application with a little translation. You can see a few of these VBScript examples at Using Windows Firewall API.

Check out John’s web site or his book Professional Windows 7 Development Guide.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in internet, network, system and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Access firewall information and check firewall status using the dynamic keyword in C#

  1. Joe Pearson says:

    Hey! your work is awesome! One thing I have noticed is that this seems to pass as “TRUE” if the windows firewall settings on either public or private networks instead of warning you as “FALSE” if either is off. How can I get this to work so that it considers both network settings then posts FAIL if either are off?

    • RodStephens says:

      I checked with John and here’s his reply:

      On my system, the current code will tell you whether the home network has the firewall turned on or not. When I put that example together, that’s really all that was available. Of course, now Microsoft has changed things, so you need a new and different method of accessing the information. So, here’s an updated bit of example code:

      private void button2_Click(object sender, EventArgs e)
      {
          // Create consts for firewall types.
          const int NET_FW_PROFILE2_DOMAIN = 1;
          const int NET_FW_PROFILE2_PRIVATE = 2;
          const int NET_FW_PROFILE2_PUBLIC = 4;
       
          // Create the firewall type.
          Type FWManagerType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
       
          // Use the firewall type to create a firewall manager object.
          dynamic FWManager = Activator.CreateInstance(FWManagerType);
       
          // Get the firewall settings.
          bool CheckDomain =
              FWManager.FirewallEnabled(NET_FW_PROFILE2_DOMAIN);
          bool CheckPrivate =
              FWManager.FirewallEnabled(NET_FW_PROFILE2_PRIVATE);
          bool CheckPublic =
              FWManager.FirewallEnabled(NET_FW_PROFILE2_PUBLIC);
       
          // Check the status of the firewall.
          MessageBox.Show("The Domain firewall is turned on: " + CheckDomain +
              "\nThe Private firewall is turned on: " + CheckPrivate +
              "\nThe Public firewall is turned on: " + CheckPublic);
      }

      The basic concept is the same, but some of the players are different.

Leave a Reply

Your email address will not be published. Required fields are marked *