Updated Hosted Sharepoing Provider (Foundation 2010):

A) Powershell support added within the provider
B) Now returns the actual deployed language packs
C) The PeoplePicker points to the organization OU and shows only the users from
the tentant organization. A requirement when used with Exchange 2010 SP2
Addressbook Policies
D) Shared SSL root added to use wild card certificates as part of hosting plan.
When enabled the host name is generated.
E) Search fix: Provisioning of localhost file where the server component is
active. This system expected to be the search server. Within the local hostfile
the sites are listed with their local ip address so the search server can resolve
the site and crawl through their data.

This component needs to be compiled with .NET 2.0 together with Provers.Base,
OS.Windows2003, OS.Windows2008, Server.Utils, and Server components.

Out standing is to update the build and deployment package for a dedicated
 deployment packaged so this component is using .NET 2.0, all other should be
 using .NET 4.0. This will eliminate the configuration circus that was required
 to get the .NET 4.0 version of this component working previously.
This commit is contained in:
robvde 2012-07-01 08:24:49 +04:00
parent 38592df9e6
commit a0d9e59db2
25 changed files with 3174 additions and 2256 deletions

View file

@ -0,0 +1 @@
INSERT INTO Quotas (QuotaID, GroupID, QuotaOrder, QuotaName,QuotaDescription, QuotaTypeID, ServiceQuota) VALUES (400, 20, 3, 'HostedSharePoint.UseSharedSSL' ,'Use shared SSL Root', 1, 0)

View file

@ -136,7 +136,8 @@ order by rg.groupOrder
public const string SHAREPOINT_SITES = "SharePoint.Sites"; // SharePoint Sites public const string SHAREPOINT_SITES = "SharePoint.Sites"; // SharePoint Sites
public const string HOSTED_SHAREPOINT_SITES = "HostedSharePoint.Sites"; // Hosted SharePoint Sites public const string HOSTED_SHAREPOINT_SITES = "HostedSharePoint.Sites"; // Hosted SharePoint Sites
public const string HOSTED_SHAREPOINT_STORAGE_SIZE = "HostedSharePoint.MaxStorage"; // Hosted SharePoint storage size; public const string HOSTED_SHAREPOINT_STORAGE_SIZE = "HostedSharePoint.MaxStorage"; // Hosted SharePoint storage size;
public const string DNS_EDITOR = "DNS.Editor"; // DNS Editor public const string HOSTED_SHAREPOINT_USESHAREDSSL = "HostedSharePoint.UseSharedSSL"; // Hosted SharePoint Use Shared SSL Root
public const string DNS_EDITOR = "DNS.Editor"; // DNS Editor
public const string DNS_ZONES = "DNS.Zones"; // DNS Editor public const string DNS_ZONES = "DNS.Zones"; // DNS Editor
public const string DNS_PRIMARY_ZONES = "DNS.PrimaryZones"; // DNS Editor public const string DNS_PRIMARY_ZONES = "DNS.PrimaryZones"; // DNS Editor
public const string DNS_SECONDARY_ZONES = "DNS.SecondaryZones"; // DNS Editor public const string DNS_SECONDARY_ZONES = "DNS.SecondaryZones"; // DNS Editor

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -30,15 +30,15 @@ using System;
namespace WebsitePanel.Providers.HostedSolution namespace WebsitePanel.Providers.HostedSolution
{ {
public class OrganizationUser public class OrganizationUser
{ {
private int accountId; private int accountId;
private int itemId; private int itemId;
private int packageId; private int packageId;
private string primaryEmailAddress; private string primaryEmailAddress;
private string accountPassword; private string accountPassword;
private string samAccountName; private string samAccountName;
private string displayName; private string displayName;
@ -65,18 +65,23 @@ namespace WebsitePanel.Providers.HostedSolution
private string domainUserName; private string domainUserName;
private bool disabled; private bool disabled;
private bool locked;
private bool isOCSUser;
private bool isBlackBerryUser;
private bool isLyncUser;
ExchangeAccountType accountType; ExchangeAccountType accountType;
private OrganizationUser manager; private OrganizationUser manager;
private Guid crmUserId; private Guid crmUserId;
public Guid CrmUserId public Guid CrmUserId
{ {
get { return crmUserId; } get { return crmUserId; }
set { crmUserId = value; } set { crmUserId = value; }
} }
public string DomainUserName public string DomainUserName
{ {
@ -98,10 +103,10 @@ namespace WebsitePanel.Providers.HostedSolution
public bool Disabled public bool Disabled
{ {
get { return disabled;} get { return disabled; }
set { disabled = value;} set { disabled = value; }
} }
public string FirstName public string FirstName
{ {
get { return firstName; } get { return firstName; }
@ -258,17 +263,40 @@ namespace WebsitePanel.Providers.HostedSolution
set { primaryEmailAddress = value; } set { primaryEmailAddress = value; }
} }
public string AccountPassword public string AccountPassword
{ {
get { return accountPassword; } get { return accountPassword; }
set { accountPassword = value; } set { accountPassword = value; }
} }
public string ExternalEmail { get; set; } public string ExternalEmail { get; set; }
public string DistinguishedName { get; set; } public string DistinguishedName { get; set; }
public bool Locked { get; set; } public bool Locked
{
get { return locked; }
set { locked = value; }
}
public bool IsOCSUser
{
get { return isOCSUser; }
set { isOCSUser = value; }
}
public bool IsLyncUser
{
get { return isLyncUser; }
set { isLyncUser = value; }
}
public bool IsBlackBerryUser
{
get { return isBlackBerryUser; }
set { isBlackBerryUser = value; }
}
} }
} }

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -30,89 +30,91 @@ using System;
namespace WebsitePanel.Providers.SharePoint namespace WebsitePanel.Providers.SharePoint
{ {
/// <summary> /// <summary>
/// Exposes functionality for share point server provider hosted in conjunction with organization management provider and /// Exposes functionality for share point server provider hosted in conjunction with organization management provider and
/// exchange server. /// exchange server.
/// </summary> /// </summary>
public interface IHostedSharePointServer public interface IHostedSharePointServer
{ {
/// <summary> /// <summary>
/// When implemented gets root web application uri. /// When implemented gets root web application uri.
/// </summary> /// </summary>
Uri RootWebApplicationUri Uri RootWebApplicationUri
{ {
get; get;
} }
/// <summary> /// <summary>
/// When implemented gets list of supported languages by this installation of SharePoint. /// When implemented gets list of supported languages by this installation of SharePoint.
/// </summary> /// </summary>
/// <returns>List of supported languages</returns> /// <returns>List of supported languages</returns>
int[] GetSupportedLanguages(); int[] GetSupportedLanguages();
/// <summary> /// <summary>
/// When implemented gets list of SharePoint collections within root web application. /// When implemented gets list of SharePoint collections within root web application.
/// </summary> /// </summary>
/// <returns>List of SharePoint collections within root web application.</returns> /// <returns>List of SharePoint collections within root web application.</returns>
SharePointSiteCollection[] GetSiteCollections(); SharePointSiteCollection[] GetSiteCollections();
/// <summary> /// <summary>
/// When implemented gets SharePoint collection within root web application with given name. /// When implemented gets SharePoint collection within root web application with given name.
/// </summary> /// </summary>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</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> /// <returns>SharePoint collection within root web application with given name.</returns>
SharePointSiteCollection GetSiteCollection(string url); SharePointSiteCollection GetSiteCollection(string url);
/// <summary> /// <summary>
/// When implemented creates site collection within predefined root web application. /// When implemented creates site collection within predefined root web application.
/// </summary> /// </summary>
/// <param name="siteCollection">Information about site coolection to be created.</param> /// <param name="siteCollection">Information about site coolection to be created.</param>
void CreateSiteCollection(SharePointSiteCollection siteCollection); void CreateSiteCollection(SharePointSiteCollection siteCollection);
/// <summary>
/// When implemented deletes site collection under given url.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
void DeleteSiteCollection(string url);
/// <summary> /// <summary>
/// When implemeneted backups site collection under give url. /// When implemented deletes site collection under given url.
/// </summary> /// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param> /// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param> void DeleteSiteCollection(SharePointSiteCollection siteCollection);
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <returns>Created backup full path.</returns>
string BackupSiteCollection(string url, string filename, bool zip);
/// <summary> /// <summary>
/// When implemented restores site collection under given url from backup. /// When implemeneted backups site collection under give url.
/// </summary> /// </summary>
/// <param name="siteCollection">Site collection to be restored.</param> /// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Backup file name to restore from.</param> /// <param name="filename">Resulting backup file name.</param>
void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename); /// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <returns>Created backup full path.</returns>
string BackupSiteCollection(string url, string filename, bool zip);
/// <summary>
/// When implemented 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>
void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename);
/// <summary>
/// When implemented 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>
byte[] GetTempFileBinaryChunk(string path, int offset, int length);
/// <summary>
/// When implemented 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>
string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk);
/// <summary>
/// When implemented 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>
byte[] GetTempFileBinaryChunk(string path, int offset, int length);
/// <summary>
/// When implemented 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>
string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk);
void UpdateQuotas(string url, long maxStorage, long warningStorage); void UpdateQuotas(string url, long maxStorage, long warningStorage);
SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls); SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls);
long GetSiteCollectionSize(string url); long GetSiteCollectionSize(string url);
}
void SetPeoplePickerOu(string site, string ou);
}
} }

View file

@ -51,6 +51,9 @@ namespace WebsitePanel.Providers.SharePoint
private long diskspace; private long diskspace;
private long maxSiteStorage; private long maxSiteStorage;
private long warningStorage; private long warningStorage;
private string rootWebApplicationInteralIpAddress;
private string rootWebApplicationFQDN;
[Persistent] [Persistent]
@ -178,6 +181,39 @@ namespace WebsitePanel.Providers.SharePoint
} }
} }
/// <summary>
/// Gets or sets the internal ip address
/// </summary>
[Persistent]
public string RootWebApplicationInteralIpAddress
{
get
{
return this.rootWebApplicationInteralIpAddress;
}
set
{
this.rootWebApplicationInteralIpAddress = value;
}
}
/// <summary>
/// Gets or sets the internal ip address
/// </summary>
[Persistent]
public string RootWebApplicationFQDN
{
get
{
return this.rootWebApplicationFQDN;
}
set
{
this.rootWebApplicationFQDN = value;
}
}
/// <summary> /// <summary>
/// Gets or sets locale id of the site collection to be created. /// Gets or sets locale id of the site collection to be created.
/// </summary> /// </summary>

View file

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

View file

