This commit is contained in:
dev_amdtel 2013-08-10 00:52:34 +04:00
commit 3b6fe9c4bb
204 changed files with 23591 additions and 9818 deletions

View file

@ -1,69 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class CommentsController
{
public static DataSet GetComments(int userId, string itemTypeId, int itemId)
{
return DataProvider.GetComments(SecurityContext.User.UserId, userId, itemTypeId, itemId);
}
public static int AddComment(string itemTypeId, int itemId,
string commentText, int severityId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// add comment
DataProvider.AddComment(SecurityContext.User.UserId, itemTypeId,
itemId, commentText, severityId);
return 0;
}
public static int DeleteComment(int commentId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// delete comment
DataProvider.DeleteComment(SecurityContext.User.UserId, commentId);
return 0;
}
}
}

View file

@ -1,78 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Configuration;
using System.Web;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for ConfigSettings.
/// </summary>
public class ConfigSettings
{
public static string DataProviderType
{
get { return ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.DataProvider"]; }
}
public static string WebApplicationsPath
{
get
{
string path = ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.WebApplicationsPath"];
if (path.StartsWith("~") && HttpContext.Current != null)
path = HttpContext.Current.Server.MapPath(path);
return path;
}
}
public static string BackupsPath
{
get
{
SystemSettings settings = SystemController.GetSystemSettingsInternal(
SystemSettings.BACKUP_SETTINGS,
false
);
return settings["BackupsPath"];
}
}
#region Communication
public static int ServerRequestTimeout
{
get { return Utils.ParseInt(
ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.ServerRequestTimeout"], -1); }
}
#endregion
}
}

View file

@ -1,227 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using Microsoft.Win32;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for CryptoUtils.
/// </summary>
public class CryptoUtils
{
static string EnterpriseServerRegistryPath = "SOFTWARE\\WebsitePanel\\EnterpriseServer";
public static string CryptoKey
{
get
{
string Key = ConfigurationManager.AppSettings["WebsitePanel.AltCryptoKey"];
string value = string.Empty;
if (!string.IsNullOrEmpty(Key))
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(EnterpriseServerRegistryPath);
if (rk != null)
{
value = (string)rk.GetValue(Key, null);
rk.Close();
}
}
if (!string.IsNullOrEmpty(value))
return value;
else
return ConfigurationManager.AppSettings["WebsitePanel.CryptoKey"];
}
}
public static bool EncryptionEnabled
{
get
{
return (ConfigurationManager.AppSettings["WebsitePanel.EncryptionEnabled"] != null)
? Boolean.Parse(ConfigurationManager.AppSettings["WebsitePanel.EncryptionEnabled"]) : true;
}
}
public static string Encrypt(string InputText)
{
string Password = CryptoKey;
if(!EncryptionEnabled)
return InputText;
if (InputText == null)
return InputText;
// We are now going to create an instance of the
// Rihndael class.
RijndaelManaged RijndaelCipher = new RijndaelManaged();
// First we need to turn the input strings into a byte array.
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
// We are using salt to make it harder to guess our key
// using a dictionary attack.
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
// The (Secret Key) will be generated from the specified
// password and salt.
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a encryptor from the existing SecretKey bytes.
// We use 32 bytes for the secret key
// (the default Rijndael key length is 256 bit = 32 bytes) and
// then 16 bytes for the IV (initialization vector),
// (the default Rijndael IV length is 128 bit = 16 bytes)
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
// Create a MemoryStream that is going to hold the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Create a CryptoStream through which we are going to be processing our data.
// CryptoStreamMode.Write means that we are going to be writing data
// to the stream and the output will be written in the MemoryStream
// we have provided. (always use write mode for encryption)
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
// Start the encryption process.
cryptoStream.Write(PlainText, 0, PlainText.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memoryStream into a byte array.
byte[] CipherBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
// A common mistake would be to use an Encoding class for that.
// It does not work, because not all byte values can be
// represented by characters. We are going to be using Base64 encoding
// That is designed exactly for what we are trying to do.
string EncryptedData = Convert.ToBase64String(CipherBytes);
// Return encrypted string.
return EncryptedData;
}
public static string Decrypt(string InputText)
{
try
{
if(!EncryptionEnabled)
return InputText;
if (InputText == null || InputText == "")
return InputText;
string Password = CryptoKey;
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a decryptor from the existing SecretKey bytes.
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
// Create a CryptoStream. (always use Read mode for decryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold EncryptedData;
// DecryptedData is never longer than EncryptedData.
byte[] PlainText = new byte[EncryptedData.Length];
// Start decrypting.
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
// Return decrypted string.
return DecryptedData;
}
catch
{
return "";
}
}
public static string SHA1(string plainText)
{
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
HashAlgorithm hash = new SHA1Managed();;
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
// Return the result.
return Convert.ToBase64String(hashBytes);
}
}
}

View file

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

View file

@ -1,100 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.Principal;
namespace WebsitePanel.EnterpriseServer
{
public class EnterpriseServerPrincipal : IPrincipal
{
private int userId;
private int ownerId;
private bool isPeer;
private bool isDemo;
private UserStatus status;
private List<string> roles = new List<string>();
private IIdentity identity;
public EnterpriseServerPrincipal(IIdentity identity, string[] roles)
{
this.identity = identity;
this.roles.AddRange(roles);
}
#region IPrincipal Members
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
return roles.Contains(role);
}
#endregion
#region Public properties
public int UserId
{
get { return this.userId; }
set { this.userId = value; }
}
public int OwnerId
{
get { return this.ownerId; }
set { this.ownerId = value; }
}
public bool IsPeer
{
get { return this.isPeer; }
set { this.isPeer = value; }
}
public bool IsDemo
{
get { return this.isDemo; }
set { this.isDemo = value; }
}
public UserStatus Status
{
get { return this.status; }
set { this.status = value; }
}
#endregion
}
}

View file

@ -1,121 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections.Generic;
using Ionic.Zip;
namespace WebsitePanel.EnterpriseServer
{
public class FileUtils
{
#region Zip/Unzip Methods
public static void ZipFiles(string zipFile, string rootPath, string[] files)
{
using (ZipFile zip = new ZipFile())
{
//use unicode if necessary
zip.UseUnicodeAsNecessary = true;
//skip locked files
zip.ZipErrorAction = ZipErrorAction.Skip;
foreach (string file in files)
{
string fullPath = Path.Combine(rootPath, file);
if (Directory.Exists(fullPath))
{
//add directory with the same directory name
zip.AddDirectory(fullPath, file);
}
else if (File.Exists(fullPath))
{
//add file to the root folder
zip.AddFile(fullPath, "");
}
}
zip.Save(zipFile);
}
}
public static List<string> UnzipFiles(string zipFile, string destFolder)
{
using (ZipFile zip = ZipFile.Read(zipFile))
{
foreach (ZipEntry e in zip)
{
e.Extract(destFolder, ExtractExistingFileAction.OverwriteSilently);
}
}
// return extracted files names
return GetFileNames(destFolder);
}
#endregion
#region Helper Functions
/// <summary>
/// This function enumerates all directories and files of the <paramref name="direcrotyPath"/> specified.
/// </summary>
/// <param name="direcrotyPath">Path to the directory.</param>
/// <returns>
/// List of files and directories reside for the <paramref name="direcrotyPath"/> specified.
/// Empty, when no files and directories are or path does not exists.
/// </returns>
public static List<string> GetFileNames(string direcrotyPath)
{
List<string> items = new List<string>();
DirectoryInfo root = new DirectoryInfo(direcrotyPath);
if (root.Exists)
{
// list directories
foreach (DirectoryInfo dir in root.GetDirectories())
{
items.Add(
System.IO.Path.Combine(direcrotyPath, dir.Name)
);
}
// list files
foreach (FileInfo file in root.GetFiles())
{
items.Add(
System.IO.Path.Combine(direcrotyPath, file.Name)
);
}
}
return items;
}
#endregion
}
}

View file

@ -1,210 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebsitePanel.EnterpriseServer {
public struct IPAddress : IComparable {
public Int128 Address;
public bool V6 { get; private set; }
public bool V4 { get { return !V6 || Null; } }
public bool IsSubnet { get; private set; }
public bool IsMask { get; private set; }
public int Cidr { get; private set; }
public bool Null { get; private set; }
public IPAddress LastSubnetIP { get { return new IPAddress { Address = (Address | (~((Int128)0) >> (V4 ? Cidr + 64 : Cidr))), Cidr = V4 ? 32 : 128, IsSubnet = false, Null = false, V6 = V6 }; } }
public IPAddress FirstSubnetIP { get { return new IPAddress { Address = (Address & ~(~((Int128)0) >> (V4 ? Cidr + 64 : Cidr))) + 1, Cidr = V4 ? 32 : 128, IsSubnet = false, Null = false, V6 = V6 }; } }
public Int128 Mask { get { return IsSubnet ? Int128.MinValue >> (Cidr-1) : Address; } }
const int c = 256*256;
public static IPAddress Parse(string ip)
{
IPAddress adr = default(IPAddress);
adr.V6 = false;
if (String.IsNullOrEmpty(ip)) {
adr.Address = 0; adr.Null = true; adr.Cidr = 32; adr.IsSubnet = false;
return adr;
}
if (ip.Contains('/')) {
var tokens = ip.Split('/');
ip = tokens[0];
adr.IsSubnet = true;
adr.Cidr = Utils.ParseInt(tokens[1], -1);
}
if (string.IsNullOrWhiteSpace(ip)) {
adr.IsMask = true; adr.V6 = true;
adr.Address = adr.Mask;
} else {
var ipadr = System.Net.IPAddress.Parse(ip);
if (adr.V6 = ipadr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) {
byte[] bytes = ipadr.GetAddressBytes();
Int128 a = 0;
for (int i = 0; i < 16; i++) {
a = a * 256 + bytes[i];
}
adr.Address = a;
} else {
string[] parts = ip.Split('.');
adr.Address = (Int128)(Int32.Parse(parts[3]) +
(Int32.Parse(parts[2]) << 8) +
(Int32.Parse(parts[1]) << 16) +
(Int32.Parse(parts[0]) << 24));
}
}
if (adr.V4 && (adr.Cidr > 32 || 0 > adr.Cidr)) throw new ArgumentOutOfRangeException("Cidr must not be greater than 32 for IPv4 Addresses.");
if (adr.V6 && (adr.Cidr > 128 || 0 > adr.Cidr)) throw new ArgumentOutOfRangeException("Cidr must not be greater than 128 for IPv6 Addresses.");
return adr;
}
public override string ToString()
{
if (Null)
return "";
var s = new System.Text.StringBuilder();
if (!V6)
{
var ipl = Address;
if (IsMask)
{
int digits = 32 - Cidr;
ipl = (Int128.MaxValue << 1) | 0x1; // remove left sign bit
ipl = ipl << digits;
}
s.Append(String.Format("{0}.{1}.{2}.{3}", (ipl >> 24) & 0xFFL, (ipl >> 16) & 0xFFL, (ipl >> 8) & 0xFFL, (ipl & 0xFFL)));
}
else if (!IsMask)
{
var vals = new List<int>();
int i;
Int128 a = Address;
for (i = 0; i < 8; i++) {
vals.Add((int)(a % c));
a = a / c;
}
int index = -1, n = 0, m = 0;
for (i = 7; i >= 0; i--) {
if (vals[i] == 0) {
n++;
if (n > m) {
index = i;
m = n;
}
}
}
index += m-1;
i = 7;
while (i >= 0) {
if (i == index) {
if (m == 8) s.Append("::");
else s.Append(":");
i -= m;
}
if (i >= 0) {
if (i < 7) s.Append(":");
s.Append(vals[i].ToString("x"));
}
i--;
}
}
if (IsSubnet && !(IsMask && V4)) {
s.Append('/'); s.Append(Cidr.ToString());
}
return s.ToString();
}
public string ToV4MaskString() {
V6 = false;
IsMask = true;
return ToString();
}
public static bool operator ==(IPAddress a, IPAddress b) { return a.Address == b.Address && a.Null == b.Null && (a.Null || !(a.IsSubnet && b.IsSubnet || a.IsMask && b.IsMask) || a.Cidr == b.Cidr); }
public static bool operator ==(IPAddress a, long b) { return a.Address == b; }
public static bool operator !=(IPAddress a, IPAddress b) { return !(a == b); }
public static bool operator !=(IPAddress a, long b) { return a.Address != b; }
public static bool operator <(IPAddress a, IPAddress b) { return a.Address < b.Address; }
public static bool operator >(IPAddress a, IPAddress b) { return a.Address > b.Address; }
public static bool operator <=(IPAddress a, IPAddress b) { return a.Address <= b.Address; }
public static bool operator >=(IPAddress a, IPAddress b) { return a.Address >= b.Address; }
public override bool Equals(object obj)
{
if (obj is IPAddress)
{
var b = (IPAddress)obj;
return this.Address == b.Address && this.Null == b.Null && (this.Null || !(this.IsSubnet && b.IsSubnet || this.IsMask && b.IsMask) || this.Cidr == b.Cidr);
}
else if (obj is long)
{
var b = (long)obj;
return this.Address == b;
}
else
{
return false;
}
}
public override int GetHashCode()
{
return this.Address.GetHashCode();
}
/*
public static IPAddress operator +(IPAddress a, IPAddress b) {
if (a.IsSubnet || b.IsSubnet || a.V6 != b.V6) throw new ArgumentException("Arithmetic with subnets or mixed v4 & v6 addresses not supported.");
return new IPAddress { Address = a.Address + b.Address, Null = a.Null && b.Null, Cidr = 0, V6 = a.V6 };
}*/
public static Int128 operator -(IPAddress a, IPAddress b) {
if (a.IsSubnet || b.IsSubnet || a.V6 != b.V6) throw new ArgumentException("Arithmetic with subnets or mixed v4 & v6 addresses not supported.");
return a.Address - b.Address;
}
public static IPAddress operator +(IPAddress a, Int128 b) {
return new IPAddress { Address = a.Address + b, Null = a.Null, Cidr = a.V4 ? 32 : 128, V6 = a.V6 };
}
public static IPAddress operator -(IPAddress a, Int128 b) {
return new IPAddress { Address = a.Address - b, Null = a.Null, Cidr = a.V4 ? 32 : 128, V6 = a.V6 };
}
public static IPAddress operator |(IPAddress a, IPAddress b) {
if (a.V6 != b.V6) throw new ArgumentException("Arithmetic with mixed v4 & v6 addresses not supported.");
return new IPAddress { Address = a.Address | b.Address, Cidr = a.V4 ? 32 : 128, Null = false, V6 = a.V6, IsSubnet = false };
}
public static IPAddress operator &(IPAddress a, IPAddress b) {
if (a.V6 != b.V6) throw new ArgumentException("Arithmetic with mixed v4 & v6 addresses not supported.");
return new IPAddress { Address = a.Address & b.Address, Cidr = a.V4 ? 32 : 128, Null = false, V6 = a.V6, IsSubnet = false };
}
public static IPAddress operator ~(IPAddress a) {
if (a.Null) return new IPAddress { Address = 0, Null = true, Cidr = a.V4 ? 32 : 128, V6 = true, IsSubnet = false };
return new IPAddress { Address = ~a.Address, Cidr = a.Cidr , Null = false, V6 = a.V6, IsSubnet = false };
}
public static implicit operator IPAddress(NullIPAddress a) { return new IPAddress { Null = true, Address = 0, Cidr = -1 }; }
public int CompareTo(object obj)
{
var a = this.Address;
var b = ((IPAddress)obj).Address;
if (a < b)
return 1;
else if (a > b)
return -1;
else
return 0;
}
}
public class NullIPAddress { }
}

View file

@ -1,143 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace WebsitePanel.EnterpriseServer
{
public class MailHelper
{
public static int SendMessage(string from, string to, string subject, string body, bool isHtml)
{
return SendMessage(from, to, null, subject, body, MailPriority.Normal, isHtml);
}
public static int SendMessage(string from, string to, string bcc, string subject, string body, bool isHtml)
{
return SendMessage(from, to, bcc, subject, body, MailPriority.Normal, isHtml);
}
public static int SendMessage(string from, string to, string bcc, string subject, string body,
MailPriority priority, bool isHtml, Attachment[] attachments)
{
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
// load SMTP client settings
SystemSettings settings = SystemController.GetSystemSettingsInternal(
SystemSettings.SMTP_SETTINGS,
true
);
client.Host = settings["SmtpServer"];
client.Port = settings.GetInt("SmtpPort");
if (!String.IsNullOrEmpty(settings["SmtpUsername"]))
{
client.Credentials = new NetworkCredential(
settings["SmtpUsername"],
settings["SmtpPassword"]
);
}
if (!String.IsNullOrEmpty(settings["SmtpEnableSsl"]))
{
client.EnableSsl = Utils.ParseBool(settings["SmtpEnableSsl"], false);
}
// create message
MailMessage message = new MailMessage(from, to);
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = isHtml;
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
if (!String.IsNullOrEmpty(bcc))
message.Bcc.Add(bcc);
message.Priority = priority;
if (attachments != null)
{
foreach(Attachment current in attachments)
{
message.Attachments.Add(current);
}
}
// send message
try
{
client.Send(message);
return 0;
}
catch (SmtpException ex)
{
switch (ex.StatusCode)
{
case SmtpStatusCode.BadCommandSequence: return BusinessErrorCodes.SMTP_BAD_COMMAND_SEQUENCE;
case SmtpStatusCode.CannotVerifyUserWillAttemptDelivery: return BusinessErrorCodes.SMTP_CANNOT_VERIFY_USER_WILL_ATTEMPT_DELIVERY;
case SmtpStatusCode.ClientNotPermitted: return BusinessErrorCodes.SMTP_CLIENT_NOT_PERMITTED;
case SmtpStatusCode.CommandNotImplemented: return BusinessErrorCodes.SMTP_COMMAND_NOT_IMPLEMENTED;
case SmtpStatusCode.CommandParameterNotImplemented: return BusinessErrorCodes.SMTP_COMMAND_PARAMETER_NOT_IMPLEMENTED;
case SmtpStatusCode.CommandUnrecognized: return BusinessErrorCodes.SMTP_COMMAND_UNRECOGNIZED;
case SmtpStatusCode.ExceededStorageAllocation: return BusinessErrorCodes.SMTP_EXCEEDED_STORAGE_ALLOCATION;
case SmtpStatusCode.GeneralFailure: return BusinessErrorCodes.SMTP_GENERAL_FAILURE;
case SmtpStatusCode.InsufficientStorage: return BusinessErrorCodes.SMTP_INSUFFICIENT_STORAGE;
case SmtpStatusCode.LocalErrorInProcessing: return BusinessErrorCodes.SMTP_LOCAL_ERROR_IN_PROCESSING;
case SmtpStatusCode.MailboxBusy: return BusinessErrorCodes.SMTP_MAILBOX_BUSY;
case SmtpStatusCode.MailboxNameNotAllowed: return BusinessErrorCodes.SMTP_MAILBOX_NAME_NOTALLOWED;
case SmtpStatusCode.MailboxUnavailable: return BusinessErrorCodes.SMTP_MAILBOX_UNAVAILABLE;
case SmtpStatusCode.MustIssueStartTlsFirst: return BusinessErrorCodes.SMTP_MUST_ISSUE_START_TLS_FIRST;
case SmtpStatusCode.ServiceClosingTransmissionChannel: return BusinessErrorCodes.SMTP_SERVICE_CLOSING_TRANSMISSION_CHANNEL;
case SmtpStatusCode.ServiceNotAvailable: return BusinessErrorCodes.SMTP_SERVICE_NOT_AVAILABLE;
case SmtpStatusCode.SyntaxError: return BusinessErrorCodes.SMTP_SYNTAX_ERROR;
case SmtpStatusCode.TransactionFailed: return BusinessErrorCodes.SMTP_TRANSACTION_FAILED;
case SmtpStatusCode.UserNotLocalTryAlternatePath: return BusinessErrorCodes.SMTP_USER_NOT_LOCAL_TRY_ALTERNATE_PATH;
case SmtpStatusCode.UserNotLocalWillForward: return BusinessErrorCodes.SMTP_USER_NOT_LOCAL_WILL_FORWARD;
default: return BusinessErrorCodes.SMTP_UNKNOWN_ERROR;
}
}
finally
{
// Clean up.
message.Dispose();
}
}
public static int SendMessage(string from, string to, string bcc, string subject, string body,
MailPriority priority, bool isHtml)
{
return SendMessage(from, to, bcc, subject, body, priority, isHtml, null);
}
}
}

View file

@ -1,659 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Reflection;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.Providers;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for ObjectUtils.
/// </summary>
public class ObjectUtils
{
public static DT ConvertObject<ST, DT>(ST so)
{
Dictionary<string, PropertyInfo> sProps = GetTypePropertiesHash(typeof(ST));
Dictionary<string, PropertyInfo> dProps = GetTypePropertiesHash(typeof(DT));
DT dobj = (DT)Activator.CreateInstance(typeof(DT));
// copy properties
foreach (string propName in sProps.Keys)
{
if (dProps.ContainsKey(propName) && sProps[propName].Name != "Item")
{
if (sProps[propName].CanRead)
{
object val = sProps[propName].GetValue(so, null);
if (dProps[propName] != null)
{
if (val != null && dProps[propName].CanWrite)
{
dProps[propName].SetValue(dobj, val, null);
}
}
}
}
}
return dobj;
}
private static Hashtable typeProperties = new Hashtable();
public static Hashtable GetObjectProperties(object obj, bool persistentOnly)
{
Hashtable hash = new Hashtable();
Type type = obj.GetType();
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance
| BindingFlags.Public);
foreach (PropertyInfo prop in props)
{
// check for persistent attribute
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
if (!persistentOnly || (persistentOnly && attrs.Length > 0))
{
object val = prop.GetValue(obj, null);
string s = "";
if (val != null)
{
if (prop.PropertyType == typeof(string[]))
s = String.Join(";", (string[])val);
else if (prop.PropertyType == typeof(int[]))
{
int[] ivals = (int[])val;
string[] svals = new string[ivals.Length];
for (int i = 0; i < svals.Length; i++)
svals[i] = ivals[i].ToString();
s = String.Join(";", svals);
}
else
s = val.ToString();
}
// add property to hash
hash.Add(prop.Name, s);
}
}
return hash;
}
public static void FillCollectionFromDataSet<T>(List<T> list, DataSet ds)
{
if(ds.Tables.Count == 0)
return;
FillCollectionFromDataView<T>(list, ds.Tables[0].DefaultView);
}
public static void FillCollectionFromDataView<T>(List<T> list, DataView dv)
{
Type type = typeof(T);
PropertyInfo[] props = GetTypeProperties(type);
foreach(DataRowView dr in dv)
{
// create an instance
T obj = (T)Activator.CreateInstance(type);
list.Add(obj);
// fill properties
for(int i = 0; i < props.Length; i++)
{
string propName = props[i].Name;
if(dv.Table.Columns[propName] == null)
continue;
object propVal = dr[propName];
if(propVal == DBNull.Value)
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
else
{
try
{
// try implicit type conversion
props[i].SetValue(obj, propVal, null);
}
catch
{
// convert to string and then set property value
try
{
string strVal = propVal.ToString();
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
}
catch
{
// skip property init
}
}
}
} // for properties
} // for rows
}
public static List<T> CreateListFromDataReader<T>(IDataReader reader)
{
List<T> list = new List<T>();
FillCollectionFromDataReader<T>(list, reader);
return list;
}
public static List<T> CreateListFromDataSet<T>(DataSet ds)
{
List<T> list = new List<T>();
FillCollectionFromDataSet<T>(list, ds);
return list;
}
public static void FillCollectionFromDataReader<T>(List<T> list, IDataReader reader)
{
Type type = typeof(T);
try
{
// get type properties
PropertyInfo[] props = GetTypeProperties(type);
// iterate through reader
while(reader.Read())
{
T obj = (T)Activator.CreateInstance(type);
list.Add(obj);
// set properties
for(int i = 0; i < props.Length; i++)
{
string propName = props[i].Name;
try
{
object propVal = reader[propName];
if(propVal == DBNull.Value)
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
else
{
try
{
// try implicit type conversion
props[i].SetValue(obj, propVal, null);
}
catch
{
// convert to string and then set property value
try
{
string strVal = propVal.ToString();
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
}
catch
{
// skip property init
}
}
}
}
catch{} // just skip
} // for properties
}
}
finally
{
reader.Close();
}
}
public static T FillObjectFromDataView<T>(DataView dv)
{
Type type = typeof(T);
T obj = default(T);
// get type properties
PropertyInfo[] props = GetTypeProperties(type);
// iterate through reader
foreach(DataRowView dr in dv)
{
obj = (T)Activator.CreateInstance(type);
// set properties
for(int i = 0; i < props.Length; i++)
{
string propName = props[i].Name;
try
{
// verify if there is such a column
if (!dr.Row.Table.Columns.Contains(propName.ToLower()))
{
// if not, we move to another property
// because this one we cannot set
continue;
}
object propVal = dr[propName];
if(propVal == DBNull.Value)
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
else
{
try
{
string strVal = propVal.ToString();
//convert to DateTime
if (props[i].PropertyType.UnderlyingSystemType.FullName == typeof(DateTime).FullName)
{
DateTime date = DateTime.MinValue;
if (DateTime.TryParse(strVal, out date))
{
props[i].SetValue(obj, date, null);
}
}
else
{
//Convert generic
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
}
}
catch
{
// skip property init
}
}
}
catch{} // just skip
} // for properties
}
return obj;
}
public static T FillObjectFromDataReader<T>(IDataReader reader)
{
Type type = typeof(T);
T obj = default(T);
try
{
// get type properties
PropertyInfo[] props = GetTypeProperties(type);
// iterate through reader
while(reader.Read())
{
obj = (T)Activator.CreateInstance(type);
// set properties
for(int i = 0; i < props.Length; i++)
{
string propName = props[i].Name;
try
{
if (!IsColumnExists(propName, reader.GetSchemaTable()))
{
continue;
}
object propVal = reader[propName];
if(propVal == DBNull.Value)
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
else
{
try
{
//try string first
if (props[i].PropertyType.UnderlyingSystemType.FullName == typeof(String).FullName)
{
props[i].SetValue(obj, propVal.ToString(), null);
}
else
{
// then, try implicit type conversion
props[i].SetValue(obj, propVal, null);
}
}
catch
{
// convert to string and then set property value
try
{
string strVal = propVal.ToString();
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
}
catch
{
// skip property init
}
}
}
}
catch{} // just skip
} // for properties
}
}
finally
{
reader.Close();
}
return obj;
}
private static Hashtable propertiesCache = new Hashtable();
public static object CreateObjectFromDataview(Type type, DataView dv,
string nameColumn, string valueColumn, bool persistentOnly)
{
// create hash of properties from datareader
Hashtable propValues = new Hashtable();
foreach (DataRowView dr in dv)
{
if (propValues[dr[nameColumn]] == null && !propValues.ContainsKey(dr[nameColumn]))
propValues.Add(dr[nameColumn], dr[valueColumn]);
}
return CreateObjectFromHash(type, propValues, persistentOnly);
}
public static object CreateObjectFromDataReader(Type type, IDataReader reader,
string nameColumn, string valueColumn, bool persistentOnly)
{
// create hash of properties from datareader
Hashtable propValues = new Hashtable();
while (reader.Read())
{
if (propValues[reader[nameColumn]] == null)
propValues.Add(reader[nameColumn], reader[valueColumn]);
}
reader.Close();
return CreateObjectFromHash(type, propValues, persistentOnly);
}
public static object CreateObjectFromHash(Type type, Hashtable propValues, bool persistentOnly)
{
// create object
object obj = Activator.CreateInstance(type);
CreateObjectFromHash(obj, propValues, persistentOnly);
return obj;
}
public static void CopyPersistentPropertiesFromSource<T>(T source, T target)
where T : ServiceProviderItem
{
//
var typeSource = source.GetType();
var typeTarget = target.GetType();
// get all property infos
Hashtable props = null;
if (propertiesCache[typeSource.Name] != null)
{
// load properties from cache
props = (Hashtable)propertiesCache[typeSource.Name];
}
else
{
// create properties cache
props = new Hashtable();
//
PropertyInfo[] objProps = typeSource.GetProperties(BindingFlags.Instance
//| BindingFlags.DeclaredOnly
| BindingFlags.Public);
foreach (PropertyInfo prop in objProps)
{
// check for persistent attribute
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
// Persistent only
if (attrs.Length > 0)
{
// add property to hash
props.Add(prop.Name, prop);
}
}
// add to cache
propertiesCache.Add(typeSource.Name, props);
}
// Copy the data
foreach (PropertyInfo propertyInfo in props.Values)
{
propertyInfo.SetValue(target, propertyInfo.GetValue(source, null), null);
}
}
public static void CreateObjectFromHash(object obj, Hashtable propValues, bool persistentOnly)
{
Type type = obj.GetType();
// get all property infos
Hashtable props = null;
if (propertiesCache[type.Name] != null)
{
// load properties from cache
props = (Hashtable)propertiesCache[type.Name];
}
else
{
// create properties cache
props = new Hashtable();
PropertyInfo[] objProps = type.GetProperties(BindingFlags.Instance
//| BindingFlags.DeclaredOnly
| BindingFlags.Public);
foreach (PropertyInfo prop in objProps)
{
// check for persistent attribute
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
if (!persistentOnly || (persistentOnly && attrs.Length > 0) && !props.ContainsKey(prop.Name))
{
// add property to hash
props.Add(prop.Name, prop);
}
}
// add to cache
propertiesCache.Add(type.Name, props);
}
// fill properties
foreach (string propName in propValues.Keys)
{
// try to locate specified property
if (props[propName] != null)
{
// set property
// we support:
// String
// Int32
// Boolean
// Float
PropertyInfo prop = (PropertyInfo)props[propName];
string val = propValues[propName].ToString();
if (prop.PropertyType == typeof(String))
prop.SetValue(obj, val, null);
else if (prop.PropertyType == typeof(Int32))
prop.SetValue(obj, Int32.Parse(val), null);
else
if (prop.PropertyType == typeof(long))
prop.SetValue(obj, long.Parse(val), null);
else
if (prop.PropertyType == typeof(Boolean))
prop.SetValue(obj, Boolean.Parse(val), null);
else if (prop.PropertyType == typeof(Single))
prop.SetValue(obj, Single.Parse(val), null);
else if (prop.PropertyType.IsEnum)
prop.SetValue(obj, Enum.Parse(prop.PropertyType, val, true), null);
else
if (prop.PropertyType == typeof(Guid))
prop.SetValue(obj, new Guid(val), null);
else
if (prop.PropertyType == typeof(string[]))
{
if (val == "")
prop.SetValue(obj, new string[0], null);
else
prop.SetValue(obj, val.Split(';'), null);
}
else if (prop.PropertyType == typeof(int[]))
{
string[] svals = val.Split(';');
int[] ivals = new int[svals.Length];
for (int i = 0; i < svals.Length; i++)
ivals[i] = Int32.Parse(svals[i]);
if (val == "")
ivals = new int[0];
prop.SetValue(obj, ivals, null);
}
}
}
}
private static Dictionary<string, PropertyInfo> GetTypePropertiesHash(Type type)
{
Dictionary<string, PropertyInfo> hash = new Dictionary<string, PropertyInfo>();
PropertyInfo[] props = GetTypeProperties(type);
foreach (PropertyInfo prop in props)
hash.Add(prop.Name, prop);
return hash;
}
private static PropertyInfo[] GetTypeProperties(Type type)
{
string typeName = type.AssemblyQualifiedName;
if(typeProperties[typeName] != null)
return (PropertyInfo[])typeProperties[typeName];
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
typeProperties[typeName] = props;
return props;
}
public static object GetNull(Type type)
{
if(type == typeof(string))
return null;
if(type == typeof(Int32))
return 0;
if(type == typeof(Int64))
return 0;
if(type == typeof(Boolean))
return false;
if(type == typeof(Decimal))
return 0M;
else
return null;
}
public static object Cast(string val, Type type)
{
if(type == typeof(string))
return val;
if(type == typeof(Int32))
return Int32.Parse(val);
if(type == typeof(Int64))
return Int64.Parse(val);
if(type == typeof(Boolean))
return Boolean.Parse(val);
if(type == typeof(Decimal))
return Decimal.Parse(val);
if(type == typeof(string[]) && val != null)
{
return val.Split(';');
}
if (type.IsEnum)
return Enum.Parse(type, val, true);
if (type == typeof(int[]) && val != null)
{
string[] sarr = val.Split(';');
int[] iarr = new int[sarr.Length];
for (int i = 0; i < sarr.Length; i++)
iarr[i] = Int32.Parse(sarr[i]);
return iarr;
}
else
return val;
}
public static string GetTypeFullName(Type type)
{
return type.FullName + ", " + type.Assembly.GetName().Name;
}
#region Helper Functions
/// <summary>
/// This function is used to determine whether IDataReader contains a Column.
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <param name="schemaTable">The schema <see cref="DataTable"/> that decribes result-set <see cref="IDataReader"/> contains.</param>
/// <returns>True, when required column exists in the <paramref name="schemaTable"/>. Otherwise, false.</returns>
/// <remark>
/// The followin example shows how to look for the "Role" column in the <see cref="IDataReader"/>.
/// <example>
/// IDataReader reader = ....
/// if (!IsColumnExists("Role", reader.GetSchemaTable())
/// {
/// continue;
/// }
///
/// object roleValue = reader["Role"];
/// </example>
/// </remark>
static bool IsColumnExists(string columnName, DataTable schemaTable)
{
foreach (DataRow row in schemaTable.Rows)
{
if (String.Compare(row[0].ToString(), columnName, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
#endregion
}
}

View file

@ -1,249 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Web;
using WebsitePanel.Providers.Common;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Provides security utilities.
/// </summary>
public class SecurityContext
{
public const string ROLE_ADMINISTRATOR = "Administrator";
public const string ROLE_RESELLER = "Reseller";
public const string ROLE_USER = "User";
public const string ROLE_PLATFORMCSR = "PlatformCSR";
public const string ROLE_PLATFORMHELPDESK = "PlatformHelpdesk";
public const string ROLE_RESELLERCSR = "ResellerCSR";
public const string ROLE_RESELLERHELPDESK = "ResellerHelpdesk";
public const string CONTEXT_USER_INFO = "CONTEXT_USER_INFO";
public static void SetThreadPrincipal(int userId)
{
UserInfo user = UserController.GetUserInternally(userId);
if (user == null)
throw new Exception(String.Format("User '{0}' can not be loaded", userId));
SetThreadPrincipal(user);
}
public static void SetThreadPrincipal(UserInfo user)
{
// set roles array
List<string> roles = new List<string>();
roles.Add(SecurityContext.ROLE_USER);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
user.Role == UserRole.PlatformHelpdesk || user.Role == UserRole.ResellerHelpdesk)
roles.Add(SecurityContext.ROLE_RESELLERHELPDESK);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
user.Role == UserRole.PlatformCSR || user.Role == UserRole.ResellerCSR)
roles.Add(SecurityContext.ROLE_RESELLERCSR);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
user.Role == UserRole.PlatformHelpdesk)
roles.Add(SecurityContext.ROLE_PLATFORMHELPDESK);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
user.Role == UserRole.PlatformCSR)
roles.Add(SecurityContext.ROLE_PLATFORMCSR);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator)
roles.Add(SecurityContext.ROLE_RESELLER);
if (user.Role == UserRole.Administrator)
roles.Add(SecurityContext.ROLE_ADMINISTRATOR);
// create a new generic principal/identity and place them to context
EnterpriseServerIdentity identity = new EnterpriseServerIdentity(user.UserId.ToString());
EnterpriseServerPrincipal principal = new EnterpriseServerPrincipal(identity, roles.ToArray());
principal.UserId = user.UserId;
principal.OwnerId = user.OwnerId;
principal.IsPeer = user.IsPeer;
principal.IsDemo = user.IsDemo;
principal.Status = user.Status;
Thread.CurrentPrincipal = principal;
}
public static void SetThreadSupervisorPrincipal()
{
UserInfo user = new UserInfo();
user.UserId = -1;
user.OwnerId = 0;
user.IsPeer = false;
user.IsDemo = false;
user.Status = UserStatus.Active;
user.Role = UserRole.Administrator;
SetThreadPrincipal(user);
}
public static EnterpriseServerPrincipal User
{
get
{
EnterpriseServerPrincipal principal = Thread.CurrentPrincipal as EnterpriseServerPrincipal;
if(principal != null)
return principal;
// Username Token Manager was unable to set principal
// or authentication is disabled
// create supervisor principal
SetThreadSupervisorPrincipal();
return (EnterpriseServerPrincipal)Thread.CurrentPrincipal;
}
}
public static bool CheckAccount(ResultObject res, DemandAccount demand)
{
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
res.ErrorCodes.Add(BusinessErrorCodes.ToText(accountCheck));
return false;
}
return true;
}
public static int CheckAccount(DemandAccount demand)
{
if ((demand & DemandAccount.NotDemo) == DemandAccount.NotDemo)
{
// should make a check if the account is not in demo mode
if (User.IsDemo)
return BusinessErrorCodes.ERROR_USER_ACCOUNT_DEMO;
}
if ((demand & DemandAccount.IsActive) == DemandAccount.IsActive)
{
// check is the account is active
if (User.Status == UserStatus.Pending)
return BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING;
else if (User.Status == UserStatus.Suspended)
return BusinessErrorCodes.ERROR_USER_ACCOUNT_SUSPENDED;
else if (User.Status == UserStatus.Cancelled)
return BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED;
}
if ((demand & DemandAccount.IsAdmin) == DemandAccount.IsAdmin)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_ADMINISTRATOR))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_SHOULD_BE_ADMINISTRATOR;
}
if ((demand & DemandAccount.IsReseller) == DemandAccount.IsReseller)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_RESELLER))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
}
if ((demand & DemandAccount.IsPlatformCSR) == DemandAccount.IsPlatformCSR)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_PLATFORMCSR))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
}
if ((demand & DemandAccount.IsPlatformHelpdesk) == DemandAccount.IsPlatformHelpdesk)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_PLATFORMHELPDESK))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
}
if ((demand & DemandAccount.IsResellerHelpdesk) == DemandAccount.IsResellerHelpdesk)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_RESELLERHELPDESK))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
}
if ((demand & DemandAccount.IsResellerCSR) == DemandAccount.IsResellerCSR)
{
// should make a check if the account has Admin role
if (!User.IsInRole(ROLE_RESELLERCSR))
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
}
return 0;
}
public static bool CheckPackage(ResultObject res, int packageId, DemandPackage demand)
{
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
if (packageCheck < 0)
{
res.ErrorCodes.Add(BusinessErrorCodes.ToText(packageCheck));
return false;
}
return true;
}
public static int CheckPackage(int packageId, DemandPackage demand)
{
// load package
PackageInfo package = PackageController.GetPackage(packageId);
if (package == null)
return BusinessErrorCodes.ERROR_PACKAGE_NOT_FOUND;
return CheckPackage(package, demand);
}
public static int CheckPackage(PackageInfo package, DemandPackage demand)
{
if ((demand & DemandPackage.IsActive) == DemandPackage.IsActive)
{
// should make a check if the package is active
if (package.StatusId == (int)PackageStatus.Cancelled)
return BusinessErrorCodes.ERROR_PACKAGE_CANCELLED;
else if (package.StatusId == (int)PackageStatus.Suspended)
return BusinessErrorCodes.ERROR_PACKAGE_SUSPENDED;
}
return 0;
}
}
}

View file

@ -1,119 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.DirectoryServices;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Services3;
using WebsitePanel.Server.Client;
namespace WebsitePanel.EnterpriseServer
{
public class ServiceProviderProxy
{
public static WebServicesClientProtocol Init(WebServicesClientProtocol proxy, int serviceId)
{
ServerProxyConfigurator cnfg = new ServerProxyConfigurator();
// get service
ServiceInfo service = ServerController.GetServiceInfo(serviceId);
if (service == null)
throw new Exception(String.Format("Service with ID {0} was not found", serviceId));
// set service settings
StringDictionary serviceSettings = ServerController.GetServiceSettings(serviceId);
foreach (string key in serviceSettings.Keys)
cnfg.ProviderSettings.Settings[key] = serviceSettings[key];
// get provider
ProviderInfo provider = ServerController.GetProvider(service.ProviderId);
cnfg.ProviderSettings.ProviderGroupID = provider.GroupId;
cnfg.ProviderSettings.ProviderCode = provider.ProviderName;
cnfg.ProviderSettings.ProviderName = provider.DisplayName;
cnfg.ProviderSettings.ProviderType = provider.ProviderType;
// init service on the server level
return ServerInit(proxy, cnfg, service.ServerId);
}
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy, ServerProxyConfigurator cnfg, int serverId)
{
// get server info
ServerInfo server = ServerController.GetServerByIdInternal(serverId);
if (server == null)
throw new Exception(String.Format("Server with ID {0} was not found", serverId));
// set AD integration settings
cnfg.ServerSettings.ADEnabled = server.ADEnabled;
cnfg.ServerSettings.ADAuthenticationType = AuthenticationTypes.Secure;
try
{
cnfg.ServerSettings.ADAuthenticationType = (AuthenticationTypes)Enum.Parse(typeof(AuthenticationTypes), server.ADAuthenticationType, true);
}
catch { /* ignore */ }
cnfg.ServerSettings.ADRootDomain = server.ADRootDomain;
cnfg.ServerSettings.ADUsername = server.ADUsername;
cnfg.ServerSettings.ADPassword = server.ADPassword;
// set timeout
cnfg.Timeout = ConfigSettings.ServerRequestTimeout;
return ServerInit(proxy, cnfg, server.ServerUrl, server.Password);
}
private static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy,
ServerProxyConfigurator cnfg, string serverUrl, string serverPassword)
{
// set URL & password
cnfg.ServerUrl = serverUrl;
cnfg.ServerPassword = serverPassword;
// configure proxy!
cnfg.Configure(proxy);
return proxy;
}
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy,
string serverUrl, string serverPassword)
{
return ServerInit(proxy, new ServerProxyConfigurator(), serverUrl, serverPassword);
}
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy, int serverId)
{
return ServerInit(proxy, new ServerProxyConfigurator(), serverId);
}
}
}

View file

@ -1,81 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Threading;
using System.Web;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3.Security.Tokens;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for UsernameTokenManager.
/// </summary>
public class ServiceUsernameTokenManager : UsernameTokenManager
{
/// <summary>
/// Constructs an instance of this security token manager.
/// </summary>
public ServiceUsernameTokenManager()
{
}
/// <summary>
/// Constructs an instance of this security token manager.
/// </summary>
/// <param name="nodes">An XmlNodeList containing XML elements from a configuration file.</param>
public ServiceUsernameTokenManager(XmlNodeList nodes)
: base(nodes)
{
}
/// <summary>
/// Returns the password or password equivalent for the username provided.
/// </summary>
/// <param name="token">The username token</param>
/// <returns>The password (or password equivalent) for the username</returns>
protected override string AuthenticateToken(UsernameToken token)
{
// try to load user account
UserInfo user = UserController.GetUserInternally(token.Username);
if (user == null)
return null;
SecurityContext.SetThreadPrincipal(user);
return user.Password;
}
}
}

View file

@ -1,407 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WSE = Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3.Security.Tokens;
namespace WebsitePanel.EnterpriseServer
{
public class UsernameAssertion : SecurityPolicyAssertion
{
#region Public properties
private bool signRequest = true;
public bool SignRequest
{
get { return signRequest; }
set { signRequest = value; }
}
private bool encryptRequest = true;
public bool EncryptRequest
{
get { return encryptRequest; }
set { encryptRequest = value; }
}
private int serverId = 0;
public int ServerId
{
get { return serverId; }
set { serverId = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
#endregion
public UsernameAssertion()
{
}
public UsernameAssertion(int serverId, string password)
{
this.serverId = serverId;
this.password = password;
}
public override SoapFilter CreateServiceInputFilter(FilterCreationContext context)
{
return new ServiceInputFilter(this, context);
}
public override SoapFilter CreateServiceOutputFilter(FilterCreationContext context)
{
return null;
}
public override SoapFilter CreateClientInputFilter(FilterCreationContext context)
{
return null;
}
public override SoapFilter CreateClientOutputFilter(FilterCreationContext context)
{
return new ClientOutputFilter(this, context);
}
public override void ReadXml(XmlReader reader, IDictionary<string, Type> extensions)
{
if (reader == null)
throw new ArgumentNullException("reader");
if (extensions == null)
throw new ArgumentNullException("extensions");
// find the current extension
string tagName = null;
foreach (string extName in extensions.Keys)
{
if (extensions[extName] == typeof(UsernameAssertion))
{
tagName = extName;
break;
}
}
// read the first element (maybe empty)
reader.ReadStartElement(tagName);
}
public override void WriteXml(XmlWriter writer)
{
// Typically this is not needed for custom policies
}
#region ServiceInputFilter
public class ServiceInputFilter : ReceiveSecurityFilter
{
UsernameAssertion parentAssertion;
FilterCreationContext filterContext;
public ServiceInputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
{
this.parentAssertion = parentAssertion;
this.filterContext = filterContext;
}
public override void ValidateMessageSecurity(SoapEnvelope envelope, WSE.Security security)
{
if (security != null)
ProcessWSERequest(envelope, security);
//else if (envelope.Header != null)
// ProcessSoapRequest(envelope);
else// if (HttpContext.Current.Request.Headers["Authorization"] != null)
ProcessBasicAuthRequest();
}
private void ProcessBasicAuthRequest()
{
string authStr = HttpContext.Current.Request.Headers["Authorization"];
if (authStr == null || authStr.Length == 0)
{
// No credentials; anonymous request
DenyAccess();
return;
}
authStr = authStr.Trim();
if (authStr.IndexOf("Basic", 0) != 0)
{
// Don't understand this header...we'll pass it along and
// assume someone else will handle it
DenyAccess();
return;
}
string encodedCredentials = authStr.Substring(6);
byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);
string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
UserInfo user = UserController.GetUserByUsernamePassword(
username, password, System.Web.HttpContext.Current.Request.UserHostAddress);
if (user == null)
{
// Invalid credentials; deny access
DenyAccess();
return;
//throw new Exception("Wrong BASIC credentials have been supplied");
}
SecurityContext.SetThreadPrincipal(user);
}
private void DenyAccess()
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.StatusCode = 401;
response.StatusDescription = "Access Denied";
response.Write("401 Access Denied");
string realm = "WebsitePanel Enterprise Server";
string val = String.Format("Basic Realm=\"{0}\"", realm);
response.AppendHeader("WWW-Authenticate", val);
response.End();
}
private void ProcessSoapRequest(SoapEnvelope envelope)
{
XmlNode authNode = envelope.Header.SelectSingleNode("Authentication");
if (authNode == null)
throw new Exception("Couldn't find authentication token specified");
XmlNode userNode = authNode.SelectSingleNode("Username");
XmlNode passwordNode = authNode.SelectSingleNode("Password");
if (userNode == null || passwordNode == null)
throw new Exception("Authentication token is invalid or broken");
UserInfo user = UserController.GetUserByUsernamePassword(
userNode.InnerText,
passwordNode.InnerText,
System.Web.HttpContext.Current.Request.UserHostAddress
);
if (user == null)
throw new Exception("Authentication token is invalid or broken");
SecurityContext.SetThreadPrincipal(user);
}
private void ProcessWSERequest(SoapEnvelope envelope, WSE.Security security)
{
// by default we consider that SOAP messages is not signed
bool IsSigned = false;
// if security element is null
// the call is made not from WSE-enabled client
if (security != null)
{
foreach (ISecurityElement element in security.Elements)
{
if (element is MessageSignature)
{
// The given context contains a Signature element.
MessageSignature sign = element as MessageSignature;
if (CheckSignature(envelope, security, sign))
{
// The SOAP message is signed.
if (sign.SigningToken is UsernameToken)
{
UsernameToken token = sign.SigningToken as UsernameToken;
// The SOAP message is signed
// with a UsernameToken.
IsSigned = true;
}
}
}
}
}
// throw an exception if the message did not pass all the tests
if (!IsSigned)
throw new SecurityFault("SOAP response should be signed.");
// check encryption
bool IsEncrypted = false;
foreach (ISecurityElement element in security.Elements)
{
if (element is EncryptedData)
{
EncryptedData encryptedData = element as EncryptedData;
System.Xml.XmlElement targetElement = encryptedData.TargetElement;
if (SoapHelper.IsBodyElement(targetElement))
{
// The given SOAP message has the Body element Encrypted.
IsEncrypted = true;
}
}
}
if (!IsEncrypted)
throw new SecurityFault("SOAP response should be encrypted.");
}
private bool CheckSignature(SoapEnvelope envelope, WSE.Security security, MessageSignature signature)
{
//
// Now verify which parts of the message were actually signed.
//
SignatureOptions actualOptions = signature.SignatureOptions;
SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;
if (security != null && security.Timestamp != null)
expectedOptions |= SignatureOptions.IncludeTimestamp;
//
// The <Action> and <To> are required addressing elements.
//
expectedOptions |= SignatureOptions.IncludeAction;
expectedOptions |= SignatureOptions.IncludeTo;
if (envelope.Context.Addressing.FaultTo != null && envelope.Context.Addressing.FaultTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeFaultTo;
if (envelope.Context.Addressing.From != null && envelope.Context.Addressing.From.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeFrom;
if (envelope.Context.Addressing.MessageID != null && envelope.Context.Addressing.MessageID.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeMessageId;
if (envelope.Context.Addressing.RelatesTo != null && envelope.Context.Addressing.RelatesTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeRelatesTo;
if (envelope.Context.Addressing.ReplyTo != null && envelope.Context.Addressing.ReplyTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeReplyTo;
//
// Check if the all the expected options are the present.
//
return ((expectedOptions & actualOptions) == expectedOptions);
}
}
#endregion
#region ClientOutputFilter
public class ClientOutputFilter : SendSecurityFilter
{
UsernameAssertion parentAssertion;
FilterCreationContext filterContext;
public ClientOutputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
{
this.parentAssertion = parentAssertion;
this.filterContext = filterContext;
}
public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
{
// get server password from database
string password = parentAssertion.Password;
if (password == null)
return;
// hash password
password = CryptoUtils.SHA1(password);
// create username token
UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
PasswordOption.SendNone);
if (parentAssertion.signRequest || parentAssertion.encryptRequest)
{
// Add the token to the SOAP header.
security.Tokens.Add(userToken);
}
if (parentAssertion.signRequest)
{
// Sign the SOAP message by using the UsernameToken.
MessageSignature sig = new MessageSignature(userToken);
security.Elements.Add(sig);
}
if (parentAssertion.encryptRequest)
{
// we don't return any custom SOAP headers
// so, just encrypt a message Body
EncryptedData data = new EncryptedData(userToken);
// encrypt custom headers
for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
{
XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;
// find all SecureSoapHeader headers marked with a special attribute
if (child != null && child.NamespaceURI == "http://com/websitepanel/server/")
{
// create ID attribute for referencing purposes
string id = Guid.NewGuid().ToString();
child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);
// Create an encryption reference for the custom SOAP header.
data.AddReference(new EncryptionReference("#" + id));
}
}
security.Elements.Add(data);
}
}
}
#endregion
}
}

View file

@ -1,173 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Web;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for Utils.
/// </summary>
public class Utils
{
public static int ParseInt(string val, int defaultValue)
{
int result = defaultValue;
try { result = Int32.Parse(val); }
catch { /* do nothing */ }
return result;
}
public static bool ParseBool(object val, bool defaultValue)
{
bool result = defaultValue;
try { result = Boolean.Parse(val.ToString()); }
catch { /* do nothing */ }
return result;
}
public static bool ParseBool(string val, bool defaultValue)
{
bool result = defaultValue;
try { result = Boolean.Parse(val); }
catch { /* do nothing */ }
return result;
}
public static decimal ParseDecimal(string val, decimal defaultValue)
{
decimal result = defaultValue;
try { result = Decimal.Parse(val); }
catch { /* do nothing */ }
return result;
}
public static string[] ParseDelimitedString(string str, params char[] delimiter)
{
if (String.IsNullOrEmpty(str))
return new string[] { };
string[] parts = str.Split(delimiter);
ArrayList list = new ArrayList();
foreach (string part in parts)
if (part.Trim() != "" && !list.Contains(part.Trim()))
list.Add(part);
return (string[])list.ToArray(typeof(string));
}
public static string ReplaceStringVariable(string str, string variable, string value)
{
return ReplaceStringVariable(str, variable, value, false);
}
public static string ReplaceStringVariable(string str, string variable, string value, bool allowEmptyValue)
{
if (allowEmptyValue)
{
if (String.IsNullOrEmpty(str)) return str;
}
else
{
if (String.IsNullOrEmpty(str) || String.IsNullOrEmpty(value))
return str;
}
Regex re = new Regex("\\[" + variable + "\\]+", RegexOptions.IgnoreCase);
return re.Replace(str, value);
}
public static string CleanIdentifier(string str)
{
if (String.IsNullOrEmpty(str))
return str;
return Regex.Replace(str, "\\W", "_");
}
public static string GetRandomHexString(int length)
{
byte[] buf = new byte[length];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(buf);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++)
sb.AppendFormat("{0:X2}", buf[i]);
return sb.ToString();
}
public static string GetRandomString(int length)
{
string ptrn = "abcdefghjklmnpqrstwxyzABCDEFGHJKLMNPQRSTWXYZ0123456789";
StringBuilder sb = new StringBuilder();
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = (randomBytes[0] & 0x7f) << 24 |
randomBytes[1] << 16 |
randomBytes[2] << 8 |
randomBytes[3];
Random rnd = new Random(seed);
for (int i = 0; i < length; i++)
sb.Append(ptrn[rnd.Next(ptrn.Length - 1)]);
return sb.ToString();
}
public static DateTime ParseDate(object value)
{
try
{
return (DateTime) value;
}
catch(Exception )
{
return DateTime.MinValue;
}
}
}
}

View file

@ -1,987 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Database;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.EnterpriseServer
{
public class DatabaseServerController : IImportController, IBackupController
{
private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB
public static DatabaseServer GetDatabaseServer(int serviceId)
{
DatabaseServer db = new DatabaseServer();
ServiceProviderProxy.Init(db, serviceId);
return db;
}
#region Databases
public static DataSet GetRawSqlDatabasesPaged(int packageId,
string groupName, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return PackageController.GetRawPackageItemsPaged(packageId, groupName, typeof(SqlDatabase),
true, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<SqlDatabase> GetSqlDatabases(int packageId, string groupName, bool recursive)
{
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(
packageId, groupName, typeof(SqlDatabase), recursive);
return items.ConvertAll<SqlDatabase>(
new Converter<ServiceProviderItem, SqlDatabase>(ConvertItemToSqlDatabase));
}
private static SqlDatabase ConvertItemToSqlDatabase(ServiceProviderItem item)
{
return (SqlDatabase)item;
}
public static SqlDatabase GetSqlDatabase(int itemId)
{
// load meta item
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItem(itemId);
// load service item
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
SqlDatabase database = sql.GetDatabase(item.Name);
if (database == null)
return item;
// add common properties
database.Id = item.Id;
database.PackageId = item.PackageId;
database.ServiceId = item.ServiceId;
database.GroupName = item.GroupName;
StringDictionary settings = ServerController.GetServiceSettings(item.ServiceId);
if (settings["InternalAddress"] != null) database.InternalServerName = settings["InternalAddress"];
if (settings["ExternalAddress"] != null) database.ExternalServerName = settings["ExternalAddress"];
return database;
}
public static int AddSqlDatabase(SqlDatabase item, string groupName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check quota
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, groupName + ".Databases");
if (quota.QuotaExhausted)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_RESOURCE_QUOTA_LIMIT;
// check if mail resource is available
int serviceId = PackageController.GetPackageServiceId(item.PackageId, groupName);
if (serviceId == 0)
return BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE;
// check package items
if (PackageController.GetPackageItemByName(item.PackageId, groupName, item.Name, typeof(SqlDatabase)) != null)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_EXISTS;
// place log record
TaskManager.StartTask("SQL_DATABASE", "ADD", item.Name);
TaskManager.WriteParameter("Provider", groupName);
int itemId = default(int);
//
try
{
// check service items
DatabaseServer sql = GetDatabaseServer(serviceId);
if (sql.DatabaseExists(item.Name))
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_SERVICE_ITEM_EXISTS;
// calculate database location
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
UserInfo user = PackageController.GetPackageOwner(item.PackageId);
if (settings["UseDefaultDatabaseLocation"] != null &&
!Utils.ParseBool(settings["UseDefaultDatabaseLocation"], false))
{
item.Location = Utils.ReplaceStringVariable(settings["DatabaseLocation"], "user_name", user.Username);
}
// set database size
item.DataSize = GetMaxDatabaseSize(item.PackageId, groupName);
// set log size
item.LogSize = GetMaxLogSize(item.PackageId, groupName);
// add service item
sql.CreateDatabase(item);
// save item
item.ServiceId = serviceId;
itemId = PackageController.AddPackageItem(item);
TaskManager.ItemId = itemId;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
//
if (ex.Message.Contains("INVALID_DATABASE_NAME"))
return BusinessErrorCodes.ERROR_MYSQL_INVALID_DATABASE_NAME;
// Return a generic error instead of default(int)
itemId = BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
return itemId;
}
public static int UpdateSqlDatabase(SqlDatabase item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlDatabase origItem = (SqlDatabase)PackageController.GetPackageItem(item.Id);
if (origItem == null)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("SQL_DATABASE", "UPDATE", origItem.Name);
TaskManager.ItemId = item.Id;
TaskManager.WriteParameter("Provider", origItem.GroupName);
try
{
// get service
DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);
// update service item
sql.UpdateDatabase(item);
return 0;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
// Return a generic error instead of re-throwing an exception
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int DeleteSqlDatabase(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlDatabase origItem = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("SQL_DATABASE", "DELETE", origItem.Name);
TaskManager.ItemId = itemId;
TaskManager.WriteParameter("Provider", origItem.GroupName);
try
{
// get service
DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);
// delete service item
sql.DeleteDatabase(origItem.Name);
// delete meta item
PackageController.DeletePackageItem(origItem.Id);
return 0;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
// Return a generic error instead of re-throwing an exception
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
}
private static int GetMaxSize(int packageId, string groupName, string prefix)
{
// load package context
int maxSize = 0; // unlimited
string quotaName = groupName + prefix;
PackageContext cntx = PackageController.GetPackageContext(packageId);
if (cntx != null && cntx.Quotas.ContainsKey(quotaName))
{
maxSize = cntx.Quotas[quotaName].QuotaAllocatedValue;
if (maxSize == -1)
maxSize = 0;
}
return maxSize;
}
private static int GetMaxDatabaseSize(int packageId, string groupName)
{
return GetMaxSize(packageId, groupName, ".MaxDatabaseSize");
}
private static int GetMaxLogSize(int packageId, string groupName)
{
return GetMaxSize(packageId, groupName, ".MaxLogSize");
}
public static string BackupSqlDatabase(int itemId, string backupName,
bool zipBackup, bool download, string folderName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return null;
// load original meta item
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (item == null)
return null;
// place log record
TaskManager.StartTask("SQL_DATABASE", "BACKUP", item.Name);
TaskManager.ItemId = itemId;
try
{
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
string backFile = sql.BackupDatabase(item.Name, backupName, zipBackup);
if (!download)
{
// copy backup files to space folder
string relFolderName = FilesController.CorrectRelativePath(folderName);
if (!relFolderName.EndsWith("\\"))
relFolderName = relFolderName + "\\";
// create backup folder if not exists
if (!FilesController.DirectoryExists(item.PackageId, relFolderName))
FilesController.CreateFolder(item.PackageId, relFolderName);
string packageFile = relFolderName + Path.GetFileName(backFile);
// delete destination file if exists
if (FilesController.FileExists(item.PackageId, packageFile))
FilesController.DeleteFiles(item.PackageId, new string[] { packageFile });
byte[] buffer = null;
int offset = 0;
do
{
// read remote content
buffer = sql.GetTempFileBinaryChunk(backFile, offset, FILE_BUFFER_LENGTH);
// write remote content
FilesController.AppendFileBinaryChunk(item.PackageId, packageFile, buffer);
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
}
return backFile;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static byte[] GetSqlBackupBinaryChunk(int itemId, string path, int offset, int length)
{
// load original meta item
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (item == null)
return null;
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
return sql.GetTempFileBinaryChunk(path, offset, length);
}
public static string AppendSqlBackupBinaryChunk(int itemId, string fileName, string path, byte[] chunk)
{
// load original meta item
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (item == null)
return null;
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
return sql.AppendTempFileBinaryChunk(fileName, path, chunk);
}
public static int RestoreSqlDatabase(int itemId, string[] uploadedFiles, string[] packageFiles)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (item == null)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("SQL_DATABASE", "RESTORE", item.Name);
TaskManager.ItemId = itemId;
try
{
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
List<string> backupFiles = new List<string>();
if (packageFiles != null && packageFiles.Length > 0)
{
// copy package files to the remote SQL Server
foreach (string packageFile in packageFiles)
{
string path = null;
byte[] buffer = null;
int offset = 0;
do
{
// read package file
buffer = FilesController.GetFileBinaryChunk(item.PackageId, packageFile, offset, FILE_BUFFER_LENGTH);
// write remote backup file
string tempPath = sql.AppendTempFileBinaryChunk(Path.GetFileName(packageFile), path, buffer);
if (path == null)
{
path = tempPath;
backupFiles.Add(path);
}
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
}
}
else if (uploadedFiles != null && uploadedFiles.Length > 0)
{
// upladed files
backupFiles.AddRange(uploadedFiles);
}
// restore
if (backupFiles.Count > 0)
sql.RestoreDatabase(item.Name, backupFiles.ToArray());
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int TruncateSqlDatabase(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlDatabase origItem = (SqlDatabase)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("SQL_DATABASE", "TRUNCATE", origItem.Name);
TaskManager.ItemId = itemId;
try
{
// get service
DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);
// truncate database
sql.TruncateDatabase(origItem.Name);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
private static string[] GetSqlDatabasesArray(int packageId, string groupName)
{
List<SqlDatabase> databases = GetSqlDatabases(packageId, groupName, false);
string[] arr = new string[databases.Count];
for (int i = 0; i < databases.Count; i++)
arr[i] = databases[i].Name;
return arr;
}
public static DatabaseBrowserConfiguration GetDatabaseBrowserConfiguration(int packageId, string groupName)
{
DatabaseBrowserConfiguration config = new DatabaseBrowserConfiguration();
int serviceId = PackageController.GetPackageServiceId(packageId, groupName);
if (serviceId == 0)
return config;
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
config.Enabled = !String.IsNullOrEmpty(settings["BrowseURL"]);
return config;
}
public static DatabaseBrowserConfiguration GetDatabaseBrowserLogonScript(int packageId,
string groupName, string username)
{
int serviceId = PackageController.GetPackageServiceId(packageId, groupName);
if (serviceId == 0)
return null;
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
string url = settings["BrowseURL"];
string method = settings["BrowseMethod"];
string prms = settings["BrowseParameters"];
DatabaseBrowserConfiguration config = new DatabaseBrowserConfiguration();
config.Enabled = !String.IsNullOrEmpty(url);
config.Method = method;
prms = Utils.ReplaceStringVariable(prms, "server", settings["InternalAddress"]);
// load database user
SqlUser user = (SqlUser)PackageController.GetPackageItemByName(packageId, groupName, username, typeof(SqlUser));
if (user != null)
{
prms = Utils.ReplaceStringVariable(prms, "user", username);
prms = Utils.ReplaceStringVariable(prms, "password", CryptoUtils.Decrypt(user.Password));
string[] lines = Utils.ParseDelimitedString(prms, '\n', '\r');
StringBuilder sb = new StringBuilder();
if (String.Compare(method, "get", true) == 0)
{
// GET
sb.Append(url).Append("?");
foreach (string line in lines)
sb.Append(line).Append("&");
config.GetData = sb.ToString();
}
else
{
// POST
sb.Append("<html><body>");
sb.Append("<form id=\"AspForm\" method=\"POST\" action=\"").Append(url).Append("\">");
foreach (string line in lines)
{
//
var indexOfSplit = line.IndexOf('=');
//
if (indexOfSplit == -1)
continue;
//
sb.Append("<input type=\"hidden\" name=\"").Append(line.Substring(0, indexOfSplit))
.Append("\" value=\"").Append(line.Substring(indexOfSplit + 1)).Append("\"></input>");
}
sb.Append("</form><script language=\"javascript\">document.getElementById(\"AspForm\").submit();</script>");
sb.Append("</body></html>");
config.PostData = sb.ToString();
}
}
return config;
}
#endregion
#region Users
public static DataSet GetRawSqlUsersPaged(int packageId,
string groupName, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return PackageController.GetRawPackageItemsPaged(packageId, groupName, typeof(SqlUser),
true, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<SqlUser> GetSqlUsers(int packageId, string groupName, bool recursive)
{
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(
packageId, groupName, typeof(SqlUser), recursive);
return items.ConvertAll<SqlUser>(
new Converter<ServiceProviderItem, SqlUser>(ConvertItemToSqlUser));
}
private static SqlUser ConvertItemToSqlUser(ServiceProviderItem item)
{
return (SqlUser)item;
}
public static SqlUser GetSqlUser(int itemId)
{
// load meta item
SqlUser item = (SqlUser)PackageController.GetPackageItem(itemId);
// load service item
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
SqlUser user = sql.GetUser(item.Name, GetSqlDatabasesArray(item.PackageId, item.GroupName));
// add common properties
user.Id = item.Id;
user.PackageId = item.PackageId;
user.ServiceId = item.ServiceId;
user.Password = CryptoUtils.Decrypt(item.Password);
user.GroupName = item.GroupName;
return user;
}
public static int AddSqlUser(SqlUser item, string groupName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check quota
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, groupName + ".Users");
if (quota.QuotaExhausted)
return BusinessErrorCodes.ERROR_MSSQL_USERS_RESOURCE_QUOTA_LIMIT;
// check if mail resource is available
int serviceId = PackageController.GetPackageServiceId(item.PackageId, groupName);
if (serviceId == 0)
return BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE;
// check package items
if (PackageController.GetPackageItemByName(item.PackageId, groupName, item.Name, typeof(SqlUser)) != null)
return BusinessErrorCodes.ERROR_MSSQL_USERS_PACKAGE_ITEM_EXISTS;
// place log record
TaskManager.StartTask("SQL_USER", "ADD", item.Name);
TaskManager.WriteParameter("Provider", groupName);
int itemId = default(int);
try
{
// check service items
DatabaseServer sql = GetDatabaseServer(serviceId);
if (sql.UserExists(item.Name))
return BusinessErrorCodes.ERROR_MSSQL_USERS_SERVICE_ITEM_EXISTS;
// add service item
sql.CreateUser(item, item.Password);
// save item
item.Password = CryptoUtils.Encrypt(item.Password);
item.ServiceId = serviceId;
itemId = PackageController.AddPackageItem(item);
TaskManager.ItemId = itemId;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
//
if (ex.Message.Contains("INVALID_USERNAME"))
return BusinessErrorCodes.ERROR_MYSQL_INVALID_USER_NAME;
// Return a generic error instead of default(int)
itemId = BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
return itemId;
}
public static int UpdateSqlUser(SqlUser item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlUser origItem = (SqlUser)PackageController.GetPackageItem(item.Id);
if (origItem == null)
return BusinessErrorCodes.ERROR_MSSQL_USERS_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("SQL_USER", "UPDATE", origItem.Name);
TaskManager.ItemId = item.Id;
try
{
// get service
DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);
// update service item
sql.UpdateUser(item, GetSqlDatabasesArray(origItem.PackageId, origItem.GroupName));
// update meta item
if (item.Password == "")
item.Password = CryptoUtils.Decrypt(origItem.Password);
item.Password = CryptoUtils.Encrypt(item.Password);
PackageController.UpdatePackageItem(item);
return 0;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
// Return a generic error instead of re-throwing an exception
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int DeleteSqlUser(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
SqlUser origItem = (SqlUser)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_MSSQL_USERS_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("SQL_USER", "DELETE", origItem.Name);
TaskManager.ItemId = itemId;
try
{
// get service
DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);
// delete service item
sql.DeleteUser(origItem.Name, GetSqlDatabasesArray(origItem.PackageId, origItem.GroupName));
// delete meta item
PackageController.DeletePackageItem(origItem.Id);
return 0;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
// Return a generic error instead of re-throwing an exception
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
#region IImportController Members
public List<string> GetImportableItems(int packageId, int itemTypeId,
Type itemType, ResourceGroupInfo group)
{
List<string> items = new List<string>();
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
DatabaseServer db = GetDatabaseServer(serviceId);
if (itemType == typeof(SqlDatabase))
items.AddRange(db.GetDatabases());
else if (itemType == typeof(SqlUser))
items.AddRange(db.GetUsers());
return items;
}
public void ImportItem(int packageId, int itemTypeId,
Type itemType, ResourceGroupInfo group, string itemName)
{
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return;
if (itemType == typeof(SqlDatabase))
{
// import database
SqlDatabase db = new SqlDatabase();
db.ServiceId = serviceId;
db.PackageId = packageId;
db.Name = itemName;
db.GroupName = group.GroupName;
PackageController.AddPackageItem(db);
}
else if (itemType == typeof(SqlUser))
{
// import user
SqlUser user = new SqlUser();
user.ServiceId = serviceId;
user.PackageId = packageId;
user.Name = itemName;
user.GroupName = group.GroupName;
user.Password = "";
PackageController.AddPackageItem(user);
}
}
#endregion
#region IBackupController Members
public int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
if (item is SqlDatabase)
{
// backup database
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
string backupName = String.Format("DatabaseBackup_{0}.zip", item.Id);
string remoteBackupFile = sql.BackupDatabase(item.Name, backupName, true);
// download remote backup
string localBackupPath = Path.Combine(tempFolder, backupName);
byte[] buffer = null;
FileStream stream = new FileStream(localBackupPath, FileMode.Create, FileAccess.Write);
int offset = 0;
long length = 0;
do
{
// read remote content
buffer = sql.GetTempFileBinaryChunk(remoteBackupFile, offset, FILE_BUFFER_LENGTH);
// write remote content
stream.Write(buffer, 0, buffer.Length);
length += buffer.Length;
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
stream.Close();
// add file pointer
BackupController.WriteFileElement(writer, "DatabaseBackup", backupName, length);
// store meta item
SqlDatabase database = sql.GetDatabase(item.Name);
XmlSerializer serializer = new XmlSerializer(typeof(SqlDatabase));
serializer.Serialize(writer, database);
}
else if (item is SqlUser)
{
// backup user
DatabaseServer sql = GetDatabaseServer(item.ServiceId);
SqlUser userItem = item as SqlUser;
// store user info
SqlUser user = sql.GetUser(item.Name, GetSqlDatabasesArray(item.PackageId, item.GroupName));
user.Password = userItem.Password;
XmlSerializer serializer = new XmlSerializer(typeof(SqlUser));
serializer.Serialize(writer, user);
}
return 0;
}
public int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType == typeof(SqlDatabase))
{
DatabaseServer sql = GetDatabaseServer(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(SqlDatabase));
SqlDatabase db = (SqlDatabase)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("SqlDatabase")));
// create database if required
if (!sql.DatabaseExists(itemName))
{
sql.CreateDatabase(db);
}
// copy database backup to remote server
XmlNode fileNode = itemNode.SelectSingleNode("File[@name='DatabaseBackup']");
string backupFileName = fileNode.Attributes["path"].Value;
long backupFileLength = Int64.Parse(fileNode.Attributes["size"].Value);
string localBackupFilePath = Path.Combine(tempFolder, backupFileName);
if (new FileInfo(localBackupFilePath).Length != backupFileLength)
return -3;
FileStream stream = new FileStream(localBackupFilePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int readBytes = 0;
long length = 0;
string remoteBackupPath = null;
do
{
// read package file
readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
length += readBytes;
if (readBytes < FILE_BUFFER_LENGTH)
// resize buffer
Array.Resize<byte>(ref buffer, readBytes);
// write remote backup file
string tempPath = sql.AppendTempFileBinaryChunk(backupFileName, remoteBackupPath, buffer);
if (remoteBackupPath == null)
remoteBackupPath = tempPath;
}
while (readBytes == FILE_BUFFER_LENGTH);
stream.Close();
// restore database
sql.RestoreDatabase(itemName, new string[] { remoteBackupPath });
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, group.GroupName,
itemName, typeof(SqlDatabase)) == null)
{
db.PackageId = packageId;
db.ServiceId = serviceId;
db.GroupName = group.GroupName;
PackageController.AddPackageItem(db);
}
}
else if (itemType == typeof(SqlUser))
{
DatabaseServer sql = GetDatabaseServer(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(SqlUser));
SqlUser user = (SqlUser)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("SqlUser")));
// create user if required
if (!sql.UserExists(itemName))
{
sql.CreateUser(user, CryptoUtils.Decrypt(user.Password));
}
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, group.GroupName,
itemName, typeof(SqlUser)) == null)
{
user.PackageId = packageId;
user.ServiceId = serviceId;
user.GroupName = group.GroupName;
PackageController.AddPackageItem(user);
}
}
return 0;
}
#endregion
}
}

View file

@ -1,496 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;
using WebsitePanel.Providers;
using WebsitePanel.Providers.DNS;
namespace WebsitePanel.EnterpriseServer
{
public class DnsServerController : IImportController, IBackupController
{
private static DNSServer GetDNSServer(int serviceId)
{
DNSServer dns = new DNSServer();
ServiceProviderProxy.Init(dns, serviceId);
return dns;
}
public static int AddZone(int packageId, int serviceId, string zoneName)
{
return AddZone(packageId, serviceId, zoneName, true, false);
}
public static int AddZone(int packageId, int serviceId, string zoneName, bool addPackageItem, bool ignoreGlobalDNSRecords)
{
// get DNS provider
DNSServer dns = GetDNSServer(serviceId);
// check if zone already exists
if (dns.ZoneExists(zoneName))
return BusinessErrorCodes.ERROR_DNS_ZONE_EXISTS;
//
TaskManager.StartTask("DNS_ZONE", "ADD", zoneName);
//
int zoneItemId = default(int);
//
try
{
// get secondary DNS services
StringDictionary primSettings = ServerController.GetServiceSettings(serviceId);
string[] primaryIPAddresses = GetExternalIPAddressesFromString(primSettings["ListeningIPAddresses"]);
List<string> secondaryIPAddresses = new List<string>();
List<int> secondaryServiceIds = new List<int>();
string strSecondaryServices = primSettings["SecondaryDNSServices"];
if (!String.IsNullOrEmpty(strSecondaryServices))
{
string[] secondaryServices = strSecondaryServices.Split(',');
foreach (string strSecondaryId in secondaryServices)
{
int secondaryId = Utils.ParseInt(strSecondaryId, 0);
if (secondaryId == 0)
continue;
secondaryServiceIds.Add(secondaryId);
StringDictionary secondarySettings = ServerController.GetServiceSettings(secondaryId);
// add secondary IPs to the master array
secondaryIPAddresses.AddRange(
GetExternalIPAddressesFromString(secondarySettings["ListeningIPAddresses"]));
}
}
// add "Allow zone transfers"
string allowTransfers = primSettings["AllowZoneTransfers"];
if (!String.IsNullOrEmpty(allowTransfers))
{
string[] ips = Utils.ParseDelimitedString(allowTransfers, '\n', ' ', ',', ';');
foreach (string ip in ips)
{
if (!secondaryIPAddresses.Contains(ip))
secondaryIPAddresses.Add(ip);
}
}
// add primary zone
dns.AddPrimaryZone(zoneName, secondaryIPAddresses.ToArray());
// get DNS zone records
List<GlobalDnsRecord> records = ServerController.GetDnsRecordsTotal(packageId);
// get name servers
PackageSettings packageSettings = PackageController.GetPackageSettings(packageId, PackageSettings.NAME_SERVERS);
string[] nameServers = new string[] { };
if (!String.IsNullOrEmpty(packageSettings["NameServers"]))
nameServers = packageSettings["NameServers"].Split(';');
// build records list
List<DnsRecord> zoneRecords = new List<DnsRecord>();
string primaryNameServer = "ns." + zoneName;
if (nameServers.Length > 0)
primaryNameServer = nameServers[0];
// update SOA record
string hostmaster = primSettings["ResponsiblePerson"];
if (String.IsNullOrEmpty(hostmaster))
{
hostmaster = "hostmaster." + zoneName;
}
else
{
hostmaster = Utils.ReplaceStringVariable(hostmaster, "domain_name", zoneName);
}
dns.UpdateSoaRecord(zoneName, "", primaryNameServer, hostmaster);
// add name servers
foreach (string nameServer in nameServers)
{
DnsRecord ns = new DnsRecord();
ns.RecordType = DnsRecordType.NS;
ns.RecordName = "";
ns.RecordData = nameServer;
zoneRecords.Add(ns);
}
if (!ignoreGlobalDNSRecords)
{
// add all other records
zoneRecords.AddRange(BuildDnsResourceRecords(records, "", zoneName, ""));
}
// add zone records
dns.AddZoneRecords(zoneName, zoneRecords.ToArray());
// add secondary zones
foreach (int secondaryId in secondaryServiceIds)
{
try
{
// add secondary zone
DNSServer secDns = GetDNSServer(secondaryId);
secDns.AddSecondaryZone(zoneName, primaryIPAddresses);
RegisterZoneItems(packageId, secondaryId, zoneName, false);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Error adding secondary zone (service ID = " + secondaryId + ")");
}
}
if (!addPackageItem)
return 0;
// add service item
zoneItemId = RegisterZoneItems(packageId, serviceId, zoneName, true);
//
TaskManager.ItemId = zoneItemId;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
//
return zoneItemId;
}
private static int RegisterZoneItems(int spaceId, int serviceId, string zoneName, bool primaryZone)
{
// zone item
DnsZone zone = primaryZone ? new DnsZone() : new SecondaryDnsZone();
zone.Name = zoneName;
zone.PackageId = spaceId;
zone.ServiceId = serviceId;
int zoneItemId = PackageController.AddPackageItem(zone);
return zoneItemId;
}
public static int DeleteZone(int zoneItemId)
{
// delete DNS zone if applicable
DnsZone zoneItem = (DnsZone)PackageController.GetPackageItem(zoneItemId);
//
if (zoneItem != null)
{
TaskManager.StartTask("DNS_ZONE", "DELETE", zoneItem.Name);
//
try
{
//
TaskManager.ItemId = zoneItemId;
// delete DNS zone
DNSServer dns = new DNSServer();
ServiceProviderProxy.Init(dns, zoneItem.ServiceId);
// delete secondary zones
StringDictionary primSettings = ServerController.GetServiceSettings(zoneItem.ServiceId);
string strSecondaryServices = primSettings["SecondaryDNSServices"];
if (!String.IsNullOrEmpty(strSecondaryServices))
{
string[] secondaryServices = strSecondaryServices.Split(',');
foreach (string strSecondaryId in secondaryServices)
{
try
{
int secondaryId = Utils.ParseInt(strSecondaryId, 0);
if (secondaryId == 0)
continue;
DNSServer secDns = new DNSServer();
ServiceProviderProxy.Init(secDns, secondaryId);
secDns.DeleteZone(zoneItem.Name);
}
catch (Exception ex1)
{
// problem when deleting secondary zone
TaskManager.WriteError(ex1, "Error deleting secondary DNS zone");
}
}
}
try
{
dns.DeleteZone(zoneItem.Name);
}
catch (Exception ex2)
{
TaskManager.WriteError(ex2, "Error deleting primary DNS zone");
}
// delete service item
PackageController.DeletePackageItem(zoneItemId);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
//
return 0;
}
public static List<DnsRecord> BuildDnsResourceRecords(List<GlobalDnsRecord> records, string hostName, string domainName, string serviceIP)
{
List<DnsRecord> zoneRecords = new List<DnsRecord>();
foreach (GlobalDnsRecord record in records)
{
DnsRecord rr = new DnsRecord();
rr.RecordType = (DnsRecordType)Enum.Parse(typeof(DnsRecordType), record.RecordType, true);
rr.RecordName = Utils.ReplaceStringVariable(record.RecordName, "host_name", hostName, true);
if (record.RecordType == "A" || record.RecordType == "AAAA")
{
// If the service IP address and the DNS records external address are empty / null SimpleDNS will fail to properly create the zone record
if (String.IsNullOrEmpty(serviceIP) && String.IsNullOrEmpty(record.ExternalIP) && String.IsNullOrEmpty(record.RecordData))
continue;
rr.RecordData = String.IsNullOrEmpty(record.RecordData) ? record.ExternalIP : record.RecordData;
rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "ip", string.IsNullOrEmpty(serviceIP) ? record.ExternalIP : serviceIP);
rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "domain_name", string.IsNullOrEmpty(domainName) ? string.Empty : domainName);
if (String.IsNullOrEmpty(rr.RecordData) && !String.IsNullOrEmpty(serviceIP))
rr.RecordData = serviceIP;
}
else if (record.RecordType == "SRV")
{
rr.SrvPriority = record.SrvPriority;
rr.SrvWeight = record.SrvWeight;
rr.SrvPort = record.SrvPort;
rr.RecordText = record.RecordData;
rr.RecordData = record.RecordData;
}
else
{
rr.RecordData = record.RecordData;
}
// substitute variables
rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "domain_name", domainName);
// add MX priority
if (record.RecordType == "MX")
rr.MxPriority = record.MxPriority;
if (!String.IsNullOrEmpty(rr.RecordData))
{
if (rr.RecordName != "[host_name]")
zoneRecords.Add(rr);
}
}
return zoneRecords;
}
public static string[] GetExternalIPAddressesFromString(string str)
{
List<string> ips = new List<string>();
if (str != null && str.Trim() != "")
{
string[] sips = str.Split(',');
foreach (string sip in sips)
{
IPAddressInfo ip = ServerController.GetIPAddress(Int32.Parse(sip));
if (ip != null)
ips.Add(ip.ExternalIP);
}
}
return ips.ToArray();
}
#region IImportController Members
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
{
List<string> items = new List<string>();
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
// Mail provider
DNSServer dns = new DNSServer();
ServiceProviderProxy.Init(dns, serviceId);
if (itemType == typeof(DnsZone))
items.AddRange(dns.GetZones());
return items;
}
public void ImportItem(int packageId, int itemTypeId, Type itemType,
ResourceGroupInfo group, string itemName)
{
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return;
if (itemType == typeof(DnsZone))
{
// add DNS zone
DnsZone zone = new DnsZone();
zone.Name = itemName;
zone.ServiceId = serviceId;
zone.PackageId = packageId;
int zoneId = PackageController.AddPackageItem(zone);
// add/update domains/pointers
RestoreDomainByZone(itemName, packageId, zoneId);
}
}
private void RestoreDomainByZone(string itemName, int packageId, int zoneId)
{
DomainInfo domain = ServerController.GetDomain(itemName);
if (domain == null)
{
domain = new DomainInfo();
domain.DomainName = itemName;
domain.PackageId = packageId;
domain.ZoneItemId = zoneId;
ServerController.AddDomainItem(domain);
}
else
{
domain.ZoneItemId = zoneId;
ServerController.UpdateDomain(domain);
}
}
#endregion
#region IBackupController Members
public int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
if (!(item is DnsZone))
return 0;
// DNS provider
DNSServer dns = GetDNSServer(item.ServiceId);
// zone records serialized
XmlSerializer serializer = new XmlSerializer(typeof(DnsRecord));
try
{
// get zone records
DnsRecord[] records = dns.GetZoneRecords(item.Name);
// serialize zone records
foreach (DnsRecord record in records)
serializer.Serialize(writer, record);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Could not read zone records");
}
return 0;
}
public int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType,
string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType != typeof(DnsZone))
return 0;
// DNS provider
DNSServer dns = GetDNSServer(serviceId);
// check service item
if (!dns.ZoneExists(itemName))
{
// create primary and secondary zones
AddZone(packageId, serviceId, itemName, false, false);
// restore records
XmlSerializer serializer = new XmlSerializer(typeof(DnsRecord));
List<DnsRecord> records = new List<DnsRecord>();
foreach (XmlNode childNode in itemNode.ChildNodes)
{
if (childNode.Name == "DnsRecord")
{
records.Add((DnsRecord)serializer.Deserialize(new XmlNodeReader(childNode)));
}
}
dns.AddZoneRecords(itemName, records.ToArray());
}
// check if meta-item exists
int zoneId = 0;
DnsZone item = (DnsZone)PackageController.GetPackageItemByName(packageId, itemName, typeof(DnsZone));
if (item == null)
{
// restore meta-item
item = new DnsZone();
item.Name = itemName;
item.PackageId = packageId;
item.ServiceId = serviceId;
zoneId = PackageController.AddPackageItem(item);
}
else
{
zoneId = item.Id;
}
// restore domains
RestoreDomainByZone(itemName, packageId, zoneId);
return 0;
}
#endregion
}
}

View file

@ -1,135 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class CategoryController
{
#region Category routines
public static DataSet GetWholeCategoriesSet(int userId)
{
return EcommerceProvider.GetWholeCategoriesSet(
ES.SecurityContext.User.UserId,
userId
);
}
public static int GetCategoriesCount(int userId, int parentId)
{
return EcommerceProvider.GetCategoriesCount(
ES.SecurityContext.User.UserId,
userId,
parentId
);
}
public static List<Category> GetCategoriesPaged(int userId, int parentId, int maximumRows, int startRowIndex)
{
return ES.ObjectUtils.CreateListFromDataReader<Category>(
EcommerceProvider.GetCategoriesPaged(
ES.SecurityContext.User.UserId,
userId,
parentId,
maximumRows,
startRowIndex
)
);
}
public static int AddCategory(int userId, string categoryName, string categorySku, int parentId, string shortDescription, string fullDescription)
{
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
//
if (!result.Success)
return result.ResultCode;
//
return EcommerceProvider.AddCategory(
ES.SecurityContext.User.UserId,
userId,
categoryName,
categorySku,
parentId,
shortDescription,
fullDescription
);
}
public static Category GetCategory(int userId, int categoryId)
{
return ES.ObjectUtils.FillObjectFromDataReader<Category>(
EcommerceProvider.GetCategory(
ES.SecurityContext.User.UserId,
userId,
categoryId
)
);
}
public static int UpdateCategory(int userId, int categoryId, string categoryName, string categorySku, int parentId, string shortDescription, string fullDescription)
{
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
//
if (!result.Success)
return result.ResultCode;
return EcommerceProvider.UpdateCategory(
ES.SecurityContext.User.UserId,
userId,
categoryId,
categoryName,
categorySku,
parentId,
shortDescription,
fullDescription
);
}
public static int DeleteCategory(int userId, int categoryId)
{
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
//
if (!result.Success)
return result.ResultCode;
return EcommerceProvider.DeleteCategory(
ES.SecurityContext.User.UserId,
userId,
categoryId
);
}
#endregion
}
}

View file

@ -1,218 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer.ContractSystem
{
public class ContractController
{
public static GenericResult AddContract(int resellerId, ContractAccount accountSettings)
{
try
{
ES.SecurityContext.SetThreadPrincipal(resellerId);
//
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_ADD_CONTRACT);
//
GenericResult result = new GenericResult();
//
int customerId = -1;
int contractStatus = (int)ContractStatus.Pending;
//
if (accountSettings.PropertyExists(ContractAccount.CUSTOMER_ID))
{
customerId = accountSettings.GetProperty<int>(ContractAccount.CUSTOMER_ID);
//
contractStatus = (int)ContractStatus.Active;
}
// Ensure customer not specified and then check requested username availability
if (customerId == -1)
{
if (ES.UserController.UserExists(accountSettings[ContractAccount.USERNAME]))
{
result.Succeed = false;
result.SetProperty("ResultCode", ES.BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS);
return result;
}
// EXIT
}
//
string strNames = null;
string strValues = null;
//
if (customerId == -1)
{
strNames = strValues = String.Empty;
SecurityUtils.SerializeGenericProfile(ref strNames, ref strValues, accountSettings);
}
// emit the new contract
string contractId = EcommerceProvider.AddContract(customerId, resellerId, accountSettings[ContractAccount.USERNAME],
contractStatus, 0m, accountSettings[ContractAccount.FIRST_NAME], accountSettings[ContractAccount.LAST_NAME],
accountSettings[ContractAccount.EMAIL], accountSettings[ContractAccount.COMPANY_NAME],
strNames, strValues);
//
result.Succeed = true;
result.SetProperty("ContractId", contractId);
// Add contract object
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = GetContract(contractId);
//
return result;
}
catch (Exception ex)
{
throw ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
}
public static bool CheckCustomerContractExists()
{
return EcommerceProvider.CheckCustomerContractExists(ES.SecurityContext.User.UserId);
}
public static GenericResult DeleteContract(string contractId)
{
return null;
}
public static void ImpersonateAsContractReseller(string contractId)
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
// Impersonate
ImpersonateAsContractReseller(contract);
}
public static void ImpersonateAsContractReseller(Contract contractInfo)
{
// Impersonate
ES.SecurityContext.SetThreadPrincipal(contractInfo.ResellerId);
}
public static Contract GetCustomerContract(int customerId)
{
Contract contractInfo = ES.ObjectUtils.FillObjectFromDataReader<Contract>(
EcommerceProvider.GetCustomerContract(customerId));
//
if (contractInfo == null)
throw new Exception("Could not find customer contract.");
//
return contractInfo;
}
public static Contract GetContract(string contractId)
{
Contract contractInfo = ES.ObjectUtils.FillObjectFromDataReader<Contract>(EcommerceProvider.GetContract(contractId));
//
if (contractInfo == null)
throw new Exception("Could not find the contract specified. ContractID: " + contractId);
//
return contractInfo;
}
public static int UpdateContract(string contractId, int customerId, string accountName,
ContractStatus status, decimal balance, string firstName, string lastName, string email,
string companyName, string propertyNames, string propertyValues)
{
return EcommerceProvider.UpdateContract(contractId, customerId, accountName, (int)status, balance,
firstName, lastName, email, companyName, propertyNames, propertyValues);
}
public static ContractAccount GetContractAccountSettings(string contractId)
{
return GetContractAccountSettings(contractId, false);
}
public static ContractAccount GetContractAccountSettings(string contractId, bool internally)
{
//
ContractAccount account = new ContractAccount();
//
IDataReader dr = null;
//
try
{
int customerId = -1;
dr = EcommerceProvider.GetContract(contractId);
//
if (dr.Read())
{
string propertyNames = Convert.ToString(dr["PropertyNames"]);
string propertyValues = Convert.ToString(dr["PropertyValues"]);
if (dr["CustomerID"] != DBNull.Value)
customerId = Convert.ToInt32(dr["CustomerID"]);
else
SecurityUtils.DeserializeGenericProfile(propertyNames, propertyValues, account);
}
//
if (customerId > -1)
{
ES.UserInfo userInfo = (internally) ? ES.UserController.GetUserInternally(customerId) :
ES.UserController.GetUser(customerId);
//
if (internally)
account[ContractAccount.PASSWORD] = userInfo.Password;
//
account[ContractAccount.USERNAME] = userInfo.Username;
account[ContractAccount.FIRST_NAME] = userInfo.FirstName;
account[ContractAccount.LAST_NAME] = userInfo.LastName;
account[ContractAccount.EMAIL] = userInfo.Email;
account[ContractAccount.COMPANY_NAME] = userInfo.CompanyName;
account[ContractAccount.COUNTRY] = userInfo.Country;
account[ContractAccount.CITY] = userInfo.City;
account[ContractAccount.ADDRESS] = userInfo.Address;
account[ContractAccount.FAX_NUMBER] = userInfo.Fax;
account[ContractAccount.INSTANT_MESSENGER] = userInfo.InstantMessenger;
account[ContractAccount.PHONE_NUMBER] = userInfo.PrimaryPhone;
account[ContractAccount.STATE] = userInfo.State;
account[ContractAccount.ZIP] = userInfo.Zip;
account[ContractAccount.MAIL_FORMAT] = userInfo.HtmlMail ? "HTML" : "PlainText";
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dr != null)
dr.Close();
}
//
return account;
}
}
}

View file

@ -1,591 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.Web.Caching;
using System.Globalization;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class SettingsHelper
{
public static string ConvertObjectSettings(string[][] settings)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("settings");
foreach (string[] pair in settings)
{
XmlElement s_item = doc.CreateElement("setting");
s_item.SetAttribute("name", pair[0]);
s_item.SetAttribute("value", pair[1]);
root.AppendChild(s_item);
}
return root.OuterXml;
}
public static string ConvertObjectSettings(string[][] settings, string rootName, string childName)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement(rootName);
// exit
if (settings == null)
return root.OuterXml;
// iterate
foreach (string[] pair in settings)
{
XmlElement s_item = doc.CreateElement(childName);
s_item.SetAttribute("name", pair[0]);
s_item.SetAttribute("value", pair[1]);
root.AppendChild(s_item);
}
//
return root.OuterXml;
}
public static string ConvertControlsBunch(string[][] bunch)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Controls");
foreach (string[] pair in bunch)
{
XmlElement s_item = doc.CreateElement("Control");
s_item.SetAttribute("Key", pair[0]);
s_item.SetAttribute("Src", pair[1]);
root.AppendChild(s_item);
}
return root.OuterXml;
}
public static KeyValueBunch FillSettingsBunch(IDataReader reader)
{
return FillSettingsBunch(
reader,
"SettingName",
"SettingValue"
);
}
public static T FillSettingsBunch<T>(IDataReader reader, string keyNameColumn, string keyValueColumn)
{
Type type = typeof(T);
KeyValueBunch bunch = (KeyValueBunch)Activator.CreateInstance(type);
try
{
while (reader.Read())
bunch[(String)reader[keyNameColumn]] = (String)reader[keyValueColumn];
}
catch
{
bunch = null;
}
finally
{
if (reader != null)
reader.Close();
}
return (T)Convert.ChangeType(bunch, typeof(T));
}
public static KeyValueBunch FillSettingsBunch(IDataReader reader,
string keyNameColumn, string keyValueColumn)
{
KeyValueBunch bunch = null;
try
{
bunch = new KeyValueBunch();
while (reader.Read())
bunch[(String)reader[keyNameColumn]] = (String)reader[keyValueColumn];
}
catch
{
bunch = null;
}
finally
{
if (reader != null)
reader.Close();
}
return bunch;
}
public static KeyValueBunch FillControlsBunch(IDataReader reader)
{
KeyValueBunch bunch = null;
try
{
bunch = new KeyValueBunch();
while (reader.Read())
bunch[(String)reader["ControlKey"]] = (String)reader["ControlSrc"];
}
catch
{
bunch = null;
}
finally
{
if (reader != null)
reader.Close();
}
return bunch;
}
public static KeyValueBunch FillProperties(IDataReader reader)
{
KeyValueBunch settings = null;
try
{
settings = new KeyValueBunch();
while (reader.Read())
{
string name = (string)reader["PropertyName"];
string value = (string)reader["PropertyValue"];
//
settings[name] = value;
}
}
catch
{
settings = null;
}
finally
{
if (reader != null)
reader.Close();
}
return settings;
}
public static KeyValueBunch FillSettings(IDataReader reader)
{
KeyValueBunch settings = null;
try
{
settings = new KeyValueBunch();
while (reader.Read())
{
settings[(string)reader["SettingName"]] = (string)reader["SettingValue"];
}
}
catch
{
settings = null;
}
finally
{
if (reader != null)
reader.Close();
}
return settings;
}
}
class Currency
{
public string ISOCode;
public string Symbol;
public decimal Rate;
public Currency()
{
}
public Currency(string isocode, string symbol, decimal rate)
{
this.ISOCode = isocode;
this.Symbol = symbol;
this.Rate = rate;
}
}
public class CurrenciesHelper
{
private const string ServiceUrl = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
public const string HttpCacheKey = "__Currencies";
private Dictionary<string, Currency> _currencies;
public CurrenciesHelper()
{
Initialize();
}
public string[] GetSupportedCurrencies()
{
string[] array = new string[_currencies.Count];
_currencies.Keys.CopyTo(array, 0);
return array;
}
public string GetCurrencySymbol(string ISOCode)
{
ISOCode = ISOCode.ToUpper();
if (_currencies.ContainsKey(ISOCode))
return _currencies[ISOCode].Symbol;
return ISOCode;
}
public decimal GetCurrencyRate(string ISOCode)
{
ISOCode = ISOCode.ToUpper();
if (_currencies.ContainsKey(ISOCode))
return _currencies[ISOCode].Rate;
return Decimal.Zero;
}
private XmlDocument GetServiceResponse()
{
WebClient ecb = new WebClient();
try
{
TaskManager.StartTask("CURRENCY_HELPER", "LOAD_CURRENCIES_RATES");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(
ecb.DownloadString(
ServiceUrl
)
);
return xmlDoc;
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Failed to get response from www.ecb.int");
}
finally
{
TaskManager.CompleteTask();
}
return null;
}
private Currency ConvertFromXml(XmlElement element, RegionInfo region)
{
string ISOCode = element.GetAttribute("currency");
Currency currency = new Currency();
currency.Rate = Decimal.Parse(element.GetAttribute("rate"));
currency.ISOCode = ISOCode;
if (region != null)
currency.Symbol = region.CurrencySymbol;
else
currency.Symbol = ISOCode;
return currency;
}
private void Initialize()
{
/*Cache cache = new Cache();
_currencies = (Dictionary<string, Currency>)cache[HttpCacheKey];*/
if (_currencies == null)
_currencies = LoadRatesFromService();
}
private void OnCacheItem_Removed(string key, object value, CacheItemRemovedReason reason)
{
// if currencies rates were expired - renew them
if (String.Compare(HttpCacheKey, key) == 0)
_currencies = LoadRatesFromService();
}
private Dictionary<string, Currency> LoadRatesFromService()
{
XmlDocument ecbXml = GetServiceResponse();
Dictionary<string, Currency> currencies = new Dictionary<string, Currency>();
// add euro first
currencies.Add("EUR", new Currency("EUR", "ˆ", 1));
if (ecbXml != null)
{
XmlNode cube = ecbXml.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Cube']/*[local-name()='Cube']");
if (cube != null)
{
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
IEnumerator iterator = cultures.GetEnumerator();
// load symbols for currencies
while (iterator.MoveNext() && cube.ChildNodes.Count > 0)
{
CultureInfo culture = (CultureInfo)iterator.Current;
RegionInfo region = new RegionInfo(culture.LCID);
string ISOCode = region.ISOCurrencySymbol;
// find currency by ISO code
XmlElement element = (XmlElement)cube.SelectSingleNode(
String.Format(
"*[local-name()='Cube' and @currency='{0}']",
ISOCode
)
);
if (element != null)
{
currencies.Add(ISOCode, ConvertFromXml(element, region));
cube.RemoveChild(element);
}
}
// we still have an unrecognized currencies
if (cube.ChildNodes.Count > 0)
{
foreach (XmlElement element in cube.ChildNodes)
currencies.Add(element.GetAttribute("currency"), ConvertFromXml(element, null));
}
}
}
// calculate 12.00 time span
DateTime expire = DateTime.Now.AddDays(1).Subtract(DateTime.Now.TimeOfDay);
// add currencies to the cache
/*Cache cache = new Cache();
cache.Add(
HttpCacheKey,
currencies,
null,
expire,
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
new CacheItemRemovedCallback(OnCacheItem_Removed)
);*/
return currencies;
}
}
public class SecurityUtils
{
internal static void SerializeProfile(ref string propertyNames, ref string propertyValues,
bool encrypt, CheckoutDetails profile)
{
// names
StringBuilder namesBuilder = new StringBuilder();
// string values
StringBuilder valsBuilder = new StringBuilder();
//
string[] allKeys = profile.GetAllKeys();
//
foreach (string keyName in allKeys)
{
//
int length = 0, position = 0;
// get serialized property value
string keyValue = profile[keyName];
//
if (String.IsNullOrEmpty(keyValue))
{
length = -1;
}
else
{
//
length = keyValue.Length;
//
position = valsBuilder.Length;
//
valsBuilder.Append(keyValue);
}
//
namesBuilder.Append(keyName + ":S:" + position.ToString(CultureInfo.InvariantCulture) + ":" + length.ToString(CultureInfo.InvariantCulture) + ":");
}
//
propertyNames = (encrypt) ? CryptoUtils.Encrypt(namesBuilder.ToString()) : namesBuilder.ToString();
//
propertyValues = (encrypt) ? CryptoUtils.Encrypt(valsBuilder.ToString()) : valsBuilder.ToString();
}
internal static void DeserializeProfile(string propertyNames, string propertyValues,
bool encrypted, CheckoutDetails details)
{
// Input format:
// PROPERTY_NAME:S:START_INDEX:PROP_VALUE_LENGTH
//
if ((propertyNames != null && propertyValues != null) && details != null)
{
//
try
{
// decrypt
propertyNames = (encrypted) ? CryptoUtils.Decrypt(propertyNames) : propertyNames;
//
propertyValues = (encrypted) ? CryptoUtils.Decrypt(propertyValues) : propertyValues;
//
string[] names = propertyNames.Split(':');
// divide names length by 4 parts
int count = names.Length / 4;
// iterate through
for (int i = 0; i < count; i++)
{
// get property name
string keyName = names[i * 4];
//
string keyValue = String.Empty;
// calculate property value start index
int startIndex = Int32.Parse(names[(i * 4) + 2], CultureInfo.InvariantCulture);
// calculate property value length
int length = Int32.Parse(names[(i * 4) + 3], CultureInfo.InvariantCulture);
// ensure check property value not empty
if (length != -1)
{
keyValue = propertyValues.Substring(startIndex, length);
}
//
details[keyName] = keyValue;
}
}
catch
{
}
}
}
internal static void SerializeGenericProfile(ref string propertyNames, ref string propertyValues, IKeyValueBunch source)
{
// names
StringBuilder namesBuilder = new StringBuilder();
// string values
StringBuilder valsBuilder = new StringBuilder();
//
string[] allKeys = source.GetAllKeys();
//
foreach (string keyName in allKeys)
{
//
int length = 0, position = 0;
// get serialized property value
string keyValue = source[keyName];
//
if (String.IsNullOrEmpty(keyValue))
{
length = -1;
}
else
{
//
length = keyValue.Length;
//
position = valsBuilder.Length;
//
valsBuilder.Append(keyValue);
}
//
namesBuilder.Append(keyName + ":S:" + position.ToString(CultureInfo.InvariantCulture) + ":" + length.ToString(CultureInfo.InvariantCulture) + ":");
}
//
propertyNames = namesBuilder.ToString();
//
propertyValues = valsBuilder.ToString();
}
internal static void DeserializeGenericProfile(string propertyNames, string propertyValues, IKeyValueBunch target)
{
// Input format:
// PROPERTY_NAME:S:START_INDEX:PROP_VALUE_LENGTH
//
if ((propertyNames != null && propertyValues != null) && target != null)
{
//
try
{
//
string[] names = propertyNames.Split(':');
// divide names length by 4 parts
int count = names.Length / 4;
// iterate through
for (int i = 0; i < count; i++)
{
// get property name
string keyName = names[i * 4];
//
string keyValue = String.Empty;
// calculate property value start index
int startIndex = Int32.Parse(names[(i * 4) + 2], CultureInfo.InvariantCulture);
// calculate property value length
int length = Int32.Parse(names[(i * 4) + 3], CultureInfo.InvariantCulture);
// ensure check property value not empty
if (length != -1)
{
keyValue = propertyValues.Substring(startIndex, length);
}
//
target[keyName] = keyValue;
}
}
catch
{
}
}
}
}
}

View file

@ -1,375 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ES = WebsitePanel.EnterpriseServer;
using System.Threading;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Templates;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class InvoiceController
{
private InvoiceController()
{
}
#region Ecommerce v2.1.0 routines
#region Helper methods
public static string BuildAddXmlForInvoiceItems(List<InvoiceItem> items)
{
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("items");
foreach (InvoiceItem item in items)
{
XmlElement node = xml.CreateElement("item");
node.SetAttribute("serviceid", item.ServiceId.ToString());
node.SetAttribute("itemname", item.ItemName);
node.SetAttribute("typename", item.TypeName);
node.SetAttribute("quantity", item.Quantity.ToString());
node.SetAttribute("total", item.Total.ToString(CultureInfo.InvariantCulture));
node.SetAttribute("subtotal", item.SubTotal.ToString(CultureInfo.InvariantCulture));
node.SetAttribute("unitprice", item.UnitPrice.ToString(CultureInfo.InvariantCulture));
root.AppendChild(node);
}
return root.OuterXml;
}
public static List<InvoiceItem> CalculateInvoiceLinesForServices(List<int> services)
{
List<InvoiceItem> lines = new List<InvoiceItem>();
foreach (int serviceId in services)
{
ProductType svc_type = ServiceController.GetServiceItemType(serviceId);
//
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svc_type.ProvisioningController));
//
InvoiceItem[] ilines = controller.CalculateInvoiceLines(serviceId);
foreach (InvoiceItem iline in ilines)
{
iline.SubTotal = iline.UnitPrice * iline.Quantity;
iline.Total = iline.SubTotal;
}
//
lines.AddRange(ilines);
}
//
return lines;
}
#endregion
public static int VoidCustomerInvoice(int invoiceId)
{
SecurityResult result = StorehouseController.CheckAccountIsAdminOrReseller();
if (!result.Success)
return result.ResultCode;
// void
EcommerceProvider.VoidCustomerInvoice(ES.SecurityContext.User.UserId, invoiceId);
//
return 0;
}
public static Taxation GetCustomerTaxation(string contractId, string country, string state)
{
return ES.ObjectUtils.FillObjectFromDataReader<Taxation>(
EcommerceProvider.GetCustomerTaxation(contractId, country, state));
}
public static void CalculateInvoiceChargeAmounts(Taxation tax, List<InvoiceItem> items,
out decimal totalAmount, out decimal subTotalAmount, out decimal taxAmount)
{
totalAmount = subTotalAmount = taxAmount = 0;
// calculate all invoice items
foreach (InvoiceItem item in items)
subTotalAmount += item.SubTotal;
//
totalAmount = subTotalAmount;
// tax applies
if (tax != null)
{
switch (tax.Type)
{
case TaxationType.Fixed:
taxAmount = tax.Amount;
totalAmount += taxAmount;
break;
case TaxationType.Percentage:
taxAmount = (subTotalAmount / 100) * tax.Amount;
totalAmount += taxAmount;
break;
case TaxationType.TaxIncluded:
taxAmount = totalAmount - totalAmount * 100 / (100M + tax.Amount);
subTotalAmount -= taxAmount;
break;
}
}
}
public static int AddInvoice(string contractId, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
{
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
// read customer tax
Taxation tax = GetCustomerTaxation(contractId, account[ContractAccount.COUNTRY], account[ContractAccount.STATE]);
int taxationId = (tax == null) ? -1 : tax.TaxationId;
// Calculate invoice amounts
decimal totalAmount = 0, subTotalAmount = 0, taxAmount = 0;
CalculateInvoiceChargeAmounts(tax, invoiceLines, out totalAmount, out subTotalAmount, out taxAmount);
// align svcs suspend date
int[] svcs = new int[invoiceLines.Count];
for (int i = 0; i < invoiceLines.Count; i++)
svcs[i] = invoiceLines[i].ServiceId;
DateTime sdateAligned = ServiceController.GetSvcsSuspendDateAligned(svcs, DateTime.Now);
//
StoreSettings settings = StorehouseController.GetStoreSettings(ES.SecurityContext.User.UserId,
StoreSettings.SYSTEM_SETTINGS);
// get invoice grace period in days
int gracePeriod = Common.Utils.Utils.ParseInt(settings["InvoiceGracePeriod"], 0);
//
if (gracePeriod < 0) gracePeriod = 0;
//
DateTime created = DateTime.Now;
DateTime dueDate = sdateAligned.AddDays(gracePeriod);
//
return AddInvoice(contractId, created, dueDate, taxationId, totalAmount, subTotalAmount, taxAmount,
invoiceLines, extraArgs);
}
public static int AddInvoice(string contractId, DateTime created, DateTime dueDate,
int taxationId, decimal totalAmount, decimal subTotalAmount, decimal taxAmount, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
{
//
try
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
//
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_ADD_INVOICE);
// build xml representation
string invoiceLinesXml = BuildAddXmlForInvoiceItems(invoiceLines);
// add invoice
int result = EcommerceProvider.AddInvoice(contractId, created, dueDate,
taxationId, totalAmount, subTotalAmount, taxAmount, invoiceLinesXml,
StorehouseController.GetBaseCurrency(contract.ResellerId));
// check error
if (result < 1)
return result; // EXIT
// build invoice number
Invoice invoice = GetCustomerInvoiceInternally(result);
StoreSettings settings = StorehouseController.GetStoreSettings(contract.ResellerId, StoreSettings.SYSTEM_SETTINGS);
if (!String.IsNullOrEmpty(settings["InvoiceNumberFormat"]))
{
Hashtable options = new Hashtable();
options["ID"] = result;
invoice.InvoiceNumber = StorehouseController.ApplyStringCustomFormat(
settings["InvoiceNumberFormat"], options);
}
else
{
invoice.InvoiceNumber = result.ToString();
}
// update invoice
InvoiceController.UpdateInvoice(invoice.InvoiceId, invoice.InvoiceNumber, invoice.DueDate,
invoice.Total, invoice.SubTotal, invoice.TaxationId, invoice.TaxAmount, invoice.Currency);
//
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = contract;
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE] = invoice;
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE_LINES] = invoiceLines;
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_EXTRA_ARGS] = extraArgs;
//
return result;
}
catch (Exception ex)
{
throw ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
}
public static int UpdateInvoice(int invoiceId, string invoiceNumber, DateTime dueDate,
decimal total, decimal subTotal, int taxationId, decimal taxAmount, string currency)
{
return EcommerceProvider.UpdateInvoice(ES.SecurityContext.User.UserId, invoiceId,
invoiceNumber, dueDate, total, subTotal, taxationId, taxAmount, currency);
}
internal static Invoice GetCustomerInvoiceInternally(int invoiceId)
{
return ES.ObjectUtils.FillObjectFromDataReader<Invoice>(
EcommerceProvider.GetCustomerInvoice(ES.SecurityContext.User.UserId, invoiceId));
}
public static List<InvoiceItem> GetCustomerInvoiceItems(int invoiceId)
{
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
EcommerceProvider.GetCustomerInvoiceItems(ES.SecurityContext.User.UserId, invoiceId));
}
internal static string GetCustomerInvoiceFormattedInternally(int invoiceId, string cultureName)
{
Invoice invoice = GetCustomerInvoiceInternally(invoiceId);
//
return GetCustomerInvoiceFormattedInternally(invoice.ContractId, invoiceId, cultureName);
}
internal static string GetCustomerInvoiceFormattedInternally(string contractId, int invoiceId, string cultureName)
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
ContractAccount accountSettings = ContractSystem.ContractController.GetContractAccountSettings(contractId);
//
return GetCustomerInvoiceFormattedInternally(contract, invoiceId, accountSettings, cultureName);
}
internal static string GetCustomerInvoiceFormattedInternally(Contract contract, int invoiceId, ContractAccount accountSettings, string cultureName)
{
//
Invoice invoiceInfo = GetCustomerInvoiceInternally(invoiceId);
// impersonate
ES.SecurityContext.SetThreadPrincipal(contract.ResellerId);
// load settings
StoreSettings settings = StorehouseController.GetStoreSettings(contract.ResellerId, StoreSettings.NEW_INVOICE);
//
string templateBody = settings["HtmlBody"];
//
Taxation invoiceTax = StorehouseController.GetTaxation(contract.ResellerId, invoiceInfo.TaxationId);
//
List<InvoiceItem> invoiceLines = GetCustomerInvoiceItems(invoiceId);
Dictionary<int, Service> invoiceServices = ServiceController.GetServicesDictionary(invoiceLines);
//
Template tm = new Template(templateBody);
tm["Invoice"] = invoiceInfo;
tm["InvoiceLines"] = invoiceLines;
tm["InvoiceServices"] = invoiceServices;
tm["Customer"] = accountSettings;
tm["Tax"] = invoiceTax;
StringWriter writer = new StringWriter();
try
{
// Preserve an original thread culture
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
//
if (!String.IsNullOrEmpty(cultureName))
{
try
{
CultureInfo formattingCulture = new CultureInfo(cultureName);
// Empty currency symbol to supporty 3-letters ISO format
// hardcorded in HTML templates
formattingCulture.NumberFormat.CurrencySymbol = String.Empty;
// Set formatting culture
Thread.CurrentThread.CurrentCulture = formattingCulture;
}
catch (Exception ex)
{
TaskManager.WriteWarning("Wrong culture name has been provided. Culture name: {0}.", cultureName);
TaskManager.WriteWarning(ex.StackTrace);
TaskManager.WriteWarning(ex.Message);
}
}
// Process template
tm.Evaluate(writer);
templateBody = writer.ToString();
// Revert the original thread's culture back
Thread.CurrentThread.CurrentCulture = originalCulture;
}
catch (ParserException ex)
{
return String.Format("Error in template (Line {0}, Column {1}): {2}",
ex.Line, ex.Column, ex.Message);
}
return templateBody;
}
public static List<Invoice> GetUnpaidInvoices(int resellerId)
{
return ES.ObjectUtils.CreateListFromDataReader<Invoice>(
EcommerceProvider.GetUnpaidInvoices(ES.SecurityContext.User.UserId, resellerId));
}
#endregion
#region New implementation
public static List<InvoiceItem> GetInvoicesItemsToActivate(int resellerId)
{
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
EcommerceProvider.GetInvoicesItemsToActivate(ES.SecurityContext.User.UserId, resellerId));
}
public static List<InvoiceItem> GetInvoicesItemsOverdue(int resellerId, DateTime dueDate)
{
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
EcommerceProvider.GetInvoicesItemsOverdue(ES.SecurityContext.User.UserId, resellerId, dueDate));
}
public static int SetInvoiceItemProcessed(int invoiceId, int itemId)
{
return EcommerceProvider.SetInvoiceItemProcessed(invoiceId, itemId);
}
#endregion
#region Provisioning routines
#endregion
}
}

View file

@ -1,172 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using ES = WebsitePanel.EnterpriseServer;
using WebsitePanel.Templates;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class MiscController
{
private MiscController()
{
}
public static int SendNewInvoiceNotification(int invoiceId)
{
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
return SendNewInvoiceNotification(invoice, invoiceLines, null);
}
public static int SendNewInvoiceNotification(Invoice invoice)
{
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoice.InvoiceId);
return SendNewInvoiceNotification(invoice, invoiceLines, null);
}
public static int SendNewInvoiceNotification(Invoice invoice, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
{
Contract contract = ContractSystem.ContractController.GetContract(invoice.ContractId);
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(invoice.ContractId);
Dictionary<int, Service> invoiceServices = ServiceController.GetServicesDictionary(invoiceLines);
Hashtable items = new Hashtable();
items["Invoice"] = invoice;
items["InvoiceLines"] = invoiceLines;
items["InvoiceServices"] = invoiceServices;
items["Tax"] = StorehouseController.GetTaxation(contract.ResellerId, invoice.TaxationId);
items["Customer"] = account;
items["IsEmail"] = "1";
if (extraArgs != null)
items["ExtraArgs"] = extraArgs;
return SendSystemNotification(StoreSettings.NEW_INVOICE, account, items, "HtmlBody", "TextBody");
}
public static int SendServiceActivatedNotification(int serviceId)
{
Hashtable items = new Hashtable();
//
Service serviceInfo = ServiceController.GetService(serviceId);
//
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
items["Service"] = serviceInfo;
items["Customer"] = account;
return SendSystemNotification(StoreSettings.SERVICE_ACTIVATED, account, items, "HtmlBody", "TextBody");
}
public static int SendServiceSuspendedNotification(int serviceId)
{
Hashtable items = new Hashtable();
Service serviceInfo = ServiceController.GetService(serviceId);
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
items["Service"] = serviceInfo;
items["Customer"] = account;
return SendSystemNotification(StoreSettings.SERVICE_SUSPENDED, account, items, "HtmlBody", "TextBody");
}
public static int SendServiceCanceledNotification(int serviceId)
{
Hashtable items = new Hashtable();
Service serviceInfo = ServiceController.GetService(serviceId);
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
items["Service"] = serviceInfo;
items["Customer"] = account;
return SendSystemNotification(StoreSettings.SERVICE_CANCELLED, account, items, "HtmlBody", "TextBody");
}
public static int SendPaymentReceivedNotification(CustomerPayment payment)
{
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(payment.ContractId);
Hashtable items = new Hashtable();
items["Payment"] = payment;
items["Customer"] = account;
return SendSystemNotification(StoreSettings.PAYMENT_RECEIVED, account, items, "HtmlBody", "TextBody");
}
protected static int SendSystemNotification(string settingsName, ContractAccount recipient, Hashtable items,
string htmlKeyName, string textKeyName)
{
// load e-mail template
StoreSettings settings = StorehouseController.GetStoreSettings(ES.SecurityContext.User.UserId,
settingsName);
//
bool htmlMail = (recipient[ContractAccount.MAIL_FORMAT] == "HTML");
string email = recipient[ContractAccount.EMAIL];
//
string messageBody = htmlMail ? settings[htmlKeyName] : settings[textKeyName];
Template tmp = new Template(messageBody);
if (items != null)
{
foreach (string key in items.Keys)
tmp[key] = items[key];
}
StringWriter writer = new StringWriter();
try
{
tmp.Evaluate(writer);
}
catch (ParserException ex)
{
writer.WriteLine(String.Format("Error in template (Line {0}, Column {1}): {2}",
ex.Line, ex.Column, ex.Message));
}
// evaluate message body
messageBody = writer.ToString();
return ES.MailHelper.SendMessage(settings["From"], email, settings["CC"], settings["Subject"],
messageBody, htmlMail);
}
}
}

View file

@ -1,165 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class PaymentGatewayController
{
public const string TASK_SOURCE = "PAYMENT_CONTROLLER";
public const string CHECKOUT_TASK = "CHECKOUT";
public const string GENERAL_FAILURE = "CHECKOUT_GENERAL_FAILURE";
private PaymentGatewayController()
{
}
#region Payment Gateway routines
/// <summary>
/// Performs checkout operation
/// </summary>
/// <param name="spaceId">Space.</param>
/// <param name="gatewayId">Gateway.</param>
/// <param name="invoiceId">Invoice.</param>
/// <param name="details">Array of parameters.</param>
/// <returns>Checkout result object.</returns>
public static CheckoutResult CheckOut(string contractId, int invoiceId, string methodName,
CheckoutDetails details)
{
CheckoutResult result = new CheckoutResult();
try
{
Contract contractInfo = ContractSystem.ContractController.GetContract(contractId);
// impersonate
ContractSystem.ContractController.ImpersonateAsContractReseller(contractInfo);
// TRACE
ES.TaskManager.StartTask(TASK_SOURCE, CHECKOUT_TASK, methodName);
ES.TaskManager.Write("Start accepting payment for invoice");
ES.TaskManager.WriteParameter("ContractID", contractId);
ES.TaskManager.WriteParameter("InvoiceID", invoiceId);
// get user details
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
// try to load plugin type and throw an exception if type not found
IPaymentGatewayProvider provider = (IPaymentGatewayProvider)SystemPluginController.GetContractPaymentMethod(
contractInfo, methodName);
// add invoice details
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
// append information for the provider
details[CheckoutKeys.ContractNumber] = contractId;
details[CheckoutKeys.Amount] = invoice.Total.ToString("0.00");
details[CheckoutKeys.InvoiceNumber] = invoice.InvoiceNumber;
details[CheckoutKeys.Currency] = invoice.Currency;
ES.TaskManager.Write("Submitting payment transaction");
// call checkout routine
TransactionResult pgResult = provider.SubmitPaymentTransaction(details);
// log provider response
SystemPluginController.LogContractPayment(contractInfo, methodName, pgResult.RawResponse);
// ERROR
if (!pgResult.Succeed)
{
result.Succeed = false;
result.StatusCode = pgResult.StatusCode;
//
ES.TaskManager.WriteError("Transaction failed");
ES.TaskManager.WriteParameter("StatusCode", result.StatusCode);
ES.TaskManager.WriteParameter("RawResponse", pgResult.RawResponse);
// EXIT
return result;
}
// OK
ES.TaskManager.Write("Transaction is OK");
// check whether the transaction already exists
CustomerPayment tran = StorehouseController.LookupForTransaction(pgResult.TransactionId);
// lookup for pending transaction
if (tran == null)
{
// add payment record
result.PaymentId = StorehouseController.AddCustomerPayment(contractId, invoice.InvoiceId,
pgResult.TransactionId, invoice.Total, invoice.Currency, methodName,
pgResult.TransactionStatus);
// ERROR
if (result.PaymentId < 1)
{
result.Succeed = false;
result.StatusCode = result.PaymentId.ToString();
//
ES.TaskManager.WriteError("Could not add customer payment record to the db");
ES.TaskManager.WriteParameter("ResultCode", result.StatusCode);
// EXIT
return result;
}
}
// if transaction is already submitted just update it's status
if (tran != null)
StorehouseController.UpdateTransactionStatus(tran.PaymentId, pgResult.TransactionStatus);
// OK
result.Succeed = true;
// ensure user requests to persist his payment details for credit card
if (details.Persistent && methodName == PaymentMethod.CREDIT_CARD)
StorehouseController.SetPaymentProfile(contractId, details);
}
catch (Exception ex)
{
result.Succeed = false;
result.StatusCode = GENERAL_FAILURE;
//
ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
// EXIT
return result;
}
#endregion
}
}

View file

@ -1,543 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class DomainNameController : ServiceProvisioningBase, IServiceProvisioning
{
public const string SOURCE_NAME = "SPF_DOMAIN_NAME";
public static Dictionary<int, string> ApiErrorCodesMap;
static DomainNameController()
{
ApiErrorCodesMap = new Dictionary<int, string>();
ApiErrorCodesMap.Add(BusinessErrorCodes.ERROR_DOMAIN_QUOTA_LIMIT, ERROR_DOMAIN_QUOTA_EXCEEDED);
}
#region Trace Messages
public const string START_ACTIVATION_MSG = "Starting domain name activation";
public const string START_SUSPENSION_MSG = "Starting domain name suspension";
public const string START_CANCELLATION_MSG = "Starting domain name cancellation";
public const string START_ROLLBACK_MSG = "Trying rollback operation";
public const string TLD_PROVISIONED_MSG = "Domain name has been provisioned";
#endregion
#region Error Messages
public const string ERROR_UPDATE_USR_SETTINGS_MSG = "Could not update user settings";
public const string ERROR_ADD_INTERNAL_DOMAIN = "Could not add internal domain";
public const string ERROR_DOMAIN_QUOTA_EXCEEDED = "Domain quota has been exceeded in the customer's hosting plan";
public const string ERROR_ROLLBACK_DOM_MSG = "Could not rollback added internal domain";
#endregion
protected DomainNameSvc GetDomainNameSvc(int serviceId)
{
// assemble svc instance
DomainNameSvc domainSvc = ObjectUtils.FillObjectFromDataReader<DomainNameSvc>(
EcommerceProvider.GetDomainNameSvc(SecurityContext.User.UserId, serviceId));
// deserialize svc properties
SecurityUtils.DeserializeGenericProfile(domainSvc.PropertyNames, domainSvc.PropertyValues, domainSvc);
// return result
return domainSvc;
}
protected InvoiceItem GetDomainSvcSetupFee(DomainNameSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.Quantity = 1;
line.UnitPrice = service.SetupFee;
line.TypeName = "Setup Fee";
return line;
}
protected InvoiceItem GetDomainSvcFee(DomainNameSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.ServiceId = service.ServiceId;
line.Quantity = 1;
line.UnitPrice = service.RecurringFee;
// define line type
if (service.Status != ServiceStatus.Ordered)
{
line.TypeName = "Recurring Fee";
}
else
{
switch (service["SPF_ACTION"])
{
case DomainNameSvc.SPF_TRANSFER_ACTION:
line.TypeName = String.Concat(Product.TOP_LEVEL_DOMAIN_NAME, " Transfer");
break;
case DomainNameSvc.SPF_REGISTER_ACTION:
line.TypeName = String.Concat(Product.TOP_LEVEL_DOMAIN_NAME, " Registration");
break;
}
}
return line;
}
#region IServiceProvisioning Members
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
{
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
EcommerceProvider.GetDomainNameSvcHistory(SecurityContext.User.UserId, serviceId));
//
if (history != null)
return history.ToArray();
//
return new ServiceHistoryRecord[] { };
}
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
{
List<InvoiceItem> lines = new List<InvoiceItem>();
//
DomainNameSvc domainSvc = GetDomainNameSvc(serviceId);
//
if (domainSvc["SPF_ACTION"] != DomainNameSvc.SPF_UPDATE_NS_ACTION)
{
// domain svc fee
lines.Add(GetDomainSvcFee(domainSvc));
// setup fee
if (domainSvc.SetupFee > 0M && domainSvc.Status == ServiceStatus.Ordered)
lines.Add(GetDomainSvcSetupFee(domainSvc));
}
//
return lines.ToArray();
}
public Service GetServiceInfo(int serviceId)
{
return GetDomainNameSvc(serviceId);
}
public int UpdateServiceInfo(Service serviceInfo)
{
DomainNameSvc domainSvc = (DomainNameSvc)serviceInfo;
// serialize props & values
string propertyNames = null;
string propertyValues = null;
SecurityUtils.SerializeGenericProfile(ref propertyNames, ref propertyValues, domainSvc);
// update svc
return EcommerceProvider.UpdateDomainNameSvc(SecurityContext.User.UserId, domainSvc.ServiceId,
domainSvc.ProductId, (int)domainSvc.Status, domainSvc.DomainId, domainSvc.Fqdn,
propertyNames, propertyValues);
}
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
{
string propertyNames = null;
string propertyValues = null;
// deserialize
SecurityUtils.SerializeGenericProfile(ref propertyNames, ref propertyValues, orderItem);
//
return EcommerceProvider.AddDomainNameSvc(contractId, orderItem.ParentSvcId,
orderItem.ProductId, orderItem.ItemName, orderItem.BillingCycle, currency, propertyNames, propertyValues);
}
public GenericSvcResult ActivateService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
// remeber svc state
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
// concretize service to be provisioned
DomainNameSvc domainSvc = (DomainNameSvc)context.ServiceInfo;
// concretize parent service
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ParentSvcInfo;
try
{
// LOG INFO
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
TaskManager.WriteParameter(CONTRACT_PARAM, domainSvc.ContractId);
TaskManager.WriteParameter(SVC_PARAM, domainSvc.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, domainSvc.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// error: hosting addon should have parent svc assigned
if (packageSvc == null || packageSvc.PackageId == 0)
{
result.Succeed = false;
//
result.Error = PARENT_SVC_NOT_FOUND_MSG;
//
result.ResultCode = EcommerceErrorCodes.ERROR_PARENT_SVC_NOT_FOUND;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// first of all - create internal domain in WebsitePanel
if (domainSvc.Status == ServiceStatus.Ordered)
{
// create domain info object
DomainInfo domain = ServerController.GetDomain(domainSvc.Fqdn);
//
if (domain != null)
domainSvc.DomainId = domain.DomainId;
//
if (domain == null)
{
domain = new DomainInfo();
domain.DomainName = domainSvc.Fqdn;
domain.HostingAllowed = false;
domain.PackageId = packageSvc.PackageId;
// add internal domain
domainSvc.DomainId = ServerController.AddDomain(domain);
// check API result
if (domainSvc.DomainId < 1)
{
// ASSEMBLE ERROR
result.Succeed = false;
// try to find corresponding error code->error message mapping
if (ApiErrorCodesMap.ContainsKey(domainSvc.DomainId))
result.Error = ApiErrorCodesMap[domainSvc.DomainId];
else
result.Error = ERROR_ADD_INTERNAL_DOMAIN;
// copy result code
result.ResultCode = domainSvc.DomainId;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
}
}
// update nameservers only
if (domainSvc["SPF_ACTION"] == "UPDATE_NS")
{
// remove service here...
ServiceController.DeleteCustomerService(domainSvc.ServiceId);
//
result.Succeed = true;
// EXIT
return result;
}
// load registrar wrapper
IDomainRegistrar registrar = (IDomainRegistrar)SystemPluginController.GetSystemPluginInstance(
domainSvc.ContractId, domainSvc.PluginId, true);
#region Commented operations
// prepare consumer account information
/*CommandParams cmdParams = PrepeareAccountParams(context.ConsumerInfo);
// copy svc properties
foreach (string keyName in domainSvc.GetAllKeys())
cmdParams[keyName] = domainSvc[keyName];
// check registrar requires sub-account to be created
if (registrar.SubAccountRequired)
{
// 1. Load user's settings
UserSettings userSettings = LoadUserSettings(context.ConsumerInfo.UserId, registrar.PluginName);
// 2. Ensure user has account on registrar's side
if (userSettings.SettingsArray == null || userSettings.SettingsArray.Length == 0)
{
// 3. Check account exists
bool exists = registrar.CheckSubAccountExists(context.ConsumerInfo.Username, context.ConsumerInfo.Email);
//
AccountResult accResult = null;
//
if (!exists)
{
// 4. Create user account
accResult = registrar.CreateSubAccount(cmdParams);
// copy keys & values
foreach (string keyName in accResult.AllKeys)
{
userSettings[keyName] = accResult[keyName];
}
}
else
{
// 4a. Get sub-account info
accResult = registrar.GetSubAccount(context.ConsumerInfo.Username,
context.ConsumerInfo.Email);
//
foreach (string keyName in accResult.AllKeys)
userSettings[keyName] = accResult[keyName];
}
// 5. Update user settings
int apiResult = UserController.UpdateUserSettings(userSettings);
// check API result
if (apiResult < 0)
{
// BUILD ERROR
result.Error = ERROR_UPDATE_USR_SETTINGS_MSG;
result.Succeed = false;
result.ResultCode = apiResult;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK
RollbackOperation(domainSvc.DomainId);
// EXIT
return result;
}
}
// copy registrar-specific data
foreach (string[] pair in userSettings.SettingsArray)
{
// copy 2
cmdParams[pair[0]] = pair[1];
}
}*/
#endregion
// load NS settings
PackageSettings nsSettings = PackageController.GetPackageSettings(packageSvc.PackageId, PackageSettings.NAME_SERVERS);
// build name servers array
string[] nameServers = null;
if (!String.IsNullOrEmpty(nsSettings[PackageSettings.NAME_SERVERS]))
nameServers = nsSettings[PackageSettings.NAME_SERVERS].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// register or renew domain
if (domainSvc.Status == ServiceStatus.Ordered)
// try to register domain
registrar.RegisterDomain(domainSvc, context.ConsumerInfo, nameServers);
else
// try to renew domain
registrar.RenewDomain(domainSvc, context.ConsumerInfo, nameServers);
// change svc status to active
domainSvc.Status = ServiceStatus.Active;
// update service info
int updResult = UpdateServiceInfo(domainSvc);
// check update result for errors
if (updResult < 0)
{
// BUILD ERROR
result.ResultCode = updResult;
result.Succeed = false;
result.Error = ERROR_SVC_UPDATE_MSG;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK
RollbackOperation(domainSvc.DomainId);
// EXIT
return result;
}
//
result.Succeed = true;
//
SetOutboundParameters(context);
}
catch (Exception ex)
{
// LOG ERROR
TaskManager.WriteError(ex);
result.Succeed = false;
// ROLLBACK
RollbackOperation(result.ResultCode);
}
finally
{
TaskManager.CompleteTask();
}
//
return result;
}
public GenericSvcResult SuspendService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
result.Succeed = true;
//
DomainNameSvc service = (DomainNameSvc)context.ServiceInfo;
service.Status = ServiceStatus.Suspended;
//
UpdateServiceInfo(service);
//
SetOutboundParameters(context);
//
return result;
}
public GenericSvcResult CancelService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
result.Succeed = true;
//
DomainNameSvc service = (DomainNameSvc)context.ServiceInfo;
service.Status = ServiceStatus.Cancelled;
//
UpdateServiceInfo(service);
//
SetOutboundParameters(context);
//
return result;
}
public void LogServiceUsage(ProvisioningContext context)
{
// concretize svc to be provisioned
DomainNameSvc domainSvc = (DomainNameSvc)context.ServiceInfo;
//
base.LogServiceUsage(context.ServiceInfo, domainSvc.SvcCycleId,
domainSvc.BillingPeriod, domainSvc.PeriodLength);
}
#endregion
private void RollbackOperation(int domainId)
{
if (domainId < 1)
return;
try
{
// restore
DomainNameSvc domainSvc = (DomainNameSvc)RestoreObjectState(SERVICE_INFO);
int apiResult = 0;
switch (domainSvc.Status)
{
// Service
case ServiceStatus.Ordered:
apiResult = ServerController.DeleteDomain(domainId);
break;
}
// check API result
if (apiResult < 0)
{
// LOG ERROR
TaskManager.WriteError(ERROR_ROLLBACK_DOM_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
}
// rollback service changes in EC metabase
apiResult = UpdateServiceInfo(domainSvc);
// check API result
if (apiResult < 0)
{
// LOG ERROR
TaskManager.WriteError(ERROR_ROLLBACK_SVC_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
// EXIT
return;
}
//
TaskManager.Write(ROLLBACK_SUCCEED_MSG);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
/// <summary>
/// Loads user's plugin-specific settings
/// </summary>
/// <param name="userId"></param>
/// <param name="pluginName"></param>
/// <returns></returns>
private UserSettings LoadUserSettings(int userId, string pluginName)
{
// build settings name
string settingsName = pluginName + "Settings";
// load user settings
UserSettings settings = UserController.GetUserSettings(userId, settingsName);
// set settings name
settings.SettingsName = settingsName;
//
return settings;
}
private CommandParams PrepeareAccountParams(UserInfo userInfo)
{
CommandParams args = new CommandParams();
args[CommandParams.USERNAME] = userInfo.Username;
args[CommandParams.PASSWORD] = userInfo.Password;
args[CommandParams.FIRST_NAME] = userInfo.FirstName;
args[CommandParams.LAST_NAME] = userInfo.LastName;
args[CommandParams.EMAIL] = userInfo.Email;
args[CommandParams.ADDRESS] = userInfo.Address;
args[CommandParams.CITY] = userInfo.City;
args[CommandParams.STATE] = userInfo.State;
args[CommandParams.COUNTRY] = userInfo.Country;
args[CommandParams.ZIP] = userInfo.Zip;
args[CommandParams.PHONE] = userInfo.PrimaryPhone;
args[CommandParams.FAX] = userInfo.Fax;
return args;
}
}
}

View file

@ -1,673 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class HostingAddonController : ServiceProvisioningBase, IServiceProvisioning
{
public const string SOURCE_NAME = "SPF_HOSTING_ADDN";
#region Trace Messages
public const string START_ACTIVATION_MSG = "Starting addon activation";
public const string START_SUSPENSION_MSG = "Starting addon suspension";
public const string START_CANCELLATION_MSG = "Starting addon cancellation";
public const string START_ROLLBACK_MSG = "Trying rollback operation";
public const string ADDON_PROVISIONED_MSG = "Addon has been provisioned";
#endregion
#region Error Messages
public const string ERROR_CREATE_ADDON_MSG = "Could not create hosting addon";
public const string ERROR_ACTIVATE_ADDON_MSG = "Could not activate hosting addon";
public const string ERROR_SUSPEND_ADDON_MSG = "Could not suspend hosting addon";
public const string ERROR_CANCEL_ADDON_MSG = "Could not cancel hosting addon";
public const string ERROR_ROLLBACK_ORDER_MSG = "Could not rollback operation and delete addon";
public const string ERROR_ROLLBACK_MSG = "Could not rollback operation and revert addon state";
public const string ADDON_NOT_FOUND_MSG = "Could not find hosting addon";
#endregion
protected HostingAddonSvc GetHostingAddonSvc(int serviceId)
{
return ObjectUtils.FillObjectFromDataReader<HostingAddonSvc>(
EcommerceProvider.GetHostingAddonSvc(SecurityContext.User.UserId, serviceId));
}
protected InvoiceItem GetAddonSvcFee(HostingAddonSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.ServiceId = service.ServiceId;
line.Quantity = service.Quantity;
line.UnitPrice = service.CyclePrice;
if (service.Recurring && service.Status != ServiceStatus.Ordered)
line.TypeName = "Recurring Fee";
else
line.TypeName = Product.HOSTING_ADDON_NAME;
return line;
}
protected InvoiceItem GetAddonSvcSetupFee(HostingAddonSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.Quantity = service.Quantity;
line.UnitPrice = service.SetupFee;
line.TypeName = "Setup Fee";
return line;
}
#region IServiceProvisioning Members
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
{
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
EcommerceProvider.GetHostingAddonSvcHistory(SecurityContext.User.UserId, serviceId));
//
if (history != null)
return history.ToArray();
//
return new ServiceHistoryRecord[] { };
}
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
{
List<InvoiceItem> lines = new List<InvoiceItem>();
//
HostingAddonSvc addonSvc = GetHostingAddonSvc(serviceId);
// addon svc fee
lines.Add(GetAddonSvcFee(addonSvc));
// addon svc setup fee
if (addonSvc.SetupFee > 0M && addonSvc.Status == ServiceStatus.Ordered)
lines.Add(GetAddonSvcSetupFee(addonSvc));
//
return lines.ToArray();
}
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
{
// get hosting addon product
HostingAddon addon = StorehouseController.GetHostingAddon(SecurityContext.User.UserId,
orderItem.ProductId);
// uncountable addons always have 1 for quantity
int quantity = addon.Countable ? orderItem.Quantity : 1;
// add hosting addon
return EcommerceProvider.AddHostingAddonSvc(contractId, orderItem.ParentSvcId, orderItem.ProductId,
quantity, orderItem.ItemName, orderItem.BillingCycle, currency);
}
public Service GetServiceInfo(int serviceId)
{
return GetHostingAddonSvc(serviceId);
}
public int UpdateServiceInfo(Service serviceInfo)
{
HostingAddonSvc addonSvc = (HostingAddonSvc)serviceInfo;
//
return EcommerceProvider.UpdateHostingAddonSvc(SecurityContext.User.UserId, addonSvc.ServiceId,
addonSvc.ProductId, addonSvc.ServiceName, (int)addonSvc.Status, addonSvc.PlanId,
addonSvc.PackageAddonId, addonSvc.Recurring, addonSvc.DummyAddon);
}
public GenericSvcResult ActivateService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
// remeber svc state
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
// concretize service to be provisioned
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
// concretize parent svc
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ParentSvcInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
// LOG INFO
TaskManager.Write(START_ACTIVATION_MSG);
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// dummy addon should be just updated in metabase
if (addonSvc.DummyAddon)
goto UpdateSvcMetaInfo;
if (addonSvc.Status == ServiceStatus.Ordered)
{
// error: hosting addon should have parent svc assigned
if (packageSvc == null || packageSvc.PackageId == 0)
{
result.Succeed = false;
//
result.Error = PARENT_SVC_NOT_FOUND_MSG;
//
result.ResultCode = EcommerceErrorCodes.ERROR_PARENT_SVC_NOT_FOUND;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// fill package add-on fields
PackageAddonInfo addon = new PackageAddonInfo();
//
addon.PackageId = packageSvc.PackageId;
//
addon.PlanId = addonSvc.PlanId;
// set addon quantity
addon.Quantity = addonSvc.Quantity;
//
addon.StatusId = (int)PackageStatus.Active;
//
addon.PurchaseDate = DateTime.Now;
// Create hosting addon through WebsitePanel API
PackageResult apiResult = PackageController.AddPackageAddon(addon);
// Failed to create addon
if (apiResult.Result < 1)
{
result.Succeed = false;
//
result.ResultCode = apiResult.Result;
// LOG ERROR
TaskManager.WriteError(ERROR_CREATE_ADDON_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// store package id
addonSvc.PackageAddonId = apiResult.Result;
}
else
{
// load package addon
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
// package addon not found
if (addonInfo == null)
{
result.Succeed = false;
//
result.ResultCode = EcommerceErrorCodes.ERROR_PCKG_ADDON_NOT_FOUND;
//
result.Error = ADDON_NOT_FOUND_MSG;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// workaround for bug in GetPackageAddon routine
//addonInfo.PackageAddonId = addonSvc.PackageAddonId;
// change package add-on status
addonInfo.StatusId = (int)PackageStatus.Active;
// save hosting addon changes
PackageResult apiResult = PackageController.UpdatePackageAddon(addonInfo);
// check returned result
if (apiResult.Result < 0)
{
result.Succeed = false;
//
result.ResultCode = apiResult.Result;
// LOG ERROR
TaskManager.WriteError(ERROR_ACTIVATE_ADDON_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
}
UpdateSvcMetaInfo:
// update status only if necessary
if (addonSvc.Status != ServiceStatus.Active)
{
// change service status to active
addonSvc.Status = ServiceStatus.Active;
// put data into metabase
int svcResult = UpdateServiceInfo(addonSvc);
// failed to update metabase
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Succeed = false;
//
result.Error = ERROR_SVC_UPDATE_MSG;
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
// EXIT
return result;
}
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(ADDON_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public GenericSvcResult SuspendService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
// concretize service to be provisioned
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_SUSPEND);
// LOG INFO
TaskManager.Write(START_SUSPENSION_MSG);
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// dummy addon should be just updated in metabase
if (addonSvc.DummyAddon)
goto UpdateSvcMetaInfo;
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
addonInfo.StatusId = (int)PackageStatus.Suspended;
// suspend hosting addon
int apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
// check WebsitePanel API result
if (apiResult < 0)
{
result.ResultCode = apiResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_SUSPEND_ADDON_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// exit
return result;
}
UpdateSvcMetaInfo:
// change addon status to Suspended
addonSvc.Status = ServiceStatus.Suspended;
// put data into metabase
int svcResult = UpdateServiceInfo(addonSvc);
//
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
// EXIT
return result;
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(ADDON_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public GenericSvcResult CancelService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
// concretize service to be provisioned
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL);
// LOG INFO
TaskManager.Write(START_CANCELLATION_MSG);
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// dummy addon should be just updated in metabase
if (addonSvc.DummyAddon)
goto UpdateSvcMetaInfo;
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
addonInfo.StatusId = (int)PackageStatus.Cancelled;
// cancel hosting addon
int apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
// check WebsitePanel API result
if (apiResult < 0)
{
result.ResultCode = apiResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_CANCEL_ADDON_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// exit
return result;
}
UpdateSvcMetaInfo:
// change addon status to Cancelled
addonSvc.Status = ServiceStatus.Cancelled;
// put data into metabase
int svcResult = UpdateServiceInfo(addonSvc);
//
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
// EXIT
return result;
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(ADDON_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(addonSvc.PackageAddonId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public void LogServiceUsage(ProvisioningContext context)
{
// concretize service to be logged
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
// addon is recurring
if (addonSvc.Recurring)
{
// log service usage
base.LogServiceUsage(context.ServiceInfo, addonSvc.SvcCycleId,
addonSvc.BillingPeriod, addonSvc.PeriodLength);
}
}
#endregion
protected void RollbackOperation(int packageAddonId)
{
// check input parameters first
if (packageAddonId < 1)
return; // exit
//
try
{
TaskManager.Write(START_ROLLBACK_MSG);
// restore service
HostingAddonSvc addonSvc = (HostingAddonSvc)RestoreObjectState(SERVICE_INFO);
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
//
int apiResult = 0;
// during rollback addon should be reverted to its original state
// compensation logic - revert back addon status
switch (addonSvc.Status)
{
// Active State
case ServiceStatus.Active:
addonInfo.StatusId = (int)PackageStatus.Active;
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
break;
// Suspended State
case ServiceStatus.Suspended:
addonInfo.StatusId = (int)PackageStatus.Suspended;
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
break;
// Cancelled State
case ServiceStatus.Cancelled:
addonInfo.StatusId = (int)PackageStatus.Cancelled;
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
break;
// service has been just ordered & during rollback should be removed
case ServiceStatus.Ordered:
// compensation logic - remove created package
apiResult = PackageController.DeletePackageAddon(packageAddonId);
break;
}
// check WebsitePanel API result
if (apiResult < 0)
{
//
if (addonSvc.Status == ServiceStatus.Ordered)
TaskManager.WriteError(ERROR_ROLLBACK_ORDER_MSG);
else
TaskManager.WriteError(ERROR_ROLLBACK_MSG);
//
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
}
// rollback service changes in EC metabase
apiResult = UpdateServiceInfo(addonSvc);
// check API result
if (apiResult < 0)
{
// LOG ERROR
TaskManager.WriteError(ERROR_ROLLBACK_SVC_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
//
return;
}
//
TaskManager.Write(ROLLBACK_SUCCEED_MSG);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
}

View file

@ -1,676 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class HostingPackageController : ServiceProvisioningBase, IServiceProvisioning
{
//
public const string SOURCE_NAME = "SPF_HOSTING_PKG";
#region Trace Messages
public const string START_ACTIVATION_MSG = "Starting package activation";
public const string START_SUSPENSION_MSG = "Starting package suspension";
public const string START_CANCELLATION_MSG = "Starting package cancellation";
public const string CREATE_PCKG_MSG = "Creating new hosting package";
public const string CREATE_PCKG_ERROR_MSG = "Could not create hosting package";
public const string ERROR_ACTIVATE_PCKG_MSG = "Could not activate hosting package";
public const string ERROR_SUSPEND_PCKG_MSG = "Could not suspend hosting package";
public const string ERROR_CANCEL_PCKG_MSG = "Could not cancel hosting package";
public const string START_USR_ACTIVATION_MSG = "Activating service consumer account";
public const string START_CHANGE_USR_ROLE_MSG = "Changing consumer user role";
public const string ERROR_USR_ACTIVATION_MSG = "Could not activate consumer account";
public const string ERROR_CHANGE_USR_ROLE_MSG = "Could not change consumer user role";
public const string PCKG_PROVISIONED_MSG = "Package has been provisioned";
#endregion
protected HostingPackageSvc GetHostingPackageSvc(int serviceId)
{
return ObjectUtils.FillObjectFromDataReader<HostingPackageSvc>(
EcommerceProvider.GetHostingPackageSvc(SecurityContext.User.UserId, serviceId));
}
protected InvoiceItem GetSetupFeeInvoiceLine(HostingPackageSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.Quantity = 1;
line.UnitPrice = service.SetupFee;
line.TypeName = "Setup Fee";
return line;
}
protected InvoiceItem GetRecurringFeeInvoiceLine(HostingPackageSvc service)
{
InvoiceItem line = new InvoiceItem();
line.ItemName = service.ServiceName;
line.ServiceId = service.ServiceId;
line.Quantity = 1;
line.UnitPrice = service.RecurringFee;
line.TypeName = (service.Status == ServiceStatus.Ordered) ? Product.HOSTING_PLAN_NAME : "Recurring Fee";
return line;
}
#region IServiceProvisioning Members
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
{
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
EcommerceProvider.GetHostingPackageSvcHistory(SecurityContext.User.UserId, serviceId));
if (history != null)
return history.ToArray();
return new ServiceHistoryRecord[] { };
}
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
{
List<InvoiceItem> lines = new List<InvoiceItem>();
// load svc
HostingPackageSvc packageSvc = GetHostingPackageSvc(serviceId);
// recurring fee
lines.Add(GetRecurringFeeInvoiceLine(packageSvc));
// setup fee
if (packageSvc.Status == ServiceStatus.Ordered && packageSvc.SetupFee > 0M)
lines.Add(GetSetupFeeInvoiceLine(packageSvc));
return lines.ToArray();
}
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
{
return EcommerceProvider.AddHostingPlanSvc(contractId, orderItem.ProductId,
orderItem.ItemName, orderItem.BillingCycle, currency);
}
public Service GetServiceInfo(int serviceId)
{
return GetHostingPackageSvc(serviceId);
}
public int UpdateServiceInfo(Service service)
{
HostingPackageSvc packageSvc = (HostingPackageSvc)service;
//
return EcommerceProvider.UpdateHostingPlanSvc(SecurityContext.User.UserId, packageSvc.ServiceId,
packageSvc.ProductId, packageSvc.ServiceName, (int)packageSvc.Status, packageSvc.PlanId,
packageSvc.PackageId, (int)packageSvc.UserRole, (int)packageSvc.InitialStatus);
}
public GenericSvcResult ActivateService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
//
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
// concretize service to be provisioned
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
// LOG INFO
TaskManager.Write(START_ACTIVATION_MSG);
TaskManager.WriteParameter(USERNAME_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL] = context.SendEmail;
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// 1. Hosting package is just ordered
if (context.ServiceInfo.Status == ServiceStatus.Ordered && context.ContractInfo.CustomerId > 0)
{
// LOG INFO
TaskManager.Write(CREATE_PCKG_MSG);
// create new package
PackageResult apiResult = PackageController.AddPackage(context.ContractInfo.CustomerId, packageSvc.PlanId,
packageSvc.ServiceName, String.Empty, (int)packageSvc.InitialStatus, DateTime.Now, true, true);
// failed to instantiate package
if (apiResult.Result <= 0)
{
result.ResultCode = apiResult.Result;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(CREATE_PCKG_ERROR_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// save result PackageId
packageSvc.PackageId = apiResult.Result;
}
else // 2. Package requires only to update its status
{
// LOG INFO
TaskManager.Write(START_ACTIVATION_MSG);
//
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
PackageStatus.Active, false);
//
if (apiResult < 0)
{
result.ResultCode = apiResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_ACTIVATE_PCKG_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
}
// check user role
if (context.ContractInfo.CustomerId > 0)
{
UserInfo user = UserController.GetUserInternally(context.ContractInfo.CustomerId);
// check user status
//
if (user.Status != UserStatus.Active)
{
// LOG INFO
TaskManager.Write(START_USR_ACTIVATION_MSG);
// trying to change user status
int userResult = UserController.ChangeUserStatus(context.ContractInfo.CustomerId,
UserStatus.Active);
// failed to activate user account
if (userResult < 0)
{
result.ResultCode = userResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_USR_ACTIVATION_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(result.ResultCode);
// EXIT
return result;
}
}
// check user role
if (user.Role != packageSvc.UserRole)
{
// LOG INFO
TaskManager.Write(START_CHANGE_USR_ROLE_MSG);
//
user.Role = packageSvc.UserRole;
// trying to change user role
int roleResult = UserController.UpdateUser(user);
// failed to change user role
if (roleResult < 0)
{
result.ResultCode = roleResult;
//
result.Succeed = false;
//
TaskManager.WriteError(ERROR_CHANGE_USR_ROLE_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(result.ResultCode);
// EXIT
return result;
}
}
}
// update plan status if necessary
if (packageSvc.Status != ServiceStatus.Active)
{
// change service status to active
packageSvc.Status = ServiceStatus.Active;
// put data into metabase
int svcResult = UpdateServiceInfo(packageSvc);
// error updating svc details
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Succeed = false;
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
// LOG ERROR
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(PCKG_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public GenericSvcResult SuspendService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
//
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
// concretize service to be provisioned
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_SUSPEND);
// LOG INFO
TaskManager.Write(START_SUSPENSION_MSG);
TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// suspend hosting package
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
PackageStatus.Suspended, false);
// check WebsitePanel API result
if (apiResult < 0)
{
result.ResultCode = apiResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_SUSPEND_PCKG_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// exit
return result;
}
// change service status to Suspended
packageSvc.Status = ServiceStatus.Suspended;
// put data into metabase
int svcResult = UpdateServiceInfo(packageSvc);
//
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
//
return result;
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(PCKG_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public GenericSvcResult CancelService(ProvisioningContext context)
{
GenericSvcResult result = new GenericSvcResult();
//
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
//
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
// concretize service to be provisioned
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
//
try
{
//
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL);
// LOG INFO
TaskManager.Write(START_CANCELLATION_MSG);
TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
// 0. Do security checks
if (!CheckOperationClientPermissions(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
if (!CheckOperationClientStatus(result))
{
// LOG ERROR
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// cancel hosting package
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
PackageStatus.Cancelled, false);
// check WebsitePanel API result
if (apiResult < 0)
{
//
result.ResultCode = apiResult;
//
result.Succeed = false;
// LOG ERROR
TaskManager.WriteError(ERROR_CANCEL_PCKG_MSG);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
// change service status to Cancelled
packageSvc.Status = ServiceStatus.Cancelled;
// put data into metabase
int svcResult = UpdateServiceInfo(packageSvc);
//
if (svcResult < 0)
{
result.ResultCode = svcResult;
//
result.Error = ERROR_SVC_UPDATE_MSG;
//
result.Succeed = false;
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
// LOG ERROR
TaskManager.WriteError(result.Error);
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
// EXIT
return result;
}
//
SetOutboundParameters(context);
// LOG INFO
TaskManager.Write(PCKG_PROVISIONED_MSG);
//
result.Succeed = true;
}
catch (Exception ex)
{
//
TaskManager.WriteError(ex);
// ROLLBACK CHANGES
RollbackOperation(packageSvc.PackageId);
//
result.Succeed = false;
//
result.Error = ex.Message;
}
finally
{
// complete task
TaskManager.CompleteTask();
}
//
return result;
}
public void LogServiceUsage(ProvisioningContext context)
{
// concretize service to be logged
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
// log service usage
base.LogServiceUsage(context.ServiceInfo, packageSvc.SvcCycleId,
packageSvc.BillingPeriod, packageSvc.PeriodLength);
}
protected void RollbackOperation(int packageId)
{
// check input parameters first
if (packageId < 1)
return; // exit
//
try
{
TaskManager.Write("Trying rollback operation");
// restore service
HostingPackageSvc packageSvc = (HostingPackageSvc)RestoreObjectState("ServiceInfo");
// restore consumer
UserInfo consumer = (UserInfo)RestoreObjectState("ConsumerInfo");
//
int apiResult = 0;
// rollback consumer changes first
apiResult = UserController.UpdateUser(consumer);
// check WebsitePanel API result
if (apiResult < 0)
{
//
TaskManager.WriteError("Could not rollback consumer changes");
//
TaskManager.WriteParameter("ResultCode", apiResult);
}
// during rollback package should be reverted to its original state
// compensation logic - revert back package status
switch (packageSvc.Status)
{
// Active State
case ServiceStatus.Active:
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Active, false);
break;
// Suspended State
case ServiceStatus.Suspended:
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Suspended, false);
break;
// Cancelled State
case ServiceStatus.Cancelled:
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Cancelled, false);
break;
// service has been just ordered & during rollback should be removed
case ServiceStatus.Ordered:
// compensation logic - remove created package
apiResult = PackageController.DeletePackage(packageId);
break;
}
// check WebsitePanel API result
if (apiResult < 0)
{
//
if (packageSvc.Status == ServiceStatus.Ordered)
TaskManager.WriteError("Could not rollback operation and delete package");
else
TaskManager.WriteError("Could not rollback operation and revert package state");
//
TaskManager.WriteParameter("ResultCode", apiResult);
}
// rollback service changes in EC metabase
apiResult = UpdateServiceInfo(packageSvc);
// check API result
if (apiResult < 0)
{
//
TaskManager.WriteError("Could not rollback service changes");
//
TaskManager.WriteParameter("ResultCode", apiResult);
}
//
TaskManager.Write("Rollback succeed");
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
#endregion
}
}

View file

@ -1,50 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public interface IServiceProvisioning
{
ServiceHistoryRecord[] GetServiceHistory(int serviceId);
InvoiceItem[] CalculateInvoiceLines(int serviceId);
ProvisioningContext GetProvisioningContext(int serviceId, bool sendEmail);
int AddServiceInfo(string contractId, string currency, OrderItem orderItem);
int UpdateServiceInfo(Service serviceInfo);
Service GetServiceInfo(int serviceId);
GenericSvcResult ActivateService(ProvisioningContext context);
GenericSvcResult SuspendService(ProvisioningContext context);
GenericSvcResult CancelService(ProvisioningContext context);
void LogServiceUsage(ProvisioningContext context);
}
}

View file

@ -1,102 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
/// <summary>
/// Represents context for provisioning controllers
/// </summary>
public class ProvisioningContext
{
private Contract contractInfo;
private ContractAccount consumerInfo;
private Service serviceInfo;
private Service parentSvcInfo;
private bool sendEmail;
public bool SendEmail
{
get { return sendEmail; }
set { sendEmail = value; }
}
/// <summary>
/// Gets service consumer contract information
/// </summary>
public Contract ContractInfo
{
get { return contractInfo; }
}
/// <summary>
/// Gets service consumer information
/// </summary>
public ContractAccount ConsumerInfo
{
get { return consumerInfo; }
}
/// <summary>
/// Get service information
/// </summary>
public Service ServiceInfo
{
get { return serviceInfo; }
}
/// <summary>
/// Get parent service information
/// </summary>
public Service ParentSvcInfo
{
get { return parentSvcInfo; }
}
/// <summary>
/// Ctor.
/// </summary>
/// <param name="service"></param>
/// <param name="consumer"></param>
public ProvisioningContext(Contract contract, Service service, ContractAccount consumer, Service parentSvc)
{
this.contractInfo = contract;
this.serviceInfo = service;
this.consumerInfo = consumer;
this.parentSvcInfo = parentSvc;
}
}
}

View file

@ -1,362 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class Memento
{
private string mStateObjectType;
private Hashtable mementoState;
public Memento()
{
//
mementoState = new Hashtable();
}
/// <summary>
/// Saves object public properties state using reflection. Does not support indexed properties.
/// </summary>
/// <param name="objectKey"></param>
/// <param name="value"></param>
public void SaveObjectState(object value)
{
//
Type valueType = value.GetType();
//
PropertyInfo[] properties = valueType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
//
if (properties != null && properties.Length > 0)
{
//
Hashtable stateHash = new Hashtable();
//
foreach (PropertyInfo property in properties)
{
// copy property value
if (property.GetIndexParameters() == null || property.GetIndexParameters().Length == 0)
mementoState.Add(property.Name, property.GetValue(value, null));
}
// save object full-qualified name
mStateObjectType = valueType.AssemblyQualifiedName;
}
}
public object RestoreObjectState()
{
// create object instance
object keyObject = Activator.CreateInstance(Type.GetType(mStateObjectType));
//
Type objectType = keyObject.GetType();
//
PropertyInfo[] properties = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
//
if (properties != null && properties.Length > 0)
{
// load object state back
foreach (PropertyInfo property in properties)
{
// restore property value back
if (property.GetIndexParameters() == null || property.GetIndexParameters().Length == 0)
property.SetValue(keyObject, mementoState[property.Name], null);
}
}
//
return keyObject;
}
}
public abstract class ServiceProvisioningBase
{
// Contants
public const string SERVICE_INFO = "ServiceInfo";
public const string CONSUMER_INFO = "ConsumerInfo";
#region Error Messages
public const string ERROR_SVC_UPDATE_MSG = "Could not update service data";
public const string PARENT_SVC_NOT_FOUND_MSG = "Could not find parent service assigned";
public const string ERROR_ROLLBACK_SVC_MSG = "Could not rollback service changes";
public const string ERROR_CLIENT_OPERATION_PERMISSIONS = "Account does not have enough permissions to do this operation";
public const string ERROR_CLIENT_OPERATION_STATUS = "Account is demo or suspended and not allowed to do this operation";
#endregion
#region Trace Messages
public const string ROLLBACK_SUCCEED_MSG = "Rollback succeed";
#endregion
#region Trace Parameters
public const string CONTRACT_PARAM = "ContractID";
public const string USERNAME_PARAM = "Username";
public const string SVC_PARAM = "Service";
public const string SVC_ID_PARAM = "ServiceID";
public const string RESULT_CODE_PARAM = "ResultCode";
public const string PCKG_PARAM = "Package";
public const string PCKG_ID_PARAM = "PackageID";
#endregion
public bool CheckOperationClientPermissions(GenericSvcResult result)
{
// 1. Do security checks
SecurityResult secResult = StorehouseController.CheckAccountIsAdminOrReseller();
// ERROR
if (!secResult.Success)
{
result.Succeed = false;
result.ResultCode = secResult.ResultCode;
//
return false;
}
//
return true;
}
public bool CheckOperationClientStatus(GenericSvcResult result)
{
// 2. Check account status
SecurityResult secResult = StorehouseController.CheckAccountNotDemoAndActive();
// ERROR
if (!secResult.Success)
{
result.Succeed = false;
result.ResultCode = secResult.ResultCode;
//
return false;
}
//
return true;
}
public ProvisioningContext GetProvisioningContext(int serviceId, bool sendEmail)
{
IServiceProvisioning controller = (IServiceProvisioning)this;
Service serviceInfo = controller.GetServiceInfo(serviceId);
Contract contractInfo = ContractSystem.ContractController.GetContract(serviceInfo.ContractId);
ContractAccount consumerInfo = ContractSystem.ContractController.GetContractAccountSettings(
serviceInfo.ContractId, true);
// load parent svc
Service parentSvcInfo = (serviceInfo.ParentId == 0) ? null :
ServiceController.GetService(serviceInfo.ParentId);
// return prepeared context
ProvisioningContext ctx = new ProvisioningContext(contractInfo, serviceInfo, consumerInfo, parentSvcInfo);
//
ctx.SendEmail = sendEmail;
//
return ctx;
}
//
private Dictionary<string, Memento> undoSteps = new Dictionary<string, Memento>();
protected void SaveObjectState(string objectKey, object value)
{
//
Memento memento = new Memento();
//
memento.SaveObjectState(value);
//
undoSteps.Add(objectKey, memento);
}
protected object RestoreObjectState(string objectKey)
{
//
if (!undoSteps.ContainsKey(objectKey))
return null;
//
Memento memento = undoSteps[objectKey];
//
return memento.RestoreObjectState();
}
protected void LogServiceUsage(Service service, int svcCycleId, string billingPeriod, int periodLength)
{
// define start date
DateTime startDate = ServiceController.GetServiceSuspendDate(service.ServiceId);
//
DateTime endDate = startDate;
//
switch (billingPeriod)
{
case "day":
endDate = startDate.AddDays(periodLength);
break;
case "month":
endDate = endDate.AddMonths(periodLength);
break;
case "year":
endDate = endDate.AddYears(periodLength);
break;
}
// add service usage record
EcommerceProvider.AddServiceUsageRecord(SecurityContext.User.UserId, service.ServiceId,
svcCycleId, startDate, endDate);
}
protected void SetOutboundParameters(ProvisioningContext context)
{
// set task outbound parameters
TaskManager.TaskParameters[SystemTaskParams.PARAM_SERVICE] = context.ServiceInfo;
TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = context.ContractInfo;
TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT_ACCOUNT] = context.ConsumerInfo;
TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL] = context.SendEmail;
}
}
/*public abstract class ProvisioningController
{
// user info (context)
// product general info
// cart prov settings
// product prov settings
// product type prov settings
//
#region Private vars
private string notificationTemplate;
private bool notificationLoaded;
private UserInfo userInfo;
private Service serviceInfo;
private KeyValueBunch serviceSettings;
#endregion
#region Public properties
public string NotificationTemplate
{
get
{
if (!notificationLoaded)
return notificationTemplate;
}
}
public UserInfo UserInfo
{
get { return userInfo; }
}
public Service ServiceInfo
{
get { return serviceInfo; }
}
public KeyValueBunch ServiceSettings
{
get { return serviceSettings; }
}
#endregion
#region Abstract routines
//
public abstract GenericSvcResult ActivateService(Service service);
//
public abstract GenericSvcResult SuspendService();
//
public abstract GenericSvcResult CancelService();
//
public abstract void RollbackOperation();
#endregion
protected ProvisioningController(Service serviceInfo)
{
this.serviceInfo = serviceInfo;
Initialize();
}
protected virtual void Initialize()
{
// get user profile
userInfo = UserController.GetUser(serviceInfo.UserId);
}
protected DateTime CalculateNextSuspendDate(DateTime startDate, string cyclePeriod, int cycleLength)
{
// calculate next suspend date
switch (cyclePeriod)
{
case "day":
return startDate.AddDays(cycleLength);
case "month":
return startDate.AddMonths(cycleLength);
case "year":
return startDate.AddYears(cycleLength);
}
//
return startDate;
}
public virtual void LoadProvisioningSettings()
{
throw new NotImplementedException();
// get service settings
/*serviceSettings = ServiceController.GetServiceSettings(
serviceInfo.SpaceId,
serviceInfo.ServiceId
);*/
/*}
public virtual void SaveProvisioningSettings()
{
if (ServiceSettings.HasPendingChanges)
{
/*int result = ServiceController.SetServiceSettings(
serviceInfo.SpaceId,
serviceInfo.ServiceId,
serviceSettings
);
if (result < 0)
throw new Exception("Unable to save provisioning settings. Status code: " + result);*/
/*}
}
}*/
}

View file

@ -1,304 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Xml;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using ES = WebsitePanel.EnterpriseServer;
using Common.Utils;
using Microsoft.ApplicationBlocks.Data;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class ServiceController
{
private ServiceController()
{
}
public static int SetUsageRecordsClosed(int[] serviceIds)
{
return EcommerceProvider.SetSvcsUsageRecordsClosed(
ES.SecurityContext.User.UserId, serviceIds);
}
#region Ecommerce v 2.1.0 routines
public static DateTime GetSvcsSuspendDateAligned(int[] services, DateTime defaultValue)
{
string svcsXml = Utils.BuildIdentityXmlFromArray(services, "Svcs", "Svc");
return EcommerceProvider.GetSvcsSuspendDateAligned(ES.SecurityContext.User.UserId,
svcsXml, defaultValue);
}
public static int ChangeHostingPlanSvcCycle(int serviceId, int productId, int cycleId, string currency)
{
return EcommerceProvider.ChangeHostingPlanSvcCycle(ES.SecurityContext.User.UserId, serviceId,
productId, cycleId, currency);
}
public static ProductType GetServiceItemType(int serviceId)
{
return ES.ObjectUtils.FillObjectFromDataReader<ProductType>(
EcommerceProvider.GetServiceItemType(serviceId));
}
public static Service GetRawCustomerService(int serviceId)
{
return ES.ObjectUtils.FillObjectFromDataReader<Service>(
EcommerceProvider.GetCustomerService(ES.SecurityContext.User.UserId, serviceId));
}
public static Service GetService(int serviceId)
{
// read service type
ProductType svcType = GetServiceItemType(serviceId);
// create svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svcType.ProvisioningController));
//
return controller.GetServiceInfo(serviceId);
}
public static Dictionary<int, Service> GetServicesDictionary(List<InvoiceItem> invoiceLines)
{
List<int> serviceIds = new List<int>();
//
foreach (InvoiceItem invoiceLine in Array.FindAll<InvoiceItem>(
invoiceLines.ToArray(), x => x.ServiceId > 0))
{
serviceIds.Add(invoiceLine.ServiceId);
}
//
return GetServicesDictionary(serviceIds);
}
public static Dictionary<int, Service> GetServicesDictionary(List<int> serviceIds)
{
Dictionary<int, Service> hash = new Dictionary<int, Service>();
//
foreach (int serviceId in serviceIds)
hash.Add(serviceId, GetService(serviceId));
//
return hash;
}
public static int UpdateService(Service service)
{
// read service type
ProductType svcType = GetServiceItemType(service.ServiceId);
// create svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svcType.ProvisioningController));
//
return controller.UpdateServiceInfo(service);
}
public static void AddServiceUsageRecord(int serviceId)
{
// read service type
ProductType svcType = GetServiceItemType(serviceId);
// create svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svcType.ProvisioningController));
//
controller.LogServiceUsage(controller.GetProvisioningContext(serviceId, false));
}
public static ServiceHistoryRecord[] GetServiceHistory(int serviceId)
{
// read service type
ProductType svcType = GetServiceItemType(serviceId);
// create svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svcType.ProvisioningController));
//
return controller.GetServiceHistory(serviceId);
}
public static GenericSvcResult ActivateService(int serviceId, bool sendEmail)
{
GenericSvcResult result = new GenericSvcResult();
try
{
Service svc = GetRawCustomerService(serviceId);
//
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_ACTIVATE);
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
//
ActivatePaidInvoicesTask task = new ActivatePaidInvoicesTask();
// obtain result
result = task.ActivateService(serviceId, sendEmail, false);
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
//
return result;
}
public static List<GenericSvcResult> ActivateInvoice(int invoiceId, bool sendEmail)
{
List<GenericSvcResult> results = new List<GenericSvcResult>();
try
{
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
//
ES.TaskManager.StartTask("SPF", "ACTIVATE_INVOICE");
ES.TaskManager.WriteParameter("InvoiceID", invoiceId);
//
ActivatePaidInvoicesTask task = new ActivatePaidInvoicesTask();
// load invoice lines
List<InvoiceItem> lines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
// iterate and activate
foreach (InvoiceItem line in lines)
{
if (!line.Processed && line.ServiceId > 0)
results.Add(task.ActivateInvoiceItem(line));
}
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
//
return results;
}
public static GenericSvcResult SuspendService(int serviceId, bool sendEmail)
{
GenericSvcResult result = new GenericSvcResult();
try
{
Service svc = GetRawCustomerService(serviceId);
//
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_SUSPEND);
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
//
SuspendOverdueInvoicesTask task = new SuspendOverdueInvoicesTask();
// obtain result
result = task.SuspendService(serviceId, sendEmail);
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
//
return result;
}
public static GenericSvcResult CancelService(int serviceId, bool sendEmail)
{
GenericSvcResult result = new GenericSvcResult();
try
{
Service svc = GetRawCustomerService(serviceId);
//
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_CANCEL);
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
//
CancelOverdueInvoicesTask task = new CancelOverdueInvoicesTask();
// obtain result
result = task.CancelService(serviceId, sendEmail);
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
}
finally
{
ES.TaskManager.CompleteTask();
}
//
return result;
}
#endregion
public static DateTime GetServiceSuspendDate(int serviceId)
{
// get service suspend date
DateTime date = EcommerceProvider.GetServiceSuspendDate(ES.SecurityContext.User.UserId, serviceId);
// check returned result
if (date == DateTime.MinValue)
date = DateTime.UtcNow;
// return service suspend date
return date;
}
public static List<Service> GetServicesToInvoice(int resellerId, DateTime todayDate, int daysOffset)
{
return ES.ObjectUtils.CreateListFromDataReader<Service>(EcommerceProvider.GetServicesToInvoice(
ES.SecurityContext.User.UserId, resellerId, todayDate,daysOffset));
}
public static int GetCustomersServicesCount(int userId, bool isReseller)
{
return EcommerceProvider.GetCustomersServicesCount(ES.SecurityContext.User.UserId, userId, isReseller);
}
public static List<Service> GetCustomersServicesPaged(int userId, bool isReseller,
int maximumRows, int startRowIndex)
{
return ES.ObjectUtils.CreateListFromDataReader<Service>(EcommerceProvider.GetCustomersServicesPaged(
ES.SecurityContext.User.UserId, userId, isReseller, maximumRows, startRowIndex));
}
public static int DeleteCustomerService(int serviceId)
{
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
//
if (!result.Success)
return result.ResultCode;
//
return EcommerceProvider.DeleteCustomerService(ES.SecurityContext.User.UserId, serviceId);
}
}
}

View file

@ -1,55 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class ServiceHandlerController
{
public static void AddServiceHandlerTextResponse(string serviceId, string contractId, int invoiceId, string dataReceived)
{
EcommerceProvider.AddServiceHandlerTextResponse(serviceId, contractId, invoiceId, dataReceived);
}
public static void UpdateServiceHandlersResponses(int resellerId, string xmlData)
{
EcommerceProvider.UpdateServiceHandlersResponses(resellerId, xmlData);
}
internal static List<HandlerResponse> GetServiceHandlersResponsesByReseller(int resellerId)
{
return ES.ObjectUtils.CreateListFromDataReader<HandlerResponse>(
EcommerceProvider.GetServiceHandlersResponsesByReseller(resellerId));
}
}
}

View file

@ -1,373 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public sealed class StorefrontController
{
public const int EMPTY_ORDER_ITEMS_CODE = -15;
private StorefrontController()
{
}
public static string GetContractInvoiceFormatted(string contractId, int invoiceId, string cultureName)
{
//
ContractSystem.ContractController.ImpersonateAsContractReseller(contractId);
//
return InvoiceController.GetCustomerInvoiceFormattedInternally(contractId, invoiceId, cultureName);
}
#region Ecommerce v 2.1.0 routines
public static TopLevelDomain GetResellerTopLevelDomain(int resellerId, string tld)
{
return ES.ObjectUtils.FillObjectFromDataReader<TopLevelDomain>(
EcommerceProvider.GetResellerTopLevelDomain(resellerId, tld));
}
public static List<Product> GetStorefrontProductsByType(int resellerId, int typeId)
{
return ES.ObjectUtils.CreateListFromDataReader<Product>(
EcommerceProvider.GetStorefrontProductsByType(resellerId, typeId)
);
}
public static Product GetStorefrontProduct(int resellerId, int productId)
{
return ES.ObjectUtils.FillObjectFromDataReader<Product>(
EcommerceProvider.GetStorefrontProduct(resellerId, productId));
}
public static List<HostingAddon> GetHostingPlanAddons(int resellerId, int planId)
{
return ES.ObjectUtils.CreateListFromDataReader<HostingAddon>(
EcommerceProvider.GetStorefrontHostingPlanAddons(resellerId, planId));
}
public static OrderResult SubmitCustomerOrder(string contractId, OrderItem[] orderItems, KeyValueBunch extraArgs)
{
//
Contract contract = ContractSystem.ContractController.GetContract(contractId);
// Impersonate
ContractSystem.ContractController.ImpersonateAsContractReseller(contract);
//
OrderResult oResult = new OrderResult();
// check account
SecurityResult sResult = StorehouseController.CheckAccountActive();
//
if (!sResult.Success)
{
//
oResult.Succeed = false;
//
oResult.ResultCode = sResult.ResultCode;
//
return oResult;
}
// check order items not empty
if (orderItems == null || orderItems.Length == 0)
{
//
oResult.Succeed = false;
//
oResult.ResultCode = EMPTY_ORDER_ITEMS_CODE;
//
return oResult;
}
//
ES.TaskManager.StartTask("Storefront", "SUBMIT_CUSTOMER_ORDER");
//
try
{
string currency = StorehouseController.GetBaseCurrency(contract.ResellerId);
// ordered services
List<int> orderedSvcs = new List<int>();
// build services to be ordered
for (int i = 0; i < orderItems.Length; i++)
{
//
OrderItem orderItem = orderItems[i];
//
int orderedSvcId = 0;
//
orderItem.ParentSvcId = (orderItem.ParentIndex > -1) ? orderedSvcs[orderItem.ParentIndex] : orderItem.ParentSvcId;
// load svc type
ProductType svcType = StorehouseController.GetProductType(orderItem.TypeId);
//
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svcType.ProvisioningController));
// add service
orderedSvcId = controller.AddServiceInfo(contractId, currency, orderItem);
// check service controller result
if (orderedSvcId < 1)
{
// ROLLBACK HERE
StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
oResult.Succeed = false;
oResult.ResultCode = orderedSvcId;
return oResult;
// EXIT
}
//
orderedSvcs.Add(orderedSvcId);
}
// build invoice lines
List<InvoiceItem> invoiceLines = InvoiceController.CalculateInvoiceLinesForServices(orderedSvcs);
//
int resultCode = InvoiceController.AddInvoice(contractId, invoiceLines, extraArgs);
// ERROR
if (resultCode < 1)
{
// ROLLBACK HERE
StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
oResult.Succeed = false;
oResult.ResultCode = resultCode;
return oResult;
}
//
oResult.OrderInvoice = resultCode;
//
oResult.Succeed = true;
}
catch (Exception ex)
{
//
oResult.ResultCode = -1;
//
oResult.Succeed = false;
//
ES.TaskManager.WriteError(ex);
}
finally
{
//
ES.TaskManager.CompleteTask();
}
//
return oResult;
}
public static List<PaymentMethod> GetResellerPaymentMethods(int resellerId)
{
return ES.ObjectUtils.CreateListFromDataReader<PaymentMethod>(
EcommerceProvider.GetResellerPaymentMethods(resellerId));
}
public static PaymentMethod GetContractPaymentMethod(string contractId, string methodName)
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
return ES.ObjectUtils.FillObjectFromDataReader<PaymentMethod>(
EcommerceProvider.GetResellerPaymentMethod(contract.ResellerId, methodName));
}
public static ES.UserInfo GetCustomerProfile(int resellerId, int userId, string sessionId)
{
//
ES.SecurityContext.SetThreadPrincipal(resellerId);
//
return ES.UserController.GetUser(userId);
}
public static string GetCustomerInvoiceFormatted(int resellerId, int userId, int invoiceId, string sessionId)
{
return null;// InvoiceController.GetCustomerInvoiceFormattedInternally(resellerId, userId, invoiceId);
}
public static Invoice GetCustomerInvoice(int resellerId, int userId, int invoiceId, string sessionId)
{
return InvoiceController.GetCustomerInvoiceInternally(invoiceId);
}
public static CheckoutResult CompleteCheckout(string contractId, int invoiceId,
string methodName, CheckoutDetails details)
{
//
return PaymentGatewayController.CheckOut(contractId, invoiceId, methodName, details);
}
public static KeyValueBunch GetHostingPlansQuotas(int resellerId, int planId)
{
KeyValueBunch hpQuotas = new KeyValueBunch();
//
ES.SecurityContext.SetThreadPrincipal(resellerId);
//
ES.HostingPlanContext ctx = ES.PackageController.GetHostingPlanContext(planId);
//
if (ctx != null)
{
//
ES.QuotaValueInfo[] quotasArray = ctx.QuotasArray;
//
for (int i = 0; i < ctx.GroupsArray.Length; i++)
{
//
ES.HostingPlanGroupInfo group = ctx.GroupsArray[i];
//
if (group.Enabled)
{
//
List<string> planQuota = new List<string>();
//
foreach (ES.QuotaValueInfo quota in quotasArray)
{
//
if (quota.QuotaName.StartsWith(group.GroupName))
{
// boolean quota
if (quota.QuotaTypeId == 1)
{
// only enabled quotas will be displayed
if (quota.QuotaAllocatedValue == 1)
planQuota.Add(quota.QuotaName + "=Enabled");
}
// numeric
else
{
if (quota.QuotaAllocatedValue > 0)
planQuota.Add(quota.QuotaName + "=" + quota.QuotaAllocatedValue);
else if (quota.QuotaAllocatedValue == -1)
planQuota.Add(quota.QuotaName + "=Unlimited");
}
}
}
// only filled-up groups are allowed to display
if (planQuota.Count > 0)
hpQuotas[group.GroupName] = String.Join(",", planQuota.ToArray());
}
}
}
//
return hpQuotas;
}
public static CheckDomainResult CheckDomain(int resellerId, string domain, string tld)
{
//
CheckDomainResult result = new CheckDomainResult();
//
try
{
//
TopLevelDomain rslTld = GetResellerTopLevelDomain(resellerId, tld);
//
if (rslTld != null && !rslTld.WhoisEnabled)
{
//
result.Succeed = true;
//
result.ResultCode = 0;
//
return result;
}
//
WhoisResult wResult = WhoisLookup.Query(domain, tld);
// query error
if (!wResult.Success)
{
//
result.ErrorMessage = wResult.ErrorMessage;
//
result.Succeed = false;
//
result.ResultCode = CheckDomainResult.QUERY_ERROR;
//
return result;
}
// whois record found
if (wResult.RecordFound)
{
//
result.ResultCode = CheckDomainResult.DOMAIN_BUSY;
//
result.Succeed = true;
//
return result;
}
// whois record not found - domain is available for purchase
result.Succeed = true;
//
result.ResultCode = 0;
}
catch (Exception ex)
{
//
result.ErrorMessage = ex.StackTrace;
//
result.Succeed = false;
//
result.ResultCode = CheckDomainResult.UNSPECIFIED_ERROR;
}
//
return result;
}
#endregion
#region Storefront Categories routines
public static List<Category> GetStorefrontPath(int resellerId, int categoryId)
{
return ES.ObjectUtils.CreateListFromDataReader<Category>(
EcommerceProvider.GetStorefrontPath(resellerId, categoryId));
}
public static List<Category> GetStorefrontCategories(int resellerId, int parentId)
{
return ES.ObjectUtils.CreateListFromDataReader<Category>(
EcommerceProvider.GetStorefrontCategories(resellerId, parentId));
}
public static Category GetStorefrontCategory(int resellerId, int categoryId)
{
return ES.ObjectUtils.FillObjectFromDataReader<Category>(
EcommerceProvider.GetStorefrontCategory(resellerId, categoryId));
}
public static List<Product> GetStorefrontProductsInCategory(int resellerId, int categoryId)
{
return ES.ObjectUtils.CreateListFromDataReader<Product>(
EcommerceProvider.GetStorefrontProductsInCategory(resellerId, categoryId));
}
#endregion
}
}

View file

@ -1,320 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Reflection;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class SystemPluginController
{
#region Ecommerce v 2.1.0
/// <summary>
/// Gets contracts' payment provider
/// </summary>
/// <param name="contractInfo"></param>
/// <param name="methodName"></param>
/// <returns></returns>
internal static SystemPluginBase GetContractPaymentMethod(Contract contractInfo, string methodName)
{
// Load supported plugin
SupportedPlugin plugin = GetResellerPMPlugin(contractInfo.ResellerId, methodName);
//
return GetSystemPluginInstance(contractInfo, plugin, true);
}
internal static void SetupSystemPlugin(int resellerId, SystemPluginBase pluginObj)
{
// load plugin settings
pluginObj.PluginSettings = GetPluginPropertiesInternal(resellerId, pluginObj.PluginId,
false, pluginObj.SecureSettings);
// check whether plugin settings should be decrypted
if (pluginObj.SecureSettings != null && pluginObj.SecureSettings.Length > 0)
{
// decrypt secret settings
foreach (string keyName in pluginObj.SecureSettings)
{
// call WebsitePanel Crypto API
pluginObj.PluginSettings[keyName] = CryptoUtils.Decrypt(pluginObj.PluginSettings[keyName]);
}
}
}
internal static SystemPluginBase GetSystemPluginInstance(string contractId, SupportedPlugin plugin,
bool setupPlugin)
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
//
return GetSystemPluginInstance(contract, plugin, setupPlugin);
}
internal static SystemPluginBase GetSystemPluginInstance(Contract contract, SupportedPlugin plugin,
bool setupPlugin)
{
// load plugin
SystemPluginBase pluginObj = GetSystemPluginInstance(plugin);
//
if (setupPlugin)
SetupSystemPlugin(contract.ResellerId, pluginObj);
//
return pluginObj;
}
internal static SystemPluginBase GetSystemPluginInstance(int resellerId, int pluginId, bool setupPlugin)
{
// load plugin
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
//
if (setupPlugin)
SetupSystemPlugin(resellerId, pluginObj);
//
return pluginObj;
}
internal static SystemPluginBase GetSystemPluginInstance(string contractId, int pluginId, bool setupPlugin)
{
Contract contract = ContractSystem.ContractController.GetContract(contractId);
// load plugin
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
//
if (setupPlugin)
SetupSystemPlugin(contract.ResellerId, pluginObj);
//
return pluginObj;
}
internal static SystemPluginBase GetSystemPluginInstance(int pluginId)
{
// load plugin
SupportedPlugin plugin = GetSupportedPluginById(pluginId);
//
return GetSystemPluginInstance(plugin);
}
internal static SystemPluginBase GetSystemPluginInstance(SupportedPlugin plugin)
{
// check plugin not empty
if (plugin == null)
throw new ArgumentNullException("plugin");
// create system plugin instance
SystemPluginBase pluginObj = (SystemPluginBase)Activator.CreateInstance(Type.GetType(plugin.TypeName));
// copy fields
pluginObj.PluginId = plugin.PluginId;
pluginObj.PluginName = plugin.PluginName;
// return
return pluginObj;
}
internal static SupportedPlugin GetResellerPMPlugin(int resellerId, string methodName)
{
SupportedPlugin plugin = ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
EcommerceProvider.GetResellerPMPlugin(resellerId, methodName));
//
if (plugin == null)
throw new Exception("RESELLER_PM_PLUGIN_NOT_FOUND");
//
return plugin;
}
internal static KeyValueBunch GetPluginPropertiesInternal(int userId, int pluginId, bool skipSensitive,
string[] secureSettings)
{
// load plugin settings
KeyValueBunch properties = SettingsHelper.FillProperties(EcommerceProvider.GetPluginProperties(
SecurityContext.User.UserId, userId, pluginId));
// cleanup plugin settings
if (skipSensitive && secureSettings != null)
{
// iterate through secure settings
foreach (string keyName in secureSettings)
{
// remove secure setting
properties.RemoveKey(keyName);
}
}
// return plugin settings
return properties;
}
public static KeyValueBunch GetPluginProperties(int userId, int pluginId)
{
// get plugin
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
// get settings
return GetPluginPropertiesInternal(userId, pluginId, true, pluginObj.SecureSettings);
}
public static int SetPluginProperties(int userId, int pluginId, KeyValueBunch props)
{
string xmlText = String.Empty;
string[][] pluginProps = null;
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
//
if (!result.Success)
return result.ResultCode;
if (props != null)
{
// create system plugin
SystemPluginBase pluginObj = GetSystemPluginInstance(userId, pluginId, false);
// crypt sensitive data
foreach (string keyName in props.GetAllKeys())
{
//
string keyValue = props[keyName];
//
if (pluginObj.SecureSettings != null)
{
int indexOf = Array.IndexOf(pluginObj.SecureSettings, keyName);
// crypt sensitive data
if (indexOf > -1)
keyValue = CryptoUtils.Encrypt(keyValue);
}
//
props[keyName] = keyValue;
}
// load old properties
KeyValueBunch oldProps = GetPluginPropertiesInternal(userId, pluginId,
false, pluginObj.SecureSettings);
// merge old props with new props
foreach (string keyName in props.GetAllKeys())
{
// copy
oldProps[keyName] = props[keyName];
}
//
pluginProps = oldProps.KeyValueArray;
}
// build update xml
xmlText = SettingsHelper.ConvertObjectSettings(pluginProps, "properties", "property");
//
return EcommerceProvider.SetPluginProperties(SecurityContext.User.UserId, userId, pluginId, xmlText);
}
public static int LogContractPayment(Contract contract, string methodName, string rawData)
{
SupportedPlugin plugin = GetResellerPMPlugin(contract.ResellerId, methodName);
//
return EcommerceProvider.WriteSupportedPluginLog(contract.ContractId, plugin.PluginId, 0, rawData);
}
private static int WriteSupportedPluginLog(string contractId, int pluginId, int recordType, string rawData)
{
return EcommerceProvider.WriteSupportedPluginLog(contractId, pluginId, recordType, rawData);
}
public static List<SupportedPlugin> GetSupportedPluginsByGroup(string groupName)
{
return ObjectUtils.CreateListFromDataReader<SupportedPlugin>(
EcommerceProvider.GetSupportedPluginsByGroup(groupName));
}
public static SupportedPlugin GetSupportedPlugin(string pluginName, string groupName)
{
return ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
EcommerceProvider.GetSupportedPlugin(pluginName, groupName));
}
public static SupportedPlugin GetSupportedPluginById(int pluginId)
{
return ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
EcommerceProvider.GetSupportedPluginById(pluginId));
}
internal static CheckoutFormParams GetCheckoutFormParams(string contractId, int invoiceId,
string methodName, KeyValueBunch options)
{
Contract contractInfo = ContractSystem.ContractController.GetContract(contractId);
// Impersonate
ContractSystem.ContractController.ImpersonateAsContractReseller(contractInfo);
//
SupportedPlugin pmPlugin = GetResellerPMPlugin(contractInfo.ResellerId, methodName);
//
if (pmPlugin == null)
throw new Exception("Incorrect payment method has been specified");
// create instance of plugin
IInteractivePaymentGatewayProvider provider = (IInteractivePaymentGatewayProvider)
SystemPluginController.GetSystemPluginInstance(contractInfo, pmPlugin, true);
//
Invoice userInvoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
//
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
// load contract account
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
// build form parameters
FormParameters formParams = new FormParameters();
// copy reseller id
formParams[FormParameters.CONTRACT] = userInvoice.ContractId;
// copy invoice number
formParams[FormParameters.INVOICE] = userInvoice.InvoiceId.ToString();
// copy invoice amount
formParams[FormParameters.AMOUNT] = userInvoice.Total.ToString("0.00");
// copy invoice tax amount
formParams[FormParameters.TAX_AMOUNT] = userInvoice.TaxAmount.ToString("0.00");
// copy invoice currency
formParams[FormParameters.CURRENCY] = userInvoice.Currency;
// copy first name
formParams[FormParameters.FIRST_NAME] = account[ContractAccount.FIRST_NAME];
// copy last name
formParams[FormParameters.LAST_NAME] = account[ContractAccount.LAST_NAME];
// copy email
formParams[FormParameters.EMAIL] = account[ContractAccount.EMAIL];
// copy address
formParams[FormParameters.ADDRESS] = account[ContractAccount.ADDRESS];
// copy country
formParams[FormParameters.COUNTRY] = account[ContractAccount.COUNTRY];
// copy phone number
formParams[FormParameters.PHONE] = account[ContractAccount.PHONE_NUMBER];
// copy city
formParams[FormParameters.CITY] = account[ContractAccount.CITY];
// copy state
formParams[FormParameters.STATE] = account[ContractAccount.STATE];
// copy zip
formParams[FormParameters.ZIP] = account[ContractAccount.ZIP];
// copy options if any
if (options != null)
{
foreach (string keyName in options.GetAllKeys())
formParams[keyName] = options[keyName];
}
// return result
return provider.GetCheckoutFormParams(formParams, invoiceLines.ToArray());
}
#endregion
}
}

View file

@ -1,165 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer.TaskEventHandlers
{
public class SendEmailNotification : TaskEventHandler
{
public override void OnStart()
{
// Nothing to do
}
/// <summary>
/// Sends corresponding notifications.
/// </summary>
public override void OnComplete()
{
if (!TaskManager.HasErrors)
{
switch (TaskManager.TaskName)
{
case SystemTasks.SVC_SUSPEND:
case SystemTasks.SVC_CANCEL:
case SystemTasks.SVC_ACTIVATE:
SendServiceStatusChangedNotification();
break;
case SystemTasks.TASK_ADD_INVOICE:
SendInvoiceNotification();
break;
case SystemTasks.TASK_UPDATE_PAYMENT:
case SystemTasks.TASK_ADD_PAYMENT:
SendPaymentNotification();
break;
default:
break;
}
}
}
private void SendServiceStatusChangedNotification()
{
// send an e-mail notification
try
{
bool sendNotification = (bool)TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL];
// Ensure notification is required
if (!sendNotification)
{
TaskManager.Write("Notification send is not required, thus skipped");
return;
}
Service service = (Service)TaskManager.TaskParameters[SystemTaskParams.PARAM_SERVICE];
int smtpResult = 0;
switch (service.Status)
{
case ServiceStatus.Active:
smtpResult = MiscController.SendServiceActivatedNotification(service.ServiceId);
break;
case ServiceStatus.Suspended:
smtpResult = MiscController.SendServiceSuspendedNotification(service.ServiceId);
break;
case ServiceStatus.Cancelled:
smtpResult = MiscController.SendServiceCanceledNotification(service.ServiceId);
break;
}
//
if (smtpResult != 0)
{
TaskManager.WriteWarning("Unable to send e-mail notification");
TaskManager.WriteParameter("SMTP Status", smtpResult);
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
private void SendPaymentNotification()
{
//
try
{
// Read task parameters
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
CustomerPayment payment = (CustomerPayment)TaskManager.TaskParameters[SystemTaskParams.PARAM_PAYMENT];
//
if (payment.Status == TransactionStatus.Approved)
{
//
int smtpResult = MiscController.SendPaymentReceivedNotification(payment);
//
if (smtpResult != 0)
{
TaskManager.WriteWarning("Unable to send e-mail notification");
TaskManager.WriteParameter("SMTP Status", smtpResult);
}
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
private void SendInvoiceNotification()
{
//
try
{
// Read task parameters
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
List<InvoiceItem> invoiceLines = (List<InvoiceItem>)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE_LINES];
KeyValueBunch extraArgs = (KeyValueBunch)TaskManager.TaskParameters[SystemTaskParams.PARAM_EXTRA_ARGS];
// modify invoice direct url
if (extraArgs != null && !String.IsNullOrEmpty(extraArgs["InvoiceDirectURL"]))
extraArgs["InvoiceDirectURL"] += "&InvoiceId=" + invoice.InvoiceId;
//
int smtpResult = MiscController.SendNewInvoiceNotification(invoice, invoiceLines, extraArgs);
//
if (smtpResult != 0)
{
TaskManager.WriteWarning("Unable to send e-mail notification");
TaskManager.WriteParameter("SMTP Status", smtpResult);
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
}

View file

@ -1,106 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer.TaskEventHandlers
{
public class SystemTriggersAgent : TaskEventHandler
{
public override void OnStart()
{
// Nothing to do
}
public override void OnComplete()
{
if (!TaskManager.HasErrors)
{
switch (TaskManager.TaskName)
{
case SystemTasks.TASK_ADD_INVOICE:
RegisterInvoiceActivationTrigger();
break;
case SystemTasks.TASK_ADD_CONTRACT:
RegisterContractActivationTrigger();
break;
case SystemTasks.TASK_UPDATE_PAYMENT:
case SystemTasks.TASK_ADD_PAYMENT:
ActivatePaymentSystemTriggers();
break;
}
}
}
private void RegisterInvoiceActivationTrigger()
{
// Read contract invoice
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
//
TriggerSystem.TriggerController.AddSystemTrigger(invoice.InvoiceId.ToString(),
ActivateInvoiceTrigger.STATUS_AWAITING_PAYMENT, typeof(ActivateInvoiceTrigger));
}
private void RegisterContractActivationTrigger()
{
// Ensure the contract has been registered successfully
if (TaskManager.TaskParameters.ContainsKey(SystemTaskParams.PARAM_CONTRACT))
{
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
//
if (contract.Status == ContractStatus.Pending)
{
TriggerSystem.TriggerController.AddSystemTrigger(contract.ContractId,
ActivateContractTrigger.STATUS_AWAITING_PAYMENT, typeof(ActivateContractTrigger));
}
}
}
private void ActivatePaymentSystemTriggers()
{
CustomerPayment payment = (CustomerPayment)TaskManager.TaskParameters[SystemTaskParams.PARAM_PAYMENT];
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
// Run activate contract trigger if the transaction was approved
if (payment.Status == TransactionStatus.Approved)
{
// Activate contract
TriggerSystem.TriggerController.ExecuteSystemTrigger(contract.ContractId,
ActivateContractTrigger.NAMESPACE, null);
// Activate invoice
TriggerSystem.TriggerController.ExecuteSystemTrigger(payment.InvoiceId.ToString(),
ActivateInvoiceTrigger.NAMESPACE, null);
}
}
}
}

View file

@ -1,153 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class ActivateInvoiceTrigger : TriggerHandlerBase
{
public const string NAMESPACE = "INVOICE";
public const string STATUS_AWAITING_PAYMENT = "AWAITING_PAYMENT";
public override string TriggerNamespace
{
get { return NAMESPACE; }
}
public override void ExecuteTrigger(TriggerEventArgs eventArgs)
{
//
try
{
ActivatePaidInvoicesTask activator = new ActivatePaidInvoicesTask();
// Load invoice items to activate
List<InvoiceItem> items = InvoiceController.GetCustomerInvoiceItems(Convert.ToInt32(ReferenceId));
//
foreach (InvoiceItem item in items)
{
try
{
ES.TaskManager.Write("Activating service");
// activating
GenericSvcResult result = activator.ActivateInvoiceItem(item);
// LOG ERROR
if (!result.Succeed)
{
ES.TaskManager.WriteError(result.Error);
if (!String.IsNullOrEmpty(result.ErrorCode))
ES.TaskManager.WriteParameter("Error code", result.ErrorCode);
ES.TaskManager.WriteParameter("Result code", result.ResultCode);
// go to next item
continue;
}
//
ES.TaskManager.Write("Activated");
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
}
}
}
catch (Exception ex)
{
TriggerStatus = "ERROR";
ES.TaskManager.WriteError(ex);
}
}
}
public class ActivateContractTrigger : TriggerHandlerBase
{
public const string NAMESPACE = "CONTRACT";
public const string STATUS_AWAITING_PAYMENT = "AWAITING_PAYMENT";
public override string TriggerNamespace
{
get { return NAMESPACE; }
}
public override void ExecuteTrigger(TriggerEventArgs eventArgs)
{
//
try
{
Contract contract = ContractSystem.ContractController.GetContract(ReferenceId);
//
if (contract.Status == ContractStatus.Pending)
{
//
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(ReferenceId);
//
// create user account
ES.UserInfo userInfo = new ES.UserInfo();
userInfo.Username = account[ContractAccount.USERNAME];
userInfo.Password = account[ContractAccount.PASSWORD];
userInfo.Email = account[ContractAccount.EMAIL];
userInfo.FirstName = account[ContractAccount.FIRST_NAME];
userInfo.LastName = account[ContractAccount.LAST_NAME];
userInfo.HtmlMail = (account[ContractAccount.MAIL_FORMAT] == "HTML");
userInfo.Address = account[ContractAccount.ADDRESS];
userInfo.City = account[ContractAccount.CITY];
userInfo.CompanyName = account[ContractAccount.COMPANY_NAME];
userInfo.Country = account[ContractAccount.COUNTRY];
userInfo.State = account[ContractAccount.STATE];
userInfo.PrimaryPhone = account[ContractAccount.PHONE_NUMBER];
userInfo.Fax = account[ContractAccount.FAX_NUMBER];
userInfo.InstantMessenger = account[ContractAccount.INSTANT_MESSENGER];
userInfo.Zip = account[ContractAccount.ZIP];
userInfo.Role = ES.UserRole.User;
userInfo.Status = ES.UserStatus.Active;
// set account parent
userInfo.OwnerId = contract.ResellerId;
userInfo.Created = DateTime.Now;
// create account
int resultCode = ES.UserController.AddUser(userInfo, true);
//
if (resultCode > 0)
{
ContractSystem.ContractController.UpdateContract(ReferenceId, resultCode, contract.AccountName,
ContractStatus.Active, 0m, contract.FirstName, contract.LastName, contract.Email,
contract.CompanyName, null, null);
}
}
}
catch (Exception ex)
{
TriggerStatus = "ERROR";
ES.TaskManager.WriteError(ex);
}
}
}
}

View file

@ -1,111 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using ES = WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer.TriggerSystem
{
public class TriggerController
{
public static void AddSystemTrigger(string referenceId, string triggerStatus, Type triggerType)
{
//
ITriggerHandler trigger = (ITriggerHandler)Activator.CreateInstance(triggerType);
//
EcommerceProvider.AddSystemTrigger(ES.SecurityContext.User.UserId, ES.SecurityContext.User.UserId,
triggerType.AssemblyQualifiedName, referenceId, trigger.TriggerNamespace, triggerStatus);
}
public static void ExecuteSystemTrigger(string referenceId, string triggerNamespace, TriggerEventArgs eventArgs)
{
//
IDataReader dr = null;
try
{
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_EXEC_SYSTEM_TRIGGER);
List<ITriggerHandler> triggers = new List<ITriggerHandler>();
dr = EcommerceProvider.GetSystemTrigger(ES.SecurityContext.User.UserId, referenceId, triggerNamespace);
//
while(dr.Read())
{
int ownerId = Convert.ToInt32(dr["OwnerID"]);
string triggerId = Convert.ToString(dr["TriggerID"]);
string triggerHandler = Convert.ToString(dr["TriggerHandler"]);
string triggerStatus = (dr["Status"] == DBNull.Value) ? null : Convert.ToString(dr["Status"]);
// Instantiate trigger handler
ITriggerHandler trigger = (ITriggerHandler)Activator.CreateInstance(Type.GetType(triggerHandler));
//
trigger.TriggerId = triggerId;
trigger.OwnerId = ownerId;
trigger.TriggerStatus = triggerStatus;
trigger.ReferenceId = referenceId;
//
triggers.Add(trigger);
//
}
dr.Close();
//
foreach (ITriggerHandler trigger in triggers)
{
try
{
trigger.ExecuteTrigger(eventArgs);
}
catch (Exception ex)
{
ES.TaskManager.WriteError(ex);
continue;
}
//
DeleteSystemTrigger(trigger.TriggerId);
}
}
catch (Exception ex)
{
throw ES.TaskManager.WriteError(ex);
}
finally
{
if (dr != null)
dr.Close();
//
ES.TaskManager.CompleteTask();
}
}
private static void DeleteSystemTrigger(string triggerId)
{
EcommerceProvider.DeleteSystemTrigger(ES.SecurityContext.User.UserId, triggerId);
}
}
}

View file

@ -1,416 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using WebsitePanel.Providers;
using WebsitePanel.Providers.FTP;
namespace WebsitePanel.EnterpriseServer
{
public class FtpServerController : IImportController, IBackupController
{
public static FTPServer GetFTPServer(int serviceId)
{
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, serviceId);
return ftp;
}
public static FtpSite[] GetFtpSites(int serviceId)
{
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, serviceId);
return ftp.GetSites();
}
public static DataSet GetRawFtpAccountsPaged(int packageId,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return PackageController.GetRawPackageItemsPaged(packageId, typeof(FtpAccount),
true, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<FtpAccount> GetFtpAccounts(int packageId, bool recursive)
{
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(
packageId, typeof(FtpAccount), recursive);
return items.ConvertAll<FtpAccount>(
new Converter<ServiceProviderItem, FtpAccount>(ConvertItemToFtpAccount));
}
private static FtpAccount ConvertItemToFtpAccount(ServiceProviderItem item)
{
FtpAccount account = (FtpAccount)item;
string homeFolder = FilesController.GetHomeFolder(account.PackageId);
if(!String.IsNullOrEmpty(account.Folder) && account.Folder.IndexOf(":") != -1)
account.Folder = account.Folder.Substring(homeFolder.Length);
account.Folder = (account.Folder == "") ? "\\" : account.Folder;
// decode password
account.Password = CryptoUtils.Decrypt(account.Password);
return account;
}
public static bool FtpAccountExists(string name)
{
return PackageController.CheckServiceItemExists(name, typeof(FtpAccount));
}
public static bool FtpAccountExists(int serviceId, string name)
{
return PackageController.CheckServiceItemExists(serviceId, name, typeof(FtpAccount));
}
public static FtpAccount GetFtpAccount(int itemId)
{
// load meta item
FtpAccount item = (FtpAccount)PackageController.GetPackageItem(itemId);
// load service item
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, item.ServiceId);
FtpAccount account = ftp.GetAccount(item.Name);
// truncate home folder
account.Folder = FilesController.GetVirtualPackagePath(item.PackageId, account.Folder);
account.Id = item.Id;
account.PackageId = item.PackageId;
account.ServiceId = item.ServiceId;
account.Password = CryptoUtils.Decrypt(item.Password);
return account;
}
public static int AddFtpAccount(FtpAccount item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check quota
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.FTP_ACCOUNTS);
if (quota.QuotaExhausted)
return BusinessErrorCodes.ERROR_FTP_RESOURCE_QUOTA_LIMIT;
// check if FTP account already exists
int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Ftp);
if(serviceId == 0)
return BusinessErrorCodes.ERROR_FTP_RESOURCE_UNAVAILABLE;
// place log record
TaskManager.StartTask("FTP_ACCOUNT", "ADD", item.Name);
TaskManager.WriteParameter("Folder", item.Folder);
TaskManager.WriteParameter("CanRead", item.CanRead);
TaskManager.WriteParameter("CanWrite", item.CanWrite);
try
{
// check package items
if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(FtpAccount)) != null)
return BusinessErrorCodes.ERROR_FTP_PACKAGE_ITEM_EXISTS;
// check service items
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, serviceId);
if (ftp.AccountExists(item.Name))
return BusinessErrorCodes.ERROR_FTP_SERVICE_ITEM_EXISTS;
// store original path
string origFolder = item.Folder;
// convert folder
StringDictionary ftpSettings = ServerController.GetServiceSettings(serviceId);
if (Utils.ParseBool(ftpSettings["BuildUncFilesPath"], false))
{
// UNC
// get OS service
int osServiceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Os);
item.Folder = FilesController.GetFullUncPackagePath(item.PackageId, osServiceId, item.Folder);
}
else
{
// Absolute
item.Folder = FilesController.GetFullPackagePath(item.PackageId, item.Folder);
}
item.Enabled = true;
// add service item
ftp.CreateAccount(item);
// save item
item.Password = CryptoUtils.Encrypt(item.Password);
item.ServiceId = serviceId;
item.Folder = (origFolder == "") ? "\\" : origFolder;
int itemId = PackageController.AddPackageItem(item);
TaskManager.ItemId = itemId;
return itemId;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
throw;
}
finally
{
TaskManager.CompleteTask();
}
}
public static int UpdateFtpAccount(FtpAccount item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
FtpAccount origItem = (FtpAccount)PackageController.GetPackageItem(item.Id);
if (origItem == null)
return BusinessErrorCodes.ERROR_FTP_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("FTP_ACCOUNT", "UPDATE", origItem.Name);
TaskManager.ItemId = item.Id;
TaskManager.WriteParameter("Folder", item.Folder);
TaskManager.WriteParameter("CanRead", item.CanRead);
TaskManager.WriteParameter("CanWrite", item.CanWrite);
try
{
// get service
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, origItem.ServiceId);
// store original folder
string origFolder = item.Folder;
// convert folder
StringDictionary ftpSettings = ServerController.GetServiceSettings(origItem.ServiceId);
if (Utils.ParseBool(ftpSettings["BuildUncFilesPath"], false))
{
// UNC
// get OS service
int osServiceId = PackageController.GetPackageServiceId(origItem.PackageId, ResourceGroups.Os);
item.Folder = FilesController.GetFullUncPackagePath(origItem.PackageId, osServiceId, item.Folder);
}
else
{
// Absolute
item.Folder = FilesController.GetFullPackagePath(origItem.PackageId, item.Folder);
}
item.Enabled = true;
// add service item
ftp.UpdateAccount(item);
// save item
item.Password = String.IsNullOrEmpty(item.Password) ? origItem.Password : CryptoUtils.Encrypt(item.Password);
item.Folder = (origFolder == "") ? "\\" : origFolder;
PackageController.UpdatePackageItem(item);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int DeleteFtpAccount(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
FtpAccount origItem = (FtpAccount)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_FTP_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("FTP_ACCOUNT", "DELETE", origItem.Name);
TaskManager.ItemId = itemId;
try
{
// get service
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, origItem.ServiceId);
// delete service item
ftp.DeleteAccount(origItem.Name);
// delete meta item
PackageController.DeletePackageItem(origItem.Id);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#region IImportController Members
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
{
List<string> items = new List<string>();
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
// FTP provider
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, serviceId);
FtpAccount[] accounts = ftp.GetAccounts();
foreach (FtpAccount account in accounts)
items.Add(account.Name);
return items;
}
public void ImportItem(int packageId, int itemTypeId,
Type itemType, ResourceGroupInfo group, string itemName)
{
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return;
// FTP provider
FTPServer ftp = new FTPServer();
ServiceProviderProxy.Init(ftp, serviceId);
if (itemType == typeof(FtpAccount))
{
// load FTP account
FtpAccount account = ftp.GetAccount(itemName);
account.Folder = FilesController.GetFullPackagePath(packageId, "\\"); // root space folder
// update FTP account
ftp.UpdateAccount(account);
// save account
account.ServiceId = serviceId;
account.PackageId = packageId;
PackageController.AddPackageItem(account);
}
}
#endregion
#region IBackupController Members
public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
if (item is FtpAccount)
{
// backup FTP account
FTPServer ftp = GetFTPServer(item.ServiceId);
// read FTP account info
FtpAccount account = ftp.GetAccount(item.Name);
account.Password = ((FtpAccount)item).Password;
XmlSerializer serializer = new XmlSerializer(typeof(FtpAccount));
serializer.Serialize(writer, account);
}
return 0;
}
public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType == typeof(FtpAccount))
{
FTPServer ftp = GetFTPServer(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(FtpAccount));
FtpAccount account = (FtpAccount)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("FtpAccount")));
// create DSN if required
if (!ftp.AccountExists(itemName))
{
account.Password = CryptoUtils.Decrypt(account.Password);
ftp.CreateAccount(account);
// restore password
account.Password = CryptoUtils.Encrypt(account.Password);
}
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, itemName, typeof(FtpAccount)) == null)
{
account.PackageId = packageId;
account.ServiceId = serviceId;
PackageController.AddPackageItem(account);
}
}
return 0;
}
#endregion
}
}

View file

@ -1,228 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using Microsoft.ApplicationBlocks.Data;
using WebsitePanel.Providers.HeliconZoo;
using WebsitePanel.Providers.Web;
using WebsitePanel.Server;
namespace WebsitePanel.EnterpriseServer
{
public class HeliconZooController
{
public const string HeliconZooQuotaPrefix = "HeliconZoo.";
public static HeliconZooEngine[] GetEngines(int serviceId)
{
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
return zooServer.GetEngines();
}
public static void SetEngines(int serviceId, HeliconZooEngine[] userEngines)
{
// update applicationHost.config
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
zooServer.SetEngines(userEngines);
// update Helicon Zoo quotas in Quotas table
UpdateQuotas(serviceId, userEngines);
}
public static bool IsEnginesEnabled(int serviceId)
{
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
return zooServer.IsEnginesEnabled();
}
public static void SwithEnginesEnabled(int serviceId, bool enabled)
{
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
zooServer.SwithEnginesEnabled(enabled);
}
public static ShortHeliconZooEngine[] GetAllowedHeliconZooQuotasForPackage(int packageId)
{
List<ShortHeliconZooEngine> allowedEngines = new List<ShortHeliconZooEngine>();
IDataReader reader = DataProvider.GetEnabledHeliconZooQuotasForPackage(packageId);
while (reader.Read())
{
allowedEngines.Add( new ShortHeliconZooEngine(){
Name = (string)reader["QuotaName"],
DisplayName= (string)reader["QuotaDescription"],
});
}
return allowedEngines.ToArray();
}
public static string[] GetEnabledEnginesForSite(string siteId, int packageId)
{
int serviceId = GetHeliconZooServiceIdByPackageId(packageId);
if (-1 == serviceId)
{
// Helicon Zoo is not enabled for this package
return new string[0];
}
// ask Server to enabled engines for site
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
string[] enabledEngines = zooServer.GetEnabledEnginesForSite(siteId);
return enabledEngines;
}
public static void SetEnabledEnginesForSite(string siteId, int packageId, string[] engines)
{
int serviceId = GetHeliconZooServiceIdByPackageId(packageId);
// tell Server to enable engines for site
HeliconZoo zooServer = new HeliconZoo();
ServiceProviderProxy.Init(zooServer, serviceId);
zooServer.SetEnabledEnginesForSite(siteId, engines);
}
#region private helpers
private static void UpdateQuotas(int serviceId, HeliconZooEngine[] userEngines)
{
List<HeliconZooEngine> updatedEngines = new List<HeliconZooEngine>(userEngines);
int providerId, groupId;
DataProvider.GetHeliconZooProviderAndGroup("HeliconZoo", out providerId, out groupId);
// get existing Helicon Zoo quotas
List<string> existingQuotas = new List<string>();
IDataReader reader = DataProvider.GetHeliconZooQuotas(providerId);
while (reader.Read())
{
string quota = (string) reader["QuotaName"];
if (quota.StartsWith(HeliconZooQuotaPrefix))
{
quota = quota.Substring(HeliconZooQuotaPrefix.Length);
}
existingQuotas.Add(quota);
}
// sort: engine to remove and add
List<string> engineNamesToRemove = new List<string>();
List<HeliconZooEngine> enginesToAdd = new List<HeliconZooEngine>();
// find engine to remove in existing engines
foreach (string existingEngineName in existingQuotas)
{
if (
Array.Find(updatedEngines.ToArray(), engine => engine.name == existingEngineName) == null
&&
!engineNamesToRemove.Contains(existingEngineName)
)
{
engineNamesToRemove.Add(existingEngineName);
}
}
// find engines to add
foreach (HeliconZooEngine engine in updatedEngines)
{
if (!existingQuotas.Contains(engine.name))
{
enginesToAdd.Add(engine);
}
}
// remove engines
foreach (string engineName in engineNamesToRemove)
{
DataProvider.RemoveHeliconZooQuota(groupId, HeliconZooQuotaPrefix+engineName);
}
// add engines
int order = 0;
foreach (HeliconZooEngine engine in enginesToAdd)
{
int quotaId = GenerateIntId(engine);
DataProvider.AddHeliconZooQuota(groupId, quotaId,
HeliconZooQuotaPrefix+engine.name,
engine.displayName,
order++);
}
}
private static int GenerateIntId(HeliconZooEngine engine)
{
return engine.name.GetHashCode();
}
private static int GetHeliconZooServiceIdByPackageId(int packageId)
{
// get server id
int serverId = DataProvider.GetServerIdForPackage(packageId);
if (-1 == serverId)
{
throw new Exception(string.Format("Server not found for package {0}", packageId));
}
// get Helicon Zoo provider
int heliconZooProviderId = -1;
List<ProviderInfo> providers = ServerController.GetProviders();
foreach (ProviderInfo providerInfo in providers)
{
if (string.Equals("HeliconZoo", providerInfo.ProviderName, StringComparison.OrdinalIgnoreCase))
{
heliconZooProviderId = providerInfo.ProviderId;
break;
}
}
if (-1 == heliconZooProviderId)
{
throw new Exception("Helicon Zoo provider not found");
}
// get Helicon Zoo service for site
int serviceId = DataProvider.GetServiceIdByProviderForServer(heliconZooProviderId, serverId);
return serviceId;
}
#endregion
}
}

View file

@ -1,534 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.EnterpriseServer.Code.HostedSolution
{
public class BlackBerryController
{
private static bool CheckQuota(int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
IntResult userCount = GetBlackBerryUsersCount(itemId, string.Empty, string.Empty);
int allocatedBlackBerryUsers = cntx.Quotas[Quotas.BLACKBERRY_USERS].QuotaAllocatedValue;
return allocatedBlackBerryUsers == -1 || allocatedBlackBerryUsers > userCount.Value;
}
private static BlackBerry GetBlackBerryProxy(int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.BlackBerry);
BlackBerry blackBerry = new BlackBerry();
ServiceProviderProxy.Init(blackBerry, serviceId);
return blackBerry;
}
internal static bool CheckBlackBerryUserExists(int accountId)
{
return DataProvider.CheckBlackBerryUserExists(accountId);
}
public static ResultObject CreateBlackBerryUser(int itemId, int accountId)
{
ResultObject res = TaskManager.StartResultTask<ResultObject>("BLACBERRY", "CREATE_BLACKBERRY_USER");
bool isBlackBerryUser;
try
{
isBlackBerryUser = DataProvider.CheckBlackBerryUserExists(accountId);
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_CHECK_IF_BLACKBERRY_USER_EXISTS, ex);
return res;
}
if (isBlackBerryUser)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_IS_ALREADY_BLAKBERRY_USER);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
if (user.AccountType != ExchangeAccountType.Mailbox)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.ACCOUNT_TYPE_IS_NOT_MAILBOX);
return res;
}
try
{
user = OrganizationController.GetUserGeneralSettings(itemId, accountId);
if (string.IsNullOrEmpty(user.FirstName))
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED);
return res;
}
if (string.IsNullOrEmpty(user.LastName))
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_LAST_NAME_IS_NOT_SPECIFIED);
return res;
}
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_USER_GENERAL_SETTINGS, ex);
return res;
}
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
try
{
bool quota = CheckQuota(itemId);
if (!quota)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_QUOTA_HAS_BEEN_REACHED);
return res;
}
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_CHECK_QUOTA, ex);
return res;
}
try
{
ResultObject userRes = blackBerry.CreateBlackBerryUser(user.PrimaryEmailAddress);
res.ErrorCodes.AddRange(userRes.ErrorCodes);
if (!userRes.IsSuccess)
{
TaskManager.CompleteResultTask(res);
return res;
}
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_ADD_BLACKBERRY_USER, ex);
return res;
}
try
{
DataProvider.AddBlackBerryUser(accountId);
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_ADD_BLACKBERRY_USER_TO_DATABASE, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static OrganizationUsersPagedResult GetBlackBerryUsers(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int count)
{
OrganizationUsersPagedResult res = TaskManager.StartResultTask<OrganizationUsersPagedResult>("BLACKBERRY", "GET_BLACKBERRY_USERS");
try
{
IDataReader reader =
DataProvider.GetBlackBerryUsers(itemId, sortColumn, sortDirection, name, email, startRow, count);
List<OrganizationUser> accounts = new List<OrganizationUser>();
ObjectUtils.FillCollectionFromDataReader(accounts, reader);
res.Value = new OrganizationUsersPaged {PageUsers = accounts.ToArray()};
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, CrmErrorCodes.GET_CRM_USERS, ex);
return res;
}
IntResult intRes = GetBlackBerryUsersCount(itemId, name, email);
res.ErrorCodes.AddRange(intRes.ErrorCodes);
if (!intRes.IsSuccess)
{
TaskManager.CompleteResultTask(res);
return res;
}
res.Value.RecordsCount = intRes.Value;
TaskManager.CompleteResultTask();
return res;
}
public static IntResult GetBlackBerryUsersCount(int itemId, string name, string email)
{
IntResult res = TaskManager.StartResultTask<IntResult>("BLACKBERRY", "GET_BLACKBERRY_USERS_COUNT");
try
{
res.Value = DataProvider.GetBlackBerryUsersCount(itemId, name, email);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, CrmErrorCodes.GET_CRM_USER_COUNT, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static ResultObject DeleteBlackBerryUser(int itemId, int accountId)
{
ResultObject res = TaskManager.StartResultTask<ResultObject>("BLACKBERRY", "DELETE_BLACKBERRY_USER");
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
ResultObject bbRes = blackBerry.DeleteBlackBerryUser(user.PrimaryEmailAddress);
res.ErrorCodes.AddRange(bbRes.ErrorCodes);
if (!bbRes.IsSuccess)
{
TaskManager.CompleteResultTask(res);
return res;
}
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_BLACKBERRY_USER, ex);
return res;
}
try
{
DataProvider.DeleteBlackBerryUser(accountId);
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_BLACKBERRY_USER_FROM_METADATA, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static BlackBerryUserStatsResult GetBlackBerryUserStats(int itemId, int accountId)
{
BlackBerryUserStatsResult res = TaskManager.StartResultTask<BlackBerryUserStatsResult>("BLACKBERRY",
"DELETE_BLACKBERRY_USER");
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
BlackBerryUserStatsResult tmp = blackBerry.GetBlackBerryUserStats(user.PrimaryEmailAddress);
res.ErrorCodes.AddRange(tmp.ErrorCodes);
if (!tmp.IsSuccess)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_USER_STATS);
return res;
}
res.Value = tmp.Value;
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_USER_STATS, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static ResultObject SetActivationPasswordWithExpirationTime(int itemId, int accountId, string password, int time)
{
BlackBerryUserStatsResult res = TaskManager.StartResultTask<BlackBerryUserStatsResult>("BLACKBERRY",
"DELETE_BLACKBERRY_USER");
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
ResultObject tmp = blackBerry.SetActivationPasswordWithExpirationTime(user.PrimaryEmailAddress, password, time);
res.ErrorCodes.AddRange(tmp.ErrorCodes);
if (!tmp.IsSuccess)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_SET_ACTIVATION_PASSWORD);
return res;
}
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_SET_ACTIVATION_PASSWORD, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static ResultObject SetEmailActivationPassword(int itemId, int accountId)
{
ResultObject res = TaskManager.StartResultTask<BlackBerryUserStatsResult>("BLACKBERRY",
"DELETE_BLACKBERRY_USER");
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
ResultObject tmp = blackBerry.SetEmailActivationPassword(user.PrimaryEmailAddress);
res.ErrorCodes.AddRange(tmp.ErrorCodes);
if (!tmp.IsSuccess)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_SET_EMAIL_ACTIVATION_PASSWORD);
return res;
}
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_SET_EMAIL_ACTIVATION_PASSWORD, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static ResultObject DeleteDataFromBlackBerryDevice(int itemId, int accountId)
{
ResultObject res = TaskManager.StartResultTask<BlackBerryUserStatsResult>("BLACKBERRY",
"DELETE_BLACKBERRY_USER");
BlackBerry blackBerry;
try
{
blackBerry = GetBlackBerryProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
ResultObject tmp = blackBerry.DeleteDataFromBlackBerryDevice(user.PrimaryEmailAddress);
res.ErrorCodes.AddRange(tmp.ErrorCodes);
if (!tmp.IsSuccess)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_DATA_FROM_BLACKBERRY_DEVICE);
return res;
}
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_DATA_FROM_BLACKBERRY_DEVICE, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
}
}

View file

@ -1,97 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers.Lync;
using WebsitePanel.EnterpriseServer.Code.HostedSolution;
namespace WebsitePanel.EnterpriseServer.Code.HostedSolution
{
public class LyncControllerAsync
{
private int lyncServiceId;
private int organizationServiceId;
public int LyncServiceId
{
get { return this.lyncServiceId; }
set { this.lyncServiceId = value; }
}
public int OrganizationServiceId
{
get { return this.organizationServiceId; }
set { this.organizationServiceId = value; }
}
public void Enable_CsComputerAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Enable_CsComputer));
t.Start();
}
private void Enable_CsComputer()
{
int[] lyncServiceIds;
LyncController.GetLyncServices(lyncServiceId, out lyncServiceIds);
foreach (int id in lyncServiceIds)
{
LyncServer lync = null;
try
{
lync = LyncController.GetLyncServer(id, organizationServiceId);
if (lync != null)
{
lync.ReloadConfiguration();
}
}
catch (Exception exe)
{
TaskManager.WriteError(exe);
continue;
}
}
}
}
}

View file

@ -1,450 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers.OCS;
namespace WebsitePanel.EnterpriseServer.Code.HostedSolution
{
public class OCSController
{
private static OCSServer GetOCSProxy(int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.OCS);
OCSServer ocs = new OCSServer();
ServiceProviderProxy.Init(ocs, serviceId);
return ocs;
}
private static bool CheckQuota(int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
IntResult userCount = GetOCSUsersCount(itemId, string.Empty, string.Empty);
int allocatedBlackBerryUsers = cntx.Quotas[Quotas.OCS_USERS].QuotaAllocatedValue;
return allocatedBlackBerryUsers == -1 || allocatedBlackBerryUsers > userCount.Value;
}
private static void SetUserGeneralSettingsByDefault(int itemId, string instanceId, OCSServer ocs)
{
Organization org = OrganizationController.GetOrganization(itemId);
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
ocs.SetUserGeneralSettings(instanceId, !cntx.Quotas[Quotas.OCS_FederationByDefault].QuotaExhausted,
!cntx.Quotas[Quotas.OCS_PublicIMConnectivityByDefault].QuotaExhausted,
!cntx.Quotas[Quotas.OCS_ArchiveIMConversationByDefault].QuotaExhausted,
!cntx.Quotas[Quotas.OCS_ArchiveFederatedIMConversationByDefault].QuotaExhausted,
!cntx.Quotas[Quotas.OCS_PresenceAllowedByDefault].QuotaExhausted);
}
private static OCSEdgeServer[] GetEdgeServers(string edgeServices)
{
List<OCSEdgeServer> list = new List<OCSEdgeServer>();
if (!string.IsNullOrEmpty(edgeServices))
{
string[] services = edgeServices.Split(';');
foreach (string current in services)
{
string[] data = current.Split(',');
try
{
int serviceId = int.Parse(data[1]);
OCSEdgeServer ocs = new OCSEdgeServer();
ServiceProviderProxy.Init(ocs, serviceId);
list.Add(ocs);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
return list.ToArray();
}
public static void DeleteDomain(int itemId, string domainName)
{
Organization org = OrganizationController.GetOrganization(itemId);
if (org.IsOCSOrganization)
{
int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.OCS);
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
string edgeServersData = settings[OCSConstants.EDGEServicesData];
OCSEdgeServer[] edgeServers = GetEdgeServers(edgeServersData);
DeleteDomain(domainName, edgeServers);
}
}
public static void DeleteDomain(string domainName, OCSEdgeServer[] edgeServers)
{
foreach (OCSEdgeServer currentEdgeServer in edgeServers)
{
try
{
currentEdgeServer.DeleteDomain(domainName);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
public static void AddDomain(string domainName, OCSEdgeServer[] edgeServers)
{
foreach (OCSEdgeServer currentEdgeServer in edgeServers)
{
try
{
currentEdgeServer.AddDomain(domainName);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
public static void AddDomain(string domainName, int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
if (!org.IsOCSOrganization)
{
int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.OCS);
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
string edgeServersData = settings[OCSConstants.EDGEServicesData];
OCSEdgeServer[] edgeServers = GetEdgeServers(edgeServersData);
AddDomain(domainName, edgeServers);
}
}
private static void CreateOCSDomains(int itemId)
{
Organization org = OrganizationController.GetOrganization(itemId);
if (!org.IsOCSOrganization)
{
List<OrganizationDomainName> domains = OrganizationController.GetOrganizationDomains(itemId);
int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.OCS);
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
string edgeServersData = settings[OCSConstants.EDGEServicesData];
OCSEdgeServer[] edgeServers = GetEdgeServers(edgeServersData);
foreach (OrganizationDomainName currentDomain in domains)
{
AddDomain(currentDomain.DomainName, edgeServers);
}
org.IsOCSOrganization = true;
PackageController.UpdatePackageItem(org);
}
}
public static OCSUserResult CreateOCSUser(int itemId, int accountId)
{
OCSUserResult res = TaskManager.StartResultTask<OCSUserResult>("OCS", "CREATE_OCS_USER");
OCSUser retOCSUser = new OCSUser();
bool isOCSUser;
try
{
isOCSUser = DataProvider.CheckOCSUserExists(accountId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_CHECK_IF_OCS_USER_EXISTS, ex);
return res;
}
if (isOCSUser)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.USER_IS_ALREADY_OCS_USER);
return res;
}
OrganizationUser user;
try
{
user = OrganizationController.GetAccount(itemId, accountId);
if (user == null)
throw new ApplicationException(
string.Format("User is null. ItemId={0}, AccountId={1}", itemId,
accountId));
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex);
return res;
}
try
{
user = OrganizationController.GetUserGeneralSettings(itemId, accountId);
if (string.IsNullOrEmpty(user.FirstName))
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED);
return res;
}
if (string.IsNullOrEmpty(user.LastName))
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.USER_LAST_NAME_IS_NOT_SPECIFIED);
return res;
}
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_GET_USER_GENERAL_SETTINGS, ex);
return res;
}
try
{
bool quota = CheckQuota(itemId);
if (!quota)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.USER_QUOTA_HAS_BEEN_REACHED);
return res;
}
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_CHECK_QUOTA, ex);
return res;
}
OCSServer ocs;
try
{
ocs = GetOCSProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_GET_OCS_PROXY, ex);
return res;
}
string instanceId;
try
{
CreateOCSDomains(itemId);
instanceId = ocs.CreateUser(user.PrimaryEmailAddress, user.DistinguishedName);
retOCSUser.InstanceId = instanceId;
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_ADD_OCS_USER, ex);
return res;
}
try
{
SetUserGeneralSettingsByDefault(itemId, instanceId, ocs);
}
catch(Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_SET_DEFAULT_SETTINGS, ex);
return res;
}
try
{
DataProvider.AddOCSUser(accountId, instanceId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_ADD_OCS_USER_TO_DATABASE, ex);
return res;
}
res.Value = retOCSUser;
TaskManager.CompleteResultTask();
return res;
}
public static OCSUsersPagedResult GetOCSUsers(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int count)
{
OCSUsersPagedResult res = TaskManager.StartResultTask<OCSUsersPagedResult>("OCS", "GET_OCS_USERS");
try
{
IDataReader reader =
DataProvider.GetOCSUsers(itemId, sortColumn, sortDirection, name, email, startRow, count);
List<OCSUser> accounts = new List<OCSUser>();
ObjectUtils.FillCollectionFromDataReader(accounts, reader);
res.Value = new OCSUsersPaged { PageUsers = accounts.ToArray() };
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.GET_OCS_USERS, ex);
return res;
}
IntResult intRes = GetOCSUsersCount(itemId, name, email);
res.ErrorCodes.AddRange(intRes.ErrorCodes);
if (!intRes.IsSuccess)
{
TaskManager.CompleteResultTask(res);
return res;
}
res.Value.RecordsCount = intRes.Value;
TaskManager.CompleteResultTask();
return res;
}
public static IntResult GetOCSUsersCount(int itemId, string name, string email)
{
IntResult res = TaskManager.StartResultTask<IntResult>("OCS", "GET_OCS_USERS_COUNT");
try
{
res.Value = DataProvider.GetOCSUsersCount(itemId, name, email);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.GET_OCS_USER_COUNT, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static ResultObject DeleteOCSUser(int itemId, string instanceId)
{
ResultObject res = TaskManager.StartResultTask<ResultObject>("OCS", "DELETE_OCS_USER");
OCSServer ocsServer;
try
{
ocsServer = GetOCSProxy(itemId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_GET_OCS_PROXY, ex);
return res;
}
try
{
ocsServer.DeleteUser(instanceId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_DELETE_OCS_USER, ex);
return res;
}
try
{
DataProvider.DeleteOCSUser(instanceId);
}
catch (Exception ex)
{
TaskManager.CompleteResultTask(res, OCSErrorCodes.CANNOT_DELETE_OCS_USER_FROM_METADATA, ex);
return res;
}
TaskManager.CompleteResultTask();
return res;
}
public static OCSUser GetUserGeneralSettings(int itemId, string instanceId)
{
TaskManager.StartTask("OCS", "GET_OCS_USER_GENERAL_SETTINGS");
OCSUser user;
try
{
OCSServer ocs = GetOCSProxy(itemId);
user = ocs.GetUserGeneralSettings(instanceId);
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
TaskManager.CompleteTask();
return user;
}
public static void SetUserGeneralSettings(int itemId, string instanceId, bool enabledForFederation, bool enabledForPublicIMConnectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence)
{
TaskManager.StartTask("OCS", "SET_OCS_USER_GENERAL_SETTINGS");
try
{
OCSServer ocs = GetOCSProxy(itemId);
ocs.SetUserGeneralSettings(instanceId, enabledForFederation, enabledForPublicIMConnectivity,
archiveInternalCommunications, archiveFederatedCommunications,
enabledForEnhancedPresence);
}
catch(Exception ex)
{
throw TaskManager.WriteError(ex);
}
TaskManager.CompleteTask();
}
}
}

View file

@ -1,672 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WebsitePanel.EnterpriseServer.Code.SharePoint;
using WebsitePanel.Providers.CRM;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers.SharePoint;
namespace WebsitePanel.EnterpriseServer.Code.HostedSolution
{
public class ReportController
{
private static void PopulateOrganizationStatisticsReport(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
OrganizationStatisticsRepotItem item = new OrganizationStatisticsRepotItem();
PopulateBaseItem(item, org, topReseller);
if (report.ExchangeReport != null)
{
try
{
List<ExchangeMailboxStatistics> mailboxStats =
report.ExchangeReport.Items.FindAll(
delegate(ExchangeMailboxStatistics stats)
{ return stats.OrganizationID == org.OrganizationId; });
item.TotalMailboxes = mailboxStats.Count;
foreach (ExchangeMailboxStatistics current in mailboxStats)
{
item.TotalMailboxesSize += current.TotalSize;
}
Providers.Exchange.ExchangeServer exchange;
if (!string.IsNullOrEmpty(org.GlobalAddressList))
{
try
{
int exchangeServiceId = GetExchangeServiceID(org.PackageId);
exchange =
ExchangeServerController.GetExchangeServer(exchangeServiceId, org.ServiceId);
}
catch (Exception ex)
{
throw new ApplicationException(
string.Format("Could not get exchange server. PackageId: {0}", org.PackageId), ex);
}
try
{
item.TotalPublicFoldersSize = exchange.GetPublicFolderSize(org.OrganizationId, "\\" + org.OrganizationId);
}
catch (Exception ex)
{
throw new ApplicationException(
string.Format("Could not get public folder size. OrgId: {0}", org.OrganizationId), ex);
}
}
try
{
org.DiskSpace = (int)(item.TotalPublicFoldersSize + item.TotalMailboxesSize);
PackageController.UpdatePackageItem(org);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Could not calcualate diskspace. Org Id: {0}", org.Id), ex);
}
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
if (report.SharePointReport != null)
{
List<SharePointStatistics> sharePoints =
report.SharePointReport.Items.FindAll(
delegate(SharePointStatistics stats) { return stats.OrganizationID == org.OrganizationId; });
item.TotalSharePointSiteCollections = sharePoints.Count;
foreach (SharePointStatistics current in sharePoints)
{
item.TotalSharePointSiteCollectionsSize += current.SiteCollectionSize;
}
}
if (report.CRMReport != null)
{
List<CRMOrganizationStatistics> crmOrganizationStatistics =
report.CRMReport.Items.FindAll(
delegate(CRMOrganizationStatistics stats) { return stats.OrganizationID == org.OrganizationId; });
item.TotalCRMUsers = crmOrganizationStatistics.Count;
}
item.TotalLyncUsers = 0;
item.TotalLyncEVUsers = 0;
if (report.LyncReport != null)
{
List<LyncUserStatistics> lyncOrganizationStatistics =
report.LyncReport.Items.FindAll(
delegate(LyncUserStatistics stats) { return stats.OrganizationID == org.OrganizationId; });
foreach (LyncUserStatistics current in lyncOrganizationStatistics)
{
if (current.EnterpriseVoice) item.TotalLyncEVUsers++;
}
item.TotalLyncUsers = lyncOrganizationStatistics.Count;
}
report.OrganizationReport.Items.Add(item);
}
private static HostedSharePointServer GetHostedSharePointServer(int serviceId)
{
HostedSharePointServer sps = new HostedSharePointServer();
ServiceProviderProxy.Init(sps, serviceId);
return sps;
}
private static int GetHostedSharePointServiceId(int packageId)
{
return PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedSharePoint);
}
private static void PopulateBaseItem(BaseStatistics stats, Organization org, string topReseller)
{
PackageInfo package;
UserInfo user;
try
{
package = PackageController.GetPackage(org.PackageId);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Could not get package {0}", org.PackageId), ex);
}
try
{
user = UserController.GetUser(package.UserId);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Could not get user {0}", package.UserId), ex);
}
stats.HostingSpace = package.PackageName;
stats.OrganizationID = org.OrganizationId;
stats.OrganizationName = org.Name;
stats.CustomerName = UserController.GetUser(package.UserId).Username;
stats.CustomerCreated = user.Created;
stats.ResellerName = UserController.GetUser(user.OwnerId).Username;
stats.TopResellerName = topReseller;
stats.OrganizationCreated = org.CreatedDate;
stats.HostingSpaceCreated = package.PurchaseDate;
}
private static int GetCRMServiceId(int packageId)
{
int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
return serviceId;
}
private static CRM GetCRMProxy(int packageId)
{
int crmServiceId = GetCRMServiceId(packageId);
CRM ws = new CRM();
ServiceProviderProxy.Init(ws, crmServiceId);
return ws;
}
private static void PopulateCRMReportItems(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
if (org.CrmOrganizationId == Guid.Empty)
return;
List<OrganizationUser> users;
try
{
users = CRMController.GetCRMOrganizationUsers(org.Id);
}
catch(Exception ex)
{
throw new ApplicationException(
string.Format("Could not get CRM Organization users. OrgId : {0}", org.Id), ex);
}
CRM crm;
try
{
crm = GetCRMProxy(org.PackageId);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Could not get CRM Proxy. PackageId: {0}", org.PackageId),
ex);
}
foreach (OrganizationUser user in users)
{
try
{
CRMOrganizationStatistics stats = new CRMOrganizationStatistics();
PopulateBaseItem(stats, org, topReseller);
stats.CRMOrganizationId = org.CrmOrganizationId;
stats.CRMUserName = user.DisplayName;
Guid crmUserId = CRMController.GetCrmUserId(user.AccountId);
CrmUserResult res = crm.GetCrmUserById(crmUserId, org.OrganizationId);
if (res.IsSuccess && res.Value != null)
{
stats.ClientAccessMode = res.Value.ClientAccessMode;
stats.CRMDisabled = res.Value.IsDisabled;
}
else
{
StringBuilder sb = new StringBuilder("Could not get CRM user by id.");
foreach (string str in res.ErrorCodes)
{
sb.AppendFormat("\n{0};", str);
}
throw new ApplicationException(sb.ToString());
}
report.CRMReport.Items.Add(stats);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void PopulateOrganizationData(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
if (report.ExchangeReport != null)
{
try
{
PopulateExchangeReportItems(org, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
if (report.CRMReport != null)
{
try
{
PopulateCRMReportItems(org, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
if (report.SharePointReport != null)
{
try
{
PopulateSharePointItem(org, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
if (report.LyncReport != null)
{
try
{
PopulateLyncReportItems(org, report, topReseller);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
if (report.OrganizationReport != null)
{
try
{
PopulateOrganizationStatisticsReport(org, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static int GetExchangeServiceID(int packageId)
{
return PackageController.GetPackageServiceId(packageId, ResourceGroups.Exchange);
}
private static int GetLyncServiceID(int packageId)
{
return PackageController.GetPackageServiceId(packageId, ResourceGroups.Lync);
}
private static void PopulateSharePointItem(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
List<SharePointSiteCollection> siteCollections;
try
{
siteCollections = HostedSharePointServerController.GetSiteCollections(org.Id);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Could not get site collections. OrgId: {0}", org.Id), ex);
}
if (siteCollections == null || siteCollections.Count == 0)
return;
HostedSharePointServer srv;
try
{
int serviceId = GetHostedSharePointServiceId(org.PackageId);
srv = GetHostedSharePointServer(serviceId);
}
catch(Exception ex)
{
throw new ApplicationException(
string.Format("Could not get sharepoint server. PackageId: {0}", org.PackageId), ex);
}
foreach (SharePointSiteCollection siteCollection in siteCollections)
{
try
{
SharePointStatistics stats = new SharePointStatistics();
PopulateBaseItem(stats, org, topReseller);
stats.SiteCollectionUrl = siteCollection.PhysicalAddress;
stats.SiteCollectionOwner = siteCollection.OwnerName;
stats.SiteCollectionQuota = siteCollection.MaxSiteStorage;
stats.SiteCollectionCreated = siteCollection.CreatedDate;
stats.SiteCollectionSize = srv.GetSiteCollectionSize(siteCollection.PhysicalAddress);
report.SharePointReport.Items.Add(stats);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void PopulateExchangeReportItems(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
//Check if exchange organization
if (string.IsNullOrEmpty(org.GlobalAddressList))
return;
List<ExchangeAccount> mailboxes;
Providers.Exchange.ExchangeServer exchange;
try
{
mailboxes = ExchangeServerController.GetExchangeMailboxes(org.Id);
}
catch (Exception ex)
{
throw new ApplicationException(
string.Format("Could not get mailboxes for current organization {0}", org.Id), ex);
}
try
{
int exchangeServiceId = GetExchangeServiceID(org.PackageId);
exchange = ExchangeServerController.GetExchangeServer(exchangeServiceId, org.ServiceId);
}
catch(Exception ex)
{
throw new ApplicationException(
string.Format("Could not get exchange server. PackageId: {0}", org.PackageId), ex);
}
ExchangeMailboxStatistics stats;
foreach (ExchangeAccount mailbox in mailboxes)
{
try
{
stats = null;
try
{
stats = exchange.GetMailboxStatistics(mailbox.UserPrincipalName);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Could not get mailbox statistics. AccountName: {0}",
mailbox.UserPrincipalName);
}
if (stats != null)
{
PopulateBaseItem(stats, org, topReseller);
stats.MailboxType = mailbox.AccountType;
if (mailbox.AccountType == ExchangeAccountType.Mailbox)
{
ExchangeAccount a = ExchangeServerController.GetAccount(mailbox.ItemId, mailbox.AccountId);
stats.MailboxPlan = a.MailboxPlan;
}
stats.BlackberryEnabled = BlackBerryController.CheckBlackBerryUserExists(mailbox.AccountId);
report.ExchangeReport.Items.Add(stats);
}
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void PopulateLyncReportItems(Organization org, EnterpriseSolutionStatisticsReport report, string topReseller)
{
//Check if lync organization
if (string.IsNullOrEmpty(org.LyncTenantId))
return;
LyncUser[] lyncUsers = null;
try
{
LyncUsersPagedResult res = LyncController.GetLyncUsers(org.Id);
if (res.IsSuccess) lyncUsers = res.Value.PageUsers;
}
catch (Exception ex)
{
throw new ApplicationException(
string.Format("Could not get lync users for current organization {0}", org.Id), ex);
}
if (lyncUsers == null)
return;
foreach (LyncUser lyncUser in lyncUsers)
{
try
{
LyncUserStatistics stats = new LyncUserStatistics();
try
{
stats.SipAddress = lyncUser.SipAddress;
if (string.IsNullOrEmpty(lyncUser.LineUri)) stats.PhoneNumber = string.Empty; else stats.PhoneNumber = lyncUser.LineUri;
LyncUserPlan plan = LyncController.GetLyncUserPlan(org.Id, lyncUser.LyncUserPlanId);
stats.Conferencing = plan.Conferencing;
stats.EnterpriseVoice = plan.EnterpriseVoice;
stats.Federation = plan.Federation;
stats.InstantMessaing = plan.IM;
stats.MobileAccess = plan.Mobility;
stats.LyncUserPlan = plan.LyncUserPlanName;
stats.DisplayName = lyncUser.DisplayName;
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Could not get lync statistics. AccountName: {0}",
lyncUser.DisplayName);
}
if (stats != null)
{
PopulateBaseItem(stats, org, topReseller);
report.LyncReport.Items.Add(stats);
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void PopulateSpaceData(int packageId, EnterpriseSolutionStatisticsReport report, string topReseller)
{
List<Organization> organizations;
try
{
organizations = OrganizationController.GetOrganizations(packageId, false);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Cannot get organizations in current package {0}", packageId), ex);
}
foreach(Organization org in organizations)
{
try
{
PopulateOrganizationData(org, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void PopulateUserData(UserInfo user, EnterpriseSolutionStatisticsReport report, string topReseller)
{
DataSet ds;
try
{
ds = PackageController.GetRawMyPackages(user.UserId);
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("Cannot get user's spaces {0}", user.UserId), ex);
}
foreach(DataRow row in ds.Tables[0].Rows)
{
int packageId = (int) row["PackageID"];
try
{
PopulateSpaceData(packageId, report, topReseller);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
private static void GetUsersData(EnterpriseSolutionStatisticsReport report, int userId, bool generateExchangeReport, bool generateSharePointReport, bool generateCRMReport, bool generateOrganizationReport, bool generateLyncReport, string topReseller)
{
List<UserInfo> users;
try
{
users = UserController.GetUsers(userId, false);
}
catch(Exception ex)
{
throw new ApplicationException("Cannot get users for report", ex);
}
foreach (UserInfo user in users)
{
try
{
PopulateUserData(user, report, topReseller);
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator)
{
GetUsersData(report, user.UserId, generateExchangeReport, generateSharePointReport,
generateCRMReport,
generateOrganizationReport,
generateLyncReport,
string.IsNullOrEmpty(topReseller) ? user.Username : topReseller);
}
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
public static EnterpriseSolutionStatisticsReport GetEnterpriseSolutionStatisticsReport(int userId, bool generateExchangeReport, bool generateSharePointReport, bool generateCRMReport, bool generateOrganizationReport, bool generateLyncReport)
{
EnterpriseSolutionStatisticsReport report = new EnterpriseSolutionStatisticsReport();
if (generateExchangeReport || generateOrganizationReport)
report.ExchangeReport = new ExchangeStatisticsReport();
if (generateSharePointReport || generateOrganizationReport)
report.SharePointReport = new SharePointStatisticsReport();
if (generateLyncReport || generateOrganizationReport)
report.LyncReport = new LyncStatisticsReport();
if (generateCRMReport || generateOrganizationReport)
report.CRMReport = new CRMStatisticsReport();
if (generateOrganizationReport)
report.OrganizationReport = new OrganizationStatisticsReport();
try
{
GetUsersData(report, userId, generateExchangeReport, generateSharePointReport, generateCRMReport,
generateOrganizationReport, generateLyncReport, null);
}
catch(Exception ex)
{
TaskManager.WriteError(ex, "Cannot get enterprise solution statistics report");
}
return report;
}
}
}

View file

@ -1,111 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class AuditLog
{
public static DataSet GetAuditLogRecordsPaged(int userId, int packageId, int itemId, string itemName, DateTime startDate, DateTime endDate,
int severityId, string sourceName, string taskName, string sortColumn, int startRow, int maximumRows)
{
return DataProvider.GetAuditLogRecordsPaged(SecurityContext.User.UserId,
userId, packageId, itemId, itemName, GetStartDate(startDate), GetEndDate(endDate),
severityId, sourceName, taskName, sortColumn, startRow, maximumRows);
}
public static DataSet GetAuditLogSources()
{
return DataProvider.GetAuditLogSources();
}
public static DataSet GetAuditLogTasks(string sourceName)
{
return DataProvider.GetAuditLogTasks(sourceName);
}
public static LogRecord GetAuditLogRecord(string recordId)
{
return ObjectUtils.FillObjectFromDataReader<LogRecord>(
DataProvider.GetAuditLogRecord(recordId));
}
public static int DeleteAuditLogRecords(int userId, int itemId, string itemName,
DateTime startDate, DateTime endDate, int severityId, string sourceName, string taskName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
DataProvider.DeleteAuditLogRecords(SecurityContext.User.UserId,
userId, itemId, itemName, GetStartDate(startDate), GetEndDate(endDate), severityId, sourceName, taskName);
return 0;
}
public static int DeleteAuditLogRecordsComplete()
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin);
if (accountCheck < 0) return accountCheck;
DataProvider.DeleteAuditLogRecordsComplete();
return 0;
}
public static void AddAuditLogRecord(string recordId, int severityId, int userId, string username,
int packageId, int itemId, string itemName, DateTime startDate, DateTime finishDate,
string sourceName, string taskName, string executionLog)
{
try
{
DataProvider.AddAuditLogRecord(recordId, severityId, userId, username, packageId, itemId, itemName,
startDate, finishDate, sourceName, taskName, executionLog);
}
catch
{
// skip error
}
}
private static DateTime GetStartDate(DateTime d)
{
return new DateTime(d.Year, d.Month, d.Day, 0, 0, 0);
}
private static DateTime GetEndDate(DateTime d)
{
return new DateTime(d.Year, d.Month, d.Day, 23, 59, 59);
}
}
}

View file

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

View file

@ -1,817 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using WebsitePanel.Server;
using WebsitePanel.Providers;
using WebsitePanel.Providers.OS;
using OS = WebsitePanel.Providers.OS;
using System.Collections;
namespace WebsitePanel.EnterpriseServer
{
public class OperatingSystemController : IImportController, IBackupController
{
private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB
private static OS.OperatingSystem GetOS(int serviceId)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, serviceId);
return os;
}
#region ODBC DSNs
public static DataSet GetRawOdbcSourcesPaged(int packageId,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return PackageController.GetRawPackageItemsPaged(packageId, ResourceGroups.Os, typeof(SystemDSN),
true, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<SystemDSN> GetOdbcSources(int packageId, bool recursive)
{
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(
packageId, ResourceGroups.Os, typeof(SystemDSN), recursive);
return items.ConvertAll<SystemDSN>(
new Converter<ServiceProviderItem, SystemDSN>(ConvertItemToSystemDSN));
}
private static SystemDSN ConvertItemToSystemDSN(ServiceProviderItem item)
{
return (SystemDSN)item;
}
public static string[] GetInstalledOdbcDrivers(int packageId)
{
// load service item
int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
OS.OperatingSystem os = GetOS(serviceId);
return os.GetInstalledOdbcDrivers();
}
public static SystemDSN GetOdbcSource(int itemId)
{
// load meta item
SystemDSN item = (SystemDSN)PackageController.GetPackageItem(itemId);
// load service item
OS.OperatingSystem os = GetOS(item.ServiceId);
SystemDSN dsn = os.GetDSN(item.Name);
// add common properties
dsn.Id = item.Id;
dsn.PackageId = item.PackageId;
dsn.ServiceId = item.ServiceId;
if(dsn.Driver == "MsAccess" || dsn.Driver == "Excel" || dsn.Driver == "Text")
dsn.DatabaseName = FilesController.GetVirtualPackagePath(item.PackageId, dsn.DatabaseName);
return dsn;
}
public static int AddOdbcSource(SystemDSN item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check quota
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.OS_ODBC);
if (quota.QuotaExhausted)
return BusinessErrorCodes.ERROR_OS_DSN_RESOURCE_QUOTA_LIMIT;
// check if mail resource is available
int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Os);
if (serviceId == 0)
return BusinessErrorCodes.ERROR_OS_RESOURCE_UNAVAILABLE;
// check package items
if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(SystemDSN)) != null)
return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_EXISTS;
// place log record
TaskManager.StartTask("ODBC_DSN", "ADD", item.Name);
try
{
// check service items
OS.OperatingSystem os = GetOS(serviceId);
if (os.GetDSN(item.Name) != null)
return BusinessErrorCodes.ERROR_OS_DSN_SERVICE_ITEM_EXISTS;
string[] dbNameParts = item.DatabaseName.Split('|');
string groupName = null;
if (dbNameParts.Length > 1)
{
item.DatabaseName = dbNameParts[0];
groupName = dbNameParts[1];
}
// get database server address
item.DatabaseServer = GetDatabaseServerName(groupName, item.PackageId);
if (item.Driver == "MsAccess" || item.Driver == "Excel" || item.Driver == "Text")
item.DatabaseName = FilesController.GetFullPackagePath(item.PackageId, item.DatabaseName);
// add service item
os.CreateDSN(item);
// save item
item.DatabasePassword = CryptoUtils.Encrypt(item.DatabasePassword);
item.ServiceId = serviceId;
int itemId = PackageController.AddPackageItem(item);
TaskManager.ItemId = itemId;
return itemId;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int UpdateOdbcSource(SystemDSN item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(item.Id);
if (origItem == null)
return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// place log record
TaskManager.StartTask("ODBC_DSN", "UPDATE", origItem.Name);
TaskManager.ItemId = item.Id;
try
{
// get service
OS.OperatingSystem os = GetOS(origItem.ServiceId);
// password
item.Driver = origItem.Driver;
item.Name = origItem.Name;
if (item.DatabasePassword == "")
item.DatabasePassword = CryptoUtils.Decrypt(origItem.DatabasePassword);
string[] dbNameParts = item.DatabaseName.Split('|');
string groupName = null;
if (dbNameParts.Length > 1)
{
item.DatabaseName = dbNameParts[0];
groupName = dbNameParts[1];
}
// get database server address
item.DatabaseServer = GetDatabaseServerName(groupName, item.PackageId);
if (item.Driver == "MsAccess" || item.Driver == "Excel" || item.Driver == "Text")
item.DatabaseName = FilesController.GetFullPackagePath(origItem.PackageId, item.DatabaseName);
// update service item
os.UpdateDSN(item);
// update meta item
if (item.DatabasePassword != "")
{
item.DatabasePassword = CryptoUtils.Encrypt(item.DatabasePassword);
PackageController.UpdatePackageItem(item);
}
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
private static string GetDatabaseServerName(string groupName, int packageId)
{
int sqlServiceId = PackageController.GetPackageServiceId(packageId, groupName);
if (sqlServiceId > 0)
{
StringDictionary sqlSettings = ServerController.GetServiceSettings(sqlServiceId);
return sqlSettings["ExternalAddress"];
}
return "";
}
public static int DeleteOdbcSource(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("ODBC_DSN", "DELETE", origItem.Name);
TaskManager.ItemId = itemId;
try
{
// get service
OS.OperatingSystem os = GetOS(origItem.ServiceId);
// delete service item
os.DeleteDSN(origItem.Name);
// delete meta item
PackageController.DeletePackageItem(origItem.Id);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
private static WindowsServer GetServerService(int serverId)
{
WindowsServer winServer = new WindowsServer();
ServiceProviderProxy.ServerInit(winServer, serverId);
return winServer;
}
#region Terminal Services Sessions
public static TerminalSession[] GetTerminalServicesSessions(int serverId)
{
return GetServerService(serverId).GetTerminalServicesSessions();
}
public static int CloseTerminalServicesSession(int serverId, int sessionId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load server info
ServerInfo server = ServerController.GetServerById(serverId);
// place log record
TaskManager.StartTask("SERVER", "RESET_TERMINAL_SESSION", sessionId);
TaskManager.ItemId = serverId;
try
{
GetServerService(serverId).CloseTerminalServicesSession(sessionId);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
#region Windows Processes
public static WindowsProcess[] GetWindowsProcesses(int serverId)
{
return GetServerService(serverId).GetWindowsProcesses();
}
public static int TerminateWindowsProcess(int serverId, int pid)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load server info
ServerInfo server = ServerController.GetServerById(serverId);
// place log record
TaskManager.StartTask("SERVER", "TERMINATE_SYSTEM_PROCESS", pid);
TaskManager.ItemId = serverId;
try
{
GetServerService(serverId).TerminateWindowsProcess(pid);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
#region Windows Services
public static WindowsService[] GetWindowsServices(int serverId)
{
return GetServerService(serverId).GetWindowsServices();
}
public static int ChangeWindowsServiceStatus(int serverId, string id, WindowsServiceStatus status)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load server info
ServerInfo server = ServerController.GetServerById(serverId);
// place log record
TaskManager.StartTask("SERVER", "CHANGE_WINDOWS_SERVICE_STATUS", id);
TaskManager.ItemId = serverId;
TaskManager.WriteParameter("New Status", status);
try
{
GetServerService(serverId).ChangeWindowsServiceStatus(id, status);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
// Check If FSRM Role services were installed
public static bool CheckFileServicesInstallation(int serviceId)
{
OS.OperatingSystem os = GetOS(serviceId);
return os.CheckFileServicesInstallation();
}
#endregion
#region Web Platform Installer
public static bool CheckLoadUserProfile(int serverId)
{
int serviceId = getWebServiceId(serverId);
if (serviceId != -1)
{
return WebServerController.GetWebServer(serviceId).CheckLoadUserProfile();
}
return false;
}
private static int getWebServiceId(int serverId)
{
DataSet dsServices = ServerController.GetRawServicesByServerId(serverId);
int webGroup = -1;
if (dsServices.Tables.Count < 1) return -1;
foreach (DataRow r in dsServices.Tables[0].Rows)
{
if (r["GroupName"].ToString() == "Web")
{
webGroup = (int)r["GroupID"];
break;
}
}
if (webGroup == -1) return -1;
foreach (DataRow r in dsServices.Tables[1].Rows)
{
if ((int)r["GroupID"] == webGroup)
{
return (int)r["ServiceID"];
}
}
return -1;
}
public static void EnableLoadUserProfile(int serverId)
{
int serviceId = getWebServiceId(serverId);
if (serviceId != -1)
{
WebServerController.GetWebServer(serviceId).EnableLoadUserProfile();
}
}
public static void InitWPIFeeds(int serverId, string feedUrls)
{
GetServerService(serverId).InitWPIFeeds(feedUrls);
}
public static WPITab[] GetWPITabs(int serverId)
{
return GetServerService(serverId).GetWPITabs();
}
public static WPIKeyword[] GetWPIKeywords(int serverId)
{
return GetServerService(serverId).GetWPIKeywords();
}
public static WPIProduct[] GetWPIProducts(int serverId, string tabId, string keywordId)
{
return GetServerService(serverId).GetWPIProducts(tabId, keywordId);
}
public static WPIProduct[] GetWPIProductsFiltered(int serverId, string keywordId)
{
return GetServerService(serverId).GetWPIProductsFiltered(keywordId);
}
public static WPIProduct[] GetWPIProductsWithDependencies(int serverId, string[] products)
{
return GetServerService(serverId).GetWPIProductsWithDependencies(products);
}
public static void InstallWPIProducts(int serverId, string[] products)
{
GetServerService(serverId).InstallWPIProducts(products);
}
public static void CancelInstallWPIProducts(int serverId)
{
GetServerService(serverId).CancelInstallWPIProducts();
}
public static string GetWPIStatus(int serverId)
{
return GetServerService(serverId).GetWPIStatus();
}
public static string WpiGetLogFileDirectory(int serverId)
{
return GetServerService(serverId).WpiGetLogFileDirectory();
}
public static SettingPair[] WpiGetLogsInDirectory(int serverId, string Path)
{
return GetServerService(serverId).WpiGetLogsInDirectory(Path);
}
#endregion
#region Event Viewer
public static string[] GetLogNames(int serverId)
{
return GetServerService(serverId).GetLogNames();
}
public static SystemLogEntry[] GetLogEntries(int serverId, string logName)
{
return GetServerService(serverId).GetLogEntries(logName);
}
public static SystemLogEntriesPaged GetLogEntriesPaged(int serverId, string logName, int startRow, int maximumRows)
{
return GetServerService(serverId).GetLogEntriesPaged(logName, startRow, maximumRows);
}
public static int ClearLog(int serverId, string logName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
TaskManager.StartTask("SERVER", "CLEAR_EVENT_LOG", logName);
TaskManager.ItemId = serverId;
try
{
GetServerService(serverId).ClearLog(logName);
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
#endregion
#region Server Reboot
public static int RebootSystem(int serverId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load server info
ServerInfo server = ServerController.GetServerById(serverId);
// place log record
TaskManager.StartTask("SERVER", "REBOOT");
TaskManager.ItemId = serverId;
try
{
GetServerService(serverId).RebootSystem();
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
#region IImportController Members
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType,
ResourceGroupInfo group)
{
List<string> items = new List<string>();
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
OS.OperatingSystem os = GetOS(serviceId);
if (itemType == typeof(SystemDSN))
items.AddRange(os.GetDSNNames());
return items;
}
public void ImportItem(int packageId, int itemTypeId, Type itemType,
ResourceGroupInfo group, string itemName)
{
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return;
if (itemType == typeof(SystemDSN))
{
// save DSN info
SystemDSN dsn = new SystemDSN();
dsn.Name = itemName;
dsn.ServiceId = serviceId;
dsn.PackageId = packageId;
PackageController.AddPackageItem(dsn);
}
}
#endregion
#region IBackupController Members
public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
if (item is HomeFolder)
{
// backup home folder files
string backupName = String.Format("SpaceFiles_{0}_{1}.zip",
item.Id, DateTime.Now.Ticks);
// get the list of remote files
List<SystemFile> files = FilesController.GetFiles(item.PackageId, "\\", true);
string[] zipFiles = new string[files.Count];
for(int i = 0; i < zipFiles.Length; i++)
zipFiles[i] = files[i].Name;
// zip remote files
FilesController.ZipFiles(item.PackageId, zipFiles, backupName);
// download zipped file
string localBackupPath = Path.Combine(tempFolder, backupName);
byte[] buffer = null;
FileStream stream = new FileStream(localBackupPath, FileMode.Create, FileAccess.Write);
int offset = 0;
long length = 0;
do
{
// read remote content
buffer = FilesController.GetFileBinaryChunk(item.PackageId, backupName, offset, FILE_BUFFER_LENGTH);
// write remote content
stream.Write(buffer, 0, buffer.Length);
length += buffer.Length;
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
stream.Close();
// delete zipped file
if (FilesController.FileExists(item.PackageId, backupName))
FilesController.DeleteFiles(item.PackageId, new string[] { backupName });
// add file pointer
BackupController.WriteFileElement(writer, "SpaceFiles", backupName, length);
// store meta item
XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder));
serializer.Serialize(writer, item);
}
else if (item is SystemDSN)
{
// backup ODBC DSN
OS.OperatingSystem os = GetOS(item.ServiceId);
// read DSN info
SystemDSN itemDsn = item as SystemDSN;
SystemDSN dsn = os.GetDSN(item.Name);
dsn.DatabasePassword = itemDsn.DatabasePassword;
XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN));
serializer.Serialize(writer, dsn);
}
return 0;
}
public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType == typeof(HomeFolder))
{
OS.OperatingSystem os = GetOS(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder));
HomeFolder homeFolder = (HomeFolder)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("HomeFolder")));
// create home folder if required
if (!os.DirectoryExists(homeFolder.Name))
{
os.CreatePackageFolder(homeFolder.Name);
}
// copy database backup to remote server
XmlNode fileNode = itemNode.SelectSingleNode("File[@name='SpaceFiles']");
string backupFileName = fileNode.Attributes["path"].Value;
long backupFileLength = Int64.Parse(fileNode.Attributes["size"].Value);
string localBackupFilePath = Path.Combine(tempFolder, backupFileName);
if (new FileInfo(localBackupFilePath).Length != backupFileLength)
return -3;
FileStream stream = new FileStream(localBackupFilePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int readBytes = 0;
long length = 0;
string remoteBackupPath = Path.Combine(homeFolder.Name, backupFileName);
do
{
// read package file
readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
length += readBytes;
if (readBytes < FILE_BUFFER_LENGTH)
// resize buffer
Array.Resize<byte>(ref buffer, readBytes);
// write remote backup file
os.AppendFileBinaryContent(remoteBackupPath, buffer);
}
while (readBytes == FILE_BUFFER_LENGTH);
stream.Close();
// unzip files
os.UnzipFiles(remoteBackupPath, homeFolder.Name);
// delete archive
if (os.FileExists(remoteBackupPath))
os.DeleteFile(remoteBackupPath);
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, itemName, typeof(HomeFolder)) == null)
{
homeFolder.PackageId = packageId;
homeFolder.ServiceId = serviceId;
PackageController.AddPackageItem(homeFolder);
}
}
else if (itemType == typeof(SystemDSN))
{
OS.OperatingSystem os = GetOS(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN));
SystemDSN dsn = (SystemDSN)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("SystemDSN")));
// create DSN if required
if (os.GetDSN(itemName) == null)
{
dsn.DatabasePassword = CryptoUtils.Decrypt(dsn.DatabasePassword);
os.CreateDSN(dsn);
// restore password
dsn.DatabasePassword = CryptoUtils.Encrypt(dsn.DatabasePassword);
}
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemDSN)) == null)
{
dsn.PackageId = packageId;
dsn.ServiceId = serviceId;
PackageController.AddPackageItem(dsn);
}
}
return 0;
}
#endregion
}
}

View file

@ -1,235 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Threading;
using WebsitePanel.Providers;
namespace WebsitePanel.EnterpriseServer
{
public class PackageAsyncWorker
{
private int userId = -1;
private List<PackageInfo> packages = new List<PackageInfo>();
private PackageStatus itemsStatus = PackageStatus.Active;
#region Public properties
public int UserId
{
get { return this.userId; }
set { this.userId = value; }
}
public System.Collections.Generic.List<PackageInfo> Packages
{
get { return this.packages; }
set { this.packages = value; }
}
public PackageStatus ItemsStatus
{
get { return this.itemsStatus; }
set { this.itemsStatus = value; }
}
#endregion
#region Delete Packages Service Items
public void DeletePackagesServiceItemsAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(DeletePackagesServiceItems));
t.Start();
}
public void DeletePackagesServiceItems()
{
// impersonate thread
if(userId != -1)
SecurityContext.SetThreadPrincipal(userId);
// delete package by package
foreach (PackageInfo package in packages)
{
TaskManager.StartTask("SPACE", "DELETE_ITEMS", package.PackageName);
TaskManager.WriteParameter("User", package.UserId);
// get package service items
List<ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
0, package.PackageId, false, false, false, true); // disposable items
// order items by service
Dictionary<int, List<ServiceProviderItem>> orderedItems =
PackageController.OrderServiceItemsByServices(items);
// delete service items by service sets
foreach (int serviceId in orderedItems.Keys)
{
ServiceInfo service = ServerController.GetServiceInfo(serviceId);
//Delete Exchange Organization
if (service.ProviderId == 103 /*Organizations*/)
{
OrganizationController.DeleteOrganization(orderedItems[serviceId][0].Id);
//int exchangeId = PackageController.GetPackageServiceId(package.PackageId, ResourceGroups.Exchange2007);
//ExchangeServerController.DeleteOrganization(orderedItems[serviceId][0].Id);
}
else
ProcessServiceItems(false, false, serviceId, orderedItems[serviceId] );
}
// delete package from database
DataProvider.DeletePackage(SecurityContext.User.UserId, package.PackageId);
}
// add log record
TaskManager.CompleteTask();
}
#endregion
#region Change Packages Service Items State
public void ChangePackagesServiceItemsStateAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(ChangePackagesServiceItemsState));
t.Start();
}
public void ChangePackagesServiceItemsState()
{
// impersonate thread
if (userId != -1)
SecurityContext.SetThreadPrincipal(userId);
TaskManager.StartTask("SPACE", "CHANGE_ITEMS_STATUS");
// collect required service items
List<ServiceProviderItem> items = new List<ServiceProviderItem>();
foreach (PackageInfo package in packages)
{
items.AddRange(PackageController.GetServiceItemsForStatistics(
0, package.PackageId, false, false, true, false)); // suspendable items
}
// order items by service
Dictionary<int, List<ServiceProviderItem>> orderedItems =
PackageController.OrderServiceItemsByServices(items);
// process items
bool enabled = (ItemsStatus == PackageStatus.Active);
foreach (int serviceId in orderedItems.Keys)
{
ProcessServiceItems(true, enabled, serviceId, orderedItems[serviceId]);
}
// add log record
TaskManager.CompleteTask();
}
#endregion
private void ProcessServiceItems(bool changeState, bool enabled,
int serviceId, List<ServiceProviderItem> items)
{
string methodName = changeState ? "ChangeServiceItemsState" : "DeleteServiceItems";
int PACKET_SIZE = 10;
int ATTEMPTS = 3;
TaskManager.Write(String.Format("Start analyze {0} service ({1} items)",
serviceId, items.Count));
try
{
// convert items to SoapObjects by packets of 0
int startItem = 0;
List<SoapServiceProviderItem> objItems = new List<SoapServiceProviderItem>();
for (int i = 0; i < items.Count; i++)
{
// add to the packet
objItems.Add(SoapServiceProviderItem.Wrap(items[i]));
if (((i > 0) && (i % PACKET_SIZE == 0))
|| i == (items.Count - 1)) // packet is ready
{
if (objItems.Count == 0)
continue;
int attempt = 0;
bool success = false;
while (attempt < ATTEMPTS)
{
// increment attempt
attempt++;
try
{
// send packet for calculation
// invoke service provider
TaskManager.Write(String.Format("Invoke {0} method ('{1}' - '{2}' items) - {3} attempt",
methodName, items[startItem].Name, items[i].Name, attempt));
ServiceProvider prov = new ServiceProvider();
ServiceProviderProxy.Init(prov, serviceId);
if (changeState)
prov.ChangeServiceItemsState(objItems.ToArray(), enabled);
else
prov.DeleteServiceItems(objItems.ToArray());
// exit from the loop
success = true;
break;
}
catch (Exception ex)
{
TaskManager.WriteWarning(ex.ToString());
}
}
if (!success)
throw new Exception("The number of attemtps has been reached. The whole operation aborted.");
// reset packet counter
startItem = i + 1;
objItems.Clear();
}
} // end for items
}
catch (Exception ex)
{
// log exception
TaskManager.WriteWarning(ex.ToString());
}
TaskManager.Write(String.Format("End analyze {0} service ({1} items)",
serviceId, items.Count));
}
}
}

View file

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

View file

@ -1,92 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class BackupAsyncWorker
{
public int threadUserId = -1;
public string taskId;
public int userId;
public int packageId;
public int serviceId;
public int serverId;
public string backupFileName;
public int storePackageId;
public string storePackageFolder;
public string storeServerFolder;
public string storePackageBackupPath;
public string storeServerBackupPath;
public bool deleteTempBackup;
#region Backup
public void BackupAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Backup));
t.Start();
}
public void Backup()
{
// impersonate thread
if (threadUserId != -1)
SecurityContext.SetThreadPrincipal(threadUserId);
// perform backup
BackupController.BackupInternal(taskId, userId, packageId, serviceId, serverId, backupFileName, storePackageId,
storePackageFolder, storeServerFolder, deleteTempBackup);
}
#endregion
#region Restore
public void RestoreAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Restore));
t.Start();
}
public void Restore()
{
// impersonate thread
if (threadUserId != -1)
SecurityContext.SetThreadPrincipal(threadUserId);
// perform restore
BackupController.RestoreInternal(taskId, userId, packageId, serviceId, serverId,
storePackageId, storePackageBackupPath, storeServerBackupPath);
}
#endregion
}
}

View file

@ -1,924 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using WebsitePanel.Providers;
using OS = WebsitePanel.Providers.OS;
using WebsitePanel.Ecommerce.EnterpriseServer;
namespace WebsitePanel.EnterpriseServer
{
public class BackupController
{
public const string BACKUP_CATALOG_FILE_NAME = "BackupCatalog.xml";
private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB
private const string RSA_SETTINGS_KEY = "RSA_KEY";
public static int Backup(bool async, string taskId, int userId, int packageId, int serviceId, int serverId,
string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder,
bool deleteTempBackup)
{
// check demo account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check admin account
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if ((serviceId > 0 || serverId > 0) && accountCheck < 0) return accountCheck;
if (accountCheck < 0)
deleteTempBackup = true;
// check if backup temp folder is available
string tempFolder = GetTempBackupFolder();
if (!FolderWriteAccessible(tempFolder))
return BusinessErrorCodes.ERROR_BACKUP_TEMP_FOLDER_UNAVAILABLE;
// check destination folder if required
if (!String.IsNullOrEmpty(storePackageFolder) &&
!RemoteServerFolderWriteAccessible(storePackageId, storePackageFolder))
return BusinessErrorCodes.ERROR_BACKUP_DEST_FOLDER_UNAVAILABLE;
// check server folder if required
if (!String.IsNullOrEmpty(storeServerFolder) &&
!FolderWriteAccessible(storeServerFolder))
return BusinessErrorCodes.ERROR_BACKUP_SERVER_FOLDER_UNAVAILABLE;
// check/reset delete flag
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if (accountCheck < 0 && !deleteTempBackup)
deleteTempBackup = true;
if (async)
{
BackupAsyncWorker worker = new BackupAsyncWorker();
worker.threadUserId = SecurityContext.User.UserId;
worker.taskId = taskId;
worker.userId = userId;
worker.packageId = packageId;
worker.serviceId = serviceId;
worker.serverId = serverId;
worker.backupFileName = backupFileName;
worker.storePackageId = storePackageId;
worker.storePackageFolder = storePackageFolder;
worker.storeServerFolder = storeServerFolder;
worker.deleteTempBackup = deleteTempBackup;
// run
worker.BackupAsync();
return 0;
}
else
{
return BackupInternal(taskId, userId, packageId, serviceId, serverId,
backupFileName, storePackageId, storePackageFolder, storeServerFolder,
deleteTempBackup);
}
}
public static int BackupInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder,
bool deleteTempBackup)
{
try
{
TaskManager.StartTask(taskId, "BACKUP", "BACKUP", backupFileName);
TaskManager.ItemId = SecurityContext.User.UserId;
// get the list of items to backup
TaskManager.Write("Calculate items to backup");
List<ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);
if (items.Count == 0)
return 0;
// group items by item types
Dictionary<int, List<ServiceProviderItem>> groupedItems = new Dictionary<int, List<ServiceProviderItem>>();
// sort by groups
foreach (ServiceProviderItem item in items)
{
// add to group
if (!groupedItems.ContainsKey(item.TypeId))
groupedItems[item.TypeId] = new List<ServiceProviderItem>();
groupedItems[item.TypeId].Add(item);
}
// temp backup folder
string tempFolder = GetTempBackupFolder();
// create backup catalog file
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
// write backup file header
writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
writer.WriteStartElement("Backup");
writer.WriteStartElement("Info");
writer.WriteElementString("Name", backupFileName);
writer.WriteElementString("Created", DateTime.Now.ToString("r"));
writer.WriteElementString("User", GetLoggedUsername());
writer.WriteEndElement(); // Info
// determine the number of items to backup
int totalItems = 0;
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
if (!itemType.Backupable)
continue;
totalItems += groupedItems[itemTypeId].Count;
}
TaskManager.IndicatorMaximum = totalItems + 2;
TaskManager.IndicatorCurrent = 0;
// backup grouped items
writer.WriteStartElement("Items");
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
if (!itemType.Backupable)
continue;
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// instantiate controller
IBackupController controller = null;
try
{
if (group.GroupController != null)
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
// backup items
foreach (ServiceProviderItem item in groupedItems[itemTypeId])
{
TaskManager.Write(String.Format("Backup {0} of {1} - {2} '{3}'",
TaskManager.IndicatorCurrent + 1,
totalItems,
itemType.DisplayName,
item.Name));
try
{
int backupResult = BackupItem(tempFolder, writer, item, group, controller);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't backup item");
}
// increment progress
TaskManager.IndicatorCurrent += 1;
}
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
writer.WriteEndElement(); // Items
// close catalog writer
writer.WriteEndElement(); // Backup
writer.Close();
// convert to Xml document
XmlDocument doc = new XmlDocument();
doc.LoadXml(sw.ToString());
// sign XML document
//SignXmlDocument(doc);
// save signed doc to file
try
{
doc.Save(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't save backup catalog file: "
+ Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
return 0;
}
TaskManager.Write("Packaging backup...");
// compress backup files
string[] zipFiles = Directory.GetFiles(tempFolder);
string[] zipFileNames = new string[zipFiles.Length];
for (int i = 0; i < zipFiles.Length; i++)
zipFileNames[i] = Path.GetFileName(zipFiles[i]);
string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
try
{
FileUtils.ZipFiles(backupFileNamePath, tempFolder, zipFileNames);
// delete packed files
foreach (string zipFile in zipFiles)
File.Delete(zipFile);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't zip backed up files");
return 0;
}
TaskManager.IndicatorCurrent += 1;
TaskManager.Write("Copying backup...");
// move/copy backup file
if (!String.IsNullOrEmpty(storeServerFolder))
{
// copy to local folder or UNC
try
{
string destFile = Path.Combine(storeServerFolder, backupFileName);
File.Copy(backupFileNamePath, destFile, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy backup to destination location");
return 0;
}
}
else if (storePackageId > 0)
{
try
{
// copy to space folder
int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
Path.Combine(storePackageFolder, backupFileName));
FileStream stream = new FileStream(backupFileNamePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int readBytes = 0;
do
{
// read package file
readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
if (readBytes < FILE_BUFFER_LENGTH)
// resize buffer
Array.Resize<byte>(ref buffer, readBytes);
// write remote backup file
os.AppendFileBinaryContent(remoteBackupPath, buffer);
}
while (readBytes == FILE_BUFFER_LENGTH);
stream.Close();
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy backup to destination hosting space");
return 0;
}
}
TaskManager.IndicatorCurrent += 1;
// delete backup file if required
if (deleteTempBackup)
{
try
{
// delete backup folder and all its contents
Directory.Delete(tempFolder, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't delete temporary backup folder");
return 0;
}
}
TaskManager.IndicatorCurrent = TaskManager.IndicatorMaximum;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
public static List<ServiceProviderItem> GetBackupItems(int userId,
int packageId, int serviceId, int serverId)
{
List<ServiceProviderItem> items = new List<ServiceProviderItem>();
if (packageId > 0)
{
items.AddRange(PackageController.GetPackageItems(packageId));
}
else if (serviceId > 0)
{
items.AddRange(PackageController.GetServiceItems(serviceId));
}
else if (serverId > 0)
{
// get server services
List<ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
foreach (ServiceInfo service in services)
items.AddRange(PackageController.GetServiceItems(service.ServiceId));
}
else if (userId > 0)
{
List<PackageInfo> packages = new List<PackageInfo>();
// get own spaces
packages.AddRange(PackageController.GetMyPackages(userId));
// get user spaces
packages.AddRange(PackageController.GetPackages(userId));
// build collection
foreach (PackageInfo package in packages)
items.AddRange(PackageController.GetPackageItems(package.PackageId));
}
return items;
}
public static KeyValueBunch GetBackupContentSummary(int userId, int packageId,
int serviceId, int serverId)
{
Dictionary<string, List<string>> summary = new Dictionary<string, List<string>>();
// Get backup items
List<ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);
// Prepare filter for in-loop sort
ServiceProviderItemType[] itemTypes = PackageController.GetServiceItemTypes().ToArray();
// Group service items by type id
foreach (ServiceProviderItem si in items)
{
ServiceProviderItemType itemType = Array.Find<ServiceProviderItemType>(itemTypes,
x => x.ItemTypeId == si.TypeId && x.Backupable);
// Sort out item types without backup capabilities
if (itemType != null)
{
// Mimic a grouping sort
if (!summary.ContainsKey(itemType.DisplayName))
summary.Add(itemType.DisplayName, new List<string>());
//
summary[itemType.DisplayName].Add(si.Name);
}
}
//
KeyValueBunch result = new KeyValueBunch();
// Convert grouped data into serializable format
foreach (string groupName in summary.Keys)
result[groupName] = String.Join(",", summary[groupName].ToArray());
//
return result;
}
public static int Restore(bool async, string taskId, int userId, int packageId, int serviceId, int serverId,
int storePackageId, string storePackageBackupPath, string storeServerBackupPath)
{
// check demo account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// check admin account
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if ((serviceId > 0 || serverId > 0) && accountCheck < 0) return accountCheck;
// check if backup temp folder is available
string tempFolder = GetTempBackupFolder();
if (!FolderWriteAccessible(tempFolder))
return BusinessErrorCodes.ERROR_BACKUP_TEMP_FOLDER_UNAVAILABLE;
// check server source path if required
if (!String.IsNullOrEmpty(storeServerBackupPath))
{
try
{
if (!File.Exists(storeServerBackupPath))
return BusinessErrorCodes.ERROR_RESTORE_BACKUP_SOURCE_NOT_FOUND;
}
catch
{
return BusinessErrorCodes.ERROR_RESTORE_BACKUP_SOURCE_UNAVAILABLE;
}
}
if (async)
{
BackupAsyncWorker worker = new BackupAsyncWorker();
worker.threadUserId = SecurityContext.User.UserId;
worker.taskId = taskId;
worker.userId = userId;
worker.packageId = packageId;
worker.serviceId = serviceId;
worker.serverId = serverId;
worker.storePackageId = storePackageId;
worker.storePackageBackupPath = storePackageBackupPath;
worker.storeServerBackupPath = storeServerBackupPath;
// run
worker.RestoreAsync();
return 0;
}
else
{
return RestoreInternal(taskId, userId, packageId, serviceId, serverId,
storePackageId, storePackageBackupPath, storeServerBackupPath);
}
}
public static int RestoreInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
int storePackageId, string storePackageBackupPath, string storeServerBackupPath)
{
try
{
// copy backup from remote or local server
string backupFileName = (storePackageId > 0)
? Path.GetFileName(storePackageBackupPath) : Path.GetFileName(storeServerBackupPath);
TaskManager.StartTask(taskId, "BACKUP", "RESTORE", backupFileName);
TaskManager.ItemId = SecurityContext.User.UserId;
// create temp folder
string tempFolder = GetTempBackupFolder();
string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
if (storePackageId > 0)
{
try
{
int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
storePackageBackupPath);
FileStream stream = new FileStream(backupFileNamePath, FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int offset = 0;
do
{
// read remote content
buffer = os.GetFileBinaryChunk(remoteBackupPath, offset, FILE_BUFFER_LENGTH);
// write remote content
stream.Write(buffer, 0, buffer.Length);
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
stream.Close();
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy source backup set");
return 0;
}
}
else
{
backupFileNamePath = storeServerBackupPath;
}
try
{
// unpack archive
FileUtils.UnzipFiles(backupFileNamePath, tempFolder);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't unzip backup set");
return 0;
}
// load backup catalog
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't find/open backup catalog file");
return 0;
}
// validate XML document
//if (!ValidateXmlDocument(doc))
//{
// TaskManager.WriteError("Corrupted or altered backup catalog file has been read");
// return 0;
//}
// get the list of items to restore
string condition = "";
if (userId > 0)
{
// get user spaces
List<PackageInfo> packages = new List<PackageInfo>();
packages.AddRange(PackageController.GetMyPackages(userId));
packages.AddRange(PackageController.GetPackages(userId));
List<string> parts = new List<string>();
foreach (PackageInfo package in packages)
parts.Add("@packageId = " + package.PackageId.ToString());
condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
}
else if (packageId > 0)
{
condition = "[@packageId = " + packageId + "]";
}
else if (serviceId > 0)
{
condition = "[@serviceId = " + serviceId + "]";
}
else if (serverId > 0)
{
// get server services
List<ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
List<string> parts = new List<string>();
foreach (ServiceInfo service in services)
parts.Add("@serviceId = " + service.ServiceId.ToString());
condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
}
XmlNodeList itemNodes = doc.SelectNodes("Backup/Items/Item" + condition);
TaskManager.IndicatorMaximum = itemNodes.Count;
TaskManager.IndicatorCurrent = 0;
// group items by item types
Dictionary<int, List<XmlNode>> groupedItems = new Dictionary<int, List<XmlNode>>();
// sort by groups
foreach (XmlNode itemNode in itemNodes)
{
int itemTypeId = Utils.ParseInt(itemNode.Attributes["itemTypeId"].Value, 0);
// add to group
if (!groupedItems.ContainsKey(itemTypeId))
groupedItems[itemTypeId] = new List<XmlNode>();
groupedItems[itemTypeId].Add(itemNode);
}
// restore grouped items
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemTypeInfo = PackageController.GetServiceItemType(itemTypeId);
if (!itemTypeInfo.Backupable)
continue;
Type itemType = Type.GetType(itemTypeInfo.TypeName);
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemTypeInfo.GroupId);
// instantiate controller
IBackupController controller = null;
try
{
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
// backup items
foreach (XmlNode itemNode in groupedItems[itemTypeId])
{
int itemId = Utils.ParseInt(itemNode.Attributes["itemId"].Value, 0);
string itemName = itemNode.Attributes["itemName"].Value;
int itemPackageId = Utils.ParseInt(itemNode.Attributes["packageId"].Value, 0);
int itemServiceId = Utils.ParseInt(itemNode.Attributes["serviceId"].Value, 0);
TaskManager.Write(String.Format("Restore {0} '{1}'",
itemTypeInfo.DisplayName, itemName));
try
{
int restoreResult = controller.RestoreItem(tempFolder, itemNode,
itemId, itemType, itemName, itemPackageId, itemServiceId, group);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't restore item");
}
TaskManager.IndicatorCurrent++;
}
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
// delete backup folder and all its contents
try
{
Directory.Delete(tempFolder, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't delete temporary backup folder");
return 0;
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
public static int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(item.TypeId);
if (!itemType.Backupable)
return -1;
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// create controller
IBackupController controller = null;
try
{
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
return BackupItem(tempFolder, writer, item, group, controller);
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
return -2;
}
private static int BackupItem(string tempFolder, XmlWriter writer,
ServiceProviderItem item, ResourceGroupInfo group, IBackupController controller)
{
writer.WriteStartElement("Item");
writer.WriteAttributeString("itemId", item.Id.ToString());
writer.WriteAttributeString("itemTypeId", item.TypeId.ToString());
writer.WriteAttributeString("itemName", item.Name);
writer.WriteAttributeString("packageId", item.PackageId.ToString());
writer.WriteAttributeString("serviceId", item.ServiceId.ToString());
try
{
return controller.BackupItem(tempFolder, writer, item, group);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
writer.WriteEndElement(); // Item
}
return 0;
}
public static int RestoreItem()
{
return 0;
}
public static void WriteFileElement(XmlWriter writer, string fileName, string filePath, long size)
{
writer.WriteStartElement("File");
writer.WriteAttributeString("name", fileName);
writer.WriteAttributeString("path", filePath);
writer.WriteAttributeString("size", size.ToString());
writer.WriteEndElement();
}
#region Utility Methods
public static bool FolderWriteAccessible(string path)
{
try
{
string tempFile = Path.Combine(path, "check");
StreamWriter writer = File.CreateText(tempFile);
writer.Close();
File.Delete(tempFile);
return true;
}
catch
{
return false;
}
}
public static bool RemoteServerFolderWriteAccessible(int packageId, string path)
{
try
{
// copy to space folder
int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteServerPathCheck = FilesController.GetFullPackagePath(packageId,
Path.Combine(path, "check.txt"));
//
os.CreateFile(remoteServerPathCheck);
os.AppendFileBinaryContent(remoteServerPathCheck, Encoding.UTF8.GetBytes(remoteServerPathCheck));
os.DeleteFile(remoteServerPathCheck);
}
//
return true;
}
catch
{
//
return false;
}
}
public static void SignXmlDocument(XmlDocument doc)
{
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = GetUserRSAKey();
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
}
public static bool ValidateXmlDocument(XmlDocument doc)
{
// Create a new SignedXml object and pass it
// the XML document class.
SignedXml signedXml = new SignedXml(doc);
// Find the "Signature" node and create a new
// XmlNodeList object.
XmlNodeList nodeList = doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// This example only supports one signature for
// the entire XML document. Throw an exception
// if more than one signature was found.
if (nodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(GetUserRSAKey());
}
public static RSA GetUserRSAKey()
{
int userId = SecurityContext.User.UserId;
if(SecurityContext.User.IsPeer)
userId = SecurityContext.User.OwnerId;
UserSettings settings = UserController.GetUserSettings(userId, RSA_SETTINGS_KEY);
string keyXml = settings[RSA_SETTINGS_KEY];
RSA rsa = RSA.Create();
if (String.IsNullOrEmpty(keyXml) || settings.UserId != userId)
{
// generate new key
keyXml = rsa.ToXmlString(true);
// store to settings
settings[RSA_SETTINGS_KEY] = keyXml;
settings.UserId = userId;
UserController.UpdateUserSettings(settings);
}
else
{
rsa.FromXmlString(keyXml);
}
return rsa;
}
private static string GetLoggedUsername()
{
string username = SecurityContext.User.Identity.Name;
UserInfo user = UserController.GetUser(SecurityContext.User.UserId);
if (user != null)
username = user.Username;
return username;
}
public static string GetTempBackupFolder()
{
string timeStamp = DateTime.Now.Ticks.ToString();
string tempFolder = Path.Combine(ConfigSettings.BackupsPath, GetLoggedUsername() + "_" + timeStamp);
// create folder
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
return tempFolder;
}
#endregion
}
}

View file

@ -1,50 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using WebsitePanel.Providers;
namespace WebsitePanel.EnterpriseServer
{
public interface IBackupController
{
int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group);
int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType,
string itemName, int packageId, int serviceId, ResourceGroupInfo group);
}
}

View file

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

View file

@ -1,60 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace WebsitePanel.EnterpriseServer
{
public class ImportAsyncWorker
{
public int threadUserId = -1;
public string taskId;
public int packageId;
public string[] items;
public void ImportAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Import));
t.Start();
}
public void Import()
{
// impersonate thread
if (threadUserId != -1)
SecurityContext.SetThreadPrincipal(threadUserId);
// perform import
ImportController.ImportItemsInternal(taskId, packageId, items);
}
}
}

View file

@ -1,311 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Web;
namespace WebsitePanel.EnterpriseServer
{
public class ImportController
{
public static List<ServiceProviderItemType> GetImportableItemTypes(int packageId)
{
// load all service item types
List<ServiceProviderItemType> itemTypes = PackageController.GetServiceItemTypes();
// load package context
PackageContext cntx = PackageController.GetPackageContext(packageId);
// build importable items list
List<ServiceProviderItemType> importableTypes = new List<ServiceProviderItemType>();
foreach (ServiceProviderItemType itemType in itemTypes)
{
if (!itemType.Importable)
continue;
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
if (cntx.Groups.ContainsKey(group.GroupName))
importableTypes.Add(itemType);
}
return importableTypes;
}
public static List<string> GetImportableItems(int packageId, int itemTypeId)
{
List<string> items = new List<string>();
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin | DemandAccount.NotDemo);
if (accountCheck < 0) return items;
// load item type
if (itemTypeId > 0)
{
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
DataTable dtServiceItems = PackageController.GetServiceItemsDataSet(serviceId).Tables[0];
DataTable dtPackageItems = PackageController.GetPackageItemsDataSet(packageId).Tables[0];
// instantiate controller
IImportController ctrl = null;
try
{
List<string> importableItems = null;
ctrl = Activator.CreateInstance(Type.GetType(group.GroupController)) as IImportController;
if (ctrl != null)
{
importableItems = ctrl.GetImportableItems(packageId, itemTypeId, Type.GetType(itemType.TypeName), group);
}
foreach (string importableItem in importableItems)
{
// filter items by service
bool serviceContains = false;
foreach (DataRow dr in dtServiceItems.Rows)
{
string serviceItemName = (string)dr["ItemName"];
int serviceItemTypeId = (int)dr["ItemTypeId"];
if (String.Compare(importableItem, serviceItemName, true) == 0
&& serviceItemTypeId == itemTypeId)
{
serviceContains = true;
break;
}
}
// filter items by package
bool packageContains = false;
foreach (DataRow dr in dtPackageItems.Rows)
{
string packageItemName = (string)dr["ItemName"];
int packageItemTypeId = (int)dr["ItemTypeId"];
if (String.Compare(importableItem, packageItemName, true) == 0
&& packageItemTypeId == itemTypeId)
{
packageContains = true;
break;
}
}
if (!serviceContains && !packageContains)
items.Add(importableItem);
}
}
catch { /* do nothing */ }
}
else
return GetImportableCustomItems(packageId, itemTypeId);
return items;
}
public static int ImportItems(bool async, string taskId, int packageId, string[] items)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin);
if (accountCheck < 0) return accountCheck;
if (async)
{
ImportAsyncWorker worker = new ImportAsyncWorker();
worker.threadUserId = SecurityContext.User.UserId;
worker.taskId = taskId;
worker.packageId = packageId;
worker.items = items;
// import
worker.ImportAsync();
return 0;
}
else
{
return ImportItemsInternal(taskId, packageId, items);
}
}
public static int ImportItemsInternal(string taskId, int packageId, string[] items)
{
PackageInfo package = PackageController.GetPackage(packageId);
TaskManager.StartTask(taskId, "IMPORT", "IMPORT", package.PackageName);
TaskManager.ItemId = packageId;
TaskManager.IndicatorMaximum = items.Length;
TaskManager.IndicatorCurrent = 0;
Dictionary<int, List<string>> groupedItems = new Dictionary<int, List<string>>();
List<string> customItems = new List<string>();
// sort by groups
foreach (string item in items)
{
string[] itemParts = item.Split('|');
if (!item.StartsWith("+"))
{
int itemTypeId = Utils.ParseInt(itemParts[0], 0);
string itemName = itemParts[1];
// add to group
if (!groupedItems.ContainsKey(itemTypeId))
groupedItems[itemTypeId] = new List<string>();
groupedItems[itemTypeId].Add(itemName);
}
else
{
switch (itemParts[0])
{
case ("+100"):
if (itemParts.Length > 2)
customItems.Add(item);
break;
}
}
}
// import each group
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// instantiate controller
IImportController ctrl = null;
try
{
ctrl = Activator.CreateInstance(Type.GetType(group.GroupController)) as IImportController;
if (ctrl != null)
{
foreach (string itemName in groupedItems[itemTypeId])
{
TaskManager.Write(String.Format("Import {0} '{1}'",
itemType.DisplayName, itemName));
try
{
// perform import
ctrl.ImportItem(packageId, itemTypeId,
Type.GetType(itemType.TypeName), group, itemName);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't import item");
}
TaskManager.IndicatorCurrent++;
}
}
}
catch { /* do nothing */ }
}
foreach (string s in customItems)
{
try
{
string[] sParts = s.Split('|');
switch (sParts[0])
{
case "+100":
TaskManager.Write(String.Format("Import {0}", sParts[4]));
int result = WebServerController.ImporHostHeader(int.Parse(sParts[2],0), int.Parse(sParts[3],0), int.Parse(sParts[5],0));
if (result < 0)
TaskManager.WriteError(String.Format("Failed to Import {0} ,error: {1}: ", sParts[4], result.ToString()));
break;
}
}
catch { /* do nothing */ }
TaskManager.IndicatorCurrent++;
}
TaskManager.IndicatorCurrent = items.Length;
TaskManager.CompleteTask();
return 0;
}
private static List<string> GetImportableCustomItems(int packageId, int itemTypeId)
{
List<string> items = new List<string>();
PackageInfo packageInfo = PackageController.GetPackage(packageId);
if (packageInfo == null) return items;
switch (itemTypeId)
{
case -100:
List<UserInfo> users = UserController.GetUsers(packageInfo.UserId, true);
foreach (UserInfo user in users)
{
List<PackageInfo> packages = PackageController.GetPackages(user.UserId);
foreach (PackageInfo package in packages)
{
List<WebSite> webSites = WebServerController.GetWebSites(package.PackageId, false);
foreach (WebSite webSite in webSites)
{
items.Add(user.Username+"|"+user.UserId.ToString()+"|"+package.PackageId.ToString()+"|"+webSite.SiteId+"|"+webSite.Id);
}
}
}
break;
}
return items;
}
}
}

View file

@ -1,201 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class ActivatePaidInvoicesTask : SchedulerTask
{
public override void DoWork()
{
//
PickupReceivedTransactions();
// activate paid services
ActivatePaidServices();
}
public void PickupReceivedTransactions()
{
TaskManager.Write("Start looking for transactions submitted");
//
List<HandlerResponse> transactions = ServiceHandlerController.GetServiceHandlersResponsesByReseller(SecurityContext.User.UserId);
//
if (transactions.Count > 0)
{
XmlDocument xmldoc = new XmlDocument();
XmlElement root = xmldoc.CreateElement("Result");
XmlElement succeedNode = xmldoc.CreateElement("Succeed");
XmlElement failedNode = xmldoc.CreateElement("Failed");
root.AppendChild(succeedNode);
root.AppendChild(failedNode);
//
List<HandlerResponse> succeedItems = new List<HandlerResponse>();
List<HandlerResponse> failedItems = new List<HandlerResponse>();
//
TaskManager.Write("Found {0} transactions pending", transactions.Count.ToString());
foreach (HandlerResponse transaction in transactions)
{
XmlElement responseNode = xmldoc.CreateElement("Response");
responseNode.SetAttribute("ID", Convert.ToString(transaction.ResponseId));
//
try
{
CheckoutDetails details = new CheckoutDetails();
//
string[] dataPairs = transaction.TextResponse.Split('&');
foreach (string dataPair in dataPairs)
{
string[] data = dataPair.Split('=');
if (data.Length >= 2)
details[data[0]] = data[1];
}
//
CheckoutResult result = PaymentGatewayController.CheckOut(transaction.ContractId, transaction.InvoiceId,
transaction.MethodName, details);
//
if (result.Succeed)
{
succeedNode.AppendChild(responseNode);
succeedItems.Add(transaction);
}
else
{
responseNode.SetAttribute("Error", result.StatusCode);
failedNode.AppendChild(responseNode);
//
transaction.ErrorMessage = result.StatusCode;
failedItems.Add(transaction);
}
}
catch (Exception ex)
{
//
if (!failedItems.Contains(transaction))
{
responseNode.SetAttribute("Error", ex.StackTrace);
failedNode.AppendChild(responseNode);
//
transaction.ErrorMessage = ex.StackTrace;
failedItems.Add(transaction);
}
//
TaskManager.WriteError(ex);
}
}
// peform transactions update
ServiceHandlerController.UpdateServiceHandlersResponses(SecurityContext.User.UserId, root.InnerXml);
}
else
{
TaskManager.Write("No transactions found");
}
TaskManager.Write("End looking for transactions submitted");
}
public void ActivatePaidServices()
{
// load paid invoice items
List<InvoiceItem> items = InvoiceController.GetInvoicesItemsToActivate(SecurityContext.User.UserId);
// TRACE
TaskManager.Write("Activate paid services");
TaskManager.WriteParameter("Items found", items.Count);
// iterate
foreach (InvoiceItem item in items)
{
try
{
TaskManager.Write("Activating service");
// activating
GenericSvcResult result = ActivateInvoiceItem(item);
// LOG ERROR
if (!result.Succeed)
{
TaskManager.WriteError(result.Error);
if (!String.IsNullOrEmpty(result.ErrorCode))
TaskManager.WriteParameter("Error code", result.ErrorCode);
TaskManager.WriteParameter("Result code", result.ResultCode);
// go to next item
continue;
}
//
TaskManager.Write("Activated");
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
public GenericSvcResult ActivateInvoiceItem(InvoiceItem item)
{
GenericSvcResult svc_result = ActivateService(item.ServiceId, true, true);
//
if (svc_result.Succeed)
InvoiceController.SetInvoiceItemProcessed(item.InvoiceId, item.ItemId);
//
return svc_result;
}
public GenericSvcResult ActivateService(int serviceId, bool sendEmail, bool logSvcUsage)
{
GenericSvcResult result = null;
// load svc type
ProductType svc_type = ServiceController.GetServiceItemType(serviceId);
//
if (svc_type == null)
{
result = new GenericSvcResult();
result.Succeed = true;
return result;
}
// instantiate svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svc_type.ProvisioningController));
// create context
ProvisioningContext context = controller.GetProvisioningContext(serviceId, sendEmail);
// activate svc
result = controller.ActivateService(context);
// check result
if (result.Succeed)
{
// log svc usage
if (logSvcUsage)
controller.LogServiceUsage(context);
}
//
return result;
}
}
}

View file

@ -1,106 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Database;
namespace WebsitePanel.EnterpriseServer
{
public class BackupDatabaseTask : SchedulerTask
{
public override void DoWork()
{
// Input parameters:
// - DATABASE_GROUP
// - DATABASE_NAME
// - BACKUP_FOLDER
// - BACKUP_NAME
// - ZIP_BACKUP
string databaseGroup = (string)TaskManager.TaskParameters["DATABASE_GROUP"];
string databaseName = (string)TaskManager.TaskParameters["DATABASE_NAME"];
string backupFolder = (string)TaskManager.TaskParameters["BACKUP_FOLDER"];
string backupName = (string)TaskManager.TaskParameters["BACKUP_NAME"];
string strZipBackup = (string)TaskManager.TaskParameters["ZIP_BACKUP"];
// check input parameters
if (String.IsNullOrEmpty(databaseName))
{
TaskManager.WriteWarning("Specify 'Database Name' task parameter.");
return;
}
bool zipBackup = (strZipBackup.ToLower() == "true");
if (String.IsNullOrEmpty(backupName))
{
backupName = databaseName + (zipBackup ? ".zip" : ".bak");
}
else
{
// check extension
string ext = Path.GetExtension(backupName);
if (zipBackup && String.Compare(ext, ".zip", true) != 0)
{
// change extension to .zip
backupName = Path.GetFileNameWithoutExtension(backupName) + ".zip";
}
}
// try to find database
SqlDatabase item = (SqlDatabase)PackageController.GetPackageItemByName(TaskManager.PackageId, databaseGroup,
databaseName, typeof(SqlDatabase));
if (item == null)
{
TaskManager.WriteError("Database with the specified name was not found in the current hosting space.");
return;
}
if (String.IsNullOrEmpty(backupFolder))
backupFolder = "\\";
// substitute parameters
DateTime d = DateTime.Now;
string date = d.ToString("yyyyMMdd");
string time = d.ToString("HHmm");
backupFolder = Utils.ReplaceStringVariable(backupFolder, "date", date);
backupFolder = Utils.ReplaceStringVariable(backupFolder, "time", time);
backupName = Utils.ReplaceStringVariable(backupName, "date", date);
backupName = Utils.ReplaceStringVariable(backupName, "time", time);
// backup database
DatabaseServerController.BackupSqlDatabase(item.Id, backupName, zipBackup, false, backupFolder);
}
}
}

View file

@ -1,83 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Represents scheduler task that performs hosting space backup.
/// </summary>
public class BackupTask : SchedulerTask
{
/// <summary>
/// Performs actual backup.
/// </summary>
public override void DoWork()
{
string backupFileName;
int storePackageId;
string storePackageFolder;
string storeServerFolder;
bool deleteTempBackup;
try
{
backupFileName = (string)TaskManager.TaskParameters["BACKUP_FILE_NAME"];
storePackageId = Convert.ToInt32(TaskManager.TaskParameters["STORE_PACKAGE_ID"]);
storePackageFolder = (string)TaskManager.TaskParameters["STORE_PACKAGE_FOLDER"];
storeServerFolder = (string)TaskManager.TaskParameters["STORE_SERVER_FOLDER"];
deleteTempBackup = Convert.ToBoolean(TaskManager.TaskParameters["DELETE_TEMP_BACKUP"]);
}
catch(Exception ex)
{
TaskManager.WriteError(ex, "Some parameters are absent or have incorrect value.");
return;
}
try
{
PackageInfo package = PackageController.GetPackage(TaskManager.PackageId);
// We do not take into account service id as long as scheduled tasks run against packages.
BackupController.Backup(false, "BackupTask", package.UserId, package.PackageId, 0, 0,
backupFileName, storePackageId, storePackageFolder, storeServerFolder, deleteTempBackup);
}
catch(Exception ex)
{
TaskManager.WriteError(ex, "Failed to do backup.");
}
}
}
}

View file

@ -1,57 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Exchange;
using WebsitePanel.Providers.HostedSolution;
namespace WebsitePanel.EnterpriseServer
{
public class CalculateExchangeDiskspaceTask : SchedulerTask
{
public override void DoWork()
{
CalculateDiskspace();
}
public void CalculateDiskspace()
{
// get all space organizations recursively
List<Organization> items = ExchangeServerController.GetExchangeOrganizations(TaskManager.PackageId, true);
foreach (Organization item in items)
{
ExchangeServerController.CalculateOrganizationDiskspaceInternal(item.Id);
}
}
}
}

View file

@ -1,189 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using WebsitePanel.Providers;
namespace WebsitePanel.EnterpriseServer
{
public class CalculatePackagesBandwidthTask : SchedulerTask
{
private readonly bool suspendOverused = false;
public override void DoWork()
{
// Input parameters:
// - SUSPEND_OVERUSED_PACKAGES
CalculateBandwidth();
}
public void CalculateBandwidth()
{
// get all owned packages
List<PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.PackageId, true);
TaskManager.Write("Packages to calculate: " + packages.Count.ToString());
foreach (PackageInfo package in packages)
{
// calculating package bandwidth
CalculatePackage(package.PackageId);
}
}
public void CalculatePackage(int packageId)
{
DateTime since = PackageController.GetPackageBandwidthUpdate(packageId);
DateTime nextUpdate = DateTime.Now;
try
{
// get all package items
List<ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
0, packageId, false, true, false, false);
// order items by service
Dictionary<int, List<ServiceProviderItem>> orderedItems =
PackageController.OrderServiceItemsByServices(items);
// calculate statistics for each service set
List<ServiceProviderItemBandwidth> itemsBandwidth = new List<ServiceProviderItemBandwidth>();
foreach (int serviceId in orderedItems.Keys)
{
ServiceProviderItemBandwidth[] serviceBandwidth = CalculateItems(serviceId,
orderedItems[serviceId], since);
if (serviceBandwidth != null)
itemsBandwidth.AddRange(serviceBandwidth);
}
// update info in the database
string xml = BuildDiskBandwidthStatisticsXml(itemsBandwidth.ToArray());
PackageController.UpdatePackageBandwidth(packageId, xml);
// if everything is OK
// update date
PackageController.UpdatePackageBandwidthUpdate(packageId, nextUpdate);
// suspend package if requested
if (suspendOverused)
{
// disk space
QuotaValueInfo dsQuota = PackageController.GetPackageQuota(packageId, Quotas.OS_BANDWIDTH);
if (dsQuota.QuotaExhausted)
PackageController.ChangePackageStatus(null, packageId, PackageStatus.Suspended, false);
}
}
catch (Exception ex)
{
// load package details
PackageInfo package = PackageController.GetPackage(packageId);
// load user details
UserInfo user = PackageController.GetPackageOwner(package.PackageId);
// log error
TaskManager.WriteError(String.Format("Error calculating bandwidth for '{0}' space of user '{1}': {2}",
package.PackageName, user.Username, ex.ToString()));
}
}
public ServiceProviderItemBandwidth[] CalculateItems(int serviceId, List<ServiceProviderItem> items,
DateTime since)
{
// convert items to SoapObjects
List<SoapServiceProviderItem> objItems = new List<SoapServiceProviderItem>();
foreach (ServiceProviderItem item in items)
objItems.Add(SoapServiceProviderItem.Wrap(item));
int attempt = 0;
int ATTEMPTS = 3;
while (attempt < ATTEMPTS)
{
// increment attempt
attempt++;
try
{
// send packet for calculation
// invoke service provider
//TaskManager.Write(String.Format("{0} - Invoke GetServiceItemsDiskSpace method ('{1}' items) - {2} attempt",
// DateTime.Now, objItems.Count, attempt));
ServiceProvider prov = new ServiceProvider();
ServiceProviderProxy.Init(prov, serviceId);
return prov.GetServiceItemsBandwidth(objItems.ToArray(), since);
}
catch (Exception ex)
{
TaskManager.WriteError(ex.ToString());
}
}
throw new Exception("The number of attemtps has been reached. The package calculation has been aborted.");
}
private string BuildDiskBandwidthStatisticsXml(ServiceProviderItemBandwidth[] itemsBandwidth)
{
StringBuilder sb = new StringBuilder();
sb.Append("<items>");
if (itemsBandwidth != null)
{
CultureInfo culture = CultureInfo.InvariantCulture;
if (itemsBandwidth != null)
{
foreach (ServiceProviderItemBandwidth item in itemsBandwidth)
{
if (item != null && item.Days != null)
{
foreach (DailyStatistics day in item.Days)
{
string dt = new DateTime(day.Year, day.Month, day.Day).ToString("MM/dd/yyyy", culture);
sb.Append("<item id=\"").Append(item.ItemId).Append("\"")
.Append(" date=\"").Append(dt).Append("\"")
.Append(" sent=\"").Append(day.BytesSent).Append("\"")
.Append(" received=\"").Append(day.BytesReceived).Append("\"")
.Append("></item>\n");
}
}
}
}
}
sb.Append("</items>");
return sb.ToString();
}
}
}

View file

@ -1,238 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.EnterpriseServer.Code.SharePoint;
using WebsitePanel.Providers;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.SharePoint;
namespace WebsitePanel.EnterpriseServer
{
public class CalculatePackagesDiskspaceTask : SchedulerTask
{
private readonly bool suspendOverused = false;
public override void DoWork()
{
// Input parameters:
// - SUSPEND_OVERUSED_PACKAGES
CalculateDiskspace();
}
public void CalculateDiskspace()
{
// get all owned packages
List<PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.PackageId, true);
TaskManager.Write("Packages to calculate: " + packages.Count.ToString());
foreach (PackageInfo package in packages)
{
// calculating package diskspace
CalculatePackage(package.PackageId);
}
}
public void CalculatePackage(int packageId)
{
try
{
// get all package items
List<ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
0, packageId, true, false, false, false);
//TaskManager.Write("Items: " + items.Count);
// order items by service
Dictionary<int, List<ServiceProviderItem>> orderedItems =
PackageController.OrderServiceItemsByServices(items);
// calculate statistics for each service set
List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
foreach (int serviceId in orderedItems.Keys)
{
ServiceProviderItemDiskSpace[] serviceDiskspace = CalculateItems(serviceId, orderedItems[serviceId]);
if (serviceDiskspace != null)
itemsDiskspace.AddRange(serviceDiskspace);
}
// update info in the database
string xml = BuildDiskSpaceStatisticsXml(itemsDiskspace.ToArray());
PackageController.UpdatePackageDiskSpace(packageId, xml);
//TaskManager.Write("XML: " + xml);
// suspend package if requested
if (suspendOverused)
{
// disk space
QuotaValueInfo dsQuota = PackageController.GetPackageQuota(packageId, Quotas.OS_DISKSPACE);
if (dsQuota.QuotaExhausted)
PackageController.ChangePackageStatus(null, packageId, PackageStatus.Suspended, false);
}
}
catch (Exception ex)
{
// load package details
PackageInfo package = PackageController.GetPackage(packageId);
// load user details
UserInfo user = PackageController.GetPackageOwner(package.PackageId);
// log error
TaskManager.WriteError(String.Format("Error calculating diskspace for '{0}' space of user '{1}': {2}",
package.PackageName, user.Username, ex.ToString()));
}
}
private static int GetExchangeServiceID(int packageId)
{
return PackageController.GetPackageServiceId(packageId, ResourceGroups.Exchange);
}
public ServiceProviderItemDiskSpace[] CalculateItems(int serviceId, List<ServiceProviderItem> items)
{
// convert items to SoapObjects
List<SoapServiceProviderItem> objItems = new List<SoapServiceProviderItem>();
//hack for organization... Refactoring!!!
List<ServiceProviderItemDiskSpace> organizationDiskSpaces = new List<ServiceProviderItemDiskSpace>();
foreach (ServiceProviderItem item in items)
{
long size = 0;
if (item is Organization)
{
Organization org = (Organization) item;
//Exchange DiskSpace
if (!string.IsNullOrEmpty(org.GlobalAddressList))
{
int exchangeServiceId = GetExchangeServiceID(org.PackageId);
ServiceProvider exchangeProvider = ExchangeServerController.GetExchangeServiceProvider(exchangeServiceId, item.ServiceId);
SoapServiceProviderItem soapOrg = SoapServiceProviderItem.Wrap(org);
ServiceProviderItemDiskSpace[] itemsDiskspace =
exchangeProvider.GetServiceItemsDiskSpace(new SoapServiceProviderItem[] {soapOrg});
if (itemsDiskspace != null && itemsDiskspace.Length > 0)
{
size += itemsDiskspace[0].DiskSpace;
}
}
// Crm DiskSpace
if (org.CrmOrganizationId != Guid.Empty)
{
//CalculateCrm DiskSpace
}
//SharePoint DiskSpace
int res;
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
if (cntx.Groups.ContainsKey(ResourceGroups.HostedSharePoint))
{
SharePointSiteDiskSpace[] sharePointSiteDiskSpaces =
HostedSharePointServerController.CalculateSharePointSitesDiskSpace(org.Id, out res);
if (res == 0)
{
foreach (SharePointSiteDiskSpace currecnt in sharePointSiteDiskSpaces)
{
size += currecnt.DiskSpace;
}
}
}
ServiceProviderItemDiskSpace tmp = new ServiceProviderItemDiskSpace();
tmp.ItemId = item.Id;
tmp.DiskSpace = size;
organizationDiskSpaces.Add(tmp);
}
else
objItems.Add(SoapServiceProviderItem.Wrap(item));
}
int attempt = 0;
int ATTEMPTS = 3;
while (attempt < ATTEMPTS)
{
// increment attempt
attempt++;
try
{
// send packet for calculation
// invoke service provider
//TaskManager.Write(String.Format("{0} - Invoke GetServiceItemsDiskSpace method ('{1}' items) - {2} attempt",
// DateTime.Now, objItems.Count, attempt));
ServiceProvider prov = new ServiceProvider();
ServiceProviderProxy.Init(prov, serviceId);
ServiceProviderItemDiskSpace[] itemsDiskSpace = prov.GetServiceItemsDiskSpace(objItems.ToArray());
if (itemsDiskSpace != null && itemsDiskSpace.Length > 0)
organizationDiskSpaces.AddRange(itemsDiskSpace);
return organizationDiskSpaces.ToArray();
}
catch (Exception ex)
{
TaskManager.WriteError(ex.ToString());
}
}
throw new Exception("The number of attemtps has been reached. The package calculation has been aborted.");
}
private string BuildDiskSpaceStatisticsXml(ServiceProviderItemDiskSpace[] itemsDiskspace)
{
StringBuilder sb = new StringBuilder();
sb.Append("<items>");
if (itemsDiskspace != null)
{
foreach (ServiceProviderItemDiskSpace item in itemsDiskspace)
{
sb.Append("<item id=\"").Append(item.ItemId).Append("\"")
.Append(" bytes=\"").Append(item.DiskSpace).Append("\"></item>\n");
}
}
sb.Append("</items>");
return sb.ToString();
}
}
}

View file

@ -1,105 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class CancelOverdueInvoicesTask : SchedulerTask
{
public override void DoWork()
{
// cancel overdue services
CancelOverdueServices();
}
public void CancelOverdueServices()
{
// load store settings
StoreSettings settings = StorehouseController.GetStoreSettings(SecurityContext.User.UserId,
StoreSettings.SYSTEM_SETTINGS);
//
int threshold = Convert.ToInt32(settings["SvcCancelThreshold"]);
//
TimeSpan ts = new TimeSpan(threshold, 0, 0, 0);
// calculate actual suspend date
DateTime dueDate = DateTime.Now.Subtract(ts);
// lookup for overdue invoices
List<InvoiceItem> items = InvoiceController.GetInvoicesItemsOverdue(SecurityContext.User.UserId, dueDate);
// TRACE
TaskManager.Write("Cancel overdue services");
TaskManager.WriteParameter("Items found", items.Count);
//
foreach (InvoiceItem item in items)
{
try
{
TaskManager.Write("Cancelling service");
// cancelling
GenericSvcResult result = CancelService(item.ServiceId, true);
// LOG ERROR
if (!result.Succeed)
{
TaskManager.WriteError(result.Error);
if (!String.IsNullOrEmpty(result.ErrorCode))
TaskManager.WriteParameter("Error code", result.ErrorCode);
TaskManager.WriteParameter("Result code", result.ResultCode);
// go to next item
continue;
}
//
TaskManager.Write("Cancelled");
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
public GenericSvcResult CancelService(int serviceId, bool sendEmail)
{
GenericSvcResult result = null;
// load svc type
ProductType svc_type = ServiceController.GetServiceItemType(serviceId);
// instantiate svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svc_type.ProvisioningController));
// create context
ProvisioningContext context = controller.GetProvisioningContext(serviceId, sendEmail);
// cancel svc
result = controller.CancelService(context);
//
return result;
}
}
}

View file

@ -1,233 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace WebsitePanel.EnterpriseServer
{
public class CheckWebSiteTask : SchedulerTask
{
private class WebSiteResponse
{
public int Status;
public string Text;
}
public override void DoWork()
{
// Input parameters:
// - URL
// - USERNAME
// - PASSWORD
// - RESPONSE_STATUS
// - RESPONSE_CONTAIN
// - RESPONSE_DOESNT_CONTAIN
// - MAIL_FROM
// - MAIL_TO
// - MAIL_SUBJECT
// - MAIL_BODY
// get input parameters
string url = (string)TaskManager.TaskParameters["URL"];
string username = (string)TaskManager.TaskParameters["USERNAME"];
string password = (string)TaskManager.TaskParameters["PASSWORD"];
string strResponseStatus = (string)TaskManager.TaskParameters["RESPONSE_STATUS"];
string responseContains = (string)TaskManager.TaskParameters["RESPONSE_CONTAIN"];
string responseNotContains = (string)TaskManager.TaskParameters["RESPONSE_DOESNT_CONTAIN"];
bool useResponseStatus = Convert.ToBoolean(TaskManager.TaskParameters["USE_RESPONSE_STATUS"]);
bool useResponseContains = Convert.ToBoolean(TaskManager.TaskParameters["USE_RESPONSE_CONTAIN"]);
bool useResponseDoesntContain = Convert.ToBoolean(TaskManager.TaskParameters["USE_RESPONSE_DOESNT_CONTAIN"]);
// check input parameters
if (String.IsNullOrEmpty(url))
{
TaskManager.WriteWarning("Specify 'Web Site URL' task parameter.");
return;
}
if ((String.IsNullOrEmpty(strResponseStatus) || !useResponseStatus)
&& (String.IsNullOrEmpty(responseContains) || !useResponseContains)
&& (String.IsNullOrEmpty(responseNotContains) || !useResponseDoesntContain))
{
TaskManager.WriteWarning("Specify one of 'Response Status', 'Response Contain' or 'Response Doesn't Contain' parameters.");
return;
}
int responseStatus = Utils.ParseInt(strResponseStatus, -1);
if (!String.IsNullOrEmpty(strResponseStatus) && responseStatus == -1)
{
TaskManager.WriteWarning("Specify correct response HTTP status, e.g. 404, 500, 503, etc.");
return;
}
// load web site
WebSiteResponse resp = GetWebDocument(url, username, password);
// check if there was a generic error
if (resp.Status == -1)
{
SendMailMessage(url, resp.Text, "");
}
bool sendMessage = false;
// check status
if (responseStatus != -1)
{
sendMessage |= ((resp.Status == responseStatus) && useResponseStatus);
}
// check "contains"
if (!String.IsNullOrEmpty(responseContains))
{
sendMessage |= ((resp.Text.ToLower().IndexOf(responseContains.ToLower()) != -1) && useResponseContains);
}
// check "not contains"
if (!String.IsNullOrEmpty(responseNotContains))
{
sendMessage |= ((resp.Text.ToLower().IndexOf(responseNotContains.ToLower()) == -1) && useResponseDoesntContain);
}
if (sendMessage)
SendMailMessage(url, "", resp.Text);
}
private void SendMailMessage(string url, string message, string content)
{
// input parameters
string mailFrom = (string)TaskManager.TaskParameters["MAIL_FROM"];
string mailTo = (string)TaskManager.TaskParameters["MAIL_TO"];
string mailSubject = (string)TaskManager.TaskParameters["MAIL_SUBJECT"];
string mailBody = (string)TaskManager.TaskParameters["MAIL_BODY"];
if (String.IsNullOrEmpty(mailTo))
{
TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty.");
}
else
{
if (String.IsNullOrEmpty(mailFrom))
mailFrom = "automatic@localhost";
if (!String.IsNullOrEmpty(mailSubject))
{
mailSubject = Utils.ReplaceStringVariable(mailSubject, "url", url);
}
if (!String.IsNullOrEmpty(mailBody))
{
mailBody = Utils.ReplaceStringVariable(mailBody, "url", url);
mailBody = Utils.ReplaceStringVariable(mailBody, "message", message);
mailBody = Utils.ReplaceStringVariable(mailBody, "content", content);
}
else
{
mailBody = message;
}
// send mail message
MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false);
}
}
private WebSiteResponse GetWebDocument(string url, string username, string password)
{
WebSiteResponse result = new WebSiteResponse();
HttpWebResponse resp = null;
StringBuilder sb = new StringBuilder();
Stream respStream = null;
try
{
WebRequest req = WebRequest.Create(url);
// set site credentials if required
if (!String.IsNullOrEmpty(username))
{
req.Credentials = new NetworkCredential(username, password);
}
resp = (HttpWebResponse)req.GetResponse();
respStream = resp.GetResponseStream();
string charSet = !String.IsNullOrEmpty(resp.CharacterSet) ? resp.CharacterSet : "utf-8";
Encoding encode = System.Text.Encoding.GetEncoding(charSet);
StreamReader sr = new StreamReader(respStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
sb.Append(str);
count = sr.Read(read, 0, 256);
}
result.Status = (int)resp.StatusCode;
result.Text = sb.ToString();
}
catch (ThreadAbortException)
{
}
catch (WebException ex)
{
result.Status = (int)((HttpWebResponse)ex.Response).StatusCode;
result.Text = ex.ToString();
TaskManager.WriteError(ex.ToString());
}
catch (Exception ex)
{
result.Status = -1;
result.Text = ex.ToString();
TaskManager.WriteError(ex.ToString());
}
finally
{
if (respStream != null)
{
respStream.Close();
}
if (resp != null)
{
resp.Close();
}
}
return result;
}
}
}

View file

@ -1,134 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Server;
namespace WebsitePanel.EnterpriseServer
{
public class FTPFilesTask : SchedulerTask
{
public override void DoWork()
{
// Input parameters:
// - FILE_PATH
// - FTP_SERVER
// - FTP_USERNAME
// - FTP_PASSWORD
// - FTP_FOLDER
// get input parameters
string filePath = (string)TaskManager.TaskParameters["FILE_PATH"];
string ftpServer = (string)TaskManager.TaskParameters["FTP_SERVER"];
string ftpUsername = (string)TaskManager.TaskParameters["FTP_USERNAME"];
string ftpPassword = (string)TaskManager.TaskParameters["FTP_PASSWORD"];
string ftpFolder = (string)TaskManager.TaskParameters["FTP_FOLDER"];
// check input parameters
if (String.IsNullOrEmpty(filePath))
{
TaskManager.WriteWarning("Specify 'File' task parameter");
return;
}
if (String.IsNullOrEmpty(ftpServer))
{
TaskManager.WriteWarning("Specify 'FTP Server' task parameter");
return;
}
// substitute parameters
DateTime d = DateTime.Now;
string date = d.ToString("yyyyMMdd");
string time = d.ToString("HHmm");
filePath = Utils.ReplaceStringVariable(filePath, "date", date);
filePath = Utils.ReplaceStringVariable(filePath, "time", time);
// build FTP command file
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
// FTP server
writer.WriteLine("open " + ftpServer);
// check if anonymous mode
if (String.IsNullOrEmpty(ftpUsername))
{
ftpUsername = "anonymous";
ftpPassword = "anonymous@email.com";
}
// FTP username/password
writer.WriteLine(ftpUsername);
writer.WriteLine(ftpPassword);
// check if we need to change remote folder
if (!String.IsNullOrEmpty(ftpFolder))
{
writer.WriteLine("cd " + ftpFolder.Replace("\\", "/"));
}
// file to send
writer.WriteLine("binary");
writer.WriteLine("put " + FilesController.GetFullPackagePath(TaskManager.PackageId, filePath));
// bye
writer.WriteLine("bye");
string cmdBatch = sb.ToString();
// create temp file in user space
string cmdPath = Utils.GetRandomString(10) + ".txt";
string fullCmdPath = FilesController.GetFullPackagePath(TaskManager.PackageId, cmdPath);
// upload batch
FilesController.UpdateFileBinaryContent(TaskManager.PackageId, cmdPath, Encoding.UTF8.GetBytes(cmdBatch));
// execute system command
// load OS service
int serviceId = PackageController.GetPackageServiceId(TaskManager.PackageId, ResourceGroups.Os);
// load service
ServiceInfo service = ServerController.GetServiceInfo(serviceId);
if (service == null)
return;
WindowsServer winServer = new WindowsServer();
ServiceProviderProxy.ServerInit(winServer, service.ServerId);
TaskManager.Write(winServer.ExecuteSystemCommand("ftp.exe", "-s:" + fullCmdPath));
// delete batch file
FilesController.DeleteFiles(TaskManager.PackageId, new string[] { cmdPath });
}
}
}

View file

@ -1,103 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class GenerateInvoicesTask : SchedulerTask
{
public override void DoWork()
{
// invoice active services
InvoiceActiveServices();
}
public void InvoiceActiveServices()
{
DateTime dateTimeNow = DateTime.Now;
// load store settings
StoreSettings settings = StorehouseController.GetStoreSettings(SecurityContext.User.UserId,
StoreSettings.SYSTEM_SETTINGS);
//
int threshold = Convert.ToInt32(settings["SvcInvoiceThreshold"]);
// get expiring services today
List<Service> services = ServiceController.GetServicesToInvoice(SecurityContext.User.UserId,
dateTimeNow, threshold);
// group services by users
Dictionary<string, List<int>> usersServices = new Dictionary<string, List<int>>();
// iterate
foreach (Service service in services)
{
if (!usersServices.ContainsKey(service.ContractId))
usersServices.Add(service.ContractId, new List<int>());
usersServices[service.ContractId].Add(service.ServiceId);
}
// generate invoice per contract
foreach (string contractId in usersServices.Keys)
{
try
{
TaskManager.Write("Creating invoice");
// TRACE
Contract contract = ContractSystem.ContractController.GetContract(contractId);
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
TaskManager.WriteParameter("ContractID", contractId);
TaskManager.WriteParameter("Username", account[ContractAccount.USERNAME]);
//
List<int> userSvcs = usersServices[contractId];
// build invoice items
List<InvoiceItem> invoiceLines = InvoiceController.CalculateInvoiceLinesForServices(userSvcs);
//
int resultCode = InvoiceController.AddInvoice(contractId, invoiceLines, null);
//
if (resultCode < 1)
{
TaskManager.WriteParameter("ResultCode", resultCode);
continue;
}
//
if (ServiceController.SetUsageRecordsClosed(userSvcs.ToArray()) != 0)
TaskManager.WriteWarning("Unable to close usage records automatically");
// TRACE
TaskManager.WriteParameter("InvoiceID", resultCode);
TaskManager.Write("Succeed");
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
}
}

View file

@ -1,123 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using WebsitePanel.EnterpriseServer.Code.HostedSolution;
using WebsitePanel.Providers.HostedSolution;
namespace WebsitePanel.EnterpriseServer
{
public class HostedSolutionReportTask : SchedulerTask
{
private static readonly string EXCHANGE_REPORT = "EXCHANGE_REPORT";
private static readonly string ORGANIZATION_REPORT = "ORGANIZATION_REPORT";
private static readonly string SHAREPOINT_REPORT = "SHAREPOINT_REPORT";
private static readonly string LYNC_REPORT = "LYNC_REPORT";
private static readonly string CRM_REPORT = "CRM_REPORT";
private static readonly string EMAIL = "EMAIL";
public override void DoWork()
{
try
{
bool isExchange = Utils.ParseBool(TaskManager.TaskParameters[EXCHANGE_REPORT], false);
bool isSharePoint = Utils.ParseBool(TaskManager.TaskParameters[SHAREPOINT_REPORT], false);
bool isLync = Utils.ParseBool(TaskManager.TaskParameters[LYNC_REPORT], false);
bool isCRM = Utils.ParseBool(TaskManager.TaskParameters[CRM_REPORT], false);
bool isOrganization = Utils.ParseBool(TaskManager.TaskParameters[ORGANIZATION_REPORT], false);
string email = TaskManager.TaskParameters[EMAIL].ToString();
UserInfo user = PackageController.GetPackageOwner(TaskManager.PackageId);
EnterpriseSolutionStatisticsReport report =
ReportController.GetEnterpriseSolutionStatisticsReport(user.UserId, isExchange, isSharePoint, isCRM,
isOrganization, isLync);
SendMessage(user, email, isExchange && report.ExchangeReport != null ? report.ExchangeReport.ToCSV() : string.Empty,
isSharePoint && report.SharePointReport != null ? report.SharePointReport.ToCSV() : string.Empty,
isCRM && report.CRMReport != null ? report.CRMReport.ToCSV() : string.Empty,
isOrganization && report.OrganizationReport != null ? report.OrganizationReport.ToCSV() : string.Empty,
isLync && report.LyncReport != null ? report.LyncReport.ToCSV() : string.Empty);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
}
}
private static void PrepareAttament(string name, string csv, List<Attachment> attacments)
{
if (!string.IsNullOrEmpty(csv))
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] buffer = encoding.GetBytes(csv);
MemoryStream stream = new MemoryStream(buffer);
Attachment attachment = new Attachment(stream, name, MediaTypeNames.Text.Plain);
attacments.Add(attachment);
}
}
private void SendMessage(UserInfo user,string email, string exchange_csv, string sharepoint_csv, string crm_csv, string organization_csv, string lync_csv)
{
List<Attachment> attacments = new List<Attachment>();
PrepareAttament("exchange.csv", exchange_csv, attacments);
PrepareAttament("sharepoint.csv", sharepoint_csv, attacments);
PrepareAttament("lync.csv", lync_csv, attacments);
PrepareAttament("crm.csv", crm_csv, attacments);
PrepareAttament("organization.csv", organization_csv, attacments);
// get letter settings
UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.HOSTED_SOLUTION_REPORT);
string from = settings["From"];
string cc = settings["CC"];
string subject = settings["Subject"];
string body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
bool isHtml = user.HtmlMail;
MailPriority priority = MailPriority.Normal;
MailHelper.SendMessage(from, email, cc, subject, body, priority, isHtml, attacments.ToArray());
}
}
}

View file

@ -1,267 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace WebsitePanel.EnterpriseServer
{
public class NotifyOverusedDatabasesTask : SchedulerTask
{
public const string DISKSPACE_FORMAT_STRING = "{0} - {1}Mb ({2}%)";
public const string ALLOC_FORMAT_STRING = "{0} - {1}Mb";
public override void DoWork()
{
// Input parameters:
// - DISKSPACE_OVERUSED
// - BANDWIDTH_OVERUSED
// get the list of all packages
List<PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.PackageId, false);
TaskManager.Write("Packages to verify: " + packages.Count.ToString());
bool checkMSSQL = (String.Compare((string)TaskManager.TaskParameters["MSSQL_OVERUSED"], "true", true) == 0);
bool checkMySQL = (String.Compare((string)TaskManager.TaskParameters["MYSQL_OVERUSED"], "true", true) == 0);
bool sendWarningEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_WARNING_EMAIL"]);
bool sendOverusedEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_OVERUSED_EMAIL"]);
int warningUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["WARNING_USAGE_THRESHOLD"]);
int overusedUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["OVERUSED_USAGE_THRESHOLD"]);
string warningMailFrom = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_FROM"]);
string warningMailBcc = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BCC"]);
string warningMailSubject = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_SUBJECT"]);
string warningMailBody = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BODY"]);
string overusedMailFrom = Convert.ToString(TaskManager.TaskParameters["OVERUSED_MAIL_FROM"]);
string overusedMailBcc = Convert.ToString(TaskManager.TaskParameters["OVERUSED_MAIL_BCC"]);
string overusedMailSubject = Convert.ToString(TaskManager.TaskParameters["OVERUSED_MAIL_SUBJECT"]);
string overusedMailBody = Convert.ToString(TaskManager.TaskParameters["OVERUSED_MAIL_BODY"]);
int overusedPackages = 0;
foreach (PackageInfo package in packages)
{
UserInfo userInfo = UserController.GetUser(package.UserId);
List<DatabaseQuota> quotaMSSQL = new List<DatabaseQuota>();
List<DatabaseQuota> quotaMYSQL = new List<DatabaseQuota>();
if (checkMSSQL || checkMySQL)
{
QuotaValueInfo dsQuota = null;
DataSet Diskspace = PackageController.GetPackageDiskspace(package.PackageId);
foreach (DataRow spaceRow in Diskspace.Tables[0].Rows)
{
string groupName = spaceRow["GroupName"].ToString();
if (checkMSSQL && groupName.ToUpper().Contains("MSSQL"))
{
dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize");
if (dsQuota.QuotaAllocatedValue > 0)
{
int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue;
quotaMSSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MSSQL","SQL Server "),
Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue,
databaseSpaceUsage < warningUsageThreshold,
databaseSpaceUsage < overusedUsageThreshold));
}
}
if (checkMySQL && groupName.ToUpper().Contains("MYSQL"))
{
dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize");
if (dsQuota.QuotaAllocatedValue > 0)
{
int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue;
quotaMYSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MYSQL", "MySQL "),
Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue,
databaseSpaceUsage < warningUsageThreshold,
databaseSpaceUsage < overusedUsageThreshold));
}
}
}
string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email);
bool notifyOverusedByMail = false;
bool notifyWarningByMail = false;
List<string> formatItems = new List<string>();
List<string> formatWarningThreshold = new List<string>();
List<string> formatOverusedThreshold = new List<string>();
// add Microsoft SQL usage if enabled
if (checkMSSQL)
{
foreach (DatabaseQuota q in quotaMSSQL)
{
if (!q.BelowWarningThreshold || !q.BelowUsageThreshold)
{
formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, q.SpaceUsed * 100 / q.SpaceAllocated));
}
if (!q.BelowWarningThreshold)
{
formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
notifyWarningByMail = true;
}
if (!q.BelowUsageThreshold)
{
formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
notifyOverusedByMail = true;
}
}
}
// add MySQL usage if enabled
if (checkMySQL)
{
foreach (DatabaseQuota q in quotaMYSQL)
{
if (!q.BelowWarningThreshold || !q.BelowUsageThreshold)
{
formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, (q.SpaceUsed * 100) / q.SpaceAllocated));
}
if (!q.BelowWarningThreshold)
{
formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
notifyWarningByMail = true;
}
if (!q.BelowUsageThreshold)
{
formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
notifyOverusedByMail = true;
}
}
}
// build usage strings
string usage = String.Join("\n", formatItems.ToArray());
string usageWarning = String.Join("\n", formatWarningThreshold.ToArray());
string usageOverused = String.Join("\n", formatOverusedThreshold.ToArray());
string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, usageWarning, usage, package.PackageName, userName);
string warningMailBodyProcessed = ReplaceVariables(warningMailBody, usageWarning, usage, package.PackageName, userName);
string overusedMailSubjectProcessed = ReplaceVariables(overusedMailSubject, usageOverused, usage, package.PackageName, userName);
string overusedMailBodyProcessed = ReplaceVariables(overusedMailBody, usageOverused, usage, package.PackageName, userName);
// Send email notifications
if (sendWarningEmail && notifyWarningByMail)
{
// Send warning email.
this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false);
}
if (sendOverusedEmail && notifyOverusedByMail)
{
// Send overused email.
this.SendEmail(overusedMailFrom, userInfo.Email, overusedMailBcc, overusedMailSubjectProcessed, overusedMailBodyProcessed, false);
}
if (notifyOverusedByMail)
{
overusedPackages++;
}
}
}
// log results
TaskManager.Write("Total packages overused: " + overusedPackages.ToString());
}
private string ReplaceVariables(string content, string threshold, string usage, string spaceName, string customerName)
{
if (!String.IsNullOrEmpty(content))
{
content = Utils.ReplaceStringVariable(content, "threshold", threshold);
content = Utils.ReplaceStringVariable(content, "date", DateTime.Now.ToString());
content = Utils.ReplaceStringVariable(content, "usage", usage);
content = Utils.ReplaceStringVariable(content, "space", spaceName);
content = Utils.ReplaceStringVariable(content, "customer", customerName);
}
return content;
}
private void SendEmail(string from, string to, string bcc, string subject, string body, bool isHtml)
{
// check input parameters
if (String.IsNullOrEmpty(from))
{
TaskManager.WriteWarning("Specify 'Mail From' task parameter");
return;
}
if (String.IsNullOrEmpty(to))
{
TaskManager.WriteWarning("Specify 'Mail To' task parameter");
return;
}
// send mail message
MailHelper.SendMessage(from, to, bcc, subject, body, isHtml);
}
}
internal class DatabaseQuota
{
private string providerName = string.Empty;
private int spaceUsed = 0;
private int spaceAllocated = 0;
private bool belowWarningThreshold = false;
private bool belowUsageThreshold = false;
public DatabaseQuota(string ProviderName, int SpaceUsed, int SpaceAllocated, bool BelowWarningThreshold, bool BelowUsageThreshold)
{
providerName = ProviderName;
spaceUsed = SpaceUsed;
spaceAllocated = SpaceAllocated;
belowWarningThreshold = BelowWarningThreshold;
belowUsageThreshold = BelowUsageThreshold;
}
public string ProviderName
{
get { return providerName; }
}
public int SpaceUsed
{
get { return spaceUsed; }
}
public int SpaceAllocated
{
get { return spaceAllocated; }
}
public bool BelowWarningThreshold
{
get { return belowWarningThreshold; }
}
public bool BelowUsageThreshold
{
get { return belowUsageThreshold; }
}
}
}

View file

@ -1,87 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class RunPaymentQueueTask : SchedulerTask
{
public override void DoWork()
{
// run payment queue
RunPaymentQueue();
}
public void RunPaymentQueue()
{
int resellerId = SecurityContext.User.UserId;
// 1. load unpaid invoices
List<Invoice> invoices = InvoiceController.GetUnpaidInvoices(resellerId);
// TRACE
TaskManager.Write("Running payment queue");
TaskManager.WriteParameter("Items found", invoices.Count);
// 2. load payment profile for each customer
foreach (Invoice invoice in invoices)
{
try
{
// load payment profile
CheckoutDetails details = StorehouseController.GetPaymentProfileInternally(invoice.ContractId);
//
if (details != null)
{
// TRACE
TaskManager.Write("Trying to submit payment");
TaskManager.WriteParameter("InvoiceID", invoice.InvoiceId);
// 3. submit payment for each invoice if profile exists
CheckoutResult result = PaymentGatewayController.CheckOut(invoice.ContractId,
invoice.InvoiceId, PaymentMethod.CREDIT_CARD, details);
// ERROR
if (!result.Succeed)
{
TaskManager.WriteError("Payment failed");
TaskManager.WriteParameter("Result code", result.StatusCode);
continue;
}
// OK
TaskManager.Write("Payment OK");
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Payment failed");
}
}
}
}
}

View file

@ -1,80 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Server;
namespace WebsitePanel.EnterpriseServer
{
public class RunSystemCommandTask : SchedulerTask
{
public override void DoWork()
{
// Input parameters:
// - SERVER_NAME
// - EXECUTABLE_PATH
// get input parameters
string serverName = (string)TaskManager.TaskParameters["SERVER_NAME"];
string execPath = (string)TaskManager.TaskParameters["EXECUTABLE_PATH"];
string execParams = (string)TaskManager.TaskParameters["EXECUTABLE_PARAMS"];
if (execParams == null)
execParams = "";
// check input parameters
if (String.IsNullOrEmpty(serverName))
{
TaskManager.WriteWarning("Specify 'Server Name' task parameter");
return;
}
if (String.IsNullOrEmpty(execPath))
{
TaskManager.WriteWarning("Specify 'Executable Path' task parameter");
return;
}
// find server by name
ServerInfo server = ServerController.GetServerByName(serverName);
if (server == null)
{
TaskManager.WriteWarning(String.Format("Server with the name '{0}' was not found", serverName));
return;
}
// execute system command
WindowsServer winServer = new WindowsServer();
ServiceProviderProxy.ServerInit(winServer, server.ServerId);
TaskManager.Write(winServer.ExecuteSystemCommand(execPath, execParams));
}
}
}

View file

@ -1,74 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class SendMailNotificationTask : SchedulerTask
{
public override void DoWork()
{
// Input parameters:
// - MAIL_FROM
// - MAIL_TO
// - MAIL_SUBJECT
// - MAIL_BODY
// get input parameters
string mailFrom = (string)TaskManager.TaskParameters["MAIL_FROM"];
string mailTo = (string)TaskManager.TaskParameters["MAIL_TO"];
string mailSubject = (string)TaskManager.TaskParameters["MAIL_SUBJECT"];
string mailBody = (string)TaskManager.TaskParameters["MAIL_BODY"];
// check input parameters
if (String.IsNullOrEmpty(mailFrom))
{
TaskManager.WriteWarning("Specify 'Mail From' task parameter");
return;
}
if (String.IsNullOrEmpty(mailTo))
{
TaskManager.WriteWarning("Specify 'Mail To' task parameter");
return;
}
if (String.IsNullOrEmpty(mailSubject))
{
TaskManager.WriteWarning("Specify 'Mail Subject' task parameter");
return;
}
// send mail message
MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false);
}
}
}

View file

@ -1,96 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class SuspendOverdueInvoicesTask : SchedulerTask
{
public override void DoWork()
{
// suspend overdue services
SuspendOverdueServices();
}
public GenericSvcResult SuspendService(int serviceId, bool sendEmail)
{
GenericSvcResult result = null;
// load svc type
ProductType svc_type = ServiceController.GetServiceItemType(serviceId);
// instantiate svc controller
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
Type.GetType(svc_type.ProvisioningController));
// create context
ProvisioningContext context = controller.GetProvisioningContext(serviceId, sendEmail);
// suspend svc
result = controller.SuspendService(context);
//
return result;
}
public void SuspendOverdueServices()
{
// lookup for today's overdue invoices
List<InvoiceItem> items = InvoiceController.GetInvoicesItemsOverdue(SecurityContext.User.UserId, DateTime.Now);
// TRACE
TaskManager.Write("Suspend overdue services");
TaskManager.WriteParameter("Items found", items.Count);
//
foreach (InvoiceItem item in items)
{
try
{
TaskManager.Write("Suspending service");
// suspending
GenericSvcResult result = SuspendService(item.ServiceId, true);
// LOG ERROR
if (!result.Succeed)
{
TaskManager.WriteError(result.Error);
if (!String.IsNullOrEmpty(result.ErrorCode))
TaskManager.WriteParameter("Error code", result.ErrorCode);
TaskManager.WriteParameter("Result code", result.ResultCode);
// go to next item
continue;
}
//
TaskManager.Write("Suspended");
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
}
}

View file

@ -1,211 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class SuspendOverusedPackagesTask : SchedulerTask
{
public const string DISKSPACE_FORMAT_STRING = "disk space usage - {0}%";
public const string BANDWIDTH_FORMAT_STRING = "bandwidth usage - {0}%";
public override void DoWork()
{
// Input parameters:
// - DISKSPACE_OVERUSED
// - BANDWIDTH_OVERUSED
// get the list of all packages
List<PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.PackageId, false);
TaskManager.Write("Packages to verify: " + packages.Count.ToString());
bool checkDiskspace = (String.Compare((string)TaskManager.TaskParameters["DISKSPACE_OVERUSED"], "true", true) == 0);
bool checkBandwidth = (String.Compare((string)TaskManager.TaskParameters["BANDWIDTH_OVERUSED"], "true", true) == 0);
bool suspendOverused = Convert.ToBoolean(TaskManager.TaskParameters["SUSPEND_OVERUSED"]);
bool sendWarningEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_WARNING_EMAIL"]);
bool sendSuspensionEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_SUSPENSION_EMAIL"]);
int warningUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["WARNING_USAGE_THRESHOLD"]);
int suspensionUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["SUSPENSION_USAGE_THRESHOLD"]);
string warningMailFrom = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_FROM"]);
string warningMailBcc = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BCC"]);
string warningMailSubject = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_SUBJECT"]);
string warningMailBody = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BODY"]);
string suspensionMailFrom = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_FROM"]);
string suspensionMailBcc = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_BCC"]);
string suspensionMailSubject = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_SUBJECT"]);
string suspensionMailBody = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_BODY"]);
int suspendedPackages = 0;
foreach (PackageInfo package in packages)
{
bool isBandwidthBelowWarningThreshold = true;
bool isBandwidthBelowSuspensionThreshold = true;
bool isDiskSpaceBelowWarningThreshold = true;
bool isDiskSpaceBelowSuspensionThreshold = true;
UserInfo userInfo = UserController.GetUser(package.UserId);
int diskSpaceUsage = 0;
int bandwidthUsage = 0;
// disk space
if (checkDiskspace)
{
QuotaValueInfo dsQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_DISKSPACE);
if (dsQuota.QuotaAllocatedValue > 0)
{
diskSpaceUsage = (dsQuota.QuotaUsedValue*100/dsQuota.QuotaAllocatedValue);
isDiskSpaceBelowWarningThreshold = diskSpaceUsage < warningUsageThreshold;
isDiskSpaceBelowSuspensionThreshold = diskSpaceUsage < suspensionUsageThreshold;
}
}
// bandwidth
if (checkBandwidth)
{
QuotaValueInfo bwQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_BANDWIDTH);
if (bwQuota.QuotaAllocatedValue > 0)
{
bandwidthUsage = (bwQuota.QuotaUsedValue*100/bwQuota.QuotaAllocatedValue);
isBandwidthBelowWarningThreshold = bandwidthUsage < warningUsageThreshold;
isBandwidthBelowSuspensionThreshold = bandwidthUsage < suspensionUsageThreshold;
}
}
string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email);
//
List<string> formatItems = new List<string>();
// add diskspace usage if enabled
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, diskSpaceUsage));
// add bandwidth usage if enabled
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, bandwidthUsage));
// build usage string
string usage = String.Join(", ", formatItems.ToArray());
// cleanup items
formatItems.Clear();
// add diskspace warning max usage
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, warningUsageThreshold));
// add bandwidth warning max usage
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, warningUsageThreshold));
// build warning max usage string
string warningMaxUsage = String.Join(", ", formatItems.ToArray());
// cleanup items
formatItems.Clear();
// add diskspace suspension max usage
if (checkDiskspace) formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, suspensionUsageThreshold));
// add bandwidth suspension max usage
if (checkBandwidth) formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, suspensionUsageThreshold));
// build suspension max usage string
string suspensionMaxUsage = String.Join(", ", formatItems.ToArray());
string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, warningMaxUsage, usage, package.PackageName, userName);
string warningMailBodyProcessed = ReplaceVariables(warningMailBody, warningMaxUsage, usage, package.PackageName, userName);
string suspensionMailSubjectProcessed = ReplaceVariables(suspensionMailSubject, suspensionMaxUsage, usage, package.PackageName, userName);
string suspensionMailBodyProcessed = ReplaceVariables(suspensionMailBody, suspensionMaxUsage, usage, package.PackageName, userName);
// Send email notifications
if (sendWarningEmail && (!isDiskSpaceBelowWarningThreshold || !isBandwidthBelowWarningThreshold))
{
// Send warning email.
this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false);
}
if (sendSuspensionEmail && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
{
// Send suspension email.
this.SendEmail(suspensionMailFrom, userInfo.Email, suspensionMailBcc, suspensionMailSubjectProcessed, suspensionMailBodyProcessed, false);
}
// suspend package if required
if (suspendOverused && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
{
suspendedPackages++;
// load user details
UserInfo user = PackageController.GetPackageOwner(package.PackageId);
TaskManager.Write(String.Format("Suspend space '{0}' of user '{1}'",
package.PackageName, user.Username));
try
{
PackageController.ChangePackageStatus(null, package.PackageId, PackageStatus.Suspended, false);
}
catch (Exception ex)
{
TaskManager.WriteError("Error while changing space status: " + ex.ToString());
}
}
}
// log results
TaskManager.Write("Total packages suspended: " + suspendedPackages.ToString());
}
private string ReplaceVariables(string content, string threshold, string usage, string spaceName, string customerName)
{
if (!String.IsNullOrEmpty(content))
{
content = Utils.ReplaceStringVariable(content, "threshold", threshold);
content = Utils.ReplaceStringVariable(content, "date", DateTime.Now.ToString());
content = Utils.ReplaceStringVariable(content, "usage", usage);
content = Utils.ReplaceStringVariable(content, "space", spaceName);
content = Utils.ReplaceStringVariable(content, "customer", customerName);
}
return content;
}
private void SendEmail(string from, string to, string bcc, string subject, string body, bool isHtml)
{
// check input parameters
if (String.IsNullOrEmpty(from))
{
TaskManager.WriteWarning("Specify 'Mail From' task parameter");
return;
}
if (String.IsNullOrEmpty(to))
{
TaskManager.WriteWarning("Specify 'Mail To' task parameter");
return;
}
// send mail message
MailHelper.SendMessage(from, to, bcc, subject, body, isHtml);
}
}
}

View file

@ -1,74 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class ZipFilesTask : SchedulerTask
{
public override void DoWork()
{
// Input parameters:
// - FOLDER
// - ZIP_FILE
// get input parameters
string filesList = (string)TaskManager.TaskParameters["FOLDER"];
string zipFile = (string)TaskManager.TaskParameters["ZIP_FILE"];
// check input parameters
if (String.IsNullOrEmpty(filesList))
{
TaskManager.WriteWarning("Specify 'Files List' task parameter");
return;
}
if (String.IsNullOrEmpty(zipFile))
{
TaskManager.WriteWarning("Specify 'Zip File' task parameter");
return;
}
// substitute parameters
DateTime d = DateTime.Now;
string date = d.ToString("yyyyMMdd");
string time = d.ToString("HHmm");
filesList = Utils.ReplaceStringVariable(filesList, "date", date);
filesList = Utils.ReplaceStringVariable(filesList, "time", time);
zipFile = Utils.ReplaceStringVariable(zipFile, "date", date);
zipFile = Utils.ReplaceStringVariable(zipFile, "time", time);
// zip files and folders
FilesController.ZipFiles(TaskManager.PackageId, new string[] { filesList }, zipFile);
}
}
}

View file

@ -1,186 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace WebsitePanel.EnterpriseServer
{
public delegate void ScheduleFinished(SchedulerJob schedule);
public sealed class Scheduler
{
public static SchedulerJob nextSchedule = null;
// main timer and put it to sleep
static Timer scheduleTimer = new Timer(new TimerCallback(RunNextSchedule),
null,
Timeout.Infinite,
Timeout.Infinite);
public static void Start()
{
// schedule tasks
ScheduleTasks();
}
public static bool IsScheduleActive(int scheduleId)
{
Dictionary<int, BackgroundTask> scheduledTasks = TaskManager.GetScheduledTasks();
return scheduledTasks.ContainsKey(scheduleId);
}
public static void StartSchedule(SchedulerJob schedule)
{
Dictionary<int, BackgroundTask> scheduledTasks = TaskManager.GetScheduledTasks();
if (scheduledTasks.ContainsKey(schedule.ScheduleInfo.ScheduleId))
return;
// run schedule
RunSchedule(schedule, false);
}
public static void StopSchedule(SchedulerJob schedule)
{
Dictionary<int, BackgroundTask> scheduledTasks = TaskManager.GetScheduledTasks();
if (!scheduledTasks.ContainsKey(schedule.ScheduleInfo.ScheduleId))
return;
BackgroundTask activeTask = scheduledTasks[schedule.ScheduleInfo.ScheduleId];
TaskManager.StopTask(activeTask.TaskId);
}
public static void ScheduleTasks()
{
nextSchedule = SchedulerController.GetNextSchedule();
// set timer
if (nextSchedule != null)
{
if (nextSchedule.ScheduleInfo.NextRun <= DateTime.Now)
{
// this will put the timer to sleep
scheduleTimer.Change(Timeout.Infinite, Timeout.Infinite);
System.Threading.Thread.Sleep(1000);
// run immediately
RunNextSchedule(null);
}
else
{
// set timer
TimeSpan ts = nextSchedule.ScheduleInfo.NextRun.Subtract(DateTime.Now);
if (ts < TimeSpan.Zero)
ts = TimeSpan.Zero; // cannot be negative !
// invoke after the timespan
scheduleTimer.Change((long)ts.TotalMilliseconds, Timeout.Infinite);
}
}
}
// call back for the timer function
static void RunNextSchedule(object obj) // obj ignored
{
if (nextSchedule == null)
return;
RunSchedule(nextSchedule, true);
// schedule next task
ScheduleTasks();
}
static void RunSchedule(SchedulerJob schedule, bool changeNextRun)
{
try
{
// update next run (if required)
if (changeNextRun)
{
SchedulerController.CalculateNextStartTime(schedule.ScheduleInfo);
}
// disable run once task
if (schedule.ScheduleInfo.ScheduleType == ScheduleType.OneTime)
schedule.ScheduleInfo.Enabled = false;
Dictionary<int, BackgroundTask> scheduledTasks = TaskManager.GetScheduledTasks();
if (!scheduledTasks.ContainsKey(schedule.ScheduleInfo.ScheduleId))
// this task should be run, so
// update its last run
schedule.ScheduleInfo.LastRun = DateTime.Now;
// update schedule
int MAX_RETRY_COUNT = 10;
int counter = 0;
while (counter < MAX_RETRY_COUNT)
{
try
{
SchedulerController.UpdateSchedule(schedule.ScheduleInfo);
break;
}
catch (SqlException)
{
System.Threading.Thread.Sleep(1000);
}
counter++;
}
// skip execution if the current task is still running
scheduledTasks = TaskManager.GetScheduledTasks();
if (!scheduledTasks.ContainsKey(schedule.ScheduleInfo.ScheduleId))
{
// run the schedule in the separate thread
schedule.Run();
}
}
catch (Exception Ex)
{
try
{
TaskManager.WriteError(string.Format("RunSchedule Error : {0}", Ex.Message));
}
catch (Exception)
{
}
}
}
}
}

View file

@ -1,344 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using WebsitePanel.EnterpriseServer.Base.Scheduling;
namespace WebsitePanel.EnterpriseServer
{
public class SchedulerController
{
public static DateTime GetSchedulerTime()
{
return DateTime.Now;
}
public static List<ScheduleTaskInfo> GetScheduleTasks()
{
return ObjectUtils.CreateListFromDataReader<ScheduleTaskInfo>(
DataProvider.GetScheduleTasks(SecurityContext.User.UserId));
}
public static ScheduleTaskInfo GetScheduleTask(string taskId)
{
return ObjectUtils.FillObjectFromDataReader<ScheduleTaskInfo>(
DataProvider.GetScheduleTask(SecurityContext.User.UserId, taskId));
}
public static DataSet GetSchedules(int packageId)
{
DataSet ds = DataProvider.GetSchedules(SecurityContext.User.UserId, packageId);
// set status to each returned schedule
foreach (DataRow dr in ds.Tables[0].Rows)
{
dr["StatusID"] = Scheduler.IsScheduleActive((int)dr["ScheduleID"])
? ScheduleStatus.Running : ScheduleStatus.Idle;
}
return ds;
}
public static DataSet GetSchedulesPaged(int packageId, bool recursive,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
DataSet ds = DataProvider.GetSchedulesPaged(SecurityContext.User.UserId, packageId,
recursive, filterColumn, filterValue, sortColumn, startRow, maximumRows);
// set status to each returned schedule
foreach (DataRow dr in ds.Tables[1].Rows)
{
dr["StatusID"] = Scheduler.IsScheduleActive((int)dr["ScheduleID"])
? ScheduleStatus.Running : ScheduleStatus.Idle;
}
return ds;
}
public static ScheduleInfo GetSchedule(int scheduleId)
{
DataSet ds = DataProvider.GetSchedule(SecurityContext.User.UserId, scheduleId);
ScheduleInfo si = ObjectUtils.FillObjectFromDataView<ScheduleInfo>(ds.Tables[0].DefaultView);
return si;
}
/// <summary>
/// Gets view configuration for a certain task.
/// </summary>
/// <param name="taskId">Task id for which view configuration is intended to be loeaded.</param>
/// <returns>View configuration for the task with supplied id.</returns>
public static List<ScheduleTaskViewConfiguration> GetScheduleTaskViewConfigurations(string taskId)
{
List<ScheduleTaskViewConfiguration> c = ObjectUtils.CreateListFromDataReader<ScheduleTaskViewConfiguration>(DataProvider.GetScheduleTaskViewConfigurations(taskId));
return c;
}
internal static SchedulerJob GetScheduleComplete(int scheduleId)
{
DataSet ds = DataProvider.GetSchedule(SecurityContext.User.UserId, scheduleId);
return CreateCompleteScheduleFromDataSet(ds);
}
internal static SchedulerJob GetNextSchedule()
{
DataSet ds = DataProvider.GetNextSchedule();
return CreateCompleteScheduleFromDataSet(ds);
}
internal static SchedulerJob CreateCompleteScheduleFromDataSet(DataSet ds)
{
if (ds.Tables[0].Rows.Count == 0)
return null;
SchedulerJob schedule = new SchedulerJob();
// schedule info
schedule.ScheduleInfo = ObjectUtils.FillObjectFromDataView<ScheduleInfo>(ds.Tables[0].DefaultView);
// task info
schedule.Task = ObjectUtils.FillObjectFromDataView<ScheduleTaskInfo>(ds.Tables[1].DefaultView);
// parameters info
List<ScheduleTaskParameterInfo> parameters = new List<ScheduleTaskParameterInfo>();
ObjectUtils.FillCollectionFromDataView<ScheduleTaskParameterInfo>(
parameters, ds.Tables[2].DefaultView);
schedule.ScheduleInfo.Parameters = parameters.ToArray();
return schedule;
}
public static ScheduleInfo GetScheduleInternal(int scheduleId)
{
return ObjectUtils.FillObjectFromDataReader<ScheduleInfo>(
DataProvider.GetScheduleInternal(scheduleId));
}
public static List<ScheduleTaskParameterInfo> GetScheduleParameters(string taskId, int scheduleId)
{
return ObjectUtils.CreateListFromDataReader<ScheduleTaskParameterInfo>(
DataProvider.GetScheduleParameters(SecurityContext.User.UserId,
taskId, scheduleId));
}
public static int StartSchedule(int scheduleId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
SchedulerJob schedule = GetScheduleComplete(scheduleId);
if (schedule == null)
return 0;
Scheduler.StartSchedule(schedule);
return 0;
}
public static int StopSchedule(int scheduleId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
SchedulerJob schedule = GetScheduleComplete(scheduleId);
if (schedule == null)
return 0;
Scheduler.StopSchedule(schedule);
return 0;
}
public static void CalculateNextStartTime(ScheduleInfo schedule)
{
if (schedule.ScheduleType == ScheduleType.OneTime)
{
// start time stay intact
// we only disable this task for the next time
schedule.NextRun = schedule.StartTime;
}
else if (schedule.ScheduleType == ScheduleType.Interval)
{
DateTime lastRun = schedule.LastRun;
DateTime now = DateTime.Now;
// the task is running first time by default
DateTime nextStart = DateTime.Now;
if (lastRun != DateTime.MinValue)
{
// the task is running next times
nextStart = lastRun.AddSeconds(schedule.Interval);
}
if (nextStart < now)
nextStart = now; // run immediately
// check if start time is in allowed interval
DateTime fromTime = new DateTime(now.Year, now.Month, now.Day,
schedule.FromTime.Hour, schedule.FromTime.Minute, schedule.FromTime.Second);
DateTime toTime = new DateTime(now.Year, now.Month, now.Day,
schedule.ToTime.Hour, schedule.ToTime.Minute, schedule.ToTime.Second);
if (!(nextStart >= fromTime && nextStart <= toTime))
{
// run task in the start of the interval, but only tomorrow
nextStart = fromTime.AddDays(1);
}
schedule.NextRun = nextStart;
}
else if (schedule.ScheduleType == ScheduleType.Daily)
{
DateTime now = DateTime.Now;
DateTime startTime = schedule.StartTime;
DateTime nextStart = new DateTime(now.Year, now.Month, now.Day,
startTime.Hour, startTime.Minute, startTime.Second);
if (nextStart < now) // start time is in the past
nextStart = nextStart.AddDays(1); // run tomorrow
schedule.NextRun = nextStart;
}
else if (schedule.ScheduleType == ScheduleType.Weekly)
{
DateTime now = DateTime.Now;
DateTime startTime = schedule.StartTime;
DateTime nextStart = new DateTime(now.Year, now.Month, now.Day,
startTime.Hour, startTime.Minute, startTime.Second);
int todayWeekDay = (int)now.DayOfWeek;
nextStart = nextStart.AddDays(schedule.WeekMonthDay - todayWeekDay);
if (nextStart < now) // start time is in the past
nextStart = nextStart.AddDays(7); // run next week
schedule.NextRun = nextStart;
}
else if (schedule.ScheduleType == ScheduleType.Monthly)
{
DateTime now = DateTime.Now;
DateTime startTime = schedule.StartTime;
DateTime nextStart = new DateTime(now.Year, now.Month, now.Day,
startTime.Hour, startTime.Minute, startTime.Second);
int todayDay = now.Day;
nextStart = nextStart.AddDays(schedule.WeekMonthDay - todayDay);
if (nextStart < now) // start time is in the past
nextStart = nextStart.AddMonths(1); // run next month
schedule.NextRun = nextStart;
}
}
public static int AddSchedule(ScheduleInfo schedule)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check quota
if (PackageController.GetPackageQuota(schedule.PackageId, Quotas.OS_SCHEDULEDTASKS).QuotaExhausted)
return BusinessErrorCodes.ERROR_OS_SCHEDULED_TASK_QUOTA_LIMIT;
CalculateNextStartTime(schedule);
string xmlParameters = BuildParametersXml(schedule.Parameters);
int scheduleId = DataProvider.AddSchedule(SecurityContext.User.UserId,
schedule.TaskId, schedule.PackageId, schedule.ScheduleName, schedule.ScheduleTypeId,
schedule.Interval, schedule.FromTime, schedule.ToTime, schedule.StartTime,
schedule.NextRun, schedule.Enabled, schedule.PriorityId,
schedule.HistoriesNumber, schedule.MaxExecutionTime, schedule.WeekMonthDay, xmlParameters);
// re-schedule tasks
Scheduler.ScheduleTasks();
return scheduleId;
}
public static int UpdateSchedule(ScheduleInfo schedule)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original schedule
ScheduleInfo originalSchedule = GetScheduleInternal(schedule.ScheduleId);
schedule.LastRun = schedule.LastRun;
CalculateNextStartTime(schedule);
string xmlParameters = BuildParametersXml(schedule.Parameters);
DataProvider.UpdateSchedule(SecurityContext.User.UserId,
schedule.ScheduleId, schedule.TaskId, schedule.ScheduleName, schedule.ScheduleTypeId,
schedule.Interval, schedule.FromTime, schedule.ToTime, schedule.StartTime,
schedule.LastRun, schedule.NextRun, schedule.Enabled, schedule.PriorityId,
schedule.HistoriesNumber, schedule.MaxExecutionTime, schedule.WeekMonthDay, xmlParameters);
// re-schedule tasks
Scheduler.ScheduleTasks();
return 0;
}
private static string BuildParametersXml(ScheduleTaskParameterInfo[] parameters)
{
XmlDocument doc = new XmlDocument();
XmlElement nodeProps = doc.CreateElement("parameters");
if (parameters != null)
{
foreach (ScheduleTaskParameterInfo parameter in parameters)
{
XmlElement nodeProp = doc.CreateElement("parameter");
nodeProp.SetAttribute("id", parameter.ParameterId);
nodeProp.SetAttribute("value", parameter.ParameterValue);
nodeProps.AppendChild(nodeProp);
}
}
return nodeProps.OuterXml;
}
public static int DeleteSchedule(int scheduleId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// stop schedule if active
StopSchedule(scheduleId);
// delete schedule
DataProvider.DeleteSchedule(SecurityContext.User.UserId, scheduleId);
// re-schedule tasks
Scheduler.ScheduleTasks();
return 0;
}
}
}

View file

@ -1,132 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class SchedulerJob
{
private ScheduleInfo scheduleInfo;
private ScheduleTaskInfo task;
public ScheduleFinished ScheduleFinishedCallback;
#region public properties
public ScheduleInfo ScheduleInfo
{
get { return this.scheduleInfo; }
set { this.scheduleInfo = value; }
}
public ScheduleTaskInfo Task
{
get { return this.task; }
set { this.task = value; }
}
#endregion
// Constructor
public SchedulerJob()
{
}
// Sets the next time this Schedule is kicked off and kicks off events on
// a seperate thread, freeing the Scheduler to continue
public void Run()
{
// create worker
Thread worker = new Thread(new ThreadStart(RunSchedule));
// set worker priority
switch (scheduleInfo.Priority)
{
case SchedulePriority.Highest: worker.Priority = ThreadPriority.Highest; break;
case SchedulePriority.AboveNormal: worker.Priority = ThreadPriority.AboveNormal; break;
case SchedulePriority.Normal: worker.Priority = ThreadPriority.Normal; break;
case SchedulePriority.BelowNormal: worker.Priority = ThreadPriority.BelowNormal; break;
case SchedulePriority.Lowest: worker.Priority = ThreadPriority.Lowest; break;
}
// start worker!
worker.Start();
}
// Implementation of ThreadStart delegate.
// Used by Scheduler to kick off events on a seperate thread
private void RunSchedule()
{
// impersonate thread
UserInfo user = PackageController.GetPackageOwner(scheduleInfo.PackageId);
SecurityContext.SetThreadPrincipal(user.UserId);
TaskManager.StartTask("SCHEDULER", "RUN_SCHEDULE", scheduleInfo.ScheduleName);
TaskManager.PackageId = scheduleInfo.PackageId;
TaskManager.ItemId = scheduleInfo.ScheduleId;
TaskManager.ScheduleId = scheduleInfo.ScheduleId;
TaskManager.MaximumExecutionTime = scheduleInfo.MaxExecutionTime;
// set task parameters
foreach (ScheduleTaskParameterInfo prm in scheduleInfo.Parameters)
TaskManager.TaskParameters[prm.ParameterId] = prm.ParameterValue;
// run task
try
{
// create scheduled task object
SchedulerTask objTask = (SchedulerTask)Activator.CreateInstance(Type.GetType(task.TaskType));
if (objTask != null)
objTask.DoWork();
else
throw new Exception(String.Format("Could not create scheduled task of '{0}' type",
task.TaskType));
}
catch (Exception ex)
{
// log error
TaskManager.WriteError(ex, "Error executing scheduled task");
}
finally
{
// complete task
try
{
TaskManager.CompleteTask();
}
catch (Exception)
{
}
}
}
}
}

View file

@ -1,393 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Web;
using WebsitePanel.Providers.Statistics;
namespace WebsitePanel.EnterpriseServer
{
public class StatisticsServerController : IImportController, IBackupController
{
public static StatisticsServer GetStatisticsServer(int serviceId)
{
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, serviceId);
return stats;
}
public static DataSet GetRawStatisticsSitesPaged(int packageId,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return PackageController.GetRawPackageItemsPaged(packageId, typeof(StatsSite),
true, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<StatsSite> GetStatisticsSites(int packageId, bool recursive)
{
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(
packageId, typeof(StatsSite), recursive);
return items.ConvertAll<StatsSite>(
new Converter<ServiceProviderItem, StatsSite>(ConvertItemToStatisticsSiteItem));
}
private static StatsSite ConvertItemToStatisticsSiteItem(ServiceProviderItem item)
{
return (StatsSite)item;
}
public static StatsServer[] GetServers(int serviceId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive
| DemandAccount.IsAdmin);
if (accountCheck < 0) return null;
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, serviceId);
return stats.GetServers();
}
public static StatsSite GetSite(int itemId)
{
// load meta item
StatsSite item = (StatsSite)PackageController.GetPackageItem(itemId);
if (item == null)
return null;
// load item from service
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, item.ServiceId);
StatsSite site = stats.GetSite(item.SiteId);
if (site == null)
return null;
site.Id = item.Id;
site.Name = item.Name;
site.ServiceId = item.ServiceId;
site.PackageId = item.PackageId;
site.SiteId = item.SiteId;
// update statistics URL
if (!String.IsNullOrEmpty(site.StatisticsUrl))
{
// load space owner
UserInfo user = PackageController.GetPackageOwner(item.PackageId);
if (user != null)
{
site.StatisticsUrl = Utils.ReplaceStringVariable(site.StatisticsUrl, "username",
HttpUtility.UrlEncode(user.Username));
site.StatisticsUrl = Utils.ReplaceStringVariable(site.StatisticsUrl, "password",
HttpUtility.UrlEncode(user.Password));
}
}
return site;
}
public static int AddSite(StatsSite item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check package
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// check quota
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.STATS_SITES);
if (quota.QuotaExhausted)
return BusinessErrorCodes.ERROR_STATS_RESOURCE_QUOTA_LIMIT;
// check if stats resource is available
int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Statistics);
if (serviceId == 0)
return BusinessErrorCodes.ERROR_STATS_RESOURCE_UNAVAILABLE;
// check package items
if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(StatsSite)) != null)
return BusinessErrorCodes.ERROR_STATS_PACKAGE_ITEM_EXISTS;
// place log record
TaskManager.StartTask("STATS_SITE", "ADD", item.Name);
try
{
// load web site
WebSite siteItem = (WebSite)PackageController.GetPackageItemByName(item.PackageId,
item.Name, typeof(WebSite));
if (siteItem == null)
return BusinessErrorCodes.ERROR_WEB_SITE_SERVICE_UNAVAILABLE;
// get service web site
WebServer web = new WebServer();
ServiceProviderProxy.Init(web, siteItem.ServiceId);
WebSite site = web.GetSite(siteItem.SiteId);
List<DomainInfo> pointers = WebServerController.GetWebSitePointers(siteItem.Id);
List<string> aliases = new List<string>();
foreach(DomainInfo pointer in pointers)
aliases.Add(pointer.DomainName);
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, serviceId);
string siteNumber = (site.IIs7) ? site[WebSite.IIS7_SITE_ID] : siteItem.SiteId.Replace("/", "");
string logsCommonFolder = site.LogsPath;
string logsFolder = Path.Combine(logsCommonFolder, siteNumber);
// get service settings
StringDictionary settings = ServerController.GetServiceSettings(serviceId);
if (Utils.ParseBool(settings["BuildUncLogsPath"], false))
{
logsFolder = FilesController.ConvertToUncPath(siteItem.ServiceId, logsFolder);
}
item.LogDirectory = logsFolder;
item.DomainAliases = aliases.ToArray();
// install statistics
item.SiteId = stats.AddSite(item);
// save statistics item
item.ServiceId = serviceId;
int itemId = PackageController.AddPackageItem(item);
TaskManager.ItemId = itemId;
return itemId;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int UpdateSite(StatsSite item)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// load original meta item
StatsSite origItem = (StatsSite)PackageController.GetPackageItem(item.Id);
if (origItem == null)
return BusinessErrorCodes.ERROR_STATS_PACKAGE_ITEM_NOT_FOUND;
// check package
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0) return packageCheck;
// update statistics site
item.Name = origItem.Name;
item.SiteId = origItem.SiteId;
// place log record
TaskManager.StartTask("STATS_SITE", "UPDATE", origItem.Name);
TaskManager.ItemId = origItem.Id;
try
{
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, origItem.ServiceId);
stats.UpdateSite(item);
// update service item
PackageController.UpdatePackageItem(item);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int DeleteSite(int itemId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// load original meta item
StatsSite origItem = (StatsSite)PackageController.GetPackageItem(itemId);
if (origItem == null)
return BusinessErrorCodes.ERROR_STATS_PACKAGE_ITEM_NOT_FOUND;
// place log record
TaskManager.StartTask("STATS_SITE", "DELETE", origItem.Name);
TaskManager.ItemId = origItem.Id;
try
{
// get service
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, origItem.ServiceId);
// delete service item
stats.DeleteSite(origItem.SiteId);
// delete meta item
PackageController.DeletePackageItem(origItem.Id);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#region IImportController Members
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
{
List<string> items = new List<string>();
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return items;
// Mail provider
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, serviceId);
if (itemType == typeof(StatsSite))
items.AddRange(stats.GetSites());
return items;
}
public void ImportItem(int packageId, int itemTypeId, Type itemType,
ResourceGroupInfo group, string itemName)
{
// get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
return;
StatisticsServer stats = new StatisticsServer();
ServiceProviderProxy.Init(stats, serviceId);
if (itemType == typeof(StatsSite))
{
// import statistics site
StatsSite site = new StatsSite();
site.ServiceId = serviceId;
site.PackageId = packageId;
site.Name = itemName;
site.GroupName = group.GroupName;
// load site id
site.SiteId = stats.GetSiteId(itemName);
PackageController.AddPackageItem(site);
}
}
#endregion
#region IBackupController Members
public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
if (item is StatsSite)
{
// backup stats site
StatisticsServer stats = GetStatisticsServer(item.ServiceId);
// read site info
StatsSite itemSite = item as StatsSite;
StatsSite site = stats.GetSite(itemSite.SiteId);
XmlSerializer serializer = new XmlSerializer(typeof(StatsSite));
serializer.Serialize(writer, site);
}
return 0;
}
public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType == typeof(StatsSite))
{
StatisticsServer stats = GetStatisticsServer(serviceId);
// extract meta item
XmlSerializer serializer = new XmlSerializer(typeof(StatsSite));
StatsSite site = (StatsSite)serializer.Deserialize(
new XmlNodeReader(itemNode.SelectSingleNode("StatsSite")));
// create site if required
if (stats.GetSite(site.SiteId) == null)
{
stats.AddSite(site);
}
// add meta-item if required
if (PackageController.GetPackageItemByName(packageId, itemName, typeof(StatsSite)) == null)
{
site.PackageId = packageId;
site.ServiceId = serviceId;
PackageController.AddPackageItem(site);
}
}
return 0;
}
#endregion
}
}

View file

@ -1,194 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Xml;
using System.Data;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class SystemController
{
private SystemController()
{
}
public static SystemSettings GetSystemSettings(string settingsName)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin | DemandAccount.IsActive);
if (accountCheck < 0)
return null;
bool isDemoAccount = (SecurityContext.CheckAccount(DemandAccount.NotDemo) < 0);
return GetSystemSettingsInternal(settingsName, !isDemoAccount);
}
internal static SystemSettings GetSystemSettingsInternal(string settingsName, bool decryptPassword)
{
// create settings object
SystemSettings settings = new SystemSettings();
// get service settings
IDataReader reader = null;
try
{
// get service settings
reader = DataProvider.GetSystemSettings(settingsName);
while (reader.Read())
{
string name = (string)reader["PropertyName"];
string val = (string)reader["PropertyValue"];
if (name.ToLower().IndexOf("password") != -1 && decryptPassword)
val = CryptoUtils.Decrypt(val);
settings[name] = val;
}
}
finally
{
if (reader != null && !reader.IsClosed)
reader.Close();
}
return settings;
}
public static int SetSystemSettings(string settingsName, SystemSettings settings)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin
| DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
XmlDocument xmldoc = new XmlDocument();
XmlElement root = xmldoc.CreateElement("properties");
foreach (string[] pair in settings.SettingsArray)
{
string name = pair[0];
string val = pair[1];
if (name.ToLower().IndexOf("password") != -1)
val = CryptoUtils.Encrypt(val);
XmlElement property = xmldoc.CreateElement("property");
property.SetAttribute("name", name);
property.SetAttribute("value", val);
root.AppendChild(property);
}
DataProvider.SetSystemSettings(settingsName, root.OuterXml);
return 0;
}
internal static bool GetSystemSetupMode()
{
var scpaSystemSettings = GetSystemSettings(SystemSettings.SETUP_SETTINGS);
// Flag either not found or empty
if (String.IsNullOrEmpty(scpaSystemSettings["EnabledSCPA"]))
{
return false;
}
//
return true;
}
internal static int SetupControlPanelAccounts(string passwordA, string passwordB, string ip)
{
try
{
TaskManager.StartTask("SYSTEM", "COMPLETE_SCPA");
//
TaskManager.WriteParameter("Password A", passwordA);
TaskManager.WriteParameter("Password B", passwordB);
TaskManager.WriteParameter("IP Address", ip);
//
var enabledScpaMode = GetSystemSetupMode();
//
if (enabledScpaMode == false)
{
//
TaskManager.WriteWarning("Attempt to execute SCPA procedure for an uknown reason");
//
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
// Entering the security context into Supervisor mode
SecurityContext.SetThreadSupervisorPrincipal();
//
var accountA = UserController.GetUserInternally("serveradmin");
var accountB = UserController.GetUserInternally("admin");
//
var resultCodeA = UserController.ChangeUserPassword(accountA.UserId, passwordA);
//
if (resultCodeA < 0)
{
TaskManager.WriteParameter("Result Code A", resultCodeA);
//
return resultCodeA;
}
//
var resultCodeB = UserController.ChangeUserPassword(accountB.UserId, passwordB);
//
if (resultCodeB < 0)
{
TaskManager.WriteParameter("Result Code B", resultCodeB);
//
return resultCodeB;
}
// Disable SCPA mode
SetSystemSettings(SystemSettings.SETUP_SETTINGS, SystemSettings.Empty);
// Operation has succeeded
return 0;
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
//
return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
}
finally
{
TaskManager.CompleteTask();
}
}
}
}

View file

@ -1,139 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
namespace WebsitePanel.EnterpriseServer.Tasks
{
public class SendEmailNotification : TaskEventHandler
{
public override void OnStart()
{
// nothing to-do
}
public override void OnComplete()
{
if (!TaskManager.HasErrors)
{
// Send user add notification
if (TaskManager.TaskSource == "USER" &&
TaskManager.TaskName == "ADD" && TaskManager.ItemId > 0)
{
SendAddUserNotification();
}
// Send hosting package add notification
if (TaskManager.TaskSource == "HOSTING_SPACE"
&& TaskManager.TaskName == "ADD" && TaskManager.ItemId > 0)
{
SendAddPackageNotification();
}
// Send hosting package add notification
if (TaskManager.TaskSource == "HOSTING_SPACE_WR"
&& TaskManager.TaskName == "ADD" && TaskManager.ItemId > 0)
{
SendAddPackageWithResourcesNotification();
}
}
}
private void CheckSmtpResult(int resultCode)
{
if (resultCode != 0)
{
TaskManager.WriteWarning("Unable to send an e-mail notification");
TaskManager.WriteParameter("SMTP Result", resultCode);
}
}
protected void SendAddPackageWithResourcesNotification()
{
try
{
bool sendLetter = (bool)TaskManager.TaskParameters["SendLetter"];
if (sendLetter)
{
int sendResult = PackageController.SendPackageSummaryLetter(TaskManager.ItemId, null, null, true);
CheckSmtpResult(sendResult);
}
}
catch (Exception ex)
{
TaskManager.WriteWarning(ex.StackTrace);
}
}
protected void SendAddPackageNotification()
{
try
{
int userId = (int)TaskManager.TaskParameters["UserId"];
bool sendLetter = (bool)TaskManager.TaskParameters["SendLetter"];
bool signup = (bool)TaskManager.TaskParameters["Signup"];
// send space letter if enabled
UserSettings settings = UserController.GetUserSettings(userId, UserSettings.PACKAGE_SUMMARY_LETTER);
if (sendLetter
&& !String.IsNullOrEmpty(settings["EnableLetter"])
&& Utils.ParseBool(settings["EnableLetter"], false))
{
// send letter
int smtpResult = PackageController.SendPackageSummaryLetter(TaskManager.ItemId, null, null, signup);
CheckSmtpResult(smtpResult);
}
}
catch (Exception ex)
{
TaskManager.WriteWarning(ex.StackTrace);
}
}
protected void SendAddUserNotification()
{
try
{
bool sendLetter = (bool)TaskManager.TaskParameters["SendLetter"];
int userId = TaskManager.ItemId;
// send account letter if enabled
UserSettings settings = UserController.GetUserSettings(userId, UserSettings.ACCOUNT_SUMMARY_LETTER);
if (sendLetter
&& !String.IsNullOrEmpty(settings["EnableLetter"])
&& Utils.ParseBool(settings["EnableLetter"], false))
{
// send letter
int smtpResult = PackageController.SendAccountSummaryLetter(userId, null, null, true);
CheckSmtpResult(smtpResult);
}
}
catch (Exception ex)
{
TaskManager.WriteWarning(ex.StackTrace);
}
}
}
}

View file

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

View file

@ -1,649 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Reflection;
using WebsitePanel.Providers.Common;
namespace WebsitePanel.EnterpriseServer
{
public class TaskManager
{
private static Hashtable tasks = Hashtable.Synchronized(new Hashtable());
private static Hashtable eventHandlers = null;
// purge timer, used for killing old tasks from the hash
static Timer purgeTimer = new Timer(new TimerCallback(PurgeCompletedTasks),
null,
60000, // start from 1 minute
60000); // invoke each minute
private static BackgroundTask RootTask
{
get { return TasksStack.Count > 0 ? TasksStack[0] : null; }
}
private static BackgroundTask TopTask
{
get { return TasksStack.Count > 0 ? TasksStack[TasksStack.Count - 1] : null; }
}
private static List<BackgroundTask> TasksStack
{
get
{
List<BackgroundTask> stack = (List<BackgroundTask>)Thread.GetData(Thread.GetNamedDataSlot("BackgroundTasksStack"));
if (stack == null)
{
stack = new List<BackgroundTask>();
Thread.SetData(Thread.GetNamedDataSlot("BackgroundTasksStack"), stack);
}
return stack;
}
}
public static void StartTask(string source, string taskName)
{
StartTask(null, source, taskName, null);
}
public static void StartTask(string source, string taskName, object itemName)
{
StartTask(null, source, taskName, itemName);
}
public static void StartTask(string taskId, string source, string taskName, object itemName)
{
// create new task object
BackgroundTask task = new BackgroundTask();
task.TaskId = String.IsNullOrEmpty(taskId) ? Guid.NewGuid().ToString("N") : taskId;
task.UserId = SecurityContext.User.UserId;
task.EffectiveUserId = SecurityContext.User.IsPeer ? SecurityContext.User.OwnerId : task.UserId;
task.StartDate = DateTime.Now;
task.Source = source;
task.TaskName = taskName;
task.ItemName = itemName != null ? itemName.ToString() : "";
task.Severity = 0; //info
task.TaskThread = Thread.CurrentThread;
// new "parent" task?
if (TasksStack.Count == 0)
{
// register task globally
tasks[task.TaskId] = task;
}
else
{
// child task
// add log record to the root task
BackgroundTaskLogRecord logRecord = new BackgroundTaskLogRecord();
logRecord.InnerTaskStart = true;
logRecord.Text = source + "_" + taskName;
logRecord.TextParameters = new string[] { itemName != null ? itemName.ToString() : "" };
logRecord.TextIdent = TasksStack.Count - 1;
RootTask.LogRecords.Add(logRecord);
// change log records destination
// for nested task
task.LogRecords = RootTask.LogRecords;
}
// call event handler
CallTaskEventHandler(task, false);
// push task on the stack
TasksStack.Add(task);
}
public static void WriteParameter(string parameterName, object parameterValue)
{
string val = parameterValue != null ? parameterValue.ToString() : "";
WriteLogRecord(0, parameterName + ": " + val, null, null);
}
public static void Write(string text, params string[] textParameters)
{
// INFO
WriteLogRecord(0, text, null, textParameters);
}
public static void WriteWarning(string text, params string[] textParameters)
{
// WARNING
WriteLogRecord(1, text, null, textParameters);
}
public static Exception WriteError(Exception ex)
{
// ERROR
WriteLogRecord(2, ex.Message, ex.StackTrace);
return new Exception((TopTask != null) ? String.Format("Error executing '{0}' task on '{1}' {2}",
TopTask.TaskName, TopTask.ItemName, TopTask.Source) : String.Format("Error executing task"), ex);
}
public static void WriteError(Exception ex, string text, params string[] textParameters)
{
// ERROR
string[] prms = new string[] { ex.Message };
if (textParameters != null && textParameters.Length > 0)
{
prms = new string[textParameters.Length + 1];
Array.Copy(textParameters, 0, prms, 1, textParameters.Length);
prms[0] = ex.Message;
}
WriteLogRecord(2, text, ex.Message + "\n" + ex.StackTrace, prms);
}
public static void WriteError(string text, params string[] textParameters)
{
// ERROR
WriteLogRecord(2, text, null, textParameters);
}
private static void WriteLogRecord(int severity, string text, string stackTrace, params string[] textParameters)
{
BackgroundTaskLogRecord logRecord = new BackgroundTaskLogRecord();
logRecord.Severity = severity;
logRecord.Text = text;
logRecord.TextParameters = textParameters;
logRecord.TextIdent = TasksStack.Count - 1;
logRecord.ExceptionStackTrace = stackTrace;
if (RootTask != null)
{
RootTask.LogRecords.Add(logRecord);
RootTask.LastLogRecord = logRecord;
// change entire task severity
if (severity > RootTask.Severity)
RootTask.Severity = severity;
}
}
public static void CompleteTask()
{
if (TasksStack.Count == 0)
return;
// call event handler
CallTaskEventHandler(TopTask, true);
// finish task
TopTask.FinishDate = DateTime.Now;
TopTask.Completed = true;
// write task execution result to database
if (TasksStack.Count == 1) // single task
{
// unregister task globally
// tasks.Remove(TopTask.TaskId);
// write to database
string itemName = TopTask.ItemName != null ? TopTask.ItemName.ToString() : null;
string executionLog = FormatExecutionLog(TopTask);
UserInfo user = UserController.GetUserInternally(TopTask.UserId);
string username = user != null ? user.Username : null;
AuditLog.AddAuditLogRecord(TopTask.TaskId, TopTask.Severity, TopTask.UserId,
username, TopTask.PackageId, TopTask.ItemId,
itemName, TopTask.StartDate, TopTask.FinishDate, TopTask.Source,
TopTask.TaskName, executionLog);
}
// remove task from the stack
TasksStack.RemoveAt(TasksStack.Count - 1);
}
static string FormatExecutionLog(BackgroundTask task)
{
StringWriter sw = new StringWriter();
XmlWriter writer = new XmlTextWriter(sw);
writer.WriteStartElement("log");
// parameters
writer.WriteStartElement("parameters");
foreach (string name in task.Parameters.Keys)
{
string val = task.Parameters[name] != null ? task.Parameters[name].ToString() : "";
writer.WriteStartElement("parameter");
writer.WriteAttributeString("name", name);
writer.WriteString(val);
writer.WriteEndElement();
}
writer.WriteEndElement(); // parameters
// records
writer.WriteStartElement("records");
foreach (BackgroundTaskLogRecord record in task.LogRecords)
{
writer.WriteStartElement("record");
writer.WriteAttributeString("severity", record.Severity.ToString());
writer.WriteAttributeString("date", record.Date.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteAttributeString("ident", record.TextIdent.ToString());
// text
writer.WriteElementString("text", record.Text);
// text parameters
if (record.TextParameters != null && record.TextParameters.Length > 0)
{
writer.WriteStartElement("textParameters");
foreach (string prm in record.TextParameters)
{
writer.WriteElementString("value", prm);
}
writer.WriteEndElement(); // textParameters
}
// stack trace
writer.WriteElementString("stackTrace", record.ExceptionStackTrace);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
return sw.ToString();
}
static void PurgeCompletedTasks(object obj)
{
// remove completed tasks
List<string> completedTasks = new List<string>();
foreach (BackgroundTask task in tasks.Values)
{
if (task.MaximumExecutionTime != -1
&& ((TimeSpan)(DateTime.Now - task.StartDate)).TotalSeconds > task.MaximumExecutionTime)
{
// terminate task
try
{
task.TaskThread.Abort();
}
catch
{
// nope
}
// add to the list
completedTasks.Add(task.TaskId);
}
if ((task.FinishDate != DateTime.MinValue
&& ((TimeSpan)(DateTime.Now - task.FinishDate)).TotalMinutes > 2))
{
// add to the list
completedTasks.Add(task.TaskId);
}
}
// remove tasks
foreach (string taskId in completedTasks)
tasks.Remove(taskId);
}
public static int PackageId
{
get { return TopTask.PackageId; }
set { TopTask.PackageId = value; }
}
public static int ItemId
{
get { return TopTask.ItemId; }
set { TopTask.ItemId = value; }
}
public static string ItemName
{
get { return TopTask.ItemName; }
set { TopTask.ItemName = value; }
}
public static string TaskName
{
get { return TopTask.TaskName; }
}
public static string TaskSource
{
get { return TopTask.Source; }
}
public static int IndicatorMaximum
{
get { return TopTask.IndicatorMaximum; }
set { TopTask.IndicatorMaximum = value; }
}
public static int IndicatorCurrent
{
get { return TopTask.IndicatorCurrent; }
set { TopTask.IndicatorCurrent = value; }
}
public static int MaximumExecutionTime
{
get { return TopTask.MaximumExecutionTime; }
set { TopTask.MaximumExecutionTime = value; }
}
public static int ScheduleId
{
get { return TopTask.ScheduleId; }
set { TopTask.ScheduleId = value; }
}
public static bool HasErrors
{
get { return (TopTask.Severity == 2); }
}
public static BackgroundTask GetTask(string taskId)
{
BackgroundTask task = (BackgroundTask)tasks[taskId];
if (task == null)
return null;
task.LastLogRecords.Clear();
return task;
}
public static BackgroundTask GetTaskWithLogRecords(string taskId, DateTime startLogTime)
{
BackgroundTask task = GetTask(taskId);
if (task == null)
return null;
// fill log records
foreach (BackgroundTaskLogRecord record in task.LogRecords)
{
if (record.Date >= startLogTime)
task.LastLogRecords.Add(record);
}
return task;
}
public static Dictionary<int, BackgroundTask> GetScheduledTasks()
{
Dictionary<int, BackgroundTask> scheduledTasks = new Dictionary<int, BackgroundTask>();
try
{
foreach (BackgroundTask task in tasks.Values)
{
if (task.ScheduleId > 0
&& !task.Completed
&& !scheduledTasks.ContainsKey(task.ScheduleId))
scheduledTasks.Add(task.ScheduleId, task);
}
}
catch (Exception)
{
}
return scheduledTasks;
}
public static void SetTaskNotifyOnComplete(string taskId)
{
BackgroundTask task = (BackgroundTask)tasks[taskId];
if (task == null)
return;
task.NotifyOnComplete = true;
}
public static void StopTask(string taskId)
{
BackgroundTask task = (BackgroundTask)tasks[taskId];
if (task == null)
return;
try
{
task.TaskThread.Abort();
}
catch
{
// nope
}
// remove it from stack
tasks.Remove(taskId);
}
public static Hashtable TaskParameters
{
get { return TopTask.Parameters; }
}
internal static int GetTasksNumber()
{
return tasks.Count;
}
internal static List<BackgroundTask> GetUserTasks(int userId)
{
List<BackgroundTask> list = new List<BackgroundTask>();
// try to get user first
UserInfo user = UserController.GetUser(userId);
if (user == null)
return list; // prohibited user
// get user tasks
foreach (BackgroundTask task in tasks.Values)
{
if(task.EffectiveUserId == userId && !task.Completed)
list.Add(task);
}
return list;
}
internal static List<BackgroundTask> GetUserCompletedTasks(int userId)
{
// get user tasks
List<BackgroundTask> list = GetUserTasks(userId);
// extract completed only
List<BackgroundTask> completedTasks = new List<BackgroundTask>();
foreach (BackgroundTask task in list)
{
if (task.Completed && task.NotifyOnComplete)
{
// add to the list
completedTasks.Add(task);
// remove from hash
tasks.Remove(task.TaskId);
}
}
return completedTasks;
}
#region Private Helpers
private static void CallTaskEventHandler(BackgroundTask task, bool onComplete)
{
string[] taskHandlers = GetTaskEventHandlers(task.Source, task.TaskName);
if (taskHandlers != null)
{
foreach(string taskHandler in taskHandlers)
{
try
{
Type handlerType = Type.GetType(taskHandler);
TaskEventHandler handler = (TaskEventHandler)Activator.CreateInstance(handlerType);
if (handler != null)
{
if (onComplete)
handler.OnComplete();
else
handler.OnStart();
}
}
catch (Exception ex)
{
WriteError(ex, "Error executing task event handler: {0}", ex.Message);
}
}
}
}
private static string[] GetTaskEventHandlers(string source, string taskName)
{
// load configuration
string appRoot = AppDomain.CurrentDomain.BaseDirectory;
string path = Path.Combine(appRoot, "TaskEventHandlers.config");
if (eventHandlers == null)
{
eventHandlers = Hashtable.Synchronized(new Hashtable());
// load from XML
if (File.Exists(path))
{
List<XmlDocument> xmlConfigs = new List<XmlDocument>();
xmlConfigs.Add(new XmlDocument());
xmlConfigs[0].Load(path);
// Lookup for external references first
XmlNodeList xmlReferences = xmlConfigs[0].SelectNodes("//reference");
foreach (XmlElement xmlReference in xmlReferences)
{
string referencePath = Path.Combine(appRoot, xmlReference.GetAttribute("src"));
if (File.Exists(referencePath))
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(referencePath);
xmlConfigs.Add(xmldoc);
}
}
// parse XML
foreach (XmlDocument xml in xmlConfigs)
{
XmlNodeList xmlHandlers = xml.SelectNodes("//handler");
foreach (XmlNode xmlHandler in xmlHandlers)
{
string keyName = xmlHandler.ParentNode.Attributes["source"].Value
+ xmlHandler.ParentNode.Attributes["name"].Value;
// get handlers collection
List<string> taskHandlers = (List<string>)eventHandlers[keyName];
if (taskHandlers == null)
{
taskHandlers = new List<string>();
eventHandlers[keyName] = taskHandlers;
}
string handlerType = xmlHandler.Attributes["type"].Value;
taskHandlers.Add(handlerType);
}
}
}
}
string fullTaskName = source + taskName;
List<string> handlersList = (List<string>)eventHandlers[fullTaskName];
return handlersList == null ? null : handlersList.ToArray();
}
#endregion
#region ResultTasks
public static void CompleteResultTask(ResultObject res, string errorCode, Exception ex, string errorMessage)
{
if (res != null)
{
res.IsSuccess = false;
if (!string.IsNullOrEmpty(errorCode))
res.ErrorCodes.Add(errorCode);
}
if (ex != null)
TaskManager.WriteError(ex);
if (!string.IsNullOrEmpty(errorMessage))
TaskManager.WriteError(errorMessage);
//LogRecord.
CompleteTask();
}
public static void CompleteResultTask(ResultObject res, string errorCode, Exception ex)
{
CompleteResultTask(res, errorCode, ex, null);
}
public static void CompleteResultTask(ResultObject res, string errorCode)
{
CompleteResultTask(res, errorCode, null, null);
}
public static void CompleteResultTask(ResultObject res)
{
CompleteResultTask(res, null);
}
public static void CompleteResultTask()
{
CompleteResultTask(null);
}
public static T StartResultTask<T>(string source, string taskName, Guid taskId) where T : ResultObject, new()
{
StartTask(taskId.ToString(), source, taskName, null);
T res = new T();
res.IsSuccess = true;
return res;
}
public static T StartResultTask<T>(string source, string taskName) where T : ResultObject, new()
{
StartTask(source, taskName);
T res = new T();
res.IsSuccess = true;
return res;
}
#endregion
}
}

View file

@ -1,139 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.EnterpriseServer
{
public class UserAsyncWorker
{
private int threadUserId = -1;
private int userId;
private string taskId;
private UserInfo user;
#region Public properties
public int ThreadUserId
{
get { return this.threadUserId; }
set { this.threadUserId = value; }
}
public int UserId
{
get { return this.userId; }
set { this.userId = value; }
}
public string TaskId
{
get { return this.taskId; }
set { this.taskId = value; }
}
public UserInfo User
{
get { return this.user; }
set { this.user = value; }
}
#endregion
#region Update User
public void UpdateUserAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(UpdateUser));
t.Start();
}
public void UpdateUser()
{
// impersonate thread
if (threadUserId != -1)
SecurityContext.SetThreadPrincipal(threadUserId);
// update
UserController.UpdateUser(taskId, user);
}
#endregion
#region Delete User
public void DeleteUserAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(DeleteUser));
t.Start();
}
public void DeleteUser()
{
// impersonate thread
if (threadUserId != -1)
SecurityContext.SetThreadPrincipal(threadUserId);
// get user details
UserInfo user = UserController.GetUserInternally(userId);
// place log record
TaskManager.StartTask(taskId, "USER", "DELETE", user.Username);
TaskManager.ItemId = userId;
try
{
// delete user packages
List<PackageInfo> packages = PackageController.GetMyPackages(userId);
// delete user packages synchronously
if (packages.Count > 0)
{
PackageAsyncWorker packageWorker = new PackageAsyncWorker();
packageWorker.UserId = SecurityContext.User.UserId;
packageWorker.Packages = packages;
// invoke worker
packageWorker.DeletePackagesServiceItems();
}
// delete user from database
DataProvider.DeleteUser(SecurityContext.User.UserId, userId);
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
}
}

View file

@ -1,838 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for UserController.
/// </summary>
public class UserController
{
public static bool UserExists(string username)
{
// try to get user from database
UserInfo user = GetUserInternally(username);
return (user != null);
}
public static int AuthenticateUser(string username, string password, string ip)
{
// start task
TaskManager.StartTask("USER", "AUTHENTICATE", username);
TaskManager.WriteParameter("IP", ip);
try
{
// try to get user from database
UserInfo user = GetUserInternally(username);
// check if the user exists
if (user == null)
{
TaskManager.WriteWarning("Wrong username");
return BusinessErrorCodes.ERROR_USER_WRONG_USERNAME;
}
// check if the user is disabled
if (user.LoginStatus == UserLoginStatus.Disabled)
{
TaskManager.WriteWarning("User disabled");
return BusinessErrorCodes.ERROR_USER_ACCOUNT_DISABLED;
}
// check if the user is locked out
if (user.LoginStatus == UserLoginStatus.LockedOut)
{
TaskManager.WriteWarning("User locked out");
return BusinessErrorCodes.ERROR_USER_ACCOUNT_LOCKEDOUT;
}
//Get the password policy
UserSettings userSettings = UserController.GetUserSettings(user.UserId, UserSettings.WEBSITEPANEL_POLICY);
int lockOut = -1;
if (!string.IsNullOrEmpty(userSettings["PasswordPolicy"]))
{
string passwordPolicy = userSettings["PasswordPolicy"];
try
{
// parse settings
string[] parts = passwordPolicy.Split(';');
lockOut = Convert.ToInt32(parts[7]);
}
catch { /* skip */ }
}
// compare user passwords
if (user.Password != password)
{
if (lockOut >= 0)
DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, false);
TaskManager.WriteWarning("Wrong password");
return BusinessErrorCodes.ERROR_USER_WRONG_PASSWORD;
}
else
DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, true);
// check status
if (user.Status == UserStatus.Cancelled)
{
TaskManager.WriteWarning("Account cancelled");
return BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED;
}
if (user.Status == UserStatus.Pending)
{
TaskManager.WriteWarning("Account pending");
return BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING;
}
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static UserInfo GetUserByUsernamePassword(string username, string password, string ip)
{
// place log record
TaskManager.StartTask("USER", "GET_BY_USERNAME_PASSWORD", username);
TaskManager.WriteParameter("IP", ip);
try
{
// try to get user from database
UserInfo user = GetUserInternally(username);
// check if the user exists
if (user == null)
{
TaskManager.WriteWarning("Account not found");
return null;
}
// compare user passwords
if (user.Password == password)
return user;
return null;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int ChangeUserPassword(string username, string oldPassword, string newPassword, string ip)
{
// place log record
TaskManager.StartTask("USER", "CHANGE_PASSWORD_BY_USERNAME_PASSWORD", username);
TaskManager.WriteParameter("IP", ip);
try
{
UserInfo user = GetUserByUsernamePassword(username, oldPassword, ip);
if (user == null)
{
TaskManager.WriteWarning("Account not found");
return BusinessErrorCodes.ERROR_USER_NOT_FOUND;
}
// change password
DataProvider.ChangeUserPassword(-1, user.UserId,
CryptoUtils.Encrypt(newPassword));
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int SendPasswordReminder(string username, string ip)
{
// place log record
TaskManager.StartTask("USER", "SEND_REMINDER", username);
TaskManager.WriteParameter("IP", ip);
try
{
// try to get user from database
UserInfo user = GetUserInternally(username);
if (user == null)
{
TaskManager.WriteWarning("Account not found");
// Fix for item #273 (NGS-9)
//return BusinessErrorCodes.ERROR_USER_NOT_FOUND;
return 0;
}
UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.PASSWORD_REMINDER_LETTER);
string from = settings["From"];
string cc = settings["CC"];
string subject = settings["Subject"];
string body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
bool isHtml = user.HtmlMail;
MailPriority priority = MailPriority.Normal;
if (!String.IsNullOrEmpty(settings["Priority"]))
priority = (MailPriority)Enum.Parse(typeof(MailPriority), settings["Priority"], true);
if (body == null || body == "")
return BusinessErrorCodes.ERROR_SETTINGS_PASSWORD_LETTER_EMPTY_BODY;
// set template context items
Hashtable items = new Hashtable();
items["user"] = user;
items["Email"] = true;
// get reseller details
UserInfo reseller = UserController.GetUser(user.OwnerId);
if (reseller != null)
{
reseller.Password = "";
items["reseller"] = reseller;
}
subject = PackageController.EvaluateTemplate(subject, items);
body = PackageController.EvaluateTemplate(body, items);
// send message
MailHelper.SendMessage(from, user.Email, cc, subject, body, priority, isHtml);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
internal static UserInfo GetUserInternally(int userId)
{
// try to get user from database
UserInfo user = ObjectUtils.FillObjectFromDataReader<UserInfo>(
DataProvider.GetUserByIdInternally(userId));
if (user != null)
user.Password = CryptoUtils.Decrypt(user.Password);
return user;
}
internal static UserInfo GetUserInternally(string username)
{
// try to get user from database
UserInfo user = ObjectUtils.FillObjectFromDataReader<UserInfo>(
DataProvider.GetUserByUsernameInternally(username));
if (user != null)
{
user.Password = CryptoUtils.Decrypt(user.Password);
}
return user;
}
public static UserInfo GetUser(int userId)
{
// try to get user from database
UserInfo user = ObjectUtils.FillObjectFromDataReader<UserInfo>(
DataProvider.GetUserById(SecurityContext.User.UserId, userId));
if (user != null)
user.Password = CryptoUtils.Decrypt(user.Password);
return user;
}
public static UserInfo GetUser(string username)
{
// try to get user from database
UserInfo user = ObjectUtils.FillObjectFromDataReader<UserInfo>(
DataProvider.GetUserByUsername(SecurityContext.User.UserId, username));
if (user != null)
user.Password = CryptoUtils.Decrypt(user.Password);
return user;
}
public static List<UserInfo> GetUserParents(int userId)
{
// get users from database
DataSet dsUsers = DataProvider.GetUserParents(SecurityContext.User.UserId, userId);
// convert to arraylist
List<UserInfo> users = new List<UserInfo>();
ObjectUtils.FillCollectionFromDataSet<UserInfo>(users, dsUsers);
return users;
}
public static List<UserInfo> GetUsers(int userId, bool recursive)
{
// get users from database
DataSet dsUsers = DataProvider.GetUsers(SecurityContext.User.UserId, userId, recursive);
// convert to arraylist
List<UserInfo> users = new List<UserInfo>();
ObjectUtils.FillCollectionFromDataSet<UserInfo>(users, dsUsers);
return users;
}
public static DataSet GetUsersPaged(int userId, string filterColumn, string filterValue,
int statusId, int roleId,
string sortColumn, int startRow, int maximumRows)
{
// get users from database
return DataProvider.GetUsersPaged(SecurityContext.User.UserId, userId,
filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, false);
}
public static DataSet GetUsersPagedRecursive(int userId, string filterColumn, string filterValue,
int statusId, int roleId,
string sortColumn, int startRow, int maximumRows)
{
// get users from database
return DataProvider.GetUsersPaged(SecurityContext.User.UserId, userId,
filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, true);
}
public static DataSet GetUsersSummary(int userId)
{
return DataProvider.GetUsersSummary(SecurityContext.User.UserId, userId);
}
public static DataSet GetUserDomainsPaged(int userId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
// get users from database
return DataProvider.GetUserDomainsPaged(SecurityContext.User.UserId, userId,
filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
public static List<UserInfo> GetUserPeers(int userId)
{
// get user peers from database
return ObjectUtils.CreateListFromDataSet<UserInfo>(GetRawUserPeers(userId));
}
public static DataSet GetRawUserPeers(int userId)
{
// get user peers from database
return DataProvider.GetUserPeers(SecurityContext.User.UserId, userId);
}
public static DataSet GetRawUsers(int ownerId, bool recursive)
{
// get users from database
return DataProvider.GetUsers(SecurityContext.User.UserId, ownerId, recursive);
}
public static int AddUser(UserInfo user, bool sendLetter)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
string pattern = @"[\\/:*?<>|""]+";
if (String.IsNullOrEmpty(user.Username))
return BusinessErrorCodes.ERROR_INVALID_USER_NAME;
if (Regex.IsMatch(user.Username, pattern))
return BusinessErrorCodes.ERROR_INVALID_USER_NAME;
if (UserExists(user.Username))
return BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS;
// only administrators can set admin role
if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) &&
user.Role == UserRole.Administrator)
user.Role = UserRole.User;
// check integrity when creating a user account
if (user.Role == UserRole.User)
user.EcommerceEnabled = false;
// place log record
TaskManager.StartTask("USER", "ADD", user.Username);
try
{
// add user to database
int userId = DataProvider.AddUser(
SecurityContext.User.UserId,
user.OwnerId,
user.RoleId,
user.StatusId,
user.SubscriberNumber,
user.LoginStatusId,
user.IsDemo,
user.IsPeer,
user.Comments,
user.Username.Trim(),
CryptoUtils.Encrypt(user.Password),
user.FirstName,
user.LastName,
user.Email,
user.SecondaryEmail,
user.Address,
user.City,
user.Country,
user.State,
user.Zip,
user.PrimaryPhone,
user.SecondaryPhone,
user.Fax,
user.InstantMessenger,
user.HtmlMail,
user.CompanyName,
user.EcommerceEnabled);
if (userId == -1)
{
TaskManager.WriteWarning("Account with such username already exists");
return BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS;
}
TaskManager.ItemId = userId;
TaskManager.TaskParameters["SendLetter"] = sendLetter;
return userId;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
const string userAdditionalParamsTemplate = @"<Params><VLans/></Params>";
public static void AddUserVLan(int userId, UserVlan vLan)
{
UserInfo user = GetUser(userId);
//
if (user == null)
throw new ApplicationException(String.Format("User with UserID={0} not found", userId));
XDocument doc = XDocument.Parse(user.AdditionalParams ?? userAdditionalParamsTemplate);
XElement vlans = doc.Root.Element("VLans");
vlans.Add(new XElement("VLan", new XAttribute("VLanID", vLan.VLanID), new XAttribute("Comment", vLan.Comment)));
user.AdditionalParams = doc.ToString();
UpdateUser(user);
}
public static void DeleteUserVLan(int userId, ushort vLanId)
{
UserInfo user = GetUser(userId);
//
if (user == null)
throw new ApplicationException(String.Format("User with UserID={0} not found", userId));
XDocument doc = XDocument.Parse(user.AdditionalParams ?? userAdditionalParamsTemplate);
XElement vlans = doc.Root.Element("VLans");
if (vlans != null)
foreach (XElement element in vlans.Elements("VLan"))
if (ushort.Parse(element.Attribute("VLanID").Value) == vLanId)
element.Remove();
user.AdditionalParams = doc.ToString();
UpdateUser(user);
}
public static int UpdateUser(UserInfo user)
{
return UpdateUser(null, user);
}
public static int UpdateUserAsync(string taskId, UserInfo user)
{
UserAsyncWorker usersWorker = new UserAsyncWorker();
usersWorker.ThreadUserId = SecurityContext.User.UserId;
usersWorker.TaskId = taskId;
usersWorker.User = user;
usersWorker.UpdateUserAsync();
return 0;
}
public static int UpdateUser(string taskId, UserInfo user)
{
try
{
// start task
TaskManager.StartTask(taskId, "USER", "UPDATE", user.Username);
TaskManager.ItemId = user.UserId;
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
UserInfo currentUser = GetUser(user.UserId);
//prevent downgrade reseller with child accounts to user role
if (currentUser.RoleId.Equals(2))
{
if (user.RoleId.Equals(3))
{
// check if user has child accounts (It happens when Reseller has child accounts and admin changes his role to User)
if (GetUsers(currentUser.UserId, false).Count > 0)
return BusinessErrorCodes.ERROR_USER_HAS_USERS;
}
}
// only administrators can set admin role
if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) &&
user.Role == UserRole.Administrator)
user.Role = UserRole.User;
// check integrity when creating a user account
if (user.Role == UserRole.User)
user.EcommerceEnabled = false;
//// task progress
//int maxSteps = 100;
//TaskManager.IndicatorMaximum = maxSteps;
//for (int i = 0; i < maxSteps; i++)
//{
// TaskManager.Write(String.Format("Step {0} of {1}", i, maxSteps));
// TaskManager.IndicatorCurrent = i;
// System.Threading.Thread.Sleep(1000);
//}
DataProvider.UpdateUser(
SecurityContext.User.UserId,
user.UserId,
user.RoleId,
user.StatusId,
user.SubscriberNumber,
user.LoginStatusId,
user.IsDemo,
user.IsPeer,
user.Comments,
user.FirstName,
user.LastName,
user.Email,
user.SecondaryEmail,
user.Address,
user.City,
user.Country,
user.State,
user.Zip,
user.PrimaryPhone,
user.SecondaryPhone,
user.Fax,
user.InstantMessenger,
user.HtmlMail,
user.CompanyName,
user.EcommerceEnabled,
user.AdditionalParams);
return 0;
}
catch (System.Threading.ThreadAbortException ex)
{
TaskManager.WriteError(ex, "The process has been terminated by the user.");
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int DeleteUser(int userId)
{
return DeleteUser(null, userId);
}
public static int DeleteUser(string taskId, int userId)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// check if user has child accounts
if (GetUsers(userId, false).Count > 0)
return BusinessErrorCodes.ERROR_USER_HAS_USERS;
UserAsyncWorker userWorker = new UserAsyncWorker();
userWorker.ThreadUserId = SecurityContext.User.UserId;
userWorker.UserId = userId;
userWorker.TaskId = taskId;
userWorker.DeleteUserAsync();
return 0;
}
public static int ChangeUserPassword(int userId, string password)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// get user details
UserInfo user = GetUserInternally(userId);
// place log record
TaskManager.StartTask("USER", "CHANGE_PASSWORD", user.Username);
TaskManager.ItemId = user.UserId;
try
{
DataProvider.ChangeUserPassword(SecurityContext.User.UserId, userId,
CryptoUtils.Encrypt(password));
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static int ChangeUserStatus(int userId, UserStatus status)
{
return ChangeUserStatus(null, userId, status);
}
public static int ChangeUserStatus(string taskId, int userId, UserStatus status)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
int result = 0;
// get user details
UserInfo user = GetUserInternally(userId);
// place log record
TaskManager.StartTask(taskId, "USER", "CHANGE_STATUS", user.Username);
TaskManager.ItemId = user.UserId;
// update user packages
List<PackageInfo> packages = new List<PackageInfo>();
// Add the users package(s)
packages.AddRange(PackageController.GetPackages(userId));
try
{
// change this account
result = ChangeUserStatusInternal(userId, status);
if (result < 0)
return result;
// change peer accounts
List<UserInfo> peers = GetUserPeers(userId);
foreach (UserInfo peer in peers)
{
result = ChangeUserStatusInternal(peer.UserId, status);
if (result < 0)
return result;
}
// change child accounts
List<UserInfo> children = GetUsers(userId, true);
foreach (UserInfo child in children)
{
// Add the child users packages
packages.AddRange(PackageController.GetPackages(child.UserId));
// change child user peers
List<UserInfo> childPeers = GetUserPeers(child.UserId);
foreach (UserInfo peer in childPeers)
{
result = ChangeUserStatusInternal(peer.UserId, status);
if (result < 0)
return result;
}
// change child account
result = ChangeUserStatusInternal(child.UserId, status);
if (result < 0)
return result;
}
PackageStatus packageStatus = PackageStatus.Active;
switch (status)
{
case UserStatus.Active: packageStatus = PackageStatus.Active; break;
case UserStatus.Cancelled: packageStatus = PackageStatus.Cancelled; break;
case UserStatus.Pending: packageStatus = PackageStatus.New; break;
case UserStatus.Suspended: packageStatus = PackageStatus.Suspended; break;
}
// change packages state
result = PackageController.ChangePackagesStatus(packages, packageStatus, true);
if (result < 0)
return result;
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
private static int ChangeUserStatusInternal(int userId, UserStatus status)
{
// get user details
UserInfo user = GetUser(userId);
if (user != null && user.Status != status)
{
// change status
user.Status = status;
// save user
UpdateUser(user);
}
return 0;
}
#region User Settings
public static UserSettings GetUserSettings(int userId, string settingsName)
{
IDataReader reader = DataProvider.GetUserSettings(
SecurityContext.User.UserId, userId, settingsName);
UserSettings settings = new UserSettings();
settings.UserId = userId;
settings.SettingsName = settingsName;
while (reader.Read())
{
settings.UserId = (int)reader["UserID"];
settings[(string)reader["PropertyName"]] = (string)reader["PropertyValue"];
}
reader.Close();
return settings;
}
public static int UpdateUserSettings(UserSettings settings)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// get user details
UserInfo user = GetUserInternally(settings.UserId);
// place log record
TaskManager.StartTask("USER", "UPDATE_SETTINGS", user.Username);
TaskManager.ItemId = user.UserId;
try
{
// build xml
XmlDocument doc = new XmlDocument();
XmlElement nodeProps = doc.CreateElement("properties");
if (settings.SettingsArray != null)
{
foreach (string[] pair in settings.SettingsArray)
{
XmlElement nodeProp = doc.CreateElement("property");
nodeProp.SetAttribute("name", pair[0]);
nodeProp.SetAttribute("value", pair[1]);
nodeProps.AppendChild(nodeProp);
}
}
string xml = nodeProps.OuterXml;
// update settings
DataProvider.UpdateUserSettings(SecurityContext.User.UserId,
settings.UserId, settings.SettingsName, xml);
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
#endregion
}
}

View file

@ -1,85 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
using WebsitePanel.Providers.Virtualization;
namespace WebsitePanel.EnterpriseServer
{
public class CreateServerAsyncWorker
{
#region Properties
public int ThreadUserId { get; set; }
public string TaskId { get; set; }
public VirtualMachine Item { get; set; }
public LibraryItem OsTemplate { get; set; }
public int ExternalAddressesNumber { get; set; }
public bool RandomExternalAddresses { get; set; }
public int[] ExternalAddresses { get; set; }
public int PrivateAddressesNumber { get; set; }
public bool RandomPrivateAddresses { get; set; }
public string[] PrivateAddresses { get; set; }
public string SummaryLetterEmail { get; set; }
#endregion
public CreateServerAsyncWorker()
{
ThreadUserId = -1; // admin
}
#region Create
public void CreateAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Create));
t.Start();
}
private void Create()
{
// impersonate thread
if (ThreadUserId != -1)
SecurityContext.SetThreadPrincipal(ThreadUserId);
// perform backup
VirtualizationServerController.CreateVirtualMachineInternal(TaskId, Item, OsTemplate,
ExternalAddressesNumber, RandomExternalAddresses, ExternalAddresses,
PrivateAddressesNumber, RandomPrivateAddresses, PrivateAddresses,
SummaryLetterEmail);
}
#endregion
}
}

View file

@ -1,113 +0,0 @@
//using System;
//using System.Collections.Generic;
//using System.Web;
//using System.Threading;
//using System.ComponentModel;
//using WebsitePanel.Providers;
//using WebsitePanel.Providers.Common;
//using WebsitePanel.Providers.ResultObjects;
//using WebsitePanel.Providers.Virtualization;
//using WebsitePanel.Providers.VirtualizationForPC;
//namespace WebsitePanel.EnterpriseServer
//{
// public class CreateAsyncVMfromVM
// {
// public static void Run(string sourceVM, VMInfo vmInfo)
// {
// BackgroundWorker createVMBackground = new BackgroundWorker();
// ResultObject taskInfo = null;
// object[] parameters = { sourceVM, vmInfo };
// createVMBackground.DoWork += (sender, e) => {
// string sourceVMName = (string)((object[])e.Argument)[0];
// VMInfo vm = (VMInfo)((object[])e.Argument)[1];
// e.Result = vm;
// Guid taskGuid = Guid.NewGuid();
// // Add audit log
// taskInfo = TaskManager.StartResultTask<ResultObject>("VPSForPC", "CREATE", taskGuid);
// TaskManager.ItemId = vm.Id;
// TaskManager.ItemName = vm.Name;
// TaskManager.PackageId = vm.PackageId;
// e.Result = CreateVM(sourceVMName, vm, taskGuid);
// };
// createVMBackground.RunWorkerCompleted += (sender, e) => {
// if (e.Error != null || !String.IsNullOrEmpty(((VMInfo)e.Result).exMessage) )
// {
// if (taskInfo != null)
// {
// TaskManager.CompleteResultTask(taskInfo
// , VirtualizationErrorCodes.CREATE_ERROR
// , new Exception(((VMInfo)e.Result).exMessage)
// , ((VMInfo)e.Result).logMessage);
// }
// }
// else
// {
// if (taskInfo != null)
// {
// TaskManager.CompleteResultTask(taskInfo, null, null, ((VMInfo)e.Result).logMessage);
// }
// PackageController.UpdatePackageItem((VMInfo)e.Result);
// }
// };
// createVMBackground.RunWorkerAsync(parameters);
// }
// private static VMInfo CreateVM(string sourceVMName, VMInfo vmInfo, Guid taskGuid)
// {
// VirtualizationServerForPC ws = new VirtualizationServerForPC();
// ServiceProviderProxy.Init(ws, vmInfo.ServiceId);
// vmInfo = ws.CreateVMFromVM(sourceVMName, vmInfo, taskGuid);
// return vmInfo;
// }
// }
//}
using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
using WebsitePanel.Providers.Virtualization;
using WebsitePanel.Providers.VirtualizationForPC;
namespace WebsitePanel.EnterpriseServer
{
public class CreateVMFromVMAsyncWorker
{
public int ThreadUserId { get; set; }
public VMInfo vmTemplate {get; set; }
public string vmName { get; set; }
public int packageId { get; set; }
public CreateVMFromVMAsyncWorker()
{
ThreadUserId = -1; // admin
}
public void CreateAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Create));
t.Start();
}
private void Create()
{
// impersonate thread
if (ThreadUserId != -1)
SecurityContext.SetThreadPrincipal(ThreadUserId);
// perform backup
VirtualizationServerControllerForPrivateCloud.CreateVMFromVMAsunc(packageId, vmTemplate, vmName);
}
}
}

View file

@ -1,65 +0,0 @@
// Copyright (c) 2012, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
using WebsitePanel.Providers.Virtualization;
using WebsitePanel.Providers.VirtualizationForPC;
namespace WebsitePanel.EnterpriseServer
{
public class CreateVMAsyncWorker
{
public int ThreadUserId { get; set; }
public VMInfo vmTemplate { get; set; }
public CreateVMAsyncWorker()
{
ThreadUserId = -1; // admin
}
public void CreateAsync()
{
// start asynchronously
Thread t = new Thread(new ThreadStart(Create));
t.Start();
}
private void Create()
{
// impersonate thread
if (ThreadUserId != -1)
SecurityContext.SetThreadPrincipal(ThreadUserId);
// perform backup
VirtualizationServerControllerForPrivateCloud.CreateVirtualMachineAsunc(vmTemplate);
}
}
}

Some files were not shown because too many files have changed in this diff Show more