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); } }
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(SystemUser)) { // import user SystemUser user = new SystemUser(); user.ServiceId = serviceId; user.PackageId = packageId; user.Name = itemName; user.Password = ""; user.GroupName = group.GroupName; PackageController.AddPackageItem(user); } else if (itemType == typeof(SystemGroup)) { // import group SystemGroup spGroup = new SystemGroup(); spGroup.ServiceId = serviceId; spGroup.PackageId = packageId; spGroup.Name = itemName; spGroup.GroupName = group.GroupName; PackageController.AddPackageItem(spGroup); } }
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); }
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); } }
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); }
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 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); } }
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); // 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); }
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); } }
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); } }
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)) { // Get ascii form in punycode var zoneName = GetAsciiZoneName(itemName); // add DNS zone DnsZone zone = new DnsZone(); zone.Name = zoneName; zone.ServiceId = serviceId; zone.PackageId = packageId; int zoneId = PackageController.AddPackageItem(zone); // Add secondary zone(s) try { // get secondary DNS services var primSettings = ServerController.GetServiceSettings(serviceId); var secondaryServiceIds = new List<int>(); var strSecondaryServices = primSettings["SecondaryDNSServices"]; if (!String.IsNullOrEmpty(strSecondaryServices)) { var secondaryServices = strSecondaryServices.Split(','); secondaryServiceIds.AddRange(secondaryServices.Select(strSecondaryId => Utils.ParseInt(strSecondaryId, 0)).Where(secondaryId => secondaryId != 0)); } // add secondary zones var secondaryZoneFound = false; foreach (var secondaryId in secondaryServiceIds) { var secDns = GetDNSServer(secondaryId); if (secDns.ZoneExists(zoneName)) { secondaryZoneFound = true; var secondaryZone = new SecondaryDnsZone { Name = zoneName, ServiceId = secondaryId, PackageId = packageId }; PackageController.AddPackageItem(secondaryZone); } } if (!secondaryZoneFound) { TaskManager.WriteWarning("No secondary zone(s) found when importing zone " + itemName); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing secondary zone(s)"); } // add/update domains/pointers RestoreDomainByZone(itemName, packageId, zoneId); } }
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 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 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 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 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, 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); } } BackgroundTask topTask = TaskManager.TopTask; topTask.IndicatorCurrent = topTask.IndicatorMaximum; TaskController.UpdateTask(topTask); } catch (Exception ex) { TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } return(0); }
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 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; // Mail provider MailServer mail = new MailServer(); ServiceProviderProxy.Init(mail, serviceId); if (itemType == typeof(MailDomain)) { QuotaLimit result = IsQuotasWillExceed(packageId, mail, itemName); //in case quotas will exceed the space - exit the import function if (result.IsExceeded) { if (result.Message.Equals("Mail_Domain")) { const string exceededQuota = "number of domains"; TaskManager.WriteWarning( String.Format( "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}." , itemName, exceededQuota ) ); return; } if (result.Message.Equals("Mail_Account")) { const string exceededQuota = "number of mail accounts"; TaskManager.WriteWarning( String.Format( "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}." , itemName, exceededQuota ) ); return; } if (result.Message.Equals("Mail_Group")) { const string exceededQuota = "number of groups"; TaskManager.WriteWarning( String.Format( "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}." , itemName, exceededQuota ) ); return; } if (result.Message.Equals("Mail_List")) { const string exceededQuota = "number of mail lists"; TaskManager.WriteWarning( String.Format( "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}." , itemName, exceededQuota ) ); return; } } List<string> domains = new List<string>(); domains.Add(itemName); try { domains.AddRange(mail.GetDomainAliases(itemName)); } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing mail domain - skipped"); return; } MailDomain mailDomain = new MailDomain(); mailDomain.Name = itemName; mailDomain.ServiceId = serviceId; mailDomain.PackageId = packageId; int mailDomainId = PackageController.AddPackageItem(mailDomain); // restore domains RestoreDomainsByMail(domains, packageId, mailDomainId); // add mail accounts try { MailAccount[] accounts = mail.GetAccounts(itemName); foreach (MailAccount account in accounts) { account.ServiceId = serviceId; account.PackageId = packageId; //get mail account password account.Password = CryptoUtils.Encrypt(account.Password); PackageController.AddPackageItem(account); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing mail account"); } //add mail aliases (forwardings) try { MailAlias[] aliases = mail.GetMailAliases(itemName); foreach (MailAlias alias in aliases) { alias.ServiceId = serviceId; alias.PackageId = packageId; PackageController.AddPackageItem(alias); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing mail aliases"); } // add mail groups try { MailGroup[] groups = mail.GetGroups(itemName); foreach (MailGroup mailGroup in groups) { mailGroup.ServiceId = serviceId; mailGroup.PackageId = packageId; PackageController.AddPackageItem(mailGroup); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing mail group"); } // add mail lists try { MailList[] lists = mail.GetLists(itemName); foreach (MailList list in lists) { list.ServiceId = serviceId; list.PackageId = packageId; PackageController.AddPackageItem(list); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing mail list"); } } }
public int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group) { if (item is MailDomain) { // backup mail domain MailServer mail = GetMailServer(item.ServiceId); // read domain info MailDomain domain = mail.GetDomain(item.Name); XmlSerializer serializer = new XmlSerializer(typeof(MailDomain)); serializer.Serialize(writer, domain); XmlSerializer accountSerializer = new XmlSerializer(typeof(MailAccount)); XmlSerializer groupSerializer = new XmlSerializer(typeof(MailGroup)); XmlSerializer listSerializer = new XmlSerializer(typeof(MailList)); // get domain aliases string[] aliases = mail.GetDomainAliases(item.Name); foreach (string alias in aliases) writer.WriteElementString("Alias", alias); // get domain accounts List<ServiceProviderItem> accounts = PackageController.GetPackageItemsByName( item.PackageId, "%@" + item.Name); // backup accounts foreach (ServiceProviderItem domainItem in accounts) { if (domainItem is MailAccount || domainItem is MailAlias) { MailAccount account = mail.GetAccount(domainItem.Name); account.Password = ((MailAccount)domainItem).Password; account.DeleteOnForward = domainItem is MailAlias; accountSerializer.Serialize(writer, account); } else if (domainItem is MailGroup) { MailGroup mailGroup = mail.GetGroup(domainItem.Name); groupSerializer.Serialize(writer, mailGroup); } else if (domainItem is MailList) { MailList list = mail.GetList(domainItem.Name); list.Password = ((MailList)domainItem).Password; listSerializer.Serialize(writer, list); } } } return 0; }
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 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 MailServer mail = new MailServer(); ServiceProviderProxy.Init(mail, serviceId); if (itemType == typeof(MailDomain)) items.AddRange(mail.GetDomains()); return items; }
public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group) { if (itemType == typeof(SystemUser)) { SharePointServer sps = GetSharePoint(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(SystemUser)); SystemUser user = (SystemUser)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("SystemUser"))); // create user if required if (!sps.UserExists(itemName)) { user.Password = CryptoUtils.Decrypt(user.Password); sps.CreateUser(user); // restore password user.Password = CryptoUtils.Encrypt(user.Password); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemUser)) == null) { user.PackageId = packageId; user.ServiceId = serviceId; PackageController.AddPackageItem(user); } } else if (itemType == typeof(SystemGroup)) { SharePointServer sps = GetSharePoint(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(SystemGroup)); SystemGroup sysGroup = (SystemGroup)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("SystemGroup"))); // create user if required if (!sps.GroupExists(itemName)) { sps.CreateGroup(sysGroup); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemGroup)) == null) { sysGroup.PackageId = packageId; sysGroup.ServiceId = serviceId; PackageController.AddPackageItem(sysGroup); } } return(0); }
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 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); }
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; WebServer web = GetWebServer(serviceId); if (itemType == typeof(WebSite)) items.AddRange(web.GetSites()); return items; }
public int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group) { if (itemType == typeof(MailDomain)) { MailServer mail = GetMailServer(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(MailDomain)); MailDomain domain = (MailDomain)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("MailDomain"))); // create mail domain if required List<string> domains = new List<string>(); if (!mail.DomainExists(domain.Name)) { mail.CreateDomain(domain); domains.Add(domain.Name); // add domain aliases foreach (XmlNode aliasNode in itemNode.SelectNodes("Alias")) { mail.AddDomainAlias(domain.Name, aliasNode.InnerText); domains.Add(aliasNode.InnerText); } } // add meta-item if required int mailDomainId = 0; MailDomain existDomain = (MailDomain)PackageController.GetPackageItemByName(packageId, itemName, typeof(MailDomain)); if (existDomain == null) { domain.PackageId = packageId; domain.ServiceId = serviceId; mailDomainId = PackageController.AddPackageItem(domain); } else { mailDomainId = existDomain.Id; } // restore domains RestoreDomainsByMail(domains, packageId, mailDomainId); XmlSerializer accountSerializer = new XmlSerializer(typeof(MailAccount)); XmlSerializer groupSerializer = new XmlSerializer(typeof(MailGroup)); XmlSerializer listSerializer = new XmlSerializer(typeof(MailList)); // restore accounts foreach (XmlNode accountNode in itemNode.SelectNodes("MailAccount")) { MailAccount account = (MailAccount)accountSerializer.Deserialize(new XmlNodeReader(accountNode)); if (!mail.AccountExists(account.Name)) { account.Password = CryptoUtils.Decrypt(account.Password); mail.CreateAccount(account); // restore password account.Password = CryptoUtils.Encrypt(account.Password); } // add meta-item if required if (account.DeleteOnForward && PackageController.GetPackageItemByName(packageId, account.Name, typeof(MailAlias)) == null) { MailAlias forw = new MailAlias(); forw.PackageId = packageId; forw.ServiceId = serviceId; forw.Name = account.Name; PackageController.AddPackageItem(forw); } else if (!account.DeleteOnForward && PackageController.GetPackageItemByName(packageId, account.Name, typeof(MailAccount)) == null) { account.PackageId = packageId; account.ServiceId = serviceId; PackageController.AddPackageItem(account); } } // restore groups foreach (XmlNode groupNode in itemNode.SelectNodes("MailGroup")) { MailGroup mailGroup = (MailGroup)groupSerializer.Deserialize(new XmlNodeReader(groupNode)); if (!mail.GroupExists(mailGroup.Name)) { mail.CreateGroup(mailGroup); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, mailGroup.Name, typeof(MailGroup)) == null) { mailGroup.PackageId = packageId; mailGroup.ServiceId = serviceId; PackageController.AddPackageItem(mailGroup); } } // restore lists foreach (XmlNode listNode in itemNode.SelectNodes("MailList")) { MailList list = (MailList)listSerializer.Deserialize(new XmlNodeReader(listNode)); if (!mail.ListExists(list.Name)) { list.Password = CryptoUtils.Decrypt(list.Password); mail.CreateList(list); // restore password list.Password = CryptoUtils.Encrypt(list.Password); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, list.Name, typeof(MailList)) == null) { list.PackageId = packageId; list.ServiceId = serviceId; PackageController.AddPackageItem(list); } } } return 0; }
public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group) { if (item is WebSite) { WebServer web = GetWebServer(item.ServiceId); // read web site WebSite itemSite = item as WebSite; string siteId = itemSite.SiteId; WebSite site = web.GetSite(siteId); site.SiteId = itemSite.SiteId; site.SiteIPAddressId = itemSite.SiteIPAddressId; site.DataPath = itemSite.DataPath; site.FrontPageAccount = itemSite.FrontPageAccount; site.FrontPagePassword = itemSite.FrontPagePassword; // serialize web site XmlSerializer serializer = new XmlSerializer(typeof(WebSite)); serializer.Serialize(writer, site); // process virtual directories WebVirtualDirectory[] vdirs = web.GetVirtualDirectories(siteId); foreach (WebVirtualDirectory vdirShort in vdirs) { WebVirtualDirectory vdir = web.GetVirtualDirectory(siteId, vdirShort.Name); // serialize vdir serializer = new XmlSerializer(typeof(WebVirtualDirectory)); serializer.Serialize(writer, vdir); } } else if (item is SharedSSLFolder) { SharedSSLFolder sslFolder = GetSharedSSLFolder(item.Id); // convert content path to physical sslFolder.ContentPath = FilesController.GetFullPackagePath(item.PackageId, sslFolder.ContentPath); XmlSerializer serializer = new XmlSerializer(typeof(SharedSSLFolder)); serializer.Serialize(writer, sslFolder); } return 0; }
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 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); // Is it DNS Zones? Then create a IDN Mapping object var isDnsZones = group.GroupName == "DNS"; var idn = new IdnMapping(); // 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) { var itemToImport = importableItem; // For DNS zones the compare has been made using ascii, convert to unicode if necessary to make the list of items easier to read if (isDnsZones && itemToImport.StartsWith("xn--")) { itemToImport = idn.GetUnicode(importableItem); } items.Add(itemToImport); } } } catch { /* do nothing */ } } else { return(GetImportableCustomItems(packageId, itemTypeId)); } 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); } }
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); }
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 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); } SharePointServer sps = GetSharePoint(serviceId); if (itemType == typeof(SystemUser)) { items.AddRange(sps.GetUsers()); } else if (itemType == typeof(SystemGroup)) { items.AddRange(sps.GetGroups()); } return(items); }
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; }
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); }
public IntResult SaveStorageSpaceLevel(StorageSpaceLevel level, ResourceGroupInfo[] groups) { object[] results = this.Invoke("SaveStorageSpaceLevel", new object[] { level, groups}); return ((IntResult)(results[0])); }
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); } }
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 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); // IDN: The list of importable names is populated with unicode names, to make it easier for the user var idn = new IdnMapping(); if (itemType == typeof(DnsZone)) items.AddRange(dns.GetZones()); return items; }
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 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; }
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 void ImportItem(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group, string itemName) { // Controller supports web sites only if (itemType != typeof(WebSite)) return; // Get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return; // WebServer web = GetWebServer(serviceId); // Obtaining web site unique id string siteId = web.GetSiteId(itemName); if (siteId == null) return; // Obtaining OperatingSystem service provider id within the context of package. int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os); if (osServiceId == 0) return; // OS.OperatingSystem os = new OS.OperatingSystem(); ServiceProviderProxy.Init(os, osServiceId); // get site info WebSite site = web.GetSite(siteId); PackageIPAddress ipMatch = default(PackageIPAddress); #region Resolving web site ip // Loading package context to evaluate IP Addresses quota PackageContext packageCtx = PackageController.GetPackageContext(packageId); // We are unable to step further because there are // no bindings on the web site to choose from if (site.Bindings == null || site.Bindings.Length == 0) { TaskManager.WriteError("Could not import the web site because it has no bindings assigned."); return; } // Loading service provider settings StringDictionary webSettings = ServerController.GetServiceSettings(serviceId); int sharedIpId = Utils.ParseInt(webSettings["SharedIP"], 0); IPAddressInfo sharedIp = ServerController.GetIPAddress(sharedIpId); // Trying to match site's bindings to against either // external or internal address of the shared ip bool sharedIpMatch = Array.Exists(site.Bindings, x => sharedIp != null && (x.IP.Equals(sharedIp.ExternalIP) || x.IP.Equals(sharedIp.InternalIP))); // Quering dedicated ips package quota allotted bool dedicatedIpsAllotted = Array.Exists(packageCtx.QuotasArray, x => x.QuotaName == Quotas.WEB_IP_ADDRESSES && x.QuotaAllocatedValue != 0); // By default we fallback to the service provider's shared ip, // so the web site being imported is "hooked up" to the proper ip, // even if current bindings match different ip for some reason if (!dedicatedIpsAllotted || sharedIpMatch) { site.SiteIPAddressId = sharedIpId; } // Trying to find a match in dedicated ips list if any. if (dedicatedIpsAllotted && !sharedIpMatch) { // Obtaining first binding with non-empty ip ServerBinding binding = Array.Find<ServerBinding>(site.Bindings, x => !String.IsNullOrEmpty(x.IP)); // No bindings were found - throw an exception if (binding == null) { TaskManager.WriteError(@"Could not import the web site because IP address field of all of its bindings is empty. Please ensure the web site has been assigned bindings in the appropriate format and then try to run import procedure once again."); return; } // ServiceInfo webService = ServerController.GetServiceInfo(serviceId); // Loading ip addresses from Web Sites address pool related to the package List<PackageIPAddress> ips = ServerController.GetPackageUnassignedIPAddresses(packageId, IPAddressPool.WebSites); // Looking for an entry matching by package and external/internal ip ipMatch = Array.Find<PackageIPAddress>(ips.ToArray(), x => x.ExternalIP == binding.IP || x.InternalIP == binding.IP); // No match has been found - we are in a fault state if (ipMatch == null) { TaskManager.WriteError(@"Could not import the web site because no dedicated IP address match in the target space has been found. Please ensure the space has been allocated {0} IP address as a dedicated one and it is free. Then try to run import procedure once again.", binding.IP); return; } // site.SiteIPAddressId = ipMatch.AddressID; } #endregion // folders UserInfo user = PackageController.GetPackageOwner(packageId); UserSettings webPolicy = UserController.GetUserSettings(user.UserId, UserSettings.WEB_POLICY); string packageHome = FilesController.GetHomeFolder(packageId); // add random string to the domain if specified string randDomainName = itemName; if (!String.IsNullOrEmpty(webPolicy["AddRandomDomainString"]) && Utils.ParseBool(webPolicy["AddRandomDomainString"], false)) randDomainName += "_" + Utils.GetRandomString(DOMAIN_RANDOM_LENGTH); // ROOT folder string contentPath = GetWebFolder(packageId, WEBSITE_ROOT_FOLDER_PATTERN, randDomainName); if (!String.IsNullOrEmpty(webPolicy["WebRootFolder"])) contentPath = GetWebFolder(packageId, webPolicy["WebRootFolder"], randDomainName); // LOGS folder string logsPath = GetWebFolder(packageId, WEBSITE_LOGS_FOLDER_PATTERN, randDomainName); if (!String.IsNullOrEmpty(webPolicy["WebLogsFolder"])) logsPath = GetWebFolder(packageId, webPolicy["WebLogsFolder"], randDomainName); // DATA folder string dataPath = GetWebFolder(packageId, WEBSITE_DATA_FOLDER_PATTERN, randDomainName); if (!String.IsNullOrEmpty(webPolicy["WebDataFolder"])) dataPath = GetWebFolder(packageId, webPolicy["WebDataFolder"], randDomainName); // copy site files try { os.CopyFile(site.ContentPath, contentPath); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't copy web site files"); } // copy site logs try { string logFolder = (site.IIs7) ? site[WebSite.IIS7_SITE_ID] : "W3SVC" + siteId; string logsSrcFolder = Path.Combine(site.LogsPath, logFolder); if (os.DirectoryExists(logsSrcFolder)) os.CopyFile(logsSrcFolder, Path.Combine(logsPath, logFolder)); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't copy web site log files"); } // set new folders site.ContentPath = contentPath; site.LogsPath = logsPath; site.DataPath = dataPath; // update web site web.UpdateSite(site); // process virtual directories WebVirtualDirectory[] virtDirs = web.GetVirtualDirectories(siteId); foreach (WebVirtualDirectory virtDirPointer in virtDirs) { try { // load virtual directory WebVirtualDirectory virtDir = web.GetVirtualDirectory(siteId, virtDirPointer.Name); // copy directory files string vdirPath = Path.Combine(contentPath, virtDir.Name); os.CopyFile(virtDir.ContentPath, vdirPath); virtDir.ContentPath = vdirPath; // update directory web.UpdateVirtualDirectory(siteId, virtDir); } catch (Exception ex) { TaskManager.WriteError(ex, String.Format("Error importing '{0}' virtual directory", virtDirPointer.Name)); continue; } } // import web site site.ServiceId = serviceId; site.PackageId = packageId; site.Name = itemName; site.SiteId = siteId; int webSiteId = PackageController.AddPackageItem(site); // Assign dedicated IP address to the web site from package context. if (ipMatch != null) { ServerController.AddItemIPAddress(webSiteId, ipMatch.PackageAddressID); } // restore/update domains RestoreDomainsByWebSite(site.Bindings, packageId, webSiteId, itemName); }
public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group) { if (item is SystemUser) { // backup system user SharePointServer sps = GetSharePoint(item.ServiceId); // read user info SystemUser user = sps.GetUser(item.Name); user.Password = ((SystemUser)item).Password; XmlSerializer serializer = new XmlSerializer(typeof(SystemUser)); serializer.Serialize(writer, user); } else if (item is SystemGroup) { // backup system group SharePointServer sps = GetSharePoint(item.ServiceId); // read site info SystemGroup sysGroup = sps.GetGroup(item.Name); XmlSerializer serializer = new XmlSerializer(typeof(SystemGroup)); serializer.Serialize(writer, group); } 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(WebSite)) { WebServer web = GetWebServer(serviceId); // restore web site XmlSerializer serializer = new XmlSerializer(typeof(WebSite)); WebSite site = (WebSite)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("WebSite"))); // create site if required if (!web.SiteExists(site.SiteId)) { web.CreateSite(site); // install FPSE if required if (site.FrontPageInstalled && !web.IsFrontPageInstalled(site.SiteId)) { web.InstallFrontPage(site.SiteId, site.FrontPageAccount, CryptoUtils.Decrypt(site.FrontPagePassword)); } } // restore virtual directories foreach (XmlNode vdirNode in itemNode.SelectNodes("WebVirtualDirectory")) { // deserialize vdir serializer = new XmlSerializer(typeof(WebVirtualDirectory)); WebVirtualDirectory vdir = (WebVirtualDirectory)serializer.Deserialize( new XmlNodeReader(vdirNode)); if (!web.VirtualDirectoryExists(site.SiteId, vdir.Name)) { web.CreateVirtualDirectory(site.SiteId, vdir); } } // add meta-item if required int webSiteId = 0; WebSite existItem = (WebSite)PackageController.GetPackageItemByName(packageId, itemName, typeof(WebSite)); if (existItem == null) { site.PackageId = packageId; site.ServiceId = serviceId; webSiteId = PackageController.AddPackageItem(site); } else { webSiteId = existItem.Id; } // restore/update domains RestoreDomainsByWebSite(site.Bindings, packageId, webSiteId, itemName); } else if (itemType == typeof(SharedSSLFolder)) { WebServer web = GetWebServer(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(SharedSSLFolder)); SharedSSLFolder sslFolder = (SharedSSLFolder)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("SharedSSLFolder"))); // create vdir if required int idx = sslFolder.Name.LastIndexOf("/"); string domainName = sslFolder.Name.Substring(0, idx); string vdirName = sslFolder.Name.Substring(idx + 1); string siteId = web.GetSiteId(domainName); if (siteId == null) return -1; if (!web.VirtualDirectoryExists(siteId, vdirName)) { web.CreateVirtualDirectory(siteId, sslFolder); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SharedSSLFolder)) == null) { sslFolder.PackageId = packageId; sslFolder.ServiceId = serviceId; PackageController.AddPackageItem(sslFolder); } } return 0; }
/// <remarks/> public System.IAsyncResult BeginSaveLevelResourceGroups(int levelId, ResourceGroupInfo[] newGroups, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SaveLevelResourceGroups", new object[] { levelId, newGroups}, callback, asyncState); }
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, 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); }
/// <remarks/> public void SaveLevelResourceGroupsAsync(int levelId, ResourceGroupInfo[] newGroups) { this.SaveLevelResourceGroupsAsync(levelId, newGroups, null); }
public static int ImportItemsInternal(string taskId, int packageId, string[] items) { PackageInfo package = PackageController.GetPackage(packageId); TaskManager.StartTask(taskId, "IMPORT", "IMPORT", package.PackageName, 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); }
/// <remarks/> public void SaveLevelResourceGroupsAsync(int levelId, ResourceGroupInfo[] newGroups, object userState) { if ((this.SaveLevelResourceGroupsOperationCompleted == null)) { this.SaveLevelResourceGroupsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSaveLevelResourceGroupsOperationCompleted); } this.InvokeAsync("SaveLevelResourceGroups", new object[] { levelId, newGroups}, this.SaveLevelResourceGroupsOperationCompleted, userState); }
/// <remarks/> public System.IAsyncResult BeginSaveStorageSpaceLevel(StorageSpaceLevel level, ResourceGroupInfo[] groups, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SaveStorageSpaceLevel", new object[] { level, groups}, callback, asyncState); }
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(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); }
/// <remarks/> public void SaveStorageSpaceLevelAsync(StorageSpaceLevel level, ResourceGroupInfo[] groups) { this.SaveStorageSpaceLevelAsync(level, groups, null); }
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); } }
/// <remarks/> public void SaveStorageSpaceLevelAsync(StorageSpaceLevel level, ResourceGroupInfo[] groups, object userState) { if ((this.SaveStorageSpaceLevelOperationCompleted == null)) { this.SaveStorageSpaceLevelOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSaveStorageSpaceLevelOperationCompleted); } this.InvokeAsync("SaveStorageSpaceLevel", new object[] { level, groups}, this.SaveStorageSpaceLevelOperationCompleted, userState); }
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; }
public ResultObject SaveLevelResourceGroups(int levelId, ResourceGroupInfo[] newGroups) { object[] results = this.Invoke("SaveLevelResourceGroups", new object[] { levelId, newGroups}); return ((ResultObject)(results[0])); }