Initial project's source code check-in.

This commit is contained in:
ptsurbeleu 2011-07-13 16:07:32 -07:00
commit b03b0b373f
4573 changed files with 981205 additions and 0 deletions

View file

@ -0,0 +1,20 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyCopyright("Copyright © 2011 Outercurve Foundation.")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.34")]
[assembly: AssemblyInformationalVersion("1.2.0")]

View file

@ -0,0 +1,27 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{58249F88-194C-4F6C-872D-94AA37B62E6D}"
ProjectSection(SolutionItems) = preProject
..\..\LICENSE.txt = ..\..\LICENSE.txt
..\..\Readme.htm = ..\..\Readme.htm
..\..\ReleaseNotes.htm = ..\..\ReleaseNotes.htm
VersionInfo.cs = VersionInfo.cs
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.HyperV.Utils", "WebsitePanel.HyperV.Utils\WebsitePanel.HyperV.Utils.csproj", "{824FB237-2208-4BD7-9F61-413DC2A32827}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{824FB237-2208-4BD7-9F61-413DC2A32827}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{824FB237-2208-4BD7-9F61-413DC2A32827}.Debug|Any CPU.Build.0 = Debug|Any CPU
{824FB237-2208-4BD7-9F61-413DC2A32827}.Release|Any CPU.ActiveCfg = Release|Any CPU
{824FB237-2208-4BD7-9F61-413DC2A32827}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,48 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WebsitePanel.HyperV.Utils
{
public class ConcreteJob
{
public string Id { get; set; }
public ConcreteJobState JobState { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
public DateTime ElapsedTime { get; set; }
public DateTime StartTime { get; set; }
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public int PercentComplete { get; set; }
}
}

View file

@ -0,0 +1,47 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.HyperV.Utils
{
public enum ConcreteJobState
{
New = 2,
Starting = 3,
Running = 4,
Suspended = 5,
ShuttingDown = 6,
Completed = 7,
Terminated = 8,
Killed = 9,
Exception = 10
}
}

View file

@ -0,0 +1,40 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.HyperV.Utils
{
public class JobResult
{
public ConcreteJob Job { get; set; }
public ReturnCode ReturnValue { get; set; }
}
}

View file

@ -0,0 +1,445 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Management;
using Vds = Microsoft.Storage.Vds;
using System.Diagnostics;
namespace WebsitePanel.HyperV.Utils
{
class Program
{
// command line parameters
private const string ns = @"root\virtualization";
private static Wmi wmi = null;
private static string computer = null;
private static string command = null;
private static Dictionary<string, string> Parameters = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
static void Main(string[] args)
{
// display welcome screen
DisplayWelcome();
// parse parameters
if (!ParseParameters(args))
{
DisplayUsage();
return;
}
// connect WMI
wmi = new Wmi(computer, ns);
try
{
// run command
if (String.Equals(command, "MountVHD", StringComparison.CurrentCultureIgnoreCase))
MountVHD();
else if (String.Equals(command, "UnmountVHD", StringComparison.CurrentCultureIgnoreCase))
UnmountVHD();
else
{
Console.WriteLine("Unknown command: " + command);
DisplayUsage();
}
}
catch (Exception ex)
{
Console.WriteLine("\nError: " + ex.Message);
if (ex.InnerException != null)
Console.WriteLine("System message: " + ex.InnerException.Message);
}
}
private static void MountVHD()
{
// check parameters
AssertParameter("path");
string vhdPath = Parameters["path"];
ManagementObject objImgSvc = GetImageManagementService();
Console.WriteLine("Mount VHD: " + vhdPath);
// get method params
ManagementBaseObject inParams = objImgSvc.GetMethodParameters("Mount");
inParams["Path"] = vhdPath;
ManagementBaseObject outParams = (ManagementBaseObject)objImgSvc.InvokeMethod("Mount", inParams, null);
JobResult result = CreateJobResultFromWmiMethodResults(outParams);
// load storage job
if (result.ReturnValue != ReturnCode.JobStarted
|| result.Job.JobState == ConcreteJobState.Exception)
{
throw new Exception("Mount job failed to start with the following message: " + result.Job.ErrorDescription);
}
ManagementObject objJob = wmi.GetWmiObject("msvm_StorageJob", "InstanceID = '{0}'", result.Job.Id);
if (JobCompleted(result.Job))
{
// load output data
ManagementObject objImage = wmi.GetRelatedWmiObject(objJob, "Msvm_MountedStorageImage");
int pathId = Convert.ToInt32(objImage["PathId"]);
int portNumber = Convert.ToInt32(objImage["PortNumber"]);
int targetId = Convert.ToInt32(objImage["TargetId"]);
int lun = Convert.ToInt32(objImage["Lun"]);
string diskAddress = String.Format("Port{0}Path{1}Target{2}Lun{3}", portNumber, pathId, targetId, lun);
// find mounted disk using VDS
Vds.Advanced.AdvancedDisk advancedDisk = null;
Vds.Pack diskPack = null;
// first attempt
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Querying mounted disk...");
FindVdsDisk(diskAddress, out advancedDisk, out diskPack);
// second attempt
if (advancedDisk == null)
{
System.Threading.Thread.Sleep(20000);
Console.WriteLine("Querying mounted disk - second attempt...");
FindVdsDisk(diskAddress, out advancedDisk, out diskPack);
}
if (advancedDisk == null)
throw new Exception("Could not find mounted disk");
List<string> volumes = new List<string>();
Console.WriteLine("Disk flags: " + advancedDisk.Flags);
// clear READONLY
if ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly)
{
Console.Write("Clearing disk Read-Only flag...");
advancedDisk.ClearFlags(Vds.DiskFlags.ReadOnly);
while ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly)
{
System.Threading.Thread.Sleep(100);
advancedDisk.Refresh();
}
Console.WriteLine("Done");
}
// bring disk ONLINE
if (advancedDisk.Status == Vds.DiskStatus.Offline)
{
Console.Write("Bringing disk online...");
advancedDisk.Online();
while (advancedDisk.Status == Vds.DiskStatus.Offline)
{
System.Threading.Thread.Sleep(100);
advancedDisk.Refresh();
}
Console.WriteLine("Done");
}
// determine disk index for DiskPart
Wmi cimv2 = new Wmi(computer, "root\\CIMV2");
ManagementObject objDisk = cimv2.GetWmiObject("win32_diskdrive",
"Model='Msft Virtual Disk SCSI Disk Device' and ScsiTargetID={0} and ScsiLogicalUnit={1} and scsiPort={2}",
targetId, lun, portNumber);
if (objDisk != null)
{
Console.WriteLine("DiskPart disk index: " + Convert.ToInt32(objDisk["Index"]));
}
// find volume
diskPack.Refresh();
foreach (Vds.Volume volume in diskPack.Volumes)
{
volumes.Add(volume.DriveLetter.ToString());
}
if (volumes.Count == 0 && objDisk != null)
{
// find volumes using WMI
foreach (ManagementObject objPartition in objDisk.GetRelated("Win32_DiskPartition"))
{
foreach (ManagementObject objVolume in objPartition.GetRelated("Win32_LogicalDisk"))
{
volumes.Add(objVolume["Name"].ToString().TrimEnd(':'));
}
}
}
foreach (string volume in volumes)
{
Console.WriteLine("Volume found: " + volume);
}
//// find disk index
//Wmi win32 = new Wmi(computer, @"root\cimv2");
//System.Threading.Thread.Sleep(1000); // small pause
//ManagementObject objDisk = win32.GetWmiObject("win32_DiskDrive",
// "Model='Msft Virtual Disk SCSI Disk Device' and ScsiTargetID={0} and ScsiLogicalUnit={1} and ScsiPort={2}",
// targetId, lun, portNumber);
//int diskIndex = Convert.ToInt32(objDisk["Index"]);
Console.WriteLine("\nDisk has been mounted.\n");
//Console.WriteLine("Disk index: " + advancedDisk.);
}
}
private static void FindVdsDisk(string diskAddress, out Vds.Advanced.AdvancedDisk advancedDisk, out Vds.Pack diskPack)
{
advancedDisk = null;
diskPack = null;
Vds.ServiceLoader serviceLoader = new Vds.ServiceLoader();
Vds.Service vds = serviceLoader.LoadService(computer);
vds.WaitForServiceReady();
foreach (Vds.Disk disk in vds.UnallocatedDisks)
{
if (disk.DiskAddress == diskAddress)
{
advancedDisk = (Vds.Advanced.AdvancedDisk)disk;
break;
}
}
if (advancedDisk == null)
{
vds.HardwareProvider = false;
vds.SoftwareProvider = true;
foreach (Vds.SoftwareProvider provider in vds.Providers)
foreach (Vds.Pack pack in provider.Packs)
foreach (Vds.Disk disk in pack.Disks)
if (disk.DiskAddress == diskAddress)
{
diskPack = pack;
advancedDisk = (Vds.Advanced.AdvancedDisk)disk;
break;
}
}
}
private static void UnmountVHD()
{
// check parameters
AssertParameter("path");
string vhdPath = Parameters["path"];
Console.WriteLine("Unmount VHD: " + vhdPath);
ManagementObject objImgSvc = GetImageManagementService();
// get method params
ManagementBaseObject inParams = objImgSvc.GetMethodParameters("Unmount");
inParams["Path"] = vhdPath;
ManagementBaseObject outParams = (ManagementBaseObject)objImgSvc.InvokeMethod("Unmount", inParams, null);
ReturnCode result = (ReturnCode)Convert.ToInt32(outParams["ReturnValue"]);
if (result != ReturnCode.OK)
{
throw new Exception("Unmount task failed with the \"" + result + "\" code");
}
Console.WriteLine("\nDisk has been unmounted.");
}
#region Jobs
private static bool JobCompleted(ConcreteJob job)
{
bool jobCompleted = true;
while (job.JobState == ConcreteJobState.Starting ||
job.JobState == ConcreteJobState.Running)
{
System.Threading.Thread.Sleep(200);
job = GetJob(job.Id);
}
if (job.JobState != ConcreteJobState.Completed)
{
jobCompleted = false;
}
return jobCompleted;
}
public static ConcreteJob GetJob(string jobId)
{
ManagementObject objJob = GetJobWmiObject(jobId);
return CreateJobFromWmiObject(objJob);
}
private static ConcreteJob CreateJobFromWmiMethodResults(ManagementBaseObject outParams)
{
ManagementBaseObject objJob = wmi.GetWmiObjectByPath((string)outParams["Job"]);
if (objJob == null || objJob.Properties.Count == 0)
return null;
return CreateJobFromWmiObject(objJob);
}
private static JobResult CreateJobResultFromWmiMethodResults(ManagementBaseObject outParams)
{
JobResult result = new JobResult();
// return value
result.ReturnValue = (ReturnCode)Convert.ToInt32(outParams["ReturnValue"]);
// job
ManagementBaseObject objJob = wmi.GetWmiObjectByPath((string)outParams["Job"]);
if (objJob != null && objJob.Properties.Count > 0)
{
result.Job = CreateJobFromWmiObject(objJob);
}
return result;
}
private static ManagementObject GetJobWmiObject(string id)
{
return wmi.GetWmiObject("CIM_ConcreteJob", "InstanceID = '{0}'", id);
}
private static ConcreteJob CreateJobFromWmiObject(ManagementBaseObject objJob)
{
if (objJob == null || objJob.Properties.Count == 0)
return null;
ConcreteJob job = new ConcreteJob();
job.Id = (string)objJob["InstanceID"];
job.JobState = (ConcreteJobState)Convert.ToInt32(objJob["JobState"]);
job.Caption = (string)objJob["Caption"];
job.Description = (string)objJob["Description"];
job.ElapsedTime = wmi.ToDateTime((string)objJob["ElapsedTime"]);
job.StartTime = wmi.ToDateTime((string)objJob["StartTime"]);
job.ErrorCode = Convert.ToInt32(objJob["ErrorCode"]);
job.ErrorDescription = (string)objJob["ErrorDescription"];
job.PercentComplete = Convert.ToInt32(objJob["PercentComplete"]);
return job;
}
#endregion
#region Managers
private static ManagementObject GetVirtualSystemManagementService()
{
return wmi.GetWmiObject("msvm_VirtualSystemManagementService");
}
private static ManagementObject GetVirtualSwitchManagementService()
{
return wmi.GetWmiObject("msvm_VirtualSwitchManagementService");
}
private static ManagementObject GetImageManagementService()
{
return wmi.GetWmiObject("msvm_ImageManagementService");
}
#endregion
private static void DisplayWelcome()
{
string ver = Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
Console.WriteLine("VmUtils - utility to work with Hyper-V virtual resources. Version " + ver);
Console.WriteLine("Copyright (C) 2011 by Outercurve Foundation. All rights reserved.\n");
}
private static bool ParseParameters(string[] args)
{
if (args == null || args.Length == 0)
return false;
// command
command = args[0];
for (int i = 1; i < args.Length; i++)
{
if (!args[i].StartsWith("-"))
return false; // wrong parameter format
string name = args[i].Substring(1);
if (i == (args.Length - 1))
return false; // no parameter value
string val = args[i + 1];
i++;
// add parameter to the hash
Parameters.Add(name, val);
if (String.Equals(name, "computer", StringComparison.CurrentCultureIgnoreCase))
computer = val;
}
return true;
}
private static void AssertParameter(string name)
{
if (!Parameters.ContainsKey(name))
{
throw new Exception(String.Format("Command \"{0}\" expect \"{1}\" parameter which was not supplied.", command, name));
}
}
private static void DisplayUsage()
{
Console.WriteLine("\nUSAGE:");
Console.WriteLine(" vmutils <command> [-parameter1 value1 -parameter2 value2 ...]\n");
Console.WriteLine("EXAMPLE:");
Console.WriteLine(" vmtuils MountVHD -path \"c:\\templates\\Windows 2008.vhd\" -computer HYPERV01\n");
Console.WriteLine("SUPPORTED COMMANDS:");
Console.WriteLine(" MountVHD - mounts VHD.");
Console.WriteLine(" Parameters:");
Console.WriteLine(" -path - path to VHD file.");
Console.WriteLine(" -computer - (optional) remote computer with Hyper-V role installed.");
Console.WriteLine("");
Console.WriteLine(" UnmountVHD - unmounts VHD.");
Console.WriteLine(" Parameters:");
Console.WriteLine(" -path - path to VHD file.");
Console.WriteLine(" -computer - (optional) remote computer with Hyper-V role installed.");
}
}
}

