// -----------------------------------------------------------------------
//
// Copyright (C) 2012 Microsoft Corporation
//
// -----------------------------------------------------------------------
namespace Microsoft.Samples.Management.OData.AssociationClient
{
using System;
using System.Collections.Generic;
using System.Net;
///
/// Program startup
///
public class Program
{
///
/// Constant for HTTP GET verb
///
private const string HttpVerbGet = "GET";
///
/// Constant for HTTP POST verb
///
private const string HttpVerbPost = "POST";
///
/// Constant for HTTP PUT verb
///
private const string HttpVerbPut = "PUT";
///
/// Constant for HTTP DELETE verb
///
private const string HttpVerbDelete = "DELETE";
///
/// Default URI value for the server where association sever is setup. This is the URI created from RoleBasedPlugin sample
///
private const string DefaultUri = "http://localhost:7000/MODataSvc/Microsoft.Management.Odata.svc";
///
/// Default authentication type
///
private const string DefaultAuthType = "Basic";
///
/// Uri of the server where Association is setup
///
private static Uri uri = new Uri(DefaultUri);
///
/// User name to be used for connecting to the server
///
private static string userName;
///
/// Password to be used for connecting to server
///
private static string password;
///
/// Authentication type used
///
private static string authType = DefaultAuthType;
///
/// Domain name for the user
///
private static string domainName;
///
/// Main routine
///
/// Command line arguments
public static void Main(string[] args)
{
if (ParseInputArgs(args) == false)
{
return;
}
// Get all Physical machines
OdataJsonRequest request = new OdataJsonRequest(HttpVerbGet, uri.ToString() + "/PhysicalMachines", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all physical machines");
}
else
{
Console.WriteLine("\nFailed to get physical machines. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
List physicalMachines = new List();
foreach (dynamic machine in request.Response.d.results)
{
PhysicalMachineResource physicalMachine = new PhysicalMachineResource();
physicalMachine.Name = machine.Name;
Console.WriteLine("Physical machine name: " + physicalMachine.Name);
physicalMachines.Add(physicalMachine);
}
// Get Physical machines with associated VMs
request = new OdataJsonRequest(HttpVerbGet, uri.ToString() + "/PhysicalMachines?$expand=VMs", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all physical machine details with all VMs");
}
else
{
Console.WriteLine("\nFailed to get physical machine with all VMs details. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
physicalMachines = new List();
foreach (dynamic machine in request.Response.d.results)
{
PhysicalMachineResource physicalMachine = new PhysicalMachineResource();
physicalMachine.Name = machine.Name;
foreach (dynamic vm in machine.VMs.results)
{
VmResource resource = new VmResource();
resource.Id = Guid.Parse(vm.Id);
resource.MachineName = vm.MachineName;
resource.OS = vm.OS;
physicalMachine.VMs.Add(resource);
}
Console.WriteLine("Physical machine name: " + physicalMachine.Name);
foreach (VmResource vm in physicalMachine.VMs)
{
Console.WriteLine("Associated virtual machine: Id " + vm.Id + " Machine Name " + vm.MachineName);
}
physicalMachines.Add(physicalMachine);
}
// Get list of Systems
request = new OdataJsonRequest(HttpVerbGet, uri.ToString() + "/Systems?$expand=VMs", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all systems details");
}
else
{
Console.WriteLine("\nFailed to get systems details. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
List systems = new List();
foreach (dynamic sys in request.Response.d.results)
{
SystemResource system = new SystemResource();
system.Id = Guid.Parse(sys.Id);
system.Name = sys.Name;
foreach (dynamic vm in sys.VMs.results)
{
VmResource resource = new VmResource();
resource.Id = Guid.Parse(vm.Id);
resource.MachineName = vm.MachineName;
resource.OS = vm.OS;
system.VMs.Add(resource);
}
Console.WriteLine("System Id: " + system.Name + " Name: " + system.Name);
foreach (VmResource vm in system.VMs)
{
Console.WriteLine("Associated virtual machine: Id " + vm.Id + " Machine Name " + vm.MachineName);
}
systems.Add(system);
}
string firstSystemUri = request.Response.d.results[0].__metadata.uri;
// Create a new Virtual machine
request = new OdataJsonRequest(HttpVerbPost, uri.ToString() + "/VirtualMachines", GetCredentials(uri));
request.RequestBody += "{";
request.RequestBody += OdataJsonRequest.EncodeJsonElement("MachineName", physicalMachines[0].Name);
request.RequestBody += ",";
request.RequestBody += OdataJsonRequest.EncodeJsonElement("OS", "win8");
request.RequestBody += "}";
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.Created)
{
Console.WriteLine("\nCreated a new VM " + request.Response.d.__metadata.uri);
}
else
{
Console.WriteLine("\nFailed to create a new VM. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
string newVMUri = request.Response.d.__metadata.uri;
// Get new VM resource
request = new OdataJsonRequest(HttpVerbGet, newVMUri, GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nnReceived a new VM instance " + request.Response.d.__metadata.uri);
}
else
{
Console.WriteLine("\nFailed to get new VM " + request.Response.d.__metadata.uri + "instance. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
VmResource newVM = new VmResource();
dynamic tempVm = request.Response.d;
newVM.Id = Guid.Parse(tempVm.Id);
newVM.MachineName = tempVm.MachineName;
newVM.OS = tempVm.OS;
// Add Virtual Machine in first system
request = new OdataJsonRequest(HttpVerbPost, firstSystemUri + "/$links/VMs", GetCredentials(uri));
request.RequestBody += "{";
request.RequestBody += OdataJsonRequest.EncodeJsonElement("uri", newVMUri);
request.RequestBody += "}";
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.NoContent)
{
Console.WriteLine("\nAdded VM " + newVMUri + " to the System " + firstSystemUri);
}
else
{
Console.WriteLine("\nFailed to add VM " + newVMUri + " to the system " + firstSystemUri + ". Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
// Get list of Virtual Machines for the System
request = new OdataJsonRequest(HttpVerbGet, firstSystemUri + "/$links/VMs", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all VMs for the system " + firstSystemUri);
}
else
{
Console.WriteLine("\nFailed to get all VMs for the system " + firstSystemUri + ". Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
List links = new List();
foreach (dynamic d in request.Response.d.results)
{
links.Add(d.uri);
}
if (links.Contains(newVMUri))
{
Console.WriteLine("VM " + newVMUri + " is present in the list of VMs associated with the system " + firstSystemUri);
}
else
{
Console.WriteLine("Error: VM " + newVMUri + " is not present in the list of VMs associated with the system " + firstSystemUri);
return;
}
// Remove Virtual Machine from System
request = new OdataJsonRequest(HttpVerbDelete, firstSystemUri + "/$links/VMs(Id=guid'" + newVM.Id + "',MachineName='" + newVM.MachineName + "')", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.NoContent)
{
Console.WriteLine("\nRemoved VM " + newVMUri + " from the system " + firstSystemUri);
}
else
{
Console.WriteLine("\nFailed to remove VM " + newVMUri + " from the system " + firstSystemUri + ". Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
// Get list of Virtual Machines for the System
request = new OdataJsonRequest(HttpVerbGet, firstSystemUri + "/$links/VMs", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all VMs for the system " + firstSystemUri);
}
else
{
Console.WriteLine("\nFailed to get all VMs for the system " + firstSystemUri + ". Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
links = new List();
foreach (dynamic d in request.Response.d.results)
{
links.Add(d.uri);
}
if (links.Contains(newVMUri))
{
Console.WriteLine("Error: VM " + newVMUri + " is associated with the system " + firstSystemUri);
}
else
{
Console.WriteLine("VM " + newVMUri + " is not associated with the system " + firstSystemUri);
}
// Delete the VM
request = new OdataJsonRequest(HttpVerbDelete, newVMUri, GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.NoContent)
{
Console.WriteLine("\nRemoved VM " + newVMUri);
}
else
{
Console.WriteLine("\nFailed to removed VM " + newVMUri + ". Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
// Get all VMs
request = new OdataJsonRequest(HttpVerbGet, uri.ToString() + "/VirtualMachines", GetCredentials(uri));
request.SendReceive();
if (request.ResponseStatus == HttpStatusCode.OK)
{
Console.WriteLine("\nReceived all VMs ");
}
else
{
Console.WriteLine("\nFailed to receive all VMs. Http Status Code " + request.ResponseStatus + "\n Response message: " + request.ResponseBody);
return;
}
List allVmLinks = new List();
foreach (dynamic d in request.Response.d.Results)
{
allVmLinks.Add(d.__metadata.uri);
}
if (allVmLinks.Contains(newVMUri))
{
Console.WriteLine("Error: VM " + newVMUri + " is present");
}
else
{
Console.WriteLine("VM " + newVMUri + " is not present");
}
}
///
/// Parses command line arguments passed to the sample
///
/// Command line arguments
/// true, if found arguments correctly else false
private static bool ParseInputArgs(string[] args)
{
bool invalidInput = false;
for (int i = 0; i < args.Length; i += 2)
{
string key = args[i];
string value = ((i + 1) < args.Length) ? args[i + 1] : string.Empty;
switch (key.ToLower())
{
case "-username":
userName = value;
break;
case "-password":
password = value;
break;
case "-authtype":
authType = value;
break;
case "-domain":
domainName = value;
break;
case "-uri":
try
{
uri = new Uri(value);
}
catch (UriFormatException ex)
{
Console.WriteLine("Error: Invalid Uri passed- " + ex.Message);
invalidInput = true;
}
break;
default:
invalidInput = true;
break;
}
}
if (invalidInput || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
{
Console.WriteLine("Incorrect input was passed");
ShowUsage();
return false;
}
return true;
}
///
/// Shows usage for the sample
///
private static void ShowUsage()
{
Console.WriteLine("Usage: Microsoft.Samples.Management.OData.AssociationClient.exe -UserName -Password [-AuthType ] [-Domain ] [-Uri ]");
Console.WriteLine("-UserName: User name");
Console.WriteLine("-Passowrd: Password");
Console.WriteLine("-Domain: [Optional] Domain name ");
Console.WriteLine("-AuthType: [Optional] Authentication type. Default value " + DefaultAuthType);
Console.WriteLine("-Uri: [Optional] Management OData endpoint service document uri. Default value " + DefaultUri);
}
///
/// Creates credentials
///
/// Uri of the server
/// Credentials cache
private static CredentialCache GetCredentials(Uri uri)
{
NetworkCredential serviceCreds = null;
if (string.IsNullOrEmpty(domainName))
{
serviceCreds = new NetworkCredential(userName, password);
}
else
{
serviceCreds = new NetworkCredential(userName, password, domainName);
}
CredentialCache cache = new CredentialCache();
// If server is setup to use some authentication mechanism other than "Basic", change the authentication mechanism below
cache.Add(uri, authType, serviceCreds);
return cache;
}
}
///
/// Physical machine resource
///
internal class PhysicalMachineResource
{
///
/// Initializes a new instance of the PhysicalMachineResource class
///
public PhysicalMachineResource()
{
this.VMs = new List();
}
///
/// Initializes a new instance of the PhysicalMachineResource class
///
/// Name of the machine
public PhysicalMachineResource(string name)
: this()
{
this.Name = name;
}
///
/// Gets or sets Name of the machine
///
public string Name { get; set; }
///
/// Gets list of Virtual machines associated with the machine
///
public List VMs { get; private set; }
}
///
/// Virtual machine resource
///
internal class VmResource
{
///
/// Initializes a new instance of the VmResource class
///
public VmResource()
{
}
///
/// Initializes a new instance of the VmResource class
///
/// Physical machine name
/// Operating system
public VmResource(PhysicalMachineResource physicalMachine, string os)
: this()
{
this.OS = os;
this.PhysicalMachine = physicalMachine;
this.MachineName = physicalMachine.Name;
this.Id = Guid.NewGuid();
}
///
/// Gets or sets machine name
///
public string MachineName { get; set; }
///
/// Gets or sets virtual machine id
///
public Guid Id { get; set; }
///
/// Gets or sets operating system value
///
public string OS { get; set; }
///
/// Gets or sets physical machine
///
public PhysicalMachineResource PhysicalMachine { get; set; }
///
/// Gets or sets system resource
///
public SystemResource System { get; set; }
}
///
/// System resource
///
internal class SystemResource
{
///
/// Initializes a new instance of the SystemResource class.
///
public SystemResource()
{
this.VMs = new List();
}
///
/// Initializes a new instance of the SystemResource class.
///
/// Name of the system
public SystemResource(string name)
: this()
{
this.Id = Guid.NewGuid();
this.Name = name;
}
///
/// Gets or sets name of the system
///
public string Name { get; set; }
///
/// Gets or sets id of the system
///
public Guid Id { get; set; }
///
/// Gets collection of virtual machines associated with the system
///
public List VMs { get; private set; }
}
}