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,467 @@
// 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.Text.RegularExpressions;
using System.Threading;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
public class BlackBerry5Provider : BlackBerryProvider
{
public string User
{
get
{
return ProviderSettings[Constants.UserName];
}
}
public override string[] Install()
{
List<string> ret = new List<string>();
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
ret.Add(BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
}
return ret.ToArray();
}
internal override ResultObject CreateBlackBerryUserInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("CreateBlackBerryUser5Internal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("CreateBlackBerry5UserInternal", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-username {0} -password {1} -add -u {2} -b {3}",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Excit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("CreateBlackBerry5UserInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("CreateBlackBerry5UserInternal");
return res;
}
internal override ResultObject SetActivationPasswordWithExpirationTimeInternal(string primaryEmailAddress, string password, int time)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("SetActivationPasswordWithExpirationTimeInternal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format(" -username {0} -password {1} -change -u {2} -b {3} -w {4} -wt {5}",
User,
Password,
primaryEmailAddress,
EnterpriseServer,
password,
time);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal");
return res;
}
private ResultObject RemoveEmailActivationPassword(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("RemoveEmailActivationPassword");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("RemoveEmailActivationPassword", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-username {0} -password {1} -change -u {2} -b {3} -cw",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("RemoveEmailActivationPassword", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("RemoveEmailActivationPassword");
return res;
}
internal override ResultObject SetEmailActivationPasswordInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("SetEmailActivationPassword");
ResultObject removeRes = RemoveEmailActivationPassword(primaryEmailAddress);
res.ErrorCodes.AddRange(removeRes.ErrorCodes);
if (!removeRes.IsSuccess)
{
HostedSolutionLog.EndLog("SetEmailActivationPassword", res);
return res;
}
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("SetEmailActivationPassword", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-username {0} -password {1} -change -u {2} -b {3} -wrandom",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("SetEmailActivationPassword", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("SetEmailActivationPassword");
return res;
}
internal override ResultObject DeleteDataFromBlackBerryDeviceInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("DeleteDataFromBlackBerry5Device");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("DeleteDataFromBlackBerryDevice", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-username {0} -password {1} -kill_handheld -u {2} -b {3}",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("DeleteDataFromBlackBerry5Device", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("DeleteDataFromBlackBerry5Device");
return res;
}
internal override BlackBerryUserStatsResult GetBlackBerryUserStatsInternal(string primaryEmailAddress)
{
BlackBerryUserStatsResult res =
HostedSolutionLog.StartLog<BlackBerryUserStatsResult>("GetBlackBerry5UserStatsInternal");
string[] keys;
string[] values;
ResultObject tempRes = GetBlackBerryUserData(primaryEmailAddress, out keys, out values);
res.ErrorCodes.AddRange(tempRes.ErrorCodes);
if (!res.IsSuccess)
{
HostedSolutionLog.EndLog("GetBlackBerry5UserStatsInternal", res);
return res;
}
try
{
List<BlackBerryStatsItem> items = new List<BlackBerryStatsItem>();
int[] inds = new int[] { 3, 4, 5, 7, 8, 10, 11, 12, 13, 14, 15, 25 };
foreach (int i in inds)
{
if (keys.Length > i && values.Length > i)
items.Add(new BlackBerryStatsItem() { Name = keys[i], Value = values[i] });
}
res.Value = items;
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerry5UserStatsInternal", res, BlackBerryErrorsCodes.CANNOT_POPULATE_STATS, ex);
return res;
}
HostedSolutionLog.EndLog("GetBlackBerry5UserStatsInternal");
return res;
}
protected override ResultObject GetBlackBerryUserData(string primaryEmailAddress, out string[] keys, out string[] values)
{
BlackBerryUserStatsResult res =
HostedSolutionLog.StartLog<BlackBerryUserStatsResult>("GetBlackBerry5UserData");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("GetBlackBerry5UserData", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
keys = null;
values = null;
return res;
}
string arguments = string.Format(" -username {0} -password {1} -stats -u {2} -b {3}",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
string output;
string error;
try
{
int exitCode = Execute(file, arguments, out output, out error);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", error, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerry5UserData", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
keys = null;
values = null;
return res;
}
try
{
string[] data = output.Split('\n');
Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
int startRow = 0;
if (data.Length > 0)
{
for (startRow = data.Length - 1; startRow >= 0; startRow--)
{
if (!string.IsNullOrEmpty(data[startRow]) && !string.IsNullOrEmpty(data[startRow].Trim()))
break;
}
}
keys = regex.Split(data[startRow -1]);
values = regex.Split(data[startRow]);
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerry5UserData", res, BlackBerryErrorsCodes.CANNOT_SPLIT_STATS, ex);
keys = null;
values = null;
return res;
}
HostedSolutionLog.EndLog("GetBlackBerry5UserData");
return res;
}
internal override ResultObject DeleteBlackBerryUserInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("DeleteBlackBerry5UserInternal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("DeleteBlackBerry5User", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-username {0} -password {1} -delete -u {2} -b {3}",
User,
Password,
primaryEmailAddress,
EnterpriseServer);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
for (int i = 0; i < 10; i++)
{
BlackBerryUserDeleteState states = GetBlackBerryUserState(primaryEmailAddress);
if (states != BlackBerryUserDeleteState.Pending)
{
break;
}
Thread.Sleep(10000);
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("DeleteBlackBerry5UserInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("DeleteBlackBerry5UserInternal");
return res;
}
}
}

View file

@ -0,0 +1,528 @@
// 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;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
public class BlackBerryProvider : HostingServiceProviderBase, IBlackBerry
{
public string UtilityPath
{
get
{
return ProviderSettings[Constants.UtilityPath];
}
}
public string Password
{
get
{
return ProviderSettings[Constants.Password];
}
}
public string AdministrationToolService
{
get
{
return ProviderSettings[Constants.AdministrationToolService];
}
}
public string EnterpriseServer
{
get
{
return ProviderSettings[Constants.EnterpriseServer];
}
}
public ResultObject CreateBlackBerryUser(string primaryEmailAddress)
{
return CreateBlackBerryUserInternal(primaryEmailAddress);
}
internal virtual ResultObject CreateBlackBerryUserInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("CreateBlackBerryUserInternal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("CreateBlackBerryUserInternal", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-add -u {0} -p {1} -b {2} -n {3}",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Excit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch(Exception ex)
{
HostedSolutionLog.EndLog("CreateBlackBerryUserInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("CreateBlackBerryUserInternal");
return res;
}
protected int Execute(string file, string arguments, out string output, out string error)
{
string oldDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(UtilityPath);
ProcessStartInfo startInfo = new ProcessStartInfo(file, arguments) ;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process proc = Process.Start(startInfo);
if (proc == null)
throw new ApplicationException("Proc is null.");
StreamReader outputReader = proc.StandardOutput;
output= outputReader.ReadToEnd();
StreamReader errorReader = proc.StandardError;
error = errorReader.ReadToEnd();
Directory.SetCurrentDirectory(oldDir);
return proc.ExitCode;
}
protected int Execute(string file, string arguments, out string output)
{
Log.WriteInfo(file);
Log.WriteInfo(arguments);
string outputData;
string errorData;
int res = Execute(file, arguments, out outputData, out errorData);
output = outputData.Length > 0 ? "Output stream:" + outputData : string.Empty;
output += errorData.Length > 0 ? "Error stream:" + errorData : string.Empty;
return res;
}
public ResultObject DeleteBlackBerryUser(string primaryEmailAddress)
{
return DeleteBlackBerryUserInternal(primaryEmailAddress);
}
internal virtual ResultObject DeleteBlackBerryUserInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("DeleteBlackBerryUserInternal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("DeleteBlackBerryUser", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-delete -u {0} -p {1} -b {2} -n {3}",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
for (int i = 0; i < 10; i++)
{
BlackBerryUserDeleteState states = GetBlackBerryUserState(primaryEmailAddress);
if (states != BlackBerryUserDeleteState.Pending)
{
break;
}
Thread.Sleep(10000);
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("DeleteBlackBerryUserInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("DeleteBlackBerryUserInternal");
return res;
}
public BlackBerryUserStatsResult GetBlackBerryUserStats(string primaryEmailAddress)
{
return GetBlackBerryUserStatsInternal(primaryEmailAddress);
}
protected virtual ResultObject GetBlackBerryUserData(string primaryEmailAddress, out string []keys, out string []values)
{
BlackBerryUserStatsResult res =
HostedSolutionLog.StartLog<BlackBerryUserStatsResult>("GetBlackBerryUserData");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("GetBlackBerryUserData", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
keys = null;
values = null;
return res;
}
string arguments = string.Format("-stats -u {0} -p {1} -b {2} -n {3}",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService);
string output;
string error;
try
{
int exitCode = Execute(file, arguments, out output, out error);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", error, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerryUserData", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
keys = null;
values = null;
return res;
}
try
{
string[] data = output.Split('\n');
Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
keys = regex.Split(data[0]);
values = regex.Split(data[1]);
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerryUserData", res, BlackBerryErrorsCodes.CANNOT_SPLIT_STATS, ex);
keys = null;
values = null;
return res;
}
HostedSolutionLog.EndLog("GetBlackBerryUserData");
return res;
}
internal virtual BlackBerryUserStatsResult GetBlackBerryUserStatsInternal(string primaryEmailAddress)
{
BlackBerryUserStatsResult res =
HostedSolutionLog.StartLog<BlackBerryUserStatsResult>("GetBlackBerryUserStatsInternal");
string[] keys;
string[] values;
ResultObject tempRes = GetBlackBerryUserData(primaryEmailAddress, out keys, out values);
res.ErrorCodes.AddRange(tempRes.ErrorCodes);
if (!res.IsSuccess)
{
HostedSolutionLog.EndLog("GetBlackBerryUserStatsInternal", res);
return res;
}
try
{
List<BlackBerryStatsItem> items = new List<BlackBerryStatsItem>();
int []inds = new int[] {3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 26};
foreach(int i in inds)
{
items.Add(new BlackBerryStatsItem() { Name = keys[i], Value = values[i] });
}
res.Value = items;
}
catch(Exception ex)
{
HostedSolutionLog.EndLog("GetBlackBerryUserStatsInternal", res, BlackBerryErrorsCodes.CANNOT_POPULATE_STATS, ex);
return res;
}
HostedSolutionLog.EndLog("GetBlackBerryUserStatsInternal");
return res;
}
public override bool IsInstalled()
{
return true;
}
public override string[] Install()
{
return CheckSettings();
}
protected string[] CheckSettings()
{
List<string> ret = new List<string>();
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
ret.Add(BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
}
string output;
int res = Execute("Net", string.Format("View {0}", AdministrationToolService), out output);
if (res != 0)
{
ret.Add(BlackBerryErrorsCodes.ADMINISTRATION_TOOL_SERVICE_IS_INVALID);
}
return ret.ToArray();
}
public ResultObject SetActivationPasswordWithExpirationTime(string primaryEmailAddress, string password, int time)
{
return SetActivationPasswordWithExpirationTimeInternal(primaryEmailAddress, password, time);
}
internal virtual ResultObject SetActivationPasswordWithExpirationTimeInternal(string primaryEmailAddress, string password, int time)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("SetActivationPasswordWithExpirationTimeInternal");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-change -u {0} -p {1} -b {2} -n {3} -w {4} -wt {5}",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService,
password,
time);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("SetActivationPasswordWithExpirationTimeInternal");
return res;
}
public ResultObject SetEmailActivationPassword(string primaryEmailAddress)
{
return SetEmailActivationPasswordInternal(primaryEmailAddress);
}
internal virtual ResultObject SetEmailActivationPasswordInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("SetEmailActivationPassword");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("SetEmailActivationPassword", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-change -u {0} -p {1} -b {2} -n {3} -wrandom",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("SetEmailActivationPassword", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("SetEmailActivationPassword");
return res;
}
public ResultObject DeleteDataFromBlackBerryDevice(string primaryEmailAddress)
{
return DeleteDataFromBlackBerryDeviceInternal(primaryEmailAddress);
}
internal virtual ResultObject DeleteDataFromBlackBerryDeviceInternal(string primaryEmailAddress)
{
ResultObject res = HostedSolutionLog.StartLog<ResultObject>("DeleteDataFromBlackBerryDevice");
string file = Path.Combine(UtilityPath, "besuseradminclient.exe");
if (!File.Exists(file))
{
HostedSolutionLog.EndLog("DeleteDataFromBlackBerryDevice", res, BlackBerryErrorsCodes.FILE_PATH_IS_INVALID);
return res;
}
string arguments = string.Format("-kill_handheld -u {0} -p {1} -b {2} -n {3}",
primaryEmailAddress,
Password,
EnterpriseServer,
AdministrationToolService);
try
{
string output;
int exitCode = Execute(file, arguments, out output);
if (exitCode == 0)
{
Log.WriteInfo(output);
}
else
{
throw new ApplicationException(
string.Format("Exit code is not 0. {0}, ExitCode = {1}", output, exitCode));
}
}
catch (Exception ex)
{
HostedSolutionLog.EndLog("DeleteDataFromBlackBerryDevice", res, BlackBerryErrorsCodes.CANNOT_EXECUTE_COMMAND, ex);
return res;
}
HostedSolutionLog.EndLog("DeleteDataFromBlackBerryDevice");
return res;
}
protected BlackBerryUserDeleteState GetBlackBerryUserState(string primaryEmailAddress)
{
string[] keys;
string[] values;
GetBlackBerryUserData(primaryEmailAddress, out keys, out values);
return values != null && values.Length == 32 && !string.IsNullOrEmpty(values[values.Length - 1])
? BlackBerryUserDeleteState.Pending
: BlackBerryUserDeleteState.None;
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,237 @@
// 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.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.DirectoryServices;
using System.Security;
using System.Security.Principal;
using System.Security.AccessControl;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using WebsitePanel.Providers;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using Microsoft.Exchange.Data.Directory.Recipient;
using Microsoft.Win32;
using Microsoft.Exchange.Data;
using Microsoft.Exchange.Data.Directory;
using Microsoft.Exchange.Data.Storage;
namespace WebsitePanel.Providers.HostedSolution
{
public class Exchange2010 : Exchange2007
{
#region Static constructor
static Exchange2010()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly);
ExchangeRegistryPath = "SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup";
}
#endregion
#region Mailboxes
internal override void SetCalendarSettings(Runspace runspace, string id)
{
ExchangeLog.LogStart("SetCalendarSettings");
Command cmd = new Command("Set-CalendarProcessing");
cmd.Parameters.Add("Identity", id);
cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept);
ExecuteShellCommand(runspace, cmd);
ExchangeLog.LogEnd("SetCalendarSettings");
}
#endregion
#region Distribution Lists
internal override string GetGroupManager(PSObject group)
{
string ret = null;
MultiValuedProperty<ADObjectId> ids =
(MultiValuedProperty<ADObjectId>)GetPSObjectProperty(group, "ManagedBy");
if ( ids.Count > 0 )
ret = ObjToString(ids[0]);
return ret;
}
internal override void RemoveDistributionGroup(Runspace runSpace, string id)
{
ExchangeLog.LogStart("RemoveDistributionGroup");
Command cmd = new Command("Remove-DistributionGroup");
cmd.Parameters.Add("Identity", id);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runSpace, cmd);
ExchangeLog.LogEnd("RemoveDistributionGroup");
}
internal override void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook)
{
Command cmd = new Command("Set-DistributionGroup");
cmd.Parameters.Add("Identity", id);
cmd.Parameters.Add("DisplayName", displayName);
cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runSpace, cmd);
}
internal override void SetGroup(Runspace runSpace, string id, string managedBy, string notes)
{
Command cmd = new Command("Set-Group");
cmd.Parameters.Add("Identity", id);
cmd.Parameters.Add("ManagedBy", managedBy);
cmd.Parameters.Add("Notes", notes);
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runSpace, cmd);
}
internal override void RemoveDistributionGroupMember(Runspace runSpace, string group, string member)
{
Command cmd = new Command("Remove-DistributionGroupMember");
cmd.Parameters.Add("Identity", group);
cmd.Parameters.Add("Member", member);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runSpace, cmd);
}
internal override void AddDistributionGroupMember(Runspace runSpace, string group, string member)
{
Command cmd = new Command("Add-DistributionGroupMember");
cmd.Parameters.Add("Identity", group);
cmd.Parameters.Add("Member", member);
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runSpace, cmd);
}
internal override void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts)
{
ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts");
Command cmd = new Command("Set-DistributionGroup");
cmd.Parameters.Add("Identity", accountName);
cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts));
cmd.Parameters.Add("BypassSecurityGroupManagerCheck");
ExecuteShellCommand(runspace, cmd);
ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts");
}
#endregion
#region PowerShell integration
internal override string ExchangeSnapInName
{
get { return "Microsoft.Exchange.Management.PowerShell.E2010"; }
}
internal override Runspace OpenRunspace()
{
Runspace runspace = base.OpenRunspace();
Command cmd = new Command("Set-ADServerSettings");
cmd.Parameters.Add("PreferredServer", PrimaryDomainController);
ExecuteShellCommand(runspace, cmd, false);
return runspace;
}
private static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args)
{
//Add path for the Exchange 2007 DLLs
if (args.Name.Contains("Microsoft.Exchange"))
{
string exchangePath = GetExchangePath();
if (string.IsNullOrEmpty(exchangePath))
return null;
string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll");
if (!File.Exists(path))
return null;
ExchangeLog.DebugInfo("Resolved assembly: {0}", path);
return Assembly.LoadFrom(path);
}
else
{
return null;
}
}
#endregion
#region Storage
internal override string CreateStorageGroup(Runspace runSpace, string name, string server)
{
return string.Empty;
}
internal override string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup)
{
ExchangeLog.LogStart("CreateMailboxDatabase");
string id;
Command cmd = new Command("Get-MailboxDatabase");
cmd.Parameters.Add("Identity", name);
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
if (result != null && result.Count > 0)
{
id = GetResultObjectIdentity(result);
}
else
{
throw new Exception(string.Format("Mailbox database {0} not found", name));
}
ExchangeLog.LogEnd("CreateMailboxDatabase");
return id;
}
#endregion
public override bool IsInstalled()
{
int value = 0;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath);
if (rk != null)
{
value = (int)rk.GetValue("MsiProductMajor", null);
rk.Close();
}
return value == 14;
}
}
}

