Example #1
0
        public void DeleteVm(IVm vm, DeleteVmOption deleteVmOption)
        {
            List <string> list = vm.GetVirtualDiskPaths().ToList <string>();

            vm.PowerOff();
            using (IVirtualSystemManagementService managmentService = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host))
            {
                using (vm)
                    managmentService.DestroySystem(((IVmInternals)vm).ComputerSystem);
            }
            if (deleteVmOption != DeleteVmOption.DeleteVhds)
            {
                return;
            }
            foreach (string path in list)
            {
                try
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
                catch (Exception ex)
                {
                    this._Logger.FormatWarningWithException(ex, "Unable to delete the file \"{0}\" due to: ", (object)path);
                }
            }
        }
Example #2
0
        public void Execute(IVm vm)
        {
            var @byte = (byte)Console.Read();
            var delta = (byte)(@byte - vm.CurrentMemory);

            Func <byte, byte> func = delta <= 0
                ? vm.IncreaseCurrentMemoryBy
                : vm.DecreaseCurrentMemoryBy;

            func(delta);
        }
Example #3
0
        public IVm CreateVm(VmCreationInfo info)
        {
            IVirtualSystemSettingData systemSettingData = VirtualSystemSettingData.CreateVirtualSystemSettingData(this._Host);

            systemSettingData.ElementName           = info.Name;
            systemSettingData.ConfigurationDataRoot = info.Location;
            systemSettingData.SnapshotDataRoot      = info.Location;
            systemSettingData.BootOrder             = new ushort[4]
            {
                (ushort)2,
                (ushort)1,
                (ushort)0,
                (ushort)3
            };
            if (!string.IsNullOrEmpty(info.VirtualSystemSubType) && info.VirtualSystemSubType != "Microsoft:Hyper-V:SubType:1")
            {
                systemSettingData.VirtualSystemSubType = info.VirtualSystemSubType;
            }
            List <string> stringList = new List <string>();

            using (IVirtualSystemManagementService managmentService = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host))
            {
                IVm vm = (IVm) new Vm(this._Host, managmentService.DefineSystem(systemSettingData, stringList.ToArray(), (IVirtualSystemSettingData)null), this._Logger);
                vm.CPUCount         = (ulong)info.NumCPU;
                vm.CPUCompatibility = info.CPUCompatibility;
                if (info.MemoryMB % 2L == 1L)
                {
                    ++info.MemoryMB;
                }
                vm.MemorySize = (ulong)(info.MemoryMB * 1024L) * 1024UL;
                try
                {
                    foreach (HVNicInfo nic in info.Nics)
                    {
                        if (string.Compare(nic.VirtualNetwork, "---Discard---", true, CultureInfo.InvariantCulture) != 0)
                        {
                            NicConnectionStatus nicStatus = string.IsNullOrEmpty(nic.VirtualNetwork) ? NicConnectionStatus.Disconnected : NicConnectionStatus.Connected;
                            vm.AddNic(nic.NicType, nic.VirtualNetwork, nicStatus, nic.NicGuid, nic.vLan);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this._Logger.FormatErrorWithException(ex, "Failed to provision the NICs for the vm.  Removing the vm");
                    using (vm)
                        managmentService.DestroySystem(((IVmInternals)vm).ComputerSystem);
                    throw;
                }
                return(vm);
            }
        }
Example #4
0
        public void Execute(IVm vm)
        {
            _ = vm ?? throw new ArgumentNullException(nameof(vm));

            var index     = IsThisIndex(vm.CurrentMemory) ? Index : vm.InstructionIndex;
            var isSmaller = vm.InstructionIndex < index;

            var delta = isSmaller
                ? (uint)(index - vm.InstructionIndex)
                : (uint)(vm.InstructionIndex - index);

            Func <uint, int> func = isSmaller
                ? vm.IncreaseInstructionIndexBy
                : vm.DecreaseInstructionIndexBy;

            func(delta);
        }
Example #5
0
 public IEnumerable <VmCfgInfo> GetAllVmCfgInfo()
 {
     foreach (IVm allVm in this.GetAllVms())
     {
         IVm vm = allVm;
         try
         {
             yield return(allVm.GetCfg());
         }
         finally
         {
             if (vm != null)
             {
                 vm.Dispose();
             }
         }
         vm = (IVm)null;
     }
 }
        private T Execute <T>(string method, IVm vm)
            where T : IVm, new()
        {
            string url     = String.Format("{0}/{1}", _host, method);
            var    data    = JsonConvert.SerializeObject(vm);
            var    request = WebRequest.Create(url);

            request.ContentType   = "application/json";
            request.Method        = "POST";
            request.ContentLength = data.Length;
            request.Headers.Add(AuthorizationHeader, _securityProvider.GetToken());
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());

            requestWriter.Write(data);
            requestWriter.Close();

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                if (response == null || response.StatusCode != HttpStatusCode.OK)
                {
                    return(new T());
                }

                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        return(new T());
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        return(JsonConvert.DeserializeObject <T>(reader.ReadToEnd()));
                    }
                }
            }
        }
