Click here to Skip to main content
Email Password   helpLost your password?
VMWare

Introduction

I've been playing with VMware lately, both Workstation and VMware Infrastructure (VI). The company has really stepped up with the new SDKs and the level of programmable interfaces, making some excellent implementation decisions that enable developers to drive virtual machines programmatically with an asynchronous, job-based programming model. Unfortunately that turns out to be too complicated for 99.9% of scenarios and most developers want to use a simple object-oriented interface for common VMWare tasks. The VMWareTasks library implements that interface and makes programming against virtual machine a no brainer. This article explains how to use the library and discusses some of its implementation details.

Background

There're two types of VMWare APIs.

Using the Library

In order to use the library or build or run the source code, you must install the following VMWare software.

In your project, add a reference to Vestris.VMWareLib.dll and a namespace reference.

using Vestris.VMWareLib;

You can now connect to a local VMWare Workstation or a remote ESX server and perform VMWare tasks. Here's an example that creates, restores, powers on and removes a snapshot on a VMWare Workstation.

// declare a virtual host
VMWareVirtualHost virtualHost = new VMWareVirtualHost();
// connect to a local (VMWare Workstation) virtual machine
virtualHost.ConnectToVMWareWorkstation();
// open an existing virtual machine
VMWareVirtualMachine virtualMachine = virtualHost.Open("C:\Virtual Machines\xp\xp.vmx");
// power on this virtual machine
virtualMachine.PowerOn();
// login to the virtual machine
virtualMachine.Login("Administrator", "password");
// run notepad
virtualMachine.RunProgramInGuest("notepad.exe", string.Empty);
// create a new snapshot
string name = "New Snapshot";
// take a snapshot at the current state
virtualMachine.Snapshots.CreateSnapshot(name, "test snapshot");
// power off
virtualMachine.PowerOff();
// find the newly created snapshot
VMWareSnapshot snapshot = virtualMachine.Snapshots.GetNamedSnapshot(name);
// revert to the new snapshot
snapshot.RevertToSnapshot();
// delete snapshot
snapshot.RemoveSnapshot();

Implementation

The following sections describe VMWareTasks library implementation details. It's absolutely not necessary to understand those in order to use the library.

Connecting to VMWare in pure VIX API

Connecting synchronously to either a local VMWare Workstation or an ESX server is virtually identical. The ESX server requires a URL to the SOAP SDK (eg. https://esxserver/sdk) and a username and password.

public IHost ConnectToVMWareWorkstation()
{
    return Connect(Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION, 
		string.Empty, 0, string.Empty, string.Empty);
}

public IHost ConnectToVMWareVIServer(string hostName, int hostPort, 
			string username, string password)
{
    return Connect(Constants.VIX_SERVICEPROVIDER_VMWARE_VI_SERVER,  
			hostName, hostPort, username, password);
}

public IHost Connect(int hostType, string hostName, int hostPort, 
			string username, string password)
{
    VixLib vix = new VixLib();
    IJob vmJob = vix.Connect(Constants.VIX_API_VERSION, hostType, 
		hostName, hostPort, username, password, 0, null, null);
    // You need to get the IHost object that represents the host 
    // where your VM is located.
    // Since COM allocates the object you need to use this funky mechanism 
    // to extract the IHosts array.
    object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_HANDLE };
    // Wait for the operation to complete
    object hosts = VmwareVixInterop.Wait(vmJob, properties);
    object[] hostArray = hosts as object[];
    return (IHost) hostArray[0];
}

You have to declare an array of properties that you want the job to produce, start a VMWare job and examine the results for the host handle. You can see how cumbersome this is! The API was originally designed for C, then extended to COM with a very limited object model: a number of interfaces were declared, but no corresponding COM classes have been implemented. Also, because the job interface is generic, there're no strongly typed results.

We can easily fill this gap in our C# implementation.

Transforming Error Codes into Exceptions

