protected void addComputerToCollection(string resourceID, string collectionID) { /* Set collection = SWbemServices.Get ("SMS_Collection.CollectionID=""" & CollID &"""") Set CollectionRule = SWbemServices.Get("SMS_CollectionRuleDirect").SpawnInstance_() CollectionRule.ResourceClassName = "SMS_R_System" CollectionRule.RuleName = "Static-"&ResourceID CollectionRule.ResourceID = ResourceID collection.AddMembershipRule CollectionRule*/ //o.Properties["ResourceID"].Value.ToString(); var pathString = "\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_Collection.CollectionID=\"" + collectionID + "\""; ManagementPath path = new ManagementPath(pathString); ManagementObject obj = new ManagementObject(path); ManagementClass ruleClass = new ManagementClass("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_CollectionRuleDirect"); ManagementObject rule = ruleClass.CreateInstance(); rule["RuleName"] = "Static-"+ resourceID; rule["ResourceClassName"] = "SMS_R_System"; rule["ResourceID"] = resourceID; obj.InvokeMethod("AddMembershipRule", new object[] { rule }); }
/// <summary> /// Create a Receive Handler. /// </summary> /// <param name="adapterName">The Adapter name.</param> /// <param name="hostName">The Host name.</param> public static void Create(string adapterName, string hostName) { PutOptions options = new PutOptions(); options.Type = PutType.CreateOnly; using (ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ReceiveHandler", null)) { foreach (ManagementObject handler in handlerManagementClass.GetInstances()) { if ((string)handler["AdapterName"] == adapterName && (string)handler["HostName"] == hostName) { handler.Delete(); } } ManagementObject recieveHandlerManager = handlerManagementClass.CreateInstance(); if (recieveHandlerManager == null) { throw new BizTalkExtensionsException("Could not create Management Object."); } recieveHandlerManager["AdapterName"] = adapterName; recieveHandlerManager["HostName"] = hostName; recieveHandlerManager.Put(options); } }
public void AddInstance(string wmiClass, string parametersJSON) { try { JavaScriptSerializer serializer = new JavaScriptSerializer(); object result = serializer.Deserialize(parametersJSON, typeof(object)); Dictionary<string, object> dic = (Dictionary<string, object>)result; WindowsImpersonationContext impersonatedUser = WindowsIdentity.GetCurrent().Impersonate(); ManagementClass genericClass = new ManagementClass(Scope, wmiClass, null); ManagementObject genericInstance = genericClass.CreateInstance(); foreach (KeyValuePair<string, object> value in dic) { genericInstance[value.Key] = value.Value.ToString(); } genericInstance.Put(); } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); log.LogError(ex.ToString()); } }
/// <summary> /// Create a Send Handler. /// </summary> /// <param name="adapterName">The Adapter name.</param> /// <param name="hostName">The Host name.</param> /// <param name="isDefault">Indicating if the Handler is the default.</param> public static void Create(string adapterName, string hostName, bool isDefault) { PutOptions options = new PutOptions(); options.Type = PutType.CreateOnly; using (ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_SendHandler2", null)) { foreach (ManagementObject handler in handlerManagementClass.GetInstances()) { if ((string)handler["AdapterName"] == adapterName && (string)handler["HostName"] == hostName) { handler.Delete(); } } ManagementObject handlerInstance = handlerManagementClass.CreateInstance(); if (handlerInstance == null) { throw new CoreException("Could not create Management Object."); } handlerInstance["AdapterName"] = adapterName; handlerInstance["HostName"] = hostName; handlerInstance["IsDefault"] = isDefault; handlerInstance.Put(options); } }
public static string MakeHost(string HostName, string Type, string HostNTGroup, bool AuthTrusted) { PutOptions options = new PutOptions(); options.Type = PutType.CreateOnly; // create a ManagementClass object and spawn a ManagementObject instance ManagementClass objHostSettingClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostSetting", null); ManagementObject objHostSetting = objHostSettingClass.CreateInstance(); // set the properties for the Managementobject // Host Name objHostSetting["Name"] = HostName; // Host Type if(Type == "Isolated") objHostSetting["HostType"] = HostType.Isolated; else objHostSetting["HostType"] = HostType.InProcess; objHostSetting["NTGroupName"] = HostNTGroup; objHostSetting["AuthTrusted"] = AuthTrusted; //create the Managementobject objHostSetting.Put(options); return Type + " Host - " + HostName + " - has been created. \r\n"; }
public static string InstallHosts(string ServerName, string HostName, string UserName, string Password, bool StartHost) { PutOptions options = new PutOptions(); options.Type = PutType.CreateOnly; ObjectGetOptions bts_objOptions = new ObjectGetOptions(); // Creating instance of BizTalk Host. ManagementClass bts_AdminObjClassServerHost = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ServerHost", bts_objOptions); ManagementObject bts_AdminObjectServerHost = bts_AdminObjClassServerHost.CreateInstance(); // Make sure to put correct Server Name,username and // password bts_AdminObjectServerHost["ServerName"] = ServerName; bts_AdminObjectServerHost["HostName"] = HostName; bts_AdminObjectServerHost.InvokeMethod("Map", null); ManagementClass bts_AdminObjClassHostInstance = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostInstance", bts_objOptions); ManagementObject bts_AdminObjectHostInstance = bts_AdminObjClassHostInstance.CreateInstance(); bts_AdminObjectHostInstance["Name"] = "Microsoft BizTalk Server " + HostName + " " + ServerName; //Also provide correct user name and password. ManagementBaseObject inParams = bts_AdminObjectHostInstance.GetMethodParameters("Install"); inParams["GrantLogOnAsService"] = false; inParams["Logon"] = UserName; inParams["Password"] = Password; bts_AdminObjectHostInstance.InvokeMethod("Install", inParams, null); if(StartHost) bts_AdminObjectHostInstance.InvokeMethod("Start", null); return " Host - " + HostName + " - has been installed. \r\n"; }
public static ManagementObject CreateInstance(String scope, String className) { if(String.IsNullOrEmpty(scope)) { throw new ArgumentNullException("scope"); } if (String.IsNullOrEmpty(className)) { throw new ArgumentNullException("className"); } ManagementClass clazz = new ManagementClass(scope, className, null); return clazz.CreateInstance(); }
ConfigureMetricsFlushInterval( TimeSpan interval) { ManagementScope scope = new ManagementScope(@"root\virtualization\v2"); // // Create an instance of the Msvm_MetricServiceSettingData class and set the specified // metrics flush interval. Note that the TimeSpan must be converted to a DMTF time // interval first. // string dmtfTimeInterval = ManagementDateTimeConverter.ToDmtfTimeInterval(interval); string serviceSettingDataEmbedded; using (ManagementClass serviceSettingDataClass = new ManagementClass( "Msvm_MetricServiceSettingData")) { serviceSettingDataClass.Scope = scope; using (ManagementObject serviceSettingData = serviceSettingDataClass.CreateInstance()) { serviceSettingData["MetricsFlushInterval"] = dmtfTimeInterval; serviceSettingDataEmbedded = serviceSettingData.GetText(TextFormat.WmiDtd20); } } // // Call the Msvm_MetricService::ModifyServiceSettings method. Note that the // Msvm_MetricServiceSettingData instance must be passed as an embedded instance. // using (ManagementObject metricService = MetricUtilities.GetMetricService(scope)) { using (ManagementBaseObject inParams = metricService.GetMethodParameters("ModifyServiceSettings")) { inParams["SettingData"] = serviceSettingDataEmbedded; using (ManagementBaseObject outParams = metricService.InvokeMethod("ModifyServiceSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "The MetricsFlushInterval was successfully configured to interval \"{0}\".", interval.ToString())); } } } }
private void TestCreate() { ConnectionOptions Conn = new ConnectionOptions(); //Conn.Username = "******"; //Conn.Password = "******"; Conn.Impersonation = ImpersonationLevel.Impersonate; Conn.EnablePrivileges = true; ManagementScope ms = new ManagementScope(@"\\.\root\sbs", Conn); ms.Connect(); ObjectGetOptions option = new ObjectGetOptions(); ManagementClass mc = new ManagementClass(ms, new ManagementPath("sbs_user"), option); ManagementObject mo = mc.CreateInstance(); mo["UserName"] = "******"; mo.Put(); }
public static WmiMonitorBrightnessMethods 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 WmiMonitorBrightnessMethods(tmpMgmtClass.CreateInstance())); }
public static RegistryValueChangeEvent 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 RegistryValueChangeEvent(tmpMgmtClass.CreateInstance())); }
public static EthernetSwitchPortBandwidthSettingData 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 EthernetSwitchPortBandwidthSettingData(tmpMgmtClass.CreateInstance())); }
public static ResourceAllocationSettingData 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 ResourceAllocationSettingData(tmpMgmtClass.CreateInstance())); }
public static EnvironmentWmi 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 EnvironmentWmi(tmpMgmtClass.CreateInstance())); }
/// <summary> /// Sets the limit for the upload network data rate. This limit is applied for the specified user. /// This method is not reentrant. Remove the policy first after creating it again. /// </summary> private static void CreateOutboundThrottlePolicy(string ruleName, string windowsUsername, long bitsPerSecond) { var StandardCimv2 = new ManagementScope(@"root\StandardCimv2"); using (ManagementClass netqos = new ManagementClass("MSFT_NetQosPolicySettingData")) { netqos.Scope = StandardCimv2; using (ManagementObject newInstance = netqos.CreateInstance()) { newInstance["Name"] = ruleName; newInstance["UserMatchCondition"] = windowsUsername; // ThrottleRateAction is in bytesPerSecond according to the WMI docs. // Acctualy the units are bits per second, as documented in the PowerShell cmdlet counterpart. newInstance["ThrottleRateAction"] = bitsPerSecond; newInstance.Put(); } } }
public static void NewVM(string serverName, string vmName) { ManagementPath classPath = new ManagementPath() { Server = serverName, NamespacePath = @"\root\virtualization\v2", ClassName = "Msvm_VirtualSystemSettingData" }; using (ManagementClass virtualSystemSettingClass = new ManagementClass(classPath)) { Credentials.conOpts.Username = Credentials.username; Credentials.conOpts.SecurePassword = Credentials.password; Credentials.conOpts.Authority = Credentials.domain; Credentials.conOpts.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", Credentials.conOpts); virtualSystemSettingClass.Scope = scope; using (ManagementObject virtualSystemSetting = virtualSystemSettingClass.CreateInstance()) { virtualSystemSetting["ElementName"] = vmName; virtualSystemSetting["VirtualsystemSubtype"] = "Microsoft:Hyper-V:Subtype:2"; string embeddedInstance = virtualSystemSetting.GetText(TextFormat.WmiDtd20); using (ManagementObject service = Functions.getVMManagementService(scope)) using (ManagementBaseObject inParams = service.GetMethodParameters("DefineSystem")) { inParams["SystemSettings"] = embeddedInstance; using (ManagementBaseObject outParams = service.InvokeMethod("DefineSystem", inParams, null)) { Console.WriteLine("ret={0}", outParams["ReturnValue"]); } } } } }
/// <summary> /// Adds the specified name. /// </summary> /// <param name="name">The name of the Adapter.</param> /// <param name="managementClassId">The management class ID.</param> /// <param name="comment">The comment.</param> public static void Add(string name, Guid managementClassId, string comment) { using (ManagementClass addAdapter_objClass = new ManagementClass(@"root\MicrosoftBizTalkServer", "MSBTS_AdapterSetting", new ObjectGetOptions())) { ManagementObject addAdapter_objInstance = addAdapter_objClass.CreateInstance(); if (addAdapter_objInstance == null) { throw new CoreException("Could not create Management Object."); } addAdapter_objInstance.SetPropertyValue("Name", name); // "B" GUID format example - "{9A7B0162-2CD5-4F61-B7EB-C40A3442A5F8}" addAdapter_objInstance.SetPropertyValue("MgmtCLSID", managementClassId.ToString("B")); if (!string.IsNullOrEmpty(comment)) { addAdapter_objInstance.SetPropertyValue("Comment", comment); } addAdapter_objInstance.Put(); } }
/// <summary> /// Sets the limit for the upload network data rate. This limit is applied for a specific server URL passing through HTTP.sys. /// This rules are applicable to IIS, IIS WHC and IIS Express. This goes hand in hand with URL Acls. /// This method is not reentrant. Remove the policy first after creating it again. /// </summary> private static void CreateOutboundThrottlePolicy(string ruleName, int urlPort, long bitsPerSecond) { var StandardCimv2 = new ManagementScope(@"root\StandardCimv2"); using (ManagementClass netqos = new ManagementClass("MSFT_NetQosPolicySettingData")) { netqos.Scope = StandardCimv2; using (ManagementObject newInstance = netqos.CreateInstance()) { newInstance["Name"] = ruleName; newInstance["URIMatchCondition"] = string.Format(CultureInfo.InvariantCulture, "http://*:{0}/", urlPort); newInstance["URIRecursiveMatchCondition"] = true; // ThrottleRateAction is in bytesPerSecond according to the WMI docs. // Acctualy the units are bits per second, as documented in the PowerShell cmdlet counterpart. newInstance["ThrottleRateAction"] = bitsPerSecond; newInstance.Put(); } } }
CreateGeneration2VM( string serverName, string vmName) { ManagementPath classPath = new ManagementPath() { Server = serverName, NamespacePath = @"\root\virtualization\v2", ClassName = "Msvm_VirtualSystemSettingData" }; using (ManagementClass virtualSystemSettingClass = new ManagementClass(classPath)) { ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null); virtualSystemSettingClass.Scope = scope; using (ManagementObject virtualSystemSetting = virtualSystemSettingClass.CreateInstance()) { virtualSystemSetting["ElementName"] = vmName; virtualSystemSetting["ConfigurationDataRoot"] = "C:\\ProgramData\\Microsoft\\Windows\\Hyper-V\\"; virtualSystemSetting["VirtualSystemSubtype"] = "Microsoft:Hyper-V:SubType:2"; string embeddedInstance = virtualSystemSetting.GetText(TextFormat.WmiDtd20); // Get the management service, VM object and its settings. using (ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope)) using (ManagementBaseObject inParams = service.GetMethodParameters("DefineSystem")) { inParams["SystemSettings"] = embeddedInstance; using (ManagementBaseObject outParams = service.InvokeMethod("DefineSystem", inParams, null)) { Console.WriteLine("ret={0}", outParams["ReturnValue"]); } } } } }
public static ServerHost CreateInstance(string pServer, string pUserName, string pPassword, string pDomain) { System.Management.ManagementScope mgmtScope = null; if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "\\\\" + pServer + "\\" + CreatedWmiNamespace; ConnectionOptions connection = new ConnectionOptions(); connection.Username = pUserName; connection.Password = pPassword; connection.Authority = "ntlmdomain:" + pDomain; mgmtScope.Options = connection; } 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 ServerHost(tmpMgmtClass.CreateInstance())); }
public static void newVhd(string serverName, string diskType, string diskFormat, string path, string parentPath, int maxInternalSize, int blockSize, int logicalSectorSize, int physicalSectorSize) { ManagementPath classPath = new ManagementPath() { Server = serverName, NamespacePath = @"\root\virtualization\v2", ClassName = "Msvm_VirtualHardDiskSettingData" }; using (ManagementClass settingsClass = new ManagementClass(classPath)) { Credentials.conOpts.Username = Credentials.username; Credentials.conOpts.SecurePassword = Credentials.password; Credentials.conOpts.Authority = Credentials.domain; Credentials.conOpts.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", Credentials.conOpts); settingsClass.Scope = scope; using (ManagementObject settingsInstance = settingsClass.CreateInstance()) { settingsInstance["Type"] = diskType; settingsInstance["Format"] = diskFormat; settingsInstance["Path"] = path; settingsInstance["ParentPath"] = parentPath; settingsInstance["MaxInternalSize"] = maxInternalSize; settingsInstance["BlockSize"] = blockSize; settingsInstance["LogicalSectorSize"] = logicalSectorSize; settingsInstance["PhysicalSectorSize"] = physicalSectorSize; string settingsInstanceString = settingsInstance.GetText(TextFormat.WmiDtd20); // return settingsInstanceString; } } }
private void Create() { if (this.CheckExists()) { if (this.Force) { this.Delete(); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "ReceiveHandler: {0} already exists for: {1}. Set Force to true to delete the ReceiveHandler.", this.AdapterName, this.HostName)); return; } } PutOptions options = new PutOptions { Type = PutType.CreateOnly }; using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_ReceiveHandler"), null)) { ManagementObject btsHostSetting = instance.CreateInstance(); if (btsHostSetting == null) { Log.LogError("There was a failure creating the MSBTS_ReceiveHandler instance"); return; } btsHostSetting["HostName"] = this.HostName; btsHostSetting["AdapterName"] = this.AdapterName; btsHostSetting["CustomCfg"] = this.CustomCfg; btsHostSetting["MgmtDbServerOverride"] = this.DatabaseServer; btsHostSetting.Put(options); this.explorer.SaveChanges(); } }
/* /// <summary> /// Performs a network scan for BSSIDs. /// </summary> /// <param name="adapter">object representing</param> public void ScanBssidList(NetworkInterface adapter) { IntPtr deviceHandle = OpenDevice(adapter.Id); try { // dummy reference variable int bytesReturned = new int(); // tell the driver to scan the networks bool success = QueryGlobalStats( deviceHandle, Oid.Oid80211BssidListScan, IntPtr.Zero, 0, ref bytesReturned ); if (success) { // Nothing to do } } finally { CloseHandle(deviceHandle); } } */ // End ScanBssidList() /// <summary> /// Initiates a discovery scan of the available wireless networkds. /// </summary> public bool Scan(NetworkInterface adapter) { try { ManagementClass mc = new ManagementClass("root\\WMI", "MSNDis_80211_BssIdListScan", null); ManagementObject mo = mc.CreateInstance(); if (mo != null) { mo["Active"] = true; mo["InstanceName"] = adapter.Description; //.Replace(" - Packet Scheduler Miniport",""); mo["UnusedParameter"] = 1; mo.Put(); } } catch (ManagementException ex) { if(ex.ErrorCode == ManagementStatus.NotSupported) { //The operation is not supported, probably not an WiFi adapter. return false; } } catch { // TODO: Verify root cause of exception. // Ignore, for now // there seems to be some issues with WMI on certain systems. Various exceptions have been // reported from this method, which relate to problems with WMI. } return true; }
public static BcdObject 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 BcdObject(tmpMgmtClass.CreateInstance()); }
/// <summary> /// Do the actual connection to remote machine for Set-WMIInstance cmdlet and raise operation complete event. /// </summary> private void ConnectSetWmi() { SetWmiInstance setObject = (SetWmiInstance)_wmiObject; _state = WmiState.Running; RaiseWmiOperationState(null, WmiState.Running); if (setObject.InputObject != null) { ManagementObject mObj = null; try { PutOptions pOptions = new PutOptions(); //Extra check if (setObject.InputObject.GetType() == typeof(ManagementClass)) { //Check if Flag specified is CreateOnly or not if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } mObj = ((ManagementClass)setObject.InputObject).CreateInstance(); setObject.PutType = PutType.CreateOnly; } else { //Check if Flag specified is Updateonly or UpdateOrCreateOnly or not if (setObject.flagSpecified) { if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) { InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { setObject.PutType = PutType.UpdateOrCreate; } mObj = (ManagementObject)setObject.InputObject.Clone(); } if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) { mObj[en.Key as string] = en.Value; } } pOptions.Type = setObject.PutType; if (mObj != null) { mObj.Put(_results, pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } catch (ManagementException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } else { ManagementPath mPath = null; //If Class is specified only CreateOnly flag is supported if (setObject.Class != null) { if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } setObject.PutType = PutType.CreateOnly; } else { mPath = new ManagementPath(setObject.Path); if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = setObject.Namespace; } else if (setObject.namespaceSpecified) { InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath"); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } if (mPath.Server != "." && setObject.serverNameSpecified) { InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath"); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } if (mPath.IsClass) { if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } setObject.PutType = PutType.CreateOnly; } else { if (setObject.flagSpecified) { if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) { InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { setObject.PutType = PutType.UpdateOrCreate; } } } //If server name is specified loop through it. if (mPath != null) { if (!(mPath.Server == "." && setObject.serverNameSpecified)) { _computerName = mPath.Server; } } ConnectionOptions options = setObject.GetConnectionOption(); ManagementObject mObject = null; try { if (setObject.Path != null) { mPath.Server = _computerName; ManagementScope mScope = new ManagementScope(mPath, options); if (mPath.IsClass) { ManagementClass mClass = new ManagementClass(mPath); mClass.Scope = mScope; mObject = mClass.CreateInstance(); } else { //This can throw if path does not exist caller should catch it. ManagementObject mInstance = new ManagementObject(mPath); mInstance.Scope = mScope; try { mInstance.Get(); } catch (ManagementException e) { if (e.ErrorCode != ManagementStatus.NotFound) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } int namespaceIndex = setObject.Path.IndexOf(':'); if (namespaceIndex == -1) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); if (classIndex == -1) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } //Get class object and create instance. string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); ManagementPath classPath = new ManagementPath(newPath); ManagementClass mClass = new ManagementClass(classPath); mClass.Scope = mScope; mInstance = mClass.CreateInstance(); } mObject = mInstance; } } else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options); ManagementClass mClass = new ManagementClass(setObject.Class); mClass.Scope = scope; mObject = mClass.CreateInstance(); } if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) { mObject[en.Key as string] = en.Value; } } PutOptions pOptions = new PutOptions(); pOptions.Type = setObject.PutType; if (mObject != null) { mObject.Put(_results, pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); internalException = exp; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } catch (ManagementException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } }
/// <summary> /// Set wmi instance helper /// </summary> internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) { ConnectionOptions options = GetConnectionOption(); ManagementObject mObject = null; var setObject = this as SetWmiInstance; if (setObject != null) { if (setObject.Path != null) { mPath.Server = serverName; ManagementScope mScope = new ManagementScope(mPath, options); if (mPath.IsClass) { ManagementClass mClass = new ManagementClass(mPath); mClass.Scope = mScope; mObject = mClass.CreateInstance(); } else { //This can throw if path does not exist caller should catch it. ManagementObject mInstance = new ManagementObject(mPath); mInstance.Scope = mScope; try { mInstance.Get(); } catch (ManagementException e) { if (e.ErrorCode != ManagementStatus.NotFound) { throw; } int namespaceIndex = setObject.Path.IndexOf(':'); if (namespaceIndex == -1) { throw; } int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); if (classIndex == -1) { throw; } //Get class object and create instance. string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); ManagementPath classPath = new ManagementPath(newPath); ManagementClass mClass = new ManagementClass(classPath); mClass.Scope = mScope; mInstance = mClass.CreateInstance(); } mObject = mInstance; } } else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(serverName, setObject.Namespace), options); ManagementClass mClass = new ManagementClass(setObject.Class); mClass.Scope = scope; mObject = mClass.CreateInstance(); } if (setObject.Arguments != null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) { mObject[en.Key as string] = en.Value; } } } return mObject; }
public static PerfFormattedData_Counters_ProcessorInformation 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 PerfFormattedData_Counters_ProcessorInformation(tmpMgmtClass.CreateInstance()); }
internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) { ConnectionOptions connectionOption = this.GetConnectionOption(); ManagementObject value = null; if (base.GetType() == typeof(SetWmiInstance)) { SetWmiInstance setWmiInstance = (SetWmiInstance)this; if (setWmiInstance.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(serverName, setWmiInstance.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(setWmiInstance.Class); managementClass.Scope = managementScope; value = managementClass.CreateInstance(); } else { mPath.Server = serverName; ManagementScope managementScope1 = new ManagementScope(mPath, connectionOption); if (!mPath.IsClass) { ManagementObject managementObject = new ManagementObject(mPath); managementObject.Scope = managementScope1; try { managementObject.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode == ManagementStatus.NotFound) { int num = setWmiInstance.Path.IndexOf(':'); if (num != -1) { int num1 = setWmiInstance.Path.Substring(num).IndexOf('.'); if (num1 != -1) { string str = setWmiInstance.Path.Substring(0, num1 + num); ManagementPath managementPath = new ManagementPath(str); ManagementClass managementClass1 = new ManagementClass(managementPath); managementClass1.Scope = managementScope1; managementObject = managementClass1.CreateInstance(); } else { throw; } } else { throw; } } else { throw; } } value = managementObject; } else { ManagementClass managementClass2 = new ManagementClass(mPath); managementClass2.Scope = managementScope1; value = managementClass2.CreateInstance(); } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator(); while (enumerator.MoveNext()) { value[enumerator.Key as string] = enumerator.Value; } } } return value; }
public static SyntheticEthernetPortSettingData 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 SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); }
private void ConnectSetWmi() { ManagementObject value; SetWmiInstance setWmiInstance = (SetWmiInstance)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (setWmiInstance.InputObject == null) { ManagementPath managementPath = null; if (setWmiInstance.Class == null) { managementPath = new ManagementPath(setWmiInstance.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (setWmiInstance.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = setWmiInstance.Namespace; } if (!(managementPath.Server != ".") || !setWmiInstance.serverNameSpecified) { if (!managementPath.IsClass) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException1 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException2 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { InvalidOperationException invalidOperationException3 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException3; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { if (setWmiInstance.flagSpecified && setWmiInstance.PutType != PutType.CreateOnly) { InvalidOperationException invalidOperationException4 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException4; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } setWmiInstance.PutType = PutType.CreateOnly; } if (managementPath != null && (!(managementPath.Server == ".") || !setWmiInstance.serverNameSpecified)) { this.computerName = managementPath.Server; } ConnectionOptions connectionOption = setWmiInstance.GetConnectionOption(); try { if (setWmiInstance.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, setWmiInstance.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(setWmiInstance.Class); managementClass.Scope = managementScope; value = managementClass.CreateInstance(); } else { managementPath.Server = this.computerName; ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); if (!managementPath.IsClass) { ManagementObject managementObject = new ManagementObject(managementPath); managementObject.Scope = managementScope1; try { managementObject.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode == ManagementStatus.NotFound) { int num = setWmiInstance.Path.IndexOf(':'); if (num != -1) { int num1 = setWmiInstance.Path.Substring(num).IndexOf('.'); if (num1 != -1) { string str = setWmiInstance.Path.Substring(0, num1 + num); ManagementPath managementPath1 = new ManagementPath(str); ManagementClass managementClass1 = new ManagementClass(managementPath1); managementClass1.Scope = managementScope1; managementObject = managementClass1.CreateInstance(); } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value = managementObject; } else { ManagementClass managementClass2 = new ManagementClass(managementPath); managementClass2.Scope = managementScope1; value = managementClass2.CreateInstance(); } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator(); while (enumerator.MoveNext()) { value[enumerator.Key as string] = enumerator.Value; } } PutOptions putOption = new PutOptions(); putOption.Type = setWmiInstance.PutType; if (value == null) { InvalidOperationException invalidOperationException5 = new InvalidOperationException(); this.internalException = invalidOperationException5; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value.Put(this.results, putOption); } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } else { ManagementObject value1 = null; try { PutOptions putType = new PutOptions(); if (setWmiInstance.InputObject.GetType() != typeof(ManagementClass)) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException6 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException6; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value1 = (ManagementObject)setWmiInstance.InputObject.Clone(); } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { value1 = ((ManagementClass)setWmiInstance.InputObject).CreateInstance(); setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException7 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException7; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator dictionaryEnumerator = setWmiInstance.Arguments.GetEnumerator(); while (dictionaryEnumerator.MoveNext()) { value1[dictionaryEnumerator.Key as string] = dictionaryEnumerator.Value; } } putType.Type = setWmiInstance.PutType; if (value1 == null) { InvalidOperationException invalidOperationException8 = new InvalidOperationException(); this.internalException = invalidOperationException8; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value1.Put(this.results, putType); } } catch (ManagementException managementException5) { ManagementException managementException4 = managementException5; this.internalException = managementException4; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } }
private void CreateOrUpdate() { if (string.IsNullOrEmpty(this.WindowsGroup)) { Log.LogError("WindowsGroup is required."); return; } PutOptions options = new PutOptions { Type = PutType.UpdateOrCreate }; using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_HostSetting"), null)) { ManagementObject btsHostSetting = instance.CreateInstance(); if (btsHostSetting == null) { Log.LogError("There was a failure creating the MSBTS_HostSetting instance"); return; } btsHostSetting["Name"] = this.HostName; btsHostSetting["HostType"] = this.hostType; btsHostSetting["NTGroupName"] = this.WindowsGroup; btsHostSetting["AuthTrusted"] = this.Trusted; btsHostSetting["MgmtDbServerOverride"] = this.DatabaseServer; btsHostSetting["IsHost32BitOnly"] = this.Use32BitHostOnly; if (this.hostType == BizTalkHostType.InProcess) { btsHostSetting.SetPropertyValue("HostTracking", this.Tracking); btsHostSetting.SetPropertyValue("IsDefault", this.Default); } if (!string.IsNullOrEmpty(this.AdditionalHostSettings)) { string[] additionalproperties = this.AdditionalHostSettings.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in additionalproperties) { string[] property = s.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); btsHostSetting[property[0]] = property[1]; } } btsHostSetting.Put(options); this.explorer.SaveChanges(); } }
static void createOrUpdateWmi() { Console.WriteLine("Checking for namespace " + wmiNamespaceString + ", and creating if missing"); PutOptions options = new PutOptions(); options.Type = PutType.UpdateOrCreate; ManagementClass objHostSettingClass = new ManagementClass("root\\cimv2", "__Namespace", null); ManagementObject wmiObject = objHostSettingClass.CreateInstance(); wmiObject.SetPropertyValue("Name", wmiNamespaceName); wmiObject.Put(options); System.Management.ManagementClass wmiClass; try { wmiClass = new System.Management.ManagementClass(wmiNamespaceString, wmiClassString, null); wmiClass.CreateInstance(); Console.WriteLine(wmiClassString + " class exists"); } catch (ManagementException me) { Console.WriteLine(wmiClassString + " class does not exist, creating"); wmiClass = new System.Management.ManagementClass(wmiNamespaceString, null, null); wmiClass["__CLASS"] = wmiClassString; wmiClass.Qualifiers.Add("Static", true); wmiClass.Put(); } if (!testValueExists(wmiClass, "ManagedFolder")) { wmiClass.Properties.Add("ManagedFolder", System.Management.CimType.String, false); wmiClass.Properties["ManagedFolder"].Qualifiers.Add("Key", true); } if (!testValueExists(wmiClass, "MachineName")) { wmiClass.Properties.Add("MachineName", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "OverallState")) { wmiClass.Properties.Add("OverallState", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "OverallStateValue")) { wmiClass.Properties.Add("OverallStateValue", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "FileCount")) { wmiClass.Properties.Add("FileCount", System.Management.CimType.UInt64, false); } if (!testValueExists(wmiClass, "NumberOfFilesFailingVerification")) { wmiClass.Properties.Add("NumberOfFilesFailingVerification", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "VerificationFailureDetails")) { wmiClass.Properties.Add("VerificationFailureDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "LastSuccessfulVerification")) { wmiClass.Properties.Add("LastSuccessfulVerification", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "VerifyNewImages")) { wmiClass.Properties.Add("VerifyNewImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "ReverifyExistingImages")) { wmiClass.Properties.Add("ReverifyExistingImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "ReverifyInterval")) { wmiClass.Properties.Add("ReverifyInterval", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "ConsolidationEnabled")) { wmiClass.Properties.Add("ConsolidationEnabled", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "LastSuccessfulConsolidation")) { wmiClass.Properties.Add("LastSuccessfulConsolidation", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "NumberOfFilesFailingConsolidation")) { wmiClass.Properties.Add("NumberOfFilesFailingConsolidation", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "ConsolidationFailureDetails")) { wmiClass.Properties.Add("ConsolidationFailureDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "FailedReplications")) { wmiClass.Properties.Add("FailedReplications", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "NumberOfFilesQueuedForReplication")) { wmiClass.Properties.Add("NumberOfFilesQueuedForReplication", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "ReplicationTargetDetails")) { wmiClass.Properties.Add("ReplicationTargetDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "RetentionIssues")) { wmiClass.Properties.Add("RetentionIssues", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "RetentionIssueDetails")) { wmiClass.Properties.Add("RetentionIssueDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "RetentionEnabled")) { wmiClass.Properties.Add("RetentionEnabled", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "RetentionPolicyInheritedFromGlobal")) { wmiClass.Properties.Add("RetentionPolicyInheritedFromGlobal", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "DaysToRetainIntraDailyImages")) { wmiClass.Properties.Add("DaysToRetainIntraDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainConsolidatedDailyImages")) { wmiClass.Properties.Add("DaysToRetainConsolidatedDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainConsolidatedWeeklyImages")) { wmiClass.Properties.Add("DaysToRetainConsolidatedWeeklyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "MonthsToRetainConsolidatedMonthlyImages")) { wmiClass.Properties.Add("MonthsToRetainConsolidatedMonthlyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainIntraDailyImages")) { wmiClass.Properties.Add("DaysToRetainIntraDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "MonthlyRetentionIsSupported")) { wmiClass.Properties.Add("MonthlyRetentionIsSupported", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "MoveConsolidatedImages")) { wmiClass.Properties.Add("MoveConsolidatedImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "FailedHeadstartJobs")) { wmiClass.Properties.Add("FailedHeadstartJobs", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "HeadstartJobDetails")) { wmiClass.Properties.Add("HeadstartJobDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "LastScriptRunTime")) { wmiClass.Properties.Add("LastScriptRunTime", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "Timestamp")) { wmiClass.Properties.Add("Timestamp", System.Management.CimType.UInt64, false); } if (!testValueExists(wmiClass, "ListOfAllManagedFolders")) { wmiClass.Properties.Add("ListOfAllManagedFolders", System.Management.CimType.String, false); } try { wmiClass.Put(); } catch (ManagementException me) { if (me.ErrorCode.Equals(ManagementStatus.ClassHasInstances)) { Console.WriteLine("Deleting existing instances of " + wmiClassString); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiNamespaceString, "SELECT * FROM " + wmiClassString); foreach (ManagementObject queryObj in searcher.Get()) { queryObj.Delete(); } wmiClass.Put(); } else { throw me; } } }
public static ComputerSystem CreateInstance() { ManagementScope mgmtScope = _statMgmtScope ?? new ManagementScope { Path = { NamespacePath = CreatedWmiNamespace } }; var mgmtPath = new ManagementPath(CreatedClassName); var tmpMgmtClass = new ManagementClass(mgmtScope, mgmtPath, null); return new ComputerSystem(tmpMgmtClass.CreateInstance()); }
private void CreateOrUpdate() { PutOptions options = new PutOptions { Type = PutType.UpdateOrCreate }; using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_AdapterSetting"), null)) { ManagementObject btsHostSetting = instance.CreateInstance(); if (btsHostSetting == null) { Log.LogError("There was a failure creating the MSBTS_AdapterSetting instance"); return; } btsHostSetting["Name"] = this.AdaptorName; btsHostSetting["Comment"] = this.Comment ?? string.Empty; btsHostSetting["MgmtCLSID"] = this.MgmtCLSID; btsHostSetting.Put(options); this.explorer.SaveChanges(); } }
MigrationServiceNetworks( string sourceHost ) { // Get the service setting object. ManagementScope scope = new ManagementScope( @"\\" + sourceHost + @"\root\virtualization\v2", null); using (ManagementObject service = GetVirtualMachineMigrationService(scope)) using (ManagementObject serviceSettings = GetMigrationServiceSettings(service)) { // // Get currently set migration networks. // Console.WriteLine("Get currently set migration networks..."); foreach (ManagementObject network in serviceSettings.GetRelated("Msvm_VirtualSystemMigrationNetworkSettingData")) { using (network) { Console.WriteLine("Network settings..."); Console.WriteLine("Subnet Number: {0}", network["SubnetNumber"]); Console.WriteLine("Prefix length: {0}", network["PrefixLength"]); Console.WriteLine(); } } // // Add a migration network. // Console.WriteLine("Add a migration network..."); { ManagementPath settingPath = new ManagementPath("Msvm_VirtualSystemMigrationNetworkSettingData"); using (ManagementClass networkSettingDataClass = new ManagementClass(scope, settingPath, null)) using (ManagementObject newNetwork = networkSettingDataClass.CreateInstance()) { newNetwork["SubnetNumber"] = "192.168.1.0"; newNetwork["PrefixLength"] = 24; newNetwork["Metric"] = 100; newNetwork["Tags"] = new string[] { "Microsoft:UserManaged" }; // Perform add network. using (ManagementBaseObject inParams = service.GetMethodParameters("AddNetworkSettings")) { inParams["NetworkSettings"] = new string[] { newNetwork.GetText(TextFormat.CimDtd20) }; using (ManagementBaseObject outParams = service.InvokeMethod("AddNetworkSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } } Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } // // Modify and remove a migration network. // foreach (ManagementObject network in serviceSettings.GetRelated("Msvm_VirtualSystemMigrationNetworkSettingData")) { using (network) { // Modify the added network. if (((string)network["SubnetNumber"]).Equals("192.168.1.0") && ((Byte)network["PrefixLength"]).Equals(24)) { // // Modify the added network. // Console.WriteLine("Modify migration network..."); { // Change metric value from 100 to 200. network["Metric"] = 200; using (ManagementBaseObject inParams = service.GetMethodParameters("ModifyNetworkSettings")) { inParams["NetworkSettings"] = new string[] { network.GetText(TextFormat.CimDtd20) }; using (ManagementBaseObject outParams = service.InvokeMethod("ModifyNetworkSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } // // Remove migration network. // Console.WriteLine("Remove migration network..."); { using (ManagementBaseObject inParams = service.GetMethodParameters("RemoveNetworkSettings")) { inParams["NetworkSettings"] = new string[] { network.Path.Path }; using (ManagementBaseObject outParams = service.InvokeMethod("RemoveNetworkSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } } } } } }
/// <summary> /// Copy a ManagementObject to a new Path /// </summary> /// <param name="MO"></param> /// <param name="Scope"></param> /// <param name="Dest"></param> static public void ManagementObjectCopy(ManagementBaseObject MO, ManagementScope Scope, ManagementPath Dest) { if (MO != null) { try { ManagementObject MORemote = new ManagementObject(); ManagementClass RemoteClas = new ManagementClass(Scope, Dest, new ObjectGetOptions()); MORemote = RemoteClas.CreateInstance(); foreach (PropertyData PD in MO.Properties) { try { MORemote.Properties[PD.Name].Value = PD.Value; } catch { } } MORemote.Put(); } catch { } } }
public static NetworkAdapterConfiguration CreateInstance() { var mgmtScope = _statMgmtScope ?? new ManagementScope { Path = { NamespacePath = CreatedWmiNamespace } }; var mgmtPath = new ManagementPath(CreatedClassName); var tmpMgmtClass = new ManagementClass(mgmtScope, mgmtPath, null); return new NetworkAdapterConfiguration(tmpMgmtClass.CreateInstance()); }