View file

@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hyper-V Utilities")]
[assembly: AssemblyDescription("Utility to work with Hyper-V virtual resources.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("VmUtils")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c72a836b-0d6e-482f-afba-8c03964d9933")]

View file

@ -0,0 +1,51 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.HyperV.Utils
{
public enum ReturnCode
{
OK = 0,
JobStarted = 4096,
Failed = 32768,
AccessDenied = 32769,
NotSupported = 32770,
Unknown = 32771,
Timeout = 32772,
InvalidParameter = 32773,
SystemIsInUse = 32774,
InvalidStateForThisOperation = 32775,
IncorrectDataType = 32776,
SystemIsNotAvailable = 32777,
OutOfMemory = 32778
}
}

View file

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{824FB237-2208-4BD7-9F61-413DC2A32827}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WebsitePanel.HyperV.Utils</RootNamespace>
<AssemblyName>WebsitePanel.HyperV.Utils</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<StartupObject>WebsitePanel.HyperV.Utils.Program</StartupObject>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Storage.Vds, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\Microsoft.Storage.Vds.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\VersionInfo.cs">
<Link>VersionInfo.cs</Link>
</Compile>
<Compile Include="ConcreteJob.cs" />
<Compile Include="ConcreteJobState.cs" />
<Compile Include="JobResult.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ResultCode.cs" />
<Compile Include="Wmi.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View file

