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,230 @@
// 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.Xml;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace WebsitePanel.Setup
{
public sealed class AppConfig
{
public const string AppConfigFileNameWithoutExtension = "WebsitePanel.Installer.exe";
private AppConfig()
{
}
private static Configuration appConfig = null;
private static XmlDocument xmlConfig = null;
public static void LoadConfiguration()
{
//
var exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfigFileNameWithoutExtension);
//
appConfig = ConfigurationManager.OpenExeConfiguration(exePath);
//
ConfigurationSection section = appConfig.Sections["installer"];
if (section == null)
throw new ConfigurationErrorsException("instalelr section not found");
string strXml = section.SectionInformation.GetRawXml();
xmlConfig = new XmlDocument();
xmlConfig.LoadXml(strXml);
}
public static XmlDocument Configuration
{
get
{
return xmlConfig;
}
}
public static void EnsureComponentConfig(string componentId)
{
var xmlConfigNode = GetComponentConfig(componentId);
//
if (xmlConfigNode != null)
return;
//
CreateComponentConfig(componentId);
}
public static XmlNode CreateComponentConfig(string componentId)
{
XmlNode components = Configuration.SelectSingleNode("//components");
if (components == null)
{
components = Configuration.CreateElement("components");
Configuration.FirstChild.AppendChild(components);
}
XmlElement componentNode = Configuration.CreateElement("component");
componentNode.SetAttribute("id", componentId);
components.AppendChild(componentNode);
XmlElement settingsNode = Configuration.CreateElement("settings");
componentNode.AppendChild(settingsNode);
return componentNode;
}
public static XmlNode GetComponentConfig(string componentId)
{
string xPath = string.Format("//component[@id=\"{0}\"]", componentId);
return Configuration.SelectSingleNode(xPath);
}
public static void SaveConfiguration()
{
if (appConfig != null && xmlConfig != null)
{
ConfigurationSection section = appConfig.Sections["installer"];
section.SectionInformation.SetRawXml(xmlConfig.OuterXml);
appConfig.Save();
}
}
public static void SetComponentSettingStringValue(string componentId, string settingName, string value)
{
XmlNode componentNode = GetComponentConfig(componentId);
XmlNode settings = componentNode.SelectSingleNode("settings");
string xpath = string.Format("add[@key=\"{0}\"]", settingName);
XmlNode settingNode = settings.SelectSingleNode(xpath);
if (settingNode == null)
{
settingNode = Configuration.CreateElement("add");
XmlUtils.SetXmlAttribute(settingNode, "key", settingName);
settings.AppendChild(settingNode);
}
XmlUtils.SetXmlAttribute(settingNode, "value", value);
}
public static void SetComponentSettingBooleanValue(string componentId, string settingName, bool value)
{
XmlNode componentNode = GetComponentConfig(componentId);
XmlNode settings = componentNode.SelectSingleNode("settings");
string xpath = string.Format("add[@key=\"{0}\"]", settingName);
XmlNode settingNode = settings.SelectSingleNode(xpath);
if (settingNode == null)
{
settingNode = Configuration.CreateElement("add");
XmlUtils.SetXmlAttribute(settingNode, "key", settingName);
settings.AppendChild(settingNode);
}
XmlUtils.SetXmlAttribute(settingNode, "value", value.ToString());
}
public static void LoadComponentSettings(SetupVariables vars)
{
XmlNode componentNode = GetComponentConfig(vars.ComponentId);
//
if (componentNode != null)
{
var typeRef = vars.GetType();
//
XmlNodeList settingNodes = componentNode.SelectNodes("settings/add");
//
foreach (XmlNode item in settingNodes)
{
var sName = XmlUtils.GetXmlAttribute(item, "key");
var sValue = XmlUtils.GetXmlAttribute(item, "value");
//
if (String.IsNullOrEmpty(sName))
continue;
//
var objProperty = typeRef.GetProperty(sName);
//
if (objProperty == null)
continue;
// Set property value
objProperty.SetValue(vars, Convert.ChangeType(sValue, objProperty.PropertyType), null);
}
}
}
public static string GetComponentSettingStringValue(string componentId, string settingName)
{
string ret = null;
XmlNode componentNode = GetComponentConfig(componentId);
if (componentNode != null)
{
string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName);
XmlNode settingNode = componentNode.SelectSingleNode(xpath);
if (settingNode != null)
{
ret = XmlUtils.GetXmlAttribute(settingNode, "value");
}
}
return ret;
}
internal static int GetComponentSettingInt32Value(string componentId, string settingName)
{
int ret = 0;
XmlNode componentNode = GetComponentConfig(componentId);
if (componentNode != null)
{
string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName);
XmlNode settingNode = componentNode.SelectSingleNode(xpath);
string val = XmlUtils.GetXmlAttribute(settingNode, "value");
Int32.TryParse(val, out ret);
}
return ret;
}
internal static bool GetComponentSettingBooleanValue(string componentId, string settingName)
{
bool ret = false;
XmlNode componentNode = GetComponentConfig(componentId);
if (componentNode != null)
{
string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName);
XmlNode settingNode = componentNode.SelectSingleNode(xpath);
string val = XmlUtils.GetXmlAttribute(settingNode, "value");
Boolean.TryParse(val, out ret);
}
return ret;
}
internal static string GetSettingStringValue(string settingName)
{
string ret = null;
string xPath = string.Format("settings/add[@key=\"{0}\"]", settingName);
XmlNode settingNode = Configuration.SelectSingleNode(xPath);
if (settingNode != null)
{
ret = XmlUtils.GetXmlAttribute(settingNode, "value");
}
return ret;
}
}
}

View file

@ -0,0 +1,217 @@
// 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;
using System.IO;
using System.Security.Cryptography;
namespace WebsitePanel.Setup
{
internal class CRC32 : HashAlgorithm
{
protected static uint AllOnes = 0xffffffff;
protected static Hashtable cachedCRC32Tables;
protected static bool autoCache;
protected uint[] crc32Table;
private uint m_crc;
/// <summary>
/// Returns the default polynomial (used in WinZip, Ethernet, etc)
/// </summary>
public static uint DefaultPolynomial
{
get { return 0x04C11DB7; }
}
/// <summary>
/// Gets or sets the auto-cache setting of this class.
/// </summary>
public static bool AutoCache
{
get { return autoCache; }
set { autoCache = value; }
}
/// <summary>
/// Initialize the cache
/// </summary>
static CRC32()
{
cachedCRC32Tables = Hashtable.Synchronized(new Hashtable());
autoCache = true;
}
public static void ClearCache()
{
cachedCRC32Tables.Clear();
}
/// <summary>
/// Builds a crc32 table given a polynomial
/// </summary>
/// <param name="ulPolynomial"></param>
/// <returns></returns>
protected static uint[] BuildCRC32Table(uint ulPolynomial)
{
uint dwCrc;
uint[] table = new uint[256];
// 256 values representing ASCII character codes.
for (int i = 0; i < 256; i++)
{
dwCrc = (uint)i;
for (int j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
dwCrc = (dwCrc >> 1) ^ ulPolynomial;
else
dwCrc >>= 1;
}
table[i] = dwCrc;
}
return table;
}
/// <summary>
/// Creates a CRC32 object using the DefaultPolynomial
/// </summary>
public CRC32()
: this(DefaultPolynomial)
{
}
/// <summary>
/// Creates a CRC32 object using the specified Creates a CRC32 object
/// </summary>
public CRC32(uint aPolynomial)
: this(aPolynomial, CRC32.AutoCache)
{
}
/// <summary>
/// Construct the
/// </summary>
public CRC32(uint aPolynomial, bool cacheTable)
{
this.HashSizeValue = 32;
crc32Table = (uint[])cachedCRC32Tables[aPolynomial];
if (crc32Table == null)
{
crc32Table = CRC32.BuildCRC32Table(aPolynomial);
if (cacheTable)
cachedCRC32Tables.Add(aPolynomial, crc32Table);
}
Initialize();
}
/// <summary>
/// Initializes an implementation of HashAlgorithm.
/// </summary>
public override void Initialize()
{
m_crc = AllOnes;
}
/// <summary>
///
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
protected override void HashCore(byte[] buffer, int offset, int count)
{
// Save the text in the buffer.
for (int i = offset; i < count; i++)
{
ulong tabPtr = (m_crc & 0xFF) ^ buffer[i];
m_crc >>= 8;
m_crc ^= crc32Table[tabPtr];
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override byte[] HashFinal()
{
byte[] finalHash = new byte[4];
ulong finalCRC = m_crc ^ AllOnes;
finalHash[0] = (byte)((finalCRC >> 24) & 0xFF);
finalHash[1] = (byte)((finalCRC >> 16) & 0xFF);
finalHash[2] = (byte)((finalCRC >> 8) & 0xFF);
finalHash[3] = (byte)((finalCRC >> 0) & 0xFF);
return finalHash;
}
/// <summary>
/// Computes the hash value for the specified Stream.
/// </summary>
new public byte[] ComputeHash(Stream inputStream)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, 4096)) > 0)
{
HashCore(buffer, 0, bytesRead);
}
return HashFinal();
}
/// <summary>
/// Overloaded. Computes the hash value for the input data.
/// </summary>
new public byte[] ComputeHash(byte[] buffer)
{
return ComputeHash(buffer, 0, buffer.Length);
}
/// <summary>
/// Overloaded. Computes the hash value for the input data.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
new public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
HashCore(buffer, offset, count);
return HashFinal();
}
}
}

View file

@ -0,0 +1,68 @@
// 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.Setup
{
public enum CheckTypes
{
None,
OperationSystem,
IISVersion,
ASPNET,
WPServer,
WPEnterpriseServer,
WPPortal,
ASPNET32
}
public enum CheckStatuses
{
Success,
Warning,
Error
}
public class ConfigurationCheck
{
public ConfigurationCheck(CheckTypes checkType, string action)
{
this.CheckType = checkType;
this.Action = action;
}
public CheckTypes CheckType {get;set;}
public string Action { get; set; }
public CheckStatuses Status {get;set;}
public string Details { get; set; }
public SetupVariables SetupVariables { get; set; }
}
}

View file

@ -0,0 +1,132 @@
// 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.IO;
using System.Windows.Forms;
namespace WebsitePanel.Setup
{
/// <summary>
/// Shows copy process.
/// </summary>
public sealed class CopyProcess
{
private ProgressBar progressBar;
private DirectoryInfo sourceFolder;
private DirectoryInfo destFolder;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="bar">Progress bar.</param>
/// <param name="source">Source folder.</param>
/// <param name="destination">Destination folder.</param>
public CopyProcess(ProgressBar bar, string source, string destination)
{
this.progressBar = bar;
this.sourceFolder = new DirectoryInfo(source);
this.destFolder = new DirectoryInfo(destination);
}
/// <summary>
/// Copy source to the destination folder.
/// </summary>
internal void Run()
{
// unzip
long totalSize = FileUtils.CalculateFolderSize(sourceFolder.FullName);
long copied = 0;
progressBar.Minimum = 0;
progressBar.Maximum = 100;
progressBar.Value = 0;
int i = 0;
List<DirectoryInfo> folders = new List<DirectoryInfo>();
List<FileInfo> files = new List<FileInfo>();
DirectoryInfo di = null;
//FileInfo fi = null;
string path = null;
// Part 1: Indexing
folders.Add(sourceFolder);
while (i < folders.Count)
{
foreach (DirectoryInfo info in folders[i].GetDirectories())
{
if (!folders.Contains(info))
folders.Add(info);
}
foreach (FileInfo info in folders[i].GetFiles())
{
files.Add(info);
}
i++;
}
// Part 2: Destination Folders Creation
///////////////////////////////////////////////////////
for (i = 0; i < folders.Count; i++)
{
if (folders[i].Exists)
{
path = destFolder.FullName +
Path.DirectorySeparatorChar +
folders[i].FullName.Remove(0, sourceFolder.FullName.Length);
di = new DirectoryInfo(path);
// Prevent IOException
if (!di.Exists)
di.Create();
}
}
// Part 3: Source to Destination File Copy
///////////////////////////////////////////////////////
for (i = 0; i < files.Count; i++)
{
if (files[i].Exists)
{
path = destFolder.FullName +
Path.DirectorySeparatorChar +
files[i].FullName.Remove(0, sourceFolder.FullName.Length + 1);
FileUtils.CopyFile(files[i], path);
copied += files[i].Length;
if (totalSize != 0)
{
progressBar.Value = Convert.ToInt32(copied * 100 / totalSize);
}
}
}
}
}
}

View file

