/// <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); } }
/// <summary> /// Disconnects the Connection /// </summary> public void Disconnect() { if (_service != null) { if (BeforeDisconnect != null) { BeforeDisconnect(this, new ConnectionEventArgs()); } if (_sic != null) { _service.Logout(_sic.sessionManager); } _service.Dispose(); _service = null; _sic = null; _state = ConnectionState.Disconnected; if (AfterDisconnect != null) { AfterDisconnect(this, new ConnectionEventArgs()); } } }
public void Disconnect() { if (_service != null) { _service.Logout(_sic.sessionManager); _service.Dispose(); _service = null; _sic = null; } }
private void Disconnect() { // Disconnect from the service: if (vim_svc != null) { vim_svc.Logout(vim_svc_content.sessionManager); vim_svc.Dispose(); vim_svc = null; vim_svc_content = null; } }
public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script vCenterESXHostInfo.", m_taskId); StringBuilder ESX_Info = new StringBuilder(); Boolean success = false; try { if (resultCode == ResultCodes.RC_SUCCESS) { UserSession userSessionObj = null; if (m_connection.ContainsKey(@"VimServiceObj")) { vim_svc = (VimService)m_connection[@"VimServiceObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter VimServiceObj.", m_taskId); } if (m_connection.ContainsKey(@"VimServiceContentObj")) { vim_svc_content = (ServiceContent)m_connection[@"VimServiceContentObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter VimServiceContentObj.", m_taskId); } if (m_connection.ContainsKey(@"userSessionObj")) { userSessionObj = (UserSession)m_connection[@"userSessionObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter userSessionObj.", m_taskId); } String url = null; if (m_connection.ContainsKey(@"WebServiceUrl")) { url = (String)m_connection[@"WebServiceUrl"]; } if (userSessionObj != null) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Going to get ESX Info. Elapsed time {1} ms.", m_taskId, m_executionTimer.ElapsedMilliseconds); //collect ESX Host's basic info: //StringBuilder HostBasicInfo = getEsxHostBasicInfo(); //ESX_Info.Append(HostBasicInfo); ESX_Info.Append(getEsxHostBasicInfo()); //collect ESX host info: StringBuilder ESX_MoreInfo = getEsxHostInfo(); ESX_Info.Append(ESX_MoreInfo); /**** TODO - Need more research how to capture ESX license info using vCenter ****/ /* * //collect ESX license information: * StringBuilder ESX_License = getEsxLicenseInfo(); * ESX_Info.Append(ESX_License); * * //collect ESX datastore information: * StringBuilder ESX_Datastore = getEsxDatastoreInfo(); * ESX_Info.Append(ESX_Datastore); */ //Console.WriteLine("ESX INFO: {0}", ESX_Info); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Collected ESX Info. Elapsed time {1} ms.", m_taskId, m_executionTimer.ElapsedMilliseconds); success = true; this.BuildDataRow(@"HostAndGuestData", ESX_Info); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: could not connect to esx web services at url {1}.", m_taskId, url); resultCode = ResultCodes.RC_LOGIN_FAILED; //@TODO: change to some other value } // Disconnect from the service: if (vim_svc != null) { Disconnect(); } } } catch (SoapException se) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught SoapException in VMwareESXHostDataScript. Elapsed time {1}.\n <Exception detail: [se: {2}]\n[Message: {3}]\n[Code: {4}]\n[Detail XML(OuterXml): {5}] Exception detail end>", m_taskId, m_executionTimer.Elapsed.ToString(), se.ToString(), se.Message.ToString(), se.Code.ToString(), se.Detail.OuterXml.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; if (se.Message.Contains("Login failed")) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else if (se.Message.Contains("Unsupported namespace")) { resultCode = ResultCodes.RC_UNSUPPORTED_MESSAGE_TYPE; } else if (se.Code.ToString().Contains("ServerFaultCode")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: SoapException (ServerFaultCode) in VMwareESXHostDataScript. Elapsed time {1}.\n <More detail: [InnerText: {2}]\n[InnerXml: {3}] end>", m_taskId, m_executionTimer.Elapsed.ToString(), se.Detail.InnerText, se.Detail.InnerXml); if (se.Detail.InnerXml.ToString().Contains("InvalidPropertyFault") || se.Detail.OuterXml.ToString().Contains("InvalidPropertyFault")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught SoapException in VMwareESXHostDataScript due to an InvalidProperty.", m_taskId); } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught exception in VMwareESXHostDataScript. Elapsed time {1}.\n{2}Result code changed to RC_PROCESSING_EXECEPTION. <EXP => {3} <EXP =>", m_taskId, m_executionTimer.Elapsed.ToString(), 1, ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught exception in - VMwareESXHostDataScript. Elapsed time {1}.\n{2} <EXP => {3} <EXP =>", m_taskId, m_executionTimer.Elapsed.ToString(), 1, ex.ToString()); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } } finally { if (vim_svc != null) { vim_svc.Dispose(); vim_svc = null; vim_svc_content = null; } } //if all data not collected then send back whatever has been collected. if (!success) { this.BuildDataRow(@"HostAndGuestData", ESX_Info); } return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
private List <VMwareDisk> Disks() { List <VMwareDisk> disks = new List <VMwareDisk>(); VMWare oVMWare = new VMWare(0, dsn); string name = "WSCLV223A"; DataSet dsGuest = oVMWare.GetGuest(name); if (dsGuest.Tables[0].Rows.Count > 0) { DataRow drGuest = dsGuest.Tables[0].Rows[0]; int intDatastore = Int32.Parse(drGuest["datastoreid"].ToString()); int intHost = Int32.Parse(drGuest["hostid"].ToString()); int intCluster = Int32.Parse(oVMWare.GetHost(intHost, "clusterid")); int intFolder = Int32.Parse(oVMWare.GetCluster(intCluster, "folderid")); int intDataCenter = Int32.Parse(oVMWare.GetFolder(intFolder, "datacenterid")); string strDataCenter = oVMWare.GetDatacenter(intDataCenter, "name"); int intVirtualCenter = Int32.Parse(oVMWare.GetDatacenter(intDataCenter, "virtualcenterid")); string strVirtualCenter = oVMWare.GetVirtualCenter(intVirtualCenter, "name"); string strVirtualCenterURL = oVMWare.GetVirtualCenter(intVirtualCenter, "url"); int intVirtualCenterEnv = Int32.Parse(oVMWare.GetVirtualCenter(intVirtualCenter, "environment")); string strConnect = oVMWare.ConnectDEBUG(strVirtualCenterURL, intVirtualCenterEnv, strDataCenter); VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); try { ManagedObjectReference oVM = oVMWare.GetVM(name); if (oVM != null) { VirtualMachineConfigInfo vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oVM, "config"); VirtualDevice[] devices = vminfo.hardware.device; List <VMwareController> controllers = new List <VMwareController>(); foreach (VirtualDevice device in devices) { // Try to cast to Controller try { VirtualController controller = (VirtualController)device; VMwareController Controller = new VMwareController(); Controller.busNumber = controller.busNumber; Controller.key = controller.key; controllers.Add(Controller); } catch { } // Try to cast to Disk try { VirtualDisk disk = (VirtualDisk)device; bool boolShared = false; string strLunID = null; try { VirtualDiskFlatVer2BackingInfo backingNonShared = (VirtualDiskFlatVer2BackingInfo)disk.backing; boolShared = false; strLunID = ""; } catch { // Not flat disk, so don't worry about it } if (strLunID != null) { VMwareDisk Disk = new VMwareDisk(); Disk.controllerKey = disk.controllerKey; Disk.label = disk.deviceInfo.label; Disk.capacityInKB = disk.capacityInKB; Disk.unitNumber = disk.unitNumber; Disk.lunUuid = strLunID; Disk.Shared = boolShared; disks.Add(Disk); } } catch { } } Storage oStorage = new Storage(0, dsn); // Match up disks with controllers for bus numbers foreach (VMwareDisk disk in disks) { disk.capacityInKB = ((disk.capacityInKB / 1024) / 1024); // convert KB to GB foreach (VMwareController controller in controllers) { if (disk.controllerKey == controller.key) { disk.busNumber = controller.busNumber; disk.Name = disk.capacityInKB.ToString() + " GB - SCSI(" + disk.busNumber.ToString() + ":" + disk.unitNumber.ToString() + ") " + disk.label; oStorage.AddLunDisk(0, disk.busNumber, disk.unitNumber, disk.lunUuid); break; } } } } } catch { } finally { if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } } return(disks); }
protected void Page_Load(object sender, EventArgs e) { bool boolError = true; if (Request.QueryString["name"] != null && Request.QueryString["name"] != "" & Request.QueryString["token"] != null && Request.QueryString["token"] != "") { Tokens oToken = new Tokens(0, dsn); string strName = Request.QueryString["name"]; string strToken = Request.QueryString["token"]; if (oToken.Get(strName, strToken) == true) { // Delete Token oToken.Update(strName, strToken); // Render Preview VMWare oVMWare = new VMWare(0, dsn); //strName = "WDBIX103A"; string strConnect = oVMWare.Connect(strName); VimService _service = oVMWare.GetService(); if (strConnect == "") { ManagedObjectReference vmRef = oVMWare.GetVM(strName); if (vmRef.Value != null) { try { VirtualMachineMksTicket oTicket = _service.AcquireMksTicket(vmRef); string strVMHost = oTicket.host; string strVMPort = oTicket.port.ToString(); string strVMPath = oTicket.cfgFile; string strVMTicket = oTicket.ticket; Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "start_count", "<script type=\"text/javascript\">window.onload = new Function(\"connect('" + strVMHost + "','" + strVMPath + "','" + strVMTicket + "','" + strVMPort + "');\");<" + "/" + "script>"); boolError = false; } catch { } } } if (_service != null) { ServiceContent _sic = oVMWare.GetSic(); _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } } if (boolError == true) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "start_count", "<script type=\"text/javascript\">window.onload = new Function(\"window.parent.VMWareNoPreview();\");<" + "/" + "script>"); } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _serviceContent = null; _vimService.Dispose(); }
/// <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); }
protected void Page_Load(object sender, EventArgs e) { AuthenticateUser(); if (Request.Cookies["profileid"] != null && Request.Cookies["profileid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); } if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } oDataPoint = new DataPoint(intProfile, dsn); oUser = new Users(intProfile, dsn); oServer = new Servers(intProfile, dsn); oAsset = new Asset(intProfile, dsnAsset); oForecast = new Forecast(intProfile, dsn); oPlatform = new Platforms(intProfile, dsn); oType = new Types(intProfile, dsn); oModel = new Models(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oIPAddresses = new IPAddresses(intProfile, dsnIP, dsn); oFunction = new Functions(intProfile, dsn, intEnvironment); oOperatingSystem = new OperatingSystems(intProfile, dsn); oServicePack = new ServicePacks(intProfile, dsn); oClass = new Classes(intProfile, dsn); oEnvironment = new Environments(intProfile, dsn); if (oUser.IsAdmin(intProfile) == true || (oDataPoint.GetPagePermission(intApplication, "ASSET") == true || intDataPointAvailableAsset == 1)) { panAllow.Visible = true; if (Request.QueryString["save"] != null) { panSave.Visible = true; } if (Request.QueryString["error"] != null) { panError.Visible = true; // -100: More than one device name // -10: No device names // -5: Improper Name Format // -1: ServerID = 0 if (Request.QueryString["error"] == "-100") { lblError.Text = "More than one name"; } else if (Request.QueryString["error"] == "-10") { lblError.Text = "User Cancelled Prompt"; } else if (Request.QueryString["error"] == "-5") { lblError.Text = "Name is in Incorrect Format"; } else if (Request.QueryString["error"] == "-1") { lblError.Text = "DeviceID = 0"; } else { lblError.Text = "Generic Error"; } } Int32.TryParse(oFunction.decryptQueryString(Request.QueryString["id"]), out intID); if (Request.QueryString["close"] != null) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "close", "<script type=\"text/javascript\">window.close();<" + "/" + "script>"); } else if (intID > 0) { DataSet ds = oDataPoint.GetAsset(intID); if (ds.Tables[0].Rows.Count == 1) { // Load General Information intAsset = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); lblAssetID.Text = "#" + intAsset.ToString(); string strSerial = ds.Tables[0].Rows[0]["serial"].ToString(); string strAsset = ds.Tables[0].Rows[0]["asset"].ToString(); string strHeader = (strSerial.Length > 15 ? strSerial.Substring(0, 15) + "..." : strSerial); lblHeader.Text = """ + strHeader.ToUpper() + """; Master.Page.Title = "DataPoint | VMware (" + strHeader + ")"; lblHeaderSub.Text = "Provides all the information about a VMware guest..."; int intMenuTab = 0; if (Request.QueryString["menu_tab"] != null && Request.QueryString["menu_tab"] != "") { intMenuTab = Int32.Parse(Request.QueryString["menu_tab"]); } Tab oTab = new Tab(hdnTab.ClientID, intMenuTab, "divMenu1", true, false); oTab.AddTab("Asset Information", ""); oTab.AddTab("Host Information", ""); oTab.AddTab("Resource Dependencies", ""); oTab.AddTab("Provisioning Information", ""); //oTab.AddTab("Network Adapter Configuration", ""); strMenuTab1 = oTab.GetTabs(); if (!IsPostBack) { //DataSet dsAssets = oServer.GetAsset(intAsset); //foreach (DataRow drAsset in dsAssets.Tables[0].Rows) //{ // if (drAsset["latest"].ToString() == "1") // { // intAsset = Int32.Parse(drAsset["assetid"].ToString()); // intAssetClass = Int32.Parse(drAsset["classid"].ToString()); // intAssetEnv = Int32.Parse(drAsset["environmentid"].ToString()); // break; // } //} // Asset Information oDataPoint.LoadTextBox(txtPlatformSerial, intProfile, null, "", lblPlatformSerial, fldPlatformSerial, "VMWARE_SERIAL", strSerial, "", false, true); oDataPoint.LoadTextBox(txtPlatformAsset, intProfile, null, "", lblPlatformAsset, fldPlatformAsset, "VMWARE_ASSET", strAsset, "", false, true); int intAssetAttribute = 0; Int32.TryParse(oAsset.Get(intAsset, "asset_attribute"), out intAssetAttribute); oDataPoint.LoadDropDown(ddlAssetAttribute, intProfile, null, "", lblAssetAttribute, fldAssetAttribute, "ASSET_ATTRIBUTE", "Name", "AttributeId", oAsset.getAssetAttributes(null, "", 1), intAssetAttribute, true, false, false); oDataPoint.LoadTextBox(txtAssetAttributeComment, intProfile, null, "", lblAssetAttributeComment, fldAssetAttributeComment, "ASSET_ATTRIBUTE_COMMENT", oAsset.getAssetAttributesComments(intAsset), "", false, true); ddlAssetAttribute.Attributes.Add("onclick", "return SetControlsForAssetAttributes()"); ddlPlatform.Attributes.Add("onchange", "PopulatePlatformTypes('" + ddlPlatform.ClientID + "','" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformType.Attributes.Add("onchange", "PopulatePlatformModels('" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModel.Attributes.Add("onchange", "PopulatePlatformModelProperties('" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModelProperty.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformModelProperty.ClientID + "','" + hdnModel.ClientID + "');"); int intModel = 0; Int32.TryParse(oAsset.Get(intAsset, "modelid"), out intModel); hdnModel.Value = intModel.ToString(); int intModelParent = 0; Int32.TryParse(oModelsProperties.Get(intModel, "modelid"), out intModelParent); int intType = oModel.GetType(intModelParent); int intPlatform = oType.GetPlatform(intType); oDataPoint.LoadDropDown(ddlPlatform, intProfile, null, "", lblPlatform, fldPlatform, "VMWARE_PLATFORM", "name", "platformid", oPlatform.Gets(1), intPlatform, false, false, true); oDataPoint.LoadDropDown(ddlPlatformType, intProfile, null, "", lblPlatformType, fldPlatformType, "VMWARE_TYPE", "name", "id", oType.Gets(intPlatform, 1), intType, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModel, intProfile, null, "", lblPlatformModel, fldPlatformModel, "VMWARE_MODEL", "name", "id", oModel.Gets(intType, 1), intModelParent, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModelProperty, intProfile, null, "", lblPlatformModelProperty, fldPlatformModelProperty, "VMWARE_MODEL_PROP", "name", "id", oModelsProperties.GetModels(0, intModelParent, 1), intModel, false, false, true); // Get Asset DataSet dsAsset = oAsset.GetGuest(intAsset); if (dsAsset.Tables[0].Rows.Count > 0) { oDataPoint.LoadTextBoxDeviceName(txtName, btnName, null, true, hdnPNC, intProfile, btnNameLookup, "/datapoint/asset/datapoint_asset_search.aspx?t=name&q=" + oFunction.encryptQueryString(dsAsset.Tables[0].Rows[0]["name"].ToString()), lblName, fldName, "VMWARE_NAME", dsAsset.Tables[0].Rows[0]["name"].ToString(), "", false, false); if (txtName.Text != "") { lblHeader.Text += " [" + txtName.Text + "]"; } lblStatus.Text = dsAsset.Tables[0].Rows[0]["statusname"].ToString(); int intClass = Int32.Parse(dsAsset.Tables[0].Rows[0]["classid"].ToString()); int intEnv = Int32.Parse(dsAsset.Tables[0].Rows[0]["environmentid"].ToString()); hdnEnvironment.Value = intEnv.ToString(); oDataPoint.LoadDropDown(ddlPlatformClass, intProfile, null, "", lblPlatformClass, fldPlatformClass, "VMWARE_CLASS", "name", "id", oClass.Gets(1), intClass, false, false, true); oDataPoint.LoadDropDown(ddlPlatformEnvironment, intProfile, null, "", lblPlatformEnvironment, fldPlatformEnvironment, "VMWARE_ENVIRONMENT", "name", "id", oClass.GetEnvironment(intClass, 0), intEnv, false, false, true); ddlStatus.SelectedValue = dsAsset.Tables[0].Rows[0]["status"].ToString(); ddlStatus.Enabled = (intAssetAttribute == (int)AssetAttribute.Ok); panStatus.Visible = (ddlStatus.Enabled == false); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } // Get Original Detail VMWare oVMWare = new VMWare(intProfile, dsn); DataSet dsGuest = oVMWare.GetGuest(dsAsset.Tables[0].Rows[0]["name"].ToString()); if (dsGuest.Tables[0].Rows.Count > 0) { panVMWare.Visible = true; DataRow drGuest = dsGuest.Tables[0].Rows[0]; int intDatastore = Int32.Parse(drGuest["datastoreid"].ToString()); lblBuildDataStore.Text = oVMWare.GetDatastore(intDatastore, "name"); int intHost = Int32.Parse(drGuest["hostid"].ToString()); lblBuildHost.Text = oVMWare.GetHost(intHost, "name"); int intCluster = Int32.Parse(oVMWare.GetHost(intHost, "clusterid")); lblBuildCluster.Text = oVMWare.GetCluster(intCluster, "name"); int intFolder = Int32.Parse(oVMWare.GetCluster(intCluster, "folderid")); lblBuildFolder.Text = oVMWare.GetFolder(intFolder, "name"); int intDataCenter = Int32.Parse(oVMWare.GetFolder(intFolder, "datacenterid")); lblBuildDataCenter.Text = oVMWare.GetDatacenter(intDataCenter, "name"); int intVirtualCenter = Int32.Parse(oVMWare.GetDatacenter(intDataCenter, "virtualcenterid")); lblBuildVirtualCenter.Text = oVMWare.GetVirtualCenter(intVirtualCenter, "name"); // Get Host if (Request.Cookies["host"] != null && Request.Cookies["host"].Value != "") { string strHost = ""; string strFind = txtName.Text; //strFind = "ohcleapp103d"; DateTime datStart = DateTime.Parse(Request.Cookies["host"].Value); Response.Cookies["host"].Value = ""; //VMWare oVMWare = new VMWare(intProfile, dsn); DataSet dsVirtualCenter = oVMWare.GetVirtualCenters(1); foreach (DataRow drVirtualCenter in dsVirtualCenter.Tables[0].Rows) { intVirtualCenter = Int32.Parse(drVirtualCenter["id"].ToString()); string strVirtualCenter = drVirtualCenter["name"].ToString(); string strVirtualCenterURL = drVirtualCenter["url"].ToString(); int intVirtualCenterEnv = Int32.Parse(drVirtualCenter["environment"].ToString()); DataSet dsDataCenter = oVMWare.GetDatacenters(intVirtualCenter, 1); foreach (DataRow drDataCenter in dsDataCenter.Tables[0].Rows) { intDataCenter = Int32.Parse(drDataCenter["id"].ToString()); string strDataCenter = drDataCenter["name"].ToString(); string strConnect = oVMWare.ConnectDEBUG(strVirtualCenterURL, intVirtualCenterEnv, strDataCenter); VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); try { ManagedObjectReference oVM = oVMWare.GetVM(strFind); GuestInfo ginfo = (GuestInfo)oVMWare.getObjectProperty(oVM, "guest"); lblGuestName.Text = ginfo.guestFullName; lblGuestState.Text = ginfo.guestState; GuestNicInfo[] nInfo = ginfo.net; foreach (GuestNicInfo nic in nInfo) { string[] strIPAddresses = nic.ipAddress; foreach (string strIPAddress in strIPAddresses) { if (lblIPAddress.Text != "") { lblIPAddress.Text += ", "; } lblIPAddress.Text += strIPAddress; } if (lblMACAddress.Text != "") { lblMACAddress.Text += ", "; } lblMACAddress.Text += nic.macAddress; if (lblNetwork.Text != "") { lblNetwork.Text += ", "; } lblNetwork.Text += nic.network; } VirtualMachineConfigInfo vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oVM, "config"); VirtualMachineSummary oVMSummary = (VirtualMachineSummary)oVMWare.getObjectProperty(oVM, "summary"); VirtualMachineConfigSummary oVMConfig = oVMSummary.config; lblRAM.Text = oVMConfig.memorySizeMB.ToString(); lblCPUs.Text = oVMConfig.numCpu.ToString(); lblPath.Text = oVMConfig.vmPathName; VirtualMachineRuntimeInfo oVMRuntime = oVMSummary.runtime; ManagedObjectReference oVMHost = oVMRuntime.host; strHost = (string)oVMWare.getObjectProperty(oVMHost, "name"); if (strHost.IndexOf(".") > -1) { strHost = strHost.Substring(0, strHost.IndexOf(".")); } lblVirtualCenter.Text = strVirtualCenter; lblDataCenter.Text = strDataCenter; break; } catch { } finally { if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } } } if (strHost != "") { oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(strHost), lblHostName, fldHostName, "VMWARE_HOST", strHost, "", false, false); } else { panHostNo.Visible = true; } TimeSpan oSpan = DateTime.Now.Subtract(datStart); btnHostQuery.Enabled = false; btnHostQuery.Text = "Query Time: " + oSpan.TotalSeconds.ToString("0") + " seconds..."; } else { txtHostName.Visible = false; lblHostName.Text = "---"; lblDataCenter.Text = "---"; lblVirtualCenter.Text = "---"; } oDataPoint.LoadPanel(panHostQuery, intProfile, fldHostQuery, "VMWARE_HOST_QUERY"); } else { Solaris oSolaris = new Solaris(intProfile, dsn); DataSet dsServers = oServer.GetAssetsAsset(intAsset); foreach (DataRow drServer in dsServers.Tables[0].Rows) { DataSet dsSVE = oSolaris.GetSVEGuest(Int32.Parse(drServer["serverid"].ToString())); if (dsSVE.Tables[0].Rows.Count > 0) { panSVE.Visible = true; int intCluster = Int32.Parse(dsSVE.Tables[0].Rows[0]["clusterid"].ToString()); lblSVECluster.Text = oSolaris.GetSVECluster(intCluster, "name"); } } } // Resource Dependencies AssetOrder oAssetOrder = new AssetOrder(0, dsn, dsnAsset, intEnvironment); Services oService = new Services(0, dsn); ServiceRequests oServiceRequest = new ServiceRequests(0, dsn); rptServiceRequests.DataSource = oAssetOrder.GetByAsset(intAsset, false); rptServiceRequests.DataBind(); trServiceRequests.Visible = (rptServiceRequests.Items.Count == 0); foreach (RepeaterItem ri in rptServiceRequests.Items) { Label lblServiceID = (Label)ri.FindControl("lblServiceID"); int intService = Int32.Parse(lblServiceID.Text); Label lblDetails = (Label)ri.FindControl("lblDetails"); Label lblProgress = (Label)ri.FindControl("lblProgress"); if (lblProgress.Text == "") { lblProgress.Text = "<i>Unavailable</i>"; } else { int intResource = Int32.Parse(lblProgress.Text); double dblAllocated = 0.00; double dblUsed = 0.00; int intStatus = 0; bool boolAssigned = false; DataSet dsResource = oDataPoint.GetServiceRequestResource(intResource); if (dsResource.Tables[0].Rows.Count > 0) { Int32.TryParse(dsResource.Tables[0].Rows[0]["status"].ToString(), out intStatus); } foreach (DataRow drResource in dsResource.Tables[1].Rows) { boolAssigned = true; dblAllocated += double.Parse(drResource["allocated"].ToString()); dblUsed += double.Parse(drResource["used"].ToString()); intStatus = Int32.Parse(drResource["status"].ToString()); } if (intStatus == (int)ResourceRequestStatus.Closed) { lblProgress.Text = oServiceRequest.GetStatusBar(100.00, "100", "12", true); } else if (intStatus == (int)ResourceRequestStatus.Cancelled) { lblProgress.Text = "Cancelled"; } else if (boolAssigned == false) { string strManager = ""; DataSet dsManager = oService.GetUser(intService, 1); // Managers foreach (DataRow drManager in dsManager.Tables[0].Rows) { if (strManager != "") { strManager += "\\n"; } int intManager = Int32.Parse(drManager["userid"].ToString()); strManager += " - " + oUser.GetFullName(intManager) + " [" + oUser.GetName(intManager) + "]"; } lblProgress.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"alert('This request is pending assignment by the following...\\n\\n" + strManager + "');\">Pending Assignment</a>"; } else if (dblAllocated > 0.00) { lblProgress.Text = oServiceRequest.GetStatusBar((dblUsed / dblAllocated) * 100.00, "100", "12", true); } else { lblProgress.Text = "<i>N / A</i>"; } lblDetails.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('/datapoint/service/resource.aspx?id=" + oFunction.encryptQueryString(intResource.ToString()) + "', '800', '600');\">" + lblDetails.Text + "</a>"; } } // Provioning History rptHistory.DataSource = oAsset.GetProvisioningHistory(oDataPoint.AssetHistorySelect(intAsset)); rptHistory.DataBind(); lblHistory.Visible = (rptHistory.Items.Count == 0); oDataPoint.LoadPanel(panProvisioning, intProfile, fldProvisioning, "VMWARE_STATUS"); } } else { if (Request.QueryString["t"] != null && Request.QueryString["q"] != null) { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&r=0"); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } } } else if (Request.QueryString["q"] != null && Request.QueryString["q"] != "") { string strQuery = oFunction.decryptQueryString(Request.QueryString["q"]); DataSet ds = oDataPoint.GetAssetName(strQuery, intID, 0, "", "", 0); if (ds.Tables[0].Rows.Count == 1) { intID = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); Response.Redirect(Request.Path + "?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&id=" + oFunction.encryptQueryString(intID.ToString())); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?multiple=true&t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"]); } } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } btnClose.Attributes.Add("onclick", "window.close();return false;"); btnPrint.Attributes.Add("onclick", "window.print();return false;"); btnName.Attributes.Add("onclick", "return OpenWindow('DEVICE_NAME','?assetid=" + intAsset.ToString() + "');"); btnSave.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); btnSaveClose.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); ddlPlatformClass.Attributes.Add("onchange", "PopulateEnvironments('" + ddlPlatformClass.ClientID + "','" + ddlPlatformEnvironment.ClientID + "',0);"); ddlPlatformEnvironment.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformEnvironment.ClientID + "','" + hdnEnvironment.ClientID + "');"); btnHostQuery.Attributes.Add("onclick", "ProcessButton(this,'Querying... please be patient...','225') && ProcessControlButton();"); } else { panDenied.Visible = true; } }
protected void btnGo_Click(Object Sender, EventArgs e) { boolVMFound = false; Response.Write(DateTime.Now.ToString() + "<br/>"); Variables oVariable = new Variables(999); System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); ClearViewWebServices oWS = new ClearViewWebServices(); oWS.Timeout = Int32.Parse(ConfigurationManager.AppSettings["WS_TIMEOUT"]); oWS.Credentials = oCredentials; //oWS.Url = oVariable.WebServiceURL(); oWS.Url = "http://localhost:55030/ClearViewWebServices.asmx"; string path = oWS.GetVMwarePath(txtVM.Text, "http://localhost:53744/", "OpHAa0tdJBAdeJALK65pMptAyK2SFcismq7QZNB9rMd4Fuhp6K8Zqx8z5gdA8KIGsi1YLTV7E57alz5cDMW5escYrHVTKbaReGLyDtNmYauuA8oFka6vXNCafcGe8cwD5q5OYHJk8Kgd7RyttpIJeO4BeLrAWJoWN1zkcJRNAWwnGxcyPnUSDXxqwEJmqjyzvuzfsmqTH5jssQ4QI3UJYFs0DiYHaEyrz71l86fC7blINf8PK2OwxYKZcIMjxSTcI13uZTSLYsMXuUmykj7h0b3Lybjzu5eori9WmN00kdHflWFrvo9pUMmH7s7XKsq3oyFlUAlGth6XDYzKG1dg5ZDP6CZ4Qcq2WN1XquH5dC6NPzdj2wrSok7x30prKrZq0eaZ6LtluhdD309GzPbuVINMQC4AfpuVMPXLxnnrcfxghEFd0S25pFFsAxjDR3gfXr0ndxilCTrPjGFm70JwwzGgkElaeTKj8ttZNsaCKQCFoZi337G0"); while (path.Contains("\"")) { path = path.Replace("\"", ""); } string[] paths = path.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (paths.Length >= 3) { string strConnect = oVMware.ConnectDEBUG("https://" + paths[0] + ".pncbank.com/sdk", 999, ""); if (strConnect == "") { _service = oVMware.GetService(); _sic = oVMware.GetSic(); //ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); //ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); //ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); //ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); ManagedObjectReference oComputer = GetVM(txtVM.Text, paths); if (oComputer != null) { VirtualMachineConfigInfo oInfo = (VirtualMachineConfigInfo)oVMware.getObjectProperty(oComputer, "config"); Response.Write(oInfo.uuid + "<br/>"); } if (_service != null) { //ServiceContent _sic = oVMware.GetSic(); _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; //oLog.AddEvent(intAnswer, strName, strSerial, "Logged out of VMware", LoggingType.Information); } } } Response.Write(DateTime.Now.ToString() + "<br/>"); }
public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script VMwareESXVMsDataScript.", m_taskId); try { if (resultCode == ResultCodes.RC_SUCCESS) { UserSession userSessionObj = null; if (m_connection.ContainsKey(@"VimServiceObj")) { vim_svc = (VimService)m_connection[@"VimServiceObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter VimServiceObj.", m_taskId); } if (m_connection.ContainsKey(@"VimServiceContentObj")) { vim_svc_content = (ServiceContent)m_connection[@"VimServiceContentObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter VimServiceContentObj.", m_taskId); } if (m_connection.ContainsKey(@"userSessionObj")) { userSessionObj = (UserSession)m_connection[@"userSessionObj"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing connection parameter userSessionObj.", m_taskId); } String url = null; if (m_connection.ContainsKey(@"WebServiceUrl")) { url = (String)m_connection[@"WebServiceUrl"]; } if (userSessionObj != null) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Get VMs Info. Elapsed time {1} ms.", m_taskId, m_executionTimer.ElapsedMilliseconds); //collect ESX VMs info: StringBuilder ESXVMs_Info = getESXVMsData(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: VMs Info collected. Elapsed time {1} ms.", m_taskId, m_executionTimer.ElapsedMilliseconds); this.BuildDataRow(@"EsxVMsData", ESXVMs_Info); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: could not connect to esx web services at url {1} in (VMwareESXVMsDataScript).", m_taskId, url); resultCode = ResultCodes.RC_LOGIN_FAILED; //@TODO: change to some other value } // Disconnect from the service: if (vim_svc != null) { Disconnect(); } } } catch (SoapException se) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught SoapException in VMwareESXVMsDataScript. Elapsed time {1}.\n <Exception detail: [se: {2}]\n[Message: {3}]\n[Code: {4}]\n[Detail XML(OuterXml): {5}] Exception detail end>", m_taskId, m_executionTimer.Elapsed.ToString(), se.ToString(), se.Message.ToString(), se.Code.ToString(), se.Detail.OuterXml.ToString()); resultCode = ResultCodes.RC_ESX_WEB_SERVICE_QUERY_FAILURE; if (se.Message.Contains("Login failed")) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else if (se.Message.Contains("Unsupported namespace")) { resultCode = ResultCodes.RC_UNSUPPORTED_MESSAGE_TYPE; } else if (se.Code.ToString().Contains("ServerFaultCode")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: SoapException (ServerFaultCode) in VMwareESXVMsDataScript. Elapsed time {1}.\n <More detail: [InnerText: {2}]\n[InnerXml: {3}] end>", m_taskId, m_executionTimer.Elapsed.ToString(), se.Detail.InnerText, se.Detail.InnerXml); if (se.Detail.InnerXml.ToString().Contains("InvalidPropertyFault") || se.Detail.OuterXml.ToString().Contains("InvalidPropertyFault")) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught SoapException in VMwareESXVMsDataScript due to an InvalidProperty.", m_taskId); } } } catch (Exception ex) { if (ResultCodes.RC_SUCCESS == resultCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught exception in (VMwareESXVMsDataScript). Elapsed time {1}.\n{2}Result code changed to RC_PROCESSING_EXECEPTION. <EXP => {3} <EXP =>", m_taskId, m_executionTimer.Elapsed.ToString(), 1, ex.ToString()); resultCode = ResultCodes.RC_ESX_WEB_SERVICE_QUERY_FAILURE; } else { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Caught exception in - (VMwareESXVMsDataScript). Elapsed time {1}.\n{2} <EXP => {3} <EXP =>", m_taskId, m_executionTimer.Elapsed.ToString(), 1, ex.ToString()); resultCode = ResultCodes.RC_ESX_WEB_SERVICE_QUERY_FAILURE; } } finally { if (vim_svc != null) { vim_svc.Dispose(); vim_svc = null; vim_svc_content = null; } } return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
protected void btnGo_Click(Object Sender, EventArgs e) { Log oLog = new Log(0, dsn); string name = "ldfpg100a"; if (String.IsNullOrEmpty(Request.QueryString["n"]) == false) { name = Request.QueryString["n"]; } boolVMFound = false; Response.Write(DateTime.Now.ToString() + "<br/>"); string vc = "https://wssvt322a.pncbank.com/sdk"; string dc = "PNC-Dalton"; if (String.IsNullOrEmpty(Request.QueryString["dc"]) == false) { dc = Request.QueryString["dc"]; } string strConnect = oVMware.ConnectDEBUG(vc, 999, dc); if (strConnect == "") { oLog.AddEvent(name, "DEBUG", "Connected to " + dc + " using " + vc, LoggingType.Debug); VimService _service = oVMware.GetService(); ServiceContent _sic = oVMware.GetSic(); oLog.AddEvent(name, "DEBUG", "Connection OK", LoggingType.Debug); ManagedObjectReference datacenterRef = oVMware.GetDataCenter(); oLog.AddEvent(name, "DEBUG", "Connection to datacenterRef", LoggingType.Debug); ManagedObjectReference vmFolderRef = (ManagedObjectReference)getProperties(datacenterRef, "vmFolder"); oLog.AddEvent(name, "DEBUG", "Connection to vmFolderRef", LoggingType.Debug); ManagedObjectReference[] vmList = (ManagedObjectReference[])getProperties(vmFolderRef, "childEntity"); oLog.AddEvent(name, "DEBUG", "Connection to vmList (" + vmList.Length.ToString() + ")", LoggingType.Debug); for (int ii = 0; ii < vmList.Length; ii++) { oLog.AddEvent(name, "DEBUG", "Checking " + vmList[ii].Value, LoggingType.Debug); if (vmList[ii].type == "VirtualMachine") { oLog.AddEvent(name, "DEBUG", "Found! " + vmList[ii].Value, LoggingType.Debug); try { VirtualMachineConfigInfo vmInfo = (VirtualMachineConfigInfo)getProperties(vmList[ii], "config"); oLog.AddEvent(name, "DEBUG", "vmInfo OK (" + vmInfo.uuid + ")", LoggingType.Debug); Response.Write(vmInfo.name + " = " + vmInfo.uuid + "<br/>"); } catch (Exception ex) { oLog.AddEvent(name, "DEBUG", "ERROR: " + ex.Message, LoggingType.Debug); if (ex.InnerException != null) { oLog.AddEvent(name, "DEBUG", "ERROR: " + ex.InnerException.Message, LoggingType.Debug); } } break; } } oLog.AddEvent(name, "DEBUG", "Logging out", LoggingType.Debug); if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; oLog.AddEvent(name, "DEBUG", "Logged out", LoggingType.Debug); } } else { oLog.AddEvent(name, "DEBUG", "Unable to connect - " + strConnect, LoggingType.Debug); } Response.Write(DateTime.Now.ToString() + "<br/>"); }
protected void Page_Load(object sender, EventArgs e) { AuthenticateUser(); if (Request.Cookies["profileid"] != null && Request.Cookies["profileid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); } if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } oDataPoint = new DataPoint(intProfile, dsn); oUser = new Users(intProfile, dsn); oServer = new Servers(intProfile, dsn); oAsset = new Asset(intProfile, dsnAsset); oWorkstation = new Workstations(intProfile, dsn); oForecast = new Forecast(intProfile, dsn); oPlatform = new Platforms(intProfile, dsn); oType = new Types(intProfile, dsn); oModel = new Models(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oIPAddresses = new IPAddresses(intProfile, dsnIP, dsn); oFunction = new Functions(intProfile, dsn, intEnvironment); oOperatingSystem = new OperatingSystems(intProfile, dsn); oServicePack = new ServicePacks(intProfile, dsn); oClass = new Classes(intProfile, dsn); oEnvironment = new Environments(intProfile, dsn); oDomain = new Domains(intProfile, dsn); oVirtualHDD = new VirtualHDD(intProfile, dsn); oVirtualRam = new VirtualRam(intProfile, dsn); oZeus = new Zeus(intProfile, dsnZeus); oLog = new Log(intProfile, dsn); oService = new Services(intProfile, dsn); oServiceRequest = new ServiceRequests(intProfile, dsn); oResourceRequest = new ResourceRequest(intProfile, dsn); if (oUser.IsAdmin(intProfile) == true || (oDataPoint.GetPagePermission(intApplication, "ASSET") == true || intDataPointAvailableAsset == 1)) { panAllow.Visible = true; if (Request.QueryString["save"] != null) { panSave.Visible = true; } if (Request.QueryString["error"] != null) { panError.Visible = true; // -100: More than one device name // -10: No device names // -5: Improper Name Format // -1: ServerID = 0 if (Request.QueryString["error"] == "-100") { lblError.Text = "More than one name"; } else if (Request.QueryString["error"] == "-10") { lblError.Text = "User Cancelled Prompt"; } else if (Request.QueryString["error"] == "-5") { lblError.Text = "Name is in Incorrect Format"; } else if (Request.QueryString["error"] == "-1") { lblError.Text = "DeviceID = 0"; } else { lblError.Text = "Generic Error"; } } Int32.TryParse(oFunction.decryptQueryString(Request.QueryString["id"]), out intID); if (Request.QueryString["close"] != null) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "close", "<script type=\"text/javascript\">window.close();<" + "/" + "script>"); } else if (intID > 0) { DataSet ds = oDataPoint.GetAsset(intID); if (ds.Tables[0].Rows.Count == 1) { // Load General Information intAsset = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); lblAssetID.Text = "#" + intAsset.ToString(); string strSerial = ds.Tables[0].Rows[0]["serial"].ToString(); string strAsset = ds.Tables[0].Rows[0]["asset"].ToString(); string strHeader = (strSerial.Length > 15 ? strSerial.Substring(0, 15) + "..." : strSerial); lblHeader.Text = """ + strHeader.ToUpper() + """; Master.Page.Title = "DataPoint | VMware Workstation (" + strHeader + ")"; lblHeaderSub.Text = "Provides all the information about a VMware Workstation..."; int intMenuTab = 0; if (Request.QueryString["menu_tab"] != null && Request.QueryString["menu_tab"] != "") { intMenuTab = Int32.Parse(Request.QueryString["menu_tab"]); } Tab oTab = new Tab(hdnTab.ClientID, intMenuTab, "divMenu1", true, false); oTab.AddTab("Asset Information", ""); oTab.AddTab("Guest Information", ""); oTab.AddTab("Account Information", ""); oTab.AddTab("Resource Dependencies", ""); oTab.AddTab("Provisioning Information", ""); if (oUser.IsAdmin(intProfile) == true || oDataPoint.GetFieldPermission(intProfile, "SERVER_ADMIN") == true) { oTab.AddTab("Administration", ""); panAdministration.Visible = true; } strMenuTab1 = oTab.GetTabs(); if (!IsPostBack) { // Asset Information oDataPoint.LoadTextBox(txtPlatformSerial, intProfile, null, "", lblPlatformSerial, fldPlatformSerial, "WORKSTATION_VMWARE_SERIAL", strSerial, "", false, true); oDataPoint.LoadTextBox(txtPlatformAsset, intProfile, null, "", lblPlatformAsset, fldPlatformAsset, "WORKSTATION_VMWARE_ASSET", strAsset, "", false, true); int intAssetAttribute = Int32.Parse(oAsset.Get(intAsset, "asset_attribute")); oDataPoint.LoadDropDown(ddlAssetAttribute, intProfile, null, "", lblAssetAttribute, fldAssetAttribute, "ASSET_ATTRIBUTE", "Name", "AttributeId", oAsset.getAssetAttributes(null, "", 1), intAssetAttribute, true, false, false); oDataPoint.LoadTextBox(txtAssetAttributeComment, intProfile, null, "", lblAssetAttributeComment, fldAssetAttributeComment, "ASSET_ATTRIBUTE_COMMENT", oAsset.getAssetAttributesComments(intAsset), "", false, true); ddlAssetAttribute.Attributes.Add("onclick", "return SetControlsForAssetAttributes()"); ddlPlatform.Attributes.Add("onchange", "PopulatePlatformTypes('" + ddlPlatform.ClientID + "','" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformType.Attributes.Add("onchange", "PopulatePlatformModels('" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModel.Attributes.Add("onchange", "PopulatePlatformModelProperties('" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModelProperty.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformModelProperty.ClientID + "','" + hdnModel.ClientID + "');"); int intModel = Int32.Parse(oAsset.Get(intAsset, "modelid")); hdnModel.Value = intModel.ToString(); int intModelParent = Int32.Parse(oModelsProperties.Get(intModel, "modelid")); int intType = oModel.GetType(intModelParent); string strExecute = oType.Get(intType, "forecast_execution_path"); if (strExecute != "") { DataSet dsVirtual = oWorkstation.GetVirtualAsset(intAsset); if (dsVirtual.Tables[0].Rows.Count > 0) { btnExecute.Attributes.Add("onclick", "return OpenWindow('FORECAST_EXECUTE','" + strExecute + "?id=" + dsVirtual.Tables[0].Rows[0]["answerid"].ToString() + "');"); } else { btnExecute.Enabled = false; } } else { btnExecute.Enabled = false; } int intPlatform = oType.GetPlatform(intType); oDataPoint.LoadDropDown(ddlPlatform, intProfile, null, "", lblPlatform, fldPlatform, "WORKSTATION_VMWARE_PLATFORM", "name", "platformid", oPlatform.Gets(1), intPlatform, false, false, true); oDataPoint.LoadDropDown(ddlPlatformType, intProfile, null, "", lblPlatformType, fldPlatformType, "WORKSTATION_VMWARE_TYPE", "name", "id", oType.Gets(intPlatform, 1), intType, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModel, intProfile, null, "", lblPlatformModel, fldPlatformModel, "WORKSTATION_VMWARE_MODEL", "name", "id", oModel.Gets(intType, 1), intModelParent, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModelProperty, intProfile, null, "", lblPlatformModelProperty, fldPlatformModelProperty, "WORKSTATION_VMWARE_MODEL_PROP", "name", "id", oModelsProperties.GetModels(0, intModelParent, 1), intModel, false, false, true); // Get Asset int intWorkstation = 0; DataSet dsAsset = oWorkstation.GetVirtualAsset(intAsset); if (dsAsset.Tables[0].Rows.Count > 0) { intWorkstation = Int32.Parse(dsAsset.Tables[0].Rows[0]["id"].ToString()); lblWorkstation.Text = intWorkstation.ToString(); txtStep.Text = dsAsset.Tables[0].Rows[0]["step"].ToString(); oDataPoint.LoadTextBoxDeviceName(txtName, btnName, null, true, hdnPNC, intProfile, null, "", lblName, fldName, "WORKSTATION_VMWARE_NAME", dsAsset.Tables[0].Rows[0]["name"].ToString(), "", false, false); if (txtName.Text != "") { lblHeader.Text += " [" + txtName.Text + "]"; } lblStatus.Text = dsAsset.Tables[0].Rows[0]["statusname"].ToString(); // Administrative Functions if (Request.QueryString["admin"] != null) { if (Request.QueryString["result"] != null) { strAdministration = "<tr><td>" + oFunction.decryptQueryString(Request.QueryString["result"]) + "</td></tr>"; } if (Request.QueryString["output"] != null) { DataSet dsOutput = oWorkstation.GetVirtualOutput(intWorkstation); foreach (DataRow drOutput in dsOutput.Tables[0].Rows) { strAdministration += "<tr><td><a href=\"javascript:void(0);\" onclick=\"ShowHideDiv2('div" + drOutput["id"].ToString() + "');\">" + drOutput["type"].ToString() + "</a></td></tr>"; strAdministration += "<tr id=\"div" + drOutput["id"].ToString() + "\" style=\"display:none\"><td>" + oFunction.FormatText(drOutput["output"].ToString()) + "</td></tr>"; } if (lblStatus.Text != "") { strAdministration += "<tr><td>" + oLog.GetEvents(oLog.GetEventsByName(txtName.Text.ToUpper(), (int)LoggingType.Error), intEnvironment) + "</td></tr>"; } } } int intClass = Int32.Parse(dsAsset.Tables[0].Rows[0]["classid"].ToString()); int intEnv = Int32.Parse(dsAsset.Tables[0].Rows[0]["environmentid"].ToString()); hdnEnvironment.Value = intEnv.ToString(); oDataPoint.LoadDropDown(ddlPlatformClass, intProfile, null, "", lblPlatformClass, fldPlatformClass, "WORKSTATION_VMWARE_CLASS", "name", "id", oClass.GetWorkstationVMwares(1), intClass, false, false, true); oDataPoint.LoadDropDown(ddlPlatformEnvironment, intProfile, null, "", lblPlatformEnvironment, fldPlatformEnvironment, "WORKSTATION_VMWARE_ENVIRONMENT", "name", "id", oClass.GetEnvironment(intClass, 0), intEnv, false, false, true); ddlStatus.SelectedValue = dsAsset.Tables[0].Rows[0]["status"].ToString(); ddlStatus.Enabled = (intAssetAttribute == (int)AssetAttribute.Ok); panStatus.Visible = (ddlStatus.Enabled == false); int intOS = Int32.Parse(dsAsset.Tables[0].Rows[0]["osid"].ToString()); bool boolXP = (oOperatingSystem.Get(intOS, "code") == "XP"); bool boolWin7 = (oOperatingSystem.Get(intOS, "code") == "7"); oDataPoint.LoadDropDown(ddlPlatformOS, intProfile, null, "", lblPlatformOS, fldPlatformOS, "WORKSTATION_VMWARE_OS", "name", "id", oOperatingSystem.Gets(1, 1), intOS, false, false, true); oDataPoint.LoadDropDown(ddlPlatformServicePack, intProfile, null, "", lblPlatformServicePack, fldPlatformServicePack, "WORKSTATION_VMWARE_SP", "name", "id", oOperatingSystem.GetServicePack(intOS), Int32.Parse(dsAsset.Tables[0].Rows[0]["spid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformDomain, intProfile, null, "", lblPlatformDomain, fldPlatformDomain, "WORKSTATION_VMWARE_DOMAIN", "name", "id", oDomain.Gets(1), Int32.Parse(dsAsset.Tables[0].Rows[0]["domainid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformHDD, intProfile, null, "", lblPlatformHDD, fldPlatformHDD, "WORKSTATION_VMWARE_HDD", "name", "id", oVirtualHDD.GetVMwares((boolXP ? 1 : 0), (boolWin7 ? 1 : 0), 1), Int32.Parse(dsAsset.Tables[0].Rows[0]["hddid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformRam, intProfile, null, "", lblPlatformRam, fldPlatformRam, "WORKSTATION_VMWARE_RAM", "name", "id", oVirtualRam.GetVMwares((boolXP ? 1 : 0), (boolWin7 ? 1 : 0), 1), Int32.Parse(dsAsset.Tables[0].Rows[0]["ramid"].ToString()), false, false, true); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } // Get Host oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(dsAsset.Tables[0].Rows[0]["hostname"].ToString()), lblHostName, fldHostName, "WORKSTATION_VMWARE_HOST", dsAsset.Tables[0].Rows[0]["hostname"].ToString(), "", false, false); if (Request.Cookies["virtual_guest"] != null && Request.Cookies["virtual_guest"].Value != "") { string strHost = ""; string strFind = txtName.Text; //strFind = "ohcleapp103d"; DateTime datStart = DateTime.Parse(Request.Cookies["virtual_guest"].Value); Response.Cookies["virtual_guest"].Value = ""; VMWare oVMWare = new VMWare(intProfile, dsn); string strConnect = oVMWare.Connect(strFind); VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); try { ManagedObjectReference oVM = oVMWare.GetVM(strFind); ManagedObjectReference oParent = (ManagedObjectReference)oVMWare.getObjectProperty(oVM, "parent"); ManagedObjectReference oDataCenter = (ManagedObjectReference)oVMWare.getObjectProperty(oParent, "parent"); string strDataCenter = (string)oVMWare.getObjectProperty(oDataCenter, "name"); GuestInfo ginfo = (GuestInfo)oVMWare.getObjectProperty(oVM, "guest"); lblGuestState.Text = ginfo.guestState; GuestNicInfo[] nInfo = ginfo.net; foreach (GuestNicInfo nic in nInfo) { string[] strIPAddresses = nic.ipAddress; foreach (string strIPAddress in strIPAddresses) { if (lblIPAddress.Text != "") { lblIPAddress.Text += ", "; } lblIPAddress.Text += strIPAddress; } if (lblMACAddress.Text != "") { lblMACAddress.Text += ", "; } lblMACAddress.Text += nic.macAddress; if (lblNetwork.Text != "") { lblNetwork.Text += ", "; } lblNetwork.Text += nic.network; } // HDD GuestDiskInfo[] oVMDisks = ginfo.disk; foreach (GuestDiskInfo oDisk in oVMDisks) { if (lblHDD.Text != "") { lblHDD.Text += "<br/>"; } double dblCapacity = double.Parse(oDisk.capacity.ToString()); dblCapacity = dblCapacity / 1024.00; dblCapacity = dblCapacity / 1024.00; dblCapacity = dblCapacity / 1024.00; double dblAvailable = double.Parse(oDisk.freeSpace.ToString()); dblAvailable = dblAvailable / 1024.00; dblAvailable = dblAvailable / 1024.00; dblAvailable = dblAvailable / 1024.00; lblHDD.Text += oDisk.diskPath + " " + dblCapacity.ToString("F") + " GB (" + dblAvailable.ToString("F") + " GB available)"; } // Status VirtualMachineSummary oVMSummary = (VirtualMachineSummary)oVMWare.getObjectProperty(oVM, "summary"); ManagedEntityStatus oVMStatus = oVMSummary.overallStatus; //lblOverallStatus.Text = (string)oVMStatus; lblOverallStatus.Text = Enum.GetName(typeof(ManagedEntityStatus), (ManagedEntityStatus)oVMStatus); // RAM & CPUs & Host VirtualMachineConfigSummary oVMConfig = oVMSummary.config; lblRAM.Text = oVMConfig.memorySizeMB.ToString(); lblCPUs.Text = oVMConfig.numCpu.ToString(); VirtualMachineRuntimeInfo oVMRuntime = oVMSummary.runtime; ManagedObjectReference oVMHost = oVMRuntime.host; strHost = (string)oVMWare.getObjectProperty(oVMHost, "name"); if (strHost.IndexOf(".") > -1) { strHost = strHost.Substring(0, strHost.IndexOf(".")); } lblVirtualCenter.Text = oVMWare.VirtualCenter(); lblDataCenter.Text = oVMWare.DataCenter(); } catch { } finally { if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } if (strHost != "") { panGuestYes.Visible = true; oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(strHost), lblHostName, fldHostName, "WORKSTATION_VMWARE_HOST", strHost, "", false, false); } else { panGuestNo.Visible = true; } TimeSpan oSpan = DateTime.Now.Subtract(datStart); btnGuestQuery.Enabled = false; btnGuestQuery.Text = "Query Time: " + oSpan.TotalSeconds.ToString("0") + " seconds..."; } oDataPoint.LoadPanel(panGuestQuery, intProfile, fldHostQuery, "WORKSTATION_VMWARE_HOST_QUERY"); // Account Information DataSet dsAccounts = oWorkstation.GetAccountsVMware(intWorkstation); rptAccounts.DataSource = dsAccounts; rptAccounts.DataBind(); lblNone.Visible = (rptAccounts.Items.Count == 0); // Resource Dependencies rptServiceRequests.DataSource = ds.Tables[1]; rptServiceRequests.DataBind(); trServiceRequests.Visible = (rptServiceRequests.Items.Count == 0); foreach (RepeaterItem ri in rptServiceRequests.Items) { Label lblRequestID = (Label)ri.FindControl("lblRequestID"); Label lblServiceID = (Label)ri.FindControl("lblServiceID"); Label lblNumber = (Label)ri.FindControl("lblNumber"); int intService = Int32.Parse(lblServiceID.Text); Label lblDetails = (Label)ri.FindControl("lblDetails"); Label lblProgress = (Label)ri.FindControl("lblProgress"); if (lblProgress.Text == "") { lblProgress.Text = "<i>Unavailable</i>"; } else { int intResource = Int32.Parse(lblProgress.Text); //lblProgress.Text = oResourceRequest.GetStatus(Int32.Parse(lblRequestID.Text), Int32.Parse(lblServiceID.Text), Int32.Parse(lblNumber.Text), true, true, dsnServiceEditor, dsnAsset, intServiceDecommission); lblProgress.Text = oResourceRequest.GetStatus(null, null, Int32.Parse(lblRequestID.Text), Int32.Parse(lblServiceID.Text), null, Int32.Parse(lblNumber.Text), true, dsnServiceEditor)[0].status; /* * double dblAllocated = 0.00; * double dblUsed = 0.00; * int intStatus = 0; * bool boolAssigned = false; * DataSet dsResource = oDataPoint.GetServiceRequestResource(intResource); * if (dsResource.Tables[0].Rows.Count > 0) * Int32.TryParse(dsResource.Tables[0].Rows[0]["status"].ToString(), out intStatus); * foreach (DataRow drResource in dsResource.Tables[1].Rows) * { * boolAssigned = true; * dblAllocated += double.Parse(drResource["allocated"].ToString()); * dblUsed += double.Parse(drResource["used"].ToString()); * intStatus = Int32.Parse(drResource["status"].ToString()); * } * if (intStatus == (int)ResourceRequestStatus.Closed) * lblProgress.Text = oServiceRequest.GetStatusBar(100.00, "100", "12", true); * else if (intStatus == (int)ResourceRequestStatus.Cancelled) * lblProgress.Text = "Cancelled"; * else if (boolAssigned == false) * { * string strManager = ""; * DataSet dsManager = oService.GetUser(intService, 1); // Managers * foreach (DataRow drManager in dsManager.Tables[0].Rows) * { * if (strManager != "") * strManager += "\\n"; * int intManager = Int32.Parse(drManager["userid"].ToString()); * strManager += " - " + oUser.GetFullName(intManager) + " [" + oUser.GetName(intManager) + "]"; * } * lblProgress.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"alert('This request is pending assignment by the following...\\n\\n" + strManager + "');\">Pending Assignment</a>"; * } * else if (dblAllocated > 0.00) * lblProgress.Text = oServiceRequest.GetStatusBar((dblUsed / dblAllocated) * 100.00, "100", "12", true); * else * lblProgress.Text = "<i>N / A</i>"; */ lblDetails.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('/datapoint/service/resource.aspx?id=" + oFunction.encryptQueryString(intResource.ToString()) + "', '800', '600');\">" + lblDetails.Text + "</a>"; } } // Provioning History rptHistory.DataSource = SqlHelper.ExecuteDataset(dsnAsset, CommandType.Text, oDataPoint.AssetHistorySelect(intAsset)); rptHistory.DataBind(); lblHistory.Visible = (rptHistory.Items.Count == 0); oDataPoint.LoadPanel(panProvisioning, intProfile, fldProvisioning, "WORKSTATION_VMWARE_STATUS"); } } else { if (Request.QueryString["t"] != null && Request.QueryString["q"] != null) { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&r=0"); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } } } else if (Request.QueryString["q"] != null && Request.QueryString["q"] != "") { string strQuery = oFunction.decryptQueryString(Request.QueryString["q"]); DataSet ds = oDataPoint.GetAssetName(strQuery, intID, 0, "", "", 0); if (ds.Tables[0].Rows.Count == 1) { intAsset = Int32.Parse(ds.Tables[0].Rows[0]["assetid"].ToString()); Response.Redirect(Request.Path + "?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&id=" + oFunction.encryptQueryString(intAsset.ToString())); } } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } btnClose.Attributes.Add("onclick", "window.close();return false;"); btnPrint.Attributes.Add("onclick", "window.print();return false;"); btnName.Attributes.Add("onclick", "return OpenWindow('DEVICE_NAME','?assetid=" + intAsset.ToString() + "');"); btnSave.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); btnSaveClose.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); ddlPlatformClass.Attributes.Add("onchange", "PopulateEnvironments('" + ddlPlatformClass.ClientID + "','" + ddlPlatformEnvironment.ClientID + "',0);"); ddlPlatformEnvironment.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformEnvironment.ClientID + "','" + hdnEnvironment.ClientID + "');"); btnGuestQuery.Attributes.Add("onclick", "ProcessButton(this,'Querying... please be patient...','225') && ProcessControlButton();"); btnOutput.Attributes.Add("onclick", "return ProcessButton(this) && ProcessControlButton();"); } else { panDenied.Visible = true; } }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); Variables oVariable = new Variables(999); string strName = "healyTest"; string strCluster = "CLESVTLAB01"; double dblDriveC = 60.00; string strDatastore = "CTVXN00007"; double dblDrive2 = 10.00; double dblDrive3 = 10.00; string strPortGroupName = "dvPortGroup5"; // DHCP enabled string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_STD"; string strMDTbuildDB = "ServerShare"; string strVMguestOS = "windows7Server64Guest"; string strMACAddress = ""; string strResourcePool = ""; string strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", 999, "PNC-TestLab"); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); // Create computer ManagedObjectReference oComputer = null; oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } if (strError == "") { // 2) SCSI Controller 1 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(0, 2, 1000); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDriveC.ToString(), 0, 1000, ""); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 1 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 1 Was Not Created"; } } if (strError == "") { // 4) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive2.ToString(), 1, 1000, "_2"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } if (strError == "") { // 5) SCSI Controller 2 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(1, 3, 1001); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 6) Create Hard Disk 3 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive3 = dblDrive3 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive3.ToString(), 0, 1001, "_3"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 3 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 3 Was Not Created"; } } if (String.IsNullOrEmpty(Request.QueryString["build"]) == false) { if (strError == "") { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } if (strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if (strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if (strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if (strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); string strName = "healytest2"; string strCluster = "CDALVMTEST01"; string strDatastore1 = "dt01-ibm-lun1"; string strDatastore2 = ""; string strVLAN = "VLAN52"; string strPortGroupName = "dvPortGroup255"; string strMACAddress = ""; string strResourcePool = ""; string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_ENT"; string strMDTbuildDB = "ServerShare"; double dblDriveC = 27.5; double dblDrive2 = 2.5; string strVMguestOS = "winNetEnterprise64Guest"; intEnvironment = 999; string strConnect = oVMWare.ConnectDEBUG("https://wdsvt100a/sdk", intEnvironment, "PNC"); if (Request.QueryString["old"] != null) { strName = "healytest"; strCluster = "ohcinxcv4003"; strDatastore1 = "CINDSSVCN40063"; strVLAN = "vlan250net"; intEnvironment = 3; strConnect = oVMWare.ConnectDEBUG("https://ohcinutl4003/sdk", intEnvironment, "Dalton"); } if (Request.QueryString["w"] != null) { strName = "healytest2"; strCluster = "CLEVDTLAB01"; strDatastore1 = "VDItest"; strDatastore2 = "pagefile01"; strPortGroupName = "dvPortGroup"; strResourcePool = "VDI"; strMDTos = "DesktopWABEx86"; strMDTtask = "VDIXP"; strMDTbuildDB = "DesktopDeploymentShare"; strVMguestOS = "windows7_64Guest"; strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", intEnvironment, "PNC-TestLab"); } if (Request.QueryString["t"] != null) { strName = "healyTest2012"; strCluster = "CLESVTLAB01"; dblDriveC = 45.00; strDatastore1 = "CTVXN00008"; strDatastore2 = "CTVXN00008"; dblDrive2 = 10.00; strPortGroupName = "dvPortGroup5"; // DHCP enabled strMDTos = "WABEx64"; strMDTtask = "W2K8R2_STD"; strMDTbuildDB = "ServerShare"; strVMguestOS = "windows8Server64Guest"; strConnect = oVMWare.ConnectDEBUG("https://wcsvt013a.pnceng.pvt/sdk", (int)CurrentEnvironment.PNCENG, "PNC"); } Variables oVariable = new Variables(intEnvironment); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); int intStep = 0; Int32.TryParse(Request.QueryString["s"], out intStep); string strUUID = ""; ManagedObjectReference oComputer = null; if (intStep == 100 || intStep == 1) { if (oComputer != null && oComputer.Value != "") { // Destroy computer ManagedObjectReference _task_power = _service.Destroy_Task(oComputer); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine " + strName.ToUpper() + " Destroyed<br/>"; } else { strError = "Virtual Machine was not destroyed"; } } if (strError == "") { // Create computer oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; oConfig.firmware = "efi"; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore1 + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } } } if (intStep > 1) { oComputer = oVMWare.GetVM(strName); } if ((intStep == 100 || intStep == 2) && strError == "") { // 2) SCSI Controller VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(true); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller Created<br/>"; } else { strError = "SCSI Controller Was Not Created"; } } if ((intStep == 100 || intStep == 3) && strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore1, dblDriveC.ToString(), 0, ""); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive Was Not Created"; } } if ((intStep == 100 || intStep == 33) && strError == "") { if (strDatastore2 != "") { // 33) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore2, dblDrive2.ToString(), 1, (strDatastore1 == strDatastore2 ? "_1" : "")); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDrive2.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } } if ((intStep == 100 || intStep == 4) && strError == "") { // 4) Create Network Adapter bool boolISVmware4 = true; if (boolISVmware4 == false) { VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardNetworkBackingInfo vecnbi = new VirtualEthernetCardNetworkBackingInfo(); vecnbi.deviceName = strVLAN; VirtualEthernetCard newethdev; //newethdev = new VirtualE1000(); newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecnbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; } else { strError = "Network Adapter Was Not Created"; } } else { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } } if ((intStep == 100 || intStep == 5) && strError == "") { VirtualMachineConfigSpec _cs_swap = new VirtualMachineConfigSpec(); _cs_swap.swapPlacement = "hostLocal"; ManagedObjectReference _task_swap = _service.ReconfigVM_Task(oComputer, _cs_swap); TaskInfo _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); while (_info_swap.state == TaskInfoState.running) { _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); } if (_info_swap.state == TaskInfoState.success) { strResult += "Swap File Configured<br/>"; } else { strError = "Swap File Was Not Configured"; } /* * // 5) Attach Floppy Drive * VirtualMachineConfigSpec _cs_floppy = new VirtualMachineConfigSpec(); * VirtualDeviceConfigSpec _dcs_floppy = new VirtualDeviceConfigSpec(); * _dcs_floppy.operation = VirtualDeviceConfigSpecOperation.add; * _dcs_floppy.operationSpecified = true; * VirtualDeviceConnectInfo _ci_floppy = new VirtualDeviceConnectInfo(); * _ci_floppy.startConnected = false; * VirtualFloppy floppy = new VirtualFloppy(); * VirtualFloppyRemoteDeviceBackingInfo floppyBack = new VirtualFloppyRemoteDeviceBackingInfo(); * floppyBack.deviceName = ""; * floppy.backing = floppyBack; * floppy.key = 8000; * floppy.controllerKey = 400; * floppy.controllerKeySpecified = true; * floppy.connectable = _ci_floppy; * _dcs_floppy.device = floppy; * _cs_floppy.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_floppy }; * ManagedObjectReference _task_floppy = _service.ReconfigVM_Task(oComputer, _cs_floppy); * TaskInfo _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * while (_info_floppy.state == TaskInfoState.running) * _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * if (_info_floppy.state == TaskInfoState.success) * strResult += "Floppy Drive Created<br/>"; * else * strError = "Floppy Drive Was Not Created"; */ } if ((intStep == 100 || intStep == 6) && strError == "") { // 6) Attach CD-ROM Drive VirtualMachineConfigSpec _cs_cd = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec _dcs_cd = new VirtualDeviceConfigSpec(); _dcs_cd.operation = VirtualDeviceConfigSpecOperation.add; _dcs_cd.operationSpecified = true; VirtualDeviceConnectInfo _ci_cd = new VirtualDeviceConnectInfo(); _ci_cd.startConnected = false; VirtualCdrom cd = new VirtualCdrom(); VirtualCdromRemotePassthroughBackingInfo cdBack = new VirtualCdromRemotePassthroughBackingInfo(); cdBack.exclusive = false; cdBack.deviceName = ""; cd.backing = cdBack; cd.key = 3000; cd.controllerKey = 200; cd.controllerKeySpecified = true; cd.connectable = _ci_cd; _dcs_cd.device = cd; _cs_cd.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_cd }; ManagedObjectReference _task_cd = _service.ReconfigVM_Task(oComputer, _cs_cd); TaskInfo _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); while (_info_cd.state == TaskInfoState.running) { _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); } if (_info_cd.state == TaskInfoState.success) { strResult += "CD-ROM Was Created<br/>"; } else { strError = "CD-ROM Was Not Created"; } } if ((intStep == 100 || intStep == 7) && strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if ((intStep == 100 || intStep == 8) && strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if ((intStep == 100 || intStep == 9) && strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if ((intStep == 100 || intStep == 10) && strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
protected void Page_Load(object sender, EventArgs e) { Response.Cookies["loginreferrer"].Value = "/admin/vmware/clusters.aspx"; Response.Cookies["loginreferrer"].Expires = DateTime.Now.AddDays(30); if (Request.Cookies["adminid"] != null && Request.Cookies["adminid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["adminid"].Value); } else { Response.Redirect("/admin/login.aspx"); } oVMWare = new VMWare(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oResiliency = new Resiliency(intProfile, dsn); if (Request.QueryString["id"] != null) { panAdd.Visible = true; intID = Int32.Parse(Request.QueryString["id"]); if (intID > 0 && !IsPostBack) { DataSet ds = oVMWare.GetCluster(intID); int intFolder = Int32.Parse(ds.Tables[0].Rows[0]["folderid"].ToString()); int intDatacenter = Int32.Parse(oVMWare.GetFolder(intFolder, "datacenterid")); LoadFolders(intDatacenter); ddlParent.SelectedValue = intFolder.ToString(); int intModel = Int32.Parse(ds.Tables[0].Rows[0]["modelid"].ToString()); hdnModel.Value = intModel.ToString(); txtName.Text = ds.Tables[0].Rows[0]["name"].ToString(); ddlVersion.SelectedValue = ds.Tables[0].Rows[0]["version"].ToString(); ddlAntiAffinity.SelectedValue = ds.Tables[0].Rows[0]["anti_affinity"].ToString(); txtMaximum.Text = ds.Tables[0].Rows[0]["maximum"].ToString(); txtResourcePool.Text = ds.Tables[0].Rows[0]["resource_pool"].ToString(); txtDatastoreNotify.Text = ds.Tables[0].Rows[0]["datastores_notify"].ToString(); txtDatastoreLeft.Text = ds.Tables[0].Rows[0]["datastores_left"].ToString(); txtDatastoreSize.Text = ds.Tables[0].Rows[0]["datastores_size"].ToString(); chkPNC.Checked = (ds.Tables[0].Rows[0]["pnc"].ToString() == "1"); chkFull.Checked = (ds.Tables[0].Rows[0]["at_max"].ToString() == "1"); chkAPoff.Checked = (ds.Tables[0].Rows[0]["auto_provision_off"].ToString() == "1"); chkAPoffDR.Checked = (ds.Tables[0].Rows[0]["auto_provision_dr_off"].ToString() == "1"); chkDell.Checked = (ds.Tables[0].Rows[0]["dell"].ToString() == "1"); ddlResiliency.SelectedValue = ds.Tables[0].Rows[0]["resiliencyid"].ToString(); chkOracle.Checked = (ds.Tables[0].Rows[0]["can_oracle"].ToString() == "1"); chkOracleCluster.Checked = (ds.Tables[0].Rows[0]["can_oracle_cluster"].ToString() == "1"); chkSQL.Checked = (ds.Tables[0].Rows[0]["can_sql"].ToString() == "1"); chkSQLCluster.Checked = (ds.Tables[0].Rows[0]["can_sql_cluster"].ToString() == "1"); chkCluster.Checked = (ds.Tables[0].Rows[0]["can_cluster"].ToString() == "1"); chkEnabled.Checked = (ds.Tables[0].Rows[0]["enabled"].ToString() == "1"); // Calculations double dblA3 = 0.00; double dblA4 = 0.00; double dblA5 = 0.00; double dblA8 = 0.00; double dblA10 = 0.00; double dblA20 = 0.00; double dblA21 = 0.00; double dblA22 = 0.00; double dblA25 = 0.00; double dblA26 = 0.00; double dblA29 = 0.00; double dblA30 = 0.00; if (ds.Tables[0].Rows[0]["input_failures"].ToString() != "") { dblA3 = double.Parse(ds.Tables[0].Rows[0]["input_failures"].ToString()); } txtFailures.Text = dblA3.ToString(); if (ds.Tables[0].Rows[0]["input_cpu_utilization"].ToString() != "") { dblA4 = double.Parse(ds.Tables[0].Rows[0]["input_cpu_utilization"].ToString()); } txtCPUUtilization.Text = dblA4.ToString(); if (ds.Tables[0].Rows[0]["input_ram_utilization"].ToString() != "") { dblA5 = double.Parse(ds.Tables[0].Rows[0]["input_ram_utilization"].ToString()); } txtRAMUtilization.Text = dblA5.ToString(); if (ds.Tables[0].Rows[0]["input_max_ram"].ToString() != "") { dblA8 = double.Parse(ds.Tables[0].Rows[0]["input_max_ram"].ToString()); } txtMaxRAM.Text = dblA8.ToString(); if (ds.Tables[0].Rows[0]["input_avg_utilization"].ToString() != "") { dblA10 = double.Parse(ds.Tables[0].Rows[0]["input_avg_utilization"].ToString()); } txtAvgUtilization.Text = dblA10.ToString(); if (ds.Tables[0].Rows[0]["input_lun_size"].ToString() != "") { dblA20 = double.Parse(ds.Tables[0].Rows[0]["input_lun_size"].ToString()); } txtLunSize.Text = dblA20.ToString(); if (ds.Tables[0].Rows[0]["input_lun_utilization"].ToString() != "") { dblA21 = double.Parse(ds.Tables[0].Rows[0]["input_lun_utilization"].ToString()); } txtLunUtilization.Text = dblA21.ToString(); if (ds.Tables[0].Rows[0]["input_vms_per_lun"].ToString() != "") { dblA22 = double.Parse(ds.Tables[0].Rows[0]["input_vms_per_lun"].ToString()); } txtVMsPerLun.Text = dblA22.ToString(); if (ds.Tables[0].Rows[0]["input_time_lun"].ToString() != "") { dblA25 = double.Parse(ds.Tables[0].Rows[0]["input_time_lun"].ToString()); } txtTimeLUN.Text = dblA25.ToString(); if (ds.Tables[0].Rows[0]["input_time_cluster"].ToString() != "") { dblA26 = double.Parse(ds.Tables[0].Rows[0]["input_time_cluster"].ToString()); } txtTimeCluster.Text = dblA26.ToString(); if (ds.Tables[0].Rows[0]["input_max_vms_server"].ToString() != "") { dblA29 = double.Parse(ds.Tables[0].Rows[0]["input_max_vms_server"].ToString()); } txtMaxVMsServer.Text = dblA29.ToString(); if (ds.Tables[0].Rows[0]["input_max_vms_lun"].ToString() != "") { dblA30 = double.Parse(ds.Tables[0].Rows[0]["input_max_vms_lun"].ToString()); } txtMaxVMsLUN.Text = dblA30.ToString(); double dblA13 = 0.00; double dblA14 = 0.00; double dblA15 = 0.00; double dblA16 = 0.00; DataSet dsModel = oModelsProperties.Get(intModel); if (dsModel.Tables[0].Rows.Count > 0) { lblModel.Text = dsModel.Tables[0].Rows[0]["name"].ToString(); dblA13 = double.Parse(dsModel.Tables[0].Rows[0]["ram"].ToString()); dblA14 = double.Parse(dsModel.Tables[0].Rows[0]["cpu_count"].ToString()); dblA15 = 1.00; dblA16 = double.Parse(dsModel.Tables[0].Rows[0]["cpu_speed"].ToString()); } txtRAM.Text = dblA13.ToString(); txtCores.Text = dblA14.ToString(); txtCPUs.Text = dblA15.ToString(); txtProcs.Text = dblA16.ToString(); double dblA17 = dblA14 * dblA15 * dblA16; // =A14*A15*A16 txtTotal.Text = dblA17.ToString(); double dblA2 = 0.00; if (Request.QueryString["query"] != null) { trCapacity.Visible = true; chkQuery.Checked = true; // Get # of hosts from cluster int intVirtualCenter = Int32.Parse(oVMWare.GetDatacenter(intDatacenter, "virtualcenterid")); string strVirtualCenter = oVMWare.GetVirtualCenter(intVirtualCenter, "name"); string strConnect = oVMWare.ConnectDEBUG(oVMWare.GetVirtualCenter(intVirtualCenter, "url"), Int32.Parse(oVMWare.GetVirtualCenter(intVirtualCenter, "environment")), oVMWare.GetDatacenter(intDatacenter, "name")); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference[] hostRefs = oVMWare.GetHosts(txtName.Text); dblA2 = double.Parse(hostRefs.Length.ToString()); if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } else { dblA2 = -1.00; } } else { dblA2 = -1.00; } txtServers.Text = dblA2.ToString(); // Maximum CPU allocated double dblA9 = dblA13 * dblA8; dblA9 = dblA17 / dblA9; txtMaxCPU.Text = dblA9.ToString(); // =A17/A13*A8 // Total CPU & RAM double dblD2 = dblA2 * dblA17; txtTotalCPU.Text = dblD2.ToString(); // =A2*A17 double dblD3 = dblA2 * dblA13; txtTotalRAM.Text = dblD3.ToString(); // =A2*A13 // Reserves double dblD7 = dblA29 * dblA26 * dblA9; txtReserveCPU.Text = dblD7.ToString(); // =A29*A26*A9 double dblD8 = dblA29 * dblA26 * dblA8; txtReserveRAM.Text = dblD8.ToString(); // =A29*A26*A8 double dblD9 = dblA10 + dblA8; dblD9 = dblA30 * dblA25 * dblD9; txtReserveDisk.Text = dblD9.ToString(); // =A30*A25*(A10+A8) // Expansion double dblD12 = dblA3 * 17.00; dblD12 = dblD2 - dblD7 - dblD12; dblD12 = dblD12 / dblD2; dblD12 = dblD12 * dblA4; dblD12 = Math.Floor(dblD12); txtExpandCPU.Text = dblD12.ToString(); // =INT((D2-D7-(A3*17))/D2*A4) double dblD13 = dblA3 * 13.00; dblD13 = dblD3 - dblD8 - dblD13; dblD13 = dblD13 / dblD3; dblD13 = dblD13 * dblA5; dblD13 = Math.Floor(dblD13); txtExpandRAM.Text = dblD13.ToString(); // =INT((D3-D8-(A3*13))/D3*A5) double dblD14 = dblA20 * dblA21; dblD14 = dblD14 / 100.00; dblD14 = dblD14 - dblD9; dblD14 = dblD14 / dblA20; dblD14 = dblD14 * 100.00; dblD14 = Math.Floor(dblD14); txtExpandDisk.Text = dblD14.ToString(); // =INT(((A20*A21/100)-D9)/A20*100) btnDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this item?');"); btnModel.Attributes.Add("onclick", "return OpenWindow('SUBMODELBROWSER','" + hdnModel.ClientID + "','&control=" + hdnModel.ClientID + "&controltext=" + lblModel.ClientID + "',false,400,600);"); btnOS.Attributes.Add("onclick", "return OpenWindow('VMWARE_OS','','" + intID.ToString() + "',false,'650',500);"); } else if (intID == 0) { trCapacity.Visible = true; chkQuery.Checked = true; chkQuery.Enabled = false; btnOS.Enabled = false; } } else if (Request.QueryString["folderid"] != null) { int intFolder = Int32.Parse(Request.QueryString["folderid"]); int intDatacenter = Int32.Parse(oVMWare.GetFolder(intFolder, "datacenterid")); LoadFolders(intDatacenter); ddlParent.SelectedValue = intFolder.ToString(); panAdd.Visible = true; trCapacity.Visible = false; chkQuery.Checked = true; chkQuery.Enabled = false; btnOS.Enabled = false; } else { LoadVirtualCenters(); } }
protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); intProfile = Int32.Parse(Request.Cookies["profileid"].Value); if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "") { intPage = Int32.Parse(Request.QueryString["pageid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } oPage = new Pages(intProfile, dsn); oVMWare = new VMWare(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); if (!IsPostBack) { if (String.IsNullOrEmpty(Request.QueryString["tid"]) == false) { int tid = 0; if (Int32.TryParse(Request.QueryString["tid"], out tid) == true) { if (tid == 70) // VMWare { if (String.IsNullOrEmpty(Request.QueryString["ds"]) == false) { DataSet rec = oVMWare.GetDatastore(Int32.Parse(Request.QueryString["ds"])); if (rec.Tables[0].Rows.Count > 0) { lblDSParent.ToolTip = rec.Tables[0].Rows[0]["clusterid"].ToString(); lblDSParent.Text = oVMWare.GetCluster(Int32.Parse(lblDSParent.ToolTip), "name"); lblDSName.Text = rec.Tables[0].Rows[0]["name"].ToString(); ddlType.Text = rec.Tables[0].Rows[0]["storage_type"].ToString(); ddlOperatingSystemGroup.Text = rec.Tables[0].Rows[0]["osgroupid"].ToString(); chkReplicated.Text = rec.Tables[0].Rows[0]["replicated"].ToString(); txtDSMaximum.Text = rec.Tables[0].Rows[0]["maximum"].ToString(); chkServer.Text = rec.Tables[0].Rows[0]["server"].ToString(); chkPagefile.Text = rec.Tables[0].Rows[0]["pagefile"].ToString(); chkOverridePermission.Text = rec.Tables[0].Rows[0]["override_permission"].ToString(); ddlPartner.Text = rec.Tables[0].Rows[0]["partner"].ToString(); chkDSEnabled.Text = rec.Tables[0].Rows[0]["enabled"].ToString(); btnUpdateDS.Text = "Update"; panDS.Visible = true; } } else if (String.IsNullOrEmpty(Request.QueryString["h"]) == false) { DataSet rec = oVMWare.GetHost(Int32.Parse(Request.QueryString["h"])); if (rec.Tables[0].Rows.Count > 0) { lblHParent.ToolTip = rec.Tables[0].Rows[0]["clusterid"].ToString(); lblHParent.Text = oVMWare.GetCluster(Int32.Parse(lblHParent.ToolTip), "name"); lblHName.Text = rec.Tables[0].Rows[0]["name"].ToString(); txtHMaximum.Text = rec.Tables[0].Rows[0]["maximum"].ToString(); chkHEnabled.Text = rec.Tables[0].Rows[0]["enabled"].ToString(); btnUpdateH.Text = "Update"; panH.Visible = true; } } else if (String.IsNullOrEmpty(Request.QueryString["c"]) == false) { DataSet rec = oVMWare.GetCluster(Int32.Parse(Request.QueryString["c"])); if (rec.Tables[0].Rows.Count > 0) { int folder = Int32.Parse(rec.Tables[0].Rows[0]["folderid"].ToString()); int datacenter = Int32.Parse(oVMWare.GetFolder(folder, "datacenterid")); lblCParent.ToolTip = folder.ToString(); lblCParent.Text = oVMWare.GetFolder(folder, "name"); lblCName.Text = rec.Tables[0].Rows[0]["name"].ToString(); ddlVersion.Text = rec.Tables[0].Rows[0]["version"].ToString(); ddlAntiAffinity.Text = rec.Tables[0].Rows[0]["anti_affinity"].ToString(); txtCMaximum.Text = rec.Tables[0].Rows[0]["maximum"].ToString(); txtResourcePool.Text = rec.Tables[0].Rows[0]["resource_pool"].ToString(); txtDatastoreNotify.Text = rec.Tables[0].Rows[0]["datastores_notify"].ToString(); txtDatastoreLeft.Text = rec.Tables[0].Rows[0]["datastores_left"].ToString(); txtDatastoreSize.Text = rec.Tables[0].Rows[0]["datastores_size"].ToString(); chkFull.Text = rec.Tables[0].Rows[0]["at_max"].ToString(); chkAPoff.Text = rec.Tables[0].Rows[0]["auto_provision_off"].ToString(); chkAPoffDR.Text = rec.Tables[0].Rows[0]["auto_provision_dr_off"].ToString(); chkDell.Text = rec.Tables[0].Rows[0]["dell"].ToString(); ddlResiliency.Text = rec.Tables[0].Rows[0]["resiliencyid"].ToString(); chkOracle.Text = rec.Tables[0].Rows[0]["can_oracle"].ToString(); chkOracleCluster.Text = rec.Tables[0].Rows[0]["can_oracle_cluster"].ToString(); chkSQL.Text = rec.Tables[0].Rows[0]["can_sql"].ToString(); chkSQLCluster.Text = rec.Tables[0].Rows[0]["can_sql_cluster"].ToString(); chkCluster.Text = rec.Tables[0].Rows[0]["can_cluster"].ToString(); chkCEnabled.Text = rec.Tables[0].Rows[0]["enabled"].ToString(); // Calculations double dblA3 = 0.00; double dblA4 = 0.00; double dblA5 = 0.00; double dblA8 = 0.00; double dblA10 = 0.00; double dblA20 = 0.00; double dblA21 = 0.00; double dblA22 = 0.00; double dblA25 = 0.00; double dblA26 = 0.00; double dblA29 = 0.00; double dblA30 = 0.00; if (rec.Tables[0].Rows[0]["input_failures"].ToString() != "") { dblA3 = double.Parse(rec.Tables[0].Rows[0]["input_failures"].ToString()); } txtFailures.Text = dblA3.ToString(); if (rec.Tables[0].Rows[0]["input_cpu_utilization"].ToString() != "") { dblA4 = double.Parse(rec.Tables[0].Rows[0]["input_cpu_utilization"].ToString()); } txtCPUUtilization.Text = dblA4.ToString(); if (rec.Tables[0].Rows[0]["input_ram_utilization"].ToString() != "") { dblA5 = double.Parse(rec.Tables[0].Rows[0]["input_ram_utilization"].ToString()); } txtRAMUtilization.Text = dblA5.ToString(); if (rec.Tables[0].Rows[0]["input_max_ram"].ToString() != "") { dblA8 = double.Parse(rec.Tables[0].Rows[0]["input_max_ram"].ToString()); } txtMaxRAM.Text = dblA8.ToString(); if (rec.Tables[0].Rows[0]["input_avg_utilization"].ToString() != "") { dblA10 = double.Parse(rec.Tables[0].Rows[0]["input_avg_utilization"].ToString()); } txtAvgUtilization.Text = dblA10.ToString(); if (rec.Tables[0].Rows[0]["input_lun_size"].ToString() != "") { dblA20 = double.Parse(rec.Tables[0].Rows[0]["input_lun_size"].ToString()); } txtLunSize.Text = dblA20.ToString(); if (rec.Tables[0].Rows[0]["input_lun_utilization"].ToString() != "") { dblA21 = double.Parse(rec.Tables[0].Rows[0]["input_lun_utilization"].ToString()); } txtLunUtilization.Text = dblA21.ToString(); if (rec.Tables[0].Rows[0]["input_vms_per_lun"].ToString() != "") { dblA22 = double.Parse(rec.Tables[0].Rows[0]["input_vms_per_lun"].ToString()); } txtVMsPerLun.Text = dblA22.ToString(); if (rec.Tables[0].Rows[0]["input_time_lun"].ToString() != "") { dblA25 = double.Parse(rec.Tables[0].Rows[0]["input_time_lun"].ToString()); } txtTimeLUN.Text = dblA25.ToString(); if (rec.Tables[0].Rows[0]["input_time_cluster"].ToString() != "") { dblA26 = double.Parse(rec.Tables[0].Rows[0]["input_time_cluster"].ToString()); } txtTimeCluster.Text = dblA26.ToString(); if (rec.Tables[0].Rows[0]["input_max_vms_server"].ToString() != "") { dblA29 = double.Parse(rec.Tables[0].Rows[0]["input_max_vms_server"].ToString()); } txtMaxVMsServer.Text = dblA29.ToString(); if (rec.Tables[0].Rows[0]["input_max_vms_lun"].ToString() != "") { dblA30 = double.Parse(rec.Tables[0].Rows[0]["input_max_vms_lun"].ToString()); } txtMaxVMsLUN.Text = dblA30.ToString(); double dblA13 = 0.00; double dblA14 = 0.00; double dblA15 = 0.00; double dblA16 = 0.00; int intModel = Int32.Parse(rec.Tables[0].Rows[0]["modelid"].ToString()); DataSet dsModel = oModelsProperties.Get(intModel); if (dsModel.Tables[0].Rows.Count > 0) { //lblModel.Text = dsModel.Tables[0].Rows[0]["name"].ToString(); dblA13 = double.Parse(dsModel.Tables[0].Rows[0]["ram"].ToString()); dblA14 = double.Parse(dsModel.Tables[0].Rows[0]["cpu_count"].ToString()); dblA15 = 1.00; dblA16 = double.Parse(dsModel.Tables[0].Rows[0]["cpu_speed"].ToString()); } txtRAM.Text = dblA13.ToString(); txtCores.Text = dblA14.ToString(); txtCPUs.Text = dblA15.ToString(); txtProcs.Text = dblA16.ToString(); double dblA17 = dblA14 * dblA15 * dblA16; // =A14*A15*A16 txtTotal.Text = dblA17.ToString(); double dblA2 = 0.00; //if (Request.QueryString["query"] != null) //{ // Get # of hosts from cluster int intVirtualCenter = Int32.Parse(oVMWare.GetDatacenter(datacenter, "virtualcenterid")); string strVirtualCenter = oVMWare.GetVirtualCenter(intVirtualCenter, "name"); string strConnect = oVMWare.ConnectDEBUG(oVMWare.GetVirtualCenter(intVirtualCenter, "url"), Int32.Parse(oVMWare.GetVirtualCenter(intVirtualCenter, "environment")), oVMWare.GetDatacenter(datacenter, "name")); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference[] hostRefs = oVMWare.GetHosts(lblCName.Text); dblA2 = double.Parse(hostRefs.Length.ToString()); if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } else { dblA2 = -1.00; } //} //else // dblA2 = -1.00; txtServers.Text = dblA2.ToString(); // Maximum CPU allocated double dblA9 = dblA13 * dblA8; dblA9 = dblA17 / dblA9; txtMaxCPU.Text = dblA9.ToString(); // =A17/A13*A8 // Total CPU & RAM double dblD2 = dblA2 * dblA17; txtTotalCPU.Text = dblD2.ToString(); // =A2*A17 double dblD3 = dblA2 * dblA13; txtTotalRAM.Text = dblD3.ToString(); // =A2*A13 // Reserves double dblD7 = dblA29 * dblA26 * dblA9; txtReserveCPU.Text = dblD7.ToString(); // =A29*A26*A9 double dblD8 = dblA29 * dblA26 * dblA8; txtReserveRAM.Text = dblD8.ToString(); // =A29*A26*A8 double dblD9 = dblA10 + dblA8; dblD9 = dblA30 * dblA25 * dblD9; txtReserveDisk.Text = dblD9.ToString(); // =A30*A25*(A10+A8) // Expansion double dblD12 = dblA3 * 17.00; dblD12 = dblD2 - dblD7 - dblD12; dblD12 = dblD12 / dblD2; dblD12 = dblD12 * dblA4; dblD12 = Math.Floor(dblD12); txtExpandCPU.Text = dblD12.ToString(); // =INT((D2-D7-(A3*17))/D2*A4) double dblD13 = dblA3 * 13.00; dblD13 = dblD3 - dblD8 - dblD13; dblD13 = dblD13 / dblD3; dblD13 = dblD13 * dblA5; dblD13 = Math.Floor(dblD13); txtExpandRAM.Text = dblD13.ToString(); // =INT((D3-D8-(A3*13))/D3*A5) double dblD14 = dblA20 * dblA21; dblD14 = dblD14 / 100.00; dblD14 = dblD14 - dblD9; dblD14 = dblD14 / dblA20; dblD14 = dblD14 * 100.00; dblD14 = Math.Floor(dblD14); txtExpandDisk.Text = dblD14.ToString(); // =INT(((A20*A21/100)-D9)/A20*100) btnUpdateC.Text = "Update"; panC.Visible = true; } } else if (String.IsNullOrEmpty(Request.QueryString["f"]) == false) { DataSet rec = oVMWare.GetFolder(Int32.Parse(Request.QueryString["f"])); if (rec.Tables[0].Rows.Count > 0) { lblFParent.ToolTip = rec.Tables[0].Rows[0]["datacenterid"].ToString(); lblFParent.Text = oVMWare.GetDatacenter(Int32.Parse(lblFParent.ToolTip), "name"); lblFName.Text = rec.Tables[0].Rows[0]["name"].ToString(); txtFNotification.Text = rec.Tables[0].Rows[0]["notification"].ToString(); chkFEnabled.Text = rec.Tables[0].Rows[0]["enabled"].ToString(); btnUpdateF.Text = "Update"; panF.Visible = true; } } else { panNone.Visible = true; } } else { panNone.Visible = true; } } else { panNone.Visible = true; } } else { panNone.Visible = true; } } }