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,130 @@
// 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.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WebsitePanel.VmConfig
{
class ChangeAdministratorPasswordModule : IProvisioningModule
{
#region IProvisioningModule Members
public ExecutionResult Run(ref ExecutionContext context)
{
ExecutionResult ret = new ExecutionResult();
ret.ResultCode = 0;
ret.ErrorMessage = null;
ret.RebootRequired = false;
context.ActivityDescription = "Changing password for built-in local Administrator account...";
context.Progress = 0;
if (!context.Parameters.ContainsKey("Password"))
{
ret.ResultCode = 2;
ret.ErrorMessage = "Parameter 'Password' not found";
Log.WriteError(ret.ErrorMessage);
context.Progress = 100;
return ret;
}
string password = context.Parameters["Password"];
if (string.IsNullOrEmpty(password))
{
ret.ResultCode = 2;
ret.ErrorMessage = "Password is null or empty";
Log.WriteError(ret.ErrorMessage);
context.Progress = 100;
return ret;
}
try
{
string userPath = string.Format("WinNT://{0}/{1}", System.Environment.MachineName, GetAdministratorName());
DirectoryEntry userEntry = new DirectoryEntry(userPath);
userEntry.Invoke("SetPassword", new object[] { password });
userEntry.CommitChanges();
userEntry.Close();
}
catch (Exception ex)
{
if (IsPasswordPolicyException(ex))
{
ret.ResultCode = 1;
ret.ErrorMessage = "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.";
}
else
{
ret.ResultCode = 2;
ret.ErrorMessage = ex.ToString();
}
Log.WriteError(ret.ErrorMessage);
}
if (ret.ResultCode == 0)
{
Log.WriteInfo("Password has been changed successfully");
}
context.Progress = 100;
return ret;
}
#endregion
private bool IsPasswordPolicyException(Exception ex)
{
//0x800708C5
if (ex is System.Runtime.InteropServices.COMException &&
((System.Runtime.InteropServices.COMException)ex).ErrorCode == -2147022651)
{
return true;
}
if (ex.InnerException != null)
return IsPasswordPolicyException(ex.InnerException);
else
return false;
}
private string GetAdministratorName()
{
WmiUtils wmi = new WmiUtils("root\\cimv2");
ManagementObjectCollection objUsers = wmi.ExecuteQuery("Select * From Win32_UserAccount Where LocalAccount = TRUE");
foreach (ManagementObject objUser in objUsers)
{
string sid = (string)objUser["SID"];
if (sid != null && sid.StartsWith("S-1-5-") && sid.EndsWith("-500"))
return (string)objUser["Name"];
}
return null;
}
}
}

View file

@ -0,0 +1,124 @@
// 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.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.VmConfig
{
class ChangeComputerNameModule : IProvisioningModule
{
//P/Invoke signature
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetComputerNameEx(COMPUTER_NAME_FORMAT nameType, [MarshalAs(UnmanagedType.LPTStr)] string lpBuffer);
private enum COMPUTER_NAME_FORMAT : int
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified,
ComputerNameMax
}
#region IProvisioningModule Members
public ExecutionResult Run(ref ExecutionContext context)
{
ExecutionResult ret = new ExecutionResult();
ret.ResultCode = 0;
ret.ErrorMessage = null;
ret.RebootRequired = true;
context.ActivityDescription = "Changing computer name...";
context.Progress = 0;
if (!context.Parameters.ContainsKey("FullComputerName"))
{
ret.ResultCode = 2;
ret.ErrorMessage = "Parameter 'FullComputerName' not found";
Log.WriteError(ret.ErrorMessage);
context.Progress = 100;
return ret;
}
// Call SetComputerEx
string computerName = context.Parameters["FullComputerName"];
string netBiosName = computerName;
string primaryDnsSuffix = "";
int idx = netBiosName.IndexOf(".");
if (idx != -1)
{
netBiosName = computerName.Substring(0, idx);
primaryDnsSuffix = computerName.Substring(idx + 1);
}
try
{
// set NetBIOS name
bool res = SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname, netBiosName);
if (!res)
{
ret.ResultCode = 1;
ret.ErrorMessage = "Unexpected error";
Log.WriteError(ret.ErrorMessage);
}
// set primary DNS suffix
res = SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsDomain, primaryDnsSuffix);
if (!res)
{
ret.ResultCode = 1;
ret.ErrorMessage = "Unexpected error";
Log.WriteError(ret.ErrorMessage);
}
}
catch (Exception ex)
{
ret.ResultCode = 1;
ret.ErrorMessage = ex.ToString();
Log.WriteError(ret.ErrorMessage);
}
if (ret.ResultCode == 0)
{
Log.WriteInfo("Computer name has been changed successfully");
}
context.Progress = 100;
return ret;
}
#endregion
}
}