@ -1,7 +1,18 @@
using System; using System;
using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text; using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers.SharePoint;
namespace WebsitePanel.Providers.HostedSolution namespace WebsitePanel.Providers.HostedSolution
{ {
public class HostedSharePointServer2010 : HostedSharePointServer public class HostedSharePointServer2010 : HostedSharePointServer
@ -12,5 +23,239 @@ namespace WebsitePanel.Providers.HostedSolution
this.Wss3Registry32Key = @"SOFTWARE\Wow6432Node\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\"; this.LanguagePacksPath = @"%commonprogramfiles%\microsoft shared\Web Server Extensions\14\HCCab\";
} }
#region PowerShell integration
private static RunspaceConfiguration runspaceConfiguration = null;
internal virtual string SharepointSnapInName
{
get { return "Microsoft.SharePoint.Powershell"; }
}
internal virtual Runspace OpenRunspace()
{
HostedSolutionLog.LogStart("OpenRunspace");
if (runspaceConfiguration == null)
{
runspaceConfiguration = RunspaceConfiguration.Create();
PSSnapInException exception = null;
PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(SharepointSnapInName, out exception);
HostedSolutionLog.LogInfo("Sharepoint snapin loaded");
if (exception != null)
{
HostedSolutionLog.LogWarning("SnapIn error", exception);
}
}
Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
//
runSpace.Open();
//
runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
HostedSolutionLog.LogEnd("OpenRunspace");
return runSpace;
}
internal void CloseRunspace(Runspace runspace)
{
try
{
if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.Close();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("Runspace error", ex);
}
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd)
{
return ExecuteShellCommand(runSpace, cmd, true);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController)
{
object[] errors;
return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
{
return ExecuteShellCommand(runSpace, cmd, true, out errors);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
{
HostedSolutionLog.LogStart("ExecuteShellCommand");
List<object> errorList = new List<object>();
HostedSolutionLog.DebugCommand(cmd);
Collection<PSObject> results = null;
// Create a pipeline
Pipeline pipeLine = runSpace.CreatePipeline();
using (pipeLine)
{
// Add the command
pipeLine.Commands.Add(cmd);
// Execute the pipeline and save the objects returned.
results = pipeLine.Invoke();
// Log out any errors in the pipeline execution
// NOTE: These errors are NOT thrown as exceptions!
// Be sure to check this to ensure that no errors
// happened while executing the command.
if (pipeLine.Error != null && pipeLine.Error.Count > 0)
{
foreach (object item in pipeLine.Error.ReadToEnd())
{
errorList.Add(item);
string errorMessage = string.Format("Invoke error: {0}", item);
HostedSolutionLog.LogWarning(errorMessage);
}
}
}
pipeLine = null;
errors = errorList.ToArray();
HostedSolutionLog.LogEnd("ExecuteShellCommand");
return results;
}
/// <summary>
/// Returns the distinguished name of the object from the shell execution result
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
internal string GetResultObjectDN(Collection<PSObject> result)
{
HostedSolutionLog.LogStart("GetResultObjectDN");
if (result == null)
throw new ArgumentNullException("result", "Execution result is not specified");
if (result.Count < 1)
throw new ArgumentException("Execution result does not contain any object");
if (result.Count > 1)
throw new ArgumentException("Execution result contains more than one object");
PSMemberInfo info = result[0].Members["DistinguishedName"];
if (info == null)
throw new ArgumentException("Execution result does not contain DistinguishedName property", "result");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("GetResultObjectDN");
return ret;
}
/// <summary>
/// Checks the object from the shell execution result.
/// </summary>
/// <param name="result"></param>
/// <returns>Distinguished name of the object if object exists or null otherwise.</returns>
internal string CheckResultObjectDN(Collection<PSObject> result)
{
HostedSolutionLog.LogStart("CheckResultObjectDN");
if (result == null)
return null;
if (result.Count < 1)
return null;
PSMemberInfo info = result[0].Members["DistinguishedName"];
if (info == null)
throw new ArgumentException("Execution result does not contain DistinguishedName property", "result");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("CheckResultObjectDN");
return ret;
}
/// <summary>
/// Returns the identity of the object from the shell execution result
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
internal string GetResultObjectIdentity(Collection<PSObject> result)
{
HostedSolutionLog.LogStart("GetResultObjectIdentity");
if (result == null)
throw new ArgumentNullException("result", "Execution result is not specified");
if (result.Count < 1)
throw new ArgumentException("Execution result is empty", "result");
if (result.Count > 1)
throw new ArgumentException("Execution result contains more than one object", "result");
PSMemberInfo info = result[0].Members["Identity"];
if (info == null)
throw new ArgumentException("Execution result does not contain Identity property", "result");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("GetResultObjectIdentity");
return ret;
}
/// <summary>
/// Returns the identity of the PS object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
internal string GetPSObjectIdentity(PSObject obj)
{
HostedSolutionLog.LogStart("GetPSObjectIdentity");
if (obj == null)
throw new ArgumentNullException("obj", "PSObject is not specified");
PSMemberInfo info = obj.Members["Identity"];
if (info == null)
throw new ArgumentException("PSObject does not contain Identity property", "obj");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("GetPSObjectIdentity");
return ret;
}
internal object GetPSObjectProperty(PSObject obj, string name)
{
return obj.Members[name].Value;
}
#endregion
public override void SetPeoplePickerOu(string site, string ou)
{
HostedSolutionLog.LogStart("SetPeoplePickerOu");
HostedSolutionLog.LogInfo(" Site: {0}", site);
HostedSolutionLog.LogInfo(" OU: {0}", ou);
Runspace runSpace = null;
try
{
List<SharePointSiteCollection> siteCollections = new List<SharePointSiteCollection>();
runSpace = OpenRunspace();
Command cmd = new Command("Set-SPSite");
cmd.Parameters.Add("Identity", site);
cmd.Parameters.Add("UserAccountDirectoryPath", ou);
ExecuteShellCommand(runSpace, cmd);
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("SetPeoplePickerOu");
}
} }
} }

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -38,33 +38,48 @@ using Microsoft.SharePoint.Administration;
namespace WebsitePanel.Providers.HostedSolution namespace WebsitePanel.Providers.HostedSolution
{ {
/// <summary> /// <summary>
/// Represents SharePoint management functionality implementation. /// Represents SharePoint management functionality implementation.
/// </summary> /// </summary>
public class HostedSharePointServerImpl : MarshalByRefObject public class HostedSharePointServerImpl : MarshalByRefObject
{ {
/// <summary> /// <summary>
/// Gets list of supported languages by this installation of SharePoint. /// Gets list of supported languages by this installation of SharePoint.
/// </summary> /// </summary>
/// <returns>List of supported languages</returns> /// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages(string languagePacksPath) public int[] GetSupportedLanguages(string languagePacksPath)
{ {
List<int> languages = new List<int>(); 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(); try
} {
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
public long GetSiteCollectionSize(Uri root,string url) try
{ {
SPLanguageCollection installedLanguages = SPRegionalSettings.GlobalInstalledLanguages;
foreach (SPLanguage lang in installedLanguages)
{
languages.Add(lang.LCID);
}
return languages.ToArray();
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
public long GetSiteCollectionSize(Uri root, string url)
{
WindowsImpersonationContext wic = null; WindowsImpersonationContext wic = null;
try try
@ -77,8 +92,8 @@ namespace WebsitePanel.Providers.HostedSolution
site.RecalculateStorageUsed(); site.RecalculateStorageUsed();
else else
throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url)); throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
return site.Usage.Storage; return site.Usage.Storage;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -91,28 +106,28 @@ namespace WebsitePanel.Providers.HostedSolution
wic.Undo(); wic.Undo();
} }
} }
public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri root, string[] urls) public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri root, string[] urls)
{ {
WindowsImpersonationContext wic = null; WindowsImpersonationContext wic = null;
try try
{ {
wic = WindowsIdentity.GetCurrent().Impersonate(); wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root); SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
List<SharePointSiteDiskSpace> ret = new List<SharePointSiteDiskSpace>(); List<SharePointSiteDiskSpace> ret = new List<SharePointSiteDiskSpace>();
foreach (string url in urls) foreach (string url in urls)
{ {
SharePointSiteDiskSpace siteDiskSpace = new SharePointSiteDiskSpace(); SharePointSiteDiskSpace siteDiskSpace = new SharePointSiteDiskSpace();
rootWebApplication.Sites[url].RecalculateStorageUsed(); rootWebApplication.Sites[url].RecalculateStorageUsed();
siteDiskSpace.Url = url; siteDiskSpace.Url = url;
siteDiskSpace.DiskSpace = (long)Math.Round( rootWebApplication.Sites[url].Usage.Storage / 1024.0 / 1024.0); siteDiskSpace.DiskSpace = (long)Math.Round(rootWebApplication.Sites[url].Usage.Storage / 1024.0 / 1024.0);
ret.Add(siteDiskSpace); ret.Add(siteDiskSpace);
} }
return ret.ToArray(); return ret.ToArray();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -125,97 +140,97 @@ namespace WebsitePanel.Providers.HostedSolution
wic.Undo(); wic.Undo();
} }
} }
/// <summary> /// <summary>
/// Gets list of SharePoint collections within root web application. /// Gets list of SharePoint collections within root web application.
/// </summary> /// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <returns>List of SharePoint collections within root web application.</returns> /// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections(Uri rootWebApplicationUri) public SharePointSiteCollection[] GetSiteCollections(Uri rootWebApplicationUri)
{ {
try try
{ {
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try try
{ {
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
List<SharePointSiteCollection> siteCollections = new List<SharePointSiteCollection>(); List<SharePointSiteCollection> siteCollections = new List<SharePointSiteCollection>();
foreach(SPSite site in rootWebApplication.Sites) foreach (SPSite site in rootWebApplication.Sites)
{ {
SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection(); SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection();
FillSiteCollection(loadedSiteCollection, site); FillSiteCollection(loadedSiteCollection, site);
siteCollections.Add(loadedSiteCollection); siteCollections.Add(loadedSiteCollection);
} }
return siteCollections.ToArray(); return siteCollections.ToArray();
} }
finally finally
{ {
wic.Undo(); wic.Undo();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new InvalidOperationException("Failed to create site collection.", ex); throw new InvalidOperationException("Failed to create site collection.", ex);
} }
} }
/// <summary> /// <summary>
/// Gets SharePoint collection within root web application with given name. /// Gets SharePoint collection within root web application with given name.
/// </summary> /// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</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> /// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(Uri rootWebApplicationUri, string url) public SharePointSiteCollection GetSiteCollection(Uri rootWebApplicationUri, string url)
{ {
try try
{ {
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try try
{ {
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); 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) 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; SPFarm farm = SPFarm.Local;
SPWebService webService = farm.Services.GetValue<SPWebService>(""); SPWebService webService = farm.Services.GetValue<SPWebService>("");
SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates; SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;
quotaColl.Delete(name); quotaColl.Delete(name);
} }
public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage) public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage)
{ {
WindowsImpersonationContext wic = null; WindowsImpersonationContext wic = null;
try try
{ {
wic = WindowsIdentity.GetCurrent().Impersonate(); wic = WindowsIdentity.GetCurrent().Impersonate();
@ -230,10 +245,10 @@ namespace WebsitePanel.Providers.HostedSolution
if (warningStorage != -1 && maxStorage != -1) if (warningStorage != -1 && maxStorage != -1)
quota.StorageWarningLevel = Math.Min(warningStorage, maxStorage)*1024*1024; quota.StorageWarningLevel = Math.Min(warningStorage, maxStorage) * 1024 * 1024;
else else
quota.StorageWarningLevel = 0; quota.StorageWarningLevel = 0;
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name); rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
rootWebApplication.Sites[url].Quota = quota; rootWebApplication.Sites[url].Quota = quota;
@ -250,16 +265,17 @@ namespace WebsitePanel.Providers.HostedSolution
} }
} }
/// <summary> /// <summary>
/// Creates site collection within predefined root web application. /// Creates site collection within predefined root web application.
/// </summary> /// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="siteCollection">Information about site coolection to be created.</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> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection) public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
{ {
WindowsImpersonationContext wic = null; WindowsImpersonationContext wic = null;
HostedSolutionLog.LogStart("CreateSiteCollection");
try try
{ {
@ -267,27 +283,29 @@ namespace WebsitePanel.Providers.HostedSolution
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port); string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);
HostedSolutionLog.DebugInfo("rootWebApplicationUri: {0}", rootWebApplicationUri);
HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl);
SPQuota spQuota; SPQuota spQuota;
SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl, SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl,
siteCollection.Title, siteCollection.Description, siteCollection.Title, siteCollection.Description,
(uint) siteCollection.LocaleId, String.Empty, (uint)siteCollection.LocaleId, String.Empty,
siteCollection.OwnerLogin, siteCollection.OwnerName, siteCollection.OwnerLogin, siteCollection.OwnerName,
siteCollection.OwnerEmail, siteCollection.OwnerEmail,
null, null, null, true); null, null, null, true);
try try
{ {
spQuota = new SPQuota(); spQuota = new SPQuota();
if (siteCollection.MaxSiteStorage != -1) if (siteCollection.MaxSiteStorage != -1)
spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024; spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024;
if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1) if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1)
spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024; spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024;
} }
catch (Exception) catch (Exception)
{ {
@ -298,7 +316,7 @@ namespace WebsitePanel.Providers.HostedSolution
try try
{ {
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name); rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
spSite.Quota = spQuota; spSite.Quota = spQuota;
} }
catch (Exception) catch (Exception)
{ {
@ -308,8 +326,77 @@ namespace WebsitePanel.Providers.HostedSolution
} }
rootWebApplication.Update(true); rootWebApplication.Update(true);
try
{
if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
{
string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
string path = dirPath + "\\hosts";
if (FileUtils.FileExists(path))
{
string content = FileUtils.GetFileTextContent(path);
content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] contentArr = content.Split(new char[] { '\n' });
bool bRecordExist = false;
foreach (string s in contentArr)
{
if (s != string.Empty)
{
string IPAddr = string.Empty;
string hostName = string.Empty;
if (s[0] != '#')
{
bool bSeperator = false;
foreach (char c in s)
{
if ((c != ' ') & (c != '\t'))
{
if (bSeperator)
hostName += c;
else
IPAddr += c;
}
else
bSeperator = true;
}
if (hostName.ToLower() == siteCollection.RootWebApplicationFQDN.ToLower())
{
bRecordExist = true;
break;
}
}
}
}
if (!bRecordExist)
{
string outPut = string.Empty;
foreach (string o in contentArr)
{
if (o != string.Empty)
outPut += o + "\r\n";
}
outPut += siteCollection.RootWebApplicationInteralIpAddress + '\t' + siteCollection.RootWebApplicationFQDN + "\r\n";
FileUtils.UpdateFileTextContent(path, outPut);
}
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
}
} }
catch(Exception ex) catch (Exception ex)
{ {
HostedSolutionLog.LogError(ex); HostedSolutionLog.LogError(ex);
throw; throw;
@ -318,207 +405,267 @@ namespace WebsitePanel.Providers.HostedSolution
{ {
if (wic != null) if (wic != null)
wic.Undo(); wic.Undo();
HostedSolutionLog.LogEnd("CreateSiteCollection");
} }
} }
/// <summary> /// <summary>
/// Deletes site collection under given url. /// Deletes site collection under given url.
/// </summary> /// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</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> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void DeleteSiteCollection(Uri rootWebApplicationUri, string url) public void DeleteSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
{ {
try try
{ {
WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsImpersonationContext wic = identity.Impersonate(); WindowsImpersonationContext wic = identity.Impersonate();
try try
{ {
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);
//string args = String.Format("-o deletesite -url {0}", siteCollectionUrl); //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"; //string stsadm = @"c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM.EXE";
//// launch system process //// launch system process
//ProcessStartInfo startInfo = new ProcessStartInfo(stsadm, args); //ProcessStartInfo startInfo = new ProcessStartInfo(stsadm, args);
//startInfo.WindowStyle = ProcessWindowStyle.Hidden; //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//startInfo.RedirectStandardOutput = true; //startInfo.RedirectStandardOutput = true;
//startInfo.UseShellExecute = false; //startInfo.UseShellExecute = false;
//Process proc = Process.Start(startInfo); //Process proc = Process.Start(startInfo);
//// analyze results //// analyze results
//StreamReader reader = proc.StandardOutput; //StreamReader reader = proc.StandardOutput;
//string output = reader.ReadToEnd(); //string output = reader.ReadToEnd();
//int exitCode = proc.ExitCode; //int exitCode = proc.ExitCode;
//reader.Close(); //reader.Close();
rootWebApplication.Sites.Delete(siteCollectionUrl, true); rootWebApplication.Sites.Delete(siteCollectionUrl, true);
rootWebApplication.Update(true); rootWebApplication.Update(true);
}
finally
{
wic.Undo();
}
}
catch(Exception ex)
{
throw new InvalidOperationException("Failed to delete site collection.", ex);
}
}
/// <summary> try
/// Backups site collection under give url. {
/// </summary> if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
/// <param name="rootWebApplicationUri">Root web application uri.</param> {
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param> string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
/// <param name="filename">Resulting backup file name.</param> string path = dirPath + "\\hosts";
/// <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 if (FileUtils.FileExists(path))
{ {
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); string content = FileUtils.GetFileTextContent(path);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] contentArr = content.Split(new char[] { '\n' });
string outPut = string.Empty;
foreach (string s in contentArr)
{
if (s != string.Empty)
{
string IPAddr = string.Empty;
string hostName = string.Empty;
if (s[0] != '#')
{
bool bSeperator = false;
foreach (char c in s)
{
if ((c != ' ') & (c != '\t'))
{
if (bSeperator)
hostName += c;
else
IPAddr += c;
}
else
bSeperator = true;
}
if (String.IsNullOrEmpty(tempPath)) if (hostName.ToLower() != siteCollection.RootWebApplicationFQDN.ToLower())
{ {
tempPath = Path.GetTempPath(); outPut += s + "\r\n";
} }
string backupFileName = Path.Combine(tempPath, (zip ? StringUtils.CleanIdentifier(siteCollectionUrl) + ".bsh" : StringUtils.CleanIdentifier(filename)));
// Backup requested site.
rootWebApplication.Sites.Backup(siteCollectionUrl, backupFileName, true);
if (zip) }
{ else
string zipFile = Path.Combine(tempPath, filename); outPut += s + "\r\n";
string zipRoot = Path.GetDirectoryName(backupFileName); }
}
FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(backupFileName) }); FileUtils.UpdateFileTextContent(path, outPut);
FileUtils.DeleteFile(backupFileName); }
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
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. finally
/// </summary> {
/// <param name="customSiteCollection">Custom site collection to fill.</param> wic.Undo();
/// <param name="site">Administration object.</param> }
private static void FillSiteCollection (SharePointSiteCollection customSiteCollection, SPSite site) }
{ catch (Exception ex)
Uri siteUri = new Uri(site.Url); {
string url = (siteUri.Port > 0) ? site.Url.Replace(String.Format(":{0}", siteUri.Port), String.Empty) : site.Url; throw new InvalidOperationException("Failed to delete site collection.", ex);
}
}
customSiteCollection.Url = url; /// <summary>
customSiteCollection.OwnerLogin = site.Owner.LoginName; /// Backups site collection under give url.
customSiteCollection.OwnerName = site.Owner.Name; /// </summary>
customSiteCollection.OwnerEmail = site.Owner.Email; /// <param name="rootWebApplicationUri">Root web application uri.</param>
customSiteCollection.LocaleId = site.RootWeb.Locale.LCID; /// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
customSiteCollection.Title = site.RootWeb.Title; /// <param name="filename">Resulting backup file name.</param>
customSiteCollection.Description = site.RootWeb.Description; /// <param name="zip">A value which shows whether created backup must be archived.</param>
customSiteCollection.Bandwidth = site.Usage.Bandwidth; /// <param name="tempPath">Custom temp path for backup</param>
customSiteCollection.Diskspace = site.Usage.Storage; /// <returns>Full path to created backup.</returns>
customSiteCollection.MaxSiteStorage = site.Quota.StorageMaximumLevel; /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
customSiteCollection.WarningStorage = site.Quota.StorageWarningLevel; 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