The first task for wrapping any API is to implement error handling. Our managed implementation must translate error codes into managed exceptions. VIX API provides an implementation for the IVixLib interface which contains a couple of helper methods (very C-programmer). We'll be interested in IVixLib.ErrorIndicatesFailure and IVixLib.GetErrorText combined with a new class, VMWareException.

public abstract class VMWareInterop
{
    public static VixLib Instance = new VixLib();

    public static void Check(ulong errCode)
    {
        if (Instance.ErrorIndicatesFailure(errCode))
        {
            throw new VMWareException(errCode);
        }
    }
}  

Aside from the abstract VMWareInterop, our goal is to produce concrete classes that wrap various aspects of VMWare functionality.

Base VMWareVixHandle

VMWare COM API returns interface pointers such as ISnapshot. The objects also implement IVixHandle which gives access to a set of object properties. We will base-class everything on VMWareVixHandle.

public class VMWareVixHandle<T>
{
    protected T _handle = default(T);

    protected IVixHandle _vixhandle
    {
        get
        {
            return (IVixHandle) _handle;
        }
    }

    public VMWareVixHandle()
    {

    }

    public VMWareVixHandle(T handle)
    {
        _handle = handle;
    }

    public object[] GetProperties(object[] properties)
    {
        object result = null;
        VMWareInterop.Check(_vixhandle.GetProperties(properties, ref result));
        return (object[]) result;
    }

    public R GetProperty<R>(int propertyId)
    {
        object[] properties = { propertyId };
        return (R) GetProperties(properties)[0];
    }
}  

Implementing VMWareJob

Since all operations in VMWare are job-based, let's wrap up a job. If we use the COM API directly, we would have to call IVixLib.Wait passing a job handle. In an object-oriented library, this operation belongs inside the job, plus a job is also a VMWareVixHandle.

 public class VMWareJob : VMWareVixHandle<IJob>
 {
     public VMWareJob(IJob job)
         : base(job)
     {

     }

     public void Wait()
     {
         VMWareInterop.Check(_handle.WaitWithoutResults());
     }
 }  

One very common problem in VMWare API implementations that transform an asynchronous job into a synchronous one is to use the blocking wait above. This is a bad design decision since this call may never return. VMWare server may timeout or someone can pull the network cable, leaving your program hanging. I originally wrote a busy wait where all externally visible wait functions were based on the following InternalWait.

private void InternalWait(int timeoutInSeconds)
{
    if (timeoutInSeconds == 0)
    {
        throw new ArgumentOutOfRangeException("timeoutInSeconds");
    }

    // active wait for the job to finish
    bool isComplete = false;
    while (!isComplete && timeoutInSeconds > 0)
    {
        VMWareInterop.Check(_handle.CheckCompletion(out isComplete));
        if (isComplete) break;
        Thread.Sleep(1000);
        timeoutInSeconds--;
    }

    if (timeoutInSeconds == 0)
    {
        throw new TimeoutException();
    }
}

A more elegant implementation combines a callback mechanism provided by VixCOM with every asynchronous API and a blocking wait with a timeout. Wait is now signaled and there's no CPU spin waiting for completion of an asynchronous API call.

public class VMWareJobCallback : ICallback
{
    #region ICallback Members

    private EventWaitHandle _jobCompleted = new EventWaitHandle(
         false, EventResetMode.ManualReset);

    public void OnVixEvent(IJob job, int eventType, IVixHandle moreEventInfo)
    {
        switch (eventType)
        {
            case VixCOM.Constants.VIX_EVENTTYPE_JOB_COMPLETED:
                _jobCompleted.Set();
                break;
        }
    }

    public bool TryWaitForCompletion(int timeoutInMilliseconds)
    {
        return _jobCompleted.WaitOne(timeoutInMilliseconds, false);
    }

    public void WaitForCompletion(int timeoutInMilliseconds)
    {
        if (!TryWaitForCompletion(timeoutInMilliseconds))
        {
            throw new TimeoutException();
        }
    }

    #endregion
}  

This and some generic code in VMWareJob can now be used inside Connect. I have modified VMWareJob to require a VMWareCallback in order to prevent callers from ever having a blocking wait.

