Ejemplo n.º 1
0
        public void queryMemoryOverhead()
        {
            _service = ecb.getConnection().Service;
            _sic     = ecb.getConnection().ServiceContent;

            ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url"));
            String    hostname          = ecb.get_option("hostname");
            ManagedObjectReference hmor =
                ecb.getServiceUtil().GetDecendentMoRef(null, "HostSystem", hostname);

            if (hmor != null)
            {
                if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5"))
                {
                    VirtualMachineConfigInfo vmConfigInfo =
                        new VirtualMachineConfigInfo();
                    vmConfigInfo.changeVersion = "1";
                    DateTime dt = ecb.getConnection().Service.CurrentTime(ecb.getConnection().ServiceRef);
                    vmConfigInfo.modified = dt;

                    VirtualMachineDefaultPowerOpInfo defaultInfo
                        = new VirtualMachineDefaultPowerOpInfo();
                    vmConfigInfo.defaultPowerOps = defaultInfo;

                    VirtualMachineFileInfo fileInfo
                        = new VirtualMachineFileInfo();
                    vmConfigInfo.files = fileInfo;

                    VirtualMachineFlagInfo flagInfo
                        = new VirtualMachineFlagInfo();
                    vmConfigInfo.flags = flagInfo;

                    vmConfigInfo.guestFullName = "Full Name";
                    vmConfigInfo.guestId       = "Id";

                    VirtualHardware vhardware
                        = new VirtualHardware();
                    vhardware.memoryMB    = int.Parse(ecb.get_option("memorysize"));
                    vhardware.numCPU      = int.Parse(ecb.get_option("cpucount"));
                    vmConfigInfo.hardware = vhardware;

                    // Not Required For Computing The Overhead
                    vmConfigInfo.name               = "OnlyFoeInfo";
                    vmConfigInfo.uuid               = "12345678-abcd-1234-cdef-123456789abc";
                    vmConfigInfo.version            = "First";
                    vmConfigInfo.template           = false;
                    vmConfigInfo.alternateGuestName = "Alternate";

                    long overhead
                        = ecb._connection._service.QueryMemoryOverheadEx(
                              hmor, vmConfigInfo);
                    Console.WriteLine("Using queryMemoryOverheadEx API using vmReconfigInfo");
                    Console.WriteLine("Memory overhead necessary to "
                                      + "poweron a virtual machine with memory "
                                      + ecb.get_option("memorysize")
                                      + " MB and cpu count "
                                      + ecb.get_option("cpucount")
                                      + " -: " + overhead + " bytes");
                }
                else
                {
                    long overhead
                        = ecb._connection._service.QueryMemoryOverhead(hmor,
                                                                       long.Parse(ecb.get_option("memorysize")), 0, false,
                                                                       int.Parse(ecb.get_option("cpucount"))
                                                                       );
                    Console.WriteLine("Using queryMemoryOverhead API "
                                      + "using CPU count and Memory Size");
                    Console.WriteLine("Memory overhead necessary to "
                                      + "poweron a virtual machine with memory "
                                      + ecb.get_option("memorysize")
                                      + " MB and cpu count "
                                      + ecb.get_option("cpucount")
                                      + " -: " + overhead + " bytes");
                }
            }
            else
            {
                Console.WriteLine("Host " + ecb.get_option("hostname") + " not found");
            }
        }