@ -29,6 +29,8 @@
using System; using System;
using WebsitePanel.Providers.Common; using WebsitePanel.Providers.Common;
using WebsitePanel.Server.Utils; using WebsitePanel.Server.Utils;
using System.Text;
using System.Management.Automation.Runspaces;
namespace WebsitePanel.Providers.HostedSolution namespace WebsitePanel.Providers.HostedSolution
{ {
@ -121,6 +123,22 @@ namespace WebsitePanel.Providers.HostedSolution
res.IsSuccess = true; res.IsSuccess = true;
return res; return res;
} }
internal static void DebugCommand(Command cmd)
{
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());
}
} }
} }

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -38,186 +38,185 @@ using Microsoft.Web.Services3;
namespace WebsitePanel.Server namespace WebsitePanel.Server
{ {
/// <summary> /// <summary>
/// Summary description for HostedSharePointServer /// Summary description for HostedSharePointServer
/// </summary> /// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")] [WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")] [Policy("ServerPolicy")]
[ToolboxItem(false)] [ToolboxItem(false)]
public class HostedSharePointServer : HostingServiceProviderWebService public class HostedSharePointServer : HostingServiceProviderWebService
{ {
private delegate TReturn Action<TReturn>(); private delegate TReturn Action<TReturn>();
/// <summary> /// <summary>
/// Gets hosted SharePoint provider instance. /// Gets hosted SharePoint provider instance.
/// </summary> /// </summary>
private IHostedSharePointServer HostedSharePointServerProvider private IHostedSharePointServer HostedSharePointServerProvider
{ {
get { return (IHostedSharePointServer)Provider; } get { return (IHostedSharePointServer)Provider; }
} }
/// <summary> /// <summary>
/// Gets list of supported languages by this installation of SharePoint. /// Gets list of supported languages by this installation of SharePoint.
/// </summary> /// </summary>
/// <returns>List of supported languages</returns> /// <returns>List of supported languages</returns>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public int[] GetSupportedLanguages() public int[] GetSupportedLanguages()
{ {
return ExecuteAction<int[]>(delegate return ExecuteAction<int[]>(delegate
{ {
return HostedSharePointServerProvider.GetSupportedLanguages(); return HostedSharePointServerProvider.GetSupportedLanguages();
}, "GetSupportedLanguages"); }, "GetSupportedLanguages");
} }
/// <summary> /// <summary>
/// Gets list of SharePoint collections within root web application. /// Gets list of SharePoint collections within root web application.
/// </summary> /// </summary>
/// <returns>List of SharePoint collections within root web application.</returns> /// <returns>List of SharePoint collections within root web application.</returns>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public SharePointSiteCollection[] GetSiteCollections() public SharePointSiteCollection[] GetSiteCollections()
{ {
return ExecuteAction<SharePointSiteCollection[]>(delegate return ExecuteAction<SharePointSiteCollection[]>(delegate
{ {
return HostedSharePointServerProvider.GetSiteCollections(); return HostedSharePointServerProvider.GetSiteCollections();
}, "GetSiteCollections"); }, "GetSiteCollections");
} }
/// <summary> /// <summary>
/// Gets SharePoint collection within root web application with given name. /// Gets SharePoint collection within root web application with given name.
/// </summary> /// </summary>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</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> /// <returns>SharePoint collection within root web application with given name.</returns>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public SharePointSiteCollection GetSiteCollection(string url) public SharePointSiteCollection GetSiteCollection(string url)
{ {
return ExecuteAction<SharePointSiteCollection>(delegate return ExecuteAction<SharePointSiteCollection>(delegate
{ {
return HostedSharePointServerProvider.GetSiteCollection(url); return HostedSharePointServerProvider.GetSiteCollection(url);
}, "GetSiteCollection"); }, "GetSiteCollection");
} }
/// <summary> /// <summary>
/// Creates site collection within predefined root web application. /// Creates site collection within predefined root web application.
/// </summary> /// </summary>
/// <param name="siteCollection">Information about site coolection to be created.</param> /// <param name="siteCollection">Information about site coolection to be created.</param>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public void CreateSiteCollection(SharePointSiteCollection siteCollection) public void CreateSiteCollection(SharePointSiteCollection siteCollection)
{ {
siteCollection.OwnerLogin = AttachNetbiosDomainName(siteCollection.OwnerLogin); siteCollection.OwnerLogin = AttachNetbiosDomainName(siteCollection.OwnerLogin);
ExecuteAction<object>(delegate ExecuteAction<object>(delegate
{ {
HostedSharePointServerProvider.CreateSiteCollection(siteCollection); HostedSharePointServerProvider.CreateSiteCollection(siteCollection);
return new object(); return new object();
}, "CreateSiteCollection"); }, "CreateSiteCollection");
} }
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public void UpdateQuotas(string url, long maxSize, long warningSize) public void UpdateQuotas(string url, long maxSize, long warningSize)
{ {
ExecuteAction<object>(delegate ExecuteAction<object>(delegate
{ {
HostedSharePointServerProvider.UpdateQuotas(url, maxSize, warningSize); HostedSharePointServerProvider.UpdateQuotas(url, maxSize, warningSize);
return new object(); return new object();
}, "UpdateQuotas"); }, "UpdateQuotas");
} }
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls) public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls)
{ {
SharePointSiteDiskSpace []ret = null; SharePointSiteDiskSpace[] ret = null;
ret = ExecuteAction<SharePointSiteDiskSpace[]>(delegate ret = ExecuteAction<SharePointSiteDiskSpace[]>(delegate
{ {
return HostedSharePointServerProvider.CalculateSiteCollectionsDiskSpace(urls); return HostedSharePointServerProvider.CalculateSiteCollectionsDiskSpace(urls);
}, "CalculateSiteCollectionDiskSpace"); }, "CalculateSiteCollectionDiskSpace");
return ret; return ret;
} }
/// <summary> /// <summary>
/// Deletes site collection under given url. /// Deletes site collection under given url.
/// </summary> /// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param> /// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public void DeleteSiteCollection(string url) public void DeleteSiteCollection(SharePointSiteCollection siteCollection)
{ {
ExecuteAction<object>(delegate ExecuteAction<object>(delegate
{ {
HostedSharePointServerProvider.DeleteSiteCollection(url); HostedSharePointServerProvider.DeleteSiteCollection(siteCollection);
return new object(); return new object();
}, "DeleteSiteCollection"); }, "DeleteSiteCollection");
} }
/// <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>
[WebMethod, SoapHeader("settings")]
public string BackupSiteCollection(string url, string filename, bool zip)
{
return ExecuteAction<string>(delegate
{
return
HostedSharePointServerProvider.BackupSiteCollection(url, filename, zip);
}, "BackupSiteCollection");
}
/// <summary> /// <summary>
/// Backups site collection under give url. /// Restores site collection under given url from backup.
/// </summary> /// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param> /// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Resulting backup file name.</param> /// <param name="filename">Backup file name to restore from.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param> [WebMethod, SoapHeader("settings")]
/// <returns>Created backup full path.</returns> public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename)
[WebMethod, SoapHeader("settings")] {
public string BackupSiteCollection(string url, string filename, bool zip) siteCollection.OwnerLogin = AttachNetbiosDomainName(siteCollection.OwnerLogin);
{ ExecuteAction<object>(delegate
return ExecuteAction<string>(delegate {
{ HostedSharePointServerProvider.RestoreSiteCollection(siteCollection, filename);
return return new object();
HostedSharePointServerProvider.BackupSiteCollection(url, filename, zip); }, "RestoreSiteCollection");
}, "BackupSiteCollection"); }
}
/// <summary> /// <summary>
/// Restores site collection under given url from backup. /// Gets binary data chunk of specified size from specified offset.
/// </summary> /// </summary>
/// <param name="siteCollection">Site collection to be restored.</param> /// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="filename">Backup file name to restore from.</param> /// <param name="offset">Offset from which to start data reading.</param>
[WebMethod, SoapHeader("settings")] /// <param name="length">Binary data chunk length.</param>
public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename) /// <returns>Binary data chunk read from file.</returns>
{ [WebMethod, SoapHeader("settings")]
siteCollection.OwnerLogin = AttachNetbiosDomainName(siteCollection.OwnerLogin); public byte[] GetTempFileBinaryChunk(string path, int offset, int length)
ExecuteAction<object>(delegate {
{ return ExecuteAction<byte[]>(delegate
HostedSharePointServerProvider.RestoreSiteCollection(siteCollection, filename); {
return new object(); return
}, "RestoreSiteCollection"); HostedSharePointServerProvider.GetTempFileBinaryChunk(path, offset, length);
} }, "GetTempFileBinaryChunk");
}
/// <summary> /// <summary>
/// Gets binary data chunk of specified size from specified offset. /// Appends supplied binary data chunk to file.
/// </summary> /// </summary>
/// <param name="path">Path to file to get bunary data chunk from.</param> /// <param name="fileName">Non existent file name to append to.</param>
/// <param name="offset">Offset from which to start data reading.</param> /// <param name="path">Full path to existent file to append to.</param>
/// <param name="length">Binary data chunk length.</param> /// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Binary data chunk read from file.</returns> /// <returns>Path to file that was appended with chunk.</returns>
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
public byte[] GetTempFileBinaryChunk(string path, int offset, int length) public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{ {
return ExecuteAction<byte[]>(delegate return ExecuteAction<string>(delegate
{ {
return return
HostedSharePointServerProvider.GetTempFileBinaryChunk(path, offset, length); HostedSharePointServerProvider.AppendTempFileBinaryChunk(fileName, path, chunk);
}, "GetTempFileBinaryChunk"); }, "AppendTempFileBinaryChunk");
} }
/// <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>
[WebMethod, SoapHeader("settings")]
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
return ExecuteAction<string>(delegate
{
return
HostedSharePointServerProvider.AppendTempFileBinaryChunk(fileName, path, chunk);
}, "AppendTempFileBinaryChunk");
}
[WebMethod, SoapHeader("settings")] [WebMethod, SoapHeader("settings")]
@ -230,38 +229,46 @@ namespace WebsitePanel.Server
}, "GetSiteCollectionSize"); }, "GetSiteCollectionSize");
} }
/// <summary>
/// Executes supplied action and performs logging.
/// </summary>
/// <typeparam name="TReturn">Type of action's return value.</typeparam>
/// <param name="action">Action to be executed.</param>
/// <param name="actionName">Action name for logging purposes.</param>
/// <returns>Action execution result.</returns>
private TReturn ExecuteAction<TReturn>(Action<TReturn> action, string actionName)
{
try
{
Log.WriteStart("'{0}' {1}", ProviderSettings.ProviderName, actionName);
TReturn result = action();
Log.WriteEnd("'{0}' {1}", ProviderSettings.ProviderName, actionName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't {1} '{0}' provider", ProviderSettings.ProviderName, actionName), ex);
throw;
}
}
/// <summary> [WebMethod, SoapHeader("settings")]
/// Returns fully qualified netbios account name. public void SetPeoplePickerOu(string site, string ou)
/// </summary> {
/// <param name="accountName">Account name.</param> HostedSharePointServerProvider.SetPeoplePickerOu(site, ou);
/// <returns>Fully qualified netbios account name.</returns> }
private string AttachNetbiosDomainName(string accountName)
{
string domainNetbiosName = String.Format("{0}\\", ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain)); /// <summary>
return String.Format("{0}{1}", domainNetbiosName, accountName.Replace(domainNetbiosName, String.Empty)); /// Executes supplied action and performs logging.
} /// </summary>
} /// <typeparam name="TReturn">Type of action's return value.</typeparam>
/// <param name="action">Action to be executed.</param>
/// <param name="actionName">Action name for logging purposes.</param>
/// <returns>Action execution result.</returns>
private TReturn ExecuteAction<TReturn>(Action<TReturn> action, string actionName)
{
try
{
Log.WriteStart("'{0}' {1}", ProviderSettings.ProviderName, actionName);
TReturn result = action();
Log.WriteEnd("'{0}' {1}", ProviderSettings.ProviderName, actionName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't {1} '{0}' provider", ProviderSettings.ProviderName, actionName), ex);
throw;
}
}
/// <summary>
/// Returns fully qualified netbios account name.
/// </summary>
/// <param name="accountName">Account name.</param>
/// <returns>Fully qualified netbios account name.</returns>
private string AttachNetbiosDomainName(string accountName)
{
string domainNetbiosName = String.Format("{0}\\", ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain));
return String.Format("{0}{1}", domainNetbiosName, accountName.Replace(domainNetbiosName, String.Empty));
}
}
} }

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -95,6 +95,7 @@ namespace WebsitePanel.Portal
{ {
BindDomains(); BindDomains();
} }
} }
private void BindDomains() private void BindDomains()

