From 5d2b5d25b39de995599215d61672342e5a9408cd Mon Sep 17 00:00:00 2001 From: Francisco Santos Date: Tue, 21 Mar 2017 21:48:52 +0000 Subject: [PATCH] Initial commit --- NetworkCardRestart.sln | 22 + NetworkCardRestart/App.config | 7 + NetworkCardRestart/NetworkAdapter.cs | 1883 +++++++++++++++++ NetworkCardRestart/NetworkCardRestart.csproj | 64 + NetworkCardRestart/Program.cs | 85 + NetworkCardRestart/Properties/AssemblyInfo.cs | 36 + 6 files changed, 2097 insertions(+) create mode 100644 NetworkCardRestart.sln create mode 100644 NetworkCardRestart/App.config create mode 100644 NetworkCardRestart/NetworkAdapter.cs create mode 100644 NetworkCardRestart/NetworkCardRestart.csproj create mode 100644 NetworkCardRestart/Program.cs create mode 100644 NetworkCardRestart/Properties/AssemblyInfo.cs diff --git a/NetworkCardRestart.sln b/NetworkCardRestart.sln new file mode 100644 index 0000000..6e92946 --- /dev/null +++ b/NetworkCardRestart.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetworkCardRestart", "NetworkCardRestart\NetworkCardRestart.csproj", "{BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/NetworkCardRestart/App.config b/NetworkCardRestart/App.config new file mode 100644 index 0000000..d9a3400 --- /dev/null +++ b/NetworkCardRestart/App.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/NetworkCardRestart/NetworkAdapter.cs b/NetworkCardRestart/NetworkAdapter.cs new file mode 100644 index 0000000..be7a118 --- /dev/null +++ b/NetworkCardRestart/NetworkAdapter.cs @@ -0,0 +1,1883 @@ +namespace ROOT.CIMV2.Win32 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + + + // As funções ShouldSerialize são funções utilizadas pela janela de propriedades de VS para verificar se é necessário serializar uma propriedade em particular. Estas funções são adicionadas para todas as propriedades ValueType (propriedades do tipo Int32, BOOL, etc., que não é possível definir com o valor Null). Estas funções utilizam a função IsNull. Estas funções são igualmente utilizadas na implementação de TypeConverter para que as propriedades possam verificar se uma propriedade tem o valor NULL, para que seja possível apresentar um valor vazio na janela de propriedades caso sejam utilizadas as opções de arrastar e largar no Visual Studio. + // As funções IsNull() são utilizadas para verificar se uma propriedade é NULL. + // As funções Reset são adicionadas às propriedades Read/Write que permitem o valor Null. Estas funções são utilizadas pelo estruturador de VS na janela de propriedades para definir uma propriedade com o valor NULL. + // Todas as propriedades adicionadas à classe da propriedade WMI têm atributos especificados para definir o respectivo comportamento no estruturador do Visual Studio, bem como para definir um TypeConverter a utilizar. + // As funções de conversão de data e hora ToDateTime e ToDmtfDateTime são adicionadas à classe para converter a data e hora DMTF em System.DateTime e vice-versa. + // Foi gerada uma classe Early Bound para a classe WMI.Win32_NetworkAdapter + public class NetworkAdapter : System.ComponentModel.Component { + + // Propriedade privada para conter o espaço de nomes WMI em que a classe reside. + private static string CreatedWmiNamespace = "root\\CimV2"; + + // Propriedade privada para conter o nome da classe WMI que criou esta classe. + private static string CreatedClassName = "Win32_NetworkAdapter"; + + // Variável de membro privado para conter o ManagementScope utilizado pelos diferentes métodos. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Objecto WMI lateBound subjacente. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Variável de membro para armazenar o comportamento de consolidação automática da classe. + private bool AutoCommitProp; + + // Variável privada para conter a propriedade incorporada que representa a instância. + private System.Management.ManagementBaseObject embeddedObj; + + // O objecto WMI actual utilizado + private System.Management.ManagementBaseObject curObj; + + // Sinalizador para indicar se a instância é um objecto incorporado. + private bool isEmbedded; + + // Seguem-se diferentes sobrecargas de construtores para inicializar uma instância da classe com um objecto WMI. + public NetworkAdapter() { + this.InitializeObject(null, null, null); + } + + public NetworkAdapter(string keyDeviceID) { + this.InitializeObject(null, new System.Management.ManagementPath(NetworkAdapter.ConstructPath(keyDeviceID)), null); + } + + public NetworkAdapter(System.Management.ManagementScope mgmtScope, string keyDeviceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(NetworkAdapter.ConstructPath(keyDeviceID)), null); + } + + public NetworkAdapter(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public NetworkAdapter(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public NetworkAdapter(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public NetworkAdapter(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public NetworkAdapter(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("O nome da classe não corresponde."); + } + } + + public NetworkAdapter(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("O nome da classe não corresponde."); + } + } + + // A propriedade devolve o espaço de nomes da classe WMI. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "root\\CimV2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Propriedade que aponta para um objecto incorporado para obter as propriedades System do objecto WMI. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Propriedade que devolve o objecto lateBound subjacente. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope do objecto. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Propriedade para mostrar o comportamento de consolidação do objecto WMI. Se a definição for true, o objecto WMI será automaticamente guardado após cada modificação de propriedade (ou seja, Put() é chamado depois de uma propriedade ter sido modificada). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // ManagementPath do objecto WMI subjacente. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("O nome da classe não corresponde."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Propriedade pública de âmbito estático utilizada pelos diferentes métodos. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The AdapterType property reflects the network medium in use. This property may no" + + "t be applicable to all types of network adapters listed within this class. Windo" + + "ws NT only.")] + public string AdapterType { + get { + return ((string)(curObj["AdapterType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAdapterTypeIdNull { + get { + if ((curObj["AdapterTypeId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The AdapterTypeId property reflects the network medium in use. This property gives the same information as the AdapterType property, except that the the information is returned in the form of an integer value that corresponds to the following: +0 - Ethernet 802.3 +1 - Token Ring 802.5 +2 - Fiber Distributed Data Interface (FDDI) +3 - Wide Area Network (WAN) +4 - LocalTalk +5 - Ethernet using DIX header format +6 - ARCNET +7 - ARCNET (878.2) +8 - ATM +9 - Wireless +10 - Infrared Wireless +11 - Bpc +12 - CoWan +13 - 1394 +This property may not be applicable to all types of network adapters listed within this class. Windows NT only.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public AdapterTypeIdValues AdapterTypeId { + get { + if ((curObj["AdapterTypeId"] == null)) { + return ((AdapterTypeIdValues)(System.Convert.ToInt32(14))); + } + return ((AdapterTypeIdValues)(System.Convert.ToInt32(curObj["AdapterTypeId"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A boolean indicating whether the NetworkAdapter is capable of automatically deter" + + "mining the speed or other communications characteristics of the attached network" + + " media.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The availability and status of the device. For example, the Availability property indicates that the device is running and has full power (value=3), or is in a warning (4), test (5), degraded (10) or power save state (values 13-15 and 17). Regarding the power saving states, these are defined as follows: Value 13 (""Power Save - Unknown"") indicates that the device is known to be in a power save mode, but its exact status in this mode is unknown; 14 (""Power Save - Low Power Mode"") indicates that the device is in a power save state but still functioning, and may exhibit degraded performance; 15 (""Power Save - Standby"") describes that the device is not functioning but could be brought to full power 'quickly'; and value 17 (""Power Save - Warning"") indicates that the device is in a warning state, though also in a power save mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public AvailabilityValues Availability { + get { + if ((curObj["Availability"] == null)) { + return ((AvailabilityValues)(System.Convert.ToInt32(0))); + } + return ((AvailabilityValues)(System.Convert.ToInt32(curObj["Availability"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConfigManagerErrorCodeNull { + get { + if ((curObj["ConfigManagerErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the Win32 Configuration Manager error code. The following values may b" + + "e returned: \n0 This device is working properly. \n1 This device is not " + + "configured correctly. \n2 Windows cannot load the driver for this device. \n3" + + " The driver for this device might be corrupted, or your system may be runni" + + "ng low on memory or other resources. \n4 This device is not working properly" + + ". One of its drivers or your registry might be corrupted. \n5 The driver for" + + " this device needs a resource that Windows cannot manage. \n6 The boot confi" + + "guration for this device conflicts with other devices. \n7 Cannot filter. \n8" + + " The driver loader for the device is missing. \n9 This device is not wo" + + "rking properly because the controlling firmware is reporting the resources for t" + + "he device incorrectly. \n10 This device cannot start. \n11 This device fai" + + "led. \n12 This device cannot find enough free resources that it can use. \n13 " + + " Windows cannot verify this device\'s resources. \n14 This device cannot wo" + + "rk properly until you restart your computer. \n15 This device is not working " + + "properly because there is probably a re-enumeration problem. \n16 Windows can" + + "not identify all the resources this device uses. \n17 This device is asking f" + + "or an unknown resource type. \n18 Reinstall the drivers for this device. \n19 " + + " Your registry might be corrupted. \n20 Failure using the VxD loader. \n21 " + + " System failure: Try changing the driver for this device. If that does not wo" + + "rk, see your hardware documentation. Windows is removing this device. \n22 Th" + + "is device is disabled. \n23 System failure: Try changing the driver for this " + + "device. If that doesn\'t work, see your hardware documentation. \n24 This devi" + + "ce is not present, is not working properly, or does not have all its drivers ins" + + "talled. \n25 Windows is still setting up this device. \n26 Windows is stil" + + "l setting up this device. \n27 This device does not have valid log configurat" + + "ion. \n28 The drivers for this device are not installed. \n29 This device " + + "is disabled because the firmware of the device did not give it the required reso" + + "urces. \n30 This device is using an Interrupt Request (IRQ) resource that ano" + + "ther device is using. \n31 This device is not working properly because Window" + + "s cannot load the drivers required for this device.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ConfigManagerErrorCodeValues ConfigManagerErrorCode { + get { + if ((curObj["ConfigManagerErrorCode"] == null)) { + return ((ConfigManagerErrorCodeValues)(System.Convert.ToInt32(32))); + } + return ((ConfigManagerErrorCodeValues)(System.Convert.ToInt32(curObj["ConfigManagerErrorCode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConfigManagerUserConfigNull { + get { + if ((curObj["ConfigManagerUserConfig"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the device is using a user-defined configuration.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ConfigManagerUserConfig { + get { + if ((curObj["ConfigManagerUserConfig"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ConfigManagerUserConfig"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("CreationClassName indicates the name of the class or the subclass used in the cre" + + "ation of an instance. When used with the other key properties of this class, thi" + + "s property allows all instances of this class and its subclasses to be uniquely " + + "identified.")] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The DeviceID property contains a string uniquely identifying the network adapter " + + "from other devices on the system.")] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("ErrorCleared is a boolean property indicating that the error reported in LastErro" + + "rCode property is now cleared.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("ErrorDescription is a free-form string supplying more information about the error" + + " recorded in LastErrorCode property, and information on any corrective actions t" + + "hat may be taken.")] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The GUID property specifies the Globally-unique identifier for the connection.")] + public string GUID { + get { + return ((string)(curObj["GUID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIndexNull { + get { + if ((curObj["Index"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Index property indicates the network adapter\'s index number, which is stored" + + " in the system registry. \nExample: 0.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Index { + get { + if ((curObj["Index"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Index"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstalledNull { + get { + if ((curObj["Installed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The Installed property determines whether the network adapter is installed in the system. +Values: TRUE or FALSE. A value of TRUE indicates the network adapter is installed. +The Installed property has been deprecated. There is no replacementvalue and this property is now considered obsolete.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Installed { + get { + if ((curObj["Installed"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Installed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInterfaceIndexNull { + get { + if ((curObj["InterfaceIndex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The InterfaceIndex property contains the index value that uniquely identifies the" + + " local interface.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint InterfaceIndex { + get { + if ((curObj["InterfaceIndex"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["InterfaceIndex"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("LastErrorCode captures the last error code reported by the logical device.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The MACAddress property indicates the media access control address for this network adapter. A MAC address is a unique 48-bit number assigned to the network adapter by the manufacturer. It uniquely identifies this network adapter and is used for mapping TCP/IP network communications.")] + public string MACAddress { + get { + return ((string)(curObj["MACAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The Manufacturer property indicates the name of the network adapter\'s manufacture" + + "r.\nExample: 3COM.")] + public string Manufacturer { + get { + return ((string)(curObj["Manufacturer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxNumberControlledNull { + get { + if ((curObj["MaxNumberControlled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The MaxNumberControlled property indicates the maximum number of directly address" + + "able ports supported by this network adapter. A value of zero should be used if " + + "the number is unknown.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxNumberControlled { + get { + if ((curObj["MaxNumberControlled"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxNumberControlled"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum speed, in bits per second, for the network adapter.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The NetConnectionID property specifies the name of the network connection as it a" + + "ppears in the \'Network Connections\' folder.")] + public string NetConnectionID { + get { + return ((string)(curObj["NetConnectionID"])); + } + set { + curObj["NetConnectionID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNetConnectionStatusNull { + get { + if ((curObj["NetConnectionStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"NetConnectionStatus is a string indicating the state of the network adapter's connection to the network. The value of the property is to be interpreted as follows: +0 - Disconnected +1 - Connecting +2 - Connected +3 - Disconnecting +4 - Hardware not present +5 - Hardware disabled +6 - Hardware malfunction +7 - Media disconnected +8 - Authenticating +9 - Authentication succeeded +10 - Authentication failed +11 - Invalid Address +12 - Credentials Required +.. - Other - For integer values other than those listed above, refer to Win32 error code documentation.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NetConnectionStatus { + get { + if ((curObj["NetConnectionStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NetConnectionStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNetEnabledNull { + get { + if ((curObj["NetEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The NetEnabled property specifies whether the network connection is enabled or no" + + "t.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool NetEnabled { + get { + if ((curObj["NetEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["NetEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of strings indicating the network addresses for an adapter.")] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"PermanentAddress defines the network address hard coded into an adapter. This 'hard coded' address may be changed via firmware upgrade or software configuration. If so, this field should be updated when the change is made. PermanentAddress should be left blank if no 'hard coded' address exists for the network adapter.")] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPhysicalAdapterNull { + get { + if ((curObj["PhysicalAdapter"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The PhysicalAdapter property specifies whether the adapter is physical adapter or" + + " logical adapter.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PhysicalAdapter { + get { + if ((curObj["PhysicalAdapter"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PhysicalAdapter"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the Win32 Plug and Play device ID of the logical device. Example: *PNP" + + "030b")] + public string PNPDeviceID { + get { + return ((string)(curObj["PNPDeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates the specific power-related capabilities of the logical device. The array values, 0=""Unknown"", 1=""Not Supported"" and 2=""Disabled"" are self-explanatory. The value, 3=""Enabled"" indicates that the power management features are currently enabled but the exact feature set is unknown or the information is unavailable. ""Power Saving Modes Entered Automatically"" (4) describes that a device can change its power state based on usage or other criteria. ""Power State Settable"" (5) indicates that the SetPowerState method is supported. ""Power Cycling Supported"" (6) indicates that the SetPowerState method can be invoked with the PowerState input variable set to 5 (""Power Cycle""). ""Timed Power On Supported"" (7) indicates that the SetPowerState method can be invoked with the PowerState input variable set to 5 (""Power Cycle"") and the Time parameter set to a specific date and time, or interval, for power-on.")] + public PowerManagementCapabilitiesValues[] PowerManagementCapabilities { + get { + System.Array arrEnumVals = ((System.Array)(curObj["PowerManagementCapabilities"])); + PowerManagementCapabilitiesValues[] enumToRet = new PowerManagementCapabilitiesValues[arrEnumVals.Length]; + int counter = 0; + for (counter = 0; (counter < arrEnumVals.Length); counter = (counter + 1)) { + enumToRet[counter] = ((PowerManagementCapabilitiesValues)(System.Convert.ToInt32(arrEnumVals.GetValue(counter)))); + } + return enumToRet; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Boolean indicating that the Device can be power managed - ie, put into a power save state. This boolean does not indicate that power management features are currently enabled, or if enabled, what features are supported. Refer to the PowerManagementCapabilities array for this information. If this boolean is false, the integer value 1, for the string, ""Not Supported"", should be the only entry in the PowerManagementCapabilities array.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The ProductName property indicates the product name of the network adapter.\nExamp" + + "le: Fast EtherLink XL")] + public string ProductName { + get { + return ((string)(curObj["ProductName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The ServiceName property indicates the service name of the network adapter. This " + + "name is usually shorter that the full product name. \nExample: Elnkii.")] + public string ServiceName { + get { + return ((string)(curObj["ServiceName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An estimate of the current bandwidth in bits per second. For endpoints which vary" + + " in bandwidth or for those where no accurate estimation can be made, this proper" + + "ty should contain the nominal bandwidth.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("StatusInfo is a string indicating whether the logical device is in an enabled (va" + + "lue = 3), disabled (value = 4) or some other (1) or unknown (2) state. If this p" + + "roperty does not apply to the logical device, the value, 5 (\"Not Applicable\"), s" + + "hould be used.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public StatusInfoValues StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return ((StatusInfoValues)(System.Convert.ToInt32(0))); + } + return ((StatusInfoValues)(System.Convert.ToInt32(curObj["StatusInfo"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The scoping System\'s CreationClassName.")] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The scoping System\'s Name.")] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastResetNull { + get { + if ((curObj["TimeOfLastReset"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The TimeOfLastReset property indicates when the network adapter was last reset.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastReset { + get { + if ((curObj["TimeOfLastReset"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastReset"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAdapterTypeId() { + if ((this.IsAdapterTypeIdNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConfigManagerErrorCode() { + if ((this.IsConfigManagerErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConfigManagerUserConfig() { + if ((this.IsConfigManagerUserConfigNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIndex() { + if ((this.IsIndexNull == false)) { + return true; + } + return false; + } + + // Converte uma data/hora determinada em formato DMTF no objecto System.DateTime. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converte um objecto System.DateTime determinado no formato de data/hora DMTF. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInstalled() { + if ((this.IsInstalledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInterfaceIndex() { + if ((this.IsInterfaceIndexNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxNumberControlled() { + if ((this.IsMaxNumberControlledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private void ResetNetConnectionID() { + curObj["NetConnectionID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeNetConnectionStatus() { + if ((this.IsNetConnectionStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNetEnabled() { + if ((this.IsNetEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePhysicalAdapter() { + if ((this.IsPhysicalAdapterNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastReset() { + if ((this.IsTimeOfLastResetNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyDeviceID) { + string strPath = "root\\CimV2:Win32_NetworkAdapter"; + strPath = string.Concat(strPath, string.Concat(".DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("O nome da classe não corresponde."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Diferentes sobrecargas de GetInstances() ajudam a enumerar instâncias da classe WMI. + public static NetworkAdapterCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static NetworkAdapterCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static NetworkAdapterCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static NetworkAdapterCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static NetworkAdapterCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CimV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Win32_NetworkAdapter"; + pathObj.NamespacePath = "root\\CimV2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new NetworkAdapterCollection(clsObject.GetInstances(enumOptions)); + } + + public static NetworkAdapterCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static NetworkAdapterCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static NetworkAdapterCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\CimV2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_NetworkAdapter", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new NetworkAdapterCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static NetworkAdapter CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new NetworkAdapter(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint Disable() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Disable", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint Enable() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Enable", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum AdapterTypeIdValues { + + Ethernet_802_3 = 0, + + Token_Ring_802_5 = 1, + + Fiber_Distributed_Data_Interface_FDDI_ = 2, + + Wide_Area_Network_WAN_ = 3, + + LocalTalk = 4, + + Ethernet_using_DIX_header_format = 5, + + ARCNET = 6, + + ARCNET_878_2_ = 7, + + ATM = 8, + + Wireless = 9, + + Infrared_Wireless = 10, + + Bpc = 11, + + CoWan = 12, + + Val_1394 = 13, + + NULL_ENUM_VALUE = 14, + } + + public enum AvailabilityValues { + + Other0 = 1, + + Unknown0 = 2, + + Running_Full_Power = 3, + + Warning = 4, + + In_Test = 5, + + Not_Applicable = 6, + + Power_Off = 7, + + Off_Line = 8, + + Off_Duty = 9, + + Degraded = 10, + + Not_Installed = 11, + + Install_Error = 12, + + Power_Save_Unknown = 13, + + Power_Save_Low_Power_Mode = 14, + + Power_Save_Standby = 15, + + Power_Cycle = 16, + + Power_Save_Warning = 17, + + Paused = 18, + + Not_Ready = 19, + + Not_Configured = 20, + + Quiesced = 21, + + NULL_ENUM_VALUE = 0, + } + + public enum ConfigManagerErrorCodeValues { + + This_device_is_working_properly_ = 0, + + This_device_is_not_configured_correctly_ = 1, + + Windows_cannot_load_the_driver_for_this_device_ = 2, + + The_driver_for_this_device_might_be_corrupted_or_your_system_may_be_running_low_on_memory_or_other_resources_ = 3, + + This_device_is_not_working_properly_One_of_its_drivers_or_your_registry_might_be_corrupted_ = 4, + + The_driver_for_this_device_needs_a_resource_that_Windows_cannot_manage_ = 5, + + The_boot_configuration_for_this_device_conflicts_with_other_devices_ = 6, + + Cannot_filter_ = 7, + + The_driver_loader_for_the_device_is_missing_ = 8, + + This_device_is_not_working_properly_because_the_controlling_firmware_is_reporting_the_resources_for_the_device_incorrectly_ = 9, + + This_device_cannot_start_ = 10, + + This_device_failed_ = 11, + + This_device_cannot_find_enough_free_resources_that_it_can_use_ = 12, + + Windows_cannot_verify_this_device_s_resources_ = 13, + + This_device_cannot_work_properly_until_you_restart_your_computer_ = 14, + + This_device_is_not_working_properly_because_there_is_probably_a_re_enumeration_problem_ = 15, + + Windows_cannot_identify_all_the_resources_this_device_uses_ = 16, + + This_device_is_asking_for_an_unknown_resource_type_ = 17, + + Reinstall_the_drivers_for_this_device_ = 18, + + Failure_using_the_VxD_loader_ = 19, + + Your_registry_might_be_corrupted_ = 20, + + System_failure_Try_changing_the_driver_for_this_device_If_that_does_not_work_see_your_hardware_documentation_Windows_is_removing_this_device_ = 21, + + This_device_is_disabled_ = 22, + + System_failure_Try_changing_the_driver_for_this_device_If_that_doesn_t_work_see_your_hardware_documentation_ = 23, + + This_device_is_not_present_is_not_working_properly_or_does_not_have_all_its_drivers_installed_ = 24, + + Windows_is_still_setting_up_this_device_ = 25, + + Windows_is_still_setting_up_this_device_0 = 26, + + This_device_does_not_have_valid_log_configuration_ = 27, + + The_drivers_for_this_device_are_not_installed_ = 28, + + This_device_is_disabled_because_the_firmware_of_the_device_did_not_give_it_the_required_resources_ = 29, + + This_device_is_using_an_Interrupt_Request_IRQ_resource_that_another_device_is_using_ = 30, + + This_device_is_not_working_properly_because_Windows_cannot_load_the_drivers_required_for_this_device_ = 31, + + NULL_ENUM_VALUE = 32, + } + + public enum PowerManagementCapabilitiesValues { + + Unknown0 = 0, + + Not_Supported = 1, + + Disabled = 2, + + Enabled = 3, + + Power_Saving_Modes_Entered_Automatically = 4, + + Power_State_Settable = 5, + + Power_Cycling_Supported = 6, + + Timed_Power_On_Supported = 7, + + NULL_ENUM_VALUE = 8, + } + + public enum StatusInfoValues { + + Other0 = 1, + + Unknown0 = 2, + + Enabled = 3, + + Disabled = 4, + + Not_Applicable = 5, + + NULL_ENUM_VALUE = 0, + } + + // Implementação do enumerador para enumerar instâncias da classe. + public class NetworkAdapterCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public NetworkAdapterCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new NetworkAdapter(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new NetworkAdapterEnumerator(privColObj.GetEnumerator()); + } + + public class NetworkAdapterEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public NetworkAdapterEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new NetworkAdapter(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter para processar valores null de propriedades ValueType + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Classe incorporada para representar as propriedades System de WMI. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/NetworkCardRestart/NetworkCardRestart.csproj b/NetworkCardRestart/NetworkCardRestart.csproj new file mode 100644 index 0000000..eda610c --- /dev/null +++ b/NetworkCardRestart/NetworkCardRestart.csproj @@ -0,0 +1,64 @@ + + + + + Debug + AnyCPU + {BB1FA4A3-027A-4FF6-B84B-D3FCCA95946A} + Exe + Properties + NetworkCardRestart + NetworkCardRestart + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + Component + + + + + + + + + + \ No newline at end of file diff --git a/NetworkCardRestart/Program.cs b/NetworkCardRestart/Program.cs new file mode 100644 index 0000000..1da1fbe --- /dev/null +++ b/NetworkCardRestart/Program.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management; +using System.Net; +using System.Net.NetworkInformation; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ROOT.CIMV2.Win32; + +namespace NetworkCardRestart +{ + class Program + { + private const int MillisecondsTimeout = 3000; + + static void Main(string[] args) + { + while (!PingTest()) + { + RestartAdapter(); + } + Console.ReadLine(); + } + + private static void RestartAdapter() + { + Console.WriteLine("Restarting Adapters..."); + SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2"); + ManagementObjectSearcher search = new ManagementObjectSearcher(query); + ArrayList threads = new ArrayList(); + foreach (ManagementObject result in search.Get()) + { + Thread t = new Thread(() => + { + NetworkAdapter adapter = new NetworkAdapter(result); + + // Identify the adapter you wish to disable here. + // In particular, check the AdapterType and + // Description properties. + + // Here, we're selecting the LAN adapters. + if (adapter.AdapterType.Equals("Ethernet 802.3")) + { + adapter.Disable(); + Console.WriteLine("Waiting " + MillisecondsTimeout / 1000 + " seconds to activate the card."); + Thread.Sleep(MillisecondsTimeout); + adapter.Enable(); + } + }); + t.Start(); + threads.Add(t); + + } + + foreach (Thread thread in threads) + { + thread.Join(); + } + } + + // Ping www.google.com to check if the user has a internet connection. + private static bool PingTest() + { + Console.WriteLine("Checking if Internet is avaliable..."); + + Ping ping = new Ping(); + + PingReply pingStatus = ping.Send(IPAddress.Parse("google.com")); + + if (pingStatus != null && pingStatus.Status == IPStatus.Success) + { + Console.WriteLine("We have Internet access."); + return true; + } + else + { + Console.WriteLine("We don't have Internet access."); + return false; + } + } + } +} diff --git a/NetworkCardRestart/Properties/AssemblyInfo.cs b/NetworkCardRestart/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7fb1160 --- /dev/null +++ b/NetworkCardRestart/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("NetworkCardRestart")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Hewlett-Packard")] +[assembly: AssemblyProduct("NetworkCardRestart")] +[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bb1fa4a3-027a-4ff6-b84b-d3fcca95946a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")]