Exemple #1
0
        public static bool AddNIC(this ManagementObject VM, string VirtualSwitch = null, bool Legacy = false)
        {
            // Sanity Check
            if (VM == null || !VM["__CLASS"].ToString().Equals(VMStrings.ComputerSystem, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            ManagementScope  scope = GetScope(VM);
            ManagementObject NIC   = VM.NewResource(ResourceTypes.EthernetAdapter,
                                                    (Legacy ? ResourceSubTypes.LegacyNIC : ResourceSubTypes.SyntheticNIC),
                                                    scope);

            NIC["ElementName"] = (Legacy ? "Legacy " : "") + "Network Adapter";
            if (!Legacy)
            {
                NIC["VirtualSystemIdentifiers"] = new string[] { Guid.NewGuid().ToString("B") }
            }
            ;
            if (VirtualSwitch != null)
            {
                ManagementObject Switch =
                    new ManagementObjectSearcher(scope,
                                                 new SelectQuery(VMStrings.VirtualSwitch,
                                                                 "ElementName like '" + VirtualSwitch + "'")).Get().Cast
                    <ManagementObject>().FirstOrDefault();
                if (Switch == null)
                {
                    NIC.Delete();
                    return(false);
                }

                string           PortGUID  = Guid.NewGuid().ToString();
                ManagementObject SwitchSvc = GetServiceObject(scope, ServiceNames.SwitchManagement);
                var inputs = SwitchSvc.GetMethodParameters("CreateSwitchPort");
                inputs["VirtualSwitch"]    = Switch.Path.Path;
                inputs["Name"]             = inputs["FriendlyName"] = PortGUID;
                inputs["ScopeOfResidence"] = String.Empty;
                var ret = SwitchSvc.InvokeMethod("CreateSwitchPort", inputs, null);
                if (int.Parse(ret["ReturnValue"].ToString()) != (int)ReturnCodes.OK)
                {
                    NIC.Delete();
                    return(false);
                }
                NIC["Connection"] = new string[] { GetObject(ret["CreatedSwitchPort"].ToString()).Path.Path };
            }
            return(VM.AddDevice(NIC) != null);
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="VM"></param>
        /// <param name="SourceVHD"></param>
        /// <param name="ControllerDevice">Controller device to attach to.  If null, will attach to first available contoller discovered on VM.</param>
        /// <param name="ControllerAddress">Assign VHD to this address on the Controller Device.</param>
        /// <returns></returns>
        public static bool AttachVHD(this ManagementObject VM, string SourceVHD, ManagementObject ControllerDevice = null, int ControllerAddress = -1)
        {
            switch (VM["__CLASS"].ToString().ToUpperInvariant())
            {
            case "MSVM_COMPUTERSYSTEM":
                ControllerDevice = ControllerDevice ??
                                   (VM.GetDevices()
                                    .Where(
                                        device =>
                                        device["ResourceSubType"].ToString()
                                        .Equals(ResourceSubTypes.ControllerIDE)
                                        ||
                                        device["ResourceSubType"].ToString()
                                        .Equals(ResourceSubTypes.ControllerSCSI))).Where(each =>
                {
                    var drives =
                        VM.GetDevices()
                        .Where(
                            dev =>
                            ushort.Parse(dev["ResourceType"].ToString()) ==
                            (ushort)ResourceTypes.Disk &&
                            String.Equals(dev["Parent"].ToString(), each.Path.Path));
                    return
                    (each["ResourceSubType"].ToString()
                     .Equals(ResourceSubTypes.ControllerIDE)
                                                           ? drives.Count() < 2
                                                           : drives.Count() < 64);
                })
                                   .FirstOrDefault();
                if (ControllerDevice == null)
                {
                    return(false);     // Could not locate an open controller to attach to.
                }
                // Locate the address on the controller we need to assign to...
                IEnumerable <ManagementObject> set;
                ControllerAddress = ControllerAddress >= 0
                                            ? ControllerAddress
                                            : (set = (VM.GetDevices().Where(each => (ushort)each["ResourceType"] == (ushort)ResourceTypes.Disk &&
                                                                            String.Equals(each["Parent"].ToString(), ControllerDevice.Path.Path))
                                                      .OrderBy(each => int.Parse(each["Address"].ToString())))).Any()
                                                                   ? Task <int> .Factory.StartNew(() =>
                {
                    var set2 = set.ToArray();
                    if (
                        int.Parse(
                            set.Last()["Address"].ToString()) ==
                        set.Count() - 1)
                    {
                        return(set.Count());
                    }
                    for (int i = 0; i < set2.Length; i++)
                    {
                        if (
                            int.Parse(
                                set2[i]["Address"].ToString()) >
                            i)
                        {
                            return(i);
                        }
                    }
                    return(set2.Length);
                }, TaskCreationOptions.AttachedToParent).Result
                                    //int.Parse(set.Last()["Address"].ToString()) + 1
                                                                   : 0;



                // Need to add a Synthetic Disk Drive to connect the vhd to...
                ManagementObject SynDiskDefault = VM.NewResource(ResourceTypes.Disk, ResourceSubTypes.SyntheticDisk);
                SynDiskDefault["Parent"]  = ControllerDevice.Path.Path;
                SynDiskDefault["Address"] = ControllerAddress;
                SynDiskDefault["Limit"]   = 1;
                var SynDisk = VM.AddDevice(SynDiskDefault);
                if (SynDisk == null)
                {
                    return(false);
                }


                ManagementObject drive = VM.NewResource(ResourceTypes.StorageExtent, ResourceSubTypes.VHD);
                drive["Connection"] = new string[] { SourceVHD };
                drive["Parent"]     = SynDisk.Path.Path;
                var ret = VM.AddDevice(drive);
                return(ret != null);

            default:
                return(false);
            }
        }