View file

@ -0,0 +1,103 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Management.Automation.Runspaces;
using System.Text;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Exchange Log Helper Methods
/// </summary>
internal class ExchangeLog
{
internal static string LogPrefix = "Exchange";
internal static void LogStart(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteStart("{0} {1}", LogPrefix, text);
}
internal static void LogEnd(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteEnd("{0} {1}", LogPrefix, text);
}
internal static void LogInfo(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteInfo("{0} {1}", LogPrefix, text);
}
internal static void LogWarning(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteWarning("{0} {1}", LogPrefix, text);
}
internal static void LogError(Exception ex)
{
Log.WriteError(LogPrefix, ex);
}
internal static void LogError(string message, Exception ex)
{
string text = String.Format("{0} {1}", LogPrefix, message);
Log.WriteError(text, ex);
}
internal static void DebugInfo(string message, params object[] args)
{
#if DEBUG
string text = String.Format(message, args);
Log.WriteInfo("{0} {1}", LogPrefix, text);
#endif
}
internal static void DebugCommand(Command cmd)
{
#if DEBUG
StringBuilder sb = new StringBuilder(cmd.CommandText);
foreach (CommandParameter parameter in cmd.Parameters)
{
string formatString = " -{0} {1}";
if (parameter.Value is string)
formatString = " -{0} '{1}'";
else if (parameter.Value is bool)
formatString = " -{0} ${1}";
sb.AppendFormat(formatString, parameter.Name, parameter.Value);
}
Log.WriteInfo("{0} {1}", LogPrefix, sb.ToString());
#endif
}
}
}