VMWareJobCallback callback = new VMWareJobCallback();
VMWareJob job = new VMWareJob(VMWareInterop.Instance.Connect(
    Constants.VIX_API_VERSION, Constants.VIX_SERVICEPROVIDER_VMWARE_SERVER, 
	hostName, hostPort, username, password, 0, null, callback), callback); 

VMWareVirtualHost

With VMWareJob and VMWareException, it's now possible to implement VMWareVirtualHost and connect to it. Note references to default timeouts (a collection of constants) and some facilities in VMWareJob that add strong typing into VMWare job results.

public class VMWareVirtualHost
{
    private IHost _host = null;

    public VMWareVirtualHost()
    {

    }

    public void ConnectToVMWareWorkstation()
    {
        ConnectToVMWareWorkstation(VMWareInterop.Timeouts.ConnectTimeout);
    }

    public void ConnectToVMWareWorkstation(int timeoutInSeconds)
    {
        Connect(Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION,
            string.Empty, 0, string.Empty, string.Empty, timeoutInSeconds);
    }

    private void Connect(int hostType, string hostName, 
	int hostPort, string username, string password, int timeout)
    {
        int serviceProvider = (int)serviceProviderType;
        VMWareJobCallback callback = new VMWareJobCallback();
        VMWareJob job = new VMWareJob(VMWareInterop.Instance.Connect(
            Constants.VIX_API_VERSION, serviceProvider, hostName, hostPort,
            username, password, 0, null, callback), callback);

        _handle = job.Wait
(Constants.VIX_PROPERTY_JOB_RESULT_HANDLE, timeout);
        _serviceProviderType = serviceProviderType;
    }
}

VMWareVirtualHost can now implement opening of an actual virtual machine and return an instance of VMWareVirtualMachine.

public VMWareVirtualMachine Open(string fileName, int timeoutInSeconds)
{
    VMWareJobCallback callback = new VMWareJobCallback();
    VMWareJob job = new VMWareJob(_handle.OpenVM(fileName, callback), callback);
    return new VMWareVirtualMachine(job.Wait<ivm2>
    (
        Constants.VIX_PROPERTY_JOB_RESULT_HANDLE,
        timeoutInSeconds));
}

Based on this model, we can code many functions of VMWareVirtualMachine, VMWareSnapshot, etc. The rest is implementation details.

Advanced Implementation Details

Yielding Property Arrays

One of the peculiar VIX COM API constructs is the combination that returns arrays of properties. This is done with two functions: GetNumProperties and GetNthProperties. The first returns the number of property arrays returned by the job and the second fetches a property array at a given index. The first obvious step is to wrap the functions within the job class.

public T GetNthProperties<T>(int index, object[] properties)
{
    object result = null;
    VMWareInterop.Check(_handle.GetNthProperties(index, properties, ref result));
    return (T) result;
}

public int GetNumProperties(int property)
{
    return _handle.GetNumProperties(property);
}

We can now write such properties as RunningVirtualMachines.

public IEnumerable<VMWareVirtualMachine> RunningVirtualMachines
{
    get
    {
        VMWareJobCallback callback = new VMWareJobCallback();
        VMWareJob job = new VMWareJob(_handle.FindItems(
            Constants.VIX_FIND_RUNNING_VMS, null, -1, callback),
            callback);
        object[] properties = { Constants.VIX_PROPERTY_FOUND_ITEM_LOCATION };
        for (int i = 0; i < job.GetNumProperties((int) properties[0]); i++)
        {
            yield return this.Open(
                (string) job.GetNthProperties<object[]>(i, properties)[0]);
        }
    }
}

This is nice, but still not good enough. Let's combine the number of results and the results themselves in a YieldWait method.

public IEnumerable <object[]> YieldWait(object[] properties, int timeoutInSeconds)
{
    Wait(timeoutInSeconds);
    for (int i = 0; i < GetNumProperties((int)properties[0]); i++)
    {
        yield return GetNthProperties<object[]>(i, properties);
    }
}

This results in a nice improvement over the previous implementation.