Example #7
0
    static IVm Create(VmKind vmKind)
    {
        IVm result = null;

        switch (vmKind)
        {
        case VmKind.Status:
            result = new StatusViewModel {
                StatusId = -1, CreateDate = DateTime.Now
            };
            break;

        case VmKind.Mro:
            result = new MroViewModel {
                StatusId = -1, CreateDate = DateTime.Now
            };
            break;

        default:
            throw new ArgumentException("Unknown VM type");
            //break;
        }
        return(result);
    }
Example #8
0
        public void Execute(IVm vm)
        {
            _ = vm ?? throw new ArgumentNullException(nameof(vm));

            vm.IncreaseMemoryIndexBy(1);
        }
Example #9
0
 protected void AddNicToVm(IVm vm, VirtualNicType nicType, string vswitchName, NicConnectionStatus nicStatus, string nicGuid, int VLan)
 {
     using (IVirtualSystemManagementService managmentService = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host))
     {
         using (IVirtualEthernetSwitch virtualEthernetSwitch = VirtualEthernetSwitch.Query(this._Host, "ElementName='{0}'", (object)vswitchName).FirstOrDefault <IVirtualEthernetSwitch>())
         {
             if (virtualEthernetSwitch == null)
             {
                 throw new HyperVException("Virtual Ethernet switch '" + vswitchName + "' not found");
             }
             using (IVirtualSystemSettingData systemSettingData = ((IVmInternals)vm).ComputerSystem.GetVirtualSystemSettingData())
             {
                 ICommonEthernetPortSettingData ethernetPortSettingData;
                 if (nicType != VirtualNicType.Legacy)
                 {
                     if (nicType != VirtualNicType.Synthetic)
                     {
                         throw new HyperVException("I don't know about the nic type " + nicType.ToString());
                     }
                     ethernetPortSettingData = (ICommonEthernetPortSettingData)SyntheticEthernetPortSettingData.GetDefaultSyntheticAdapter(this._Host);
                     ((ISyntheticEthernetPortSettingData)ethernetPortSettingData).VirtualSystemIdentifiers = new string[1]
                     {
                         nicGuid
                     };
                     ethernetPortSettingData.ElementName = "Synthetic Network Adapter";
                 }
                 else
                 {
                     ethernetPortSettingData             = (ICommonEthernetPortSettingData)EmulatedEthernetPortSettingData.GetDefaultLegacyAdapter(this._Host);
                     ethernetPortSettingData.ElementName = "Legacy Network Adapter";
                 }
                 using (ethernetPortSettingData)
                 {
                     ethernetPortSettingData.StaticMacAddress = false;
                     using (IResourceAllocationSettingData allocationSettingData1 = managmentService.AddResourceSettings(systemSettingData, new string[1]
                     {
                         ((IWMICommon)ethernetPortSettingData).Object.GetText(TextFormat.WmiDtd20)
                     }).FirstOrDefault <IResourceAllocationSettingData>())
                     {
                         if (nicStatus != NicConnectionStatus.Connected)
                         {
                             return;
                         }
                         using (IEthernetPortAllocationSettingData allocationSettingData2 = EthernetPortAllocationSettingData.GetDefaultEthernetPortAllocationSettingData(this._Host))
                         {
                             using (IVirtualSwitch virtualSwitchByName = this.GetVirtualSwitchByName(vswitchName))
                             {
                                 Invariant.ArgumentNotNull((object)allocationSettingData2, "Switch port not found");
                                 Invariant.ArgumentNotNull((object)virtualSwitchByName, "Virtual switch '" + vswitchName + "' not found");
                                 allocationSettingData2.Parent       = ((IWMICommon)allocationSettingData1).Object.Path.Path;
                                 allocationSettingData2.HostResource = new string[1]
                                 {
                                     virtualSwitchByName.Object.Path.Path
                                 };
                                 managmentService.AddResourceSettings(systemSettingData, new string[1]
                                 {
                                     ((IWMICommon)allocationSettingData2).Object.GetText(TextFormat.WmiDtd20)
                                 }).FirstOrDefault <IResourceAllocationSettingData>().TryDispose();
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #10
0
 public Reflection()
 {
     VM = new VM(null);
 }
Example #11
0
 public VM(IExternalEntities externalEntities)
 {
     MyVm = externalEntities.Reflaction.VM;
 }
Example #12
0
 public void Execute(IVm vm)
 {
     _ = vm ?? throw new ArgumentNullException(nameof(vm));
 }
Example #13
0
        public void Execute(IVm vm)
        {
            _ = vm ?? throw new ArgumentNullException(nameof(vm));

            vm.DecreaseCurrentMemoryBy(1);
        }
Example #14
0
        public static VmCfgSimpleInfo[] GetAllVmCfgSimpleInfoParallel(IVm[] vms)
        {
            if (vms.Length == 0)
            {
                return(new VmCfgSimpleInfo[0]);
            }
            List <VmCfgSimpleInfo> results = new List <VmCfgSimpleInfo>();
            object syncObj = new object();

            BackgroundWorker[] backgroundWorkerArray = new BackgroundWorker[vms.Length];
            Exception          asyncError            = (Exception)null;
            int taskCompleteCount = 0;
            ManualResetEvent evt  = new ManualResetEvent(false);

            try
            {
                try
                {
                    for (int index = 0; index < vms.Length; ++index)
                    {
                        IVm vm = vms[index];
                        BackgroundWorker backgroundWorker = new BackgroundWorker();
                        backgroundWorkerArray[index]         = backgroundWorker;
                        backgroundWorker.RunWorkerCompleted += (RunWorkerCompletedEventHandler)((sender, args) =>
                        {
                            lock (syncObj)
                            {
                                try
                                {
                                    if (args.Error != null)
                                    {
                                        asyncError = args.Error;
                                    }
                                    else
                                    {
                                        results.Add(args.Result as VmCfgSimpleInfo);
                                    }
                                }
                                finally
                                {
                                    if (++taskCompleteCount == vms.Length)
                                    {
                                        try
                                        {
                                            evt.Set();
                                        }
                                        catch (ObjectDisposedException ex)
                                        {
                                        }
                                    }
                                }
                            }
                        });
                        backgroundWorker.DoWork += (DoWorkEventHandler)((sender, args) => args.Result = (object)((IVm)args.Argument).GetVmCfgSimpleInfo());
                        backgroundWorker.RunWorkerAsync((object)vm);
                    }
                    if (!evt.WaitOne(60000))
                    {
                        throw new TimeoutException("Timed out waiting for WMI to return simple VM configuration");
                    }
                    lock (syncObj)
                    {
                        if (asyncError != null)
                        {
                            throw ExceptionExtensions.PrepareForRethrow(asyncError);
                        }
                        return(results.ToArray());
                    }
                }
                finally
                {
                    foreach (Component component in backgroundWorkerArray)
                    {
                        component.Dispose();
                    }
                }
            }
            finally
            {
                if (evt != null)
                {
                    evt.Dispose();
                }
            }
        }
Example #15
0
 public Window1(IVm vm)
 {
     InitializeComponent();
     DataContext = vm;
 }
Example #16
0
        public void Execute(IVm vm)
        {
            _ = vm ?? throw new ArgumentNullException(nameof(vm));

            vm.AddCharToScreenBuffer((char)vm.CurrentMemory);
        }
Example #17
0
 public Vm(IVm viewModel1, IVm viewModel2)
 {
     ViewModel1 = viewModel1;
     ViewModel2 = viewModel2;
 }