View file

@ -0,0 +1,240 @@
// 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.Collections.Generic;
namespace WebsitePanel.Providers.HostedSolution
{
internal class ExchangeTransaction
{
List<TransactionAction> actions = null;
public ExchangeTransaction()
{
actions = new List<TransactionAction>();
}
internal List<TransactionAction> Actions
{
get { return actions; }
}
internal void RegisterNewOrganizationUnit(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateOrganizationUnit;
action.Id = id;
Actions.Add(action);
}
public void RegisterNewDistributionGroup(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateDistributionGroup;
action.Id = id;
Actions.Add(action);
}
public void RegisterMailEnabledDistributionGroup(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.EnableDistributionGroup;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewGlobalAddressList(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateGlobalAddressList;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewAddressList(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateAddressList;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewOfflineAddressBook(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateOfflineAddressBook;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewActiveSyncPolicy(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateActiveSyncPolicy;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewAcceptedDomain(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateAcceptedDomain;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewUPNSuffix(string id, string suffix)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.AddUPNSuffix;
action.Id = id;
action.Suffix = suffix;
Actions.Add(action);
}
internal void RegisterNewMailbox(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateMailbox;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewContact(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreateContact;
action.Id = id;
Actions.Add(action);
}
internal void RegisterNewPublicFolder(string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.CreatePublicFolder;
action.Id = id;
Actions.Add(action);
}
internal void AddMailBoxFullAccessPermission(string accountName, string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.AddMailboxFullAccessPermission;
action.Id = id;
action.Account = accountName;
Actions.Add(action);
}
internal void AddSendAsPermission(string accountName, string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.AddSendAsPermission;
action.Id = id;
action.Account = accountName;
Actions.Add(action);
}
internal void RemoveMailboxFullAccessPermission(string accountName, string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.RemoveMailboxFullAccessPermission;
action.Id = id;
action.Account = accountName;
Actions.Add(action);
}
internal void RemoveSendAsPermission(string accountName, string id)
{
TransactionAction action = new TransactionAction();
action.ActionType = TransactionAction.TransactionActionTypes.RemoveSendAsPermission;
action.Id = id;
action.Account = accountName;
Actions.Add(action);
}
}
internal class TransactionAction
{
private TransactionActionTypes actionType;
public TransactionActionTypes ActionType
{
get { return actionType; }
set { actionType = value; }
}
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string suffix;
public string Suffix
{
get { return suffix; }
set { suffix = value; }
}
private string account;
public string Account
{
get { return account; }
set { account = value; }
}
internal enum TransactionActionTypes
{
CreateOrganizationUnit,
CreateGlobalAddressList,
CreateAddressList,
CreateOfflineAddressBook,
CreateDistributionGroup,
EnableDistributionGroup,
CreateAcceptedDomain,
AddUPNSuffix,
CreateMailbox,
CreateContact,
CreatePublicFolder,
CreateActiveSyncPolicy,
AddMailboxFullAccessPermission,
AddSendAsPermission,
RemoveMailboxFullAccessPermission,
RemoveSendAsPermission
};
}
}

View file

@ -0,0 +1,370 @@
// 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 WebsitePanel.Providers.SharePoint;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using Microsoft.Win32;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Provides hosted SharePoint server functionality implementation.
/// </summary>
public class HostedSharePointServer : HostingServiceProviderBase, IHostedSharePointServer
{
private delegate TReturn SharePointAction<TReturn>(HostedSharePointServerImpl impl);
protected string Wss3RegistryKey;
protected string Wss3Registry32Key;
protected string LanguagePacksPath;
public HostedSharePointServer()
{
this.Wss3RegistryKey = @"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0";
this.Wss3Registry32Key = @"SOFTWARE\Wow6432Node\Microsoft\Shared Tools\Web Server Extensions\12.0";
this.LanguagePacksPath = @"%commonprogramfiles%\microsoft shared\Web Server Extensions\12\HCCab\";
}
/// <summary>
/// Gets root web application uri.
/// </summary>
public Uri RootWebApplicationUri
{
get
{
return new Uri(ProviderSettings["RootWebApplicationUri"]);
}
}
public string BackupTemporaryFolder
{
get
{
return ProviderSettings["BackupTemporaryFolder"];
}
}
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages()
{
HostedSharePointServerImpl impl = new HostedSharePointServerImpl();
return impl.GetSupportedLanguages(LanguagePacksPath);
}
/// <summary>
/// Gets list of SharePoint collections within root web application.
/// </summary>
/// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections()
{
return
ExecuteSharePointAction<SharePointSiteCollection[]>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollections(RootWebApplicationUri);
});
}
/// <summary>
/// Gets SharePoint collection within root web application with given name.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</param>
/// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(string url)
{
return
ExecuteSharePointAction<SharePointSiteCollection>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollection(RootWebApplicationUri, url);
});
}
/// <summary>
/// Creates site collection within predefined root web application.
/// </summary>
/// <param name="siteCollection">Information about site coolection to be created.</param>
public void CreateSiteCollection(SharePointSiteCollection siteCollection)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.CreateSiteCollection(RootWebApplicationUri, siteCollection);
return null;
});
}
/// <summary>
/// Deletes site collection under given url.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
public void DeleteSiteCollection(string url)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.DeleteSiteCollection(RootWebApplicationUri, url);
return null;
});
}
/// <summary>
/// Backups site collection under give url.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <returns>Created backup full path.</returns>
public string BackupSiteCollection(string url, string filename, bool zip)
{
return ExecuteSharePointAction<string>(delegate(HostedSharePointServerImpl impl)
{
return impl.BackupSiteCollection(RootWebApplicationUri, url, filename, zip, BackupTemporaryFolder);
});
}
/// <summary>
/// Restores site collection under given url from backup.
/// </summary>
/// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Backup file name to restore from.</param>
public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.RestoreSiteCollection(RootWebApplicationUri, siteCollection, filename);
return null;
});
}
/// <summary>
/// Gets binary data chunk of specified size from specified offset.
/// </summary>
/// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="offset">Offset from which to start data reading.</param>
/// <param name="length">Binary data chunk length.</param>
/// <returns>Binary data chunk read from file.</returns>
public virtual byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
byte[] buffer = FileUtils.GetFileBinaryChunk(path, offset, length);
// Delete temp file
if (buffer.Length < length)
{
FileUtils.DeleteFile(path);
}
return buffer;
}
/// <summary>
/// Appends supplied binary data chunk to file.
/// </summary>
/// <param name="fileName">Non existent file name to append to.</param>
/// <param name="path">Full path to existent file to append to.</param>
/// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Path to file that was appended with chunk.</returns>
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), fileName);
if (FileUtils.FileExists(path))
{
FileUtils.DeleteFile(path);
}
}
FileUtils.AppendFileBinaryContent(path, chunk);
return path;
}
public override bool IsInstalled()
{
return IsSharePointInstalled();
}
/// <summary>
/// Deletes service items that represent SharePoint site collection.
/// </summary>
/// <param name="items">Items to be deleted.</param>
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSiteCollection)
{
try
{
DeleteSiteCollection((item as SharePointSiteCollection).Url);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
/// <summary>
/// Calculates diskspace used by supplied service items.
/// </summary>
/// <param name="items">Service items to get diskspace usage for.</param>
/// <returns>Calculated disk space usage statistics.</returns>
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
// update items with diskspace
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSiteCollection)
{
try
{
Log.WriteStart(String.Format("Calculating '{0}' site logs size", item.Name));
SharePointSiteCollection site = GetSiteCollection(item.Name);
ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
diskspace.ItemId = item.Id;
diskspace.DiskSpace = site.Diskspace;
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating '{0}' site logs size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
}
return itemsDiskspace.ToArray();
}
/// <summary>
/// Checks whether Wss 3.0 is installed.
/// </summary>
/// <returns>true - if it is installed; false - otherwise.</returns>
private bool IsSharePointInstalled()
{
RegistryKey spKey = Registry.LocalMachine.OpenSubKey(Wss3RegistryKey);
RegistryKey spKey32 = Registry.LocalMachine.OpenSubKey(Wss3Registry32Key);
if (spKey == null && spKey32 == null)
{
return false;
}
string spVal = (string)spKey.GetValue("SharePoint");
return (String.Compare(spVal, "installed", true) == 0);
}
/// <summary>
/// Executes supplied action within separate application domain.
/// </summary>
/// <param name="action">Action to be executed.</param>
/// <returns>Any object that results from action execution or null if nothing is supposed to be returned.</returns>
/// <exception cref="ArgumentNullException">Is thrown in case supplied action is null.</exception>
private static TReturn ExecuteSharePointAction<TReturn>(SharePointAction<TReturn> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
AppDomain domain = null;
try
{
// Create instance of server implementation in a separate application domain for
// security and isolation purposes.
Type type = typeof (HostedSharePointServerImpl);
AppDomainSetup info = new AppDomainSetup();
info.ApplicationBase = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
info.PrivateBinPath = "bin; bin/debug";
domain = AppDomain.CreateDomain("WSS30", null, info);
HostedSharePointServerImpl impl =
(HostedSharePointServerImpl)
domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
// Execute requested action within created application domain.
return action(impl);
}
finally
{
if (domain != null)
{
AppDomain.Unload(domain);
}
}
}
public void UpdateQuotas(string url, long maxStorage, long warningStorage)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.UpdateQuotas(RootWebApplicationUri, url, maxStorage, warningStorage);
return null;
});
}
public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string []urls)
{
SharePointSiteDiskSpace []sd = null;
sd = ExecuteSharePointAction<SharePointSiteDiskSpace[]>(delegate(HostedSharePointServerImpl impl)
{
return impl.CalculateSiteCollectionDiskSpace(RootWebApplicationUri, urls);
});
return sd;
}
public long GetSiteCollectionSize(string url)
{
long ret;
ret = ExecuteSharePointAction<long>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollectionSize(RootWebApplicationUri, url);
});
return ret;
}
}
}

