/// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { //create the resourcelocator object IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); //create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); string resultXml = m_session.Invoke(action, m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) { Dispose(m_session); } } }//End ProcessRecord()
/// <summary> /// Change the state of the virtual machine specified by the /// virtual machine reference (ResourceLocator) and the specified state (start/stop/etc.) /// </summary> public string ChangeVirtualMachineState(Xen_VirtualMachine_Reference_Type virtualSystem, UInt16 state) { string resourceURIInUse = null; string response = null; resourceURIInUse = string.Format("{0}/{1}", m_cim_resourceURIBase, "Xen_ComputerSystem"); IWSManResourceLocator virtualMachineLoc = (IWSManResourceLocator)ConvertToResourceLocator(resourceURIInUse, virtualSystem); try { string vmParams = GenerateStateChangeInputXML(state); response = m_wsmanSession.Invoke("RequestStateChange", virtualMachineLoc, vmParams, 0); // The response contains reference to the resulting VM. Deserialize it into a class. using (StringReader stream = new StringReader(response)) { XmlSerializer serializer = new XmlSerializer(typeof(Xen_RequestStateChange_OUTPUT_Type)); Xen_RequestStateChange_OUTPUT_Type responseSer = (Xen_RequestStateChange_OUTPUT_Type)serializer.Deserialize(stream); WaitForJobCompletion(responseSer.Job, "Xen_SystemStateChangeJob", typeof(Xen_SystemStateChangeJob_Type)); // wait until the state change job is complete } } catch (Exception ex) { throw ex; } return(response); }
protected override void ProcessRecord() { try { IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, null, null, this.m_wsmanObject, this.resourceuri); this.m_session = this.helper.CreateSessionObject(this.m_wsmanObject, this.Authentication, this.sessionoption, this.Credential, this.connectionStr, this.CertificateThumbprint, this.usessl.IsPresent); string rootNodeName = this.helper.GetRootNodeName(this.helper.WSManOp, wSManResourceLocator.resourceUri, this.action); string str = this.helper.ProcessInput(this.m_wsmanObject, this.filepath, this.helper.WSManOp, rootNodeName, this.valueset, wSManResourceLocator, this.m_session); string str1 = this.m_session.Invoke(this.action, wSManResourceLocator, str, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str1); base.WriteObject(xmlDocument.DocumentElement); } finally { if (!string.IsNullOrEmpty(this.m_wsmanObject.Error)) { this.helper.AssertError(this.m_wsmanObject.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(this.m_session.Error)) { this.helper.AssertError(this.m_session.Error, true, this.resourceuri); } if (this.m_session != null) { this.Dispose(this.m_session); } } }
/// <summary> /// Create a Basic HVM (Hardware Virtualized) virtual machine with the /// specified name, description, number of processors and memory. /// </summary> public Xen_VirtualMachine_Reference_Type CreateVirtualMachine( string vmName, string vmDescription, int numProcs, int memMB ) { IWSManResourceLocator vsmsService = GetVirtualSystemManagementService(); // Create an empty VM with default processor and memory settings and no NIC or virtual disk string vmParams = GenerateDefineSystemInputXML(vmName, vmDescription, numProcs, memMB); string responseDefineSystem = m_wsmanSession.Invoke("DefineSystem", vsmsService, vmParams, 0); Xen_VirtualMachine_Reference_Type definedSystem = null; // The response contains a reference to the resulting VM. Deserialize it into a class. using (StringReader stream = new StringReader(responseDefineSystem)) { XmlSerializer serializer = new XmlSerializer(typeof(Xen_DefineSystem_OUTPUT_Type)); Xen_DefineSystem_OUTPUT_Type responseDS = (Xen_DefineSystem_OUTPUT_Type)serializer.Deserialize(stream); definedSystem = responseDS.ResultingSystem; if (responseDS.ReturnValue == 4096) // a job will be returned { WaitForJobCompletion(responseDS.Job, "Xen_VirtualSystemModifyResourcesJob", typeof(Xen_VirtualSystemModifyResourcesJob_Type)); } } return(definedSystem); }
/// <summary> /// Add a virtual Disk and a virtual NIC to the virtual machine /// specified by the virtual machine reference (resource locator) /// </summary> public void AddDiskAndNicToVirtualMachine(Xen_VirtualMachine_Reference_Type definedSystem) { IWSManResourceLocator vsmsService = GetVirtualSystemManagementService(); string responseAddResourceSetting = null; string diskPoolId = GetStoragePool(); string netPoolId = GetNetworkPool(); StringCollection rasds = GetRasdsToBeAdded(diskPoolId, netPoolId); if (rasds != null) { string vmuuid = null; // add the RASDs one by one foreach (String rasd in rasds) { vmuuid = FindVirtualMachineID(definedSystem); String vmParams = GenerateAddResourceInputXML(vmuuid, rasd); if (vmParams != null) { responseAddResourceSetting = m_wsmanSession.Invoke("AddResourceSetting", vsmsService, vmParams, 0); } } } else { throw new Exception("No RASDs defined"); } }
/// <summary> /// Waits for async jobs returned by one of the CIM methods to complete /// </summary> private bool WaitForJobCompletion(Xen_Job_Reference_Type jobRef, string jobClassName, Type jobType) { bool jobComplete = false; string resourceURI = string.Format("{0}/{1}", m_cim_resourceURIBase, jobClassName);//"Xen_SystemStateChangeJob"); IWSManResourceLocator resLoc = ConvertToResourceLocator(resourceURI, jobRef); while (true) { string jobinststr = m_wsmanSession.Get(resLoc, 0); using (StringReader stream = new StringReader(jobinststr)) { XmlSerializer serializer = new XmlSerializer(jobType); Xen_Job_Type job = (Xen_Job_Type)serializer.Deserialize(stream); if ((job.JobState == 7) || (job.JobState == 10)) // 7 = complete, 10 = exception { if (job.JobState == 7) { jobComplete = true; } break; } } } return(jobComplete); }
internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { string resource = null; if (resourceuri != null) { resource = resourceuri.ToString(); } if (selectorset != null) { resource = resource + "?"; int i = 0; foreach (DictionaryEntry entry in selectorset) { i++; resource = resource + entry.Key.ToString() + "=" + entry.Value.ToString(); if (i < selectorset.Count) { resource += "+"; } } } IWSManResourceLocator m_resource = null; try { m_resource = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(resource); if (optionset != null) { foreach (DictionaryEntry entry in optionset) { if (entry.Value.ToString() == null) { m_resource.AddOption(entry.Key.ToString(), null, 1); } else { m_resource.AddOption(entry.Key.ToString(), entry.Value, 1); } } } if (!string.IsNullOrEmpty(fragment)) { m_resource.FragmentPath = fragment; } if (dialect != null) { m_resource.FragmentDialect = dialect.ToString(); } } catch (COMException ex) { AssertError(ex.Message, false, null); } return(m_resource); }
/// <summary> /// Convert a resource URI to a WS-Management ResourceLocator /// A ResourceLocator is a reference to a specific CIM instance /// </summary> private IWSManResourceLocator ConvertToResourceLocator(string resourceURI, CTX_Reference_Type refType) { IWSManResourceLocator resLoc = (IWSManResourceLocator)m_wsman.CreateResourceLocator(resourceURI); foreach (CTX_Selector_Type selector in refType.ReferenceParameters.SelectorSet.Selector) { resLoc.AddSelector(selector.Name, selector.Value); } return(resLoc); }
/// <summary> /// Get the singleton instance of the Xen_VirtualSystemManagementService class /// This instance is a factory object that allows creation and lifecycle management of VMs /// </summary> private IWSManResourceLocator GetVirtualSystemManagementService() { if (m_vsmsServiceObj == null) { string resourceURI = string.Format("{0}/{1}", m_cim_resourceURIBase, "Xen_VirtualSystemManagementService"); m_vsmsServiceObj = (IWSManResourceLocator)m_wsman.CreateResourceLocator(resourceURI); m_vsmsServiceObj.AddSelector("Name", "Xen Hypervisor"); m_vsmsServiceObj.AddSelector("SystemCreationClassName", "Xen_HostComputerSystem"); m_vsmsServiceObj.AddSelector("SystemName", "myxenservername"); m_vsmsServiceObj.AddSelector("CreationClassName", "Xen_VirtualSystemManagementService"); } return(m_vsmsServiceObj); }
/// <summary> /// Delete the Virtual Machine specified by the /// Virtual Machine reference (ResourceLocator instance) /// </summary> public string DeleteVirtualMachine(Xen_VirtualMachine_Reference_Type affectedVM) { string responseDestroy = null; string vmid = null; try { vmid = FindVirtualMachineID(affectedVM); IWSManResourceLocator vsmsService = GetVirtualSystemManagementService(); if (vmid != null) { string vmParams = GenerateDeleteVMInputXML(vmid); responseDestroy = m_wsmanSession.Invoke("DestroySystem", vsmsService, vmParams, 0); } } catch (Exception ex) { throw ex; } return(responseDestroy); }
/// <summary> /// Enumerates all instances of a CIM class using a CIM query language (WQL supported only) /// </summary> public List <string> Query(string CIMClass, string filter, string dialect) { List <string> xml_responses = new List <string>(); string resource = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/"; IWSManResourceLocator resourceLocator = (IWSManResourceLocator)m_wsman.CreateResourceLocator(string.Format("{0}{1}", resource, CIMClass)); try { IWSManEnumerator vm_enum = (IWSManEnumerator)m_wsmanSession.Enumerate(resourceLocator, filter, dialect, 0); while (!vm_enum.AtEndOfStream) { string ss = vm_enum.ReadItem(); xml_responses.Add(ss); } } catch (Exception ex) { throw new Exception("Failed: Query()", ex); } return(xml_responses); }
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string resultString = null; //if file path is given if (!string.IsNullOrEmpty(filepath) && valueset == null) { if (!File.Exists(filepath)) { throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); } resultString = ReadFile(filepath); return(resultString); } switch (operation) { case "new": case "invoke": string parameters = null, nilns = null; string xmlns = GetXmlNs(resourceUri.ResourceUri); //if valueset is given, i.e hashtable if (valueset != null) { foreach (DictionaryEntry entry in valueset) { parameters = parameters + "<p:" + entry.Key.ToString(); if (entry.Value.ToString() == null) { parameters = parameters + " " + ATTR_NIL; nilns = " " + NS_XSI; } parameters = parameters + ">" + entry.Value.ToString() + "</p:" + entry.Key.ToString() + ">"; } } resultString = "<p:" + root + " " + xmlns + nilns + ">" + parameters + "</p:" + root + ">"; break; case "set": string getResult = sessionObj.Get(resourceUri, 0); XmlDocument xmlfile = new XmlDocument(); xmlfile.LoadXml(getResult); string xpathString = null; if (valueset != null) { foreach (DictionaryEntry entry in valueset) { xpathString = @"/*/*[local-name()=""" + entry.Key + @"""]"; if (entry.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { //'Ignore cim:Location xpathString = @"/*/*[local-name()=""" + entry.Key + @""" and namespace-uri() != """ + NS_CIMBASE + @"""]"; } XmlNodeList nodes = xmlfile.SelectNodes(xpathString); if (nodes.Count == 0) { throw new ArgumentException(_resourceMgr.GetString("NoResourceMatch")); } else if (nodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("MultipleResourceMatch")); } else { XmlNode node = nodes[0]; if (node.HasChildNodes) { if (node.ChildNodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } else { XmlNode tmpNode = node.ChildNodes[0]; //.Item[0]; if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } } } if (string.IsNullOrEmpty(entry.Key.ToString())) { //XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); XmlAttribute newnode = xmlfile.CreateAttribute(XmlNodeType.Attribute.ToString(), ATTR_NIL_NAME, NS_XSI_URI); newnode.Value = "true"; node.Attributes.Append(newnode); //(newnode.Attributes.Item(0).FirstChild ); node.Value = ""; } else { node.Attributes.RemoveNamedItem(ATTR_NIL_NAME); node.InnerText = entry.Value.ToString(); } } } //end for } //end if valueset resultString = xmlfile.OuterXml; break; }//end switch return(resultString); }
private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string fragment; try { int flags = 0; IWSManEnumerator obj; if (returntype != null) { if (returntype.Equals("object", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnObject(); } else if (returntype.Equals("epr", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnEPR(); } else { flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } } if (shallow) { flags |= wsmanObject.EnumerationFlagHierarchyShallow(); } else if (basepropertiesonly) { flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } else { flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } if (dialect != null && filter != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { if (associations) { flags |= wsmanObject.EnumerationFlagAssociationInstance(); } else { flags |= wsmanObject.EnumerationFlagAssociatedInstance(); } fragment = helper.URI_ASSOCIATION_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { filter = GetFilter(); fragment = helper.URI_SELECTOR_DIALECT; dialect = new Uri(fragment); } obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else { obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); } while (!obj.AtEndOfStream) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(obj.ReadItem()); WriteObject(xmldoc.FirstChild); } } catch (Exception ex) { ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null); WriteError(er); } }
private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string uRIWQLDIALECT; IWSManEnumerator wSManEnumerator; try { int num = 0; if (this.returntype != null) { if (!this.returntype.Equals("object", StringComparison.CurrentCultureIgnoreCase)) { if (!this.returntype.Equals("epr", StringComparison.CurrentCultureIgnoreCase)) { num = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } else { num = wsmanObject.EnumerationFlagReturnEPR(); } } else { num = wsmanObject.EnumerationFlagReturnObject(); } } if (!this.shallow) { if (!this.basepropertiesonly) { num = num | wsmanObject.EnumerationFlagHierarchyDeep(); } else { num = num | wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } } else { num = num | wsmanObject.EnumerationFlagHierarchyShallow(); } if (!(this.dialect != null) || this.filter == null) { if (this.filter == null) { wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, null, num); } else { uRIWQLDIALECT = this.helper.URI_WQL_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, this.dialect.ToString(), num); } } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_WQL_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { uRIWQLDIALECT = this.helper.URI_WQL_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_ASSOCIATION_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { if (!this.associations) { num = num | wsmanObject.EnumerationFlagAssociatedInstance(); } else { num = num | wsmanObject.EnumerationFlagAssociationInstance(); } uRIWQLDIALECT = this.helper.URI_ASSOCIATION_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } else { if (this.dialect.ToString().Equals(this.helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase) || this.dialect.ToString().Equals(this.helper.URI_SELECTOR_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { this.filter = this.GetFilter(); uRIWQLDIALECT = this.helper.URI_SELECTOR_DIALECT; this.dialect = new Uri(uRIWQLDIALECT); } } } wSManEnumerator = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, this.filter, this.dialect.ToString(), num); } while (!wSManEnumerator.AtEndOfStream) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(wSManEnumerator.ReadItem()); base.WriteObject(xmlDocument.FirstChild); } } catch (Exception exception1) { Exception exception = exception1; ErrorRecord errorRecord = new ErrorRecord(exception, "Exception", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } }
/// <summary> /// Get the singleton instance of the Xen_VirtualSystemManagementService class /// This instance is a factory object that allows creation and lifecycle management of VMs /// </summary> private IWSManResourceLocator GetVirtualSystemManagementService() { if (m_vsmsServiceObj == null) { string resourceURI = string.Format("{0}/{1}", m_cim_resourceURIBase, "Xen_VirtualSystemManagementService"); m_vsmsServiceObj = (IWSManResourceLocator)m_wsman.CreateResourceLocator(resourceURI); m_vsmsServiceObj.AddSelector("Name", "Xen Hypervisor"); m_vsmsServiceObj.AddSelector("SystemCreationClassName", "Xen_HostComputerSystem"); m_vsmsServiceObj.AddSelector("SystemName", "myxenservername"); m_vsmsServiceObj.AddSelector("CreationClassName", "Xen_VirtualSystemManagementService"); } return m_vsmsServiceObj; }
protected override void ProcessRecord() { IWSManSession wSManSession = null; IWSManEx wSManClass = (IWSManEx)(new WSManClass()); this.helper = new WSManHelper(this); this.helper.WSManOp = "Get"; string str = this.helper.CreateConnectionString(this.connectionuri, this.port, this.computername, this.applicationname); if (this.connectionuri != null) { try { string[] strArrays = new string[1]; object[] objArray = new object[4]; objArray[0] = ":"; objArray[1] = this.port; objArray[2] = "/"; objArray[3] = this.applicationname; strArrays[0] = string.Concat(objArray); string[] strArrays1 = this.connectionuri.OriginalString.Split(strArrays, StringSplitOptions.None); string[] strArrays2 = new string[1]; strArrays2[0] = "//"; string[] strArrays3 = strArrays1[0].Split(strArrays2, StringSplitOptions.None); this.computername = strArrays3[1].Trim(); } catch (IndexOutOfRangeException indexOutOfRangeException) { this.helper.AssertError(this.helper.GetResourceMsgFromResourcetext("NotProperURI"), false, this.connectionuri); } } try { IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, this.fragment, this.dialect, wSManClass, this.resourceuri); wSManSession = this.helper.CreateSessionObject(wSManClass, this.Authentication, this.sessionoption, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); if (this.enumerate) { try { this.ReturnEnumeration(wSManClass, wSManResourceLocator, wSManSession); } catch (Exception exception1) { Exception exception = exception1; this.helper.AssertError(exception.Message, false, this.computername); } } else { XmlDocument xmlDocument = new XmlDocument(); try { xmlDocument.LoadXml(wSManSession.Get(wSManResourceLocator, 0)); } catch (XmlException xmlException1) { XmlException xmlException = xmlException1; this.helper.AssertError(xmlException.Message, false, this.computername); } if (string.IsNullOrEmpty(this.fragment)) { base.WriteObject(xmlDocument.FirstChild); } else { base.WriteObject(string.Concat(xmlDocument.FirstChild.LocalName, "=", xmlDocument.FirstChild.InnerText)); } } } finally { if (!string.IsNullOrEmpty(wSManClass.Error)) { this.helper.AssertError(wSManClass.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, this.resourceuri); } if (wSManSession != null) { this.Dispose(wSManSession); } } }
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string outerXml = null; if (string.IsNullOrEmpty(filepath) || valueset != null) { string str = operation; string str1 = str; if (str != null) { if (str1 == "new" || str1 == "invoke") { string str2 = null; string str3 = null; string xmlNs = this.GetXmlNs(resourceUri.resourceUri); if (valueset != null) { foreach (DictionaryEntry dictionaryEntry in valueset) { str2 = string.Concat(str2, "<p:", dictionaryEntry.Key.ToString()); if (dictionaryEntry.Value.ToString() == null) { str2 = string.Concat(str2, " xsi:nil=\"true\""); str3 = " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; } string[] strArrays = new string[6]; strArrays[0] = str2; strArrays[1] = ">"; strArrays[2] = dictionaryEntry.Value.ToString(); strArrays[3] = "</p:"; strArrays[4] = dictionaryEntry.Key.ToString(); strArrays[5] = ">"; str2 = string.Concat(strArrays); } } string[] strArrays1 = new string[10]; strArrays1[0] = "<p:"; strArrays1[1] = root; strArrays1[2] = " "; strArrays1[3] = xmlNs; strArrays1[4] = str3; strArrays1[5] = ">"; strArrays1[6] = str2; strArrays1[7] = "</p:"; strArrays1[8] = root; strArrays1[9] = ">"; outerXml = string.Concat(strArrays1); } else { if (str1 == "set") { string str4 = sessionObj.Get(resourceUri, 0); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(str4); if (valueset != null) { foreach (DictionaryEntry dictionaryEntry1 in valueset) { string str5 = string.Concat("/*/*[local-name()=\"", dictionaryEntry1.Key, "\"]"); if (dictionaryEntry1.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { str5 = string.Concat("/*/*[local-name()=\"", dictionaryEntry1.Key, "\" and namespace-uri() != \"http://schemas.dmtf.org/wbem/wsman/1/base\"]"); } XmlNodeList xmlNodeLists = xmlDocument.SelectNodes(str5); if (xmlNodeLists.Count != 0) { if (xmlNodeLists.Count <= 1) { XmlNode itemOf = xmlNodeLists[0]; if (itemOf.HasChildNodes) { if (itemOf.ChildNodes.Count <= 1) { XmlNode xmlNodes = itemOf.ChildNodes[0]; if (!xmlNodes.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(this._resourceMgr.GetString("NOAttributeMatch")); } } else { throw new ArgumentException(this._resourceMgr.GetString("NOAttributeMatch")); } } if (!string.IsNullOrEmpty(dictionaryEntry1.Key.ToString())) { itemOf.Attributes.RemoveNamedItem("xsi:nil"); itemOf.InnerText = dictionaryEntry1.Value.ToString(); } else { XmlAttribute xmlAttribute = xmlDocument.CreateAttribute(XmlNodeType.Attribute.ToString(), "xsi:nil", "http://www.w3.org/2001/XMLSchema-instance"); xmlAttribute.Value = "true"; itemOf.Attributes.Append(xmlAttribute); itemOf.Value = ""; } } else { throw new ArgumentException(this._resourceMgr.GetString("MultipleResourceMatch")); } } else { throw new ArgumentException(this._resourceMgr.GetString("NoResourceMatch")); } } } outerXml = xmlDocument.OuterXml; } } } return outerXml; } else { if (File.Exists(filepath)) { outerXml = this.ReadFile(filepath); return outerXml; } else { throw new FileNotFoundException(this._resourceMgr.GetString("InvalidFileName")); } } }
internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { string resultString = null; //if file path is given if (!string.IsNullOrEmpty(filepath) && valueset == null) { if (!File.Exists(filepath)) { throw new FileNotFoundException(_resourceMgr.GetString("InvalidFileName")); } resultString = ReadFile(filepath); return resultString; } switch (operation) { case "new": case "invoke": string parameters = null, nilns = null; string xmlns = GetXmlNs(resourceUri.ResourceUri); //if valueset is given, i.e hashtable if (valueset != null) { foreach (DictionaryEntry entry in valueset) { parameters = parameters + "<p:" + entry.Key.ToString(); if (entry.Value.ToString() == null) { parameters = parameters + " " + ATTR_NIL; nilns = " " + NS_XSI; } parameters = parameters + ">" + entry.Value.ToString() + "</p:" + entry.Key.ToString() + ">"; } } resultString = "<p:" + root + " " + xmlns + nilns + ">" + parameters + "</p:" + root + ">"; break; case "set": string getResult = sessionObj.Get(resourceUri, 0); XmlDocument xmlfile = new XmlDocument(); xmlfile.LoadXml(getResult); string xpathString = null; if (valueset != null) { foreach (DictionaryEntry entry in valueset) { xpathString = @"/*/*[local-name()=""" + entry.Key + @"""]"; if (entry.Key.ToString().Equals("location", StringComparison.OrdinalIgnoreCase)) { //'Ignore cim:Location xpathString = @"/*/*[local-name()=""" + entry.Key + @""" and namespace-uri() != """ + NS_CIMBASE + @"""]"; } XmlNodeList nodes = xmlfile.SelectNodes(xpathString); if (nodes.Count == 0) { throw new ArgumentException(_resourceMgr.GetString("NoResourceMatch")); } else if (nodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("MultipleResourceMatch")); } else { XmlNode node = nodes[0]; if (node.HasChildNodes) { if (node.ChildNodes.Count > 1) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } else { XmlNode tmpNode = node.ChildNodes[0];//.Item[0]; if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); } } } if (string.IsNullOrEmpty(entry.Key.ToString())) { //XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); XmlAttribute newnode = xmlfile.CreateAttribute(XmlNodeType.Attribute.ToString(), ATTR_NIL_NAME, NS_XSI_URI); newnode.Value = "true"; node.Attributes.Append(newnode); //(newnode.Attributes.Item(0).FirstChild ); node.Value = ""; } else { node.Attributes.RemoveNamedItem(ATTR_NIL_NAME); node.InnerText = entry.Value.ToString(); } } }//end for }//end if valueset resultString = xmlfile.OuterXml; break; }//end switch return resultString; }
protected override void ProcessRecord() { IWSManEx wSManClass = (IWSManEx)(new WSManClass()); this.helper = new WSManHelper(this); this.helper.WSManOp = "set"; IWSManSession wSManSession = null; if (this.dialect != null) { if (this.dialect.ToString().Equals(this.helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_WQL_DIALECT); } if (this.dialect.ToString().Equals(this.helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_SELECTOR_DIALECT); } if (this.dialect.ToString().Equals(this.helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase)) { this.dialect = new Uri(this.helper.URI_ASSOCIATION_DIALECT); } } try { string str = this.helper.CreateConnectionString(this.connectionuri, this.port, this.computername, this.applicationname); if (this.connectionuri != null) { try { string[] strArrays = new string[1]; object[] objArray = new object[4]; objArray[0] = ":"; objArray[1] = this.port; objArray[2] = "/"; objArray[3] = this.applicationname; strArrays[0] = string.Concat(objArray); string[] strArrays1 = this.connectionuri.OriginalString.Split(strArrays, StringSplitOptions.None); string[] strArrays2 = new string[1]; strArrays2[0] = "//"; string[] strArrays3 = strArrays1[0].Split(strArrays2, StringSplitOptions.None); this.computername = strArrays3[1].Trim(); } catch (IndexOutOfRangeException indexOutOfRangeException) { this.helper.AssertError(this.helper.GetResourceMsgFromResourcetext("NotProperURI"), false, this.connectionuri); } } IWSManResourceLocator wSManResourceLocator = this.helper.InitializeResourceLocator(this.optionset, this.selectorset, this.fragment, this.dialect, wSManClass, this.resourceuri); wSManSession = this.helper.CreateSessionObject(wSManClass, this.Authentication, this.sessionoption, this.Credential, str, this.CertificateThumbprint, this.usessl.IsPresent); string rootNodeName = this.helper.GetRootNodeName(this.helper.WSManOp, wSManResourceLocator.resourceUri, null); string str1 = this.helper.ProcessInput(wSManClass, this.filepath, this.helper.WSManOp, rootNodeName, this.valueset, wSManResourceLocator, wSManSession); XmlDocument xmlDocument = new XmlDocument(); try { xmlDocument.LoadXml(wSManSession.Put(wSManResourceLocator, str1, 0)); } catch (XmlException xmlException1) { XmlException xmlException = xmlException1; this.helper.AssertError(xmlException.Message, false, this.computername); } if (string.IsNullOrEmpty(this.fragment)) { base.WriteObject(xmlDocument.DocumentElement); } else { if (xmlDocument.DocumentElement.ChildNodes.Count > 0) { foreach (XmlNode childNode in xmlDocument.DocumentElement.ChildNodes) { if (!childNode.Name.Equals(this.fragment, StringComparison.CurrentCultureIgnoreCase)) { continue; } base.WriteObject(string.Concat(childNode.Name, " = ", childNode.InnerText)); } } } } finally { if (!string.IsNullOrEmpty(wSManClass.Error)) { this.helper.AssertError(wSManClass.Error, true, this.resourceuri); } if (!string.IsNullOrEmpty(wSManSession.Error)) { this.helper.AssertError(wSManSession.Error, true, this.resourceuri); } if (wSManSession != null) { this.Dispose(wSManSession); } } }