@ -0,0 +1,266 @@
// 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.Web.Services3;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.HostedSolution;
namespace WebsitePanel.Setup
{
public class ServerContext
{
public string Server { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
/// <summary>
/// ES Proxy class
/// </summary>
public class ES
{
public const int ERROR_USER_WRONG_PASSWORD = -110;
public const int ERROR_USER_WRONG_USERNAME = -109;
public const int ERROR_USER_ACCOUNT_CANCELLED = -105;
public const int ERROR_USER_ACCOUNT_DEMO = -106;
public const int ERROR_USER_ACCOUNT_PENDING = -103;
public const int ERROR_USER_ACCOUNT_SHOULD_BE_ADMINISTRATOR = -107;
public const int ERROR_USER_ACCOUNT_SHOULD_BE_RESELLER = -108;
public const int ERROR_USER_ACCOUNT_SUSPENDED = -104;
private static ServerContext serverContext = null;
private static void InitializeServices(ServerContext context)
{
serverContext = context;
}
public static bool Connect(string server, string username, string password)
{
bool ret = true;
ServerContext serverContext = new ServerContext();
serverContext.Server = server;
serverContext.Username = username;
serverContext.Password = password;
InitializeServices(serverContext);
int status = -1;
try
{
status = ES.Services.Authentication.AuthenticateUser(serverContext.Username, serverContext.Password, null);
}
catch (Exception ex)
{
Log.WriteError("Authentication error", ex);
return false;
}
string errorMessage = "Check your internet connection or server URL.";
if (status != 0)
{
switch (status)
{
case ERROR_USER_WRONG_USERNAME:
errorMessage = "Wrong username.";
break;
case ERROR_USER_WRONG_PASSWORD:
errorMessage = "Wrong password.";
break;
case ERROR_USER_ACCOUNT_CANCELLED:
errorMessage = "Account cancelled.";
break;
case ERROR_USER_ACCOUNT_PENDING:
errorMessage = "Account pending.";
break;
}
Log.WriteError(
string.Format("Cannot connect to the remote server. {0}", errorMessage));
ret = false;
}
return ret;
}
public static ES Services
{
get
{
return new ES();
}
}
public esSystem System
{
get { return GetCachedProxy<esSystem>(); }
}
public esApplicationsInstaller ApplicationsInstaller
{
get { return GetCachedProxy<esApplicationsInstaller>(); }
}
public esAuditLog AuditLog
{
get { return GetCachedProxy<esAuditLog>(); }
}
public esAuthentication Authentication
{
get { return GetCachedProxy<esAuthentication>(false); }
}
public esComments Comments
{
get { return GetCachedProxy<esComments>(); }
}
public esDatabaseServers DatabaseServers
{
get { return GetCachedProxy<esDatabaseServers>(); }
}
public esFiles Files
{
get { return GetCachedProxy<esFiles>(); }
}
public esFtpServers FtpServers
{
get { return GetCachedProxy<esFtpServers>(); }
}
public esMailServers MailServers
{
get { return GetCachedProxy<esMailServers>(); }
}
public esOperatingSystems OperatingSystems
{
get { return GetCachedProxy<esOperatingSystems>(); }
}
public esPackages Packages
{
get { return GetCachedProxy<esPackages>(); }
}
public esScheduler Scheduler
{
get { return GetCachedProxy<esScheduler>(); }
}
public esTasks Tasks
{
get { return GetCachedProxy<esTasks>(); }
}
public esServers Servers
{
get { return GetCachedProxy<esServers>(); }
}
public esStatisticsServers StatisticsServers
{
get { return GetCachedProxy<esStatisticsServers>(); }
}
public esUsers Users
{
get { return GetCachedProxy<esUsers>(); }
}
public esWebServers WebServers
{
get { return GetCachedProxy<esWebServers>(); }
}
public esSharePointServers SharePointServers
{
get { return GetCachedProxy<esSharePointServers>(); }
}
public esImport Import
{
get { return GetCachedProxy<esImport>(); }
}
public esBackup Backup
{
get { return GetCachedProxy<esBackup>(); }
}
public esExchangeServer ExchangeServer
{
get { return GetCachedProxy<esExchangeServer>(); }
}
public esOrganizations Organizations
{
get { return GetCachedProxy<esOrganizations>(); }
}
protected ES()
{
}
protected virtual T GetCachedProxy<T>()
{
return GetCachedProxy<T>(true);
}
protected virtual T GetCachedProxy<T>(bool secureCalls)
{
if (serverContext == null)
{
throw new Exception("Server context is not specified");
}
Type t = typeof(T);
string key = t.FullName + ".ServiceProxy";
T proxy = (T)Activator.CreateInstance(t);
object p = proxy;
// configure proxy
EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator();
cnfg.EnterpriseServerUrl = serverContext.Server;
if (secureCalls)
{
cnfg.Username = serverContext.Username;
cnfg.Password = serverContext.Password;
}
cnfg.Configure((WebServicesClientProtocol)p);
return proxy;
}
}
}

View file

@ -0,0 +1,535 @@
// 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.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Ionic.Zip;
namespace WebsitePanel.Setup
{
/// <summary>
/// File utils.
/// </summary>
public sealed class FileUtils
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private FileUtils()
{
}
/// <summary>
/// Returns current application path.
/// </summary>
/// <returns>Curent application path.</returns>
public static string GetCurrentDirectory()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
/// <summary>
/// Returns application temp directory.
/// </summary>
/// <returns>Application temp directory.</returns>
public static string GetTempDirectory()
{
return Path.Combine(GetCurrentDirectory(), "Tmp");
}
/// <summary>
/// Returns application data directory.
/// </summary>
/// <returns>Application data directory.</returns>
public static string GetDataDirectory()
{
return Path.Combine(GetCurrentDirectory(), "Data");
}
internal static void UnzipFile(string targetDir, string zipFile)
{
using (ZipFile zip = ZipFile.Read(zipFile))
{
foreach (ZipEntry e in zip)
{
e.Extract(targetDir, ExtractExistingFileAction.OverwriteSilently);
}
}
}
/// <summary>
/// Creates drectory with the specified directory.
/// </summary>
/// <param name="path">The directory path to create.</param>
internal static void CreateDirectory(string path)
{
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
// create directory structure
Directory.CreateDirectory(dir);
}
}
/// <summary>
/// Saves file content.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="content">The array of bytes to write.</param>
internal static void SaveFileContent(string fileName, byte[] content)
{
FileStream stream = new FileStream(fileName, FileMode.Create);
stream.Write(content, 0, content.Length);
stream.Close();
}
/// <summary>
/// Saves file content.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="content">The array of bytes to write.</param>
internal static void AppendFileContent(string fileName, byte[] content)
{
FileStream stream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
stream.Write(content, 0, content.Length);
stream.Close();
}
/// <summary>
/// Copies the specified file.
/// </summary>
internal static void CopyFile(FileInfo sourceFile, string destinationFile)
{
int attempts = 0;
while (true)
{
try
{
CopyFileInternal(sourceFile, destinationFile);
break;
}
catch (Exception)
{
if (attempts > 2)
throw;
attempts++;
System.Threading.Thread.Sleep(1000);
}
}
}
/// <summary>
/// Copies the specified file.
/// </summary>
private static void CopyFileInternal(FileInfo sourceFile, string destinationFile)
{
try
{
sourceFile.CopyTo(destinationFile, true);
}
catch (UnauthorizedAccessException)
{
//try to overwrite read-only file
OverwriteReadOnlyFile(sourceFile, destinationFile);
}
}
/// <summary>
/// Copies the specified file.
/// </summary>
private static void OverwriteReadOnlyFile(FileInfo sourceFile, string destinationFile)
{
FileInfo fi = new FileInfo(destinationFile);
if (fi.Exists)
{
fi.Attributes = FileAttributes.Normal;
}
sourceFile.CopyTo(fi.FullName, true);
}
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="fileName">The name of the file to be deleted.</param>
internal static void DeleteFile(string fileName)
{
int attempts = 0;
while (true)
{
try
{
DeleteFileInternal(fileName);
break;
}
catch (Exception)
{
if (attempts > 2)
throw;
attempts++;
System.Threading.Thread.Sleep(1000);
}
}
}
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="fileName">The name of the file to be deleted.</param>
private static void DeleteReadOnlyFile(string fileName)
{
FileInfo info = new FileInfo(fileName);
info.Attributes = FileAttributes.Normal;
info.Delete();
}
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="fileName">The name of the file to be deleted.</param>
private static void DeleteFileInternal(string fileName)
{
try
{
File.Delete(fileName);
}
catch (UnauthorizedAccessException)
{
DeleteReadOnlyFile(fileName);
}
}
/// <summary>
/// Deletes the specified directory.
/// </summary>
/// <param name="directory">The name of the directory to be deleted.</param>
internal static void DeleteDirectory(string directory)
{
if (!Directory.Exists(directory))
return;
// iterate through child folders
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
// iterate through child files
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
DeleteFile(file);
}
//try to delete dir for 3 times
int attempts = 0;
while (true)
{
try
{
DeleteDirectoryInternal(directory);
break;
}
catch (Exception)
{
if (attempts > 2)
throw;
attempts++;
System.Threading.Thread.Sleep(1000);
}
}
}
/// <summary>
/// Deletes the specified directory.
/// </summary>
/// <param name="directory">The name of the directory to be deleted.</param>
private static void DeleteDirectoryInternal(string directory)
{
try
{
Directory.Delete(directory);
}
catch (IOException)
{
DeleteReadOnlyDirectory(directory);
}
}
/// <summary>
/// Deletes the specified directory.
/// </summary>
/// <param name="directory">The name of the directory to be deleted.</param>
private static void DeleteReadOnlyDirectory(string directory)
{
DirectoryInfo info = new DirectoryInfo(directory);
info.Attributes = FileAttributes.Normal;
info.Delete();
}
/// <summary>
/// Determines whether the specified file exists.
/// </summary>
/// <param name="fileName">The path to check.</param>
/// <returns></returns>
internal static bool FileExists(string fileName)
{
return File.Exists(fileName);
}
/// <summary>
/// Determines whether the given path refers to an existing directory on disk.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns></returns>
internal static bool DirectoryExists(string path)
{
return Directory.Exists(path);
}
public static long CalculateFolderSize(string path)
{
int files = 0;
int folders = 0;
return CalculateFolderSize(path, out files, out folders);
}
public static int CalculateFiles(string path)
{
int files = 0;
int folders = 0;
CalculateFolderSize(path, out files, out folders);
return files;
}
public static void CopyFileToFolder(string sourceFile, string destinationFolder)
{
string fileName = Path.GetFileName(sourceFile);
string destinationFile = Path.Combine(destinationFolder, fileName);
CopyFile(new FileInfo(sourceFile), destinationFile);
}
/// <summary>
/// Copy source to the destination folder.
/// </summary>
public static void CopyDirectory(string source, string destination)
{
int i = 0;
List<DirectoryInfo> folders = new List<DirectoryInfo>();
List<FileInfo> files = new List<FileInfo>();
DirectoryInfo sourceFolder = new DirectoryInfo(source);
DirectoryInfo destFolder = new DirectoryInfo(destination);
DirectoryInfo di = null;
FileInfo fi = null;
string path = null;
// Part 1: Indexing
folders.Add(sourceFolder);
while (i < folders.Count)
{
foreach (DirectoryInfo info in folders[i].GetDirectories())
{
if (!folders.Contains(info))
folders.Add(info);
}
foreach (FileInfo info in folders[i].GetFiles())
{
files.Add(info);
}
i++;
}
// Part 2: Destination Folders Creation
///////////////////////////////////////////////////////
for (i = 0; i < folders.Count; i++)
{
if (folders[i].Exists)
{
path = destFolder.FullName +
Path.DirectorySeparatorChar +
folders[i].FullName.Remove(0, sourceFolder.FullName.Length);
di = new DirectoryInfo(path);
// Prevent IOException
if (!di.Exists)
di.Create();
}
}
// Part 3: Source to Destination File Copy
///////////////////////////////////////////////////////
for (i = 0; i < files.Count; i++)
{
if (files[i].Exists)
{
path = destFolder.FullName +
Path.DirectorySeparatorChar +
files[i].FullName.Remove(0, sourceFolder.FullName.Length + 1);
fi = new FileInfo(path);
files[i].CopyTo(fi.FullName, true);
}
}
}
public static long CalculateFolderSize(string path, out int files, out int folders)
{
files = 0;
folders = 0;
if (!Directory.Exists(path))
return 0;
IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
long size = 0;
FindData findData = new FindData();
IntPtr findHandle;
findHandle = Kernel32.FindFirstFile(@"\\?\" + path + @"\*", findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
do
{
if ((findData.fileAttributes & (int)FileAttributes.Directory) != 0)
{
if (findData.fileName != "." && findData.fileName != "..")
{
folders++;
int subfiles, subfolders;
string subdirectory = path + (path.EndsWith(@"\") ? "" : @"\") +
findData.fileName;
size += CalculateFolderSize(subdirectory, out subfiles, out subfolders);
folders += subfolders;
files += subfiles;
}
}
else
{
// File
files++;
size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
}
}
while (Kernel32.FindNextFile(findHandle, findData));
Kernel32.FindClose(findHandle);
}
return size;
}
public static string SizeToString(long size)
{
if (size >= 0x400 && size < 0x100000)
// kilobytes
return SizeToKB(size);
else if (size >= 0x100000 && size < 0x40000000)
// megabytes
return SizeToMB(size);
else if (size >= 0x40000000 && size < 0x10000000000)
// gigabytes
return SizeToGB(size);
else
return string.Format("{0:0.0}", size);
}
public static string SizeToKB(long size)
{
return string.Format("{0:0.0} KB", (float)size / 1024 );
}
public static string SizeToMB(long size)
{
return string.Format("{0:0.0} MB", (float)size / 1024 / 1024);
}
public static string SizeToGB(long size)
{
return string.Format("{0:0.0} GB", (float)size / 1024 / 1024 / 1024);
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
}
#region File Size Calculation helper classes
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
class FindData
{
public int fileAttributes;
public int creationTime_lowDateTime;
public int creationTime_highDateTime;
public int lastAccessTime_lowDateTime;
public int lastAccessTime_highDateTime;
public int lastWriteTime_lowDateTime;
public int lastWriteTime_highDateTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public String fileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public String alternateFileName;
}
class Kernel32
{
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindFirstFile(String fileName, [In, Out] FindData findFileData);
[DllImport("kernel32", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextFile(IntPtr hFindFile, [In, Out] FindData lpFindFileData);
[DllImport("kernel32", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindClose(IntPtr hFindFile);
}
#endregion
}

View file

@ -0,0 +1,261 @@
// 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.Xml;
namespace WebsitePanel.Setup
{
public class Global
{
public const string SilentInstallerShell = "SilentInstallerShell";
public const string DefaultInstallPathRoot = @"C:\WebsitePanel";
public const string LoopbackIPv4 = "127.0.0.1";
public const string InstallerProductCode = "cfg core";
public abstract class Parameters
{
public const string ComponentId = "ComponentId";
public const string EnterpriseServerUrl = "EnterpriseServerUrl";
public const string ShellMode = "ShellMode";
public const string ShellVersion = "ShellVersion";
public const string IISVersion = "IISVersion";
public const string BaseDirectory = "BaseDirectory";
public const string Installer = "Installer";
public const string InstallerType = "InstallerType";
public const string InstallerPath = "InstallerPath";
public const string InstallerFolder = "InstallerFolder";
public const string Version = "Version";
public const string ComponentDescription = "ComponentDescription";
public const string ComponentCode = "ComponentCode";
public const string ApplicationName = "ApplicationName";
public const string ComponentName = "ComponentName";
public const string WebSiteIP = "WebSiteIP";
public const string WebSitePort = "WebSitePort";
public const string WebSiteDomain = "WebSiteDomain";
public const string ServerPassword = "ServerPassword";
public const string UserDomain = "UserDomain";
public const string UserAccount = "UserAccount";
public const string UserPassword = "UserPassword";
public const string CryptoKey = "CryptoKey";
public const string ServerAdminPassword = "ServerAdminPassword";
public const string SetupXml = "SetupXml";
public const string ParentForm = "ParentForm";
public const string Component = "Component";
public const string FullFilePath = "FullFilePath";
public const string DatabaseServer = "DatabaseServer";
public const string DbServerAdmin = "DbServerAdmin";
public const string DbServerAdminPassword = "DbServerAdminPassword";
public const string DatabaseName = "DatabaseName";
public const string ConnectionString = "ConnectionString";
public const string InstallConnectionString = "InstallConnectionString";
public const string Release = "Release";
}
public abstract class Messages
{
public const string NotEnoughPermissionsError = "You do not have the appropriate permissions to perform this operation. Make sure you are running the application from the local disk and you have local system administrator privileges.";
public const string InstallerVersionIsObsolete = "WebsitePanel Installer {0} or higher required.";
public const string ComponentIsAlreadyInstalled = "Component or its part is already installed.";
public const string AnotherInstanceIsRunning = "Another instance of the installation process is already running.";
public const string NoInputParametersSpecified = "No input parameters specified";
public const int InstallationError = -1000;
public const int UnknownComponentCodeError = -999;
public const int SuccessInstallation = 0;
public const int AnotherInstanceIsRunningError = -998;
public const int NotEnoughPermissionsErrorCode = -997;
public const int NoInputParametersSpecifiedError = -996;
public const int ComponentIsAlreadyInstalledError = -995;
}
public abstract class Server
{
public abstract class CLI
{
public const string ServerPassword = "passw";
};
public const string ComponentName = "Server";
public const string ComponentCode = "server";
public const string ComponentDescription = "WebsitePanel Server is a set of services running on the remote server to be controlled. Server application should be reachable from Enterprise Server one.";
public const string ServiceAccount = "WPServer";
public const string DefaultPort = "9003";
public const string DefaultIP = "127.0.0.1";
public const string SetupController = "Server";
public static string[] ServiceUserMembership
{
get
{
if (IISVersion.Major == 7)
{
return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_IUSRS" };
}
//
return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_WPG" };
}
}
}
public abstract class StandaloneServer
{
public const string SetupController = "StandaloneServerSetup";
public const string ComponentCode = "standalone";
public const string ComponentName = "Standalone Server Setup";
}
public abstract class WebPortal
{
public const string ComponentName = "Portal";
public const string ComponentDescription = "WebsitePanel Portal is a control panel itself with user interface which allows managing user accounts, hosting spaces, web sites, FTP accounts, files, etc.";
public const string ServiceAccount = "WPPortal";
public const string DefaultPort = "9001";
public const string DefaultIP = "";
public const string DefaultEntServURL = "http://127.0.0.1:9002";
public const string ComponentCode = "portal";
public const string SetupController = "Portal";
public static string[] ServiceUserMembership
{
get
{
if (IISVersion.Major == 7)
{
return new string[] { "IIS_IUSRS" };
}
//
return new string[] { "IIS_WPG" };
}
}
public abstract class CLI
{
public const string EnterpriseServerUrl = "esurl";
}
}
public abstract class EntServer
{
public const string ComponentName = "Enterprise Server";
public const string ComponentDescription = "Enterprise Server is the heart of WebsitePanel system. It includes all business logic of the application. Enterprise Server should have access to Server and be accessible from Portal applications.";
public const string ServiceAccount = "WPEnterpriseServer";
public const string DefaultPort = "9002";
public const string DefaultIP = "127.0.0.1";
public const string DefaultDbServer = @"localhost\sqlexpress";
public const string DefaultDatabase = "WebsitePanel";
public const string AspNetConnectionStringFormat = "server={0};database={1};uid={2};pwd={3};";
public const string ComponentCode = "enterprise server";
public const string SetupController = "EnterpriseServer";
public static string[] ServiceUserMembership
{
get
{
if (IISVersion.Major == 7)
{
return new string[] { "IIS_IUSRS" };
}
//
return new string[] { "IIS_WPG" };
}
}
public abstract class CLI
{
public const string ServeradminPassword = "passw";
public const string DatabaseName = "dbname";
public const string DatabaseServer = "dbserver";
public const string DbServerAdmin = "dbadmin";
public const string DbServerAdminPassword = "dbapassw";
}
}
public abstract class CLI
{
public const string WebSiteIP = "webip";
public const string ServiceAccountPassword = "upassw";
public const string ServiceAccountDomain = "udomaim";
public const string ServiceAccountName = "uname";
public const string WebSitePort = "webport";
public const string WebSiteDomain = "webdom";
}
private Global()
{
}
private static Version iisVersion;
//
public static Version IISVersion
{
get
{
if (iisVersion == null)
{
iisVersion = RegistryUtils.GetIISVersion();
}
//
return iisVersion;
}
}
//
private static OS.WindowsVersion osVersion = OS.WindowsVersion.Unknown;
/// <summary>
/// Represents Setup Control Panel Accounts system settings set (SCPA)
/// </summary>
public class SCPA
{
public const string SettingsKeyName = "EnabledSCPA";
}
public static OS.WindowsVersion OSVersion
{
get
{
if (osVersion == OS.WindowsVersion.Unknown)
{
osVersion = OS.GetVersion();
}
//
return osVersion;
}
}
public static XmlDocument SetupXmlDocument { get; set; }
}
public class SetupEventArgs<T> : EventArgs
{
public T EventData { get; set; }
public string EventMessage { get; set; }
}
}

View file

@ -0,0 +1,154 @@
// 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.Setup
{
public enum ActionTypes
{
None,
CopyFiles,
CreateWebSite,
CryptoKey,
ServerPassword,
UpdateServerPassword,
UpdateConfig,
UpdateEnterpriseServerUrl,
CreateDatabase,
CreateDatabaseUser,
ExecuteSql,
DeleteRegistryKey,
DeleteDirectory,
DeleteDatabase,
DeleteDatabaseUser,
DeleteDatabaseLogin,
DeleteWebSite,
DeleteVirtualDirectory,
DeleteUserAccount,
DeleteUserMembership,
DeleteApplicationPool,
DeleteFiles,
UpdateWebSite,
//UpdateFiles,
Backup,
BackupDatabase,
BackupDirectory,
BackupConfig,
UpdatePortal2811,
UpdateEnterpriseServer2810,
UpdateServer2810,
CreateShortcuts,
DeleteShortcuts,
UpdateServers,
CopyWebConfig,
UpdateWebConfigNamespaces,
StopApplicationPool,
StartApplicationPool,
RegisterWindowsService,
UnregisterWindowsService,
StartWindowsService,
StopWindowsService,
ServiceSettings,
CreateUserAccount,
InitSetupVariables,
UpdateServerAdminPassword,
UpdateLicenseInformation,
ConfigureStandaloneServerData,
CreateWPServerLogin,
FolderPermissions,
AddCustomErrorsPage,
SwitchServer2AspNet40,
SwitchEntServer2AspNet40,
SwitchWebPortal2AspNet40,
}
public class InstallAction
{
public InstallAction(ActionTypes type)
{
this.ActionType = type;
}
public ActionTypes ActionType{ get; set; }
public string Name{ get; set; }
public string Log{ get; set; }
public string Description{ get; set; }
public string ConnectionString{ get; set; }
public string Key{ get; set; }
public string Path{ get; set; }
public string UserName{ get; set; }
public string SiteId{ get; set; }
public string Source{ get; set; }
public string Destination{ get; set; }
public bool Empty{ get; set; }
public string IP{ get; set; }
public string Port{ get; set; }
public string Domain{ get; set; }
public string[] Membership { get; set; }
public SetupVariables SetupVariables { get; set; }
public string Url { get; set; }
}
}

View file

@ -0,0 +1,79 @@
// 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.Setup
{
public sealed class InstallLog
{
private InstallLog()
{
}
private static StringBuilder sb;
static InstallLog()
{
sb = new StringBuilder("Setup has:");
sb.AppendLine();
}
public static void Append(string value)
{
sb.Append(value);
}
public static void AppendLine(string value)
{
sb.AppendLine(value);
}
public static void AppendLine(string format, params object[] args)
{
sb.AppendLine(String.Format(format, args));
}
public static void AppendLine()
{
sb.AppendLine();
}
public static void AppendFormat(string format, params object[] args)
{
sb.AppendFormat(format, args);
}
public static new string ToString()
{
return sb.ToString();
}
}
}

View file

@ -0,0 +1,174 @@
// 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.Diagnostics;
using System.IO;
namespace WebsitePanel.Setup
{
/// <summary>
/// Installer 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.AutoFlush = true;
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="ex">Exception.</param>
internal static void WriteError(string message, Exception ex)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
if ( ex != null )
Trace.WriteLine(ex);
}
catch { }
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="ex">Exception.</param>
internal static void WriteError(string message)
{
WriteError(message, null);
}
/// <summary>
/// Write to log
/// </summary>
/// <param name="message"></param>
internal 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>
internal 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>
internal 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>
internal static void WriteStart(string message)
{
try
{
string line = string.Format("[{0:G}] START: {1}", DateTime.Now, message);
Trace.WriteLine(line);
Trace.Flush();
}
catch { }
}
/// <summary>
/// Write end message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteEnd(string message)
{
try
{
string line = string.Format("[{0:G}] END: {1}", DateTime.Now, message);
Trace.WriteLine(line);
Trace.Flush();
}
catch { }
}
/// <summary>
/// Opens notepad to view log file.
/// </summary>
public static void ShowLogFile()
{
try
{
string path = AppConfig.GetSettingStringValue("Log.FileName");
if (string.IsNullOrEmpty(path))
{
path = "WebsitePanel.Installer.log";
}
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
Process.Start("notepad.exe", path);
}
catch { }
}
}
}

View file

@ -0,0 +1,437 @@
// 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.Runtime.InteropServices;
namespace WebsitePanel.Setup
{
public sealed class OS
{
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFO
{
public Int32 dwOSVersionInfoSize;
public Int32 dwMajorVersion;
public Int32 dwMinorVersion;
public Int32 dwBuildNumber;
public Int32 dwPlatformID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
}
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFOEX
{
public Int32 dwOSVersionInfoSize;
public Int32 dwMajorVersion;
public Int32 dwMinorVersion;
public Int32 dwBuildNumber;
public Int32 dwPlatformID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
public short wServicePackMajor;
public short wServicePackMinor;
public short wSuiteMask;
public byte wProductType;
public byte wReserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public Int32 dwOemID;
public Int32 dwPageSize;
public Int32 wProcessorArchitecture;
public Int32 lpMinimumApplicationAddress;
public Int32 lpMaximumApplicationAddress;
public Int32 dwActiveProcessorMask;
public Int32 dwNumberOrfProcessors;
public Int32 dwProcessorType;
public Int32 dwAllocationGranularity;
public Int32 dwReserved;
}
public enum WinSuiteMask : int
{
VER_SUITE_SMALLBUSINESS = 1,
VER_SUITE_ENTERPRISE = 2,
VER_SUITE_BACKOFFICE = 4,
VER_SUITE_COMMUNICATIONS = 8,
VER_SUITE_TERMINAL = 16,
VER_SUITE_SMALLBUSINESS_RESTRICTED = 32,
VER_SUITE_EMBEDDEDNT = 64,
VER_SUITE_DATACENTER = 128,
VER_SUITE_SINGLEUSERTS = 256,
VER_SUITE_PERSONAL = 512,
VER_SUITE_BLADE = 1024,
VER_SUITE_STORAGE_SERVER = 8192,
VER_SUITE_COMPUTE_SERVER = 16384
}
public enum WinPlatform : byte
{
VER_NT_WORKSTATION = 1,
VER_NT_DOMAIN_CONTROLLER = 2,
VER_NT_SERVER = 3
}
public enum OSMajorVersion : byte
{
VER_OS_NT4 = 4,
VER_OS_2K_XP_2K3 = 5,
VER_OS_VISTA_LONGHORN = 6
}
private const Int32 SM_SERVERR2 = 89;
private const Int32 SM_MEDIACENTER = 87;
private const Int32 SM_TABLETPC = 86;
[DllImport("kernel32")]
private static extern int GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport("user32")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("kernel32", EntryPoint = "GetVersion")]
private static extern int GetVersionAdv(ref OSVERSIONINFO lpVersionInformation);
[DllImport("kernel32")]
private static extern int GetVersionEx(ref OSVERSIONINFOEX lpVersionInformation);
/*public static string GetVersionEx()
{
OSVERSIONINFO osvi = new OSVERSIONINFO();
OSVERSIONINFOEX xosvi = new OSVERSIONINFOEX();
Int32 iRet = 0;
string strDetails = string.Empty;
osvi.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFO));
xosvi.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));
try
{
iRet = (int)System.Environment.OSVersion.Platform;
if (iRet == 1)
{
iRet = GetVersionAdv(ref osvi);
strDetails = Environment.NewLine + "Release: " + osvi.dwMajorVersion + "." + osvi.dwMinorVersion + "." + osvi.dwBuildNumber + Environment.NewLine + osvi.szCSDVersion;
if (Len(osvi) == 0)
{
return "Windows 95" + strDetails;
}
else if (Len(osvi) == 10)
{
return "Windows 98" + strDetails;
}
else if (Len(osvi) == 9)
{
return "Windows ME" + strDetails;
}
}
else
{
iRet = GetVersionEx(xosvi);
strDetails = Environment.NewLine + "Release: " + xosvi.dwMajorVersion + "." + xosvi.dwMinorVersion + "." + xosvi.dwBuildNumber + Environment.NewLine + xosvi.szCSDVersion + " (" + xosvi.wServicePackMajor + "." + xosvi.wServicePackMinor + ")";
if (xosvi.dwMajorVersion == (byte)OSMajorVersion.VER_OS_NT4)
{
return "Windows NT 4" + strDetails;
}
else if (xosvi.dwMajorVersion == OSMajorVersion.VER_OS_2K_XP_2K3)
{
if (xosvi.dwMinorVersion == 0)
{
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
{
return "Windows 2000 Pro" + strDetails;
}
else if (xosvi.wProductType == WinPlatform.VER_NT_SERVER)
{
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_DATACENTER) == WinSuiteMask.VER_SUITE_DATACENTER)
{
return "Windows 2000 Datacenter Server" + strDetails;
}
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_ENTERPRISE) == WinSuiteMask.VER_SUITE_ENTERPRISE)
{
return "Windows 2000 Advanced Server" + strDetails;
}
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_SMALLBUSINESS) == WinSuiteMask.VER_SUITE_SMALLBUSINESS)
{
return "Windows 2000 Small Business Server" + strDetails;
}
else
{
return "Windows 2000 Server" + strDetails;
}
}
else if (xosvi.wProductType == WinPlatform.VER_NT_DOMAIN_CONTROLLER)
{
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_DATACENTER) == WinSuiteMask.VER_SUITE_DATACENTER)
{
return "Windows 2000 Datacenter Server Domain Controller" + strDetails;
}
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_ENTERPRISE) == WinSuiteMask.VER_SUITE_ENTERPRISE)
{
return "Windows 2000 Advanced Server Domain Controller" + strDetails;
}
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_SMALLBUSINESS) == WinSuiteMask.VER_SUITE_SMALLBUSINESS)
{
return "Windows 2000 Small Business Server Domain Controller" + strDetails;
}
else
{
return "Windows 2000 Server Domain Controller" + strDetails;
}
}
}
else if (xosvi.dwMinorVersion == 1)
{
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_PERSONAL) == WinSuiteMask.VER_SUITE_PERSONAL)
{
return "Windows XP Home Edition" + strDetails;
}
else
{
return "Windows XP Professional Edition" + strDetails;
}
}
else if (xosvi.dwMinorVersion == 2)
{
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
{
return "Windows XP Professional x64 Edition" + strDetails;
}
else if (xosvi.wProductType == WinPlatform.VER_NT_SERVER)
{
if (GetSystemMetrics(SM_SERVERR2) == 1)
{
return "Windows Server 2003 R2" + strDetails;
}
else
{
return "Windows Server 2003" + strDetails;
}
}
else if (xosvi.wProductType == WinPlatform.VER_NT_DOMAIN_CONTROLLER)
{
if (GetSystemMetrics(SM_SERVERR2) == 1)
{
return "Windows Server 2003 R2 Domain Controller" + strDetails;
}
else
{
return "Windows Server 2003 Domain Controller" + strDetails;
}
}
}
}
else if (xosvi.dwMajorVersion == OSMajorVersion.VER_OS_VISTA_LONGHORN)
{
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
{
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_PERSONAL) == WinSuiteMask.VER_SUITE_PERSONAL)
{
return "Windows Vista (Home Premium, Home Basic, or Home Ultimate) Edition";
}
else
{
return "Windows Vista (Enterprize or Business)" + strDetails;
}
}
else
{
return "Windows Server (Longhorn)" + strDetails;
}
}
}
}
catch
{
MessageBox.Show(GetLastError.ToString);
return string.Empty;
}
}*/
public enum WindowsVersion
{
Unknown = 0,
Windows95,
Windows98,
WindowsMe,
WindowsNT351,
WindowsNT4,
Windows2000,
WindowsXP,
WindowsServer2003,
WindowsVista,
WindowsServer2008
}
public static string GetName(WindowsVersion version)
{
string ret = string.Empty;
switch (version)
{
case WindowsVersion.Unknown:
ret = "Unknown";
break;
case WindowsVersion.Windows2000:
ret = "Windows 2000";
break;
case WindowsVersion.Windows95:
ret = "Windows 95";
break;
case WindowsVersion.Windows98:
ret = "Windows 98";
break;
case WindowsVersion.WindowsMe:
ret = "Windows Me";
break;
case WindowsVersion.WindowsNT351:
ret = "Windows NT 3.51";
break;
case WindowsVersion.WindowsNT4:
ret = "Windows NT 4.0";
break;
case WindowsVersion.WindowsServer2003:
ret = "Windows Server 2003";
break;
case WindowsVersion.WindowsServer2008:
ret = "Windows Server 2008";
break;
case WindowsVersion.WindowsVista:
ret = "Windows Vista";
break;
case WindowsVersion.WindowsXP:
ret = "Windows XP";
break;
}
return ret;
}
/// <summary>
/// Determine OS version
/// </summary>
/// <returns></returns>
public static WindowsVersion GetVersion()
{
WindowsVersion ret = WindowsVersion.Unknown;
OSVERSIONINFOEX info = new OSVERSIONINFOEX();
info.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));
GetVersionEx(ref info);
// Get OperatingSystem information from the system namespace.
System.OperatingSystem osInfo = System.Environment.OSVersion;
// Determine the platform.
switch (osInfo.Platform)
{
// Platform is Windows 95, Windows 98, Windows 98 Second Edition, or Windows Me.
case System.PlatformID.Win32Windows:
switch (osInfo.Version.Minor)
{
case 0:
ret = WindowsVersion.Windows95;
break;
case 10:
ret = WindowsVersion.Windows98;
break;
case 90:
ret = WindowsVersion.WindowsMe;
break;
}
break;
// Platform is Windows NT 3.51, Windows NT 4.0, Windows 2000, or Windows XP.
case System.PlatformID.Win32NT:
switch (osInfo.Version.Major)
{
case 3:
ret = WindowsVersion.WindowsNT351;
break;
case 4:
ret = WindowsVersion.WindowsNT4;
break;
case 5:
switch (osInfo.Version.Minor)
{
case 0:
ret = WindowsVersion.Windows2000;
break;
case 1:
ret = WindowsVersion.WindowsXP;
break;
case 2:
int i = GetSystemMetrics(SM_SERVERR2);
if (i != 0)
{
//Server 2003 R2
ret = WindowsVersion.WindowsServer2003;
}
else
{
if (info.wProductType == (byte)WinPlatform.VER_NT_WORKSTATION)
{
//XP Pro x64
ret = WindowsVersion.WindowsXP;
}
else
{
ret = WindowsVersion.WindowsServer2003;
}
break;
}
break;
}
break;
case 6:
if (info.wProductType == (byte)WinPlatform.VER_NT_WORKSTATION)
ret = WindowsVersion.WindowsVista;
else
ret = WindowsVersion.WindowsServer2008;
break;
}
break;
}
return ret;
}
/// <summary>
/// Returns Windows directory
/// </summary>
/// <returns></returns>
public static string GetWindowsDirectory()
{
return Environment.GetEnvironmentVariable("windir");
}
/// <summary>
/// Returns Windows directory
/// </summary>
/// <returns></returns>
public static string GetSystemTmpDirectory()
{
return Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine);
}
}
}