@ -0,0 +1,306 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Diagnostics;
namespace WebsitePanel.HyperV.Utils
{
internal class Wmi
{
string nameSpace = null;
string computerName = null;
ManagementScope scope = null;
public Wmi(string nameSpace)
: this(nameSpace, null)
{
}
public Wmi(string computerName, string nameSpace)
{
this.nameSpace = nameSpace;
this.computerName = computerName;
}
internal ManagementObjectCollection ExecuteWmiQuery(string query, params object[] args)
{
if (args != null && args.Length > 0)
query = String.Format(query, args);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(GetScope(),
new ObjectQuery(query));
return searcher.Get();
}
internal ManagementObject GetWmiObject(string className, string filter, params object[] args)
{
ManagementObjectCollection col = GetWmiObjects(className, filter, args);
ManagementObjectCollection.ManagementObjectEnumerator enumerator = col.GetEnumerator();
return enumerator.MoveNext() ? (ManagementObject)enumerator.Current : null;
}
internal ManagementObject GetWmiObject(string className)
{
return GetWmiObject(className, null);
}
internal ManagementObjectCollection GetWmiObjects(string className, string filter, params object[] args)
{
string query = "select * from " + className;
if (!String.IsNullOrEmpty(filter))
query += " where " + filter;
return ExecuteWmiQuery(query, args);
}
internal ManagementObjectCollection GetWmiObjects(string className)
{
return GetWmiObjects(className, null);
}
internal ManagementObject GetWmiObjectByPath(string path)
{
return new ManagementObject(GetScope(), new ManagementPath(path), null);
}
internal ManagementClass GetWmiClass(string className)
{
return new ManagementClass(GetScope(), new ManagementPath(className), null);
}
internal ManagementObject GetRelatedWmiObject(ManagementObject obj, string className)
{
ManagementObjectCollection col = obj.GetRelated(className);
ManagementObjectCollection.ManagementObjectEnumerator enumerator = col.GetEnumerator();
enumerator.MoveNext();
return (ManagementObject)enumerator.Current;
}
internal void Dump(ManagementBaseObject obj)
{
#if DEBUG
foreach (PropertyData prop in obj.Properties)
{
string typeName = prop.Value == null ? "null" : prop.Value.GetType().ToString();
Debug.WriteLine(prop.Name + ": " + prop.Value + " (" + typeName + ")");
}
#endif
}
// Converts a given datetime in DMTF format to System.DateTime object.
internal System.DateTime ToDateTime(string dmtfDate)
{
System.DateTime initializer = System.DateTime.MinValue;
int year = initializer.Year;
int month = initializer.Month;
int day = initializer.Day;
int hour = initializer.Hour;
int minute = initializer.Minute;
int second = initializer.Second;
long ticks = 0;
string dmtf = dmtfDate;
System.DateTime datetime = System.DateTime.MinValue;
string tempString = string.Empty;
if (String.IsNullOrEmpty(dmtf))
{
return DateTime.MinValue;
}
else if ((dmtf.Length != 25))
{
throw new System.ArgumentOutOfRangeException();
}
try
{
tempString = dmtf.Substring(0, 4);
if (("****" != tempString))
{
year = int.Parse(tempString);
}
tempString = dmtf.Substring(4, 2);
if (("**" != tempString))
{
month = int.Parse(tempString);
}
tempString = dmtf.Substring(6, 2);
if (("**" != tempString))
{
day = int.Parse(tempString);
}
tempString = dmtf.Substring(8, 2);
if (("**" != tempString))
{
hour = int.Parse(tempString);
}
tempString = dmtf.Substring(10, 2);
if (("**" != tempString))
{
minute = int.Parse(tempString);
}
tempString = dmtf.Substring(12, 2);
if (("**" != tempString))
{
second = int.Parse(tempString);
}
tempString = dmtf.Substring(15, 6);
if (("******" != tempString))
{
ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000))));
}
if (((((((((year < 0)
|| (month < 0))
|| (day < 0))
|| (hour < 0))
|| (minute < 0))
|| (minute < 0))
|| (second < 0))
|| (ticks < 0)))
{
throw new System.ArgumentOutOfRangeException();
}
}
catch (System.Exception e)
{
throw new System.ArgumentOutOfRangeException(null, e.Message);
}
if (year == 0
&& month == 0
&& day == 0
&& hour == 0
&& minute == 0
&& second == 0
&& ticks == 0)
return DateTime.MinValue;
datetime = new System.DateTime(year, month, day, hour, minute, second, 0);
datetime = datetime.AddTicks(ticks);
System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
int UTCOffset = 0;
int OffsetToBeAdjusted = 0;
long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
tempString = dmtf.Substring(22, 3);
if ((tempString != "******"))
{
tempString = dmtf.Substring(21, 4);
try
{
UTCOffset = int.Parse(tempString);
}
catch (System.Exception e)
{
throw new System.ArgumentOutOfRangeException(null, e.Message);
}
OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset)));
datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted)));
}
return datetime;
}
// Converts a given System.DateTime object to DMTF datetime format.
internal string ToDmtfDateTime(System.DateTime date)
{
string utcString = string.Empty;
System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date);
long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
if ((System.Math.Abs(OffsetMins) > 999))
{
date = date.ToUniversalTime();
utcString = "+000";
}
else
{
if ((tickOffset.Ticks >= 0))
{
utcString = string.Concat("+", ((System.Int64)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0'));
}
else
{
string strTemp = ((System.Int64)(OffsetMins)).ToString();
utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0'));
}
}
string dmtfDateTime = ((System.Int32)(date.Year)).ToString().PadLeft(4, '0');
dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32)(date.Month)).ToString().PadLeft(2, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32)(date.Day)).ToString().PadLeft(2, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32)(date.Hour)).ToString().PadLeft(2, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32)(date.Minute)).ToString().PadLeft(2, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32)(date.Second)).ToString().PadLeft(2, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, ".");
System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0);
long microsec = ((long)((((date.Ticks - dtTemp.Ticks)
* 1000)
/ System.TimeSpan.TicksPerMillisecond)));
string strMicrosec = ((System.Int64)(microsec)).ToString();
if ((strMicrosec.Length > 6))
{
strMicrosec = strMicrosec.Substring(0, 6);
}
dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0'));
dmtfDateTime = string.Concat(dmtfDateTime, utcString);
return dmtfDateTime;
}
public ManagementScope GetScope()
{
if (scope != null)
return scope;
// create new scope
if (String.IsNullOrEmpty(computerName))
{
// local
scope = new ManagementScope(nameSpace);
}
else
{
// remote
ConnectionOptions options = new ConnectionOptions();
string path = String.Format(@"\\{0}\{1}", computerName, nameSpace);
scope = new ManagementScope(path, options);
}
// connect
try
{
scope.Connect();
}
catch (Exception ex)
{
string computer = "";
if (!String.IsNullOrEmpty(computerName))
computer = " on computer \"" + computerName + "\"";
throw new Exception("Hyper-V service could not be connected" + computer, ex);
}
return scope;
}
}
}