View file

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Providers.HostedSolution
{
public class HostedSharePointServer2010 : HostedSharePointServer
{
public HostedSharePointServer2010()
{
this.Wss3RegistryKey = @"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0";
this.Wss3Registry32Key = @"SOFTWARE\Wow6432Node\Microsoft\Shared Tools\Web Server Extensions\14.0";
this.LanguagePacksPath = @"%commonprogramfiles%\microsoft shared\Web Server Extensions\14\HCCab\";
}
}
}

View file

@ -0,0 +1,531 @@
// 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.Security.Principal;
using WebsitePanel.Providers.SharePoint;
using WebsitePanel.Providers.Utils;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Represents SharePoint management functionality implementation.
/// </summary>
public class HostedSharePointServerImpl : MarshalByRefObject
{
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages(string languagePacksPath)
{
List<int> languages = new List<int>();
string rootDirectory = FileUtils.EvaluateSystemVariables(languagePacksPath);
foreach (string dir in Directory.GetDirectories(rootDirectory))
{
int languageId = 0;
if (Int32.TryParse(dir.Replace(rootDirectory, String.Empty), out languageId))
{
languages.Add(languageId);
}
}
return languages.ToArray();
}
public long GetSiteCollectionSize(Uri root,string url)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
SPSite site = rootWebApplication.Sites[url];
if (site != null)
site.RecalculateStorageUsed();
else
throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
return site.Usage.Storage;
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri root, string[] urls)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
List<SharePointSiteDiskSpace> ret = new List<SharePointSiteDiskSpace>();
foreach (string url in urls)
{
SharePointSiteDiskSpace siteDiskSpace = new SharePointSiteDiskSpace();
rootWebApplication.Sites[url].RecalculateStorageUsed();
siteDiskSpace.Url = url;
siteDiskSpace.DiskSpace = (long)Math.Round( rootWebApplication.Sites[url].Usage.Storage / 1024.0 / 1024.0);
ret.Add(siteDiskSpace);
}
return ret.ToArray();
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
/// <summary>
/// Gets list of SharePoint collections within root web application.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections(Uri rootWebApplicationUri)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
List<SharePointSiteCollection> siteCollections = new List<SharePointSiteCollection>();
foreach(SPSite site in rootWebApplication.Sites)
{
SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection();
FillSiteCollection(loadedSiteCollection, site);
siteCollections.Add(loadedSiteCollection);
}
return siteCollections.ToArray();
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
/// <summary>
/// Gets SharePoint collection within root web application with given name.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</param>
/// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(Uri rootWebApplicationUri, string url)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
SPSite site = rootWebApplication.Sites[siteCollectionUrl];
if (site != null)
{
SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection();
FillSiteCollection(loadedSiteCollection, site);
return loadedSiteCollection;
}
return null;
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
private static void DeleteQuotaTemplate(string name)
{
SPFarm farm = SPFarm.Local;
SPWebService webService = farm.Services.GetValue<SPWebService>("");
SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;
quotaColl.Delete(name);
}
public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
SPQuota quota = new SPQuota();
if (maxStorage != -1)
quota.StorageMaximumLevel = maxStorage * 1024 * 1024;
else
quota.StorageMaximumLevel = 0;
if (warningStorage != -1 && maxStorage != -1)
quota.StorageWarningLevel = Math.Min(warningStorage, maxStorage)*1024*1024;
else
quota.StorageWarningLevel = 0;
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
rootWebApplication.Sites[url].Quota = quota;
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
/// <summary>
/// Creates site collection within predefined root web application.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="siteCollection">Information about site coolection to be created.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);
SPQuota spQuota;
SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl,
siteCollection.Title, siteCollection.Description,
(uint) siteCollection.LocaleId, String.Empty,
siteCollection.OwnerLogin, siteCollection.OwnerName,
siteCollection.OwnerEmail,
null, null, null, true);
try
{
spQuota = new SPQuota();
if (siteCollection.MaxSiteStorage != -1)
spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024;
if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1)
spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024;
}
catch (Exception)
{
rootWebApplication.Sites.Delete(siteCollectionUrl);
throw;
}
try
{
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
spSite.Quota = spQuota;
}
catch (Exception)
{
rootWebApplication.Sites.Delete(siteCollectionUrl);
DeleteQuotaTemplate(siteCollection.Title);
throw;
}
rootWebApplication.Update(true);
}
catch(Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
/// <summary>
/// Deletes site collection under given url.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void DeleteSiteCollection(Uri rootWebApplicationUri, string url)
{
try
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsImpersonationContext wic = identity.Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
//string args = String.Format("-o deletesite -url {0}", siteCollectionUrl);
//string stsadm = @"c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM.EXE";
//// launch system process
//ProcessStartInfo startInfo = new ProcessStartInfo(stsadm, args);
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//startInfo.RedirectStandardOutput = true;
//startInfo.UseShellExecute = false;
//Process proc = Process.Start(startInfo);
//// analyze results
//StreamReader reader = proc.StandardOutput;
//string output = reader.ReadToEnd();
//int exitCode = proc.ExitCode;
//reader.Close();
rootWebApplication.Sites.Delete(siteCollectionUrl, true);
rootWebApplication.Update(true);
}
finally
{
wic.Undo();
}
}
catch(Exception ex)
{
throw new InvalidOperationException("Failed to delete site collection.", ex);
}
}
/// <summary>
/// Backups site collection under give url.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <param name="tempPath">Custom temp path for backup</param>
/// <returns>Full path to created backup.</returns>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public string BackupSiteCollection(Uri rootWebApplicationUri, string url, string filename, bool zip, string tempPath)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
if (String.IsNullOrEmpty(tempPath))
{
tempPath = Path.GetTempPath();
}
string backupFileName = Path.Combine(tempPath, (zip ? StringUtils.CleanIdentifier(siteCollectionUrl) + ".bsh" : StringUtils.CleanIdentifier(filename)));
// Backup requested site.
rootWebApplication.Sites.Backup(siteCollectionUrl, backupFileName, true);
if (zip)
{
string zipFile = Path.Combine(tempPath, filename);
string zipRoot = Path.GetDirectoryName(backupFileName);
FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(backupFileName) });
FileUtils.DeleteFile(backupFileName);
backupFileName = zipFile;
}
return backupFileName;
}
finally
{
wic.Undo();
}
}
catch(Exception ex)
{
throw new InvalidOperationException("Failed to backup site collection.", ex);
}
}
/// <summary>
/// Restores site collection under given url from backup.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Backup file name to restore from.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void RestoreSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection, string filename)
{
string url = siteCollection.Url;
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
string tempPath = Path.GetTempPath();
// Unzip uploaded files if required.
string expandedFile = filename;
if (Path.GetExtension(filename).ToLower() == ".zip")
{
// Unpack file.
expandedFile = FileUtils.UnzipFiles(filename, tempPath)[0];
// Delete zip archive.
FileUtils.DeleteFile(filename);
}
// Delete existent site and restore new one.
rootWebApplication.Sites.Delete(siteCollectionUrl, false);
rootWebApplication.Sites.Restore(siteCollectionUrl, expandedFile, true, true);
SPSite restoredSite = rootWebApplication.Sites[siteCollectionUrl];
SPWeb web = restoredSite.OpenWeb();
SPUser owner = null;
try
{
owner = web.SiteUsers[siteCollection.OwnerLogin];
}
catch
{
// Ignore this error.
}
if (owner == null)
{
web.SiteUsers.Add(siteCollection.OwnerLogin, siteCollection.OwnerEmail, siteCollection.OwnerName, String.Empty);
owner = web.SiteUsers[siteCollection.OwnerLogin];
}
restoredSite.Owner = owner;
web.Close();
rootWebApplication.Update();
// Delete expanded file.
FileUtils.DeleteFile(expandedFile);
}
finally
{
wic.Undo();
}
}
catch(Exception ex)
{
throw new InvalidOperationException("Failed to restore site collection.", ex);
}
}
/// <summary>
/// Fills custom site collection with information from administration object.
/// </summary>
/// <param name="customSiteCollection">Custom site collection to fill.</param>
/// <param name="site">Administration object.</param>
private static void FillSiteCollection (SharePointSiteCollection customSiteCollection, SPSite site)
{
Uri siteUri = new Uri(site.Url);
string url = (siteUri.Port > 0) ? site.Url.Replace(String.Format(":{0}", siteUri.Port), String.Empty) : site.Url;
customSiteCollection.Url = url;
customSiteCollection.OwnerLogin = site.Owner.LoginName;
customSiteCollection.OwnerName = site.Owner.Name;
customSiteCollection.OwnerEmail = site.Owner.Email;
customSiteCollection.LocaleId = site.RootWeb.Locale.LCID;
customSiteCollection.Title = site.RootWeb.Title;
customSiteCollection.Description = site.RootWeb.Description;
customSiteCollection.Bandwidth = site.Usage.Bandwidth;
customSiteCollection.Diskspace = site.Usage.Storage;
customSiteCollection.MaxSiteStorage = site.Quota.StorageMaximumLevel;
customSiteCollection.WarningStorage = site.Quota.StorageWarningLevel;
}
}
}