View file

@ -49,7 +49,7 @@
<asp:Image ID="img1" runat="server" ImageUrl='<%# GetAccountImage() %>' ImageAlign="AbsMiddle" /> <asp:Image ID="img1" runat="server" ImageUrl='<%# GetAccountImage() %>' ImageAlign="AbsMiddle" />
<asp:LinkButton ID="cmdSelectAccount" CommandName="SelectAccount" <asp:LinkButton ID="cmdSelectAccount" CommandName="SelectAccount"
CommandArgument='<%# Eval("AccountName").ToString() + "|" + Eval("DisplayName").ToString() + "|" + Eval("PrimaryEmailAddress")+ "|" + Eval("AccountId")%>' CommandArgument='<%# Eval("AccountName").ToString() + "|" + Eval("DisplayName").ToString() + "|" + Eval("PrimaryEmailAddress")+ "|" + Eval("AccountId")+ "|" + Eval("SamAccountName")%>'
runat="server" Text='<%# Eval("DisplayName") %>'></asp:LinkButton> runat="server" Text='<%# Eval("DisplayName") %>'></asp:LinkButton>
</ItemTemplate> </ItemTemplate>
</asp:TemplateField> </asp:TemplateField>

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2010, SMB SAAS Systems Inc.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -11,7 +11,7 @@
// this list of conditions and the following disclaimer in the documentation // this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution. // and/or other materials provided with the distribution.
// //
// - Neither the name of the Outercurve Foundation nor the names of its // - Neither the name of the SMB SAAS Systems Inc. nor the names of its
// contributors may be used to endorse or promote products derived from this // contributors may be used to endorse or promote products derived from this
// software without specific prior written permission. // software without specific prior written permission.
// //
@ -50,21 +50,82 @@ namespace WebsitePanel.Portal.ExchangeServer.UserControls
ViewState["IncludeMailboxes"] = value; ViewState["IncludeMailboxes"] = value;
} }
} }
public bool IncludeMailboxesOnly
{
get
{
object ret = ViewState["IncludeMailboxesOnly"];
return (ret != null) ? (bool)ret : false;
}
set
{
ViewState["IncludeMailboxesOnly"] = value;
}
}
public bool ExcludeOCSUsers
{
get
{
object ret = ViewState["ExcludeOCSUsers"];
return (ret != null) ? (bool)ret : false;
}
set
{
ViewState["ExcludeOCSUsers"] = value;
}
}
public bool ExcludeLyncUsers
{
get
{
object ret = ViewState["ExcludeLyncUsers"];
return (ret != null) ? (bool)ret : false;
}
set
{
ViewState["ExcludeLyncUsers"] = value;
}
}
public bool ExcludeBESUsers
{
get
{
object ret = ViewState["ExcludeBESUsers"];
return (ret != null) ? (bool)ret : false;
}
set
{
ViewState["ExcludeBESUsers"] = value;
}
}
public int ExcludeAccountId public int ExcludeAccountId
{ {
get { return PanelRequest.AccountID; } get { return PanelRequest.AccountID; }
} }
public void SetAccount(OrganizationUser account) public void SetAccount(OrganizationUser account)
{ {
BindSelectedAccount(account); BindSelectedAccount(account);
} }
public string GetAccount()
{
return (string)ViewState["AccountName"];
}
public string GetSAMAccountName()
{
return (string)ViewState["SAMAccountName"];
}
public string GetAccount()
{
return (string)ViewState["AccountName"];
}
public string GetDisplayName() public string GetDisplayName()
{ {
@ -77,56 +138,93 @@ namespace WebsitePanel.Portal.ExchangeServer.UserControls
} }
public int GetAccountId() public int GetAccountId()
{ {
return Utils.ParseInt(ViewState["AccountId"], 0); return Utils.ParseInt(ViewState["AccountId"], 0);
} }
protected void Page_Load(object sender, EventArgs e) protected void Page_Load(object sender, EventArgs e)
{ {
} }
private void BindSelectedAccount(OrganizationUser account) private void BindSelectedAccount(OrganizationUser account)
{ {
if (account != null) if (account != null)
{ {
txtDisplayName.Text = account.DisplayName; txtDisplayName.Text = account.DisplayName;
ViewState["AccountName"] = account.AccountName; ViewState["AccountName"] = account.AccountName;
ViewState["DisplayName"] = account.DisplayName; ViewState["DisplayName"] = account.DisplayName;
ViewState["PrimaryEmailAddress"] = account.PrimaryEmailAddress; ViewState["PrimaryEmailAddress"] = account.PrimaryEmailAddress;
ViewState["AccountId"] = account.AccountId; ViewState["AccountId"] = account.AccountId;
} ViewState["SAMAccountName"] = account.SamAccountName;
else }
{ else
txtDisplayName.Text = ""; {
ViewState["AccountName"] = null; txtDisplayName.Text = "";
ViewState["AccountName"] = null;
ViewState["DisplayName"] = null; ViewState["DisplayName"] = null;
ViewState["PrimaryEmailAddress"] = null; ViewState["PrimaryEmailAddress"] = null;
ViewState["AccountId"] = null; ViewState["AccountId"] = null;
ViewState["SAMAccountName"] = null;
} }
} }
public string GetAccountImage() public string GetAccountImage()
{ {
return GetThemedImage("Exchange/admin_16.png"); return GetThemedImage("Exchange/admin_16.png");
} }
private void BindPopupAccounts() private void BindPopupAccounts()
{ {
OrganizationUser[] accounts = ES.Services.Organizations.SearchAccounts(PanelRequest.ItemID, OrganizationUser[] accounts = ES.Services.Organizations.SearchAccounts(PanelRequest.ItemID,
ddlSearchColumn.SelectedValue, txtSearchValue.Text + "%", "", IncludeMailboxes); ddlSearchColumn.SelectedValue, txtSearchValue.Text + "%", "", IncludeMailboxes);
if (ExcludeAccountId > 0) if (ExcludeAccountId > 0)
{ {
List<OrganizationUser> updatedAccounts = new List<OrganizationUser>(); List<OrganizationUser> updatedAccounts = new List<OrganizationUser>();
foreach (OrganizationUser account in accounts) foreach (OrganizationUser account in accounts)
if (account.AccountId != ExcludeAccountId) if (account.AccountId != ExcludeAccountId)
updatedAccounts.Add(account); updatedAccounts.Add(account);
accounts = updatedAccounts.ToArray();
}
if (IncludeMailboxesOnly)
{
List<OrganizationUser> updatedAccounts = new List<OrganizationUser>();
foreach (OrganizationUser account in accounts)
{
bool addUser = false;
if (account.ExternalEmail != string.Empty) addUser = true;
if ((account.IsBlackBerryUser) & (ExcludeBESUsers)) addUser = false;
if ((account.IsLyncUser) & (ExcludeLyncUsers)) addUser = false;
if (addUser) updatedAccounts.Add(account);
}
accounts = updatedAccounts.ToArray();
}
else
if ((ExcludeOCSUsers) | (ExcludeBESUsers) | (ExcludeLyncUsers))
{
List<OrganizationUser> updatedAccounts = new List<OrganizationUser>();
foreach (OrganizationUser account in accounts)
{
bool addUser = true;
if ((account.IsOCSUser) & (ExcludeOCSUsers)) addUser = false;
if ((account.IsLyncUser) & (ExcludeLyncUsers)) addUser = false;
if ((account.IsBlackBerryUser) & (ExcludeBESUsers)) addUser = false;
if (addUser) updatedAccounts.Add(account);
}
accounts = updatedAccounts.ToArray();
}
accounts = updatedAccounts.ToArray();
}
Array.Sort(accounts, CompareAccount); Array.Sort(accounts, CompareAccount);
if (Direction == SortDirection.Ascending) if (Direction == SortDirection.Ascending)
@ -136,15 +234,15 @@ namespace WebsitePanel.Portal.ExchangeServer.UserControls
} }
else else
Direction = SortDirection.Ascending; Direction = SortDirection.Ascending;
gvPopupAccounts.DataSource = accounts; gvPopupAccounts.DataSource = accounts;
gvPopupAccounts.DataBind(); gvPopupAccounts.DataBind();
} }
private SortDirection Direction private SortDirection Direction
{ {
get { return ViewState[DirectionString] == null ? SortDirection.Descending : (SortDirection)ViewState[DirectionString]; } get { return ViewState[DirectionString] == null ? SortDirection.Descending : (SortDirection)ViewState[DirectionString]; }
set {ViewState[DirectionString] = value;} set { ViewState[DirectionString] = value; }
} }
private static int CompareAccount(OrganizationUser user1, OrganizationUser user2) private static int CompareAccount(OrganizationUser user1, OrganizationUser user2)
@ -152,57 +250,58 @@ namespace WebsitePanel.Portal.ExchangeServer.UserControls
return string.Compare(user1.DisplayName, user2.DisplayName); return string.Compare(user1.DisplayName, user2.DisplayName);
} }
protected void chkIncludeMailboxes_CheckedChanged(object sender, EventArgs e)
{
BindPopupAccounts();
}
protected void cmdSearch_Click(object sender, ImageClickEventArgs e) protected void chkIncludeMailboxes_CheckedChanged(object sender, EventArgs e)
{ {
BindPopupAccounts(); BindPopupAccounts();
} }
protected void cmdClear_Click(object sender, EventArgs e) protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
{ {
BindSelectedAccount(null); BindPopupAccounts();
} }
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) protected void cmdClear_Click(object sender, EventArgs e)
{ {
// bind all accounts BindSelectedAccount(null);
BindPopupAccounts(); }
// show modal protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
SelectAccountsModal.Show(); {
} // bind all accounts
BindPopupAccounts();
protected void gvPopupAccounts_RowCommand(object sender, GridViewCommandEventArgs e) // show modal
{ SelectAccountsModal.Show();
if (e.CommandName == "SelectAccount") }
{
string[] parts = e.CommandArgument.ToString().Split('|');
OrganizationUser account = new OrganizationUser();
account.AccountName = parts[0];
account.DisplayName = parts[1];
account.PrimaryEmailAddress = parts[2];
account.AccountId = Utils.ParseInt(parts[3]);
// set account protected void gvPopupAccounts_RowCommand(object sender, GridViewCommandEventArgs e)
BindSelectedAccount(account); {
if (e.CommandName == "SelectAccount")
{
string[] parts = e.CommandArgument.ToString().Split('|');
OrganizationUser account = new OrganizationUser();
account.AccountName = parts[0];
account.DisplayName = parts[1];
account.PrimaryEmailAddress = parts[2];
account.AccountId = Utils.ParseInt(parts[3]);
account.SamAccountName = parts[4];
// hide popup // set account
SelectAccountsModal.Hide(); BindSelectedAccount(account);
// update parent panel // hide popup
MainUpdatePanel.Update(); SelectAccountsModal.Hide();
}
} // update parent panel
MainUpdatePanel.Update();
}
}
protected void OnSorting(object sender, GridViewSortEventArgs e) protected void OnSorting(object sender, GridViewSortEventArgs e)
{ {
BindPopupAccounts(); BindPopupAccounts();
} }