View file

@ -0,0 +1,248 @@
// 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.Setup
{
/// <summary>
/// Registry helper class.
/// </summary>
public sealed class RegistryUtils
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private RegistryUtils()
{
}
internal const string ProductKey = "SOFTWARE\\DotNetPark\\WebsitePanel\\";
internal const string CompanyKey = "SOFTWARE\\DotNetPark\\";
/// <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 object GetRegistryKeyValue(string subkey, string name)
{
object ret = null;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
ret = rk.GetValue(name, null);
}
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>
internal 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>
internal 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>
internal 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;
}
internal 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>
internal 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>
internal 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>
internal 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>
internal 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>
internal 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;
}
/// <summary>
/// Returns appPoolName of the installed release
/// </summary>
/// <returns></returns>
internal static string GetInstalledReleaseName()
{
return GetRegistryKeyStringValue(ProductKey, "ReleaseName");
}
/// <summary>
/// Returns id of the installed release
/// </summary>
/// <returns></returns>
internal static int GetInstalledReleaseId()
{
return GetRegistryKeyInt32Value(ProductKey, "ReleaseId");
}
internal 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;
}
internal static bool IsAspNet20Registered()
{
object ret = GetRegistryKeyValue("SOFTWARE\\Microsoft\\ASP.NET\\2.0.50727.0", "DllFullPath");
return ( ret != null );
}
public static Version GetIISVersion()
{
int major = GetRegistryKeyInt32Value("SOFTWARE\\Microsoft\\InetStp", "MajorVersion");
int minor = GetRegistryKeyInt32Value("SOFTWARE\\Microsoft\\InetStp", "MinorVersion");
return new Version(major, minor);
}
}
}