View file

@ -0,0 +1,126 @@
// 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 WebsitePanel.Providers.Common;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
public class HostedSolutionLog
{
internal static string LogPrefix = "HostedSolution";
internal static void LogStart(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteStart("{0} {1}", LogPrefix, text);
}
internal static void LogEnd(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteEnd("{0} {1}", LogPrefix, text);
}
internal static void LogInfo(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteInfo("{0} {1}", LogPrefix, text);
}
internal static void LogWarning(string message, params object[] args)
{
string text = String.Format(message, args);
Log.WriteWarning("{0} {1}", LogPrefix, text);
}
internal static void LogError(Exception ex)
{
Log.WriteError(LogPrefix, ex);
}
internal static void LogError(string message, Exception ex)
{
string text = String.Format("{0} {1}", LogPrefix, message);
Log.WriteError(text, ex);
}
internal static void DebugInfo(string message, params object[] args)
{
#if DEBUG
string text = String.Format(message, args);
Log.WriteInfo("{0} {1}", LogPrefix, text);
#endif
}
internal static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
{
if (res != null)
{
res.IsSuccess = false;
if (!string.IsNullOrEmpty(errorCode))
res.ErrorCodes.Add(errorCode);
}
if (ex != null)
LogError(ex);
//LogRecord.
LogEnd(message);
}
internal static void EndLog(string message, ResultObject res, string errorCode)
{
EndLog(message, res, errorCode, null);
}
internal static void EndLog(string message, ResultObject res)
{
EndLog(message, res, null);
}
internal static void EndLog(string message)
{
EndLog(message, null);
}
internal static T StartLog<T>(string message) where T : ResultObject, new()
{
LogStart(message);
T res = new T();
res.IsSuccess = true;
return res;
}
}
}

View file