Ejemplo n.º 2
0
        public static int MainFindVM(MainSearchVM_In inParam, MainSearchVM_Out outRet)
        {
            VmSummaryInfo vmSummaryInfo = new VmSummaryInfo();

            System.Net.ServicePointManager.Expect100Continue = false;

            MyCertVerify certVerify = new MyCertVerify();

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                certVerify.RemoteCertificateValidationCallback;

            BasicHttpBinding binding = null;

            if (string.Compare("https", inParam.Protocal, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
                {
                    AllowCookies           = true,
                    OpenTimeout            = TimeSpan.FromHours(1),
                    ReceiveTimeout         = TimeSpan.FromHours(1),
                    SendTimeout            = TimeSpan.FromHours(1),
                    CloseTimeout           = TimeSpan.FromHours(1),
                    MaxBufferPoolSize      = 1024 * 1024 * 2,
                    MaxReceivedMessageSize = 1024 * 512,
                    MaxBufferSize          = 1024 * 512
                };
            }
            else
            {
                binding = new BasicHttpBinding()
                {
                    AllowCookies           = true,
                    OpenTimeout            = TimeSpan.FromHours(1),
                    ReceiveTimeout         = TimeSpan.FromHours(1),
                    SendTimeout            = TimeSpan.FromHours(1),
                    CloseTimeout           = TimeSpan.FromHours(1),
                    MaxBufferPoolSize      = 1024 * 1024 * 2,
                    MaxReceivedMessageSize = 1024 * 512,
                    MaxBufferSize          = 1024 * 512
                };
            }

            string          sdkUrl = string.Format("{0}://{1}{2}/sdk", inParam.Protocal, inParam.ServerName, 0 == inParam.Port ? "" : ":" + inParam.Port.ToString());
            EndpointAddress epa    = new EndpointAddress(sdkUrl);

            vmSummaryInfo.VmHost.ServerName = inParam.ServerName;
            vmSummaryInfo.VmHost.UserName   = inParam.User;
            vmSummaryInfo.VmHost.Password   = inParam.Password;
            vmSummaryInfo.VmHost.Port       = inParam.Port;


            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (var vimClient = new VimPortTypeClient(binding, epa))
            {
                //var serviceCertificate = vimClient.ClientCredentials.ServiceCertificate;
                //serviceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
                //serviceCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator(null);
                //serviceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;

                //var clientCertificate = vimClient.ClientCredentials.ClientCertificate;

                try
                {
                    ManagedObjectReference morServiceInstance = new ManagedObjectReference()
                    {
                        @type = "ServiceInstance",
                        Value = "ServiceInstance"
                    };
                    ServiceContent sc = vimClient.RetrieveServiceContent(morServiceInstance);

                    vmSummaryInfo.VmHost.ThumbPrint = StaticHelpers.FormatThumbPrint(certVerify.Thumbprint);

                    sb.AppendFormat("{0}, {1}, {2}, {3}, {4}", epa.Uri, inParam.User, inParam.Password, vmSummaryInfo.VmHost.ThumbPrint, certVerify.Thumbprint);
                    sb.AppendLine();
                    //StaticHelpers.PrintServerAboutInfo(sb, sc.about);
                    sc.about.Dump(nameof(sc.about), sw, false);

                    Console.WriteLine("{0}", sb.ToString());
                    sb.Clear();


                    using (MyCollectionDisposable collectionDisposal = new MyCollectionDisposable())
                    {
                        UserSession userSession = vimClient.Login(sc.sessionManager, inParam.User, inParam.Password, null);
                        collectionDisposal.Add(() => vimClient.Logout(sc.sessionManager));

                        //bool bListAllVMs = false;
                        //if(bListAllVMs)
                        if (inParam.ToListAllVMs)
                        {
                            CListVMs listVMs = new CListVMs(vimClient, sc.propertyCollector);
                            listVMs.list_all_vms(sc);
                        }


                        VimPropCollector pc = new VimPropCollector(vimClient, sc.propertyCollector);

                        VimFinder vimFinder = new VimFinder(vimClient, sc.propertyCollector, sc.rootFolder);

                        List <ManagedObjectReference> morDatacenters = new List <ManagedObjectReference>();
                        vimFinder.FindDatacenters(morDatacenters);

                        foreach (var datacenter in morDatacenters)
                        {
                            try
                            {
                                ManagedObjectReference morVM = (ManagedObjectReference)vimClient.FindByDatastorePath(sc.searchIndex, datacenter, inParam.VmPath);
                                if (null != morVM)
                                {
                                    vmSummaryInfo.VmHost.VmxSpec = "moref=" + morVM.Value;

                                    VirtualMachineConfigInfo virtualMachineConfigInfo = (VirtualMachineConfigInfo)pc.Get(morVM, "config");
                                    //StaticHelpers.PrintMor(sb, morVM);
                                    morVM.Dump(nameof(morVM), sw, false);
                                    //StaticHelpers.PrintVMCI(sb, virtualMachineConfigInfo);
                                    StaticHelpers.PrintVirtualDisksBriefInfo(sb, virtualMachineConfigInfo, vmSummaryInfo.VmHost.CurrentDiskPath);
                                    virtualMachineConfigInfo.Dump(nameof(virtualMachineConfigInfo), sw, false);
                                    Console.WriteLine("{0}", sb.ToString());
                                    sb.Clear();

                                    VimSnapshotInfo si = new VimSnapshotInfo(vimClient, sc.propertyCollector, morVM, sb, vmSummaryInfo.Snapshots);
                                    si.Traverse();
                                    Console.WriteLine("{0}", sb.ToString());
                                    sb.Clear();

                                    //datastore ManagedObjectReference:Datastore[] datastore-983 (datastore_on_30_1T)
                                    var datastore = (ManagedObjectReference[])pc.Get(morVM, "datastore");
                                    if (null != datastore)
                                    {
                                        var datastoreName = from item in datastore
                                                            select new { Datastore = item, DatastoreName = (string)pc.Get(item, "name") };
                                        foreach (var item in datastoreName)
                                        {
                                            sb.AppendLine();
                                            //StaticHelpers.PrintMor(sb, item.Datastore);
                                            item.Datastore.Dump(nameof(item.Datastore), sw, false);
                                            sb.AppendFormat("{0}\t\"{1}\"", nameof(item.DatastoreName), item.DatastoreName);
                                            sb.AppendLine();
                                        }
                                    }
                                    //guest GuestInfo guest
                                    var guest = (GuestInfo)pc.Get(morVM, "guest");
                                    //StaticHelpers.PrintGuestInfo(sb, guest);
                                    guest.Dump(nameof(guest), sw, false);
                                    //layout VirtualMachineFileLayout layout
                                    var layout = (VirtualMachineFileLayout)pc.Get(morVM, "layout");
                                    //StaticHelpers.PrintVirtualMachineFileLayout(sb, layout);
                                    layout.Dump(nameof(layout), sw, false);
                                    //layoutEx VirtualMachineFileLayoutEx layoutEx
                                    var layoutEx = (VirtualMachineFileLayoutEx)pc.Get(morVM, "layoutEx");
                                    //StaticHelpers.PrintVirtualMachineFileLayoutEx(sb, layoutEx);
                                    layoutEx.Dump(nameof(layoutEx), sw, false);
                                    //name string "shuli02-vc60"
                                    var name = (string)pc.Get(morVM, "name");
                                    sb.AppendFormat("{0}\t\"{1}\"", nameof(name), name);
                                    //network ManagedObjectReference:Network[] network-822(VM Network)
                                    var network = (ManagedObjectReference[])pc.Get(morVM, "network");
                                    if (null != network)
                                    {
                                        foreach (var Network in network)
                                        {
                                            //StaticHelpers.PrintMor(sb, Network);
                                            Network.Dump(nameof(Network), sw, false);
                                        }
                                    }

                                    //parent ManagedObjectReference:Folder group-v3 (vm)
                                    var parent = (ManagedObjectReference)pc.Get(morVM, "parent");
                                    //StaticHelpers.PrintMor(sb, parent);
                                    parent.Dump(nameof(parent), sw, false);

                                    //resourceConfig ResourceConfigSpec resourceConfig
                                    var resourceConfig = (ResourceConfigSpec)pc.Get(morVM, "resourceConfig");
                                    //StaticHelpers.PrintResourceConfigSpec(sb, resourceConfig);
                                    resourceConfig.Dump(nameof(resourceConfig), sw, false);

                                    //resourcePool ManagedObjectReference:ResourcePool resgroup-980 (VC)
                                    var resourcePool = (ManagedObjectReference)pc.Get(morVM, "resourcePool");
                                    //StaticHelpers.PrintMor(sb, resourcePool);
                                    resourcePool.Dump(nameof(resourcePool), sw, false);

                                    //runtime VirtualMachineRuntimeInfo runtime
                                    var runtime = (VirtualMachineRuntimeInfo)pc.Get(morVM, "runtime");
                                    //StaticHelpers.PrintVirtualMachineRuntimeInfo(sb, runtime);
                                    runtime.Dump(nameof(runtime), sw, false);

                                    string runtimeHostName = (string)pc.Get(runtime.host, "name");
                                    ManagedObjectReference morRuntimehostParent = (ManagedObjectReference)pc.Get(runtime.host, "parent");
                                    string runtimeHostParentName = (string)pc.Get(morRuntimehostParent, "name");
                                    //StaticHelpers.PrintMor(sb, runtime.host);
                                    runtime.host.Dump(nameof(runtime.host), sw, false);
                                    sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostName), runtimeHostName); sb.AppendLine();
                                    sb.AppendLine();
                                    //StaticHelpers.PrintMor(sb, morRuntimehostParent);
                                    morRuntimehostParent.Dump(nameof(morRuntimehostParent), sw, false);
                                    sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostParentName), runtimeHostParentName); sb.AppendLine();
                                    sb.AppendLine();

                                    //storage VirtualMachineStorageInfo storage
                                    var storage = (VirtualMachineStorageInfo)pc.Get(morVM, "storage");
                                    //StaticHelpers.PrintVirtualMachineStorageInfo(sb, storage);
                                    storage.Dump(nameof(storage), sw, false);
                                    Console.WriteLine("{0}", sb.ToString());
                                    sb.Clear();

                                    //summary VirtualMachineSummary summary
                                    var summary = (VirtualMachineSummary)pc.Get(morVM, "summary");
                                    //StaticHelpers.PrintVirtualMachineSummary(sb, summary);
                                    summary.Dump(nameof(summary), sw, false);


                                    Console.WriteLine("{0}", sb.ToString());
                                    sb.Clear();

                                    /////////////////////////////////////////////////////////////////////////////////////////////
                                    sb.Append('~', 80); sb.AppendLine();
                                    sb.Append('~', 80); sb.AppendLine();
                                    vmSummaryInfo.Dump(nameof(vmSummaryInfo), sw, false);
                                    sb.Append('~', 80); sb.AppendLine();
                                    sb.Append('~', 80); sb.AppendLine();
                                    Console.WriteLine("{0}", sb.ToString());
                                    sb.Clear();

                                    /////////////////////////////////////////////////////////////////////////////////////////////
                                    bool testVmOperation = false;
                                    if (testVmOperation)
                                    {
                                        try
                                        {
                                            MyVMOperation vmop = new MyVMOperation(vimClient, sc.propertyCollector, morVM);

                                            TaskInfoState state = vmop.ConsolidateVMDisks();

                                            string snapshotid1 = null;
                                            state = vmop.CreateSnapshot("test snapshot name 1", "test snapshot description1 ", false, true, out snapshotid1);
                                            VirtualDisk[] VirtualDisks1 = vmop.QuerySnapshotVirtualDisks(snapshotid1);


                                            string snapshotid2 = null;
                                            state = vmop.CreateSnapshot("test snapshot name 2", "test snapshot description2 ", false, true, out snapshotid2);
                                            VirtualDisk[] VirtualDisks2 = vmop.QuerySnapshotVirtualDisks(snapshotid2);



                                            try
                                            {
                                                foreach (var vdisk in VirtualDisks1)
                                                {
                                                    long startOffset = 0;
                                                    long diskSize    = vdisk.capacityInBytes == 0 ? vdisk.capacityInKB * 1024 : vdisk.capacityInBytes;
                                                    while (startOffset < diskSize)
                                                    {
                                                        DiskChangeInfo diskChangeInfo = vmop.QueryChangedDiskAreas(snapshotid2, vdisk, startOffset);
                                                        if (null != diskChangeInfo.changedArea)
                                                        {
                                                            foreach (var changedArea in diskChangeInfo.changedArea)
                                                            {
                                                                changedArea.Dump(nameof(changedArea), sw, false);
                                                            }
                                                            Console.WriteLine("{0}", sb.ToString());
                                                            sb.Clear();
                                                        }
                                                        startOffset = diskChangeInfo.startOffset + diskChangeInfo.length;
                                                    }
                                                }
                                            }
                                            catch (Exception exQueryChangedDiskAreas)
                                            {
                                                StaticHelpers.PrintException(exQueryChangedDiskAreas, 0);
                                            }

                                            state = vmop.RemoveSnapshot(snapshotid2, false, true);
                                            state = vmop.RemoveSnapshot(snapshotid1, false, true);
                                        }
                                        catch (Exception exTestVmOperation)
                                        {
                                            StaticHelpers.PrintException(exTestVmOperation, 0);
                                        }
                                    }

                                    /////////////////////////////////////////////////////////////////////////////////////////////
                                    bool testGustOp = false;
                                    if (testGustOp)
                                    {
                                        try
                                        {
                                            string            guestUser     = "******";
                                            string            guestPassword = "******";
                                            VimGuestOperation vimGuestOp    = new VimGuestOperation(vimClient, sc.propertyCollector, sc.guestOperationsManager, morVM, guestUser, guestPassword);

                                            string[] vars = vimGuestOp.ReadEnvironmentVariableInGuest(new string[] { "path" });

                                            GuestProgramSpec guestProgramSpec = new GuestProgramSpec()
                                            {
                                                programPath      = @"c:\Windows\notepad.exe",
                                                arguments        = "",
                                                workingDirectory = @"c:\",
                                                envVariables     = null
                                            };
                                            long pid = vimGuestOp.StartProgramInGuest(guestProgramSpec);
                                            GuestProcessInfo[] gpi = vimGuestOp.ListProcessesInGuest(new long[] { pid });
                                            vimGuestOp.TerminateProcessInGuest(pid);


                                            string guestFilePath = @"E:\1.vhdx";
                                            string localFile     = @"E:\~temp\1.vhdx";
                                            vimGuestOp.FileTransferFromGuest(guestFilePath, localFile);
                                            string guestFilePath2 = @"e:\111\1.vhdx";
                                            vimGuestOp.FileTransferToGuest(guestFilePath2, localFile, true);
                                        }
                                        catch (Exception exGust)
                                        {
                                            StaticHelpers.PrintException(exGust, 0);
                                        }
                                    }
                                }
                            }
                            catch (Exception exFind)
                            {
                                StaticHelpers.PrintException(exFind, 0);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    StaticHelpers.PrintException(ex, 0);
                }
            }

            return(0);
        }
