none
Change virtual memory programatically with c# RRS feed

  • Question

  • Hello everybody,

    I am trying to change programatically with C#, the amout of memory a virtual machine has, while the virtual machine is on.

    The c# code works ok has long has the virtual machine is powered off, but when its powered on the following error apears

    I get the error code: 4108 and the following description: 'Windows2008-I' failed to modify device 'Microsoft Virtual Machine Memory'. (Virtual machine ID 15318AFD-33F5-4D74-95DF-DB6E408CD28E)

    Has anyone know why?

    its there something i am not doing wright or is it because the hyper-v does not have this functionality

    Best Regards,

    jmar1

    =================================================== // ==============================================

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Management;
    using HyperVUtility;

    namespace ConsoleChangeMemory
    {
        class Program
        {


            public static ManagementObject GetTargetComputer(string vmElementName, ManagementScope scope)
            {
                string query = string.Format("select * from Msvm_ComputerSystem Where ElementName = '{0}'", vmElementName);

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query));

                ManagementObjectCollection computers = searcher.Get();

                ManagementObject computer = null;

                foreach (ManagementObject instance in computers)
                {
                    computer = instance;
                    break;
                }
                return computer;
            }

            public static bool JobCompleted(ManagementBaseObject outParams, ManagementScope scope)
            {
                bool jobCompleted = true;

                //Retrieve msvc_StorageJob path. This is a full wmi path
                string JobPath = (string)outParams["Job"];
                ManagementObject Job = new ManagementObject(scope, new ManagementPath(JobPath), null);
                //Try to get storage job information
                Job.Get();
                while ((UInt16)Job["JobState"] == JobState.Starting
                    || (UInt16)Job["JobState"] == JobState.Running)
                {
                    Console.WriteLine("In progress... {0}% completed.", Job["PercentComplete"]);
                    System.Threading.Thread.Sleep(1000);
                    Job.Get();
                }

                //Figure out if job failed
                UInt16 jobState = (UInt16)Job["JobState"];
                if (jobState != JobState.Completed)
                {
                    UInt16 jobErrorCode = (UInt16)Job["ErrorCode"];
                    Console.WriteLine("Error Code:{0}", jobErrorCode);
                    Console.WriteLine("ErrorDescription: {0}", (string)Job["ErrorDescription"]);
                    jobCompleted = false;
                }
                return jobCompleted;
            }

     

    //--

            static void Main(string[] args)
            {

            string virtualMachineName = "Windows2008-I";
            //string virtualMachineName = "Windows2008Template";
      UInt64 memory = 1024;
      string[] resourceSettingData = new string[2];

      ManagementPath path = new ManagementPath(@"root\virtualization");
      ManagementScope scope = new ManagementScope(path, new ConnectionOptions());
      scope.Connect();

      ManagementObject objMachine = Utility.GetTargetComputer(virtualMachineName, scope);

      // prepare settings datas.
      ManagementObject memorySetting = null;
      ManagementObject processorSetting = null;
      ManagementObjectCollection settingDatas = objMachine.GetRelated("Msvm_VirtualSystemsettingData");
      foreach (ManagementObject settingData in settingDatas)
      {
       foreach (ManagementObject memorySettingData in settingData.GetRelated("Msvm_MemorySettingData"))
       {
        memorySetting = memorySettingData;
        break;
       }
       foreach (ManagementObject proccessSettingData in settingData.GetRelated("Msvm_ProcessorSettingData"))
       {
        processorSetting = proccessSettingData;
        break;
       }
      }
      memorySetting["Limit"] = memory;
      memorySetting["Reservation"] = memory;
      memorySetting["VirtualQuantity"] = memory;
      resourceSettingData[0] = memorySetting.GetText(TextFormat.CimDtd20);

      processorSetting["VirtualQuantity"] = 2;
      resourceSettingData[1] = processorSetting.GetText(TextFormat.CimDtd20);

      // get Msvm_VirtualSystemManagementService instance.
      ManagementObject virtualSystem = null;
      ManagementClass systemManagementServiceClass = new ManagementClass(
       scope,
       new ManagementPath("Msvm_VirtualSystemManagementService"),
       null);

      ManagementObjectCollection systemManagementServices = systemManagementServiceClass.GetInstances();
      foreach (ManagementObject service in systemManagementServices)
      {
       virtualSystem = service;
      }

      ManagementBaseObject inParams = virtualSystem.GetMethodParameters("ModifyVirtualSystemResources");
      inParams["ComputerSystem"] = objMachine.Path.Path;
      inParams["ResourcesettingData"] = resourceSettingData;
      ManagementBaseObject outParams = virtualSystem.InvokeMethod("ModifyVirtualSystemResources", inParams, null);
      if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
      {
       if (Utility.JobCompleted(outParams, scope))
       {
        Console.WriteLine("Virtual machine was modified successfully.");
       }
       else
       {
        Console.WriteLine("Failed to modify virtual machine.");
       }
      }
      else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
      {
       Console.WriteLine("Virtual machine was modified successfully.");
      }
      else
      {
       Console.WriteLine("Modify virtual machine failed with error : {0}", outParams["ReturnValue"]);
      }

      inParams.Dispose();
      outParams.Dispose();
      memorySetting.Dispose();
      processorSetting.Dispose();
      objMachine.Dispose();


            }
        }
    }

    }

    }

    }

     

    Friday, April 8, 2011 4:46 PM