View file

@ -0,0 +1,95 @@
// 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 Microsoft.Win32;
namespace WebsitePanel.VmConfig
{
[Serializable]
public sealed class ExecutionContext
{
public string ActivityID { get; set; }
public string ActivityName { get; set; }
public string ActivityDefinition { get; set; }
private string activityDescription;
public string ActivityDescription
{
get
{
return activityDescription;
}
set
{
activityDescription = value;
SaveState();
}
}
private int progress = 0;
public int Progress
{
get
{
return progress;
}
set
{
progress = value;
if (progress < 0)
progress = 0;
if (progress > 100)
progress = 100;
SaveState();
}
}
private Dictionary<string, string> parameters = new Dictionary<string, string>();
public Dictionary<string, string> Parameters
{
get { return parameters; }
}
private void SaveState()
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey("SOFTWARE\\Microsoft\\Virtual Machine\\Guest");
if (rk != null)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("ActivityDefinition={0}|", ActivityDefinition);
builder.AppendFormat("ActivityDescription={0}|", ActivityDescription);
builder.AppendFormat("Progress={0}", Progress);
rk.SetValue("WSP-CurrentTask", builder.ToString());
}
}
}
}

View file

@ -0,0 +1,43 @@
// 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.VmConfig
{
[Serializable]
public class ExecutionResult
{
public int ResultCode { get; set; }
public string ErrorMessage { get; set; }
public bool RebootRequired { get; set; }
public string Value { get; set; }
}
}

View file

@ -0,0 +1,39 @@
// 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.VmConfig
{
public interface IProvisioningModule
{
ExecutionResult Run(ref ExecutionContext context);
}
}

View file

