/// <summary> /// Creates an instance of the VMA proxy and establishes a connection /// </summary> /// <param name="url"></param> /// <param name="username"></param> /// <param name="password"></param> public void Connect(string url, string username, string password) { if (vimService != null) { if (vConnection != null) { vimService.Logout(new VimApi_55.ManagedObjectReference() { type = vConnection.SessionManager.Type, Value = vConnection.SessionManager.Value }); } vimService.Dispose(); vimService = null; vConnection = null; } vimService = new VimService(); vimService.Url = url; vimService.Timeout = 600000; //The value can be set to some higher value also. vimService.CookieContainer = new System.Net.CookieContainer(); if (vConnection.SessionManager != null) { vimService.Login(new VimApi_55.ManagedObjectReference() { type = vConnection.SessionManager.Type, Value = vConnection.SessionManager.Value }, username, password, null); } }
//internal static VirtualMachineConfigInfo VmConfig{get; private set;} public bool Connect(string url, string userName, string password) { //try{ //LogEvent(this, new LogEventArgs(700, Severity.INFO, "Connecting to hypervisor "+url)); service = new VimService(); service.Url = url; service.CookieContainer = new System.Net.CookieContainer(); serviceContent = service.RetrieveServiceContent(serviceRef); propertiesCollector = serviceContent.propertyCollector; rootF = serviceContent.rootFolder; if (serviceContent.sessionManager != null) { UserSession us = service.Login(serviceContent.sessionManager, userName, password, null); if (LogEvent != null) { LogEvent(this, new LogEventArgs(0, Severity.TRIVIA, "Got session '" + us.userName + "@" + us.loginTime + "'")); } } if (LogEvent != null) { LogEvent(this, new LogEventArgs(0, Severity.DEBUG, "Instanciated connection to hypervisor " + url)); } return(true); //} //catch(Exception e){ //Logger.Append("HUBRN", Severity.ERROR, "Could not connect to hypervisor '"+url+"' : "+e.ToString()); // return false; //} }
/// <summary> /// Creates an instance of the VMA proxy and establishes a connection /// </summary> /// <param name="url"></param> /// <param name="username"></param> /// <param name="password"></param> public void Connect(string url, string username, string password) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _service.Timeout = 600000; //The value can be set to some higher value also. _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, username, password, null); } _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
public object Collect(string url, string username, string password) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; if ((_sic.sessionManager != null)) { _service.Login(_sic.sessionManager, username, password, null); } string apiversion = _sic.about.apiType; return(_sic); }
private void button1_Click(object sender, EventArgs e) { try { _service = new VimService(); _service.Url = vurl; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); CreateServiceRef("ServiceInstance"); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; Extension ext = new Extension(); ext.key = "com.virtualizeplanet." + comboBox2.SelectedItem.ToString(); //sdsd if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, vusername, vpassword, null); ManagedObjectReference extMgrMof = _sic.extensionManager; _service.UnregisterExtension(extMgrMof, ext.key); } int c2index = comboBox2.SelectedIndex; comboBox2.Items.RemoveAt(c2index); comboBox2.Text = ""; MessageBox.Show("Done"); } catch { MessageBox.Show("Something may have gone wrong"); } }
/// <summary> /// Connects to the vSphere service using the specified credentials. /// </summary> /// <param name="credential">The <see cref="NetworkCredential" /> to use to connect to vSphere.</param> /// <exception cref="ArgumentNullException"><paramref name="credential" /> is null.</exception> public void Connect(NetworkCredential credential) { if (credential == null) { throw new ArgumentNullException(nameof(credential)); } PrepareToConnect(); LogDebug($"Connecting to vSphere using user credential '{credential.UserName}'."); string userName = BuildUserName(credential); _vimService.Login(_serviceContent.sessionManager, userName, credential.Password, null); }
static void Main(string[] args) { var _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; service.Url = "https://10.2.61.62/sdk"; service.Timeout = 1800000; service.CookieContainer = new System.Net.CookieContainer(); ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true; //ServicePoint sp = ServicePointManager.FindServicePoint(new Uri("https://10.2.61.62/client/client.xml")); var context = service.RetrieveServiceContent(_svcRef); service.Login(context.sessionManager, @"vsphere.local\administrator", "1qaz2wsx#EDC", null); Console.Read(); }
public object Collect(string url, string username, string password, string EntityType) { if (_service != null) { Disconnect(); } ArrayList ObjectList = new ArrayList(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Inventory.xml"); _service = new VimService(); _service.Url = url; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; if ((_sic.sessionManager != null)) { _service.Login(_sic.sessionManager, username, password, null); } TraversalSpec rpToRp = new TraversalSpec(); rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.name = "rpToRp"; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; TraversalSpec rpToVm = new TraversalSpec(); rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.name = "rpToVm"; rpToVm.selectSet = new SelectionSpec[] { }; TraversalSpec crToRp = new TraversalSpec(); crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.name = "crToRp"; crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() }; crToRp.selectSet[1].name = "rpToVm"; TraversalSpec crToH = new TraversalSpec(); crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.name = "crToH"; crToH.selectSet = new SelectionSpec[] { }; TraversalSpec dcToHf = new TraversalSpec(); dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.name = "dcToHf"; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.name = "dcToVmf"; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; TraversalSpec HToVm = new TraversalSpec(); HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.name = "HToVm"; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders"; TraversalSpec visitFolders = new TraversalSpec(); visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.name = "visitFolders"; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, crToH, crToRp, rpToVm }; visitFolders.selectSet[0].name = "visitFolders"; TraversalSpec tSpec = default(TraversalSpec); tSpec = visitFolders; PropertySpec[] propSpecArray = null; propSpecArray = new PropertySpec[] { new PropertySpec() }; propSpecArray[0].type = EntityType; propSpecArray[0].all = true; propSpecArray[0].allSpecified = true; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propSpecArray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = _sic.rootFolder; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = new SelectionSpec[] { tSpec }; ObjectContent[] ocary = _service.RetrieveProperties(_propCol, new PropertyFilterSpec[] { spec }); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (Int32 oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; string moref = mor.Value.ToString(); pcary = oc.propSet; //string vmname =""; for (Int32 propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("guest"))) { if (((VimyyApi.GuestInfo)(pc.val)).disk != null) { int diskcount = ((VimyyApi.GuestInfo)(pc.val)).disk.Length; XmlElement xmlvdisk = xmldoc.CreateElement(null, "Vdisk", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlAttribute newAtt = xmldoc.CreateAttribute("diskcount"); newAtt.Value = diskcount.ToString(); xmlvdisk.Attributes.Append(newAtt); xmlnode3.AppendChild(xmlvdisk); for (Int32 guestcount = 0; guestcount <= diskcount - 1; guestcount++) { long capacity = (((VimyyApi.GuestInfo)(pc.val)).disk[guestcount].capacity); //capacity = capacity / bytes; long freespace = (((VimyyApi.GuestInfo)(pc.val)).disk[guestcount].freeSpace); //freespace = freespace / bytes; string diskpath = (((VimyyApi.GuestInfo)(pc.val)).disk[guestcount].diskPath); XmlElement xmldisk = xmldoc.CreateElement(null, "Disk", null); xmlnode3 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); newAtt = xmldoc.CreateAttribute("ID"); newAtt.Value = guestcount.ToString(); xmldisk.Attributes.Append(newAtt); newAtt = xmldoc.CreateAttribute("Path"); newAtt.Value = diskpath; xmldisk.Attributes.Append(newAtt); newAtt = xmldoc.CreateAttribute("Capacity"); newAtt.Value = capacity.ToString(); xmldisk.Attributes.Append(newAtt); newAtt = xmldoc.CreateAttribute("Freespace"); newAtt.Value = freespace.ToString(); xmldisk.Attributes.Append(newAtt); xmlnode3.AppendChild(xmldisk); } XmlNode xmlnode4 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlElement xmlguestState = xmldoc.CreateElement(null, "GuestState", null); xmlguestState.InnerText = ((VimyyApi.GuestInfo)(pc.val)).toolsStatus.ToString(); xmlnode4.AppendChild(xmlguestState); XmlNode xmlnode5 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlElement xmlguestFamily = xmldoc.CreateElement(null, "GuestFamily", null); xmlguestFamily.InnerText = ((VimyyApi.GuestInfo)(pc.val)).guestFamily; xmlnode5.AppendChild(xmlguestFamily); XmlNode xmlnode6 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlElement xmlhostname = xmldoc.CreateElement(null, "FQDN", null); xmlhostname.InnerText = ((VimyyApi.GuestInfo)(pc.val)).hostName; xmlnode6.AppendChild(xmlhostname); XmlNode xmlnode7 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlElement xmlIP = xmldoc.CreateElement(null, "IPaddress", null); xmlIP.InnerText = ((VimyyApi.GuestInfo)(pc.val)).ipAddress; xmlnode3.AppendChild(xmlIP); } } if ((pc.name.Equals("name"))) { string name = (pc.val.ToString()); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//VM[@moref='" + moref + "']"); XmlElement xmlvmname = xmldoc.CreateElement(null, "VMName", null); xmlvmname.InnerText = name; xmlnode3.AppendChild(xmlvmname); } } } } else { //("No Managed Entities retrieved!"); } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("Inventory.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); return(ObjectList); //return ObjectList; }
public object Collect(string url, string username, string password, string EntityType) { if (_service != null) { Disconnect(); } ArrayList ObjectList = new ArrayList(); ArrayList HostList = new ArrayList(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Inventory.xml"); _service = new VimService(); _service.Url = url; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; if ((_sic.sessionManager != null)) { _service.Login(_sic.sessionManager, username, password, null); } TraversalSpec rpToRp = new TraversalSpec(); rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.name = "rpToRp"; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; TraversalSpec rpToVm = new TraversalSpec(); rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.name = "rpToVm"; rpToVm.selectSet = new SelectionSpec[] { }; TraversalSpec crToRp = new TraversalSpec(); crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.name = "crToRp"; crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() }; crToRp.selectSet[1].name = "rpToVm"; TraversalSpec crToH = new TraversalSpec(); crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.name = "crToH"; crToH.selectSet = new SelectionSpec[] { }; TraversalSpec dcToHf = new TraversalSpec(); dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.name = "dcToHf"; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.name = "dcToVmf"; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; TraversalSpec HToVm = new TraversalSpec(); HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.name = "HToVm"; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders"; TraversalSpec visitFolders = new TraversalSpec(); visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.name = "visitFolders"; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, crToH, crToRp, rpToVm }; visitFolders.selectSet[0].name = "visitFolders"; TraversalSpec tSpec = default(TraversalSpec); tSpec = visitFolders; PropertySpec[] propSpecArray = null; propSpecArray = new PropertySpec[] { new PropertySpec() }; propSpecArray[0].type = EntityType; propSpecArray[0].all = true; propSpecArray[0].allSpecified = true; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propSpecArray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = _sic.rootFolder; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = new SelectionSpec[] { tSpec }; ObjectContent[] ocary = _service.RetrieveProperties(_propCol, new PropertyFilterSpec[] { spec }); string clusname = ""; string moref = ""; if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (Int32 oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; pcary = oc.propSet; string domain = mor.Value.ToString(); string shortdomain = domain.Substring(0, 8); if (shortdomain == "domain-c") { for (Int32 propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; moref = mor.Value; if ((pc.name.Equals("host"))) { try { for (Int32 hc = 0; hc >= 0;) { HostList.Add(((VimyyApi.ManagedObjectReference[])(pc.val))[hc].Value); hc++; } } catch { } } if ((pc.name.Equals("name"))) { clusname = pc.val.ToString(); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Cluster[@moref='" + moref + "']"); XmlElement xmlclusname = xmldoc.CreateElement(null, "ClusterName", null); xmlclusname.InnerText = clusname; xmlnode3.AppendChild(xmlclusname); XmlNode xmlnode4 = xmldoc.SelectSingleNode("//Cluster[@moref='" + moref + "']"); XmlElement xmlhostcount = xmldoc.CreateElement(null, "HostCount", null); xmlhostcount.InnerText = HostList.Count.ToString(); xmlnode4.AppendChild(xmlhostcount); /* * for (Int32 i = 0; i <= HostList.Count -1; ) * { * XmlElement xmlclushost = xmldoc.CreateElement(null, "Host", null); * newAtt = xmldoc.CreateAttribute("moref"); * newAtt.Value = (string)HostList[i]; * xmlclushost.Attributes.Append(newAtt); * xmlnode3.AppendChild(xmlclushost); * i++; * * } */ HostList.Clear(); } if ((pc.name.Equals("parent"))) { string parent = ((VimyyApi.ManagedObjectReference)(pc.val)).Value; } } } } } else { //("No Managed Entities retrieved!"); } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("Inventory.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); return(ObjectList); }
public void TestUploadFile() { // hack to ignore bad certificates ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate); var service = new VimService(); service.Url = "https://vsphere-eng/sdk/vimService"; service.CookieContainer = new CookieContainer(); ServiceContent _sic = null; ManagedObjectReference _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _sic = service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { service.Login(_sic.sessionManager, "ENGDOM\\pyramiswebbuilder", "Gilbert93", null); } Cookie cookie = service.CookieContainer.GetCookies( new Uri(service.Url))[0]; String cookieString = cookie.ToString(); DataStores datastore = DataStores.datastore4; System.IO.FileInfo fi = new System.IO.FileInfo(@"c:\temp.pdf"); //MyWebClient wc = new MyWebClient(); //wc.Credentials = new NetworkCredential("root", "Gilbert93"); // wc.UploadString("https://10.4.2.78/folder/test.txt?dcPath=ha-datacenter&dsName=" + datastore.ToString(), "PUT", "Testing"); //wc.UploadFile("https://10.4.2.78/folder/" + fi.Name + "?dcPath=ha-datacenter&dsName=" + datastore.ToString(), fi.FullName); // prepare the web page we will be asking for HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://vsphere-eng/folder/" + fi.Name + "?dcPath=DataCenter&dsName=" + datastore.ToString()); request.Headers.Add(HttpRequestHeader.Cookie, cookieString); request.PreAuthenticate = true; request.UserAgent = "Upload Test"; request.Method = "POST"; request.Credentials = new NetworkCredential("ENGDOM\\pyramiswebbuilder", "Gilbert93"); request.ContentType = "application/octet-stream"; request.Accept = "100-continue"; request.ContentLength = fi.Length; System.IO.Stream s = request.GetRequestStream(); using (System.IO.FileStream fileStream = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { // used on each read operation byte[] buffer = new byte[1024]; int len = 0; while ((len = fileStream.Read(buffer, 0, buffer.Length)) > 0) { s.Write(buffer, 0, len); } } s.Close(); // execute the request WebResponse response = request.GetResponse(); string result = String.Empty; using (System.IO.TextReader tr = new System.IO.StreamReader(response.GetResponseStream())) { result = tr.ReadToEnd(); } Console.WriteLine(result); //service.Logout(_svcRef); }
/// <summary> /// Connect method to connect to ESX Web Services. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="connectionParameterSets">List of credential sets to use for connecting to the /// remote database server.</param> /// <param name="tftpDispatcher">TFTP transfer request listener for dispatching TFTP transfer /// requests.</param> /// /// <returns>Operation results.</returns> public ConnectionScriptResults Connect( long taskId, IDictionary <string, string>[] connectionParameterSets, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Connection script ESXWebServicesConnectionScript.", taskIdString); ConnectionScriptResults result = null; if (null == connectionParameterSets) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Null credential set passed to ESXWebServicesConnectionScript", taskIdString); result = new ConnectionScriptResults(null, ResultCodes.RC_NULL_PARAMETER_SET, 0, -1); } else { try { ResultCodes resultCode = ResultCodes.RC_HOST_CONNECT_FAILED; Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Executing ESXWebServicesConnectionScript with {1} credential sets.", taskIdString, connectionParameterSets.Length.ToString()); // // Loop to process credential sets until a successful // connection is made. for (int i = 0; connectionParameterSets.Length > i; ++i) { Dictionary <string, object> connectionDic = new Dictionary <string, object>(); foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i]) { connectionDic.Add(kvp.Key, kvp.Value); } string userName = connectionParameterSets[i][@"userName"]; string password = connectionParameterSets[i][@"password"]; String protocol = null; String port = null; String hostIP = null; String url = null; protocol = connectionParameterSets[i][@"protocol"]; port = connectionParameterSets[i][@"port"]; hostIP = connectionParameterSets[i][@"address"] as string; if (hostIP != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: hostIP is \"{1}\".", taskIdString, hostIP); } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter - server address/name.", taskIdString); } url = protocol + @"://" + hostIP + @":" + port + @"/sdk"; Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Processing credential set {1}: user=\"{2}\" for esx web service url={3}.", taskIdString, i.ToString(), userName, url); Stopwatch sw = new Stopwatch(); try { // Manage certificates: System.Net.ServicePointManager.CertificatePolicy = new CertPolicy(); vim_svc_ref = new ManagedObjectReference(); vim_svc_ref.type = "ServiceInstance"; // could be ServiceInstance for "HostAgent" and "VPX" for VPXd vim_svc_ref.Value = "ServiceInstance"; // connect to esx web service: // if vim_svc not null then disconnect if (vim_svc != null) { Disconnect(); } Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Instantiate VimService object. Elapsed time {1} ms.", taskIdString, executionTimer.ElapsedMilliseconds); vim_svc = new VimService(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Instantiated VimService object. Elapsed time {1} ms.", taskIdString, executionTimer.ElapsedMilliseconds); vim_svc.Url = url; vim_svc.CookieContainer = new System.Net.CookieContainer(); vim_svc_content = vim_svc.RetrieveServiceContent(vim_svc_ref); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: RetrievedServiceContent. Elapsed time {1} ms.", taskIdString, executionTimer.ElapsedMilliseconds); UserSession userSessionObj = null; if (vim_svc_content.sessionManager != null) { sw.Start(); userSessionObj = vim_svc.Login(vim_svc_content.sessionManager, userName, password, null); sw.Stop(); if (userSessionObj != null) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Connection to {1} with user name {2} succeeded. Elapsed time {3}.", taskIdString, url, userName, sw.Elapsed.ToString()); connectionDic.Add("VimServiceObj", vim_svc); connectionDic.Add("VimServiceContentObj", vim_svc_content); connectionDic.Add("userSessionObj", userSessionObj); connectionDic.Add("WebServiceUrl", url); result = new ConnectionScriptResults(connectionDic, ResultCodes.RC_SUCCESS, 0, i); break; } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Connection to {1} failed with user name {2}. Elapsed time {3}.\n", taskIdString, url, userName, sw.Elapsed.ToString() ); } } } catch (SoapException se) { ///Console.WriteLine("DEBUG Caught SoapException - " + se.ToString() + "\n Msg = " + se.Message.ToString() + "Code = " + se.Code.ToString()); Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught SoapException in ESXWebServicesConnectionScript. Elapsed time {1}.\n<Exception detail: [se: {2}]\n[Message: {3}]\n[Code: {4}]\n[Detail XML(OuterXml): {5}] Exception detail end>", taskIdString, executionTimer, se.ToString(), se.Message.ToString(), se.Code.ToString(), se.Detail.OuterXml.ToString()); if (se.Message.Contains("Login failed") || se.Message.Contains("incorrect user name or password")) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else if (se.Message.Contains("Unsupported namespace")) { resultCode = ResultCodes.RC_UNSUPPORTED_MESSAGE_TYPE; } else if (se.Message.Contains("Permission to perform this operation was denied")) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else if (se.Code.ToString().Contains("ServerFaultCode")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: SoapException (ServerFaultCode) in ESXWebServicesConnectionScript. Elapsed time {1}.\n <More detail: [InnerText: {2}]\n[InnerXml: {3}] end>", taskIdString, executionTimer, se.Detail.InnerText, se.Detail.InnerXml); resultCode = ResultCodes.RC_ESX_WEB_SERVICE_QUERY_FAILURE; } else { resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } catch (Exception ex) { Lib.LogException(taskIdString, sw, String.Format("Connect to {0} failed", url), ex); //break; } finally { if (vim_svc != null) { vim_svc.Dispose(); vim_svc = null; vim_svc_content = null; } } } // end of for loop // // Connect failed after all credentials attempted. if (null == result) { result = new ConnectionScriptResults(null, resultCode, 0, connectionParameterSets.Length); } } catch (Exception e) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in ESXWebServicesConnectionScript. Elapsed time {1}.\n Result code changed to RC_PROCESSING_EXECEPTION. <EXP {2} EXP>", taskIdString, executionTimer, e.ToString()); // // This is really an unanticipated fail safe. We're // going to report that *no* credentials were tried, which // actually may not be true... result = new ConnectionScriptResults(null, ResultCodes.RC_PROCESSING_EXCEPTION, 0, -1); } } Debug.Assert(null != result); Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Connection script ESXWebServicesConnectionScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), result.ResultCode.ToString()); return(result); }
public object Collect(string vcentername, string url, string username, string password) { if (_service != null) { Disconnect(); } //###################setup xml file################ XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); //add root element XmlElement xmlroot = xmldoc.CreateElement("", vcentername, ""); xmldoc.AppendChild(xmlroot); //################################################### ArrayList ObjectList = new ArrayList(); _service = new VimService(); _service.Url = url; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; if ((_sic.sessionManager != null)) { _service.Login(_sic.sessionManager, username, password, null); } TraversalSpec rpToRp = new TraversalSpec(); rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.name = "rpToRp"; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; TraversalSpec rpToVm = new TraversalSpec(); rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.name = "rpToVm"; rpToVm.selectSet = new SelectionSpec[] { }; TraversalSpec crToRp = new TraversalSpec(); crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.name = "crToRp"; crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() }; crToRp.selectSet[1].name = "rpToVm"; TraversalSpec crToH = new TraversalSpec(); crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.name = "crToH"; crToH.selectSet = new SelectionSpec[] { }; TraversalSpec dcToHf = new TraversalSpec(); dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.name = "dcToHf"; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.name = "dcToVmf"; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; TraversalSpec HToVm = new TraversalSpec(); HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.name = "HToVm"; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders"; TraversalSpec visitFolders = new TraversalSpec(); visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.name = "visitFolders"; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, crToH, crToRp, rpToVm }; visitFolders.selectSet[0].name = "visitFolders"; TraversalSpec tSpec = default(TraversalSpec); tSpec = visitFolders; PropertySpec[] propSpecArray = null; propSpecArray = new PropertySpec[] { new PropertySpec() }; propSpecArray[0].type = "Datacenter"; propSpecArray[0].all = true; propSpecArray[0].allSpecified = true; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propSpecArray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = _sic.rootFolder; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = new SelectionSpec[] { tSpec }; ObjectContent[] ocary = _service.RetrieveProperties(_propCol, new PropertyFilterSpec[] { spec }); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (Int32 oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; moref = mor.Value.ToString(); pcary = oc.propSet; //string vmname =""; for (Int32 propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("hostFolder"))) { XmlElement xmldcmoref = xmldoc.CreateElement("", "Datacenter", ""); XmlAttribute newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = moref; xmldcmoref.Attributes.Append(newAtt); xmldoc.ChildNodes.Item(1).AppendChild(xmldcmoref); folder = ((VimyyApi.ManagedObjectReference)(pc.val)).Value; XmlElement xmlfolder = xmldoc.CreateElement(null, "Folder", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Datacenter[@moref='" + moref + "']"); newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = folder; xmlfolder.Attributes.Append(newAtt); xmlnode3.AppendChild(xmlfolder); } if ((pc.name.Equals("name"))) { name = (pc.val.ToString()); XmlElement xmldcname = xmldoc.CreateElement(null, "DCname", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Datacenter[@moref='" + moref + "']"); XmlAttribute newAtt = xmldoc.CreateAttribute("DCname"); newAtt.Value = name; xmldcname.Attributes.Append(newAtt); xmlnode3.AppendChild(xmldcname); } } } } else { //("No Managed Entities retrieved!"); } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("Inventory.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); return(ObjectList); }
private void removePluginWorker_DoWork(object sender, DoWorkEventArgs e) { try { string hostName = vhostname; //#########################setup plugin in a xml file################### XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); //add root element XmlElement xmlroot = xmldoc.CreateElement("root"); xmldoc.AppendChild(xmlroot); //###################################################################### _service2 = new VimService(); _service2.Url = vurl; _svcRef2 = new ManagedObjectReference(); _svcRef2.type = "ServiceInstance"; _svcRef2.Value = "ServiceInstance"; _service2.CookieContainer = new System.Net.CookieContainer(); CreateServiceRef2("ServiceInstance"); _sic2 = _service2.RetrieveServiceContent(_svcRef2); _propCol2 = _sic2.propertyCollector; _rootFolder2 = _sic2.rootFolder; String userName = vusername; String password = vpassword; if (_sic2.sessionManager != null) { _service2.Login(_sic2.sessionManager, userName, password, null); ManagedObjectReference extMOREF = _sic2.extensionManager; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = new PropertySpec[] { new PropertySpec() }; spec.propSet[0].all = false; spec.propSet[0].allSpecified = spec.propSet[0].all; spec.propSet[0].type = extMOREF.type; spec.propSet[0].pathSet = new string[] { "extensionList" }; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = extMOREF; spec.objectSet[0].skip = false; ObjectContent[] ocary = _service2.RetrieveProperties(_sic2.propertyCollector, new PropertyFilterSpec[] { spec }); ArrayList ObjectList = new ArrayList(); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (int oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; pcary = oc.propSet; for (int propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("extensionList"))) { try { for (int pci = 0; ; pci++) { ObjectList.Add(((VimApi.Extension[])(pc.val))[pci].key); } } catch { // } string leftcharObjL; for (int olc = 0; olc < ObjectList.Count; olc++) { leftcharObjL = ObjectList[olc].ToString(); if (leftcharObjL.StartsWith("com.virtualizeplanet.")) { leftcharObjL = leftcharObjL.Remove(0, 21); //comboBox2.Items.Add(leftcharObjL); //comboBox2.SelectedIndex = 0; XmlElement xmldcmoref = xmldoc.CreateElement("", "PluginList", ""); XmlAttribute newAtt = xmldoc.CreateAttribute("Position"); newAtt.Value = leftcharObjL; xmldcmoref.Attributes.Append(newAtt); xmldoc.ChildNodes.Item(1).AppendChild(xmldcmoref); } } } } } } } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("plugin.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); removePluginWorker.CancelAsync(); } catch { MessageBox.Show("Something maybe wrong with your settings"); } }
private void registerPluginWorker_DoWork(object sender, DoWorkEventArgs e) { try { _service = new VimService(); _service.Url = vurl; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); CreateServiceRef("ServiceInstance"); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; string userName = vusername; string password = vpassword; string companyStr = textBox4.Text; string descStr = textBox3.Text; string keyStr = "com.virtualizeplanet." + textBox2.Text; string ext_url = pluginUrl; string adminEmail = "*****@*****.**"; string versionStr = "4.0"; Description description = new Description(); description.label = textBox3.Text; description.summary = descStr; ExtensionServerInfo esi = new ExtensionServerInfo(); esi.url = ext_url; esi.description = description; esi.company = companyStr; esi.type = "com.vmware.vim.viClientScripts"; //do not change; esi.adminEmail = new String[] { adminEmail }; ExtensionClientInfo eci = new ExtensionClientInfo(); eci.version = versionStr; eci.description = description; eci.company = companyStr; eci.type = "com.vmware.vim.viClientScripts"; eci.url = ext_url; Extension ext = new Extension(); ext.description = description; ext.key = keyStr; ext.version = versionStr; ext.subjectName = "blank"; ext.server = new ExtensionServerInfo[] { esi }; ext.client = new ExtensionClientInfo[] { eci }; ext.lastHeartbeatTime = DateTime.Now; if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, userName, password, null); ManagedObjectReference extMgrMof = _sic.extensionManager; _service.RegisterExtension(extMgrMof, ext); } MessageBox.Show("Finished", "Completed"); } catch { MessageBox.Show("Review your settings or plugin already exists"); } }