Ejemplo n.º 3
0
        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");
            }
        }
Ejemplo n.º 4
0
        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");
            }
        }
Ejemplo n.º 5
0
        private VirtualDeviceConfigSpec getDiskDeviceConfigSpec()
        {
            String ops = cb.get_option("operation");
            VirtualDeviceConfigSpec  diskSpec = new VirtualDeviceConfigSpec();
            VirtualMachineConfigInfo vmConfigInfo
                = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(
                      _virtualMachine, "config");

            if (ops.Equals("add"))
            {
                VirtualDisk disk = new VirtualDisk();
                VirtualDiskFlatVer2BackingInfo diskfileBacking
                    = new VirtualDiskFlatVer2BackingInfo();
                String dsName
                    = getDataStoreName(int.Parse(cb.get_option("disksize")));

                int ckey       = -1;
                int unitNumber = 0;

                VirtualDevice [] test = vmConfigInfo.hardware.device;
                for (int k = 0; k < test.Length; k++)
                {
                    if (test[k].deviceInfo.label.Equals(
                            "SCSI Controller 0"))
                    {
                        ckey = test[k].key;
                    }
                }



                unitNumber = test.Length + 1;
                String fileName = "[" + dsName + "] " + cb.get_option("vmname")
                                  + "/" + cb.get_option("value") + ".vmdk";

                diskfileBacking.fileName = fileName;
                diskfileBacking.diskMode = cb.get_option("diskmode");

                disk.controllerKey          = ckey;
                disk.unitNumber             = unitNumber;
                disk.controllerKeySpecified = true;
                disk.unitNumberSpecified    = true;
                disk.backing = diskfileBacking;
                int size = 1024 * (int.Parse(cb.get_option("disksize")));
                disk.capacityInKB = size;
                disk.key          = 0;

                diskSpec.operation              = VirtualDeviceConfigSpecOperation.add;
                diskSpec.fileOperation          = VirtualDeviceConfigSpecFileOperation.create;
                diskSpec.fileOperationSpecified = true;
                diskSpec.operationSpecified     = true;
                diskSpec.device = disk;
            }
            else if (ops.Equals("remove"))
            {
                VirtualDisk disk = null;
                VirtualDiskFlatVer2BackingInfo diskfileBacking
                    = new VirtualDiskFlatVer2BackingInfo();

                VirtualDevice [] test = vmConfigInfo.hardware.device;
                for (int k = 0; k < test.Length; k++)
                {
                    if (test[k].deviceInfo.label.Equals(
                            cb.get_option("value")))
                    {
                        disk = (VirtualDisk)test[k];
                    }
                }
                if (disk != null)
                {
                    diskSpec.operation              = VirtualDeviceConfigSpecOperation.remove;
                    diskSpec.operationSpecified     = true;
                    diskSpec.fileOperation          = VirtualDeviceConfigSpecFileOperation.destroy;
                    diskSpec.fileOperationSpecified = true;
                    diskSpec.device = disk;
                }
                else
                {
                    Console.WriteLine("No device found " + cb.get_option("value"));
                    return(null);
                }
            }
            return(diskSpec);
        }