@ -0,0 +1,166 @@
// 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.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace WebsitePanel.VmConfig
{
/// <summary>
/// Log.
/// </summary>
public sealed class Log
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private Log()
{
}
/// <summary>
/// Initializes trace listeners.
/// </summary>
static Log()
{
//Trace.Listeners.Clear();
//TextWriterTraceListener consoleListener = new TextWriterTraceListener(Console.Out);
//Trace.Listeners.Add(consoleListener);
Trace.AutoFlush = true;
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="ex">Exception.</param>
public static void WriteError(string message, Exception ex)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
Trace.WriteLine(ex);
}
catch { }
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
public static void WriteError(string message)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write to log
/// </summary>
/// <param name="message"></param>
public static void Write(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.Write(line);
}
catch { }
}
/// <summary>
/// Write line to log
/// </summary>
/// <param name="message"></param>
public static void WriteLine(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write info message to log
/// </summary>
/// <param name="message"></param>
public static void WriteInfo(string message)
{
try
{
string line = string.Format("[{0:G}] INFO: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write start message to log
/// </summary>
/// <param name="message"></param>
public static void WriteStart(string message)
{
try
{
string line = string.Format("[{0:G}] START: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write end message to log
/// </summary>
/// <param name="message"></param>
public static void WriteEnd(string message)
{
try
{
string line = string.Format("[{0:G}] END: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
}
}

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("WebsitePanel Virtual Machine Configuration Service")]
[assembly: AssemblyDescription("Performs provisioning operations in the guest operating system.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("WebsitePanel VPS Solution")]
[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("8adf53f7-5d3a-45b6-829c-8ae1a23af047")]

View file

@ -0,0 +1,226 @@
// 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 Microsoft.Win32;
namespace WebsitePanel.VmConfig
{
/// <summary>
/// Registry helper class.
/// </summary>
public sealed class RegistryUtils
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private RegistryUtils()
{
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static string GetRegistryKeyStringValue(string subkey, string name)
{
string ret = null;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
ret = (string)rk.GetValue(name, string.Empty);
}
return ret;
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static int GetRegistryKeyInt32Value(string subkey, string name)
{
int ret = 0;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
ret = (int)rk.GetValue(name, 0);
}
return ret;
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static bool GetRegistryKeyBooleanValue(string subkey, string name)
{
bool ret = false;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
string strValue = (string)rk.GetValue(name, "False");
ret = Boolean.Parse(strValue);
}
return ret;
}
public static bool RegistryKeyExist(string subkey)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
return (rk != null);
}
/// <summary>
/// Deletes a registry subkey and any child subkeys.
/// </summary>
/// <param name="subkey">Subkey to delete.</param>
public static void DeleteRegistryKey(string subkey)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
root.DeleteSubKeyTree(subkey);
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyStringValue(string subkey, string name, string value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if (rk != null)
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyInt32Value(string subkey, string name, int value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if (rk != null)
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyBooleanValue(string subkey, string name, bool value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if (rk != null)
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Return the list of sub keys for the specified registry key.
/// </summary>
/// <param name="subkey">The name of the registry key</param>
/// <returns>The array of subkey names.</returns>
public static string[] GetRegistrySubKeys(string subkey)
{
string[] ret = new string[0];
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
ret = rk.GetSubKeyNames();
return ret;
}
public static int GetSubKeyCount(string subkey)
{
int ret = 0;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
ret = rk.SubKeyCount;
return ret;
}
/// <summary>
/// Return the list of value names for the specified registry key.
/// </summary>
/// <param name="subkey">The name of the registry key</param>
/// <returns>The array of value names.</returns>
public static string[] GetRegistryKeyValueNames(string subkey)
{
string[] ret = new string[0];
RegistryKey root = Registry.LocalMachine;
using (RegistryKey rk = root.OpenSubKey(subkey))
{
if (rk != null)
ret = rk.GetValueNames();
}
return ret;
}
/// <summary>
/// Deletes registry key value.
/// </summary>
public static void DeleteRegistryKeyValue(string subkey, string valueName)
{
RegistryKey root = Registry.LocalMachine;
using (RegistryKey rk = root.OpenSubKey(subkey, true))
{
if (rk != null)
rk.DeleteValue(valueName);
}
}
}
}

View file

@ -0,0 +1,281 @@
// 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.Management;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace WebsitePanel.VmConfig
{
public class SetupNetworkAdapterModule : IProvisioningModule
{
internal const string RegistryKey = @"SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}";
#region IProvisioningModule Members
public ExecutionResult Run(ref ExecutionContext context)
{
ExecutionResult ret = new ExecutionResult();
ret.ResultCode = 0;
ret.ErrorMessage = null;
ret.RebootRequired = false;
context.ActivityDescription = "Configuring network adapter...";
context.Progress = 0;
if (!CheckParameter(context, "MAC"))
{
ProcessError(context, ret, null, 2, "Parameter 'MAC' is not specified");
return ret;
}
string macAddress = context.Parameters["MAC"];
if (!IsValidMACAddress(macAddress))
{
ProcessError(context, ret, null, 2, "Parameter 'MAC' has invalid format. It should be in 12:34:56:78:90:ab format.");
return ret;
}
string adapterId = null;
ManagementObject objAdapter = null;
ManagementObjectCollection objAdapters = null;
int attempts = 0;
try
{
WmiUtils wmi = new WmiUtils("root\\cimv2");
string query = string.Format("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress = '{0}' AND IPEnabled = True", macAddress);
//try to find adapter for 10 times
while (true)
{
objAdapters = wmi.ExecuteQuery(query);
if (objAdapters.Count > 0)
{
foreach (ManagementObject adapter in objAdapters)
{
objAdapter = adapter;
adapterId = (string)adapter["SettingID"];
}
break;
}
if (attempts > 9)
{
ProcessError(context, ret, null, 2, "Network adapter not found");
return ret;
}
attempts++;
Log.WriteError(string.Format("Attempt #{0} to find network adapter failed!", attempts));
// wait 1 min
System.Threading.Thread.Sleep(60000);
//repeat loop
}
}
catch (Exception ex)
{
ProcessError(context, ret, ex, 2, "Network adapter configuration error: ");
return ret;
}
if (CheckParameter(context, "EnableDHCP", "True"))
{
try
{
EnableDHCP(objAdapter);
}
catch (Exception ex)
{
ProcessError(context, ret, ex, 2, "DHCP error: ");
return ret;
}
}
else if (CheckParameter(context, "EnableDHCP", "False"))
{
if (!CheckParameter(context, "DefaultIPGateway"))
{
ProcessError(context, ret, null, 2, "Parameter 'DefaultIPGateway' is not specified");
return ret;
}
if (!CheckParameter(context, "IPAddress"))
{
ProcessError(context, ret, null, 2, "Parameter 'IPAddresses' is not specified");
return ret;
}
if (!CheckParameter(context, "SubnetMask"))
{
ProcessError(context, ret, null, 2, "Parameter 'SubnetMasks' is not specified");
return ret;
}
try
{
DisableDHCP(context, objAdapter);
}
catch (Exception ex)
{
ProcessError(context, ret, ex, 2, "Network adapter configuration error: ");
return ret;
}
}
if (CheckParameter(context, "PreferredDNSServer"))
{
try
{
SetDNSServer(context, objAdapter);
}
catch (Exception ex)
{
ProcessError(context, ret, ex, 2, "DNS error: ");
return ret;
}
}
context.Progress = 100;
return ret;
}
private void SetDNSServer(ExecutionContext context, ManagementObject objAdapter)
{
string[] dnsServers = ParseArray(context.Parameters["PreferredDNSServer"]);
Log.WriteStart("Configuring DNS...");
ManagementBaseObject objDNS = objAdapter.GetMethodParameters("SetDNSServerSearchOrder");
objDNS["DNSServerSearchOrder"] = dnsServers;
if (dnsServers.Length == 1 && dnsServers[0] == "0.0.0.0")
{
objDNS["DNSServerSearchOrder"] = new string[] { };
}
ManagementBaseObject objRet = objAdapter.InvokeMethod("SetDNSServerSearchOrder", objDNS, null);
Log.WriteEnd("DNS configured");
}
private static string[] ParseArray(string array)
{
if (string.IsNullOrEmpty(array))
throw new ArgumentException("array");
string[] ret = array.Split(';');
return ret;
}
private static void ProcessError(ExecutionContext context, ExecutionResult ret, Exception ex, int errorCode, string errorPrefix)
{
ret.ResultCode = errorCode;
ret.ErrorMessage = errorPrefix;
if (ex != null)
ret.ErrorMessage += ex.ToString();
Log.WriteError(ret.ErrorMessage);
context.Progress = 100;
}
private static void EnableDHCP(ManagementObject adapter)
{
Log.WriteStart("Enabling DHCP...");
object ret1 = adapter.InvokeMethod("EnableDHCP", new object[] { });
object ret2 = adapter.InvokeMethod("RenewDHCPLease", new object[] { });
Log.WriteEnd("DHCP enabled");
}
private static void DisableDHCP(ExecutionContext context, ManagementObject adapter)
{
string[] ipGateways = ParseArray(context.Parameters["DefaultIPGateway"]);
string[] ipAddresses = ParseArray(context.Parameters["IPAddress"]);
string[] subnetMasks = ParseArray(context.Parameters["SubnetMask"]);
if (subnetMasks.Length != ipAddresses.Length)
{
throw new ArgumentException("Number of Subnet Masks should be equal to IP Addresses");
}
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGateway = null;
objNewIP = adapter.GetMethodParameters("EnableStatic");
objNewGateway = adapter.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGateway["DefaultIPGateway"] = ipGateways;
int[] cost = new int[ipGateways.Length];
for (int i = 0; i < cost.Length; i++)
cost[i] = 1;
objNewGateway["GatewayCostMetric"] = cost;
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = ipAddresses;
objNewIP["SubnetMask"] = subnetMasks;
Log.WriteStart("Configuring static IP...");
objSetIP = adapter.InvokeMethod("EnableStatic", objNewIP, null);
Log.WriteEnd("IP configured");
Log.WriteStart("Configuring default gateway...");
objSetIP = adapter.InvokeMethod("SetGateways", objNewGateway, null);
Log.WriteEnd("Default gateway configured");
}
private static bool IsValidMACAddress(string mac)
{
return Regex.IsMatch(mac, "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$");
}
private static bool CheckParameter(ExecutionContext context, string name)
{
return (context.Parameters.ContainsKey(name) && !string.IsNullOrEmpty(context.Parameters[name]));
}
private static bool CheckParameter(ExecutionContext context, string name, string value)
{
return (context.Parameters.ContainsKey(name) && context.Parameters[name] == value);
}
private void ChangeMACAddress(string adapterId, string mac)
{
string[] sets = RegistryUtils.GetRegistrySubKeys(RegistryKey);
foreach (string set in sets)
{
string key = string.Format("{0}\\{1}", RegistryKey, set);
string netCfgInstanceId = RegistryUtils.GetRegistryKeyStringValue(key, "NetCfgInstanceId");
if (netCfgInstanceId == adapterId)
{
Log.WriteStart("Changing MAC address...");
RegistryUtils.SetRegistryKeyStringValue(key, "NetworkAddress", mac);
Log.WriteEnd("MAC address has been changed successfully");
break;
}
}
}
#endregion
}
}

View file

@ -0,0 +1,103 @@
<?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>{456AA9C9-AB1C-490D-AD33-33EADE1071C1}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WebsitePanel.VmConfig</RootNamespace>
<AssemblyName>WebsitePanel.VmConfig.Common</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<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="System" />
<Reference Include="System.Data" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.Management" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\VersionInfo.cs">
<Link>VersionInfo.cs</Link>
</Compile>
<Compile Include="ChangeAdministratorPasswordModule.cs" />
<Compile Include="ExecutionContext.cs" />
<Compile Include="IProvisioningModule.cs" />
<Compile Include="Log.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ExecutionResult.cs" />
<Compile Include="ChangeComputerNameModule.cs" />
<Compile Include="RegistryUtils.cs" />
<Compile Include="SetupNetworkAdapterModule.cs" />
<Compile Include="WmiUtils.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,81 @@
// 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.Management;
namespace WebsitePanel.VmConfig
{
/// <summary>
/// Summary description for WmiHelper.
/// </summary>
public class WmiUtils
{
// namespace
string ns = null;
ManagementScope scope = null;
public WmiUtils(string ns)
{
this.ns = ns;
}
public ManagementObjectCollection ExecuteQuery(string query)
{
ObjectQuery objectQuery = new ObjectQuery(query);
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(WmiScope, objectQuery);
return searcher.Get();
}
public ManagementClass GetClass(string path)
{
return new ManagementClass(WmiScope, new ManagementPath(path), null);
}
public ManagementObject GetObject(string path)
{
return new ManagementObject(WmiScope, new ManagementPath(path), null);
}
private ManagementScope WmiScope
{
get
{
if (scope == null)
{
ManagementPath path = new ManagementPath(ns);
scope = new ManagementScope(path, new ConnectionOptions());
scope.Connect();
}
return scope;
}
}
}
}