public virtual void Add(string methodName, ManagementBaseObject inParameters, ManagementBaseObject outParameters) {}
} // End DisplayEventInformation. // The main entry point for the application. static void Main(string[] args) { // Get the name of the computer on // which this program runs. // Note. The monitored application must also run // on this computer. string machine = Environment.MachineName; // Define the Common Information Model (CIM) path // for WIM monitoring. string path = String.Format("\\\\{0}\\root\\aspnet", machine); // Create a managed object watcher as // defined in System.Management. string query = "select * from BaseEvent"; ManagementEventWatcher watcher = new ManagementEventWatcher(query); // Set the watcher options. TimeSpan timeInterval = new TimeSpan(0, 1, 30); watcher.Options = new EventWatcherOptions(null, timeInterval, 1); // Set the scope of the WMI events to // watch to be ASP.NET applications. watcher.Scope = new ManagementScope(new ManagementPath(path)); // Set the console background. Console.BackgroundColor = ConsoleColor.Blue; // Set foreground color. Console.ForegroundColor = ConsoleColor.Yellow; // Clear the console. Console.Clear(); // Loop indefinitely to catch the events. Console.WriteLine( "Listener started. Enter CntlC to terminate"); while (true) { try { // Capture the WMI event related to // the Web event. ManagementBaseObject ev = watcher.WaitForNextEvent(); // Display the Web event information. DisplayEventInformation(ev); // Prompt the user. Console.Beep(); } catch (Exception e) { Console.WriteLine("Error: {0}", e); break; } } }
internal BIOS(ManagementBaseObject instance) { manufacturer = instance.Properties["Manufacturer"].Value.ToString().Trim(); name = instance.Properties["Name"].Value.ToString().Trim(); version = instance.Properties["Version"].Value.ToString().Trim(); releaseDate = instance.Properties["ReleaseDate"].Value.ToString().Trim(); sMBIOSBIOSVersion = instance.Properties["SMBIOSBIOSVersion"].Value.ToString().Trim(); biosCharacteristics = instance.Properties["BiosCharacteristics"].Value as ushort[]; bIOSVersion = instance.Properties["BIOSVersion"].Value as string[]; buildNumber = (instance.Properties["BuildNumber"].Value != null && instance.Properties["BuildNumber"].Value.ToString() != string.Empty) ? instance.Properties["BuildNumber"].Value.ToString().Trim() : string.Empty; caption = (instance.Properties["Caption"].Value != null && instance.Properties["Caption"].Value.ToString() != string.Empty) ? instance.Properties["Caption"].Value.ToString().Trim() : string.Empty; codeSet = (instance.Properties["CodeSet"].Value != null && instance.Properties["CodeSet"].Value.ToString() != string.Empty) ? instance.Properties["CodeSet"].Value.ToString().Trim() : string.Empty; currentLanguage = (instance.Properties["CurrentLanguage"].Value != null && instance.Properties["CurrentLanguage"].Value.ToString() != string.Empty) ? instance.Properties["CurrentLanguage"].Value.ToString().Trim() : string.Empty; description = (instance.Properties["Description"].Value != null && instance.Properties["Description"].Value.ToString() != string.Empty) ? instance.Properties["Description"].Value.ToString().Trim() : string.Empty; identificationCode = (instance.Properties["IdentificationCode"].Value != null && instance.Properties["IdentificationCode"].Value.ToString() != string.Empty) ? instance.Properties["IdentificationCode"].Value.ToString().Trim() : string.Empty; installableLanguages = (instance.Properties["InstallableLanguages"].Value != null && instance.Properties["InstallableLanguages"].Value.ToString() != string.Empty) ? instance.Properties["InstallableLanguages"].Value.ToString().Trim() : string.Empty; installDate = (instance.Properties["InstallDate"].Value != null && instance.Properties["InstallDate"].Value.ToString() != string.Empty) ? instance.Properties["InstallDate"].Value.ToString().Trim() : string.Empty; languageEdition = (instance.Properties["LanguageEdition"].Value != null && instance.Properties["LanguageEdition"].Value.ToString() != string.Empty) ? instance.Properties["LanguageEdition"].Value.ToString().Trim() : string.Empty; listOfLanguages = instance.Properties["ListOfLanguages"].Value as string[]; otherTargetOS = (instance.Properties["OtherTargetOS"].Value != null && instance.Properties["OtherTargetOS"].Value.ToString() != string.Empty) ? instance.Properties["OtherTargetOS"].Value.ToString().Trim() : string.Empty; primaryBIOS = (instance.Properties["PrimaryBIOS"].Value != null && instance.Properties["PrimaryBIOS"].Value.ToString() != string.Empty) ? instance.Properties["PrimaryBIOS"].Value.ToString().Trim() : string.Empty; serialNumber = (instance.Properties["SerialNumber"].Value != null && instance.Properties["SerialNumber"].Value.ToString() != string.Empty) ? instance.Properties["SerialNumber"].Value.ToString().Trim() : string.Empty; sMBIOSMajorVersion = (instance.Properties["SMBIOSMajorVersion"].Value != null && instance.Properties["SMBIOSMajorVersion"].Value.ToString() != string.Empty) ? instance.Properties["SMBIOSMajorVersion"].Value.ToString().Trim() : string.Empty; sMBIOSMinorVersion = (instance.Properties["SMBIOSMinorVersion"].Value != null && instance.Properties["SMBIOSMinorVersion"].Value.ToString() != string.Empty) ? instance.Properties["SMBIOSMinorVersion"].Value.ToString().Trim() : string.Empty; sMBIOSPresent = (instance.Properties["SMBIOSPresent"].Value != null && instance.Properties["SMBIOSPresent"].Value.ToString() != string.Empty) ? instance.Properties["SMBIOSPresent"].Value.ToString().Trim() : string.Empty; softwareElementID = (instance.Properties["SoftwareElementID"].Value != null && instance.Properties["SoftwareElementID"].Value.ToString() != string.Empty) ? instance.Properties["SoftwareElementID"].Value.ToString().Trim() : string.Empty; softwareElementState = (instance.Properties["SoftwareElementState"].Value != null && instance.Properties["SoftwareElementState"].Value.ToString() != string.Empty) ? instance.Properties["SoftwareElementState"].Value.ToString().Trim() : string.Empty; targetOperatingSystem = (instance.Properties["TargetOperatingSystem"].Value != null && instance.Properties["TargetOperatingSystem"].Value.ToString() != string.Empty) ? instance.Properties["TargetOperatingSystem"].Value.ToString().Trim() : string.Empty; status = (instance.Properties["Status"].Value != null && instance.Properties["Status"].Value.ToString() != string.Empty) ? instance.Properties["Status"].Value.ToString().Trim() : string.Empty; }
/// <summary> /// Trigger Done event when InvokeMethod is complete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Done(object sender, ObjectReadyEventArgs e) { isComplete = true; returnObject = e.NewObject; }
internal EventArrivedEventArgs(ManagementBaseObject newEvent) { this.new_event = newEvent; }
public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings) {}
private Win32UsbControllerDevice GetDevice(ManagementBaseObject managementObject) { try { Win32UsbControllerDevice win32UsbControllerDevice = new Win32UsbControllerDevice(); try { String dependent = managementObject.GetPropertyValue("Dependent").ToString(); win32UsbControllerDevice.DeviceId = this.ExtractSeviceId(dependent); } catch (Exception ex) { } try { String antecedent = managementObject.GetPropertyValue("Antecedent").ToString(); win32UsbControllerDevice.ControllerId = this.ExtractSeviceId(antecedent); } catch (Exception ex) { } try { String locationInformation = this.GetLocationInformation(win32UsbControllerDevice.DeviceId); Int32 hubIndex = locationInformation.IndexOf("HUB_#", StringComparison.OrdinalIgnoreCase); Int32 portIndex = locationInformation.IndexOf("PORT_#", StringComparison.OrdinalIgnoreCase); if ((hubIndex < 0) || (portIndex < 0)) { throw new Exception("Wrong location information format"); } win32UsbControllerDevice.Hub = locationInformation.Substring(hubIndex + 5, 4); win32UsbControllerDevice.Port = locationInformation.Substring(portIndex + 6, 4); } catch (Exception ex) { } try { Int32 vidIndex = win32UsbControllerDevice.DeviceId.IndexOf("VID", StringComparison.OrdinalIgnoreCase); Int32 pidIndex = win32UsbControllerDevice.DeviceId.IndexOf("PID", StringComparison.OrdinalIgnoreCase); if ((vidIndex < 0) || (pidIndex < 0)) { throw new Exception("Wrong device ID format"); } win32UsbControllerDevice.Vid = win32UsbControllerDevice.DeviceId.Substring(vidIndex + 4, 4); win32UsbControllerDevice.Pid = win32UsbControllerDevice.DeviceId.Substring(pidIndex + 4, 4); } catch (Exception ex) { } return(win32UsbControllerDevice); } catch (Exception ex) { } return(null); }
public WindowsGPUInfo(ManagementBaseObject win32_videoController) { _win32_videoController = win32_videoController; }
public ExternalEthernetPort(ManagementBaseObject theObject) : base(theObject, ClassName) { }
protected bool GetSystemDiskSerialNumber(ref string string_0, ref ulong ulong_0) { string_0 = "NoSN"; ulong_0 = 1UL; try { string str = Environment.GetFolderPath(Environment.SpecialFolder.System).Substring(0, 2); ManagementObjectCollection.ManagementObjectEnumerator enumerator = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk WHERE DeviceID='" + str + "'").Get().GetEnumerator(); try { while (enumerator.MoveNext()) { ManagementBaseObject managementBaseObject = enumerator.Current; ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = ((ManagementObject)managementBaseObject).GetRelated("Win32_DiskPartition").GetEnumerator(); try { while (enumerator2.MoveNext()) { ManagementBaseObject managementBaseObject2 = enumerator2.Current; ManagementObjectCollection.ManagementObjectEnumerator enumerator3 = ((ManagementObject)managementBaseObject2).GetRelated("Win32_DiskDrive").GetEnumerator(); try { while (enumerator3.MoveNext()) { ManagementBaseObject managementBaseObject3 = enumerator3.Current; ManagementObject managementObject = (ManagementObject)managementBaseObject3; try { ulong_0 = (ulong)managementObject["Size"]; object obj = null; try { if (obj == null) { for (; ;) { IL_101: int num = 437563971; for (; ;) { switch (num ^ 437563970) { case 1: obj = managementObject["SerialNumber"]; num = 437563970; continue; case 2: goto IL_101; } goto Block_20; } } Block_20 :; } } catch (Exception) { } try { if (obj == null) { obj = managementObject["Signature"]; } } catch (Exception) { } if (obj != null) { for (; ;) { IL_15A: int num2 = 437563969; for (; ;) { switch (num2 ^ 437563970) { case 0: goto IL_15A; case 1: goto IL_161; case 3: string_0 = obj.ToString(); num2 = 437563971; continue; } goto Block_17; } } Block_17: continue; IL_161: return(true); } } catch (Exception) { } } } finally { if (enumerator3 != null) { for (; ;) { IL_1A4: int num3 = 437563971; for (; ;) { switch (num3 ^ 437563970) { case 0: goto IL_1A4; case 1: ((IDisposable)enumerator3).Dispose(); num3 = 437563968; continue; } goto Block_27; } } Block_27 :; } } } } finally { if (enumerator2 != null) { for (; ;) { IL_1E2: int num4 = 437563968; for (; ;) { switch (num4 ^ 437563970) { case 0: goto IL_1E2; case 2: ((IDisposable)enumerator2).Dispose(); num4 = 437563971; continue; } goto Block_30; } } Block_30 :; } } } } finally { if (enumerator != null) { for (; ;) { IL_220: int num5 = 437563971; for (; ;) { switch (num5 ^ 437563970) { case 0: goto IL_220; case 1: ((IDisposable)enumerator).Dispose(); num5 = 437563968; continue; } goto Block_33; } } Block_33 :; } } } catch (Exception) { } return(false); }
public StorageExtendedStatus(ManagementBaseObject theObject) : base(theObject, ClassName) { }
public Memory(ManagementBaseObject theObject) : base(theObject, ClassName) { }
/// <summary> /// Deletes the share permission. /// </summary> /// <param name="accountName">Name of the account.</param> public void DeleteSharePermission(string accountName) { if (accountName == null) { throw new ArgumentNullException("accountName"); } ManagementObject win32LogicalSecuritySetting = null; ManagementBaseObject getSecurityDescriptorReturn = null; ManagementBaseObject securityDescriptor = null; ManagementObject share = null; try { win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'"); getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null); if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0) { throw new WindowsShareException("Unable to delete share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]); } securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject; ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[]; if (dacl == null) { throw new WindowsShareException("Unable to delete share permission. Access control not found"); } else { List <ManagementBaseObject> newDACL = new List <ManagementBaseObject>(); foreach (ManagementBaseObject ac in dacl) { if (((ac["Trustee"] as ManagementBaseObject)["Name"] as string).ToUpperInvariant() != accountName.ToUpperInvariant()) { newDACL.Add(ac); } } if (dacl.Count() == newDACL.Count()) { throw new WindowsShareException("Unable to delete share permission. Access control not found"); } dacl = newDACL.ToArray(); } securityDescriptor["DACL"] = dacl; share = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'"); uint setShareInfoReturn = (uint)share.InvokeMethod("SetShareInfo", new object[] { null, null, securityDescriptor }); if (setShareInfoReturn != 0) { throw new WindowsShareException("Unable to delete share permission. Error code:" + setShareInfoReturn.ToString(CultureInfo.InvariantCulture)); } } catch (Exception ex) { throw new WindowsShareException("Unable to delete share permission", ex); } finally { if (win32LogicalSecuritySetting != null) { win32LogicalSecuritySetting.Dispose(); } if (getSecurityDescriptorReturn != null) { getSecurityDescriptorReturn.Dispose(); } if (securityDescriptor != null) { securityDescriptor.Dispose(); } if (share != null) { share.Dispose(); } } }
/// <summary> /// Checks if the the share has permissions. /// </summary> /// <param name="accountName">Name of the account.</param> /// <returns>True if the share contains the permission.</returns> public bool HasPermission(string accountName) { ManagementObject win32LogicalSecuritySetting = null; ManagementBaseObject getSecurityDescriptorReturn = null; ManagementBaseObject securityDescriptor = null; try { win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'"); getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null); if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0) { throw new WindowsShareException("Unable to check share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]); } securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject; ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[]; if (dacl == null) { return(false); } else { foreach (var curAce in dacl) { string curTrustee = (curAce["Trustee"] as ManagementBaseObject)["Name"] as string; // if iTrustee == accountName if (curTrustee.Equals(accountName, StringComparison.OrdinalIgnoreCase)) { return(true); } } } return(false); } catch (Exception ex) { throw new WindowsShareException("Unable to check share permission", ex); } finally { if (win32LogicalSecuritySetting != null) { win32LogicalSecuritySetting.Dispose(); } if (getSecurityDescriptorReturn != null) { getSecurityDescriptorReturn.Dispose(); } if (securityDescriptor != null) { securityDescriptor.Dispose(); } } }
public ManagementBaseObject InvokeMethod(string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) {}
CheckCompatibility( string sourceHost, string destinationHost, string systemName = null ) { if (systemName == null) { systemName = sourceHost; } ManagementScope sourceScope = new ManagementScope( @"\\" + sourceHost + @"\root\virtualization\v2", null); object compatibilityInfo = null; // Get compatibility information for the source host. using (ManagementObject computerSystem = WmiUtilities.GetVirtualMachine(systemName, sourceScope)) using (ManagementObject sourceService = GetVirtualMachineMigrationService(sourceScope)) using (ManagementBaseObject sourceInParams = sourceService.GetMethodParameters("GetSystemCompatibilityInfo")) { sourceInParams["ComputerSystem"] = computerSystem.Path.Path; using (ManagementBaseObject sourceOutParams = sourceService.InvokeMethod("GetSystemCompatibilityInfo", sourceInParams, null)) { WmiUtilities.ValidateOutput(sourceOutParams, sourceScope); compatibilityInfo = sourceOutParams["CompatibilityInfo"]; } } // // Pass the compatibility blob to the destination host and check // for compatibility. // ManagementScope destinationScope = new ManagementScope( @"\\" + destinationHost + @"\root\virtualization\v2", null); // Get compatibility information for the source host. using (ManagementObject destinationService = GetVirtualMachineMigrationService(destinationScope)) using (ManagementBaseObject destinationInParams = destinationService.GetMethodParameters("CheckSystemCompatibilityInfo")) { destinationInParams["CompatibilityInfo"] = compatibilityInfo; using (ManagementBaseObject destinationOutParams = destinationService.InvokeMethod("CheckSystemCompatibilityInfo", destinationInParams, null)) { uint returnValue = (uint)destinationOutParams["ReturnValue"]; if (returnValue == 0) { Console.WriteLine("The VM or the systems are compatible"); } else if (returnValue == 32784) { Console.WriteLine("The VM or the systems are not compatible"); } else { throw new ManagementException("The method call failed."); } } } }
internal EventArrivedEventArgs (ManagementBaseObject newEvent) { this.new_event = newEvent; }
private static bool GetEnabledState(ManagementBaseObject queryObj) { return(queryObj["StartMode"] as string != nameof(StartMode.Auto)); }
/// <summary> /// Adds the share permissions. /// </summary> /// <param name="accountName">Name of the account.</param> public void AddSharePermission(string accountName) { ManagementObject trustee = null; ManagementObject ace = null; ManagementObject win32LogicalSecuritySetting = null; ManagementObject share = null; ManagementBaseObject getSecurityDescriptorReturn = null; ManagementBaseObject securityDescriptor = null; try { //// Not necessary //// NTAccount ntAccount = new NTAccount(accountName); //// SecurityIdentifier sid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier)); //// byte[] sidArray = new byte[sid.BinaryLength]; //// sid.GetBinaryForm(sidArray, 0); trustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null); trustee["Name"] = accountName; //// trustee["SID"] = sidArray; ace = new ManagementClass(new ManagementPath("Win32_Ace"), null); //// Permissions mask http://msdn.microsoft.com/en-us/library/windows/desktop/aa394186(v=vs.85).aspx ace["AccessMask"] = 0x1F01FF; //// ace["AccessMask"] = 0x1FF; ace["AceFlags"] = 3; ace["AceType"] = 0; ace["Trustee"] = trustee; win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'"); getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null); if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0) { throw new WindowsShareException("Unable to add share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]); } securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject; ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[]; if (dacl == null) { dacl = new ManagementBaseObject[] { ace }; } else { Array.Resize(ref dacl, dacl.Length + 1); dacl[dacl.Length - 1] = ace; } securityDescriptor["DACL"] = dacl; share = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'"); uint setShareInfoReturn = (uint)share.InvokeMethod("SetShareInfo", new object[] { null, null, securityDescriptor }); if (setShareInfoReturn != 0) { throw new WindowsShareException("Unable to add share permission. Error code: " + setShareInfoReturn.ToString(CultureInfo.CurrentCulture)); } } catch (Exception ex) { throw new WindowsShareException("Unable to add share permission", ex); } finally { if (trustee != null) { trustee.Dispose(); } if (ace != null) { ace.Dispose(); } if (win32LogicalSecuritySetting != null) { win32LogicalSecuritySetting.Dispose(); } if (getSecurityDescriptorReturn != null) { getSecurityDescriptorReturn.Dispose(); } if (securityDescriptor != null) { securityDescriptor.Dispose(); } if (share != null) { share.Dispose(); } } }
public string ShutdownViaIC(string vmmachinename) { //Connect to the Remote Machines Management Scope try { ConnectionOptions options = new ConnectionOptions(); ManagementScope scope = new ManagementScope(@"\\localhost\root\virtualization\V2"); scope.Connect(); //Get the msvm_computersystem for the given VM (Vista) ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName = '" + vmmachinename + "'")); //Select the first object in the Searcher collection IEnumerator enumr = searcher.Get().GetEnumerator(); enumr.MoveNext(); ManagementObject msvm_computersystem = (ManagementObject)(enumr.Current); //Use the association to get the msvm_shutdowncomponent for the msvm_computersystem ManagementObjectCollection collection = msvm_computersystem.GetRelated("Msvm_ShutdownComponent"); ManagementObjectCollection.ManagementObjectEnumerator enumerator = collection.GetEnumerator(); enumerator.MoveNext(); ManagementObject msvm_shutdowncomponent = (ManagementObject)enumerator.Current; //Get the InitiateShudown Parameters ManagementBaseObject inParams = msvm_shutdowncomponent.GetMethodParameters("InitiateShutdown"); inParams["Force"] = true; inParams["Reason"] = "Need to Shutdown"; //Invoke the Method ManagementBaseObject outParams = msvm_shutdowncomponent.InvokeMethod("InitiateShutdown", inParams, null); uint returnValue = (uint)outParams["ReturnValue"]; //Zero indicates success if (returnValue != 0) { Console.WriteLine("SHUTDOWN Failed"); } return("1"); } catch { return("0"); } }
public ICustomActivityResult Execute() { StringWriter sw = new StringWriter(); DataTable dt = new DataTable("resultSet"); dt.Columns.Add("Result", typeof(String)); string sResult = ""; try { ConnectionOptions connectionOptions = new ConnectionOptions(); if (!String.IsNullOrEmpty(UserName)) { if (UserName.Contains("\\")) { connectionOptions.Authority = "NTLMDOMAIN:" + UserName.Split('\\')[0]; connectionOptions.Username = UserName.Split('\\')[1]; } else { connectionOptions.Username = UserName; } } if (!String.IsNullOrEmpty(Password)) { connectionOptions.Password = Password; } connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy; ManagementScope oMs; if (HostName.ToLower() == "localhost" || HostName == "127.0.0.1") { oMs = new ManagementScope(@"\\.\root\cimv2", connectionOptions); } else { oMs = new ManagementScope(@"\\" + HostName + @"\root\cimv2", connectionOptions); } oMs.Options.EnablePrivileges = true; oMs.Connect(); // Create a ManagementClass object ManagementClass managementClass = new ManagementClass(oMs, new ManagementPath("Win32_Share"), null); if (managementClass == null) { throw new Exception("Failed to initialize managment class"); } // Create ManagementBaseObjects for in and out parameters ManagementBaseObject inParams = managementClass.GetMethodParameters("Create"); ManagementBaseObject outParams; // Set the input parameters inParams["Description"] = ShareDescription; inParams["Name"] = ShareName; inParams["Path"] = SharePath; inParams["Type"] = DeviceType.DISK_DRIVE; //inParams["MaximumAllowed"] = int maxConnectionsNum; // Invoke the method on the ManagementClass object outParams = managementClass.InvokeMethod("Create", inParams, null); // Check to see if the method invocation was successful if (((uint)outParams.Properties["ReturnValue"].Value) != 0) { throw new Exception("Unable to share directory. Error code:" + ((uint)outParams.Properties["ReturnValue"].Value).ToString()); } try { DirectoryInfo dInfo = null; if (HostName.ToLower() == "localhost" || HostName == "127.0.0.1") { dInfo = new DirectoryInfo(SharePath); } else { dInfo = new DirectoryInfo(@"\\" + HostName + @"\" + SharePath.Replace(":", "$")); } if (!String.IsNullOrEmpty(ShareAccessRights)) { DirectorySecurity dSecurity = dInfo.GetAccessControl(); //if (!String.IsNullOrEmpty(ShareAccessRights)) //{ string[] rights = ShareAccessRights.Split(";,".ToCharArray()); foreach (String s in rights) { dSecurity.AddAccessRule(new FileSystemAccessRule(s, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow)); } //} //else //{ // dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow)); //} dInfo.SetAccessControl(dSecurity); } } catch (Exception ex) { if (((uint)outParams.Properties["ReturnValue"].Value) == 0) { object outParam = null; // Invoke the method on the ManagementClass object ManagementObjectCollection col = managementClass.GetInstances(); foreach (ManagementObject o in col) { if (o.Path.RelativePath.EndsWith("\"" + ShareName + "\"")) { outParam = o.InvokeMethod("Delete", null); break; } } } throw;// new Exception("Failed to set permissions"); } DataRow r = dt.NewRow(); r["Result"] = "Success"; dt.Rows.Add(r); } catch (Exception ex) { throw; } return(this.GenerateActivityResult(dt)); }
/// <summary> /// Adds the file. /// </summary> private void AddFile() { // Validation if (!this.ValidateExtract()) { return; } if (!System.IO.File.Exists(this.NewFile.GetMetadata("FullPath"))) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "New File not found: {0}", this.NewFile.GetMetadata("FullPath"))); return; } FileInfo f = new FileInfo(this.NewFile.GetMetadata("FullPath")); this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Adding File: {0} to Cab: {1}", this.NewFile.GetMetadata("FullPath"), this.CabFile.GetMetadata("FullPath"))); string tempFolderName = System.Guid.NewGuid() + "\\"; DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(Path.GetTempPath(), tempFolderName)); Directory.CreateDirectory(dirInfo.FullName); if (dirInfo.Exists) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Created: {0}", dirInfo.FullName)); } else { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to create temp folder: {0}", dirInfo.FullName)); return; } // configure the process we need to run using (Process cabProcess = new Process()) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Extracting Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.ExtractExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = true; cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/Y /L ""{0}"" ""{1}"" ""{2}""", dirInfo.FullName, this.CabFile.GetMetadata("FullPath"), "/E"); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.ExtractExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); cabProcess.Start(); cabProcess.WaitForExit(); } Directory.CreateDirectory(dirInfo.FullName + "\\" + this.NewFileDestination); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Copying new File: {0} to {1}", this.NewFile, dirInfo.FullName + "\\" + this.NewFileDestination + "\\" + f.Name)); System.IO.File.Copy(this.NewFile.GetMetadata("FullPath"), dirInfo.FullName + this.NewFileDestination + @"\" + f.Name, true); using (Process cabProcess = new Process()) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Creating Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.CabExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = false; cabProcess.StartInfo.RedirectStandardOutput = true; StringBuilder options = new StringBuilder(); options.Append("-r -p"); options.AppendFormat(" -P \"{0}\"\\", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1).Replace(@"C:\", string.Empty)); cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"{0} N ""{1}"" {2}", options, this.CabFile.GetMetadata("FullPath"), "\"" + dirInfo.FullName + "*.*\"" + " "); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.CabExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); // start the process cabProcess.Start(); // Read any messages from CABARC...and log them string output = cabProcess.StandardOutput.ReadToEnd(); cabProcess.WaitForExit(); if (output.Contains("Completed successfully")) { this.LogTaskMessage(output); } else { this.Log.LogError(output); } } string dirObject = string.Format(CultureInfo.CurrentCulture, "win32_Directory.Name='{0}'", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1)); using (ManagementObject mdir = new ManagementObject(dirObject)) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deleting Temp Folder: {0}", dirObject)); mdir.Get(); ManagementBaseObject outParams = mdir.InvokeMethod("Delete", null, null); // ReturnValue should be 0, else failure if (outParams != null) { if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.CurrentCulture) != 0) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Directory deletion error: ReturnValue: {0}", outParams.Properties["ReturnValue"].Value)); return; } } else { this.Log.LogError("The ManagementObject call to invoke Delete returned null."); return; } } }
public static object GetValue(ManagementClass mc, RegHive hDefKey, string sSubKeyName, string sValueName) { RegType rType = GetValueType(mc, hDefKey, sSubKeyName, sValueName); ManagementBaseObject inParams = mc.GetMethodParameters("GetStringValue"); inParams["hDefKey"] = hDefKey; inParams["sSubKeyName"] = sSubKeyName; inParams["sValueName"] = sValueName; object oValue = null; switch (rType) { case RegType.REG_SZ: ManagementBaseObject outParams = mc.InvokeMethod("GetStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetStringValue call failed } break; case RegType.REG_EXPAND_SZ: outParams = mc.InvokeMethod("GetExpandedStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetExpandedStringValue call failed } break; case RegType.REG_MULTI_SZ: outParams = mc.InvokeMethod("GetMultiStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetMultiStringValue call failed } break; case RegType.REG_DWORD: outParams = mc.InvokeMethod("GetDWORDValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["uValue"]; } else { // GetDWORDValue call failed } break; case RegType.REG_BINARY: outParams = mc.InvokeMethod("GetBinaryValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["uValue"] as byte[]; } else { // GetBinaryValue call failed } break; } return(oValue); }
private DateTime GetBootTimeWithWmi(ManagementClass mgmtClass, AmServerName machineName) { DateTime dateTime = ExDateTime.Now.UniversalTime; Exception ex = null; try { using (ManagementObjectCollection instances = mgmtClass.GetInstances()) { if (instances != null) { using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = instances.GetEnumerator()) { while (enumerator.MoveNext()) { ManagementBaseObject managementBaseObject = enumerator.Current; ManagementObject managementObject = (ManagementObject)managementBaseObject; using (managementObject) { string dmtfDate = (string)managementObject["LastBootupTime"]; dateTime = ManagementDateTimeConverter.ToDateTime(dmtfDate).ToUniversalTime(); AmTrace.Debug("GetBootTimeWithWmi: WMI says that the boot time for {0} is {1}.", new object[] { machineName, dateTime }); } } goto IL_102; } } AmTrace.Error("GetBootTimeWithWmi: WMI could not query the boot time on server {0}: No instances found for management path {1}.", new object[] { machineName, mgmtClass.ClassPath.Path }); ReplayEventLogConstants.Tuple_GetBootTimeWithWmiFailure.LogEvent(string.Empty, new object[] { machineName, Strings.NoInstancesFoundForManagementPath(mgmtClass.ClassPath.Path) }); IL_102 :; } } catch (COMException ex2) { ex = ex2; } catch (UnauthorizedAccessException ex3) { ex = ex3; } catch (ManagementException ex4) { ex = ex4; } catch (OutOfMemoryException ex5) { ex = ex5; } if (ex != null) { AmTrace.Error("GetBootTimeWithWmi: WMI could not query the boot time on server {0}: {1}", new object[] { machineName, ex }); ReplayEventLogConstants.Tuple_GetBootTimeWithWmiFailure.LogEvent(string.Empty, new object[] { machineName, ex.Message }); } return(dateTime); }
//Displays event related information. static void DisplayEventInformation( ManagementBaseObject ev) { // It contains the name of the WMI raised // event. This is the name of the // event class as defined in the // Aspnet.mof file. string eventTypeName; // Get the name of the WMI raised event. eventTypeName = ev.ClassPath.ToString(); // Process the raised event. switch (eventTypeName) { // Process the heartbeat event. case "HeartBeatEvent": Console.WriteLine("HeartBeat"); Console.WriteLine("\tProcess: {0}", ev["ProcessName"]); Console.WriteLine("\tApp: {0}", ev["ApplicationUrl"]); Console.WriteLine("\tWorkingSet: {0}", ev["WorkingSet"]); Console.WriteLine("\tThreads: {0}", ev["ThreadCount"]); Console.WriteLine("\tManagedHeap: {0}", ev["ManagedHeapSize"]); Console.WriteLine("\tAppDomainCount: {0}", ev["AppDomainCount"]); break; // Process the request error event. case "RequestErrorEvent": Console.WriteLine("Error"); Console.WriteLine("Url: {0}", ev["RequestUrl"]); Console.WriteLine("Path: {0}", ev["RequestPath"]); Console.WriteLine("Message: {0}", ev["EventMessage"]); Console.WriteLine("Stack: {0}", ev["StackTrace"]); Console.WriteLine("UserName: {0}", ev["UserName"]); Console.WriteLine("ThreadID: {0}", ev["ThreadAccountName"]); break; // Process the application lifetime event. case "ApplicationLifetimeEvent": Console.WriteLine("App Lifetime Event {0}", ev["EventMessage"]); break; // Handle events for which processing is not // provided. default: Console.WriteLine("ASP.NET Event {0}", ev["EventMessage"]); break; } } // End DisplayEventInformation.
public bool IsSerialDevice(ManagementBaseObject instance) { var compatibleIds = (System.String[])instance.GetPropertyValue("CompatibleID"); return(compatibleIds != null && compatibleIds.Contains("USB\\Class_02&SubClass_02")); // CDC-ACM }
//点击"应用"按钮时触发 private void submit_Click(object sender, EventArgs e) { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = wmi.GetInstances(); ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; //获取要设置的目标网卡信息-IP-子网掩码-网关-DNS1-DNS2 int num = adapterInfoToText.SelectedIndex; string ip = toadapterinfo[num, 2]; string submask = toadapterinfo[num, 3]; string way = toadapterinfo[num, 4]; string dns1 = toadapterinfo[num, 5]; string dns2 = toadapterinfo[num, 6]; foreach (ManagementObject mo in moc) { //遍历每个当前的网卡信息并与要更改的网卡进行匹配便于进行设置 string nicid = mo.GetPropertyValue("SettingID").ToString(); if (nicid == toadapterinfo[num, 7]) { //如果没有启用IP设置的网络设备则跳过 if (!(bool)mo["IPEnabled"]) { MessageBox.Show("当前网卡未启用IP设置,无法进行IP修改操作!", "设置提示:"); } else { //设置非"自动获取IP"之外的IP信息 if (num != 0) { try { //设置IP地址和子网掩码 inPar = mo.GetMethodParameters("EnableStatic"); inPar["IPAddress"] = new string[] { ip }; inPar["SubnetMask"] = new string[] { submask }; outPar = mo.InvokeMethod("EnableStatic", inPar, null); //设置网关地址 inPar = mo.GetMethodParameters("SetGateways"); inPar["DefaultIPGateway"] = new string[] { way }; mo.InvokeMethod("SetGateways", inPar, null); //设置DNS inPar = mo.GetMethodParameters("SetDNSServerSearchOrder"); string[] dns = new string[] { dns1, dns2 }; inPar["DNSServerSearchOrder"] = dns; mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null); MessageBox.Show("当前适配器设置<" + toadapterinfo[num, 0] + ">成功!", "设置提示:"); } catch { MessageBox.Show("当前适配器设置<" + toadapterinfo[num, 0] + ">失败!", "设置提示:"); } } //设置网卡为"自动获取IP地址" else { try { mo.InvokeMethod("SetDNSServerSearchOrder", null); mo.InvokeMethod("EnableStatic", null); mo.InvokeMethod("SetGateways", null); mo.InvokeMethod("EnableDHCP", null); MessageBox.Show("当前适配器设置<" + toadapterinfo[num, 0] + ">成功!", "设置提示:"); } catch { MessageBox.Show("当前适配器设置<" + toadapterinfo[num, 0] + ">失败!", "设置提示:"); } } } } } }
public bool DetectBootloader(ManagementBaseObject instance, bool connected = true) { var deviceId = GetHardwareId(instance); var vpr = DeviceIdRegex.Match(deviceId); var vid = vpr.Groups[1].ToString().PadLeft(4, '0'); var pid = vpr.Groups[2].ToString().PadLeft(4, '0'); var rev = vpr.Groups[3].ToString().PadLeft(4, '0'); string deviceName; string comPort = null; if (IsSerialDevice(instance)) { comPort = GetComPort(instance); if (MatchVidPid(deviceId, 0x03EB, 0x6124)) // Atmel SAM-BA { deviceName = "Atmel SAM-BA"; _flasher.ComPort = comPort; _devicesAvailable[(int)Chipset.AtmelSamBa] += connected ? 1 : -1; } else if (caterinaVids.Contains(vid) && caterinaPids.Contains(pid)) // Caterina { deviceName = "Caterina"; _flasher.ComPort = comPort; _devicesAvailable[(int)Chipset.Caterina] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x16C0, 0x0483)) // ArduinoISP/AVRISP { deviceName = "AVRISP"; _flasher.ComPort = comPort; _devicesAvailable[(int)Chipset.AvrIsp] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x1781, 0x0C9F)) // AVR Pocket ISP { deviceName = "USB Tiny"; _flasher.ComPort = comPort; _devicesAvailable[(int)Chipset.UsbTiny] += connected ? 1 : -1; } else { return(false); } } else if (MatchVid(deviceId, 0x03EB) && atmelDfuPids.Contains(pid)) // Atmel DFU { deviceName = "Atmel DFU"; _devicesAvailable[(int)Chipset.Dfu] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x16C0, 0x0478)) // PJRC Teensy { deviceName = "Halfkay"; _devicesAvailable[(int)Chipset.Halfkay] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x0483, 0xDF11)) // STM32 DFU { deviceName = "STM32 DFU"; _devicesAvailable[(int)Chipset.Stm32] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x1C11, 0xB007)) // Kiibohd { deviceName = "Kiibohd"; _devicesAvailable[(int)Chipset.Kiibohd] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x16C0, 0x05DF)) // Objective Development BootloadHID { deviceName = "BootloadHID"; _devicesAvailable[(int)Chipset.BootloadHid] += connected ? 1 : -1; } else if (MatchVidPid(deviceId, 0x16C0, 0x05DC)) // USBAsp and USBAspLoader { deviceName = "USBAsp"; _devicesAvailable[(int)Chipset.UsbAsp] += connected ? 1 : -1; } else { return(false); } var connectedString = connected ? "connected" : "disconnected"; var comPortString = comPort != null ? $" [{comPort}]" : ""; _printer.Print($"{deviceName} device {connectedString}: {instance.GetPropertyValue("Manufacturer")} {instance.GetPropertyValue("Name")} ({vid}:{pid}:{rev}){comPortString}", MessageType.Bootloader); return(true); }
public EthernetSwitchFeatureCapabilities(ManagementBaseObject theObject) : base(theObject, ClassName) { }
/// <summary> /// /// </summary> /// <param name="zoneName"></param> /// <param name="secondaryServers"></param> /// <remarks>Supports managed resources disposal</remarks> public virtual void AddPrimaryZone(string zoneName, string[] secondaryServers) { // check if zone exists if (ZoneExists(zoneName)) { return; } // create a zone using (ManagementClass clsZone = wmi.GetClass("MicrosoftDNS_Zone")) { using (ManagementBaseObject inParams = clsZone.GetMethodParameters("CreateZone")) { inParams["ZoneName"] = zoneName; inParams["ZoneType"] = 0; // primary zone // create zones in AD if required if (AdMode) { inParams["DsIntegrated"] = true; } using (ManagementBaseObject outParams = clsZone.InvokeMethod("CreateZone", inParams, null)) { // update created zone using (ManagementObject objZone = wmi.GetObject(String.Format( "MicrosoftDNS_Zone.ContainerName='{0}',DnsServerName='{1}',Name='{2}'", zoneName, System.Net.Dns.GetHostEntry("LocalHost").HostName, zoneName))) { try { // invoke ResetSecondaries method using (ManagementBaseObject inParams2 = objZone.GetMethodParameters("ResetSecondaries")) { inParams2["SecondaryServers"] = new string[] { }; inParams2["NotifyServers"] = new string[] { }; if (secondaryServers == null || secondaryServers.Length == 0) { // transfers are not allowed inParams2["SecureSecondaries"] = 3; inParams2["Notify"] = 0; } else if (secondaryServers.Length == 1 && secondaryServers[0] == "*") { // allowed transfer from all servers inParams2["SecureSecondaries"] = 0; inParams2["Notify"] = 1; } else { // allowed transfer from specified servers inParams2["SecureSecondaries"] = 2; inParams2["SecondaryServers"] = secondaryServers; inParams2["NotifyServers"] = secondaryServers; inParams2["Notify"] = 2; } objZone.InvokeMethod("ResetSecondaries", inParams2, null); } } catch { Log.WriteWarning("Error resetting/notifying secondary name servers"); } } } } } // delete orphan NS records DeleteOrphanNsRecords(zoneName); }
public void CopyTo(ManagementBaseObject[] objectCollection, int index) {}
public ManagementSystemProperties(ManagementBaseObject ManagedObject) { this.PrivateLateBoundObject = ManagedObject; }
public void InvokeMethod(ManagementOperationObserver watcher, string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) {}
public ProcessorSettingData(ManagementBaseObject theObject) : base(theObject, ClassName) { }
private static string GetTheNameOfTheColumn(ManagementBaseObject queryObj) { var name = string.Empty; foreach (var v in queryObj.Properties) { name = v.Name; } return name; }
public ConcreteComponent(ManagementBaseObject theObject) : base(theObject, ClassName) { }
public static System.IntPtr op_Explicit(ManagementBaseObject managementObject) {}
private ManagementPath UpdateARecord(string strDNSZone, string strHostName, string strIPAddress) { ManagementScope mgmtScope = new ManagementScope(@"\\.\Root\MicrosoftDNS"); ManagementClass mgmtClass = null; ManagementBaseObject mgmtParams = null; ManagementObjectSearcher mgmtSearch = null; ManagementObjectCollection mgmtDNSRecords = null; string strQuery; strQuery = string.Format("SELECT * FROM MicrosoftDNS_AType WHERE OwnerName = '{0}.{1}'", strHostName, strDNSZone); mgmtScope.Connect(); mgmtSearch = new ManagementObjectSearcher(mgmtScope, new ObjectQuery(strQuery)); mgmtDNSRecords = mgmtSearch.Get(); //// Multiple A records with the same record name, but different IPv4 addresses, skip. //if (mgmtDNSRecords.Count > 1) //{ // // Take appropriate action here. //} //// Existing A record found, update record. //else if (mgmtDNSRecords.Count == 1) { ManagementObject mo = new ManagementObject(); foreach (ManagementObject mgmtDNSRecord in mgmtDNSRecords) { if (mgmtDNSRecord["RecordData"].ToString() != strIPAddress) { mgmtParams = mgmtDNSRecord.GetMethodParameters("Modify"); mgmtParams["IPAddress"] = strIPAddress; mgmtDNSRecord.InvokeMethod("Modify", mgmtParams, null); } mo = mgmtDNSRecord; break; } return(new ManagementPath(mo["RR"].ToString())); } // A record does not exist, create new record. else { mgmtClass = new ManagementClass(mgmtScope, new ManagementPath("MicrosoftDNS_AType"), null); mgmtParams = mgmtClass.GetMethodParameters("CreateInstanceFromPropertyData"); mgmtParams["DnsServerName"] = Environment.MachineName; mgmtParams["ContainerName"] = strDNSZone; mgmtParams["OwnerName"] = strDNSZone;// string.Format("{0}.{1}", strHostName.ToLower(), strDNSZone); mgmtParams["IPAddress"] = strIPAddress; var outParams = mgmtClass.InvokeMethod("CreateInstanceFromPropertyData", mgmtParams, null); if ((outParams.Properties["RR"] != null)) { return(new ManagementPath(outParams["RR"].ToString())); } } return(null); }