Ejemplo n.º 6
0
        private void reConfig()
        {
            String deviceType = cb.get_option("device");
            VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();

            if (deviceType.Equals("memory"))
            {
                Console.WriteLine("Reconfiguring The Virtual Machine For Memory Update "
                                  + cb.get_option("vmname"));
                try {
                    vmConfigSpec.memoryAllocation = getShares();
                }
                catch (Exception nfe) {
                    Console.WriteLine("Value of Memory update must "
                                      + "be either Custom or Integer");
                    return;
                }
            }
            else if (deviceType.Equals("cpu"))
            {
                Console.WriteLine("Reconfiguring The Virtual Machine For CPU Update "
                                  + cb.get_option("vmname"));
                try {
                    vmConfigSpec.cpuAllocation = getShares();
                }
                catch (Exception nfe) {
                    Console.WriteLine("Value of CPU update must "
                                      + "be either Custom or Integer");
                    return;
                }
            }
            else if (deviceType.Equals("disk"))
            {
                Console.WriteLine("Reconfiguring The Virtual Machine For Disk Update "
                                  + cb.get_option("vmname"));

                VirtualDeviceConfigSpec vdiskSpec = getDiskDeviceConfigSpec();
                if (vdiskSpec != null)
                {
                    VirtualMachineConfigInfo vmConfigInfo
                        = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(
                              _virtualMachine, "config");
                    int             ckey = -1;
                    VirtualDevice[] test = vmConfigInfo.hardware.device;
                    for (int k = 0; k < test.Length; k++)
                    {
                        if (test[k].deviceInfo.label.Equals(
                                "SCSI Controller 0"))
                        {
                            ckey = test[k].key;
                        }
                    }

                    if (ckey == -1)
                    {
                        int diskCtlrKey = 1;
                        VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec();
                        scsiCtrlSpec.operation          = VirtualDeviceConfigSpecOperation.add;
                        scsiCtrlSpec.operationSpecified = true;
                        VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController();
                        scsiCtrl.busNumber  = 0;
                        scsiCtrlSpec.device = scsiCtrl;
                        scsiCtrl.key        = diskCtlrKey;
                        scsiCtrl.sharedBus  = VirtualSCSISharing.physicalSharing;
                        String ctlrType = scsiCtrl.GetType().Name;
                        vdiskSpec.device.controllerKey = scsiCtrl.key;
                        VirtualDeviceConfigSpec[] vdiskSpecArray = { scsiCtrlSpec, vdiskSpec };
                        vmConfigSpec.deviceChange = vdiskSpecArray;
                    }
                    else
                    {
                        vdiskSpec.device.controllerKey = ckey;
                        VirtualDeviceConfigSpec[] vdiskSpecArray = { vdiskSpec };
                        vmConfigSpec.deviceChange = vdiskSpecArray;
                    }
                }
                else
                {
                    return;
                }
            }
            else if (deviceType.Equals("nic"))
            {
                Console.WriteLine("Reconfiguring The Virtual Machine For NIC Update "
                                  + cb.get_option("vmname"));
                VirtualDeviceConfigSpec nicSpec = getNICDeviceConfigSpec();
                if (nicSpec != null)
                {
                    VirtualDeviceConfigSpec [] nicSpecArray = { nicSpec };
                    vmConfigSpec.deviceChange = nicSpecArray;
                }
                else
                {
                    return;
                }
            }
            else if (deviceType.Equals("cd"))
            {
                Console.WriteLine("Reconfiguring The Virtual Machine For CD Update "
                                  + cb.get_option("vmname"));
                VirtualDeviceConfigSpec cdSpec = getCDDeviceConfigSpec();
                if (cdSpec != null)
                {
                    VirtualDeviceConfigSpec [] cdSpecArray = { cdSpec };
                    vmConfigSpec.deviceChange = cdSpecArray;
                }
                else
                {
                    return;
                }
            }
            else
            {
                Console.WriteLine("Invlaid device type [memory|cpu|disk|nic|cd]");
                return;
            }

            ManagedObjectReference tmor
                = cb.getConnection()._service.ReconfigVM_Task(
                      _virtualMachine, vmConfigSpec);

            monitorTask(tmor);
        }
       public void queryMemoryOverhead()
       {
           _service = ecb.getConnection().Service;
           _sic = ecb.getConnection().ServiceContent;

           ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url"));
           String hostname = ecb.get_option("hostname");
           ManagedObjectReference hmor =
              ecb.getServiceUtil().GetDecendentMoRef(null, "HostSystem", hostname);

           if (hmor != null)
           {
               if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5"))
               {
                   VirtualMachineConfigInfo vmConfigInfo =
                           new VirtualMachineConfigInfo();
                   vmConfigInfo.changeVersion = "1";
                   DateTime dt = ecb.getConnection().Service.CurrentTime(ecb.getConnection().ServiceRef);
                   vmConfigInfo.modified = dt;
                
                   VirtualMachineDefaultPowerOpInfo defaultInfo 
                      = new VirtualMachineDefaultPowerOpInfo();
                   vmConfigInfo.defaultPowerOps=defaultInfo;
           
                   VirtualMachineFileInfo fileInfo 
                      = new VirtualMachineFileInfo();
                   vmConfigInfo.files=fileInfo;
            
                   VirtualMachineFlagInfo flagInfo 
                      = new VirtualMachineFlagInfo();
                   vmConfigInfo.flags=flagInfo;
            
                   vmConfigInfo.guestFullName="Full Name";
                   vmConfigInfo.guestId="Id";
            
                   VirtualHardware vhardware 
                      = new VirtualHardware();
                   vhardware.memoryMB=int.Parse(ecb.get_option("memorysize"));
                   vhardware.numCPU=int.Parse(ecb.get_option("cpucount"));
                   vmConfigInfo.hardware=vhardware;
            
                   // Not Required For Computing The Overhead
                   vmConfigInfo.name="OnlyFoeInfo";
                   vmConfigInfo.uuid="12345678-abcd-1234-cdef-123456789abc";
                   vmConfigInfo.version="First";
                   vmConfigInfo.template=false;
                   vmConfigInfo.alternateGuestName="Alternate";
            
                   long overhead 
                      = ecb._connection._service.QueryMemoryOverheadEx(
                                             hmor,vmConfigInfo);      
                   Console.WriteLine("Using queryMemoryOverheadEx API using vmReconfigInfo");
                   Console.WriteLine("Memory overhead necessary to "
                                     + "poweron a virtual machine with memory " 
                                     + ecb.get_option("memorysize") 
                                     + " MB and cpu count " 
                                     + ecb.get_option("cpucount") 
                                     + " -: " + overhead + " bytes");
               }
               else
               {
                   long overhead
                      = ecb._connection._service.QueryMemoryOverhead(hmor,
                           long.Parse(ecb.get_option("memorysize")), 0, false,
                           int.Parse(ecb.get_option("cpucount"))
                        );
                   Console.WriteLine("Using queryMemoryOverhead API "
                                     + "using CPU count and Memory Size");
                   Console.WriteLine("Memory overhead necessary to "
                                      + "poweron a virtual machine with memory "
                                      + ecb.get_option("memorysize")
                                      + " MB and cpu count "
                                      + ecb.get_option("cpucount")
                                      + " -: " + overhead + " bytes");
               }
           }
           else
           {
               Console.WriteLine("Host " + ecb.get_option("hostname") + " not found");
           }
       }
Ejemplo n.º 8
0
        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    = "&quot;" + strHeader.ToUpper() + "&quot;";
                        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 += "&nbsp;&nbsp;&nbsp;[" + 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;
            }
        }