@ -0,0 +1,359 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Management;
using WebsitePanel.Providers.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
public class OCS2007R2 : HostingServiceProviderBase, IOCSServer
{
#region Properties
/// <summary>
/// Pool FQDN
/// </summary>
private string PoolFQDN
{
get { return ProviderSettings[OCSConstants.PoolFQDN]; }
}
private WmiHelper wmi = null;
/// <summary>
/// Wmi helper instance
/// </summary>
private WmiHelper Wmi
{
get
{
if (wmi == null)
wmi = new WmiHelper("root\\cimv2");
return wmi;
}
}
#endregion
#region IOCSServer implementation
public string CreateUser(string userUpn, string userDistinguishedName)
{
return CreateUserInternal(userUpn, userDistinguishedName);
}
public OCSUser GetUserGeneralSettings(string instanceId)
{
return GetUserGeneralSettingsInternal(instanceId);
}
public void SetUserGeneralSettings(string instanceId, bool enabledForFederation, bool enabledForPublicIMConectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence)
{
SetUserGeneralSettingsInternal(instanceId, enabledForFederation, enabledForPublicIMConectivity, archiveInternalCommunications, archiveFederatedCommunications, enabledForEnhancedPresence);
}
public void DeleteUser(string instanceId)
{
DeleteUserInternal(instanceId);
}
public void SetUserPrimaryUri(string instanceId, string userUpn)
{
SetUserPrimaryUriInternal(instanceId, userUpn);
}
#endregion
#region Users
private void DeleteUserInternal(string instanceId)
{
HostedSolutionLog.LogStart("DeleteUserInternal");
try
{
if (string.IsNullOrEmpty(instanceId))
throw new ArgumentException("instanceId");
using (ManagementObject userObject = GetUserByInstanceId(instanceId))
{
if (userObject == null)
{
HostedSolutionLog.LogWarning("OCS user {0} not found", instanceId);
}
else
{
userObject.Delete();
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("DeleteUserInternal", ex);
throw;
}
HostedSolutionLog.LogEnd("DeleteUserInternal");
}
private void SetUserGeneralSettingsInternal(string instanceId, bool enabledForFederation, bool enabledForPublicIMConectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence)
{
HostedSolutionLog.LogStart("SetUserGeneralSettingsInternal");
try
{
if (string.IsNullOrEmpty(instanceId))
throw new ArgumentException("instanceId");
using (ManagementObject userObject = GetUserByInstanceId(instanceId))
{
if (userObject == null)
{
throw new Exception(string.Format("OCS user {0} not found", instanceId));
}
userObject["EnabledForFederation"] = enabledForFederation;
userObject["PublicNetworkEnabled"] = enabledForPublicIMConectivity;
userObject["ArchiveInternalCommunications"] = archiveInternalCommunications;
userObject["ArchiveFederatedCommunications"] = archiveFederatedCommunications;
if (enabledForEnhancedPresence)
userObject["EnabledForEnhancedPresence"] = true;
userObject.Put();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("SetUserGeneralSettingsInternal", ex);
throw;
}
HostedSolutionLog.LogEnd("SetUserGeneralSettingsInternal");
}
private void SetUserPrimaryUriInternal(string instanceId, string userUpn)
{
HostedSolutionLog.LogStart("SetUserPrimaryUriInternal");
try
{
if (string.IsNullOrEmpty(instanceId))
throw new ArgumentException("instanceId");
if (string.IsNullOrEmpty(userUpn))
throw new ArgumentException("userUpn");
using (ManagementObject userObject = GetUserByInstanceId(instanceId))
{
if (userObject == null)
{
throw new Exception(string.Format("OCS user {0} not found", instanceId));
}
string primaryUri = "sip:" + userUpn;
userObject["PrimaryURI"] = primaryUri;
userObject.Put();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("SetUserPrimaryUriInternal", ex);
throw;
}
HostedSolutionLog.LogEnd("SetUserPrimaryUriInternal");
}
private OCSUser GetUserGeneralSettingsInternal(string instanceId)
{
HostedSolutionLog.LogStart("GetUserGeneralSettingsInternal");
try
{
if (string.IsNullOrEmpty(instanceId))
throw new ArgumentException("instanceId");
using (ManagementObject userObject = GetUserByInstanceId(instanceId))
{
if (userObject == null)
{
throw new Exception(string.Format("OCS user {0} not found", instanceId));
}
OCSUser user = new OCSUser();
user.InstanceId = instanceId;
user.PrimaryUri = (string)userObject["PrimaryURI"];
user.DisplayName = (string)userObject["DisplayName"];
user.EnabledForFederation = (bool)userObject["EnabledForFederation"];
user.EnabledForPublicIMConectivity = (bool)userObject["PublicNetworkEnabled"];
user.ArchiveInternalCommunications = (bool)userObject["ArchiveInternalCommunications"];
user.ArchiveFederatedCommunications = (bool)userObject["ArchiveFederatedCommunications"];
user.EnabledForEnhancedPresence = (bool)userObject["EnabledForEnhancedPresence"];
HostedSolutionLog.LogEnd("GetUserGeneralSettingsInternal");
return user;
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("GetUserGeneralSettingsInternal", ex);
throw;
}
}
private string CreateUserInternal(string userUpn, string userDistinguishedName)
{
HostedSolutionLog.LogStart("CreateUserInternal");
HostedSolutionLog.DebugInfo("UPN: {0}", userUpn);
HostedSolutionLog.DebugInfo("User Distinguished Name: {0}", userDistinguishedName);
try
{
if (string.IsNullOrEmpty(userUpn))
throw new ArgumentException("userUpn");
if (string.IsNullOrEmpty(userDistinguishedName))
throw new ArgumentException("userDistinguishedName");
if ( string.IsNullOrEmpty(PoolFQDN))
throw new Exception("Pool FQDN is not specified");
string poolDN = GetPoolDistinguishedName(PoolFQDN);
if ( string.IsNullOrEmpty(poolDN))
throw new Exception(string.Format("Pool {0} not found", PoolFQDN));
if ( !string.IsNullOrEmpty(FindUserByDistinguishedName(userDistinguishedName)))
throw new Exception(string.Format("User with distinguished name '{0}' already exists", userDistinguishedName));
string primaryUri = "sip:" + userUpn;
if (!string.IsNullOrEmpty(FindUserByPrimaryUri(primaryUri)))
throw new Exception(string.Format("User with primary URI '{0}' already exists", primaryUri));
using (ManagementObject newUser = Wmi.CreateInstance("MSFT_SIPESUserSetting"))
{
newUser["PrimaryURI"] = primaryUri;
newUser["UserDN"] = userDistinguishedName;
newUser["HomeServerDN"] = poolDN;
newUser["Enabled"] = true;
newUser["EnabledForInternetAccess"] = true;
newUser.Put();
}
string instanceId = null;
int attempts = 0;
while (true)
{
instanceId = FindUserByPrimaryUri(primaryUri);
if (!string.IsNullOrEmpty(instanceId))
break;
if (attempts > 9)
throw new Exception(
string.Format("Could not find OCS user '{0}'", primaryUri));
attempts++;
ExchangeLog.LogWarning("Attempt #{0} to create OCS user failed!", attempts);
// wait 30 sec
System.Threading.Thread.Sleep(1000);
}
HostedSolutionLog.LogEnd("CreateUserInternal");
return instanceId;
}
catch (Exception ex)
{
HostedSolutionLog.LogError("CreateUserInternal", ex);
throw;
}
}
private string GetPoolDistinguishedName(string poolFQDN)
{
HostedSolutionLog.LogStart("GetPoolDistinguishedName");
string ret = null;
using (ManagementObject objPool = Wmi.GetWmiObject("MSFT_SIPPoolSetting", "PoolFQDN = '{0}'", poolFQDN))
{
if (objPool != null)
{
ret = (string)objPool["PoolDN"];
}
}
HostedSolutionLog.LogEnd("GetPoolDistinguishedName");
return ret;
}
private string FindUserByDistinguishedName(string userDistinguishedName)
{
string ret = null;
HostedSolutionLog.LogStart("FindUserByDistinguishedName");
using (ManagementObject objUser = Wmi.GetWmiObject("MSFT_SIPESUserSetting", "UserDN = '{0}'", userDistinguishedName))
{
if (objUser != null)
ret = (string)objUser["InstanceID"];
}
HostedSolutionLog.LogEnd("FindUserByDistinguishedName");
return ret;
}
private string FindUserByPrimaryUri(string uri)
{
string ret = null;
HostedSolutionLog.LogStart("FindUserByPrimaryUri");
using (ManagementObject objUser = Wmi.GetWmiObject("MSFT_SIPESUserSetting", "PrimaryURI = '{0}'", uri))
{
if (objUser != null)
ret = (string)objUser["InstanceID"];
}
HostedSolutionLog.LogEnd("FindUserByPrimaryUri");
return ret;
}
private ManagementObject GetUserByInstanceId(string instanceId)
{
HostedSolutionLog.LogStart("GetUserByInstanceId");
ManagementObject objUser = Wmi.GetWmiObject("MSFT_SIPESUserSetting", "InstanceID = '{0}'", instanceId);
HostedSolutionLog.LogEnd("GetUserByInstanceId");
return objUser;
}
#endregion
public override bool IsInstalled()
{
try
{
Wmi.GetWmiObjects("MSFT_SIPESUserSetting", null);
return true;
}
catch
{
return false;
}
}
}
}

View file

@ -0,0 +1,151 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Management;
using WebsitePanel.Providers.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
public class OCSEdge2007R2 : HostingServiceProviderBase, IOCSEdgeServer
{
#region Properties
private WmiHelper wmi = null;
/// <summary>
/// Wmi helper instance
/// </summary>
private WmiHelper Wmi
{
get
{
if (wmi == null)
wmi = new WmiHelper("root\\cimv2");
return wmi;
}
}
#endregion
#region IOCSEdgeServer implementation
public void AddDomain(string domainName)
{
AddDomainInternal(domainName);
}
public void DeleteDomain(string domainName)
{
DeleteDomainInternal(domainName);
}
#endregion
#region Domains
private ManagementObject GetDomain(string domainName)
{
HostedSolutionLog.LogStart("GetDomain");
ManagementObject objDomain = Wmi.GetWmiObject("MSFT_SIPFederationInternalDomainData", "SupportedInternalDomain='{0}'", domainName);
HostedSolutionLog.LogEnd("GetDomain");
return objDomain;
}
private void AddDomainInternal(string domainName)
{
HostedSolutionLog.LogStart("AddDomainInternal");
HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName);
try
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentException("domainName");
if ( GetDomain(domainName) != null )
{
HostedSolutionLog.LogWarning("OCS internal domain '{0}' already exists", domainName);
}
else
{
using (ManagementObject newDomain = Wmi.CreateInstance("MSFT_SIPFederationInternalDomainData"))
{
newDomain["SupportedInternalDomain"] = domainName;
newDomain.Put();
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("AddDomainInternal", ex);
throw;
}
HostedSolutionLog.LogEnd("AddDomainInternal");
}
private void DeleteDomainInternal(string domainName)
{
HostedSolutionLog.LogStart("DeleteDomainInternal");
HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName);
try
{
if (string.IsNullOrEmpty(domainName))
throw new ArgumentException("domainName");
using (ManagementObject domainObj = GetDomain(domainName))
{
if (domainObj == null)
HostedSolutionLog.LogWarning("OCS internal domain '{0}' not found", domainName);
else
domainObj.Delete();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("DeleteDomainInternal", ex);
throw;
}
HostedSolutionLog.LogEnd("DeleteDomainInternal");
}
#endregion
public override bool IsInstalled()
{
try
{
Wmi.GetWmiObjects("MSFT_SIPFederationInternalDomainData", null);
return true;
}
catch
{
return false;
}
}
}
}

View file

@ -0,0 +1,682 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.DirectoryServices;
using System.Globalization;
using System.Text;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.Providers.HostedSolution
{
public class OrganizationProvider : HostingServiceProviderBase, IOrganization
{
#region Properties
private string RootOU
{
get { return ProviderSettings["RootOU"]; }
}
private string RootDomain
{
get { return ServerSettings.ADRootDomain; }
}
private string PrimaryDomainController
{
get { return ProviderSettings["PrimaryDomainController"]; }
}
#endregion
#region Helpers
private string GetOrganizationPath(string organizationId)
{
StringBuilder sb = new StringBuilder();
// append provider
AppendProtocol(sb);
AppendDomainController(sb);
AppendOUPath(sb, organizationId);
AppendOUPath(sb, RootOU);
AppendDomainPath(sb, RootDomain);
return sb.ToString();
}
private string GetUserPath(string organizationId, string loginName)
{
StringBuilder sb = new StringBuilder();
// append provider
AppendProtocol(sb);
AppendDomainController(sb);
AppendCNPath(sb, loginName);
AppendOUPath(sb, organizationId);
AppendOUPath(sb, RootOU);
AppendDomainPath(sb, RootDomain);
return sb.ToString();
}
private string GetGroupPath(string organizationId)
{
StringBuilder sb = new StringBuilder();
// append provider
AppendProtocol(sb);
AppendDomainController(sb);
AppendCNPath(sb, organizationId);
AppendOUPath(sb, organizationId);
AppendOUPath(sb, RootOU);
AppendDomainPath(sb, RootDomain);
return sb.ToString();
}
private string GetRootOU()
{
StringBuilder sb = new StringBuilder();
// append provider
AppendProtocol(sb);
AppendDomainController(sb);
AppendOUPath(sb, RootOU);
AppendDomainPath(sb, RootDomain);
return sb.ToString();
}
private void AppendDomainController(StringBuilder sb)
{
sb.Append(PrimaryDomainController + "/");
}
private static void AppendCNPath(StringBuilder sb, string organizationId)
{
if (string.IsNullOrEmpty(organizationId))
return;
sb.Append("CN=").Append(organizationId).Append(",");
}
private static void AppendProtocol(StringBuilder sb)
{
sb.Append("LDAP://");
}
private static void AppendOUPath(StringBuilder sb, string ou)
{
if (string.IsNullOrEmpty(ou))
return;
string path = ou.Replace("/", "\\");
string[] parts = path.Split('\\');
for (int i = parts.Length - 1; i != -1; i--)
sb.Append("OU=").Append(parts[i]).Append(",");
}
private static void AppendDomainPath(StringBuilder sb, string domain)
{
if (string.IsNullOrEmpty(domain))
return;
string[] parts = domain.Split('.');
for (int i = 0; i < parts.Length; i++)
{
sb.Append("DC=").Append(parts[i]);
if (i < (parts.Length - 1))
sb.Append(",");
}
}
#endregion
#region Organizations
public bool OrganizationExists(string organizationId)
{
return OrganizationExistsInternal(organizationId);
}
internal bool OrganizationExistsInternal(string organizationId)
{
if (string.IsNullOrEmpty(organizationId))
throw new ArgumentNullException("organizationId");
string orgPath = GetOrganizationPath(organizationId);
return ActiveDirectoryUtils.AdObjectExists(orgPath);
}
public Organization CreateOrganization(string organizationId)
{
return CreateOrganizationInternal(organizationId);
}
internal Organization CreateOrganizationInternal(string organizationId)
{
HostedSolutionLog.LogStart("CreateOrganizationInternal");
HostedSolutionLog.DebugInfo("OrganizationId : {0}", organizationId);
if (string.IsNullOrEmpty(organizationId))
throw new ArgumentNullException("organizationId");
bool ouCreated = false;
bool groupCreated = false;
Organization org;
try
{
string parentPath = GetRootOU();
string orgPath = GetOrganizationPath(organizationId);
//Create OU
ActiveDirectoryUtils.CreateOrganizationalUnit(organizationId, parentPath);
ouCreated = true;
//Create security group
ActiveDirectoryUtils.CreateGroup(orgPath, organizationId);
groupCreated = true;
org = new Organization();
org.OrganizationId = organizationId;
org.DistinguishedName = ActiveDirectoryUtils.RemoveADPrefix(orgPath);
org.SecurityGroup = ActiveDirectoryUtils.RemoveADPrefix(GetGroupPath(organizationId));
}
catch(Exception ex)
{
HostedSolutionLog.LogError(ex);
try
{
if (groupCreated)
{
string groupPath = GetGroupPath(organizationId);
ActiveDirectoryUtils.DeleteADObject(groupPath);
}
}
catch(Exception e)
{
HostedSolutionLog.LogError(e);
}
try
{
if (ouCreated)
{
string orgPath = GetOrganizationPath(organizationId);
ActiveDirectoryUtils.DeleteADObject(orgPath);
}
}
catch(Exception e)
{
HostedSolutionLog.LogError(e);
}
throw;
}
HostedSolutionLog.LogEnd("CreateOrganizationInternal");
return org;
}
public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
{
foreach (ServiceProviderItem item in items)
{
try
{
if (item is Organization)
{
Organization org = item as Organization;
ChangeOrganizationState(org, enabled);
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(
String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
private void ChangeOrganizationState(Organization org, bool enabled)
{
string path = GetOrganizationPath(org.OrganizationId);
DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path);
string filter =
string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(!{0}=disabled))",
ADAttributes.CustomAttribute2);
using (DirectorySearcher searcher = new DirectorySearcher(entry, filter))
{
SearchResultCollection resCollection = searcher.FindAll();
foreach (SearchResult res in resCollection)
{
DirectoryEntry de = res.GetDirectoryEntry();
de.InvokeSet("AccountDisabled", !enabled);
de.CommitChanges();
}
}
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
try
{
if (item is Organization)
{
Organization org = item as Organization;
DeleteOrganizationInternal(org.OrganizationId);
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
public void DeleteOrganization(string organizationId)
{
DeleteOrganizationInternal(organizationId);
}
internal void DeleteOrganizationInternal(string organizationId)
{
HostedSolutionLog.LogStart("DeleteOrganizationInternal");
HostedSolutionLog.DebugInfo("OrganizationId : {0}", organizationId);
if (string.IsNullOrEmpty(organizationId))
throw new ArgumentNullException("organizationId");
string groupPath = GetGroupPath(organizationId);
ActiveDirectoryUtils.DeleteADObject(groupPath);
string path = GetOrganizationPath(organizationId);
ActiveDirectoryUtils.DeleteADObject(path, true);
HostedSolutionLog.LogEnd("DeleteOrganizationInternal");
}
#endregion
#region Users
public void CreateUser(string organizationId, string loginName, string displayName, string upn, string password, bool enabled)
{
CreateUserInternal(organizationId, loginName, displayName, upn, password, enabled);
}
internal int CreateUserInternal(string organizationId, string loginName, string displayName, string upn, string password, bool enabled)
{
HostedSolutionLog.LogStart("CreateUserInternal");
HostedSolutionLog.DebugInfo("organizationId : {0}", organizationId);
HostedSolutionLog.DebugInfo("loginName : {0}", loginName);
HostedSolutionLog.DebugInfo("displayName : {0}", displayName);
if (string.IsNullOrEmpty(organizationId))
throw new ArgumentNullException("organizationId");
if (string.IsNullOrEmpty(loginName))
throw new ArgumentNullException("loginName");
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException("password");
bool userCreated = false;
string userPath = null;
try
{
string path = GetOrganizationPath(organizationId);
userPath= GetUserPath(organizationId, loginName);
if (!ActiveDirectoryUtils.AdObjectExists(userPath))
{
userPath = ActiveDirectoryUtils.CreateUser(path, loginName, displayName, password, enabled);
DirectoryEntry entry = new DirectoryEntry(userPath);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.UserPrincipalName, upn);
entry.CommitChanges();
userCreated = true;
}
else
return Errors.AD_OBJECT_ALREADY_EXISTS;
string groupPath = GetGroupPath(organizationId);
ActiveDirectoryUtils.AddUserToGroup(userPath, groupPath);
}
catch(Exception e)
{
HostedSolutionLog.LogError(e);
try
{
if (userCreated)
ActiveDirectoryUtils.DeleteADObject(userPath);
}
catch(Exception ex)
{
HostedSolutionLog.LogError(ex);
}
}
HostedSolutionLog.LogEnd("CreateUserInternal");
return Errors.OK;
}
public PasswordPolicyResult GetPasswordPolicy()
{
return GetPasswordPolicyInternal();
}
internal PasswordPolicyResult GetPasswordPolicyInternal()
{
HostedSolutionLog.LogStart("GetPasswordPolicyInternal");
PasswordPolicyResult res = new PasswordPolicyResult {IsSuccess = true};
string[] policyAttributes = new[] {"minPwdLength",
"pwdProperties",
"objectClass"};
try
{
DirectoryEntry domainRoot = new DirectoryEntry(ActiveDirectoryUtils.ConvertDomainName(RootDomain));
DirectorySearcher ds = new DirectorySearcher(
domainRoot,
"(objectClass=domainDNS)",
policyAttributes,
SearchScope.Base
);
SearchResult result = ds.FindOne();
PasswordPolicy ret = new PasswordPolicy
{
MinLength = ((int) result.Properties["minPwdLength"][0]),
IsComplexityEnable = ((int) result.Properties["pwdProperties"][0] == 1)
};
res.Value = ret;
}
catch(Exception ex)
{
HostedSolutionLog.LogError(ex);
res.IsSuccess = false;
res.ErrorCodes.Add(ErrorCodes.CANNOT_GET_PASSWORD_COMPLEXITY);
}
HostedSolutionLog.LogEnd("GetPasswordPolicyInternal");
return res;
}
public void DeleteUser(string loginName, string organizationId)
{
DeleteUserInternal(loginName, organizationId);
}
internal void DeleteUserInternal(string loginName, string organizationId)
{
HostedSolutionLog.LogStart("DeleteUserInternal");
HostedSolutionLog.DebugInfo("loginName : {0}", loginName);
HostedSolutionLog.DebugInfo("organizationId : {0}", organizationId);
if (string.IsNullOrEmpty(loginName))
throw new ArgumentNullException("loginName");
if (string.IsNullOrEmpty(organizationId))
throw new ArgumentNullException("organizationId");
string path = GetUserPath(organizationId, loginName);
if (ActiveDirectoryUtils.AdObjectExists(path))
ActiveDirectoryUtils.DeleteADObject(path);
HostedSolutionLog.LogEnd("DeleteUserInternal");
}
public OrganizationUser GetUserGeneralSettings(string loginName, string organizationId)
{
return GetUserGeneralSettingsInternal(loginName, organizationId);
}
internal OrganizationUser GetUserGeneralSettingsInternal(string loginName, string organizationId)
{
HostedSolutionLog.LogStart("GetUserGeneralSettingsInternal");
HostedSolutionLog.DebugInfo("loginName : {0}", loginName);
HostedSolutionLog.DebugInfo("organizationId : {0}", organizationId);
if (string.IsNullOrEmpty(loginName))
throw new ArgumentNullException("loginName");
string path = GetUserPath(organizationId, loginName);
DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path);
OrganizationUser retUser = new OrganizationUser();
retUser.FirstName = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.FirstName);
retUser.LastName = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.LastName);
retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.DisplayName);
retUser.Initials = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Initials);
retUser.JobTitle = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.JobTitle);
retUser.Company = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Company);
retUser.Department = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Department);
retUser.Office = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Office);
retUser.BusinessPhone = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.BusinessPhone);
retUser.Fax = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Fax);
retUser.HomePhone = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.HomePhone);
retUser.MobilePhone = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.MobilePhone);
retUser.Pager = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Pager);
retUser.WebPage = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.WebPage);
retUser.Address = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Address);
retUser.City = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.City);
retUser.State = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.State);
retUser.Zip = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Zip);
retUser.Country = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Country);
retUser.Notes = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Notes);
retUser.ExternalEmail = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.ExternalEmail);
retUser.Disabled = (bool)entry.InvokeGet(ADAttributes.AccountDisabled);
retUser.Manager = GetManager(entry);
retUser.DomainUserName = GetDomainName(loginName);
retUser.DistinguishedName = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.DistinguishedName);
retUser.Locked = (bool)entry.InvokeGet(ADAttributes.AccountLocked);
HostedSolutionLog.LogEnd("GetUserGeneralSettingsInternal");
return retUser;
}
private string GetDomainName(string username)
{
string domain = ActiveDirectoryUtils.GetNETBIOSDomainName(RootDomain);
string ret = string.Format(@"{0}\{1}", domain, username);
return ret;
}
private OrganizationUser GetManager(DirectoryEntry entry)
{
OrganizationUser retUser = null;
string path = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Manager);
if (!string.IsNullOrEmpty(path))
{
path = ActiveDirectoryUtils.AddADPrefix(path, PrimaryDomainController);
if (ActiveDirectoryUtils.AdObjectExists(path))
{
DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
retUser = new OrganizationUser();
retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.DisplayName);
retUser.AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.Name);
}
}
return retUser;
}
public void SetUserGeneralSettings(string organizationId, string accountName, string displayName, string password,
bool hideFromAddressBook, bool disabled, bool locked, string firstName, string initials, string lastName,
string address, string city, string state, string zip, string country, string jobTitle,
string company, string department, string office, string managerAccountName,
string businessPhone, string fax, string homePhone, string mobilePhone, string pager,
string webPage, string notes, string externalEmail)
{
SetUserGeneralSettingsInternal(organizationId, accountName, displayName, password, hideFromAddressBook,
disabled, locked, firstName, initials, lastName, address, city, state, zip, country, jobTitle,
company, department, office, managerAccountName, businessPhone, fax, homePhone,
mobilePhone, pager, webPage, notes, externalEmail);
}
internal void SetUserGeneralSettingsInternal(string organizationId, string accountName, string displayName, string password,
bool hideFromAddressBook, bool disabled, bool locked, string firstName, string initials, string lastName,
string address, string city, string state, string zip, string country, string jobTitle,
string company, string department, string office, string managerAccountName,
string businessPhone, string fax, string homePhone, string mobilePhone, string pager,
string webPage, string notes, string externalEmail)
{
string path = GetUserPath(organizationId, accountName);
DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.FirstName, firstName);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.LastName, lastName);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.DisplayName, displayName);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Initials, initials);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.JobTitle, jobTitle);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Company, company);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Department, department);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Office, office);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.BusinessPhone, businessPhone);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Fax, fax);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.HomePhone, homePhone);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.MobilePhone, mobilePhone);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Pager, pager);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.WebPage, webPage);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Address, address);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.City, city);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.State, state);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Zip, zip);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Country, country);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Notes, notes);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.ExternalEmail, externalEmail);
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.CustomAttribute2, (disabled ? "disabled" : null));
string manager = string.Empty;
if (!string.IsNullOrEmpty(managerAccountName))
{
string managerPath = GetUserPath(organizationId, managerAccountName);
manager = ActiveDirectoryUtils.AdObjectExists(managerPath) ? managerPath : string.Empty;
}
ActiveDirectoryUtils.SetADObjectProperty(entry, ADAttributes.Manager, ActiveDirectoryUtils.RemoveADPrefix(manager));
entry.InvokeSet(ADAttributes.AccountDisabled, disabled);
if (!string.IsNullOrEmpty(password))
entry.Invoke(ADAttributes.SetPassword, password);
if (!locked)
{
bool isLoked = (bool)entry.InvokeGet(ADAttributes.AccountLocked);
if (isLoked)
entry.InvokeSet(ADAttributes.AccountLocked, locked);
}
entry.CommitChanges();
}
#endregion
#region Domains
public void CreateOrganizationDomain(string organizationDistinguishedName, string domain)
{
CreateOrganizationDomainInternal(organizationDistinguishedName, domain);
}
/// <summary>
/// Creates organization domain
/// </summary>
/// <param name="organizationDistinguishedName"></param>
/// <param name="domain"></param>
private void CreateOrganizationDomainInternal(string organizationDistinguishedName, string domain)
{
HostedSolutionLog.LogStart("CreateOrganizationDomainInternal");
string path = ActiveDirectoryUtils.AddADPrefix(organizationDistinguishedName, PrimaryDomainController);
ActiveDirectoryUtils.AddUPNSuffix(path, domain);
HostedSolutionLog.LogEnd("CreateOrganizationDomainInternal");
}
public void DeleteOrganizationDomain(string organizationDistinguishedName, string domain)
{
DeleteOrganizationDomainInternal(organizationDistinguishedName, domain);
}
/// <summary>
/// Deletes organization domain
/// </summary>
/// <param name="organizationDistinguishedName"></param>
/// <param name="domain"></param>
private void DeleteOrganizationDomainInternal(string organizationDistinguishedName, string domain)
{
HostedSolutionLog.LogStart("DeleteOrganizationDomainInternal");
//Remove UPN Suffix
string path = ActiveDirectoryUtils.AddADPrefix(organizationDistinguishedName, PrimaryDomainController);
ActiveDirectoryUtils.RemoveUPNSuffix(path, domain);
HostedSolutionLog.LogEnd("DeleteOrganizationDomainInternal");
}
#endregion
public override bool IsInstalled()
{
return Environment.UserDomainName != Environment.MachineName;
}
}
}