public IEnumerable<VMWareVirtualMachine> RunningVirtualMachines
{
    get
    {
        VMWareJobCallback callback = new VMWareJobCallback();
        VMWareJob job = new VMWareJob(_handle.FindItems(
            Constants.VIX_FIND_RUNNING_VMS, null, -1, callback),
            callback);
        foreach (object[] runningVirtualMachine in job.YieldWait
		(properties, VMWareInterop.Timeouts.FindItemsTimeout))
        {
            yield return this.Open((string) runningVirtualMachine[0]);
        }
    }
}  

Dates and Times

Date/time in VMWare VIX is expressed in UNIX EPOCH (number of seconds since January 1st, 1970).

DateTime currentDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((int) dt);

Source Code and Patches

This project lives on CodePlex at http://www.codeplex.com/vmwaretasks. You can find the latest information about this library at code.dblock.org. You're encouraged to submit patches for added functionality and bug fixes.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralList Running Virtual Machines
sdhillon07
10:44 16 Feb '10  
Hello,

This is a fantastic library by the way. Thank You Very Much for providing it. I am trying figure out how to list all running virtual machines so that I can shutdown all the machines on the host...how would I go about this?
GeneralPLEASE POST QUESTIONS ON CODEPLEX
dB.
11:16 16 Feb '10  
There's a VirtualHost.RunningVirtualMachines and RegisteredVirtualMachines property. Enumerate over it. Note that those aren't supported on all VMWare server/workstation/vi combinations.
GeneralException: A file was not found
albertitomd
9:37 30 Nov '09  
I can ConnectToVMWareVIServer, Open virtualmachine and LoginInGuest succesfully. But when I try RunProgramInGuest I get an Exception with message "A file was not found" and stacktrace:

Vestris.VMWareLib.VMWareException: A file was not found
en Vestris.VMWareLib.VMWareInterop.Check(UInt64 errCode)
en Vestris.VMWareLib.VMWareJob.Wait[T](Object[] properties)
en Vestris.VMWareLib.VMWareJob.Wait[T](Object[] properties, Int32 timeoutInSeconds)
en Vestris.VMWareLib.VMWareVirtualMachine.RunProgramInGuest(String guestProgramName, String commandLineArgs, Int32 options, Int32 timeoutInSeconds)
en Vestris.VMWareLib.VMWareVirtualMachine.RunProgramInGuest(String guestProgramName, String commandLineArgs)
en Vestris.VMWareLib.VMWareVirtualMachine.RunProgramInGuest(String guestProgramName)

I have installed vix 1.8.1 and the same command with vmrun utility and RunProgramInGuest option works ok.
GeneralPLEASE POST QUESTIONS ON CODEPLEX
dB.
9:41 30 Nov '09  
It's here: http://vmwaretasks.codeplex.com.


GeneralHow Can i get memory an Cpu usage?
Member 4064798
5:54 25 Sep '09  
there is a way to obtain, CPU and Memory usage from the virtual Machine, using Vestris?

Kind Regards.
GeneralPLEASE POST QUESTIONS ON CODEPLEX
dB.
10:28 25 Sep '09  
It's here: http://vmwaretasks.codeplex.com.


Generalvery good vmae article
Donsw
17:17 14 Jun '09  
Very good, well written

cheers,
Donsw
My Recent Article : Backup of Data files - Full and Incremental

GeneralRe: very good vmae article
dB.
3:50 11 Aug '09  
Thx.


GeneralPLEASE POST QUESTIONS ON CODEPLEX, NOT HERE
dB.
6:18 14 Jun '09  
The project has long moved to CodePlex. There's an active discussions board that is being monitored. Please post your questions there: http://vmwaretasks.codeplex.com/Thread/List.aspx[^]


GeneralHow to swtich between powerup VMs using vix api
hamidzaidi
3:39 10 Jun '09  
Hello,

I want to know as there is an option in VMware workstation to swtich between different powered on VMs so is there any function also exit in VIX api which supports this functionality.
GeneralRe: How to swtich between powerup VMs using vix api
dB.
4:45 10 Jun '09  
I don't know. This is a question for the Vix community forum.
http://communities.vmware.com/community/developer/automationapi[^]


