public static ResultObject UpdateOrganizationServicePlan(int itemId, int newServiceId)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "UPDATE_SERVICE");
                TaskManager.WriteParameter("itemId", itemId);
                TaskManager.WriteParameter("newServiceId", newServiceId);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(item.ServiceId);

                // load service settings to know ProgramID, OfferID
                StringDictionary serviceSettings = ServerController.GetServiceSettings(newServiceId);
                string           programId       = serviceSettings["programID"];
                string           offerId         = serviceSettings["offerID"];

                // check settings
                if (String.IsNullOrEmpty(programId))
                {
                    result.ErrorCodes.Add(ProgramIdIsNotSetError);
                }
                if (String.IsNullOrEmpty(offerId))
                {
                    result.ErrorCodes.Add(OfferIdIsNotSetError);
                }

                // update service plan
                exchange.UpdateOrganizationServicePlan(item.Name, programId, offerId);

                // move item between services
                int moveResult = PackageController.MovePackageItem(itemId, newServiceId);
                if (moveResult < 0)
                {
                    return(Error <ResultObject>((-moveResult).ToString()));
                }

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(UpdateServicePlanError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Пример #2
0
        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, zoneItemId);
                //
                try
                {
                    // 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);

                    // Delete also all seconday service items
                    var zoneItems = PackageController.GetPackageItemsByType(zoneItem.PackageId, ResourceGroups.Dns, typeof(SecondaryDnsZone));

                    foreach (var item in zoneItems.Where(z => z.Name == zoneItem.Name))
                    {
                        PackageController.DeletePackageItem(item.Id);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex);
                }
                finally
                {
                    TaskManager.CompleteTask();
                }
            }
            //
            return(0);
        }
Пример #3
0
        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);
        }
        public static ResultObject UpdateOrganizationCatchAllAddress(int itemId, string catchAllEmail)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "UPDATE_CATCHALL");
                TaskManager.WriteParameter("itemId", itemId);
                TaskManager.WriteParameter("catchAllEmail", catchAllEmail);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(item.ServiceId);

                // update catch-all
                exchange.UpdateOrganizationCatchAllAddress(item.Name, catchAllEmail);

                // save new catch-all in the item
                item.CatchAllAddress = catchAllEmail;
                PackageController.UpdatePackageItem(item);

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(UpdateCatchAllError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        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 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();
            }
        }
Пример #7
0
        public static int ZipRemoteFiles(int packageId, string rootFolder, string[] files, string archivePath)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            // check package
            int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);

            if (packageCheck < 0)
            {
                return(packageCheck);
            }

            // place log record
            TaskManager.StartTask("FILES", "ZIP_FILES", archivePath);
            TaskManager.ItemId = packageId;
            if (files != null)
            {
                foreach (string file in files)
                {
                    TaskManager.Write(file);
                }
            }

            try
            {
                OS.OperatingSystem os          = GetOS(packageId);
                string             zipFilePath = GetFullPackagePath(packageId, archivePath);

                List <string> archFiles = new List <string>();
                string        root      = String.IsNullOrEmpty(rootFolder) ? "" : GetFullPackagePath(packageId, rootFolder);
                foreach (string file in files)
                {
                    string archFile = GetFullPackagePath(packageId, file);
                    if (!String.IsNullOrEmpty(rootFolder))
                    {
                        archFiles.Add(archFile.Substring(root.Length + 1));
                    }
                    else
                    {
                        int idx = archFile.LastIndexOf("\\");
                        root = archFile.Substring(0, idx);
                        archFiles.Add(archFile.Substring(idx + 1));
                    }
                }

                os.ZipFiles(zipFilePath, root, archFiles.ToArray());

                return(0);
            }
            catch (Exception ex)
            {
                //Log and return a generic error rather than throwing an exception
                TaskManager.WriteError(ex);
                return(BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED);
            }
            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, 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();
            }
        }
Пример #9
0
        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> >();

            // sort by groups
            foreach (string item in items)
            {
                string[] itemParts  = item.Split('|');
                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);
            }

            // 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 */ }
            }

            TaskManager.CompleteTask();

            return(0);
        }