View file

@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebsitePanel.Providers.HostedSolution")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("WebsitePanel.Providers.HostedSolution")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c904143a-c4c1-4f4c-a9de-666f35c9ca03")]

View file

@ -0,0 +1,186 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A06DE5E4-4331-47E1-8F46-7B846146B559}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WebsitePanel.Providers.HostedSolution</RootNamespace>
<AssemblyName>WebsitePanel.Providers.HostedSolution</AssemblyName>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\WebsitePanel.Server\bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<WarningsAsErrors>618</WarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\WebsitePanel.Server\bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<WarningsAsErrors>618</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Crm">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Crm.Admin.AdminService">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.Admin.AdminService.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Crm.Setup.Common">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.Setup.Common.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Crm.Setup.DatabaseInstaller">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.Setup.DatabaseInstaller.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Crm.Setup.Server.Utility">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.Setup.Server.Utility.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Crm.Tools.Admin.DMSnapinLib">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Crm.Tools.Admin.DMSnapinLib.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Exchange.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Common.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Data, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Data.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Data.Directory, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Data.Directory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Data.Storage, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Data.Storage.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Diagnostics, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Diagnostics.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Extensibility.Internal, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Extensibility.Internal.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Exchange.Net, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\v14\Microsoft.Exchange.Net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.SharePoint">
<HintPath>..\..\Lib\References\Microsoft\Microsoft.SharePoint.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Data" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.Management" />
<Reference Include="System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\System.Management.Automation.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\VersionInfo.cs">
<Link>VersionInfo.cs</Link>
</Compile>
<Compile Include="BlackBerry5Provider.cs" />
<Compile Include="BlackBerryProvider.cs" />
<Compile Include="Exchange2010.cs" />
<Compile Include="HostedSharePointServer2010.cs" />
<Compile Include="OCSEdge2007R2.cs" />
<Compile Include="OCS2007R2.cs" />
<Compile Include="CRMProvider.cs" />
<Compile Include="CRMProxy.cs" />
<Compile Include="Exchange2007.cs" />
<Compile Include="ExchangeLog.cs" />
<Compile Include="ExchangeTransaction.cs" />
<Compile Include="HostedSharePointServer.cs" />
<Compile Include="HostedSharePointServerImpl.cs" />
<Compile Include="HostedSolutionLog.cs" />
<Compile Include="OrganizationProvider.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WebsitePanel.Providers.Base\WebsitePanel.Providers.Base.csproj">
<Project>{684C932A-6C75-46AC-A327-F3689D89EB42}</Project>
<Name>WebsitePanel.Providers.Base</Name>
</ProjectReference>
<ProjectReference Include="..\WebsitePanel.Server.Utils\WebsitePanel.Server.Utils.csproj">
<Project>{E91E52F3-9555-4D00-B577-2B1DBDD87CA7}</Project>
<Name>WebsitePanel.Server.Utils</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<WebReferences Include="Web References\" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>