View file

@ -1,10 +1,9 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// This code was generated by a tool. // This code was generated by a tool.
// Runtime Version:2.0.50727.4927
// //
// Changes to this file may cause incorrect behavior and will be lost if // Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------

View file

@ -1,25 +1,18 @@
<%@ Control Language="C#" AutoEventWireup="true" Codebehind="HostedSharePointEditSiteCollection.ascx.cs" <%@ Control Language="C#" AutoEventWireup="true" Codebehind="HostedSharePointEditSiteCollection.ascx.cs" Inherits="WebsitePanel.Portal.HostedSharePointEditSiteCollection" %>
Inherits="WebsitePanel.Portal.HostedSharePointEditSiteCollection" %>
<%@ Register Src="ExchangeServer/UserControls/SizeBox.ascx" TagName="SizeBox" TagPrefix="wsp" %> <%@ Register Src="ExchangeServer/UserControls/SizeBox.ascx" TagName="SizeBox" TagPrefix="wsp" %>
<%@ Register Src="UserControls/SimpleMessageBox.ascx" TagName="SimpleMessageBox" <%@ Register Src="UserControls/SimpleMessageBox.ascx" TagName="SimpleMessageBox" TagPrefix="wsp" %>
TagPrefix="wsp" %> <%@ Register Src="UserControls/CollapsiblePanel.ascx" TagName="CollapsiblePanel" TagPrefix="wsp" %>
<%@ Register TagPrefix="wsp" TagName="CollapsiblePanel" Src="UserControls/CollapsiblePanel.ascx" %>
<%@ Register Src="UserControls/PopupHeader.ascx" TagName="PopupHeader" TagPrefix="wsp" %> <%@ Register Src="UserControls/PopupHeader.ascx" TagName="PopupHeader" TagPrefix="wsp" %>
<%@ Register Src="ExchangeServer/UserControls/Menu.ascx" TagName="Menu" TagPrefix="wsp" %> <%@ Register Src="ExchangeServer/UserControls/Menu.ascx" TagName="Menu" TagPrefix="wsp" %>
<%@ Register Src="ExchangeServer/UserControls/Breadcrumb.ascx" TagName="Breadcrumb" <%@ Register Src="ExchangeServer/UserControls/Breadcrumb.ascx" TagName="Breadcrumb" TagPrefix="wsp" %>
TagPrefix="wsp" %> <%@ Register Src="UserControls/AllocatePackageIPAddresses.ascx" TagName="SiteUrlBuilder" TagPrefix="wsp" %>
<%@ Register Src="ExchangeServer/UserControls/DomainSelector.ascx" TagName="DomainSelector" TagPrefix="wsp" %>
<%@ Register Src="ExchangeServer/UserControls/UserSelector.ascx" TagName="UserSelector" TagPrefix="wsp" %> <%@ Register Src="ExchangeServer/UserControls/UserSelector.ascx" TagName="UserSelector" TagPrefix="wsp" %>
<%@ Register Src="UserControls/EnableAsyncTasksSupport.ascx" TagName="EnableAsyncTasksSupport" TagPrefix="wsp" %>
<%@ Register Src="UserControls/EnableAsyncTasksSupport.ascx" TagName="EnableAsyncTasksSupport"
TagPrefix="wsp" %>
<%@ Register src="UserControls/QuotaEditor.ascx" tagname="QuotaEditor" tagprefix="uc1" %> <%@ Register src="UserControls/QuotaEditor.ascx" tagname="QuotaEditor" tagprefix="uc1" %>
<%@ Register Src="DomainsSelectDomainControl.ascx" TagName="DomainsSelectDomainControl" TagPrefix="uc1" %>
<wsp:EnableAsyncTasksSupport id="asyncTasks" runat="server" /> <wsp:EnableAsyncTasksSupport id="asyncTasks" runat="server" />
<div id="ExchangeContainer"> <div id="ExchangeContainer">
<div class="Module"> <div class="Module">
<div class="Header"> <div class="Header">
@ -39,13 +32,18 @@
<wsp:SimpleMessageBox id="localMessageBox" runat="server"> <wsp:SimpleMessageBox id="localMessageBox" runat="server">
</wsp:SimpleMessageBox> </wsp:SimpleMessageBox>
<table id="tblEditItem" runat="server" cellspacing="0" cellpadding="5" width="100%"> <table id="tblEditItem" runat="server" cellspacing="0" cellpadding="5" width="100%">
<tr> <tr id="rowUrl">
<td class="SubHead" nowrap width="200"> <td class="SubHead" nowrap width="200">
<asp:Label ID="lblSiteCollectionUrl" runat="server" meta:resourcekey="lblSiteCollectionUrl" <asp:Label ID="lblSiteCollectionUrl" runat="server" meta:resourcekey="lblSiteCollectionUrl"
Text="Url:"></asp:Label> Text="Url:"></asp:Label>
</td> </td>
<td width="100%" class="NormalBold"> <td width="100%" class="NormalBold">
<wsp:DomainSelector id="domain" runat="server" ShowAt="false"/> <asp:TextBox ID="txtHostName" runat="server" CssClass="TextBox100" MaxLength="64"></asp:TextBox>.<uc1:DomainsSelectDomainControl ID="domain" runat="server" HideWebSites="true" HideDomainPointers="true" />
<asp:RequiredFieldValidator ID="valRequireHostName" runat="server" meta:resourcekey="valRequireHostName" ControlToValidate="txtHostName"
ErrorMessage="Enter hostname" ValidationGroup="CreateSite" Display="Dynamic" Text="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="valRequireCorrectHostName" runat="server"
ErrorMessage="Enter valid hostname" ControlToValidate="txtHostName" Display="Dynamic"
meta:resourcekey="valRequireCorrectHostName" ValidationExpression="^([0-9a-zA-Z])*[0-9a-zA-Z]+$" SetFocusOnError="True"></asp:RegularExpressionValidator>
</td> </td>
</tr> </tr>
<tr> <tr>

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -35,331 +35,378 @@ using WebsitePanel.Providers.DNS;
using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.SharePoint; using WebsitePanel.Providers.SharePoint;
namespace WebsitePanel.Portal namespace WebsitePanel.Portal
{ {
public partial class HostedSharePointEditSiteCollection : WebsitePanelModuleBase public partial class HostedSharePointEditSiteCollection : WebsitePanelModuleBase
{ {
SharePointSiteCollection item = null; SharePointSiteCollection item = null;
private int OrganizationId private int OrganizationId
{ {
get get
{ {
return PanelRequest.GetInt("ItemID"); return PanelRequest.GetInt("ItemID");
} }
} }
private int SiteCollectionId private int SiteCollectionId
{ {
get get
{ {
return PanelRequest.GetInt("SiteCollectionID"); return PanelRequest.GetInt("SiteCollectionID");
} }
} }
protected void Page_Load(object sender, EventArgs e)
{
domain.PackageId = PanelSecurity.PackageId;
protected void Page_Load(object sender, EventArgs e)
{
warningStorage.UnlimitedText = GetLocalizedString("WarningUnlimitedValue"); warningStorage.UnlimitedText = GetLocalizedString("WarningUnlimitedValue");
editWarningStorage.UnlimitedText = GetLocalizedString("WarningUnlimitedValue"); editWarningStorage.UnlimitedText = GetLocalizedString("WarningUnlimitedValue");
bool newItem = (this.SiteCollectionId == 0); bool newItem = (this.SiteCollectionId == 0);
tblEditItem.Visible = newItem; tblEditItem.Visible = newItem;
tblViewItem.Visible = !newItem; tblViewItem.Visible = !newItem;
//btnUpdate.Visible = newItem; //btnUpdate.Visible = newItem;
btnDelete.Visible = !newItem; btnDelete.Visible = !newItem;
btnUpdate.Text = newItem ? GetLocalizedString("Text.Add") : GetLocalizedString("Text.Update"); btnUpdate.Text = newItem ? GetLocalizedString("Text.Add") : GetLocalizedString("Text.Update");
btnUpdate.OnClientClick = newItem ? GetLocalizedString("btnCreate.OnClientClick") : GetLocalizedString("btnUpdate.OnClientClick"); btnUpdate.OnClientClick = newItem ? GetLocalizedString("btnCreate.OnClientClick") : GetLocalizedString("btnUpdate.OnClientClick");
btnBackup.Enabled = btnRestore.Enabled = !newItem; btnBackup.Enabled = btnRestore.Enabled = !newItem;
// bind item // bind item
BindItem(); BindItem();
//this.RegisterOwnerSelector(); }
}
private void BindItem() private void BindItem()
{ {
try try
{ {
if (!IsPostBack) if (!IsPostBack)
{ {
if (!this.IsDnsServiceAvailable()) if (!this.IsDnsServiceAvailable())
{ {
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_DNS"); localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_DNS");
} }
// load item if required // load item if required
if (this.SiteCollectionId > 0) if (this.SiteCollectionId > 0)
{ {
// existing item // existing item
item = ES.Services.HostedSharePointServers.GetSiteCollection(this.SiteCollectionId); item = ES.Services.HostedSharePointServers.GetSiteCollection(this.SiteCollectionId);
if (item != null) if (item != null)
{
// save package info
ViewState["PackageId"] = item.PackageId;
}
else
RedirectToBrowsePage();
}
else
{
// new item
ViewState["PackageId"] = PanelSecurity.PackageId;
}
//this.gvUsers.DataBind();
List<CultureInfo> cultures = new List<CultureInfo>();
foreach (int localeId in ES.Services.HostedSharePointServers.GetSupportedLanguages(PanelSecurity.PackageId))
{
cultures.Add(new CultureInfo(localeId, false));
}
this.ddlLocaleID.DataSource = cultures;
this.ddlLocaleID.DataBind();
}
if (!IsPostBack)
{
// bind item to controls
if (item != null)
{
// bind item to controls
lnkUrl.Text = item.PhysicalAddress;
lnkUrl.NavigateUrl = item.PhysicalAddress;
litSiteCollectionOwner.Text = String.Format("{0} ({1})", item.OwnerName, item.OwnerEmail);
litLocaleID.Text = new CultureInfo(item.LocaleId, false).DisplayName;
litTitle.Text = item.Title;
litDescription.Text = item.Description;
editWarningStorage.QuotaValue = (int)item.WarningStorage;
editMaxStorage.QuotaValue = (int)item.MaxSiteStorage;
}
Organization org = ES.Services.Organizations.GetOrganization(OrganizationId);
if (org != null)
{ {
maxStorage.ParentQuotaValue = org.MaxSharePointStorage; // save package info
maxStorage.QuotaValue = org.MaxSharePointStorage; ViewState["PackageId"] = item.PackageId;
editMaxStorage.ParentQuotaValue = org.MaxSharePointStorage;
warningStorage.ParentQuotaValue = org.WarningSharePointStorage;
warningStorage.QuotaValue = org.WarningSharePointStorage;
editWarningStorage.ParentQuotaValue = org.WarningSharePointStorage;
} }
else
} RedirectToBrowsePage();
OrganizationDomainName[] domains = ES.Services.Organizations.GetOrganizationDomains(PanelRequest.ItemID); }
else
{
// new item
ViewState["PackageId"] = PanelSecurity.PackageId;
if (UseSharedSLL(PanelSecurity.PackageId))
{
rowUrl.Visible = false;
valRequireHostName.Enabled = false;
valRequireCorrectHostName.Enabled = false;
}
}
//this.gvUsers.DataBind();
List<CultureInfo> cultures = new List<CultureInfo>();
foreach (int localeId in ES.Services.HostedSharePointServers.GetSupportedLanguages(PanelSecurity.PackageId))
{
cultures.Add(new CultureInfo(localeId, false));
}
this.ddlLocaleID.DataSource = cultures;
this.ddlLocaleID.DataBind();
}
if (!IsPostBack)
{
// bind item to controls
if (item != null)
{
// bind item to controls
lnkUrl.Text = item.PhysicalAddress;
lnkUrl.NavigateUrl = item.PhysicalAddress;
litSiteCollectionOwner.Text = String.Format("{0} ({1})", item.OwnerName, item.OwnerEmail);
litLocaleID.Text = new CultureInfo(item.LocaleId, false).DisplayName;
litTitle.Text = item.Title;
litDescription.Text = item.Description;
editWarningStorage.QuotaValue = (int)item.WarningStorage;
editMaxStorage.QuotaValue = (int)item.MaxSiteStorage;
}
Organization org = ES.Services.Organizations.GetOrganization(OrganizationId);
if (org != null)
{
maxStorage.ParentQuotaValue = org.MaxSharePointStorage;
maxStorage.QuotaValue = org.MaxSharePointStorage;
editMaxStorage.ParentQuotaValue = org.MaxSharePointStorage;
warningStorage.ParentQuotaValue = org.WarningSharePointStorage;
warningStorage.QuotaValue = org.WarningSharePointStorage;
editWarningStorage.ParentQuotaValue = org.WarningSharePointStorage;
}
}
//OrganizationDomainName[] domains = ES.Services.Organizations.GetOrganizationDomains(PanelRequest.ItemID);
//DomainInfo[] domains = ES.Services.Servers.GetMyDomains(PanelSecurity.PackageId);
EnterpriseServer.DomainInfo[] domains = ES.Services.Servers.GetDomains(PanelSecurity.PackageId);
if (domains.Length == 0)
{
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_DOMAINS");
DisableFormControls(this, btnCancel);
return;
}
//if (this.gvUsers.Rows.Count == 0)
//{
// localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_USERS");
// DisableFormControls(this, btnCancel);
// return;
//}
}
catch
{
if (domains.Length == 0)
{
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_DOMAINS");
DisableFormControls(this, btnCancel);
return;
}
//if (this.gvUsers.Rows.Count == 0)
//{
// localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_USERS");
// DisableFormControls(this, btnCancel);
// return;
//}
}
catch
{
localMessageBox.ShowWarningMessage("INIT_SERVICE_ITEM_FORM"); localMessageBox.ShowWarningMessage("INIT_SERVICE_ITEM_FORM");
DisableFormControls(this, btnCancel);
return;
}
}
private void SaveItem() DisableFormControls(this, btnCancel);
{ return;
if (!Page.IsValid) }
{ }
return;
}
private void SaveItem()
if (this.SiteCollectionId == 0) {
{ if (!Page.IsValid)
{
return;
}
if (this.SiteCollectionId == 0)
{
if (this.userSelector.GetAccount() == null) if (this.userSelector.GetAccount() == null)
{ {
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_USERS"); localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_NO_USERS");
return; return;
} }
// new item // new item
try try
{ {
SharePointSiteCollectionListPaged existentSiteCollections = ES.Services.HostedSharePointServers.GetSiteCollectionsPaged(PanelSecurity.PackageId, this.OrganizationId, "ItemName", String.Format("%{0}", this.domain.DomainName), String.Empty, 0, Int32.MaxValue); item = new SharePointSiteCollection();
foreach (SharePointSiteCollection existentSiteCollection in existentSiteCollections.SiteCollections)
{ if (!UseSharedSLL(PanelSecurity.PackageId))
Uri existentSiteCollectionUri = new Uri(existentSiteCollection.Name); {
if (existentSiteCollection.Name == String.Format("{0}://{1}", existentSiteCollectionUri.Scheme, this.domain.DomainName)) SharePointSiteCollectionListPaged existentSiteCollections = ES.Services.HostedSharePointServers.GetSiteCollectionsPaged(PanelSecurity.PackageId, this.OrganizationId, "ItemName", String.Format("%{0}", this.domain.DomainName), String.Empty, 0, Int32.MaxValue);
{ foreach (SharePointSiteCollection existentSiteCollection in existentSiteCollections.SiteCollections)
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_DOMAIN_IN_USE"); {
return; Uri existentSiteCollectionUri = new Uri(existentSiteCollection.Name);
} if (existentSiteCollection.Name == String.Format("{0}://{1}", existentSiteCollectionUri.Scheme, this.txtHostName.Text.ToLower() + "." + this.domain.DomainName))
} {
localMessageBox.ShowWarningMessage("HOSTEDSHAREPOINT_DOMAIN_IN_USE");
return;
}
}
item.Name = this.txtHostName.Text.ToLower() + "." + this.domain.DomainName;
}
else
item.Name = string.Empty;
// get form data
item.OrganizationId = this.OrganizationId;
item.Id = this.SiteCollectionId;
item.PackageId = PanelSecurity.PackageId;
item.LocaleId = Int32.Parse(this.ddlLocaleID.SelectedValue);
item.OwnerLogin = this.userSelector.GetSAMAccountName();
item.OwnerEmail = this.userSelector.GetPrimaryEmailAddress();
item.OwnerName = this.userSelector.GetDisplayName();
item.Title = txtTitle.Text;
item.Description = txtDescription.Text;
// get form data
item = new SharePointSiteCollection();
item.OrganizationId = this.OrganizationId;
item.Id = this.SiteCollectionId;
item.PackageId = PanelSecurity.PackageId;
item.Name = this.domain.DomainName;
item.LocaleId = Int32.Parse(this.ddlLocaleID.SelectedValue);
item.OwnerLogin = this.userSelector.GetAccount();
item.OwnerEmail = this.userSelector.GetPrimaryEmailAddress();
item.OwnerName = this.userSelector.GetDisplayName();
item.Title = txtTitle.Text;
item.Description = txtDescription.Text;
item.MaxSiteStorage = maxStorage.QuotaValue; item.MaxSiteStorage = maxStorage.QuotaValue;
item.WarningStorage = warningStorage.QuotaValue; item.WarningStorage = warningStorage.QuotaValue;
int result = ES.Services.HostedSharePointServers.AddSiteCollection(item); int result = ES.Services.HostedSharePointServers.AddSiteCollection(item);
if (result < 0) if (result < 0)
{ {
localMessageBox.ShowResultMessage(result); localMessageBox.ShowResultMessage(result);
return; return;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
localMessageBox.ShowErrorMessage("HOSTEDSHAREPOINT_ADD_SITECOLLECTION", ex); localMessageBox.ShowErrorMessage("HOSTEDSHAREPOINT_ADD_SITECOLLECTION", ex);
return; return;
} }
} }
else else
{ {
ES.Services.HostedSharePointServers.UpdateQuota(PanelRequest.ItemID, SiteCollectionId, editMaxStorage.QuotaValue, editWarningStorage.QuotaValue); ES.Services.HostedSharePointServers.UpdateQuota(PanelRequest.ItemID, SiteCollectionId, editMaxStorage.QuotaValue, editWarningStorage.QuotaValue);
} }
// return // return
RedirectToSiteCollectionsList(); RedirectToSiteCollectionsList();
} }
private void AddDnsRecord(int domainId, string recordName, string recordData) private void AddDnsRecord(int domainId, string recordName, string recordData)
{ {
int result = ES.Services.Servers.AddDnsZoneRecord(domainId, recordName, DnsRecordType.A, recordData, 0); int result = ES.Services.Servers.AddDnsZoneRecord(domainId, recordName, DnsRecordType.A, recordData, 0);
if (result < 0) if (result < 0)
{ {
ShowResultMessage(result); ShowResultMessage(result);
} }
} }
private bool IsDnsServiceAvailable() private bool IsDnsServiceAvailable()
{ {
ProviderInfo dnsProvider = ES.Services.Servers.GetPackageServiceProvider(PanelSecurity.PackageId, ResourceGroups.Dns); ProviderInfo dnsProvider = ES.Services.Servers.GetPackageServiceProvider(PanelSecurity.PackageId, ResourceGroups.Dns);
return dnsProvider != null; return dnsProvider != null;
} }
private void DeleteItem() private void DeleteItem()
{ {
// delete // delete
try try
{ {
int result = ES.Services.HostedSharePointServers.DeleteSiteCollection(this.SiteCollectionId); int result = ES.Services.HostedSharePointServers.DeleteSiteCollection(this.SiteCollectionId);
if (result < 0) if (result < 0)
{ {
ShowResultMessage(result); ShowResultMessage(result);
return; return;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
localMessageBox.ShowErrorMessage("HOSTEDSHAREPOINT_DELETE_SITECOLLECTION", ex); localMessageBox.ShowErrorMessage("HOSTEDSHAREPOINT_DELETE_SITECOLLECTION", ex);
return; return;
} }
// return // return
RedirectToSiteCollectionsList(); RedirectToSiteCollectionsList();
} }
protected void odsAccountsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e) protected void odsAccountsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{ {
if (e.Exception != null) if (e.Exception != null)
{ {
localMessageBox.ShowErrorMessage("ORGANIZATION_GET_USERS", e.Exception); localMessageBox.ShowErrorMessage("ORGANIZATION_GET_USERS", e.Exception);
e.ExceptionHandled = true; e.ExceptionHandled = true;
} }
} }
protected void btnCancel_Click(object sender, EventArgs e) protected void btnCancel_Click(object sender, EventArgs e)
{ {
// return // return
RedirectToSiteCollectionsList(); RedirectToSiteCollectionsList();
} }
protected void btnDelete_Click(object sender, EventArgs e) protected void btnDelete_Click(object sender, EventArgs e)
{ {
DeleteItem(); DeleteItem();
} }
protected void btnUpdate_Click(object sender, EventArgs e) protected void btnUpdate_Click(object sender, EventArgs e)
{ {
SaveItem(); SaveItem();
} }
protected void btnBackup_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_backup_sitecollection", "SiteCollectionID=" + this.SiteCollectionId,"ItemID=" + PanelRequest.ItemID.ToString()));
}
protected void btnRestore_Click(object sender, EventArgs e) protected void btnBackup_Click(object sender, EventArgs e)
{ {
Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_restore_sitecollection", "SiteCollectionID=" + this.SiteCollectionId, "ItemID=" + PanelRequest.ItemID.ToString())); Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_backup_sitecollection", "SiteCollectionID=" + this.SiteCollectionId, "ItemID=" + PanelRequest.ItemID.ToString()));
} }
protected void btnRestore_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_restore_sitecollection", "SiteCollectionID=" + this.SiteCollectionId, "ItemID=" + PanelRequest.ItemID.ToString()));
}
private void RedirectToSiteCollectionsList()
{
Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_sitecollections", "ItemID=" + PanelRequest.ItemID.ToString()));
}
//private void RegisterOwnerSelector() private void RedirectToSiteCollectionsList()
//{ {
// // Define the name and type of the client scripts on the page. Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "sharepoint_sitecollections", "ItemID=" + PanelRequest.ItemID.ToString()));
// String csname = "OwnerSelectorScript"; }
// Type cstype = this.GetType();
// // Get a ClientScriptManager reference from the Page class. private bool UseSharedSLL(int packageID)
// ClientScriptManager cs = Page.ClientScript; {
PackageContext cntx = ES.Services.Packages.GetPackageContext(PanelSecurity.PackageId);
if (cntx != null)
{
foreach (QuotaValueInfo quota in cntx.QuotasArray)
{
switch (quota.QuotaId)
{
case 400:
if (Convert.ToBoolean(quota.QuotaAllocatedValue))
{
return true;
}
// // Check to see if the client script is already registered. break;
// if (!cs.IsClientScriptBlockRegistered(cstype, csname)) }
// { }
// StringBuilder ownerSelector = new StringBuilder(); }
// ownerSelector.Append("<script type=text/javascript> function DoSelectOwner(ownerId, ownerDisplayName, email) {");
// ownerSelector.AppendFormat("{0}.{1}.value=ownerId;", this.Page.Form.ID, this.hdnSiteCollectionOwner.ClientID);
// ownerSelector.AppendFormat("{0}.{1}.value=ownerDisplayName;", this.Page.Form.ID, this.txtSiteCollectionOwner.ClientID);
// ownerSelector.AppendFormat("{0}.{1}.value=email;", this.Page.Form.ID, this.hdnSiteCollectionOwnerEmail.ClientID);
// ownerSelector.Append("} </script>");
// cs.RegisterClientScriptBlock(cstype, csname, ownerSelector.ToString(), false);
// }
//} return false;
}
//private StringDictionary ConvertArrayToDictionary(string[] settings)
//{ //private void RegisterOwnerSelector()
// StringDictionary r = new StringDictionary(); //{
// foreach (string setting in settings) // // Define the name and type of the client scripts on the page.
// { // String csname = "OwnerSelectorScript";
// int idx = setting.IndexOf('='); // Type cstype = this.GetType();
// r.Add(setting.Substring(0, idx), setting.Substring(idx + 1));
// } // // Get a ClientScriptManager reference from the Page class.
// return r; // ClientScriptManager cs = Page.ClientScript;
//}
} // // Check to see if the client script is already registered.
// if (!cs.IsClientScriptBlockRegistered(cstype, csname))
// {
// StringBuilder ownerSelector = new StringBuilder();
// ownerSelector.Append("<script type=text/javascript> function DoSelectOwner(ownerId, ownerDisplayName, email) {");
// ownerSelector.AppendFormat("{0}.{1}.value=ownerId;", this.Page.Form.ID, this.hdnSiteCollectionOwner.ClientID);
// ownerSelector.AppendFormat("{0}.{1}.value=ownerDisplayName;", this.Page.Form.ID, this.txtSiteCollectionOwner.ClientID);
// ownerSelector.AppendFormat("{0}.{1}.value=email;", this.Page.Form.ID, this.hdnSiteCollectionOwnerEmail.ClientID);
// ownerSelector.Append("} </script>");
// cs.RegisterClientScriptBlock(cstype, csname, ownerSelector.ToString(), false);
// }
//}
//private StringDictionary ConvertArrayToDictionary(string[] settings)
//{
// StringDictionary r = new StringDictionary();
// foreach (string setting in settings)
// {
// int idx = setting.IndexOf('=');
// r.Add(setting.Substring(0, idx), setting.Substring(idx + 1));
// }
// return r;
//}
}
} }

