ModifyFeatureSettings(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject managementService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))

                //
                // Find the specified switch.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                    using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                               ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                         "Msvm_SettingsDefineState",
                                                         null, null, null, null, false, null)))

                        //
                        // Find the existing bandwidth setting and modify it.
                        //
                        using (ManagementObject bandwidthSetting = WmiUtilities.GetFirstObjectFromCollection(
                                   ethernetSwitchSetting.GetRelated("Msvm_VirtualEthernetSwitchBandwidthSettingData",
                                                                    "Msvm_VirtualEthernetSwitchSettingDataComponent",
                                                                    null, null, null, null, false, null)))
                        {
                            //
                            // Increase the current reservation by 1 Mbps.
                            //
                            bandwidthSetting["DefaultFlowReservation"] =
                                (UInt64)bandwidthSetting["DefaultFlowReservation"] + 125000; // in bytes/sec

                            using (ManagementBaseObject inParams =
                                       managementService.GetMethodParameters("ModifyFeatureSettings"))
                            {
                                inParams["FeatureSettings"] = new string[] { bandwidthSetting.GetText(TextFormat.WmiDtd20) };

                                using (ManagementBaseObject outParams =
                                           managementService.InvokeMethod("ModifyFeatureSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully modified bandwidth feature setting on virtual switch '{0}'.",
                                            switchName));
        }
        AddFeatureSettings(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string featureId = NetworkingUtilities.GetSwitchFeatureId(NetworkingUtilities.SwitchFeatureType.Bandwidth);

            using (ManagementObject managementService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))

                //
                // Find the specified switch.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                    using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                               ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                         "Msvm_SettingsDefineState",
                                                         null, null, null, null, false, null)))

                        //
                        // Add a new bandwidth setting instance.
                        //
                        using (ManagementObject bandwidthSetting =
                                   NetworkingUtilities.GetDefaultFeatureSetting(featureId, scope))
                        {
                            //
                            // Set the default bandwidth reservation to 10 Mbps.
                            //
                            bandwidthSetting["DefaultFlowReservation"] = 12500000; // in bytes/sec

                            using (ManagementBaseObject inParams =
                                       managementService.GetMethodParameters("AddFeatureSettings"))
                            {
                                inParams["AffectedConfiguration"] = ethernetSwitchSetting.Path.Path;
                                inParams["FeatureSettings"]       = new string[] { bandwidthSetting.GetText(TextFormat.WmiDtd20) };

                                using (ManagementBaseObject outParams =
                                           managementService.InvokeMethod("AddFeatureSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully added bandwidth feature setting to virtual switch '{0}'.",
                                            switchName));
        }
        RemoveFeatureSettings(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject managementService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))

                //
                // Find the specified switch.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                    using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                               ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                         "Msvm_SettingsDefineState",
                                                         null, null, null, null, false, null)))

                        //
                        // Find the existing bandwidth setting and remove it.
                        //
                        using (ManagementObject bandwidthSetting = WmiUtilities.GetFirstObjectFromCollection(
                                   ethernetSwitchSetting.GetRelated("Msvm_VirtualEthernetSwitchBandwidthSettingData",
                                                                    "Msvm_VirtualEthernetSwitchSettingDataComponent",
                                                                    null, null, null, null, false, null)))
                        {
                            using (ManagementBaseObject inParams =
                                       managementService.GetMethodParameters("RemoveFeatureSettings"))
                            {
                                inParams["FeatureSettings"] = new string[] { bandwidthSetting.Path.Path };

                                using (ManagementBaseObject outParams =
                                           managementService.InvokeMethod("RemoveFeatureSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully removed bandwidth feature setting from virtual switch '{0}'.",
                                            switchName));
        }
        AddPorts(
            string switchName,
            string externalAdapterName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string ethernetSwitchSettingPath;
            string portToCreateText;

            ObjectQuery externalAdapterQuery = new ObjectQuery(string.Format(CultureInfo.InvariantCulture,
                                                                             "select * from Msvm_ExternalEthernetPort where Name=\"{0}\"", externalAdapterName));

            //
            // When modifying the switch, we need to pass in its configuration object.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    ethernetSwitchSettingPath = ethernetSwitchSetting.Path.Path;
                }

            //
            // Get the external adapter that we want to add a connection to.
            //
            using (ManagementObjectSearcher externalAdapterExecute =
                       new ManagementObjectSearcher(scope, externalAdapterQuery))
                using (ManagementObjectCollection externalAdapterCollection = externalAdapterExecute.Get())
                {
                    if (externalAdapterCollection.Count == 0)
                    {
                        throw new ManagementException(string.Format(CultureInfo.InvariantCulture,
                                                                    "There is no external adapter with the name {0}.",
                                                                    externalAdapterName));
                    }

                    using (ManagementObject externalAdapter =
                               WmiUtilities.GetFirstObjectFromCollection(externalAdapterCollection))

                        //
                        // Get the default Msvm_EthernetPortAllocationSettingData instance, which we can use to
                        // configure our external port connection for the switch.
                        // Use the same switch name, appended with "_External", for the port name.
                        // You can use any port name that you like.
                        //
                        using (ManagementObject portToCreate =
                                   NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                        {
                            portToCreate["ElementName"]  = switchName + "_External";
                            portToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                            portToCreateText = portToCreate.GetText(TextFormat.WmiDtd20);
                        }
                }

            //
            // Now add the port connection to the switch.
            //
            using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                using (ManagementBaseObject inParams =
                           switchService.GetMethodParameters("AddResourceSettings"))
                {
                    inParams["AffectedConfiguration"] = ethernetSwitchSettingPath;
                    inParams["ResourceSettings"]      = new string[] { portToCreateText };

                    using (ManagementBaseObject outParams =
                               switchService.InvokeMethod("AddResourceSettings", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "We added an external port connection to '{0}' on the switch '{1}'.",
                                            externalAdapterName, switchName));
        }
        RemovePorts(
            string switchName)
        {
            ManagementScope scope         = new ManagementScope(@"root\virtualization\v2");
            List <string>   portsToDelete = new List <string>();

            //
            // Find the switch that we want to modify.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))

                //
                // Find its internal and/or external ports to delete, but don't delete any ports that
                // are connected to virtual machines.
                // Internal ports can be recognized because their HostResource property is set to the
                // host computer.
                // Likewise, external ports can be recognized through their HostResource property,
                // which is always set to the Msvm_ExternalEthernetPort it is connected to.
                //
                using (ManagementObjectCollection ports = ethernetSwitch.GetRelated("Msvm_EthernetSwitchPort",
                                                                                    "Msvm_SystemDevice",
                                                                                    null, null, null, null, false, null))
                {
                    foreach (ManagementObject port in ports)
                    {
                        using (port)
                        {
                            //
                            // The port's connection settings are stored on its related
                            // Msvm_EthernetPortAllocationSettingData object.
                            //
                            using (ManagementObject portSettings = WmiUtilities.GetFirstObjectFromCollection(
                                       port.GetRelated("Msvm_EthernetPortAllocationSettingData",
                                                       "Msvm_ElementSettingData",
                                                       null, null, null, null, false, null)))
                            {
                                string[] hostResource = (string[])portSettings["HostResource"];

                                if (hostResource != null && hostResource.Length > 0)
                                {
                                    ManagementPath hostResourcePath = new ManagementPath(hostResource[0]);

                                    if (string.Equals(hostResourcePath.ClassName, "Msvm_ComputerSystem",
                                                      StringComparison.OrdinalIgnoreCase))
                                    {
                                        // This is the internal port. Add it to the list to delete.
                                        portsToDelete.Add(portSettings.Path.Path);
                                    }
                                    else if (string.Equals(hostResourcePath.ClassName, "Msvm_ExternalEthernetPort",
                                                           StringComparison.OrdinalIgnoreCase))
                                    {
                                        // This is the external port. Add it to the list to delete.
                                        portsToDelete.Add(portSettings.Path.Path);
                                    }
                                }
                            }
                        }
                    }
                }

            if (portsToDelete.Count == 0)
            {
                throw new ManagementException(string.Format(CultureInfo.InvariantCulture,
                                                            "The switch '{0}' does not have any internal or external ports to remove.",
                                                            switchName));
            }

            //
            // Now that we have the ports we want to delete we can call the RemoveResourceSettings
            // method.
            //
            using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                using (ManagementBaseObject inParams = switchService.GetMethodParameters("RemoveResourceSettings"))
                {
                    inParams["ResourceSettings"] = portsToDelete.ToArray();

                    using (ManagementBaseObject outParams = switchService.InvokeMethod("RemoveResourceSettings", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "We removed the internal and external ports from switch '{0}' successfully.", switchName));
        }
        ModifyPorts(
            string switchName,
            string newExternalAdapterName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            ObjectQuery externalAdapterQuery = new ObjectQuery(string.Format(CultureInfo.InvariantCulture,
                                                                             "select * from Msvm_ExternalEthernetPort where Name=\"{0}\"", newExternalAdapterName));

            //
            // Find the switch that we want to modify.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))

                //
                // Get the external adapter we are connecting to.
                //
                using (ManagementObjectSearcher externalAdapterExecute = new ManagementObjectSearcher(scope, externalAdapterQuery))
                    using (ManagementObjectCollection externalAdapterCollection = externalAdapterExecute.Get())
                    {
                        if (externalAdapterCollection.Count == 0)
                        {
                            throw new ManagementException("There is no external adapter with the name: " + newExternalAdapterName);
                        }

                        string externalAdapterPath;
                        string externalPortSettingsText = null;

                        using (ManagementObject externalAdapter = WmiUtilities.GetFirstObjectFromCollection(externalAdapterCollection))
                        {
                            externalAdapterPath = externalAdapter.Path.Path;
                        }

                        //
                        // Find the switch's current external port.
                        //

                        using (ManagementObjectCollection ports = ethernetSwitch.GetRelated("Msvm_EthernetSwitchPort",
                                                                                            "Msvm_SystemDevice",
                                                                                            null, null, null, null, false, null))
                            foreach (ManagementObject port in ports)
                            {
                                using (port)
                                {
                                    //
                                    // The port's connection settings are stored on its related
                                    // Msvm_EthernetPortAllocationSettingData object.
                                    // The external port is the one connected to a Msvm_ExternalEthernetPort
                                    // through its HostResource property.
                                    //
                                    using (ManagementObject portSettings = WmiUtilities.GetFirstObjectFromCollection(
                                               port.GetRelated("Msvm_EthernetPortAllocationSettingData",
                                                               "Msvm_ElementSettingData",
                                                               null, null, null, null, false, null)))
                                    {
                                        string[] hostResource = (string[])portSettings["HostResource"];

                                        if (hostResource != null && hostResource.Length > 0)
                                        {
                                            ManagementPath hostResourcePath = new ManagementPath(hostResource[0]);

                                            if (string.Equals(hostResourcePath.ClassName, "Msvm_ExternalEthernetPort",
                                                              StringComparison.OrdinalIgnoreCase))
                                            {
                                                //
                                                // Validate that it isn't already connected to the external adapter we
                                                // are trying to change it to.
                                                //
                                                if (string.Equals(hostResourcePath.Path, externalAdapterPath,
                                                                  StringComparison.OrdinalIgnoreCase))
                                                {
                                                    throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                                                "The switch '{0}' is already connected to '{1}'.",
                                                                                                switchName, newExternalAdapterName));
                                                }

                                                //
                                                // Now that we have the switch's external port, we can modify it so that it
                                                // is connected to newExternalAdapterName.
                                                //

                                                portSettings["HostResource"] = new string[] { externalAdapterPath };
                                                externalPortSettingsText     = portSettings.GetText(TextFormat.WmiDtd20);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                        if (externalPortSettingsText == null)
                        {
                            throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                        "The switch '{0}' is not connected to an external network.", switchName));
                        }

                        using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                            using (ManagementBaseObject inParams = switchService.GetMethodParameters("ModifyResourceSettings"))
                            {
                                inParams["ResourceSettings"] = new string[] { externalPortSettingsText };

                                using (ManagementBaseObject outParams =
                                           switchService.InvokeMethod("ModifyResourceSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                    }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully bound the switch '{0}' to the external network '{1}'.",
                                            switchName, newExternalAdapterName));
        }
        MoveExtension(
            string switchName,
            string extensionName,
            int offset)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Get the switch we want to modify.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))

                //
                // To make modifications to the switch, we need to modify its configuration object.
                //
                using (ManagementObject ethernetSwitchSettings = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    string[] extensionOrder = (string[])ethernetSwitchSettings["ExtensionOrder"];
                    byte[]   extensionTypes = new byte[extensionOrder.Length];
                    int      extensionIndex = -1;

                    for (int idx = 0; idx < extensionOrder.Length; ++idx)
                    {
                        using (ManagementObject extension = new ManagementObject(extensionOrder[idx]))
                        {
                            extension.Get();

                            extensionTypes[idx] = (byte)extension["ExtensionType"];

                            if (String.Equals(
                                    (string)extension["ElementName"],
                                    extensionName,
                                    StringComparison.OrdinalIgnoreCase))
                            {
                                extensionIndex = idx;
                            }
                        }
                    }

                    if (extensionIndex == -1)
                    {
                        throw new ApplicationException(String.Format(
                                                           CultureInfo.CurrentCulture,
                                                           "Could not find extension '{0}' on switch '{1}'.",
                                                           extensionName,
                                                           switchName));
                    }

                    //
                    // Ensure that this is a valid move operation. The new extension index must
                    // be in range, and the extension cannot be interleaved with other extensions of
                    // a different type.
                    //
                    int newExtensionIndex = extensionIndex + offset;

                    if ((newExtensionIndex < 0) || (newExtensionIndex >= extensionOrder.Length))
                    {
                        throw new ApplicationException("Invalid move operation.");
                    }

                    if (extensionTypes[newExtensionIndex] != extensionTypes[extensionIndex])
                    {
                        throw new ApplicationException("Invalid move operation.");
                    }

                    //
                    // Reorder the extensions and apply the switch settings changes.
                    //
                    string temp = extensionOrder[newExtensionIndex];
                    extensionOrder[newExtensionIndex] = extensionOrder[extensionIndex];
                    extensionOrder[extensionIndex]    = temp;

                    ethernetSwitchSettings["ExtensionOrder"] = extensionOrder;

                    using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                        using (ManagementBaseObject inParams = switchService.GetMethodParameters("ModifySystemSettings"))
                        {
                            inParams["SystemSettings"] = ethernetSwitchSettings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       switchService.InvokeMethod("ModifySystemSettings", inParams, null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                }

            Console.WriteLine(string.Format(
                                  CultureInfo.CurrentCulture,
                                  "Extension '{0}' was successfully reordered on switch '{1}'.",
                                  extensionName,
                                  switchName));
        }