GeneralUsing this API to manage multiple task on an ESX server
jbc1
6:50 9 Jun '09  
I'm trying using this API to increase our test automation coverage by running our automation jobs on an ESX server

Have you had issues with running multiple jobs (in seperate threads) on ESX?

I get an error like this:

Vestris.VMWareLib.VMWareException: The handle is not a valid VIX object
GeneralRe: Using this API to manage multiple task on an ESX server
dB.
4:45 10 Jun '09  
This is not going to work with VixCOM 1.6.2, it's just a bug in Vix API. See the VIX API community forum.
http://communities.vmware.com/community/developer/automationapi[^]


GeneralPlease supply a code snippet how I can read vm properties
Member 3999245
23:36 2 Jun '09  
like "guestOS" , "floppy0.autodetect" which appear in the vmx file.

Is this what VMWareVirtualMachine.GetProperties() is returning?
GeneralRe: Please supply a code snippet how I can read vm properties
dB.
4:09 7 Jun '09  
Make sure to get version 1.2 from http://vmwaretasks.codeplex.com. It's virtualMachine.RuntimeConfigVariables["guestOS"], etc. This eventually translates to a call to VixCOM.ReadVariable with VIX_VM_CONFIG_RUNTIME_ONLY.


GeneralHow do I find out if a VM is a linked clone of another VM?
Member 3999245
23:32 2 Jun '09  
.
GeneralRe: How do I find out if a VM is a linked clone of another VM?
dB.
3:59 3 Jun '09  
No idea. You should ask this question on the VixCOM forum: http://communities.vmware.com/community/developer/automationapi[^]


QuestionException by conect to vmware ESXi 3.5 U4 or vmwarews 3.5.1 please help
marc.peter@frsglobal.com
2:01 4 May '09  
My system VISTA x64, VS 2008 Pro, VIX API 1.1.5, ESXi 3.5 U4, VMWARE WS 6.5.1

ESXi error message

System.TypeInitializationException wurde nicht behandelt.
Message="Der Typeninitialisierer für \"Vestris.VMWareLib.VMWareInterop\" hat eine Ausnahme verursacht."
Source="Vestris.VMWareLib"
TypeName="Vestris.VMWareLib.VMWareInterop"
StackTrace:
bei Vestris.VMWareLib.VMWareVirtualHost.ConnectToVMWareVIServer(String hostName, String username, String password)
bei Vetris_Test.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\marc\Documents\Visual Studio 2008\Projects\Vetris-Test\Vetris-Test\Form1.cs:Zeile 34.
bei System.Windows.Forms.Control.OnClick(EventArgs e)
bei System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
bei System.Windows.Forms.Control.WndProc(Message& m)
bei System.Windows.Forms.ButtonBase.WndProc(Message& m)
bei System.Windows.Forms.Button.WndProc(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bei Vetris_Test.Program.Main() in C:\Users\marc\Documents\Visual Studio 2008\Projects\Vetris-Test\Vetris-Test\Program.cs:Zeile 18.
bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Runtime.InteropServices.COMException
Message="Die COM-Klassenfactory für die Komponente mit CLSID {6874E949-7186-4308-A1B9-D55A91F60728} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80040154."
Source="Vestris.VMWareLib"
ErrorCode=-2147221164
StackTrace:
bei Vestris.VMWareLib.VMWareInterop..cctor()
InnerException:


Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Vestris.VMWareLib;


namespace Vetris_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

VMWareVirtualHost virtualHost = new VMWareVirtualHost();
virtualHost.ConnectToVMWareVIServer("192.168.110.129", "root", "MiSs23");
}
}
}

}
}
}

VMWARE WS