View file

@ -1,10 +1,9 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// This code was generated by a tool. // This code was generated by a tool.
// Runtime Version:2.0.50727.1433
// //
// Changes to this file may cause incorrect behavior and will be lost if // Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -76,6 +75,15 @@ namespace WebsitePanel.Portal {
/// </remarks> /// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable tblEditItem; protected global::System.Web.UI.HtmlControls.HtmlTable tblEditItem;
/// <summary>
/// rowUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow rowUrl;
/// <summary> /// <summary>
/// lblSiteCollectionUrl control. /// lblSiteCollectionUrl control.
/// </summary> /// </summary>
@ -85,6 +93,15 @@ namespace WebsitePanel.Portal {
/// </remarks> /// </remarks>
protected global::System.Web.UI.WebControls.Label lblSiteCollectionUrl; protected global::System.Web.UI.WebControls.Label lblSiteCollectionUrl;
/// <summary>
/// txtHostName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostName;
/// <summary> /// <summary>
/// domain control. /// domain control.
/// </summary> /// </summary>
@ -92,7 +109,25 @@ namespace WebsitePanel.Portal {
/// Auto-generated field. /// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file. /// To modify move field declaration from designer file to code-behind file.
/// </remarks> /// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.DomainSelector domain; protected global::WebsitePanel.Portal.DomainsSelectDomainControl domain;
/// <summary>
/// valRequireHostName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequireHostName;
/// <summary>
/// valRequireCorrectHostName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator valRequireCorrectHostName;
/// <summary> /// <summary>
/// lblSiteCollectionOwner control. /// lblSiteCollectionOwner control.

View file

@ -112,11 +112,14 @@
<value>2.0</value> <value>2.0</value>
</resheader> </resheader>
<resheader name="reader"> <resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="chkLocalHostFile" xml:space="preserve">
<value>Provision local hosts file</value>
</data>
<data name="lblBackupTempFolder.Text" xml:space="preserve"> <data name="lblBackupTempFolder.Text" xml:space="preserve">
<value>SharePoint Backup Temporary Folder:</value> <value>SharePoint Backup Temporary Folder:</value>
</data> </data>
@ -126,9 +129,15 @@
<data name="lblRootWebApplicationIpAddress.Text" xml:space="preserve"> <data name="lblRootWebApplicationIpAddress.Text" xml:space="preserve">
<value>SharePoint Web Application IP:</value> <value>SharePoint Web Application IP:</value>
</data> </data>
<data name="lblSharedSSLRoot.Text" xml:space="preserve">
<value>Shared SSL Root:</value>
</data>
<data name="lblSharePointBackup.Text" xml:space="preserve"> <data name="lblSharePointBackup.Text" xml:space="preserve">
<value>SharePoint Backup</value> <value>SharePoint Backup</value>
</data> </data>
<data name="lblWildCardRoot.Text" xml:space="preserve">
<value>Wildcard Certificate Root</value>
</data>
<data name="lclTempBackupNote.Text" xml:space="preserve"> <data name="lclTempBackupNote.Text" xml:space="preserve">
<value>Please note that WebsitePanel Server account should have access to this folder. Leave this field blank to use default path.</value> <value>Please note that WebsitePanel Server account should have access to this folder. Leave this field blank to use default path.</value>
</data> </data>

View file

@ -17,7 +17,21 @@
<td width="100%"> <td width="100%">
<wsp:SelectIPAddress ID="ddlRootWebApplicationIpAddress" runat="server" ServerIdParam="ServerID" AllowEmptySelection="false" /> <wsp:SelectIPAddress ID="ddlRootWebApplicationIpAddress" runat="server" ServerIdParam="ServerID" AllowEmptySelection="false" />
</td> </td>
</tr> </tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="chkLocalHostFile" runat="server" meta:resourcekey="chkLocalHostFile" Text="Provision localhost file" />
</td>
</tr>
<tr>
<td class="SubHead" width="200" nowrap>
<asp:Label ID="lblSharedSSLRoot" runat="server" meta:resourcekey="lblSharedSSLRoot" Text="Shared SSL Root:"></asp:Label>
</td>
<td width="100%">
<asp:TextBox ID="txtSharedSSLRoot" runat="server" CssClass="NormalTextBox" Width="200px"></asp:TextBox>
</td>
</tr>
</table> </table>
<fieldset> <fieldset>
@ -39,4 +53,5 @@
</table> </table>
</fieldset> </fieldset>
<br /> <br />

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -41,54 +41,61 @@ using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal.ProviderControls namespace WebsitePanel.Portal.ProviderControls
{ {
public partial class HostedSharePoint30_Settings : WebsitePanelControlBase, IHostingServiceProviderSettings public partial class HostedSharePoint30_Settings : WebsitePanelControlBase, IHostingServiceProviderSettings
{ {
protected void Page_Load(object sender, EventArgs e) protected void Page_Load(object sender, EventArgs e)
{ {
} }
public void BindSettings(StringDictionary settings) public void BindSettings(StringDictionary settings)
{ {
this.txtRootWebApplication.Text = settings["RootWebApplicationUri"]; this.txtRootWebApplication.Text = settings["RootWebApplicationUri"];
int selectedAddressid = this.FindAddressByText(settings["RootWebApplicationIpAddress"]); int selectedAddressid = this.FindAddressByText(settings["RootWebApplicationIpAddress"]);
this.ddlRootWebApplicationIpAddress.AddressId = (selectedAddressid > 0) ? selectedAddressid : 0; this.ddlRootWebApplicationIpAddress.AddressId = (selectedAddressid > 0) ? selectedAddressid : 0;
txtBackupTempFolder.Text = settings["BackupTemporaryFolder"]; chkLocalHostFile.Checked = Utils.ParseBool(settings["LocalHostFile"], false);
} this.txtSharedSSLRoot.Text = settings["SharedSSLRoot"];
}
public void SaveSettings(StringDictionary settings) public void SaveSettings(StringDictionary settings)
{ {
settings["RootWebApplicationUri"] = this.txtRootWebApplication.Text; settings["RootWebApplicationUri"] = this.txtRootWebApplication.Text;
settings["LocalHostFile"] = chkLocalHostFile.Checked.ToString();
settings["RootWebApplicationInteralIpAddress"] = String.Empty;
settings["SharedSSLRoot"] = this.txtSharedSSLRoot.Text;
if (ddlRootWebApplicationIpAddress.AddressId > 0) if (ddlRootWebApplicationIpAddress.AddressId > 0)
{ {
IPAddressInfo address = ES.Services.Servers.GetIPAddress(ddlRootWebApplicationIpAddress.AddressId); IPAddressInfo address = ES.Services.Servers.GetIPAddress(ddlRootWebApplicationIpAddress.AddressId);
if (String.IsNullOrEmpty(address.ExternalIP)) if (String.IsNullOrEmpty(address.ExternalIP))
{ {
settings["RootWebApplicationIpAddress"] = address.InternalIP; settings["RootWebApplicationIpAddress"] = address.InternalIP;
} }
else else
{ {
settings["RootWebApplicationIpAddress"] = address.ExternalIP; settings["RootWebApplicationIpAddress"] = address.ExternalIP;
} }
}
else
{
settings["RootWebApplicationIpAddress"] = String.Empty;
}
settings["BackupTemporaryFolder"] = txtBackupTempFolder.Text;
}
private int FindAddressByText(string address) if (!String.IsNullOrEmpty(address.InternalIP))
{ settings["RootWebApplicationInteralIpAddress"] = address.InternalIP;
foreach (IPAddressInfo addressInfo in ES.Services.Servers.GetIPAddresses(IPAddressPool.General, PanelRequest.ServerId)) }
{ else
if (addressInfo.InternalIP == address || addressInfo.ExternalIP == address) {
{ settings["RootWebApplicationIpAddress"] = String.Empty;
return addressInfo.AddressId; }
}
} }
return 0;
} private int FindAddressByText(string address)
} {
foreach (IPAddressInfo addressInfo in ES.Services.Servers.GetIPAddresses(IPAddressPool.General, PanelRequest.ServerId))
{
if (addressInfo.InternalIP == address || addressInfo.ExternalIP == address)
{
return addressInfo.AddressId;
}
}
return 0;
}
}
} }

View file

@ -1,10 +1,9 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// This code was generated by a tool. // This code was generated by a tool.
// Runtime Version:2.0.50727.1434
// //
// Changes to this file may cause incorrect behavior and will be lost if // Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -49,6 +48,33 @@ namespace WebsitePanel.Portal.ProviderControls {
/// </remarks> /// </remarks>
protected global::WebsitePanel.Portal.SelectIPAddress ddlRootWebApplicationIpAddress; protected global::WebsitePanel.Portal.SelectIPAddress ddlRootWebApplicationIpAddress;
/// <summary>
/// chkLocalHostFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkLocalHostFile;
/// <summary>
/// lblSharedSSLRoot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSharedSSLRoot;
/// <summary>
/// txtSharedSSLRoot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSharedSSLRoot;
/// <summary> /// <summary>
/// lblSharePointBackup control. /// lblSharePointBackup control.
/// </summary> /// </summary>

View file

@ -1,4 +1,4 @@
// Copyright (c) 2012, Outercurve Foundation. // Copyright (c) 2011, Outercurve Foundation.
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
@ -80,7 +80,7 @@ namespace WebsitePanel.Portal
? ParentQuotaValue ? ParentQuotaValue
: Math.Min(Utils.ParseInt(txtQuotaValue.Text, 0), ParentQuotaValue); : Math.Min(Utils.ParseInt(txtQuotaValue.Text, 0), ParentQuotaValue);
} }
} }
} }
set set
{ {
@ -108,10 +108,10 @@ namespace WebsitePanel.Portal
} }
get get
{ {
return ViewState["ParentQuotaValue"] != null ? (int) ViewState["ParentQuotaValue"] : 0; return ViewState["ParentQuotaValue"] != null ? (int)ViewState["ParentQuotaValue"] : 0;
} }
} }
protected void Page_Load(object sender, EventArgs e) protected void Page_Load(object sender, EventArgs e)
{ {
WriteScriptBlock(); WriteScriptBlock();
@ -122,19 +122,19 @@ namespace WebsitePanel.Portal
// set textbox attributes // set textbox attributes
txtQuotaValue.Style["display"] = (txtQuotaValue.Text == "-1") ? "none" : "inline"; txtQuotaValue.Style["display"] = (txtQuotaValue.Text == "-1") ? "none" : "inline";
chkQuotaUnlimited.Attributes["onclick"] = String.Format("ToggleQuota('{0}', '{1}');", chkQuotaUnlimited.Attributes["onclick"] = String.Format("ToggleQuota('{0}', '{1}');",
txtQuotaValue.ClientID, chkQuotaUnlimited.ClientID); txtQuotaValue.ClientID, chkQuotaUnlimited.ClientID);
// call base handler // call base handler
base.OnPreRender(e); base.OnPreRender(e);
} }
private void WriteScriptBlock() private void WriteScriptBlock()
{ {
string scriptKey = "QuataScript"; string scriptKey = "QuataScript";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey)) if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
{ {
Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, @"<script language='javascript' type='text/javascript'> Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, @"<script language='javascript' type='text/javascript'>
@ -146,7 +146,7 @@ namespace WebsitePanel.Portal
} }
</script>"); </script>");
} }
} }
} }
} }

View file

@ -1,10 +1,9 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// This code was generated by a tool. // This code was generated by a tool.
// Runtime Version:2.0.50727.3053
// //
// Changes to this file may cause incorrect behavior and will be lost if // Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------