View file

@ -0,0 +1,628 @@
// 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.Threading;
using System.Xml;
namespace WebsitePanel.Setup
{
/// <summary>
/// Provides methods for rolling back after an error.
/// </summary>
public sealed class RollBack
{
private static XmlDocument script;
static RollBack()
{
script = new XmlDocument();
XmlElement root = script.CreateElement("currentScenario");
script.AppendChild(root);
}
private static XmlNode RootElement
{
get
{
return script.ChildNodes[0];
}
}
internal static XmlNodeList Actions
{
get
{
return RootElement.ChildNodes;
}
}
internal static void RegisterRegistryAction(string key)
{
XmlElement action = script.CreateElement("registry");
RootElement.AppendChild(action);
action.SetAttribute("key", key);
}
internal static void RegisterDirectoryAction(string path)
{
XmlElement action = script.CreateElement("directory");
RootElement.AppendChild(action);
action.SetAttribute("path", path);
}
internal static void RegisterDirectoryBackupAction(string source, string destination)
{
XmlElement action = script.CreateElement("directoryBackup");
RootElement.AppendChild(action);
action.SetAttribute("source", source);
action.SetAttribute("destination", destination);
}
internal static void RegisterDatabaseAction(string connectionString, string name)
{
XmlElement action = script.CreateElement("database");
RootElement.AppendChild(action);
action.SetAttribute("connectionString", connectionString);
action.SetAttribute("name", name);
}
internal static void RegisterDatabaseBackupAction(string connectionString, string name, string bakFile, string position)
{
XmlElement action = script.CreateElement("databaseBackup");
RootElement.AppendChild(action);
action.SetAttribute("connectionString", connectionString);
action.SetAttribute("name", name);
action.SetAttribute("bakFile", bakFile);
action.SetAttribute("position", position);
}
internal static void RegisterDatabaseUserAction(string connectionString, string username)
{
XmlElement action = script.CreateElement("databaseUser");
RootElement.AppendChild(action);
action.SetAttribute("connectionString", connectionString);
action.SetAttribute("username", username);
}
internal static void RegisterWebSiteAction(string siteId)
{
XmlElement action = script.CreateElement("webSite");
RootElement.AppendChild(action);
action.SetAttribute("siteId", siteId);
}
internal static void RegisterIIS7WebSiteAction(string siteId)
{
XmlElement action = script.CreateElement("IIS7WebSite");
RootElement.AppendChild(action);
action.SetAttribute("siteId", siteId);
}
internal static void RegisterVirtualDirectoryAction(string siteId, string name)
{
XmlElement action = script.CreateElement("virtualDirectory");
RootElement.AppendChild(action);
action.SetAttribute("siteId", siteId);
action.SetAttribute("name", name);
}
internal static void RegisterUserAccountAction(string domain, string userName)
{
XmlElement action = script.CreateElement("userAccount");
RootElement.AppendChild(action);
action.SetAttribute("name", userName);
action.SetAttribute("domain", domain);
}
internal static void RegisterApplicationPool(string name)
{
XmlElement action = script.CreateElement("applicationPool");
RootElement.AppendChild(action);
action.SetAttribute("name", name);
}
internal static void RegisterIIS7ApplicationPool(string name)
{
XmlElement action = script.CreateElement("IIS7ApplicationPool");
RootElement.AppendChild(action);
action.SetAttribute("name", name);
}
internal static void RegisterStopApplicationPool(string name)
{
XmlElement action = script.CreateElement("stopApplicationPool");
RootElement.AppendChild(action);
action.SetAttribute("name", name);
}
internal static void RegisterStopIIS7ApplicationPool(string name)
{
XmlElement action = script.CreateElement("stopIIS7ApplicationPool");
RootElement.AppendChild(action);
action.SetAttribute("name", name);
}
internal static void RegisterConfigAction(string componentId, string name)
{
XmlElement action = script.CreateElement("config");
RootElement.AppendChild(action);
action.SetAttribute("key", componentId);
action.SetAttribute("name", name);
}
internal static void RegisterWindowsService(string path, string name)
{
XmlElement action = script.CreateElement("WindowsService");
RootElement.AppendChild(action);
action.SetAttribute("path", path);
action.SetAttribute("name", name);
}
internal static void ProcessAction(XmlNode action)
{
switch(action.Name)
{
case "registry":
DeleteRegistryKey(XmlUtils.GetXmlAttribute(action, "key"));
break;
case "directory":
DeleteDirectory(XmlUtils.GetXmlAttribute(action, "path"));
break;
case "directoryBackup":
RestoreDirectory(
XmlUtils.GetXmlAttribute(action, "source"),
XmlUtils.GetXmlAttribute(action, "destination"));
break;
case "database":
DeleteDatabase(
XmlUtils.GetXmlAttribute(action, "connectionString"),
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "databaseBackup":
RestoreDatabase(
XmlUtils.GetXmlAttribute(action, "connectionString"),
XmlUtils.GetXmlAttribute(action, "name"),
XmlUtils.GetXmlAttribute(action, "bakFile"),
XmlUtils.GetXmlAttribute(action, "position"));
break;
case "databaseUser":
DeleteDatabaseUser(
XmlUtils.GetXmlAttribute(action, "connectionString"),
XmlUtils.GetXmlAttribute(action, "username"));
break;
case "webSite":
DeleteWebSite(
XmlUtils.GetXmlAttribute(action, "siteId"));
break;
case "IIS7WebSite":
DeleteIIS7WebSite(
XmlUtils.GetXmlAttribute(action, "siteId"));
break;
case "virtualDirectory":
DeleteVirtualDirectory(
XmlUtils.GetXmlAttribute(action, "siteId"),
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "userAccount":
DeleteUserAccount(
XmlUtils.GetXmlAttribute(action, "domain"),
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "applicationPool":
DeleteApplicationPool(
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "IIS7ApplicationPool":
DeleteIIS7ApplicationPool(
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "config":
DeleteComponentSettings(
XmlUtils.GetXmlAttribute(action, "key"),
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "stopApplicationPool":
StartApplicationPool(
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "stopIIS7ApplicationPool":
StartIIS7ApplicationPool(
XmlUtils.GetXmlAttribute(action, "name"));
break;
case "WindowsService":
UnregisterWindowsService(
XmlUtils.GetXmlAttribute(action, "path"),
XmlUtils.GetXmlAttribute(action, "name"));
break;
}
}
private static void DeleteComponentSettings(string id, string name)
{
try
{
Log.WriteStart("Deleting component settings");
Log.WriteInfo(string.Format("Deleting \"{0}\" settings", name));
XmlNode node = AppConfig.GetComponentConfig(id);
if (node != null)
{
XmlUtils.RemoveXmlNode(node);
AppConfig.SaveConfiguration();
}
Log.WriteEnd("Deleted component settings");
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Component settings delete error", ex);
throw;
}
}
private static void DeleteRegistryKey(string subkey)
{
try
{
Log.WriteStart("Deleting registry key");
Log.WriteInfo(string.Format("Deleting registry key \"{0}\"", subkey));
RegistryUtils.DeleteRegistryKey(subkey);
Log.WriteEnd("Deleted registry key");
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Registry key delete error", ex);
throw;
}
}
private static void DeleteDirectory(string path)
{
try
{
Log.WriteStart("Deleting directory");
Log.WriteInfo(string.Format("Deleting directory \"{0}\"", path));
if(FileUtils.DirectoryExists(path))
{
FileUtils.DeleteDirectory(path);
Log.WriteEnd("Deleted directory");
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Directory delete error", ex);
throw;
}
}
private static void RestoreDirectory(string targetDir, string zipFile)
{
try
{
Log.WriteStart("Restoring directory");
Log.WriteInfo(string.Format("Restoring directory \"{0}\"", targetDir));
FileUtils.UnzipFile(targetDir, zipFile);
Log.WriteStart("Restored directory");
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Directory restore error", ex);
throw;
}
}
private static void DeleteDatabase(string connectionString, string name)
{
try
{
Log.WriteStart("Deleting database");
Log.WriteInfo(string.Format("Deleting database \"{0}\"", name));
if ( SqlUtils.DatabaseExists(connectionString, name) )
{
SqlUtils.DeleteDatabase(connectionString, name);
Log.WriteEnd("Deleted database");
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Database delete error", ex);
throw;
}
}
private static void RestoreDatabase(string connectionString, string name, string bakFile, string position)
{
try
{
Log.WriteStart("Restoring database");
Log.WriteInfo(string.Format("Restoring database \"{0}\"", name));
if (SqlUtils.DatabaseExists(connectionString, name))
{
SqlUtils.RestoreDatabase(connectionString, name, bakFile, position);
Log.WriteEnd("Restored database");
}
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Database restore error", ex);
throw;
}
}
private static void DeleteDatabaseUser(string connectionString, string username)
{
try
{
Log.WriteStart("Deleting database user");
Log.WriteInfo(string.Format("Deleting database user \"{0}\"", username));
if (SqlUtils.UserExists(connectionString, username))
{
SqlUtils.DeleteUser(connectionString, username);
Log.WriteEnd("Deleted database user");
}
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Database user delete error", ex);
throw;
}
}
private static void DeleteWebSite(string siteId)
{
try
{
Log.WriteStart("Deleting web site");
Log.WriteInfo(string.Format("Deleting web site \"{0}\"", siteId));
if ( WebUtils.SiteIdExists(siteId) )
{
WebUtils.DeleteSite(siteId);
Log.WriteEnd("Deleted web site");
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Web site delete error", ex);
throw;
}
}
private static void DeleteIIS7WebSite(string siteId)
{
try
{
Log.WriteStart("Deleting web site");
Log.WriteInfo(string.Format("Deleting web site \"{0}\"", siteId));
if (WebUtils.IIS7SiteExists(siteId))
{
WebUtils.DeleteIIS7Site(siteId);
Log.WriteEnd("Deleted web site");
}
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Web site delete error", ex);
throw;
}
}
private static void DeleteVirtualDirectory(string siteId, string name)
{
try
{
Log.WriteStart("Deleting virtual directory");
Log.WriteInfo(string.Format("Deleting virtual directory \"{0}\" for the site \"{1}\"", name, siteId));
if ( WebUtils.VirtualDirectoryExists(siteId, name) )
{
WebUtils.DeleteVirtualDirectory(siteId, name);
Log.WriteEnd("Deleted virtual directory");
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Virtual directory delete error", ex);
throw;
}
}
private static void DeleteUserAccount(string domain, string user)
{
try
{
Log.WriteStart("Deleting user account");
Log.WriteInfo(string.Format("Deleting user account \"{0}\"", user));
if ( SecurityUtils.UserExists(domain, user) )
{
SecurityUtils.DeleteUser(domain, user);
Log.WriteEnd("Deleted user account");
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("User account delete error", ex);
throw;
}
}
private static void DeleteApplicationPool(string name)
{
try
{
Log.WriteStart("Deleting application pool");
Log.WriteInfo(string.Format("Deleting application pool \"{0}\"", name));
if (WebUtils.ApplicationPoolExists(name))
{
int count = WebUtils.GetApplicationPoolSitesCount(name);
if (count > 0)
{
Log.WriteEnd("Application pool is not empty");
}
else
{
WebUtils.DeleteApplicationPool(name);
Log.WriteEnd("Deleted application pool");
}
}
}
catch(Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Application pool delete error", ex);
throw;
}
}
private static void DeleteIIS7ApplicationPool(string name)
{
try
{
Log.WriteStart("Deleting application pool");
Log.WriteInfo(string.Format("Deleting application pool \"{0}\"", name));
if (WebUtils.IIS7ApplicationPoolExists(name))
{
int count = WebUtils.GetIIS7ApplicationPoolSitesCount(name);
if (count > 0)
{
Log.WriteEnd("Application pool is not empty");
}
else
{
WebUtils.DeleteIIS7ApplicationPool(name);
Log.WriteEnd("Deleted application pool");
}
}
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Application pool delete error", ex);
throw;
}
}
private static void StartApplicationPool(string name)
{
try
{
Log.WriteStart("Starting IIS application pool");
Log.WriteInfo(string.Format("Starting \"{0}\"", name));
WebUtils.StartApplicationPool(name);
Log.WriteEnd("Started application pool");
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Application pool start error", ex);
throw;
}
}
private static void StartIIS7ApplicationPool(string name)
{
try
{
Log.WriteStart("Starting IIS application pool");
Log.WriteInfo(string.Format("Starting \"{0}\"", name));
WebUtils.StartIIS7ApplicationPool(name);
Log.WriteEnd("Started application pool");
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Application pool start error", ex);
throw;
}
}
private static void UnregisterWindowsService(string path, string serviceName)
{
try
{
Log.WriteStart(string.Format("Unregistering \"{0}\" Windows service", serviceName));
try
{
Utils.StopService(serviceName);
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Windows service stop error", ex);
}
Utils.RunProcess(path, "/u");
Log.WriteEnd("Unregistered Windows service");
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
Log.WriteError("Windows service error", ex);
throw;
}
}
}
}

View file

@ -0,0 +1,75 @@
// 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.Windows.Forms;
using System.Xml;
namespace WebsitePanel.Setup
{
/// <summary>
/// Shows rollback process.
/// </summary>
public sealed class RollBackProcess
{
private ProgressBar progressBar;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="bar">Progress bar.</param>
public RollBackProcess(ProgressBar bar)
{
this.progressBar = bar;
}
/// <summary>
/// Runs rollback process.
/// </summary>
internal void Run()
{
progressBar.Minimum = 0;
progressBar.Maximum = 100;
progressBar.Value = 0;
int actions = RollBack.Actions.Count;
for ( int i=0; i<actions; i++ )
{
//reverse order
XmlNode action = RollBack.Actions[actions-i-1];
try
{
RollBack.ProcessAction(action);
}
catch
{}
progressBar.Value = Convert.ToInt32(i*100/actions);
}
}
}
}

View file

@ -0,0 +1,198 @@
// 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;
namespace WebsitePanel.Setup
{
#region Security enums
public enum ControlFlags
{
SE_OWNER_DEFAULTED = 0x1,
SE_GROUP_DEFAULTED = 0x2,
SE_DACL_PRESENT = 0x4,
SE_DACL_DEFAULTED = 0x8,
SE_SACL_PRESENT = 0x10,
SE_SACL_DEFAULTED = 0x20,
SE_DACL_AUTO_INHERIT_REQ = 0x100,
SE_SACL_AUTO_INHERIT_REQ = 0x200,
SE_DACL_AUTO_INHERITED = 0x400,
SE_SACL_AUTO_INHERITED = 0x800,
SE_DACL_PROTECTED = 0x1000,
SE_SACL_PROTECTED = 0x2000,
SE_SELF_RELATIVE = 0x8000
}
[Flags]
public enum SystemAccessMask : uint
{
// Grants the right to read data from the file. For a directory, this value grants
// the right to list the contents of the directory.
FILE_LIST_DIRECTORY = 0x1,
// Grants the right to write data to the file. For a directory, this value grants
// the right to create a file in the directory.
FILE_ADD_FILE = 0x2,
// Grants the right to append data to the file. For a directory, this value grants
// the right to create a subdirectory.
FILE_ADD_SUBDIRECTORY = 0x4,
// Grants the right to read extended attributes.
FILE_READ_EA = 0x8,
// Grants the right to write extended attributes.
FILE_WRITE_EA = 0x10,
// Grants the right to execute a file. For a directory, the directory can be traversed.
FILE_TRAVERSE = 0x20,
// Grants the right to delete a directory and all the files it contains (its children),
// even if the files are read-only.
FILE_DELETE_CHILD = 0x40,
// Grants the right to read file attributes.
FILE_READ_ATTRIBUTES = 0x80,
// Grants the right to change file attributes.
FILE_WRITE_ATTRIBUTES = 0x100,
// Grants delete access.
DELETE = 0x10000,
// Grants read access to the security descriptor and owner.
READ_CONTROL = 0x20000,
// Grants write access to the discretionary ACL.
WRITE_DAC = 0x40000,
// Assigns the write owner.
WRITE_OWNER = 0x80000,
// Synchronizes access and allows a process to wait for an object to enter the signaled state.
SYNCHRONIZE = 0x100000
}
[Flags]
public enum AceFlags : uint
{
// Non-container child objects inherit the ACE as an effective ACE. For child objects that are containers,
// the ACE is inherited as an inherit-only ACE unless the NO_PROPAGATE_INHERIT_ACE bit flag is also set.
OBJECT_INHERIT_ACE = 0x1,
// Child objects that are containers, such as directories, inherit the ACE as an effective ACE. The inherited
// ACE is inheritable unless the NO_PROPAGATE_INHERIT_ACE bit flag is also set.
CONTAINER_INHERIT_ACE = 0x2,
// If the ACE is inherited by a child object, the system clears the OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE
// flags in the inherited ACE. This prevents the ACE from being inherited by subsequent generations of objects.
NO_PROPAGATE_INHERIT_ACE = 0x4,
// Indicates an inherit-only ACE which does not control access to the object to which it is attached. If this
// flag is not set, the ACE is an effective ACE which controls access to the object to which it is attached.
// Both effective and inherit-only ACEs can be inherited depending on the state of the other inheritance flags.
INHERIT_ONLY_ACE = 0x8,
// The system sets this bit when it propagates an inherited ACE to a child object.
INHERITED_ACE = 0x10,
// Used with system-audit ACEs in a SACL to generate audit messages for successful access attempts.
SUCCESSFUL_ACCESS_ACE_FLAG = 0x40,
// Used with system-audit ACEs in a SACL to generate audit messages for failed access attempts.
FAILED_ACCESS_ACE_FLAG = 0x80
}
/// <summary>
/// Change options
/// </summary>
public enum ChangeOption
{
/// <summary>Change the owner of the logical file.</summary>
CHANGE_OWNER_SECURITY_INFORMATION = 1,
/// <summary>Change the group of the logical file.</summary>
CHANGE_GROUP_SECURITY_INFORMATION = 2,
/// <summary>Change the ACL of the logical file.</summary>
CHANGE_DACL_SECURITY_INFORMATION = 4,
/// <summary>Change the system ACL of the logical file.</summary>
CHANGE_SACL_SECURITY_INFORMATION = 8
}
/// <summary>
/// Ace types
/// </summary>
public enum AceType
{
/// <summary>Allowed</summary>
Allowed = 0,
/// <summary>Denied</summary>
Denied = 1,
/// <summary>Audit</summary>
Audit = 2
}
/// <summary>
/// NTFS permissions
/// </summary>
[Flags]
[Serializable]
public enum NtfsPermission : int
{
/// <summary>FullControl</summary>
FullControl = 0x1,// = 0x1F01FF,
/// <summary>Modify</summary>
Modify = 0x2,// = 0x1301BF,
/// <summary>Execute</summary>
Execute = 0x4,// = 0x1200A9,
/// <summary>ListFolderContents</summary>
ListFolderContents = 0x8,// = 0x1200A9,
/// <summary>Read</summary>
Read = 0x10,// = 0x120089,
/// <summary>Write</summary>
Write = 0x20// = 0x100116
}
/// <summary>
/// Well-known SIDs
/// </summary>
public class SystemSID
{
/// <summary>"Administrators" SID</summary>
public const string ADMINISTRATORS = "S-1-5-32-544";
/// <summary>"Local System (SYSTEM)" SID</summary>
public const string SYSTEM = "S-1-5-18";
/// <summary>"NETWORK SERVICE" SID</summary>
public const string NETWORK_SERVICE = "S-1-5-20";
}
#endregion
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,70 @@
// 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.
namespace WebsitePanel.Setup.Common
{
/// <summary>
/// Server item.
/// </summary>
public sealed class ServerItem
{
private string name;
private string server;
/// <summary>
/// Initializes a new instance of the SystemUserItem class.
/// </summary>
public ServerItem()
{
}
public ServerItem(string server, string name)
{
this.Name = name;
this.Server = server;
}
/// <summary>
/// Name
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Server
/// </summary>
public string Server
{
get { return server; }
set { server = value; }
}
}
}

View file

@ -0,0 +1,49 @@
// 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.Setup
{
/// <summary>
/// Install currentScenario
/// </summary>
public enum SetupActions
{
/// <summary>Install</summary>
Install,
/// <summary>Uninstall</summary>
Uninstall,
/// <summary>Upgrade</summary>
Update,
/// <summary>Setup</summary>
Setup
};
}

View file

@ -0,0 +1,340 @@
// 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.Xml;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Setup.Common;
namespace WebsitePanel.Setup
{
/// <summary>
/// Variables container.
/// </summary>
public sealed class SetupVariables
{
//
public static readonly SetupVariables Empty = new SetupVariables();
public bool EnableScpaMode { get; set; }
public string PeerAdminPassword { get; set; }
public string DatabaseUserPassword { get; set; }
public bool NewDatabaseUser { get; set; }
/// <summary>
/// Installation folder
/// </summary>
public string InstallationFolder { get; set; }
public string InstallFolder
{
get { return InstallationFolder; }
set { InstallationFolder = value; }
}
/// <summary>
/// Component id
/// </summary>
public string ComponentId { get; set; }
public string ComponentDescription { get; set; }
/// <summary>
/// Component code
/// </summary>
public string ComponentCode { get; set; }
/// <summary>
/// Component name
/// </summary>
public string ComponentName { get; set; }
/// <summary>
/// Component name
/// </summary>
public string ApplicationName { get; set; }
public string ComponentFullName
{
get { return ApplicationName + " " + ComponentName; }
}
public string Instance { get; set; }
/// <summary>
/// Install currentScenario
/// </summary>
public SetupActions SetupAction { get; set; }
/// <summary>
/// Product key
/// </summary>
public string ProductKey { get; set; }
/// <summary>
/// Release Id
/// </summary>
public int ReleaseId { get; set; }
// Workaround
public string Release
{
get { return Version; }
set { Version = value; }
}
/// <summary>
/// Release name
/// </summary>
public string Version { get; set; }
/// <summary>
/// Connection string
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// Database
/// </summary>
public string Database { get; set; }
/// <summary>
/// DatabaseServer
/// </summary>
public string DatabaseServer { get; set; }
/// <summary>
/// Database install connection string
/// </summary>
public string DbInstallConnectionString { get; set; }
public string InstallConnectionString
{
get { return DbInstallConnectionString; }
set { DbInstallConnectionString = value; }
}
/// <summary>
/// Create database
/// </summary>
public bool CreateDatabase { get; set; }
public bool NewVirtualDirectory { get; set; }
public bool NewWebApplicationPool { get; set; }
public string WebApplicationPoolName { get; set; }
public string ApplicationPool
{
get { return WebApplicationPoolName; }
set { WebApplicationPoolName = value; }
}
/// <summary>
/// Virtual directory
/// </summary>
public string VirtualDirectory { get; set; }
public bool NewWebSite { get; set; }
/// <summary>
/// Website Id
/// </summary>
public string WebSiteId { get; set; }
/// <summary>
/// Website IP
/// </summary>
public string WebSiteIP { get; set; }
/// <summary>
/// Website port
/// </summary>
public string WebSitePort { get; set; }
/// <summary>
/// Website domain
/// </summary>
public string WebSiteDomain { get; set; }
/// <summary>
/// User account
/// </summary>
public string UserAccount { get; set; }
/// <summary>
/// User password
/// </summary>
public string UserPassword { get; set; }
/// <summary>
/// User Membership
/// </summary>
public string[] UserMembership
{
get
{
if (ComponentCode.Equals(Global.Server.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.Server.ServiceUserMembership;
}
else if(ComponentCode.Equals(Global.EntServer.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.EntServer.ServiceUserMembership;
}
else if (ComponentCode.Equals(Global.WebPortal.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.WebPortal.ServiceUserMembership;
}
else
{
return new string[] {};
}
}
}
/// <summary>
/// Welcome screen has been skipped
/// </summary>
public bool WelcomeScreenSkipped { get; set; }
public string InstallerFolder { get; set; }
public string Installer { get; set; }
public string InstallerType { get; set; }
public string InstallerPath { get; set; }
public XmlNode ComponentConfig { get; set; }
public string ServerPassword { get; set; }
public string CryptoKey { get; set; }
public bool UpdateWebSite { get; set; }
public bool UpdateServerPassword { get; set; }
public bool UpdateServerAdminPassword { get; set; }
public string ServerAdminPassword { get; set; }
public string BaseDirectory { get; set; }
public string UpdateVersion { get; set; }
public string EnterpriseServerURL { get; set; }
public string UserDomain { get; set; }
public string Domain
{
get { return UserDomain; }
set { UserDomain = value; }
}
public bool NewUserAccount { get; set; }
public bool NewApplicationPool { get; set; }
public ServerItem[] SQLServers { get; set; }
public string Product { get; set; }
public Version IISVersion { get; set; }
public string ServiceIP { get; set; }
public string ServicePort { get; set; }
public string ServiceName { get; set; }
public string ConfigurationFile { get; set; }
public string ServiceFile { get; set; }
public string LicenseKey { get; set; }
public string SetupXml { get; set; }
public string RemoteServerUrl
{
get
{
string address = "http://";
string server = String.Empty;
string ipPort = String.Empty;
//server
if (String.IsNullOrEmpty(WebSiteDomain) == false
&& WebSiteDomain.Trim().Length > 0)
{
//domain
server = WebSiteDomain.Trim();
}
else
{
//ip
if (String.IsNullOrEmpty(WebSiteIP) == false
&& WebSiteIP.Trim().Length > 0)
{
server = WebSiteIP.Trim();
}
}
//port
if (server.Length > 0 &&
WebSiteIP.Trim().Length > 0 &&
WebSitePort.Trim() != "80")
{
ipPort = ":" + WebSitePort.Trim();
}
//address string
address += server + ipPort;
//
return address;
}
}
public string RemoteServerPassword { get; set; }
public string ServerComponentId { get; set; }
public string PortalComponentId { get; set; }
public string EnterpriseServerComponentId { get; set; }
public SetupVariables Clone()
{
return (SetupVariables)this.MemberwiseClone();
}
}
}

View file

@ -0,0 +1,184 @@
// 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.Data.SqlClient;
using System.IO;
using System.Text;
using System.Windows.Forms;
using WebsitePanel.Setup.Actions;
namespace WebsitePanel.Setup
{
/// <summary>
/// Shows sql script process.
/// </summary>
public sealed class SqlProcess
{
private string scriptFile;
private string connectionString;
private string database;
public event EventHandler<ActionProgressEventArgs<int>> ProgressChange;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="file">Sql script file</param>
/// <param name="connection">Sql connection string</param>
/// <param name="db">Sql server database name</param>
public SqlProcess(string file, string connection, string db)
{
this.scriptFile = file;
this.connectionString = connection;
this.database = db;
}
private void OnProgressChange(int percentage)
{
if (ProgressChange == null)
return;
//
ProgressChange(this, new ActionProgressEventArgs<int>
{
EventData = percentage
});
}
/// <summary>
/// Executes sql script file.
/// </summary>
internal void Run()
{
int commandCount = 0;
int i = 0;
string sql = string.Empty;
try
{
using (StreamReader sr = new StreamReader(scriptFile))
{
while( null != (sql = ReadNextStatementFromStream(sr)))
{
commandCount++;
}
}
}
catch(Exception ex)
{
throw new Exception("Can't read SQL script " + scriptFile, ex);
}
Log.WriteInfo(string.Format("Executing {0} database commands", commandCount));
//
OnProgressChange(0);
//
SqlConnection connection = new SqlConnection(connectionString);
try
{
// iterate through "GO" delimited command text
using (StreamReader reader = new StreamReader(scriptFile))
{
SqlCommand command = new SqlCommand();
connection.Open();
command.Connection = connection;
command.CommandType = System.Data.CommandType.Text;
command.CommandTimeout = 600;
while (null != (sql = ReadNextStatementFromStream(reader)))
{
sql = ProcessInstallVariables(sql);
command.CommandText = sql;
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error executing SQL command: " + sql, ex);
}
i++;
if (commandCount != 0)
{
OnProgressChange(Convert.ToInt32(i * 100 / commandCount));
}
}
}
}
catch (Exception ex)
{
throw new Exception("Can't run SQL script " + scriptFile, ex);
}
finally
{
connection.Close();
}
}
private string ReadNextStatementFromStream(StreamReader reader)
{
StringBuilder sb = new StringBuilder();
string lineOfText;
while(true)
{
lineOfText = reader.ReadLine();
if( lineOfText == null )
{
if( sb.Length > 0 )
{
return sb.ToString();
}
else
{
return null;
}
}
if(lineOfText.TrimEnd().ToUpper() == "GO")
{
break;
}
sb.Append(lineOfText + Environment.NewLine);
}
return sb.ToString();
}
private string ProcessInstallVariables(string input)
{
//replace install variables
string output = input;
output = output.Replace("${install.database}", database);
return output;
}
}
}

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.
namespace WebsitePanel.Setup
{
public sealed class SqlServerItem
{
public string Server { get; set; }
public bool WindowsAuthentication { get; set; }
public string User { get; set; }
public string Password { get; set; }
public string Database { get; set; }
}
}

View file

@ -0,0 +1,615 @@
// 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.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
namespace WebsitePanel.Setup
{
/// <summary>
/// Sql utils class.
/// </summary>
public sealed class SqlUtils
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private SqlUtils()
{
}
public static string BuildDbServerMasterConnectionString(string dbServer, string dbLogin, string dbPassw)
{
return BuildDbServerConnectionString(dbServer, "master", dbLogin, dbPassw);
}
public static string BuildDbServerConnectionString(string dbServer, string dbName, string dbLogin, string dbPassw)
{
if (String.IsNullOrEmpty(dbLogin) && String.IsNullOrEmpty(dbPassw))
{
return String.Format("Server={0};Database={1};Integrated Security=SSPI;", dbServer, dbName);
}
else
{
return String.Format("Server={0};Database={1};User id={2};Password={3};", dbServer, dbName, dbLogin, dbPassw);
}
}
/// <summary>
/// Check sql connection.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <returns>True if connecion is valid, otherwise false.</returns>
internal static bool CheckSqlConnection(string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
}
catch
{
return false;
}
conn.Close();
return true;
}
/// <summary>
/// Gets the version of SQL Server instance.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <returns>True if connecion is valid, otherwise false.</returns>
internal static string GetSqlServerVersion(string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand cmd = new SqlCommand("SELECT SERVERPROPERTY('productversion')", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string version = "unknown";
if (reader.HasRows)
{
reader.Read();
version = reader[0].ToString();
reader.Close();
}
return version;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// Gets the security mode of SQL Server.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <returns>1 - Windows Authentication mode, 0 - Mixed mode.</returns>
internal static int GetSqlServerSecurityMode(string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
int mode = 0;
try
{
SqlCommand cmd = new SqlCommand("SELECT SERVERPROPERTY('IsIntegratedSecurityOnly')", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
mode = Convert.ToInt32(reader[0]);
reader.Close();
}
}
catch
{
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
return mode;
}
/// <summary>
/// Get databases.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <returns>Databases.</returns>
internal static string[] GetDatabases(string connectionString)
{
DataSet ds = ExecuteQuery(connectionString, "SELECT Name FROM master..sysdatabases ORDER BY Name");
string[] ret = new string[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
ret[i] = (string)ds.Tables[0].Rows[i]["Name"];
}
return ret;
}
internal static int ExecuteStoredProcedure(string connectionString, string name, params SqlParameter[] commandParameters)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = name;
cmd.Connection = connection;
cmd.CommandTimeout = 300;
//attach parameters
if (commandParameters != null)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
// Check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput ||
p.Direction == ParameterDirection.Input) &&
(p.Value == null))
{
p.Value = DBNull.Value;
}
cmd.Parameters.Add(p);
}
}
}
int ret = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
return ret;
}
}
private static int ExecuteNonQuery(string connectionString, string commandText)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandTimeout = 300;
conn.Open();
int ret = cmd.ExecuteNonQuery();
return ret;
}
finally
{
// close connection if required
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
internal static DataSet ExecuteQuery(string connectionString, string commandText)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(commandText, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
finally
{
// close connection if required
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// Checks if the database exists.
/// </summary>
/// <param name="databaseName">Database name.</param>
/// <param name="connectionString">Connection string.</param>
/// <returns>Returns True if the database exists.</returns>
internal static bool DatabaseExists(string connectionString, string databaseName)
{
return (ExecuteQuery(connectionString,
String.Format("select name from master..sysdatabases where name = '{0}'", databaseName)).Tables[0].Rows.Count > 0);
}
/// <summary>
/// Creates database.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <param name="databaseName">Database name.</param>
internal static void CreateDatabase(string connectionString, string databaseName)
{
// create database in the default location
string commandText = string.Format("CREATE DATABASE [{0}] COLLATE Latin1_General_CI_AS;", databaseName);
// create database
ExecuteNonQuery(connectionString, commandText);
// grant users access
//UpdateDatabaseUsers(database.Name, database.Users);
}
/// <summary>
/// Creates database user.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <param name="userName">User name</param>
/// <param name="password">Password.</param>
/// <param name="database">Default database.</param>
internal static bool CreateUser(string connectionString, string userName, string password, string database)
{
bool userCreated = false;
if (!UserExists(connectionString, userName))
{
ExecuteNonQuery(connectionString,
String.Format("CREATE LOGIN {0} WITH PASSWORD='{1}', DEFAULT_DATABASE={2}, CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF",
userName, password, database));
userCreated = true;
}
AddUserToDatabase(connectionString, database, userName);
return userCreated;
}
private static void AddUserToDatabase(string connectionString, string databaseName, string user)
{
if (user == "sa")
return;
// grant database access
try
{
ExecuteNonQuery(connectionString,
string.Format("USE {0};EXEC sp_grantdbaccess '{1}';", databaseName, user));
}
catch (SqlException ex)
{
if (ex.Number == 15023)
{
// the user already exists in the database
// so, try to auto fix his login in the database
ExecuteNonQuery(connectionString,
string.Format("USE {0};EXEC sp_change_users_login 'Auto_Fix', '{1}';", databaseName, user));
}
else
{
throw new Exception("Can't add user to database", ex);
}
}
// add database owner
ExecuteNonQuery(connectionString,
string.Format("USE {0};EXEC sp_addrolemember 'db_owner', '{1}';", databaseName, user));
}
/// <summary>
/// Checks whether specified user exists.
/// </summary>
/// <param name="connectionString">Connection string</param>
/// <param name="username">User name.</param>
/// <returns>True if specified user exists, otherwise false.</returns>
internal static bool UserExists(string connectionString, string username)
{
return (ExecuteQuery(connectionString,
string.Format("select name from master..syslogins where name = '{0}'", username)).Tables[0].Rows.Count > 0);
}
/// <summary>
/// Checks whether specified login exists.
/// </summary>
/// <param name="connectionString">Connection string</param>
/// <param name="loginName">Login name.</param>
/// <returns>True if specified login exists, otherwise false.</returns>
internal static bool LoginExists(string connectionString, string loginName)
{
return (ExecuteQuery(connectionString,
string.Format("SELECT * FROM sys.server_principals WHERE name = N'{0}'", loginName)).Tables[0].Rows.Count > 0);
}
/// <summary>
/// Deletes login
/// </summary>
/// <param name="connectionString">Connection string</param>
/// <param name="loginName">Login name</param>
internal static void DeleteLogin(string connectionString, string loginName)
{
// drop login
if (LoginExists(connectionString, loginName))
ExecuteNonQuery(connectionString, String.Format("DROP LOGIN [{0}]", loginName));
}
/// <summary>
/// Deletes database user
/// </summary>
/// <param name="connectionString">Connection string</param>
/// <param name="username">Username</param>
internal static void DeleteUser(string connectionString, string username)
{
// remove user from databases
string[] userDatabases = GetUserDatabases(connectionString, username);
foreach (string database in userDatabases)
RemoveUserFromDatabase(connectionString, database, username);
// close all user connection
CloseUserConnections(connectionString, username);
// drop login
ExecuteNonQuery(connectionString, String.Format("EXEC sp_droplogin '{0}'", username));
}
/// <summary>
/// Deletes database
/// </summary>
/// <param name="connectionString">Connection string</param>
/// <param name="databaseName">Database name</param>
internal static void DeleteDatabase(string connectionString, string databaseName)
{
// remove all users from database
string[] users = GetDatabaseUsers(connectionString, databaseName);
foreach (string user in users)
{
RemoveUserFromDatabase(connectionString, databaseName, user);
}
// close all connection
CloseDatabaseConnections(connectionString, databaseName);
// drop database
ExecuteNonQuery(connectionString,
String.Format("DROP DATABASE {0}", databaseName));
}
private static string[] GetDatabaseUsers(string connectionString, string databaseName)
{
string cmdText = String.Format(@"
select su.name FROM {0}..sysusers as su
inner JOIN master..syslogins as sl on su.sid = sl.sid
where su.hasdbaccess = 1 AND su.islogin = 1 AND su.issqluser = 1 AND su.name <> 'dbo'",
databaseName);
DataView dvUsers = ExecuteQuery(connectionString, cmdText).Tables[0].DefaultView;
string[] users = new string[dvUsers.Count];
for (int i = 0; i < dvUsers.Count; i++)
{
users[i] = (string)dvUsers[i]["Name"];
}
return users;
}
private static string[] GetUserDatabaseObjects(string connectionString, string databaseName, string user)
{
DataView dvObjects = ExecuteQuery(connectionString,
String.Format("select so.name from {0}..sysobjects as so" +
" inner join {1}..sysusers as su on so.uid = su.uid" +
" where su.name = '{2}'", databaseName, databaseName, user)).Tables[0].DefaultView;
string[] objects = new string[dvObjects.Count];
for (int i = 0; i < dvObjects.Count; i++)
{
objects[i] = (string)dvObjects[i]["Name"];
}
return objects;
}
private static string[] GetUserDatabases(string connectionString, string username)
{
string cmdText = String.Format(@"
DECLARE @Username varchar(100)
SET @Username = '{0}'
CREATE TABLE #UserDatabases
(
Name nvarchar(100) collate database_default
)
DECLARE @DbName nvarchar(100)
DECLARE DatabasesCursor CURSOR FOR
SELECT name FROM master..sysdatabases
WHERE (status & 256) = 0 AND (status & 512) = 0
OPEN DatabasesCursor
WHILE (10 = 10)
BEGIN --LOOP 10: thru Databases
FETCH NEXT FROM DatabasesCursor
INTO @DbName
--print @DbName
IF (@@fetch_status <> 0)
BEGIN
DEALLOCATE DatabasesCursor
BREAK
END
DECLARE @sql nvarchar(1000)
SET @sql = 'if exists (select ''' + @DbName + ''' from [' + @DbName + ']..sysusers where name = ''' + @Username + ''') insert into #UserDatabases (Name) values (''' + @DbName + ''')'
EXECUTE(@sql)
END
SELECT Name FROM #UserDatabases
DROP TABLE #UserDatabases
", username);
DataView dvDatabases = ExecuteQuery(connectionString, cmdText).Tables[0].DefaultView;
string[] databases = new string[dvDatabases.Count];
for (int i = 0; i < dvDatabases.Count; i++)
databases[i] = (string)dvDatabases[i]["Name"];
return databases;
}
private static void CloseDatabaseConnections(string connectionString, string databaseName)
{
DataView dv = ExecuteQuery(connectionString,
String.Format(@"SELECT spid FROM master..sysprocesses WHERE dbid = DB_ID('{0}') AND spid > 50 AND spid <> @@spid", databaseName)).Tables[0].DefaultView;
// kill processes
for (int i = 0; i < dv.Count; i++)
{
KillProcess(connectionString, (short)(dv[i]["spid"]));
}
}
private static void CloseUserConnections(string connectionString, string userName)
{
DataView dv = ExecuteQuery(connectionString,
String.Format(@"SELECT spid FROM master..sysprocesses WHERE loginame = '{0}'", userName)).Tables[0].DefaultView;
// kill processes
for (int i = 0; i < dv.Count; i++)
{
KillProcess(connectionString, (short)(dv[i]["spid"]));
}
}
private static void KillProcess(string connectionString, short spid)
{
try
{
ExecuteNonQuery(connectionString,
String.Format("KILL {0}", spid));
}
catch (SqlException)
{
}
}
private static void RemoveUserFromDatabase(string connectionString, string databaseName, string user)
{
// change ownership of user's objects
string[] userObjects = GetUserDatabaseObjects(connectionString, databaseName, user);
foreach (string userObject in userObjects)
{
try
{
ExecuteNonQuery(connectionString,
String.Format("USE {0};EXEC sp_changeobjectowner '{1}.{2}', 'dbo'",
databaseName, user, userObject));
}
catch (SqlException ex)
{
if (ex.Number == 15505)
{
// Cannot change owner of object 'user.ObjectName' or one of its child objects because
// the new owner 'dbo' already has an object with the same name.
// try to rename object before changing owner
string renamedObject = user + DateTime.Now.Ticks + "_" + userObject;
ExecuteNonQuery(connectionString,
String.Format("USE {0};EXEC sp_rename '{1}.{2}', '{3}'",
databaseName, user, userObject, renamedObject));
// change owner
ExecuteNonQuery(connectionString,
String.Format("USE {0};EXEC sp_changeobjectowner '{1}.{2}', 'dbo'",
databaseName, user, renamedObject));
}
else
{
throw new Exception("Can't change database object owner", ex);
}
}
}
// revoke db access
ExecuteNonQuery(connectionString,
String.Format("USE {0};EXEC sp_revokedbaccess '{1}';",
databaseName, user));
}
internal static bool IsValidDatabaseName(string name)
{
if (name == null || name.Trim().Length == 0 || name.Length > 128)
return false;
return Regex.IsMatch(name, "^[0-9A-z_@#$]+$", RegexOptions.Singleline);
}
internal static string BackupDatabase(string connectionString, string databaseName)
{
string bakFile = databaseName + ".bak";
// backup database
ExecuteNonQuery(connectionString,
String.Format(@"BACKUP DATABASE [{0}] TO DISK = N'{1}'", // WITH INIT, NAME = '{2}'
databaseName, bakFile));
return bakFile;
}
internal static void BackupDatabase(string connectionString, string databaseName, out string bakFile, out string position)
{
bakFile = databaseName + ".bak";
position = "1";
string backupName = "Backup " + DateTime.Now.ToString("yyyyMMddHHmmss");
// backup database
ExecuteNonQuery(connectionString,
String.Format(@"BACKUP DATABASE [{0}] TO DISK = N'{1}' WITH NAME = '{2}'", // WITH INIT, NAME = '{2}'
databaseName, bakFile, backupName));
//define last position in backup set
string query = string.Format("RESTORE HEADERONLY FROM DISK = N'{0}'", bakFile);
DataSet ds = ExecuteQuery(connectionString, query);
query = string.Format("BackupName = '{0}'", backupName);
DataRow[] rows = ds.Tables[0].Select(query, "Position DESC");
if (rows != null && rows.Length > 0)
position = rows[0]["Position"].ToString();
}
internal static void RestoreDatabase(string connectionString, string databaseName, string bakFile)
{
// close current database connections
CloseDatabaseConnections(connectionString, databaseName);
// restore database
ExecuteNonQuery(connectionString,
String.Format(@"RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH REPLACE",
databaseName, bakFile));
}
internal static void RestoreDatabase(string connectionString, string databaseName, string bakFile, string position)
{
// close current database connections
CloseDatabaseConnections(connectionString, databaseName);
// restore database
ExecuteNonQuery(connectionString,
String.Format(@"RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH FILE = {2}, REPLACE",
databaseName, bakFile, position));
}
}
}

View file

@ -0,0 +1,810 @@
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.ServiceProcess;
using System.DirectoryServices;
using System.Linq;
using WebsitePanel.Setup.Web;
using Microsoft.Win32;
namespace WebsitePanel.Setup
{
/// <summary>
/// Utils class.
/// </summary>
public sealed class Utils
{
public const string AspNet40RegistrationToolx64 = @"Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe";
public const string AspNet40RegistrationToolx86 = @"Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private Utils()
{
}
#region Resources
/// <summary>
/// Get resource stream from assembly by specified resource name.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>Resource stream.</returns>
public static Stream GetResourceStream(string resourceName)
{
Assembly asm = typeof(Utils).Assembly;
Stream ret = asm.GetManifestResourceStream(resourceName);
return ret;
}
#endregion
#region Crypting
/// <summary>
/// Computes the SHA1 hash value
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string ComputeSHA1(string plainText)
{
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
HashAlgorithm hash = new SHA1Managed();
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
// Return the result.
return Convert.ToBase64String(hashBytes);
}
public static string CreateCryptoKey(int len)
{
byte[] bytes = new byte[len];
new RNGCryptoServiceProvider().GetBytes(bytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(string.Format("{0:X2}", bytes[i]));
}
return sb.ToString();
}
public static string Encrypt(string key, string str)
{
if (str == null)
return str;
// We are now going to create an instance of the
// Rihndael class.
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] plainText = System.Text.Encoding.Unicode.GetBytes(str);
byte[] salt = Encoding.ASCII.GetBytes(key.Length.ToString());
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(key, salt);
ICryptoTransform encryptor = RijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
// encode
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
// Close both streams
memoryStream.Close();
cryptoStream.Close();
// Return encrypted string
return Convert.ToBase64String(cipherBytes);
}
public static string GetRandomString(int length)
{
string ptrn = "abcdefghjklmnpqrstwxyz0123456789";
StringBuilder sb = new StringBuilder();
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = (randomBytes[0] & 0x7f) << 24 |
randomBytes[1] << 16 |
randomBytes[2] << 8 |
randomBytes[3];
Random rnd = new Random(seed);
for (int i = 0; i < length; i++)
sb.Append(ptrn[rnd.Next(ptrn.Length - 1)]);
return sb.ToString();
}
#endregion
#region Setup
public static Hashtable GetSetupParameters(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
Hashtable args = obj as Hashtable;
if (args == null)
throw new ArgumentNullException("obj");
return args;
}
public static object GetSetupParameter(Hashtable args, string paramName)
{
if (args == null)
throw new ArgumentNullException("args");
//
if (args.ContainsKey(paramName) == false)
{
return String.Empty;
}
//
return args[paramName];
}
public static string GetStringSetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (obj == null)
return null;
if (!(obj is string))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return obj as string;
}
public static int GetInt32SetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (!(obj is int))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return (int)obj;
}
public static Version GetVersionSetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (!(obj is Version))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return obj as Version;
}
public static string ReplaceScriptVariable(string str, string variable, string value)
{
Regex re = new Regex("\\$\\{" + variable + "\\}+", RegexOptions.IgnoreCase);
return re.Replace(str, value);
}
#endregion
#region Type convertions
/// <summary>
/// Converts string to int
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>
///The Int32 number equivalent to the number contained in value.
/// </returns>
public static int ParseInt(string value, int defaultValue)
{
if (value != null && value.Length > 0)
{
try
{
return Int32.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// ParseBool
/// </summary>
/// <param name="value">EventData</param>
/// <param name="defaultValue">Dafault value</param>
/// <returns>bool</returns>
public static bool ParseBool(string value, bool defaultValue)
{
if (value != null)
{
try
{
return bool.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// Converts string to decimal
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>The Decimal number equivalent to the number contained in value.</returns>
public static decimal ParseDecimal(string value, decimal defaultValue)
{
if (value != null && !string.IsNullOrEmpty(value))
{
try
{
return Decimal.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// Converts string to double
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>The double number equivalent to the number contained in value.</returns>
public static double ParseDouble(string value, double defaultValue)
{
if (value != null)
{
try
{
return double.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
#endregion
#region DB
/// <summary>
/// Converts db value to string
/// </summary>
/// <param name="val">EventData</param>
/// <returns>string</returns>
public static string GetDbString(object val)
{
string ret = string.Empty;
if ((val != null) && (val != DBNull.Value))
ret = (string)val;
return ret;
}
/// <summary>
/// Converts db value to short
/// </summary>
/// <param name="val">EventData</param>
/// <returns>short</returns>
public static short GetDbShort(object val)
{
short ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (short)val;
return ret;
}
/// <summary>
/// Converts db value to int
/// </summary>
/// <param name="val">EventData</param>
/// <returns>int</returns>
public static int GetDbInt32(object val)
{
int ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (int)val;
return ret;
}
/// <summary>
/// Converts db value to bool
/// </summary>
/// <param name="val">EventData</param>
/// <returns>bool</returns>
public static bool GetDbBool(object val)
{
bool ret = false;
if ((val != null) && (val != DBNull.Value))
ret = Convert.ToBoolean(val);
return ret;
}
/// <summary>
/// Converts db value to decimal
/// </summary>
/// <param name="val">EventData</param>
/// <returns>decimal</returns>
public static decimal GetDbDecimal(object val)
{
decimal ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (decimal)val;
return ret;
}
/// <summary>
/// Converts db value to datetime
/// </summary>
/// <param name="val">EventData</param>
/// <returns>DateTime</returns>
public static DateTime GetDbDateTime(object val)
{
DateTime ret = DateTime.MinValue;
if ((val != null) && (val != DBNull.Value))
ret = (DateTime)val;
return ret;
}
#endregion
#region Exceptions
public static bool IsThreadAbortException(Exception ex)
{
Exception innerException = ex;
while (innerException != null)
{
if (innerException is System.Threading.ThreadAbortException)
return true;
innerException = innerException.InnerException;
}
string str = ex.ToString();
return str.Contains("System.Threading.ThreadAbortException");
}
#endregion
#region Windows Firewall
public static bool IsWindowsFirewallEnabled()
{
int ret = RegistryUtils.GetRegistryKeyInt32Value(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile", "EnableFirewall");
return (ret == 1);
}
public static bool IsWindowsFirewallExceptionsAllowed()
{
int ret = RegistryUtils.GetRegistryKeyInt32Value(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile", "DoNotAllowExceptions");
return (ret != 1);
}
public static void OpenWindowsFirewallPort(string name, string port)
{
string path = Path.Combine(Environment.SystemDirectory, "netsh.exe");
string arguments = string.Format("firewall set portopening tcp {0} \"{1}\" enable", port, name);
RunProcess(path, arguments);
}
#endregion
#region Processes & Services
public static int RunProcess(string path, string arguments)
{
Process process = null;
try
{
ProcessStartInfo info = new ProcessStartInfo(path, arguments);
info.WindowStyle = ProcessWindowStyle.Hidden;
process = Process.Start(info);
process.WaitForExit();
return process.ExitCode;
}
finally
{
if (process != null)
{
process.Close();
}
}
}
public static void StartService(string serviceName)
{
ServiceController sc = new ServiceController(serviceName);
// Start the service if the current status is stopped.
if (sc.Status == ServiceControllerStatus.Stopped)
{
// Start the service, and wait until its status is "Running".
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
}
}
public static void StopService(string serviceName)
{
ServiceController sc = new ServiceController(serviceName);
// Start the service if the current status is stopped.
if (sc.Status != ServiceControllerStatus.Stopped &&
sc.Status != ServiceControllerStatus.StopPending)
{
// Start the service, and wait until its status is "Running".
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
}
#endregion
#region I/O
public static string GetSystemDrive()
{
return Path.GetPathRoot(Environment.SystemDirectory);
}
#endregion
public static bool IsWebDeployInstalled()
{
// TO-DO: Implement Web Deploy detection (x64/x86)
var isInstalled = false;
//
try
{
var msdeployRegKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\IIS Extensions\MSDeploy\2");
//
var keyValue = msdeployRegKey.GetValue("Install");
// We have found the required key in the registry hive
if (keyValue != null && keyValue.Equals(1))
{
isInstalled = true;
}
}
catch (Exception ex)
{
Log.WriteError("Could not retrieve Web Deploy key from the registry", ex);
}
//
return isInstalled;
}
public static bool IsWin64()
{
return (IntPtr.Size == 8);
}
public static void ShowConsoleErrorMessage(string format, params object[] args)
{
Console.WriteLine(String.Format(format, args));
}
public static string ResolveAspNet40RegistrationToolPath_Iis6(SetupVariables setupVariables)
{
// By default we fallback to the corresponding tool version based on the platform bitness
var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;
// Choose appropriate tool version for IIS 6
if (setupVariables.IISVersion.Major == 6)
{
// Change to x86 tool version on x64 w/ "Enable32bitAppOnWin64" flag enabled
if (Environment.Is64BitOperatingSystem == true && Utils.IIS32Enabled())
{
util = AspNet40RegistrationToolx86;
}
}
// Build path to the tool
return Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util);
}
/// <summary>
/// Beware: Web site component-dependent logic
/// </summary>
/// <param name="setupVariables"></param>
/// <returns></returns>
public static string ResolveAspNet40RegistrationToolPath_Iis7(SetupVariables setupVariables)
{
// By default we fallback to the corresponding tool version based on the platform bitness
var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;
// Choose appropriate tool version for IIS 7
if (setupVariables.IISVersion.Major == 7 && setupVariables.SetupAction == SetupActions.Update)
{
// Evaluate app pool settings on x64 platform only when update is running
if (Environment.Is64BitOperatingSystem == true)
{
// Change to x86 tool version if the component's app pool is in WOW64 mode
using (var srvman = new Microsoft.Web.Administration.ServerManager())
{
// Retrieve the component's app pool
var appPoolObj = srvman.ApplicationPools[setupVariables.WebApplicationPoolName];
// We are
if (appPoolObj == null)
{
throw new ArgumentException(String.Format("Could not find '{0}' web application pool", setupVariables.WebApplicationPoolName), "appPoolObj");
}
// Check app pool mode
else if (appPoolObj.Enable32BitAppOnWin64 == true)
{
util = AspNet40RegistrationToolx86;
}
}
}
}
// Build path to the tool
return Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util);
}
public static bool CheckAspNet40Registered(SetupVariables setupVariables)
{
//
var aspNet40Registered = false;
// Run ASP.NET Registration Tool command
var psOutput = ExecAspNetRegistrationToolCommand(setupVariables, "-lv");
// Split process output per lines
var strLines = psOutput.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
// Lookup for an evidence of ASP.NET 4.0
aspNet40Registered = strLines.Any((string s) => { return s.Contains("4.0.30319.0"); });
//
return aspNet40Registered;
}
public static string ExecAspNetRegistrationToolCommand(SetupVariables setupVariables, string arguments)
{
//
var util = (setupVariables.IISVersion.Major == 6) ? Utils.ResolveAspNet40RegistrationToolPath_Iis6(setupVariables) : Utils.ResolveAspNet40RegistrationToolPath_Iis7(setupVariables);
//
// Create a specific process start info set to redirect its standard output for further processing
ProcessStartInfo info = new ProcessStartInfo(util)
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = arguments
};
//
Log.WriteInfo(String.Format("Starting aspnet_regiis.exe {0}", info.Arguments));
//
var process = default(Process);
//
var psOutput = String.Empty;
//
try
{
// Start the process
process = Process.Start(info);
// Read the output
psOutput = process.StandardOutput.ReadToEnd();
// Wait for the completion
process.WaitForExit();
}
catch (Exception ex)
{
Log.WriteError("Could not execute ASP.NET Registration Tool command", ex);
}
finally
{
if (process != null)
process.Close();
}
// Trace output data for troubleshooting purposes
Log.WriteInfo(psOutput);
//
Log.WriteInfo(String.Format("Finished aspnet_regiis.exe {0}", info.Arguments));
//
return psOutput;
}
public static void RegisterAspNet40(Setup.SetupVariables setupVariables)
{
// Run ASP.NET Registration Tool command
ExecAspNetRegistrationToolCommand(setupVariables, arguments: (setupVariables.IISVersion.Major == 6) ? "-ir -enable" : "-ir");
}
public static WebExtensionStatus GetAspNetWebExtensionStatus_Iis6(SetupVariables setupVariables)
{
WebExtensionStatus status = WebExtensionStatus.Allowed;
if (setupVariables.IISVersion.Major == 6)
{
status = WebExtensionStatus.NotInstalled;
string path;
if (Utils.IsWin64() && !Utils.IIS32Enabled())
{
//64-bit
path = Path.Combine(OS.GetWindowsDirectory(), @"Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll");
}
else
{
//32-bit
path = Path.Combine(OS.GetWindowsDirectory(), @"Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll");
}
path = path.ToLower();
using (DirectoryEntry iis = new DirectoryEntry("IIS://LocalHost/W3SVC"))
{
PropertyValueCollection values = iis.Properties["WebSvcExtRestrictionList"];
for (int i = 0; i < values.Count; i++)
{
string val = values[i] as string;
if (!string.IsNullOrEmpty(val))
{
string strVal = val.ToString().ToLower();
if (strVal.Contains(path))
{
if (strVal[0] == '1')
{
status = WebExtensionStatus.Allowed;
}
else
{
status = WebExtensionStatus.Prohibited;
}
break;
}
}
}
}
}
return status;
}
public static void EnableAspNetWebExtension_Iis6()
{
Log.WriteStart("Enabling ASP.NET Web Service Extension");
//
var webExtensionName = (Utils.IsWin64() && Utils.IIS32Enabled()) ? "ASP.NET v4.0.30319 (32-bit)" : "ASP.NET v4.0.30319";
//
using (DirectoryEntry iisService = new DirectoryEntry("IIS://LocalHost/W3SVC"))
{
iisService.Invoke("EnableWebServiceExtension", webExtensionName);
iisService.CommitChanges();
}
//
Log.WriteEnd("Enabled ASP.NET Web Service Extension");
}
public static bool IIS32Enabled()
{
bool enabled = false;
using (DirectoryEntry obj = new DirectoryEntry("IIS://LocalHost/W3SVC/AppPools"))
{
object objProperty = GetObjectProperty(obj, "Enable32bitAppOnWin64");
if (objProperty != null)
{
enabled = (bool)objProperty;
}
}
return enabled;
}
public static void SetObjectProperty(DirectoryEntry oDE, string name, object value)
{
if (value != null)
{
if (oDE.Properties.Contains(name))
{
oDE.Properties[name][0] = value;
}
else
{
oDE.Properties[name].Add(value);
}
}
}
public static object GetObjectProperty(DirectoryEntry entry, string name)
{
if (entry.Properties.Contains(name))
return entry.Properties[name][0];
else
return null;
}
public static void OpenFirewallPort(string name, string port, Version iisVersion)
{
bool iis7 = (iisVersion.Major == 7);
if (iis7)
{
//TODO: Add IIS7 support
}
else
{
if (Utils.IsWindowsFirewallEnabled() &&
Utils.IsWindowsFirewallExceptionsAllowed())
{
//SetProgressText("Opening port in windows firewall...");
Log.WriteStart(String.Format("Opening port {0} in windows firewall", port));
Utils.OpenWindowsFirewallPort(name, port);
//update log
Log.WriteEnd("Opened port in windows firewall");
InstallLog.AppendLine(String.Format("- Opened port {0} in Windows Firewall", port));
}
}
}
public static string[] GetApplicationUrls(string ip, string domain, string port, string virtualDir)
{
List<string> urls = new List<string>();
// IP address, [port] and [virtualDir]
string url = ip;
if (String.IsNullOrEmpty(domain))
{
if (!String.IsNullOrEmpty(port) && port != "80")
url += ":" + port;
if (!String.IsNullOrEmpty(virtualDir))
url += "/" + virtualDir;
urls.Add(url);
}
// domain, [port] and [virtualDir]
if (!String.IsNullOrEmpty(domain))
{
url = domain;
if (!String.IsNullOrEmpty(port) && port != "80")
url += ":" + port;
if (!String.IsNullOrEmpty(virtualDir))
url += "/" + virtualDir;
urls.Add(url);
}
return urls.ToArray();
}
}
}

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;
namespace WebsitePanel.Setup.Common
{
[Serializable]
internal class WebException : Exception
{
public WebException()
{
}
public WebException(string message) : base(message)
{
}
public WebException(string message, Exception inner) : base(message, inner)
{
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
// 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.Management;
namespace WebsitePanel.Setup
{
/// <summary>
/// Wmi helper class.
/// </summary>
internal sealed class WmiHelper
{
// namespace
private string ns = null;
// scope
private ManagementScope scope = null;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="ns">Namespace.</param>
public WmiHelper(string ns)
{
this.ns = ns;
}
/// <summary>
/// Executes specified query.
/// </summary>
/// <param name="query">Query to execute.</param>
/// <returns>Resulting collection.</returns>
internal ManagementObjectCollection ExecuteQuery(string query)
{
ObjectQuery objectQuery = new ObjectQuery(query);
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(WmiScope, objectQuery);
return searcher.Get();
}
/// <summary>
/// Retreives ManagementClass class initialized to the given WMI path.
/// </summary>
/// <param name="path">A ManagementPath specifying which WMI class to bind to.</param>
/// <returns>Instance of the ManagementClass class.</returns>
internal ManagementClass GetClass(string path)
{
return new ManagementClass(WmiScope, new ManagementPath(path), null);
}
/// <summary>
/// Retreives ManagementObject class bound to the specified WMI path.
/// </summary>
/// <param name="path">A ManagementPath that contains a path to a WMI object.</param>
/// <returns>Instance of the ManagementObject class.</returns>
internal ManagementObject GetObject(string path)
{
return new ManagementObject(WmiScope, new ManagementPath(path), null);
}
public ManagementScope WmiScope
{
get
{
if(scope == null)
{
ManagementPath path = new ManagementPath(ns);
scope = new ManagementScope(path, new ConnectionOptions());
scope.Connect();
}
return scope;
}
}
}
}

View file

@ -0,0 +1,84 @@
// 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.Xml;
namespace WebsitePanel.Setup
{
public sealed class XmlUtils
{
private XmlUtils()
{
}
/// <summary>
/// Retrieves the specified attribute from the XML node.
/// </summary>
/// <param name="node">XML node.</param>
/// <param name="attribute">Attribute to retreive.</param>
/// <returns>Attribute value.</returns>
internal static string GetXmlAttribute(XmlNode node, string attribute)
{
string ret = null;
if (node != null)
{
XmlAttribute xmlAttribute = node.Attributes[attribute];
if (xmlAttribute != null)
{
ret = xmlAttribute.Value;
}
}
return ret;
}
internal static void SetXmlAttribute(XmlNode node, string attribute, string value)
{
if (node != null)
{
XmlAttribute xmlAttribute = node.Attributes[attribute];
if (xmlAttribute == null)
{
xmlAttribute = node.OwnerDocument.CreateAttribute(attribute);
node.Attributes.Append(xmlAttribute);
}
xmlAttribute.Value = value;
}
}
internal static void RemoveXmlNode(XmlNode node)
{
if (node != null && node.ParentNode != null)
{
node.ParentNode.RemoveChild(node);
}
}
}
}

View file

@ -0,0 +1,79 @@
// 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.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using Ionic.Zip;
namespace WebsitePanel.Setup.Common
{
/// <summary>
/// Shows progress of file zipping.
/// </summary>
public sealed class ZipIndicator
{
private ProgressBar progressBar;
string sourcePath;
string zipFile;
int totalFiles = 0;
int files = 0;
public ZipIndicator(ProgressBar progressBar, string sourcePath, string zipFile)
{
this.progressBar = progressBar;
this.sourcePath = sourcePath;
this.zipFile = zipFile;
}
public void Start()
{
totalFiles = FileUtils.CalculateFiles(sourcePath);
using (ZipFile zip = new ZipFile())
{
zip.AddProgress += ShowProgress;
zip.UseUnicodeAsNecessary = true;
zip.AddDirectory(sourcePath);
zip.Save(zipFile);
}
}
private void ShowProgress(object sender, AddProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Adding_AfterAddEntry)
{
string fileName = e.CurrentEntry.FileName;
files++;
this.progressBar.Value = Convert.ToInt32(files * 100 / totalFiles);
this.progressBar.Update();
}
}
}
}