Пример #10
0
        public static int MoveFiles(int packageId, string[] files, string destFolder)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            // check dest folder exists
            if (!DirectoryExists(packageId, destFolder))
            {
                return(BusinessErrorCodes.ERROR_FILE_DEST_FOLDER_NONEXISTENT);
            }

            // place log record
            TaskManager.StartTask("FILES", "MOVE_FILES");
            TaskManager.ItemId = packageId;
            TaskManager.WriteParameter("Destination folder", destFolder);
            if (files != null)
            {
                foreach (string file in files)
                {
                    TaskManager.Write(file);
                }
            }

            try
            {
                OS.OperatingSystem os             = GetOS(packageId);
                string             destFullFolder = GetFullPackagePath(packageId, destFolder);

                for (int i = 0; i < files.Length; i++)
                {
                    string srcFilePath  = GetFullPackagePath(packageId, files[i]);
                    string destFilePath = Path.Combine(destFullFolder,
                                                       srcFilePath.Substring(srcFilePath.LastIndexOf("\\") + 1));
                    if (srcFilePath == destFilePath)
                    {
                        return(BusinessErrorCodes.ERROR_FILE_COPY_TO_SELF);
                    }
                    //Check that we're not trying to copy a folder into its own subfolder
                    else if (destFilePath.StartsWith(srcFilePath + "\\"))
                    {
                        return(BusinessErrorCodes.ERROR_FILE_COPY_TO_OWN_SUBFOLDER);
                    }
                    else if (os.FileExists(destFilePath) || os.DirectoryExists(destFilePath))
                    {
                        return(BusinessErrorCodes.ERROR_FILE_MOVE_PATH_ALREADY_EXISTS);
                    }
                    else
                    {
                        os.MoveFile(srcFilePath, destFilePath);
                    }
                }

                return(0);
            }
            catch (Exception ex)
            {
                //Log and return a generic error rather than throwing an exception
                TaskManager.WriteError(ex);
                return(BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static StringResultObject Install(int packageId, string webAppId, string siteName, string virtualDir, List <DeploymentParameter> parameters)
        {
            StringResultObject result = new StringResultObject();

            try
            {
                // database operation results
                int databaseResult     = -1;
                int databaseUserResult = -1;

                // initialize task manager
                TaskManager.StartTask(TASK_MANAGER_SOURCE, "INSTALL_WEB_APP");
                TaskManager.WriteParameter("Package ID", packageId);
                TaskManager.WriteParameter("Site Name", siteName);

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <StringResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <StringResultObject>((-packageCheck).ToString()));
                }
                #endregion

                #region Check MS Deploy, web site and application pack
                // get target web server
                WebServer webServer = GetAssociatedWebServer(packageId);

                // Check if Web App Gallery is installed
                if (!webServer.IsMsDeployInstalled())
                {
                    return(Error <StringResultObject>(GalleryErrors.MsDeployIsNotInstalled));
                }

                // Check web site for existence
                WebSite webSite = WebServerController.GetWebSite(packageId, siteName);
                if (webSite == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.WebSiteNotFound, siteName));
                }

                // get application pack details
                GalleryApplicationResult app = webServer.GetGalleryApplication(webAppId);
                if (!app.IsSuccess)
                {
                    return(Error <StringResultObject>(app, GalleryErrors.GeneralError));
                }
                if (app.Value == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.WebApplicationNotFound, webAppId));
                }
                #endregion

                #region Trace app details

                // Assign web app pack title to the currently running task
                TaskManager.ItemName = app.Value.Title;

                // Trace additional details from the feed
                TaskManager.WriteParameter("Title", app.Value.Title);
                TaskManager.WriteParameter("Version", app.Value.Version);
                TaskManager.WriteParameter("Download URL", app.Value.DownloadUrl);
                TaskManager.WriteParameter("Author", app.Value.AuthorName);
                TaskManager.WriteParameter("Last Updated", app.Value.LastUpdated);

                // Trace out all deployment parameters
                Array.ForEach <DeploymentParameter>(parameters.ToArray(), p => TaskManager.WriteParameter(p.Name, p.Value));
                #endregion

                // elevate security context
                SecurityContext.SetThreadSupervisorPrincipal();

                #region Set AppPath
                // set correct application path
                DeploymentParameter appPath = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.IisApp);
                if (appPath == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.AppPathParameterNotFound));
                }

                appPath.Value = String.IsNullOrEmpty(virtualDir) ? siteName : String.Format("{0}/{1}", siteName, virtualDir);
                #endregion

                // database context
                // find database resource parameter
                DeploymentParameter databaseResoure = parameters.Find(p =>
                {
                    return(p.Name == DeploymentParameter.ResourceGroupParameterName);
                });

                // database is required for this application
                if (databaseResoure != null)
                {
                    // try to get database service
                    int dbServiceId = PackageController.GetPackageServiceId(packageId, databaseResoure.Value);
                    if (dbServiceId == 0)
                    {
                        return(Error <StringResultObject>(GalleryErrors.DatabaseServiceIsNotAvailable));
                    }

                    #region Setup Database server and DB Admin credentials
                    // get database service settings
                    StringDictionary dbSettings = ServerController.GetServiceSettingsAdmin(dbServiceId);

                    // database server
                    DeploymentParameter databaseServer = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBServer);
                    if (databaseServer != null)
                    {
                        databaseServer.Value = dbSettings["ExternalAddress"];
                        if (String.IsNullOrEmpty(databaseServer.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseServerExternalAddressIsEmpty));
                        }
                    }

                    // database admin
                    DeploymentParameter databaseAdminUsername = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBAdminUserName);
                    if (databaseAdminUsername != null)
                    {
                        databaseAdminUsername.Value = dbSettings["RootLogin"];
                        if (String.IsNullOrEmpty(databaseAdminUsername.Value))
                        {
                            databaseAdminUsername.Value = dbSettings["SaLogin"];
                        }

                        // raise error if database service is in Integrated Security mode (for SQL Server)
                        // or DB Admin username is not provided
                        if (String.IsNullOrEmpty(databaseAdminUsername.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseAdminUsernameNotSpecified));
                        }
                    }

                    // database admin password
                    DeploymentParameter databaseAdminPassword = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBAdminPassword);
                    if (databaseAdminPassword != null)
                    {
                        databaseAdminPassword.Value = dbSettings["RootPassword"];
                        if (String.IsNullOrEmpty(databaseAdminPassword.Value))
                        {
                            databaseAdminPassword.Value = dbSettings["SaPassword"];
                        }

                        // raise error if database service is in Integrated Security mode (for SQL Server)
                        // or DB Admin password is not provided
                        if (String.IsNullOrEmpty(databaseAdminPassword.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseAdminPasswordNotSpecified));
                        }
                    }
                    #endregion

                    #region Create database and db user account if new selected

                    // create database
                    DeploymentParameter databaseName = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBName);
                    if (databaseName != null)
                    {
                        SqlDatabase db = PackageController.GetPackageItemByName(packageId, databaseResoure.Value, databaseName.Value, typeof(SqlDatabase)) as SqlDatabase;

                        if (db == null)
                        {
                            try
                            {
                                db           = new SqlDatabase();
                                db.PackageId = packageId;
                                db.Name      = databaseName.Value;

                                // create
                                databaseResult = DatabaseServerController.AddSqlDatabase(db, databaseResoure.Value);
                                if (databaseResult < 0)
                                {
                                    result.ErrorCodes.Add((-databaseResult).ToString());
                                    return(Error <StringResultObject>(result, GalleryErrors.DatabaseCreationError));
                                }
                            }
                            catch (Exception ex)
                            {
                                // log exception
                                TaskManager.WriteError(ex);

                                // return error
                                return(Error <StringResultObject>(GalleryErrors.DatabaseCreationException, ex.Message));
                            }
                        }
                    }

                    // create database user
                    DeploymentParameter databaseUsername     = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBUserName);
                    DeploymentParameter databaseUserPassword = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBUserPassword);

                    if (databaseUsername != null && databaseUserPassword != null)
                    {
                        SqlUser user = PackageController.GetPackageItemByName(packageId, databaseResoure.Value, databaseUsername.Value, typeof(SqlUser)) as SqlUser;
                        //
                        if (user == null)
                        {
                            // create new user account
                            try
                            {
                                user           = new SqlUser();
                                user.PackageId = packageId;
                                user.Name      = databaseUsername.Value;
                                user.Databases = (databaseName != null) ? new string[] { databaseName.Value } : new string[0];
                                user.Password  = databaseUserPassword.Value;

                                // create
                                databaseUserResult = DatabaseServerController.AddSqlUser(user, databaseResoure.Value);

                                // check results
                                if (databaseUserResult < 0)
                                {
                                    // Rollback and remove db if created
                                    if (databaseResult > 0)
                                    {
                                        DatabaseServerController.DeleteSqlDatabase(databaseResult);
                                    }

                                    // raise error
                                    result.ErrorCodes.Add((-databaseUserResult).ToString());
                                    return(Error <StringResultObject>(result, GalleryErrors.DatabaseUserCreationError));
                                }
                            }
                            catch (Exception ex)
                            {
                                // log exception
                                TaskManager.WriteError(ex);

                                // return error
                                return(Error <StringResultObject>(GalleryErrors.DatabaseUserCreationException, ex.Message));
                            }
                        }
                        else
                        {
                            // check existing user account
                            DatabaseServer databaseService = DatabaseServerController.GetDatabaseServer(dbServiceId);
                            if (!databaseService.CheckConnectivity(databaseName.Value, databaseUsername.Value, databaseUserPassword.Value))
                            {
                                return(Error <StringResultObject>(GalleryErrors.DatabaseUserCannotAccessDatabase, databaseUsername.Value));
                            }
                        }
                    }
                    #endregion

                    // remove database resource parameter from the list
                    // before calling "install" method
                    parameters.Remove(databaseResoure);
                }

                // install application
                result = webServer.InstallGalleryApplication(webAppId, parameters.ToArray());

                #region Rollback in case of failure
                // Rollback - remove resources have been created previously
                if (!result.IsSuccess)
                {
                    // delete database
                    if (databaseUserResult > 0)
                    {
                        DatabaseServerController.DeleteSqlUser(databaseUserResult);
                    }

                    // delete database user
                    if (databaseResult > 0)
                    {
                        DatabaseServerController.DeleteSqlDatabase(databaseResult);
                    }

                    // exit with errors
                    return(Error <StringResultObject>(result, GalleryErrors.ApplicationInstallationError));
                }
                #endregion

                #region Update Web Application settings

                WebVirtualDirectory iisApp = null;
                if (String.IsNullOrEmpty(virtualDir))
                {
                    // load web site
                    iisApp = WebServerController.GetWebSite(packageId, siteName);
                }
                else
                {
                    // load virtual directory
                    iisApp = WebServerController.GetVirtualDirectory(webSite.Id, virtualDir);
                }

                // put correct extensions
                if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet20) == GalleryApplicationWellKnownDependency.AspNet20)
                {
                    // ASP.NET 2.0
                    iisApp.AspNetInstalled = (iisApp.IIs7) ? "2I" : "2";
                    AddDefaultDocument(iisApp, "default.aspx");
                }
                else if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet40) == GalleryApplicationWellKnownDependency.AspNet40)
                {
                    // ASP.NET 4.0
                    iisApp.AspNetInstalled = (iisApp.IIs7) ? "4I" : "4";
                    AddDefaultDocument(iisApp, "default.aspx");
                }
                else if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.PHP) == GalleryApplicationWellKnownDependency.PHP)
                {
                    // PHP 5
                    iisApp.PhpInstalled = "5";
                    AddDefaultDocument(iisApp, "index.php");
                }

                // update web site or virtual directory
                int updateResult = 0;
                if (String.IsNullOrEmpty(virtualDir))
                {
                    // update web site
                    updateResult = WebServerController.UpdateWebSite(iisApp as WebSite);
                }
                else
                {
                    // update virtual directory
                    updateResult = WebServerController.UpdateVirtualDirectory(webSite.Id, iisApp);
                }

                if (updateResult < 0)
                {
                    TaskManager.WriteWarning("Cannot update website or virtual directory programming extensions and default documents. Result code: {0}", updateResult.ToString());
                }

                #endregion

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <StringResultObject>(GalleryErrors.GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static GalleryApplicationResult GetGalleryApplicationDetails(int packageId, string applicationId)
        {
            GalleryApplicationResult result;

            //
            try
            {
                TaskManager.StartTask(TASK_MANAGER_SOURCE, GET_GALLERY_APP_DETAILS_TASK);

                // check if WAG is installed
                WebServer webServer = GetAssociatedWebServer(packageId);
                if (!webServer.IsMsDeployInstalled())
                {
                    return(Error <GalleryApplicationResult>(GalleryErrors.MsDeployIsNotInstalled));
                }

                // get application details
                result = webServer.GetGalleryApplication(applicationId);

                if (!result.IsSuccess)
                {
                    return(Error <GalleryApplicationResult>(result, GalleryErrors.GetApplicationError));
                }

                // check application requirements
                PackageContext context = PackageController.GetPackageContext(packageId);

                GalleryApplication app = result.Value;

                // ASP.NET 2.0
                if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet20) == GalleryApplicationWellKnownDependency.AspNet20 &&
                    context.Quotas.ContainsKey(Quotas.WEB_ASPNET20) && context.Quotas[Quotas.WEB_ASPNET20].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.AspNet20Required);
                }

                // ASP.NET 4.0
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet40) == GalleryApplicationWellKnownDependency.AspNet40 &&
                         context.Quotas.ContainsKey(Quotas.WEB_ASPNET40) && context.Quotas[Quotas.WEB_ASPNET40].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.AspNet40Required);
                }

                // PHP
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.PHP) == GalleryApplicationWellKnownDependency.PHP &&
                         context.Quotas.ContainsKey(Quotas.WEB_PHP4) && context.Quotas[Quotas.WEB_PHP4].QuotaAllocatedValue < 1 &&
                         context.Quotas.ContainsKey(Quotas.WEB_PHP5) && context.Quotas[Quotas.WEB_PHP5].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.PhpRequired);
                }

                // any database
                GalleryApplicationWellKnownDependency anyDatabaseFlag = GalleryApplicationWellKnownDependency.SQL | GalleryApplicationWellKnownDependency.MySQL;
                if ((app.WellKnownDependencies & anyDatabaseFlag) == anyDatabaseFlag &&
                    !(context.Groups.ContainsKey(ResourceGroups.MsSql2000) ||
                      context.Groups.ContainsKey(ResourceGroups.MsSql2005) ||
                      context.Groups.ContainsKey(ResourceGroups.MsSql2008) ||
                      context.Groups.ContainsKey(ResourceGroups.MySql4) ||
                      context.Groups.ContainsKey(ResourceGroups.MySql5)))
                {
                    result.ErrorCodes.Add(GalleryErrors.DatabaseRequired);
                }

                // SQL Server
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.SQL) == GalleryApplicationWellKnownDependency.SQL &&
                         !(context.Groups.ContainsKey(ResourceGroups.MsSql2000) ||
                           context.Groups.ContainsKey(ResourceGroups.MsSql2005) ||
                           context.Groups.ContainsKey(ResourceGroups.MsSql2008)))
                {
                    result.ErrorCodes.Add(GalleryErrors.SQLRequired);
                }

                // MySQL
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.MySQL) == GalleryApplicationWellKnownDependency.MySQL &&
                         !(context.Groups.ContainsKey(ResourceGroups.MySql4) ||
                           context.Groups.ContainsKey(ResourceGroups.MySql5)))
                {
                    result.ErrorCodes.Add(GalleryErrors.MySQLRequired);
                }

                if (result.ErrorCodes.Count > 0)
                {
                    GalleryApplicationResult warning = Warning <GalleryApplicationResult>(result, GalleryErrors.PackageDoesNotMeetRequirements);
                    warning.Value = app;
                    return(warning);
                }
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                return(Error <GalleryApplicationResult>(GalleryErrors.GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            //
            return(result);
        }
        public static GalleryApplicationsResult GetGalleryApplications(int packageId, string categoryId)
        {
            GalleryApplicationsResult result;

            //
            try
            {
                TaskManager.StartTask(TASK_MANAGER_SOURCE, GET_GALLERY_APPS_TASK);

                // check if WAG is installed
                WebServer webServer = GetAssociatedWebServer(packageId);
                if (!webServer.IsMsDeployInstalled())
                {
                    return(Error <GalleryApplicationsResult>(GalleryErrors.MsDeployIsNotInstalled));
                }

                // get applications
                result = webServer.GetGalleryApplications(categoryId);

                if (!result.IsSuccess)
                {
                    return(Error <GalleryApplicationsResult>(result, GalleryErrors.GetApplicationsError));
                }

                // get space quotas
                PackageContext context = PackageController.GetPackageContext(packageId);

                //// filter applications
                //List<string> appsFilter = new List<string>();
                //// if either ASP.NET 1.1 or 2.0 enabled in the hosting plan
                //if (context.Quotas[Quotas.WEB_ASPNET11].QuotaAllocatedValue == 1 ||
                //    context.Quotas[Quotas.WEB_ASPNET20].QuotaAllocatedValue == 1 ||
                //    context.Quotas[Quotas.WEB_ASPNET40].QuotaAllocatedValue == 1)
                //{
                //    appsFilter.AddRange(SupportedAppDependencies.ASPNET_SCRIPTING);
                //}
                //// if either PHP 4 or 5 enabled in the hosting plan
                //if (context.Quotas[Quotas.WEB_PHP4].QuotaAllocatedValue == 1 ||
                //    context.Quotas[Quotas.WEB_PHP5].QuotaAllocatedValue == 1)
                //{
                //    appsFilter.AddRange(SupportedAppDependencies.PHP_SCRIPTING);
                //}
                //// if either MSSQL 2000, 2005 or 2008 enabled in the hosting plan
                //if (context.Groups.ContainsKey(ResourceGroups.MsSql2000) ||
                //    context.Groups.ContainsKey(ResourceGroups.MsSql2005) ||
                //    context.Groups.ContainsKey(ResourceGroups.MsSql2008))
                //{
                //    appsFilter.AddRange(SupportedAppDependencies.MSSQL_DATABASE);
                //}
                //// if either MySQL 4 or 5 enabled in the hosting plan
                //if (context.Groups.ContainsKey(ResourceGroups.MySql4) ||
                //    context.Groups.ContainsKey(ResourceGroups.MySql5))
                //{
                //    appsFilter.AddRange(SupportedAppDependencies.MYSQL_DATABASE);
                //}
                //// Match applications based on the hosting plan restrictions collected
                //result.Value = new List<GalleryApplication>(Array.FindAll<GalleryApplication>(result.Value.ToArray(),
                //    x => MatchGalleryAppDependencies(x.Dependency, appsFilter.ToArray())
                //        || MatchMenaltoGalleryApp(x, appsFilter.ToArray())));

                {
                    int userId = SecurityContext.User.UserId;
                    //
                    SecurityContext.SetThreadSupervisorPrincipal();
                    //
                    string[] filteredApps = GetServiceAppsCatalogFilter(packageId);
                    //
                    if (filteredApps != null)
                    {
                        result.Value = new List <GalleryApplication>(Array.FindAll(result.Value.ToArray(),
                                                                                   x => !Array.Exists(filteredApps,
                                                                                                      z => z.Equals(x.Id, StringComparison.InvariantCultureIgnoreCase))));
                    }
                    //
                    SecurityContext.SetThreadPrincipal(userId);
                }
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                return(Error <GalleryApplicationsResult>(GalleryErrors.GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            //
            return(result);
        }
Пример #14
0
        public static int AddZone(int packageId, int serviceId, string zoneName, bool addPackageItem, bool ignoreGlobalDNSRecords)
        {
            // get DNS provider
            DNSServer dns = GetDNSServer(serviceId);

            // Ensure zoneName is in ascii before saving to database
            zoneName = GetAsciiZoneName(zoneName);

            // 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);
        }
        public static ResultObject SendExchangeOrganizationSummary(int itemId, string toEmail)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "SEND_SUMMARY");
                TaskManager.WriteParameter("Item ID", itemId);
                TaskManager.WriteParameter("To e-mail", toEmail);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // load organization details
                ExchangeOrganization org = GetOrganizationDetails(item.Id);
                if (org == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                // get evaluated summary information
                MailTemplate msg = EvaluateOrganizationSummaryTemplate(org);
                if (msg == null)
                {
                    return(Error <ResultObject>(SendOrganizationTemplateNotSetError));
                }

                // send message
                int sendResult = MailHelper.SendMessage(msg.From, toEmail, msg.Bcc, msg.Subject, msg.Body, msg.Priority, msg.IsHtml);
                if (sendResult < 0)
                {
                    return(Error <ResultObject>((-sendResult).ToString()));
                }

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(SendOrganizationSummaryError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        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 ResultObject AddOrganizationDomain(int itemId, string domainName)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "ADD_DOMAIN");
                TaskManager.WriteParameter("itemId", itemId);
                TaskManager.WriteParameter("domain", domainName);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // get organization details
                ExchangeOrganization org = GetOrganizationDetails(item.Id);
                if (org == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                // check domains quota
                if (org.MaxDomainsCountQuota > -1 && org.Domains.Length >= org.MaxDomainsCountQuota)
                {
                    return(Error <IntResult>(AddDomainQuotaExceededError));
                }

                // check if the domain already exists
                DomainInfo domain      = null;
                int        checkResult = ServerController.CheckDomain(domainName);
                if (checkResult == BusinessErrorCodes.ERROR_DOMAIN_ALREADY_EXISTS)
                {
                    // domain exists
                    // check if it belongs to the same space
                    domain = ServerController.GetDomain(domainName);
                    if (domain == null)
                    {
                        return(Error <ResultObject>((-checkResult).ToString()));
                    }

                    if (domain.PackageId != org.PackageId)
                    {
                        return(Error <ResultObject>((-checkResult).ToString()));
                    }

                    // check if domain is already used in this organization
                    foreach (ExchangeOrganizationDomain orgDomain in org.Domains)
                    {
                        if (String.Equals(orgDomain.Name, domainName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(Error <ResultObject>(AddDomainAlreadyUsedError));
                        }
                    }
                }
                else if (checkResult == BusinessErrorCodes.ERROR_RESTRICTED_DOMAIN)
                {
                    return(Error <ResultObject>((-checkResult).ToString()));
                }

                // create domain if required
                if (domain == null)
                {
                    domain                = new DomainInfo();
                    domain.PackageId      = org.PackageId;
                    domain.DomainName     = domainName;
                    domain.IsInstantAlias = false;
                    domain.IsSubDomain    = false;

                    int domainId = ServerController.AddDomain(domain);
                    if (domainId < 0)
                    {
                        return(Error <ResultObject>((-domainId).ToString()));
                    }

                    // add domain
                    domain.DomainId = domainId;
                }

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(item.ServiceId);

                // add domain
                exchange.AddOrganizationDomain(item.Name, domainName);

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(AddDomainError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Пример #18
0
        public int InstallWebApplication(InstallationInfo inst)
        {
            // place log record
            TaskManager.StartTask("APP_INSTALLER", "INSTALL_APPLICATION", inst.PackageId);

            TaskManager.WriteParameter("Virtual directory", inst.VirtualDir);
            TaskManager.WriteParameter("Database group", inst.DatabaseGroup);

            try
            {
                // get application info
                app = GetApplication(inst.PackageId, inst.ApplicationId);

                BackgroundTask topTask = TaskManager.TopTask;

                topTask.ItemName = app.Name;

                TaskController.UpdateTask(topTask);

                // check web site for existance
                WebSite webSite = WebServerController.GetWebSite(inst.WebSiteId);

                if (webSite == null)
                {
                    return(BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS);
                }

                TaskManager.WriteParameter("Web site", webSite.Name);

                webSiteName = webSite.Name;
                siteId      = webSite.SiteId;

                // change web site properties if required
                if (String.IsNullOrEmpty(inst.VirtualDir))
                {
                    ChangeVirtualDirectoryProperties(webSite, app.WebSettings);
                    WebServerController.UpdateWebSite(webSite);
                }

                // get OS service
                int osId = PackageController.GetPackageServiceId(inst.PackageId, "os");
                os = new OS.OperatingSystem();
                ServiceProviderProxy.Init(os, osId);

                // get remote content path
                contentPath = webSite.ContentPath;

                // create virtual dir if required
                if (!String.IsNullOrEmpty(inst.VirtualDir))
                {
                    // check if the required virtual dir already exists
                    contentPath = Path.Combine(contentPath, inst.VirtualDir);

                    WebVirtualDirectory vdir = null;
                    int result = WebServerController.AddVirtualDirectory(inst.WebSiteId, inst.VirtualDir, contentPath);
                    if (result == BusinessErrorCodes.ERROR_VDIR_ALREADY_EXISTS)
                    {
                        // the directory alredy exists
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        contentPath = vdir.ContentPath;
                    }
                    else
                    {
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        inst[PROPERTY_VDIR_CREATED] = "True";
                    }

                    // change virtual directory properties if required
                    ChangeVirtualDirectoryProperties(vdir, app.WebSettings);
                    WebServerController.UpdateVirtualDirectory(inst.WebSiteId, vdir);
                }

                // deploy application codebase ZIP and then unpack it
                string codebasePath       = app.Codebase;
                string remoteCodebasePath = Path.Combine(contentPath, Path.GetFileName(app.Codebase));

                // make content path absolute
                string absContentPath = FilesController.GetFullPackagePath(inst.PackageId, contentPath);

                // save content path
                inst[PROPERTY_CONTENT_PATH]          = contentPath;
                inst[PROPERTY_ABSOLUTE_CONTENT_PATH] = absContentPath;

                // copy ZIP to the target server
                FileStream stream        = File.OpenRead(codebasePath);
                int        BUFFER_LENGTH = 5000000;

                byte[] buffer    = new byte[BUFFER_LENGTH];
                int    readBytes = 0;
                while (true)
                {
                    readBytes = stream.Read(buffer, 0, BUFFER_LENGTH);

                    if (readBytes < BUFFER_LENGTH)
                    {
                        Array.Resize <byte>(ref buffer, readBytes);
                    }

                    FilesController.AppendFileBinaryChunk(inst.PackageId, remoteCodebasePath, buffer);

                    if (readBytes < BUFFER_LENGTH)
                    {
                        break;
                    }
                }



                // unpack codebase
                inst[PROPERTY_INSTALLED_FILES] = String.Join(";",
                                                             FilesController.UnzipFiles(inst.PackageId, new string[] { remoteCodebasePath }));

                // delete codebase zip
                FilesController.DeleteFiles(inst.PackageId, new string[] { remoteCodebasePath });

                // check/create databases
                if (!String.IsNullOrEmpty(inst.DatabaseGroup) &&
                    String.Compare(inst.DatabaseGroup, "None", true) != 0)
                {
                    // database
                    if (inst.DatabaseId == 0)
                    {
                        TaskManager.WriteParameter("Database name", inst.DatabaseName);

                        // we should create a new database
                        SqlDatabase db = new SqlDatabase();
                        db.PackageId    = inst.PackageId;
                        db.Name         = inst.DatabaseName;
                        inst.DatabaseId = DatabaseServerController.AddSqlDatabase(db, inst.DatabaseGroup);
                        if (inst.DatabaseId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return(inst.DatabaseId); // there was an error when creating database
                        }

                        inst[PROPERTY_DATABASE_CREATED] = "True";
                    }
                    else
                    {
                        // existing database
                        SqlDatabase db = DatabaseServerController.GetSqlDatabase(inst.DatabaseId);
                        inst.DatabaseName = db.Name;

                        TaskManager.WriteParameter("Database name", inst.DatabaseName);
                    }

                    SqlUser user = null;
                    // database user
                    if (inst.UserId == 0)
                    {
                        TaskManager.WriteParameter("Database user", inst.Username);

                        // NEW USER
                        user           = new SqlUser();
                        user.PackageId = inst.PackageId;
                        user.Name      = inst.Username;
                        user.Databases = new string[] { inst.DatabaseName };
                        user.Password  = inst.Password;
                        inst.UserId    = DatabaseServerController.AddSqlUser(user, inst.DatabaseGroup);
                        if (inst.UserId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return(inst.UserId); // error while adding user
                        }

                        inst[PROPERTY_USER_CREATED] = "True";
                    }
                    else
                    {
                        // EXISTING USER
                        user          = DatabaseServerController.GetSqlUser(inst.UserId);
                        inst.Username = user.Name;

                        TaskManager.WriteParameter("Database user", inst.Username);

                        List <string> databases = new List <string>();
                        databases.AddRange(user.Databases);

                        if (!databases.Contains(inst.DatabaseName))
                        {
                            databases.Add(inst.DatabaseName);

                            user.Databases = databases.ToArray();
                            DatabaseServerController.UpdateSqlUser(user);
                        }
                    }

                    // check connectivity with SQL Server and credentials provided
                    // load user item
                    int sqlServiceId = PackageController.GetPackageServiceId(inst.PackageId, inst.DatabaseGroup);
                    sql = new DatabaseServer();
                    ServiceProviderProxy.Init(sql, sqlServiceId);

                    if (!sql.CheckConnectivity(inst.DatabaseName, inst.Username,
                                               inst.Password))
                    {
                        // can't connect to the database
                        RollbackInstallation(inst);

                        return(BusinessErrorCodes.ERROR_WEB_INSTALLER_CANT_CONNECT_DATABASE);
                    }

                    // read SQL server settings
                    StringDictionary settings = ServerController.GetServiceSettings(sqlServiceId);
                    serverIpAddressExternal = settings["ExternalAddress"];
                    if (settings.ContainsKey("InternalAddress"))
                    {
                        serverIpAddressInternal = settings["InternalAddress"];
                    }
                }

                // ********* RUN INSTALL SCENARIO ***********
                int scriptResult = RunInstallScenario(inst);
                if (scriptResult < 0)
                {
                    // rollback installation
                    RollbackInstallation(inst);

                    // return error
                    return(scriptResult);
                }

                // add new installation to the database
                return(0);
            }
            catch (Exception ex)
            {
                // rollback installation
                RollbackInstallation(inst);

                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static ResultObject UpdateOrganizationQuotas(int itemId, int mailboxesNumber, int contactsNumber, int distributionListsNumber)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "UPDATE_QUOTAS");
                TaskManager.WriteParameter("itemId", itemId);
                TaskManager.WriteParameter("mailboxesNumber", mailboxesNumber);
                TaskManager.WriteParameter("contactsNumber", contactsNumber);
                TaskManager.WriteParameter("distributionListsNumber", distributionListsNumber);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // check quotas
                UpdateOrganizationQuotas(item);

                if (item.MaxMailboxCountQuota > -1 && mailboxesNumber > item.MaxMailboxCountQuota)
                {
                    return(Error <ResultObject>(UpdateQuotasWrongQuotaError));
                }
                if (item.MaxContactCountQuota > -1 && contactsNumber > item.MaxContactCountQuota)
                {
                    return(Error <ResultObject>(UpdateQuotasWrongQuotaError));
                }
                if (item.MaxDistributionListCountQuota > -1 && distributionListsNumber > item.MaxDistributionListCountQuota)
                {
                    return(Error <ResultObject>(UpdateQuotasWrongQuotaError));
                }

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(item.ServiceId);

                // update quotas
                exchange.UpdateOrganizationQuotas(item.Name, mailboxesNumber, contactsNumber, distributionListsNumber);

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(UpdateQuotasError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        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 IntResult CreateOrganization(int packageId, string organizationId,
                                                   string domain, string adminName, string adminEmail, string adminPassword)
        {
            IntResult result = new IntResult();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "CREATE_ORGANIZATION");
                TaskManager.WriteParameter("packageId", packageId);
                TaskManager.WriteParameter("organizationId", organizationId);
                TaskManager.WriteParameter("domain", domain);
                TaskManager.WriteParameter("adminName", adminName);
                TaskManager.WriteParameter("adminEmail", adminEmail);
                TaskManager.WriteParameter("adminPassword", adminPassword);

                // get Exchange service ID
                int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.ExchangeHostedEdition);
                if (serviceId < 1)
                {
                    return(Error <IntResult>(ExchangeServiceNotEnabledError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <IntResult>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <IntResult>((-packageCheck).ToString()));
                }
                #endregion

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(serviceId);

                // load service settings to know ProgramID, OfferID
                StringDictionary serviceSettings = ServerController.GetServiceSettings(serviceId);
                string           programId       = serviceSettings["programID"];
                string           offerId         = serviceSettings["offerID"];

                // check settings
                if (String.IsNullOrEmpty(programId))
                {
                    result.ErrorCodes.Add(ProgramIdIsNotSetError);
                }
                if (String.IsNullOrEmpty(offerId))
                {
                    result.ErrorCodes.Add(OfferIdIsNotSetError);
                }

                if (result.ErrorCodes.Count > 0)
                {
                    result.IsSuccess = false;
                    return(result);
                }

                #region Create organization
                int itemId = -1;
                ExchangeOrganization org = null;
                try
                {
                    // create organization
                    exchange.CreateOrganization(organizationId, programId, offerId, domain, adminName, adminEmail, adminPassword);

                    // save item into meta-base
                    org           = new ExchangeOrganization();
                    org.Name      = organizationId;
                    org.PackageId = packageId;
                    org.ServiceId = serviceId;
                    itemId        = PackageController.AddPackageItem(org);
                }
                catch (Exception ex)
                {
                    // log error
                    TaskManager.WriteError(ex);
                    return(Error <IntResult>(CreateOrganizationError));
                }
                #endregion

                #region Update organization quotas
                // update max org quotas
                UpdateOrganizationQuotas(org);

                // override quotas
                ResultObject quotasResult = ExchangeHostedEditionController.UpdateOrganizationQuotas(itemId,
                                                                                                     org.MaxMailboxCountQuota,
                                                                                                     org.MaxContactCountQuota,
                                                                                                     org.MaxDistributionListCountQuota);

                if (!quotasResult.IsSuccess)
                {
                    return(Error <IntResult>(quotasResult, CreateOrganizationError));
                }
                #endregion

                #region Add temporary domain
                // load settings
                PackageSettings settings           = GetExchangePackageSettings(org);
                string          tempDomainTemplate = settings[TempDomainSetting];
                if (!String.IsNullOrEmpty(tempDomainTemplate))
                {
                    // add temp domain
                    string tempDomain = String.Format("{0}.{1}", domain, tempDomainTemplate);
                    AddOrganizationDomain(itemId, tempDomain);
                }

                #endregion

                result.Value = itemId;
                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <IntResult>(GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        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);
        }
Пример #23
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);
        }