System.TypeInitializationException wurde nicht behandelt.
Message="Der Typeninitialisierer für \"Vestris.VMWareLib.VMWareInterop\" hat eine Ausnahme verursacht."
Source="Vestris.VMWareLib"
TypeName="Vestris.VMWareLib.VMWareInterop"
StackTrace:
bei Vestris.VMWareLib.VMWareVirtualHost.ConnectToVMWareWorkstation()
bei Vetris_Test.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\marc\Documents\Visual Studio 2008\Projects\Vetris-Test\Vetris-Test\Form1.cs:Zeile 26.
bei System.Windows.Forms.Control.OnClick(EventArgs e)
bei System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
bei System.Windows.Forms.Control.WndProc(Message& m)
bei System.Windows.Forms.ButtonBase.WndProc(Message& m)
bei System.Windows.Forms.Button.WndProc(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bei Vetris_Test.Program.Main() in C:\Users\marc\Documents\Visual Studio 2008\Projects\Vetris-Test\Vetris-Test\Program.cs:Zeile 18.
bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Runtime.InteropServices.COMException
Message="Die COM-Klassenfactory für die Komponente mit CLSID {6874E949-7186-4308-A1B9-D55A91F60728} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80040154."
Source="Vestris.VMWareLib"
ErrorCode=-2147221164
StackTrace:
bei Vestris.VMWareLib.VMWareInterop..cctor()
InnerException:

Code:

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Vestris.VMWareLib;


namespace Vetris_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
// declare a virtual host
VMWareVirtualHost virtualHost = new VMWareVirtualHost();
// connect to a local (VMWare Workstation) virtual machine
virtualHost.ConnectToVMWareWorkstation();
// open an existing virtual machine
//VMWareVirtualMachine virtualMachine = virtualHost.Open("D:\\VMWARE\\ESXi 4.5 U4\\ESXi 4.5 U4.vmx");


}
}
}

Cheers
Marc
AnswerRe: Exception by conect to vmware ESXi 3.5 U4 or vmwarews 3.5.1 please help
dB.
4:41 4 May '09  
Usually this means that you don't have VixCOM 1.6.2 installed.


GeneralRe: Exception by conect to vmware ESXi 3.5 U4 or vmwarews 3.5.1 please help
marc.peter@frsglobal.com
9:23 4 May '09  
Hello,

VixCOM 1.6.2 is installed and the reference to it also.
I have recreate an test project with the same references with the same error.

Cheers
Marc

System.TypeInitializationException wurde nicht behandelt.
Message="Der Typeninitialisierer für "Vestris.VMWareLib.VMWareInterop" hat eine Ausnahme verursacht."
Source="Vestris.VMWareLib"
TypeName="Vestris.VMWareLib.VMWareInterop"
StackTrace:
bei Vestris.VMWareLib.VMWareVirtualHost.ConnectToVMWareWorkstation()
bei VMWARE_Powershell.Form1.Button2_Click(Object sender, EventArgs e) in D:\Users\Marc\Documents\Visual Studio 2008\Projects\VMWARE-Powershell\VMWARE-Powershell\Form1.vb:Zeile 36.
bei System.Windows.Forms.Control.OnClick(EventArgs e)
bei System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
bei System.Windows.Forms.Control.WndProc(Message& m)
bei System.Windows.Forms.ButtonBase.WndProc(Message& m)
bei System.Windows.Forms.Button.WndProc(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bei Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
bei Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
bei Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
bei VMWARE_Powershell.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:Zeile 81.
bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Runtime.InteropServices.COMException
ErrorCode=-2147221164
Message="Die COM-Klassenfactory für die Komponente mit CLSID {6874E949-7186-4308-A1B9-D55A91F60728} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80040154."
Source="Vestris.VMWareLib"
StackTrace:
bei Vestris.VMWareLib.VMWareInterop..cctor()
InnerException:
GeneralRe: Exception by conect to vmware ESXi 3.5 U4 or vmwarews 3.5.1 please help
dB.
8:15 5 May '09  
First, get the 1.2 version from CodePlex - http://vmwaretasks.codeplex.com. Confirm that you still have the problem. This error means that the type initializer threw an exception in the VMWareInterop constructor. Frankly, I have no idea why if VixCOM is installed. My next guess is that the library has a problem on a german OS (could be VixCOM) - do you have another machine to try this on?

The next thing to do is to write the same program calling VixCOM directly. There're several samples in the vmwaretasks source code that you can just compile and run (under source\VixCOM). If it still happens, then the vmware community forum should have the answer.


GeneralRe: Exception by conect to vmware ESXi 3.5 U4 or vmwarews 3.5.1 please help
supersidor
7:58 15 Oct '09  
I encountered the same error. One should build .NET project as x86 (not x64) to solve issue
GeneralVMWareTasks 1.2 has been released
dB.
11:47 21 Apr '09  
http://vmwaretasks.codeplex.com - check it out!

- Completed VixCOM API full support.
1626: VMWareVirtualHost.Register and Unregister.
1631: VMWareVirtualMachine.InstallTools.
1629: VMWareVirtualMachine.Snapshots.Enabled.
1630: VMWareVirtualMachine.GetFileInfoInGuest.
2688: VMWareVirtualMachine.Clone and VMWareSnapshot.Clone.
2691: VMWareVirtualMachine.Delete.
1628: VMWareVirtualMachine.BeginRecording and EndRecording, VMWareSnapshot.BeginReplay and EndReplay.
1633: VMWareVirtualMachine.Reset, Suspend, Pause, UnPause, IsPaused and IsSuspended.
1913: VMWareVirtualHost.IsConnected.
1634: VMWareVirtualMachine.RunScriptInGuest.
1632: VMWareVirtualMachine.OpenUrlInGuest.
1635: VMWareVirtualMachine.UpgradeVirtualHardware.
- Added an optional VMWareTools package built on top of VMWareLib that implements additional common VMWare tasks.
VMWareLib.Tools.GuestOS.IpAddress: guest operating system IP address information.
VMWareLib.Tools.GuestOS.ReadFile, ReadFileLines and ReadFileBytes: read remote files as binary data or text with encoding support.
2232: VMWareLib.Tools.Windows.Shell.GetEnvironmentVariables: obtain logged-in user environment.
VMWareLib.Tools.Windows.Shell.RunCommandInGuest: runs commands and collect console output.
VMWareLib.Tools.Windows.MappedNetworkDrive: maps guest operating system network resources.
- Backwards incompatible interface changes.
VMWareVirtaulMachine.PowerOn no longer calls WaitForRenamed VMWareVirtualMachine.Login into LoginInGuest and renamed VMWareVirtualMachine.Logout to LogoutFromGuest to be consistent with VIX COM API and allow power-on without tools installed.
- Misc improvements.
Added VMWareVirtualMachine.ShutdownGuest and PowerOff that allow specifying shutdown parameters explicitly.
Added support for VMWare Server with VMWareVirtualMachine.ConnectToVMWareServer.
Exposed a VMWareVirtualMachine.LoginInGuest function with power options.
Lots of new documentation with examples.
- Bugs.
GetNamedSnapshot behaves differently on Workstation and VI, now throws exception when snapshot not found. Use FindSnapshotByName to get a null result when the snapshot doesn't exist.
KillProcessInGuest unit test needs to wait for process to actually die according to VMWare docs.
Removing a shared folder doesn't remove it from the collection when not the same object.
Fixed different behavior of ListDirectoryInGuest between Workstation and VI.
API-level errors aren't surfaced and the callback wait will never be set when VixCOM is not installed.


Generalenvironment variables?
jbc1
2:30 7 Apr '09  
Hi,

Is there any chance you could show me how to get environment variable values from the guest using this API?

Thanks,
jbc1
GeneralRe: environment variables?
dB.
5:10 7 Apr '09  
Theoretically it's really simple with VMWareTasks.

virtualMachine.GuestEnvironmentVariables["name"]

In practice, this doesn't work correctly. This is probably a bug in the VIX COM API. See http://communities.vmware.com/message/1166742#1166742[^] for a discussion.

Until VMWare fixes this, your best bet might be to dump environment variables into a file via RunProgramInGuest, bring the file back via CopyFileFromHostToGuest and parse the file into a hashtable.



Last Updated 13 Feb 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010