Esempio n. 1
0
        public static byte[] GetFileBinaryChunk(int packageId, string path, int offset, int length)
        {
            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            return(os.GetFileBinaryChunk(fullPath, offset, length));
        }
Esempio n. 2
0
        public static bool DirectoryExists(int packageId, string path)
        {
            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            return(os.DirectoryExists(fullPath));
        }
Esempio n. 3
0
        public static int AppendFileBinaryChunk(int packageId, string path, byte[] chunk)
        {
            // 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);
            }

            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            os.AppendFileBinaryContent(fullPath, chunk);

            return(0);
        }
Esempio n. 4
0
        public static bool RemoteServerFolderWriteAccessible(int packageId, string path)
        {
            try
            {
                // copy to space folder
                int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
                if (osServiceId > 0)
                {
                    OS.OperatingSystem os = new OS.OperatingSystem();
                    ServiceProviderProxy.Init(os, osServiceId);

                    string remoteServerPathCheck = FilesController.GetFullPackagePath(packageId,
                                                                                      Path.Combine(path, "check.txt"));

                    //
                    os.CreateFile(remoteServerPathCheck);
                    os.AppendFileBinaryContent(remoteServerPathCheck, Encoding.UTF8.GetBytes(remoteServerPathCheck));
                    os.DeleteFile(remoteServerPathCheck);
                }
                //
                return(true);
            }
            catch
            {                           //
                return(false);
            }
        }
Esempio n. 5
0
        public static int SetFilePermissions(int packageId, string path, UserPermission[] users, bool resetChildPermissions)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

            // place log record
            TaskManager.StartTask("FILES", "SET_PERMISSIONS", path, packageId);

            try
            {
                OS.OperatingSystem os       = GetOS(packageId);
                string             fullPath = GetFullPackagePath(packageId, path);

                // get users OU defined on web server
                string usersOU = WebServerController.GetWebUsersOU(packageId);

                os.GrantGroupNtfsPermissions(fullPath, users, usersOU, resetChildPermissions);

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 6
0
        public static void ExecuteSyncActions(int packageId, FileSyncAction[] actions)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                return;
            }

            OS.OperatingSystem os = GetOS(packageId);

            // update actions
            foreach (FileSyncAction action in actions)
            {
                if (!String.IsNullOrEmpty(action.SrcPath))
                {
                    action.SrcPath = GetFullPackagePath(packageId, action.SrcPath);
                }
                if (!String.IsNullOrEmpty(action.DestPath))
                {
                    action.DestPath = GetFullPackagePath(packageId, action.DestPath);
                }
            }

            // perform sync
            os.ExecuteSyncActions(actions);
        }
Esempio n. 7
0
        public static int ZipFiles(int packageId, 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, 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        rootFolder = "";
                foreach (string file in files)
                {
                    string archFile = GetFullPackagePath(packageId, file);
                    int    idx      = archFile.LastIndexOf("\\");
                    rootFolder = archFile.Substring(0, idx);
                    archFiles.Add(archFile.Substring(idx + 1));
                }

                os.ZipFiles(zipFilePath, rootFolder, 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();
            }
        }
Esempio n. 8
0
        public static byte[] GetFileBinaryContentUsingEncoding(int packageId, string path, string encoding)
        {
            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            // create file
            return(os.GetFileBinaryContentUsingEncoding(fullPath, encoding));
        }
Esempio n. 9
0
        // Synchronizing
        public static FolderGraph GetFolderGraph(int packageId, string path)
        {
            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            // get graph
            return(os.GetFolderGraph(fullPath));
        }
Esempio n. 10
0
        public static string[] GetInstalledOdbcDrivers(int packageId)
        {
            // load service item
            int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);

            OS.OperatingSystem os = GetOS(serviceId);
            return(os.GetInstalledOdbcDrivers());
        }
Esempio n. 11
0
        public static OS.OperatingSystem GetOS(int packageId)
        {
            int sid = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
            if (sid <= 0)
                return null;

            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, sid);

            return os;
        }
Esempio n. 12
0
        public static string[] UnzipFiles(int packageId, string[] files)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

            // place log record
            TaskManager.StartTask("FILES", "UNZIP_FILES", packageId);

            if (files != null)
            {
                foreach (string file in files)
                {
                    TaskManager.Write(file);
                }
            }

            try
            {
                List <string> unzippedFiles = new List <string>();

                OS.OperatingSystem os = GetOS(packageId);

                for (int i = 0; i < files.Length; i++)
                {
                    string zipFilePath    = GetFullPackagePath(packageId, files[i]);
                    string destFolderPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf("\\"));
                    unzippedFiles.AddRange(os.UnzipFiles(zipFilePath, destFolderPath));
                }

                return(unzippedFiles.ToArray());
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 13
0
        public static OS.OperatingSystem GetOS(int packageId)
        {
            int sid = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);

            if (sid <= 0)
            {
                return(null);
            }

            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, sid);

            return(os);
        }
Esempio n. 14
0
        public static int CreateFile(int packageId, string path)
        {
            // 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", "CREATE_FILE", path);
            TaskManager.ItemId = packageId;

            try
            {
                OS.OperatingSystem os       = GetOS(packageId);
                string             fullPath = GetFullPackagePath(packageId, path);

                // cannot create a file with the same name as a directory
                if (os.DirectoryExists(fullPath))
                {
                    return(BusinessErrorCodes.ERROR_FILE_CREATE_FILE_WITH_DIR_NAME);
                }

                // create file
                os.CreateFile(fullPath);

                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();
            }
        }
Esempio n. 15
0
        public static int DeleteFiles(int packageId, string[] files)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

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

            // place log record
            TaskManager.StartTask("FILES", "DELETE_FILES", packageId);

            if (files != null)
            {
                foreach (string file in files)
                {
                    TaskManager.Write(file);
                }
            }

            try
            {
                OS.OperatingSystem os = GetOS(packageId);
                for (int i = 0; i < files.Length; i++)
                {
                    files[i] = GetFullPackagePath(packageId, files[i]);
                }

                // delete files
                os.DeleteFiles(files);

                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();
            }
        }
Esempio n. 16
0
        public static int DeleteOdbcSource(int itemId)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

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

            // load original meta item
            SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(itemId);

            if (origItem == null)
            {
                return(BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND);
            }

            // place log record
            TaskManager.StartTask("ODBC_DSN", "DELETE", origItem.Name);
            TaskManager.ItemId = itemId;

            try
            {
                // get service
                OS.OperatingSystem os = GetOS(origItem.ServiceId);

                // delete service item
                os.DeleteDSN(origItem.Name);

                // delete meta item
                PackageController.DeletePackageItem(origItem.Id);

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 17
0
        public static List <SystemFile> GetFiles(int packageId, string path, bool includeFiles)
        {
            OS.OperatingSystem os = GetOS(packageId);

            string            fullPath      = GetFullPackagePath(packageId, path);
            List <SystemFile> filteredFiles = new List <SystemFile>();

            SystemFile[] files = os.GetFiles(fullPath);

            foreach (SystemFile file in files)
            {
                if (file.IsDirectory || includeFiles)
                {
                    filteredFiles.Add(file);
                }
            }

            return(filteredFiles);
        }
Esempio n. 18
0
        public static int CreateFolder(int packageId, string path)
        {
            // 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", "CREATE_FOLDER", path, packageId);

            try
            {
                OS.OperatingSystem os       = GetOS(packageId);
                string             fullPath = GetFullPackagePath(packageId, path);

                // create folder
                os.CreateDirectory(fullPath);

                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();
            }
        }
Esempio n. 19
0
        public static int UpdateFileBinaryContentUsingEncoding(int packageId, string path, byte[] content, string encoding)
        {
            // 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", "UPDATE_BINARY_CONTENT", path);
            TaskManager.ItemId = packageId;

            try
            {
                OS.OperatingSystem os       = GetOS(packageId);
                string             fullPath = GetFullPackagePath(packageId, path);

                // create file
                os.UpdateFileBinaryContentUsingEncoding(fullPath, content, encoding);

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 20
0
        public List <string> GetImportableItems(int packageId, int itemTypeId, Type itemType,
                                                ResourceGroupInfo group)
        {
            List <string> items = new List <string>();

            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);

            if (serviceId == 0)
            {
                return(items);
            }

            OS.OperatingSystem os = GetOS(serviceId);
            if (itemType == typeof(SystemDSN))
            {
                items.AddRange(os.GetDSNNames());
            }

            return(items);
        }
Esempio n. 21
0
        public static SystemDSN GetOdbcSource(int itemId)
        {
            // load meta item
            SystemDSN item = (SystemDSN)PackageController.GetPackageItem(itemId);

            // load service item
            OS.OperatingSystem os  = GetOS(item.ServiceId);
            SystemDSN          dsn = os.GetDSN(item.Name);

            // add common properties
            dsn.Id        = item.Id;
            dsn.PackageId = item.PackageId;
            dsn.ServiceId = item.ServiceId;

            if (dsn.Driver == "MsAccess" || dsn.Driver == "Excel" || dsn.Driver == "Text")
            {
                dsn.DatabaseName = FilesController.GetVirtualPackagePath(item.PackageId, dsn.DatabaseName);
            }

            return(dsn);
        }
Esempio n. 22
0
        public static UserPermission[] GetFilePermissions(int packageId, string path)
        {
            try
            {
                // get all accounts
                UserPermission[] users = GetAvailableSecurityAccounts(packageId);

                OS.OperatingSystem os       = GetOS(packageId);
                string             fullPath = GetFullPackagePath(packageId, path);

                // get users OU defined on web server
                string usersOU = WebServerController.GetWebUsersOU(packageId);

                users = os.GetGroupNtfsPermissions(fullPath, users, usersOU);

                return(users);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
        }
Esempio n. 23
0
        public static int DeleteDirectoryRecursive(int packageId, string rootPath)
        {
            // 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", "DELETE_DIRECTORY_RECURSIVE", rootPath, packageId);

            try
            {
                OS.OperatingSystem os = GetOS(packageId);
                os.DeleteDirectoryRecursive(rootPath);

                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();
            }
        }
Esempio n. 24
0
        public static int RenameFile(int packageId, string oldPath, string newPath)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

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

            // place log record
            TaskManager.StartTask("FILES", "RENAME_FILE", oldPath, packageId);

            TaskManager.WriteParameter("New name", newPath);

            try
            {
                OS.OperatingSystem os           = GetOS(packageId);
                string             oldFullPath  = GetFullPackagePath(packageId, oldPath);
                string             destFullPath = GetFullPackagePath(packageId, newPath);

                os.MoveFile(oldFullPath, destFullPath);

                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();
            }
        }
Esempio n. 25
0
        private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB

        private static OS.OperatingSystem GetOS(int serviceId)
        {
            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, serviceId);
            return(os);
        }
        private static WebsitePanel.Providers.OS.OperatingSystem GetOS(int packageId)
        {
            var esServiceInfo = ServerController.GetServiceInfo(GetEnterpriseStorageServiceID(packageId));
            var esProviderInfo = ServerController.GetProvider(esServiceInfo.ProviderId);

            var osGroups = ServerController.GetResourceGroupByName(ResourceGroups.Os);
            var osProviders = ServerController.GetProvidersByGroupID(osGroups.GroupId);

            var regexResult = Regex.Match(esProviderInfo.ProviderType, "Windows([0-9]+)");

            if (regexResult.Success)
            {
                foreach (var osProvider in osProviders)
                {
                    BoolResult result = ServerController.IsInstalled(esServiceInfo.ServerId, osProvider.ProviderId);

                    if (result.IsSuccess && result.Value)
                    {
                        var os = new WebsitePanel.Providers.OS.OperatingSystem();
                        ServerProxyConfigurator cnfg = new ServerProxyConfigurator();

                        cnfg.ProviderSettings.ProviderGroupID = osProvider.GroupId;
                        cnfg.ProviderSettings.ProviderCode = osProvider.ProviderName;
                        cnfg.ProviderSettings.ProviderName = osProvider.DisplayName;
                        cnfg.ProviderSettings.ProviderType = osProvider.ProviderType;

                        ServiceProviderProxy.ServerInit(os, cnfg, esServiceInfo.ServerId);

                        return os;
                    }
                }
            }

            return null;
        }
Esempio n. 27
0
        public static int UpdateOdbcSource(SystemDSN item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

            // load original meta item
            SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(item.Id);

            if (origItem == null)
            {
                return(BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND);
            }

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

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

            // place log record
            TaskManager.StartTask("ODBC_DSN", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;

            try
            {
                // get service
                OS.OperatingSystem os = GetOS(origItem.ServiceId);

                // password
                item.Driver = origItem.Driver;
                item.Name   = origItem.Name;

                if (item.DatabasePassword == "")
                {
                    item.DatabasePassword = CryptoUtils.Decrypt(origItem.DatabasePassword);
                }

                string[] dbNameParts = item.DatabaseName.Split('|');
                string   groupName   = null;
                if (dbNameParts.Length > 1)
                {
                    item.DatabaseName = dbNameParts[0];
                    groupName         = dbNameParts[1];
                }

                // get database server address
                item.DatabaseServer = GetDatabaseServerName(groupName, item.PackageId);

                if (item.Driver == "MsAccess" || item.Driver == "Excel" || item.Driver == "Text")
                {
                    item.DatabaseName = FilesController.GetFullPackagePath(origItem.PackageId, item.DatabaseName);
                }

                // update service item
                os.UpdateDSN(item);

                // update meta item
                if (item.DatabasePassword != "")
                {
                    item.DatabasePassword = CryptoUtils.Encrypt(item.DatabasePassword);
                    PackageController.UpdatePackageItem(item);
                }

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 28
0
        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();
            }
        }
Esempio n. 29
0
        public static int ApplyEnableHardQuotaFeature(int packageId)
        {
            if (SecurityContext.CheckAccount(DemandAccount.IsActive | DemandAccount.IsAdmin | DemandAccount.NotDemo) != 0)
            {
                throw new Exception("This method could be called by serveradmin only.");
            }

            // place log record
            TaskManager.StartTask("FILES", "APPLY_ENABLEHARDQUOTAFEATURE");

            try
            {
                // request OS service
                //int osId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
                //if (osId == 0)
                //    return -1;

                //OS.OperatingSystem os = new OS.OperatingSystem();
                //ServiceProviderProxy.Init(os, osId);

                ////Get operating system settings
                // StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
                //  bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false;
                //string driveName = osSesstings["LocationDrive"];

                //if (!diskQuotaEnabled)
                //    return -1;


                List <PackageInfo> allPackages = PackageController.GetPackagePackages(packageId, true);

                foreach (PackageInfo childPackage in allPackages)
                {
                    // request OS service
                    int osId = PackageController.GetPackageServiceId(childPackage.PackageId, ResourceGroups.Os);
                    if (osId == 0)
                    {
                        continue;
                    }

                    OS.OperatingSystem os = new OS.OperatingSystem();
                    ServiceProviderProxy.Init(os, osId);

                    //Get operating system settings
                    StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
                    string           driveName   = osSesstings["LocationDrive"];

                    if (String.IsNullOrEmpty(driveName))
                    {
                        continue;
                    }

                    string homeFolder = FilesController.GetHomeFolder(childPackage.PackageId);
                    FilesController.SetFolderQuota(childPackage.PackageId, homeFolder, driveName, Quotas.OS_DISKSPACE);
                }
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }

            return(0);
        }
Esempio n. 30
0
        public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
        {
            if (itemType == typeof(HomeFolder))
            {
                OS.OperatingSystem os = GetOS(serviceId);

                // extract meta item
                XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder));
                HomeFolder    homeFolder = (HomeFolder)serializer.Deserialize(
                    new XmlNodeReader(itemNode.SelectSingleNode("HomeFolder")));

                // create home folder if required
                if (!os.DirectoryExists(homeFolder.Name))
                {
                    os.CreatePackageFolder(homeFolder.Name);
                }

                // copy database backup to remote server
                XmlNode fileNode            = itemNode.SelectSingleNode("File[@name='SpaceFiles']");
                string  backupFileName      = fileNode.Attributes["path"].Value;
                long    backupFileLength    = Int64.Parse(fileNode.Attributes["size"].Value);
                string  localBackupFilePath = Path.Combine(tempFolder, backupFileName);

                if (new FileInfo(localBackupFilePath).Length != backupFileLength)
                {
                    return(-3);
                }

                FileStream stream = new FileStream(localBackupFilePath, FileMode.Open, FileAccess.Read);
                byte[]     buffer = new byte[FILE_BUFFER_LENGTH];

                int    readBytes        = 0;
                long   length           = 0;
                string remoteBackupPath = Path.Combine(homeFolder.Name, backupFileName);
                do
                {
                    // read package file
                    readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
                    length   += readBytes;

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

                    // write remote backup file
                    os.AppendFileBinaryContent(remoteBackupPath, buffer);
                }while (readBytes == FILE_BUFFER_LENGTH);
                stream.Close();

                // unzip files
                os.UnzipFiles(remoteBackupPath, homeFolder.Name);

                // delete archive
                if (os.FileExists(remoteBackupPath))
                {
                    os.DeleteFile(remoteBackupPath);
                }

                // add meta-item if required
                if (PackageController.GetPackageItemByName(packageId, itemName, typeof(HomeFolder)) == null)
                {
                    homeFolder.PackageId = packageId;
                    homeFolder.ServiceId = serviceId;
                    PackageController.AddPackageItem(homeFolder);
                }
            }
            else if (itemType == typeof(SystemDSN))
            {
                OS.OperatingSystem os = GetOS(serviceId);

                // extract meta item
                XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN));
                SystemDSN     dsn        = (SystemDSN)serializer.Deserialize(
                    new XmlNodeReader(itemNode.SelectSingleNode("SystemDSN")));

                // create DSN if required
                if (os.GetDSN(itemName) == null)
                {
                    dsn.DatabasePassword = CryptoUtils.Decrypt(dsn.DatabasePassword);
                    os.CreateDSN(dsn);

                    // restore password
                    dsn.DatabasePassword = CryptoUtils.Encrypt(dsn.DatabasePassword);
                }

                // add meta-item if required
                if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemDSN)) == null)
                {
                    dsn.PackageId = packageId;
                    dsn.ServiceId = serviceId;
                    PackageController.AddPackageItem(dsn);
                }
            }

            return(0);
        }
Esempio n. 31
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);
				TaskManager.ItemId = SecurityContext.User.UserId;

				// create temp folder
				string tempFolder = GetTempBackupFolder();

				string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
				if (storePackageId > 0)
				{
					try
					{
						int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
						if (osServiceId > 0)
						{
							OS.OperatingSystem os = new OS.OperatingSystem();
							ServiceProviderProxy.Init(os, osServiceId);

							string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
								storePackageBackupPath);

							FileStream stream = new FileStream(backupFileNamePath, FileMode.Create, FileAccess.Write);

							byte[] buffer = new byte[FILE_BUFFER_LENGTH];
							int offset = 0;
							do
							{
								// read remote content
								buffer = os.GetFileBinaryChunk(remoteBackupPath, offset, FILE_BUFFER_LENGTH);

								// write remote content
								stream.Write(buffer, 0, buffer.Length);

								offset += FILE_BUFFER_LENGTH;
							}
							while (buffer.Length == FILE_BUFFER_LENGTH);
							stream.Close();

						}
					}
					catch (Exception ex)
					{
						TaskManager.WriteError(ex, "Can't copy source backup set");
						return 0;
					}
				}
				else
				{
					backupFileNamePath = storeServerBackupPath;
				}

				try
				{
					// unpack archive
					FileUtils.UnzipFiles(backupFileNamePath, tempFolder);
				}
				catch (Exception ex)
				{
					TaskManager.WriteError(ex, "Can't unzip backup set");
					return 0;
				}

				// load backup catalog
				XmlDocument doc = new XmlDocument();

				try
				{
					doc.Load(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
				}
				catch (Exception ex)
				{
					TaskManager.WriteError(ex, "Can't find/open backup catalog file");
					return 0;
				}

				// validate XML document
				//if (!ValidateXmlDocument(doc))
				//{
				//    TaskManager.WriteError("Corrupted or altered backup catalog file has been read");
				//    return 0;
				//}

				// get the list of items to restore
				string condition = "";
				if (userId > 0)
				{
					// get user spaces
					List<PackageInfo> packages = new List<PackageInfo>();
					packages.AddRange(PackageController.GetMyPackages(userId));
					packages.AddRange(PackageController.GetPackages(userId));
					List<string> parts = new List<string>();
					foreach (PackageInfo package in packages)
						parts.Add("@packageId = " + package.PackageId.ToString());
					condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
				}
				else if (packageId > 0)
				{
					condition = "[@packageId = " + packageId + "]";
				}
				else if (serviceId > 0)
				{
					condition = "[@serviceId = " + serviceId + "]";
				}
				else if (serverId > 0)
				{
					// get server services
					List<ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
					List<string> parts = new List<string>();
					foreach (ServiceInfo service in services)
						parts.Add("@serviceId = " + service.ServiceId.ToString());
					condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
				}

				XmlNodeList itemNodes = doc.SelectNodes("Backup/Items/Item" + condition);

				TaskManager.IndicatorMaximum = itemNodes.Count;
				TaskManager.IndicatorCurrent = 0;

				// group items by item types
				Dictionary<int, List<XmlNode>> groupedItems = new Dictionary<int, List<XmlNode>>();

				// sort by groups
				foreach (XmlNode itemNode in itemNodes)
				{
					int itemTypeId = Utils.ParseInt(itemNode.Attributes["itemTypeId"].Value, 0);
					// add to group
					if (!groupedItems.ContainsKey(itemTypeId))
						groupedItems[itemTypeId] = new List<XmlNode>();

					groupedItems[itemTypeId].Add(itemNode);
				}

				// restore grouped items
				foreach (int itemTypeId in groupedItems.Keys)
				{
					// load item type
					ServiceProviderItemType itemTypeInfo = PackageController.GetServiceItemType(itemTypeId);
					if (!itemTypeInfo.Backupable)
						continue;

					Type itemType = Type.GetType(itemTypeInfo.TypeName);

					// load group
					ResourceGroupInfo group = ServerController.GetResourceGroup(itemTypeInfo.GroupId);

					// instantiate controller
					IBackupController controller = null;
					try
					{
						controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
						if (controller != null)
						{
							// backup items
							foreach (XmlNode itemNode in groupedItems[itemTypeId])
							{
								int itemId = Utils.ParseInt(itemNode.Attributes["itemId"].Value, 0);
								string itemName = itemNode.Attributes["itemName"].Value;
								int itemPackageId = Utils.ParseInt(itemNode.Attributes["packageId"].Value, 0);
								int itemServiceId = Utils.ParseInt(itemNode.Attributes["serviceId"].Value, 0);

								TaskManager.Write(String.Format("Restore {0} '{1}'",
									itemTypeInfo.DisplayName, itemName));

								try
								{
									int restoreResult = controller.RestoreItem(tempFolder, itemNode,
										itemId, itemType, itemName, itemPackageId, itemServiceId, group);
								}
								catch (Exception ex)
								{
									TaskManager.WriteError(ex, "Can't restore item");
								}

								TaskManager.IndicatorCurrent++;
							}
						}
					}
					catch (Exception ex)
					{
						TaskManager.WriteError(ex);
					}
				}

				// delete backup folder and all its contents
				try
				{
					Directory.Delete(tempFolder, true);
				}
				catch (Exception ex)
				{
					TaskManager.WriteError(ex, "Can't delete temporary backup folder");
					return 0;
				}
			}
			catch (Exception ex)
			{
				TaskManager.WriteError(ex);
			}
			finally
			{
				TaskManager.CompleteTask();
			}

			return 0;
		}
Esempio n. 32
0
		public static bool RemoteServerFolderWriteAccessible(int packageId, string path)
		{
			try
			{
				// copy to space folder
				int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
				if (osServiceId > 0)
				{
					OS.OperatingSystem os = new OS.OperatingSystem();
					ServiceProviderProxy.Init(os, osServiceId);

					string remoteServerPathCheck = FilesController.GetFullPackagePath(packageId,
						Path.Combine(path, "check.txt"));

					//
					os.CreateFile(remoteServerPathCheck);
					os.AppendFileBinaryContent(remoteServerPathCheck, Encoding.UTF8.GetBytes(remoteServerPathCheck));
					os.DeleteFile(remoteServerPathCheck);
				}
				//
				return true;
			}
			catch
			{
				//
				return false;
			}
		}
Esempio n. 33
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", 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();
            }
        }
Esempio n. 34
0
        private static int CreatePackageHome(int resellerPackageId, int packageId, int userId)
        {
            // request OS service
            int osId = GetPackageServiceId(packageId, ResourceGroups.Os);
            if (osId == 0)
                return 0;
            //return BusinessErrorCodes.ERROR_OS_RESOURCE_UNAVAILABLE;

            // load user details
            UserInfo user = UserController.GetUser(userId);

            // load package
            string initialPath = null;

            // load package settings
            PackageSettings packageSettings = PackageController.GetPackageSettings(packageId,
                PackageSettings.SPACES_FOLDER);

            if (!String.IsNullOrEmpty(packageSettings["ChildSpacesFolder"]))
            {
                initialPath = Path.Combine(
                    FilesController.GetFullPackagePath(resellerPackageId, packageSettings["ChildSpacesFolder"]),
                    user.Username);

            }
            else
            {
                // load service settings
                StringDictionary osSesstings = ServerController.GetServiceSettings(osId);

                // build initial path
                string usersHome = osSesstings["UsersHome"];
                if (!usersHome.EndsWith("\\"))
                    usersHome += '\\';

                initialPath = Path.Combine(usersHome, user.Username);
            }

            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, osId);
            string path = os.CreatePackageFolder(initialPath);

            // store home folder info
            HomeFolder homeFolder = new HomeFolder();
            homeFolder.ServiceId = osId;
            homeFolder.PackageId = packageId;
            homeFolder.Name = path;

            // save package item
            return AddPackageItem(homeFolder);
        }
Esempio n. 35
0
        public void ImportItem(int packageId, int itemTypeId, Type itemType,
			ResourceGroupInfo group, string itemName)
        {
			// Controller supports web sites only
			if (itemType != typeof(WebSite))
				return;
            // Get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
            if (serviceId == 0)
                return;
            //
            WebServer web = GetWebServer(serviceId);
			// Obtaining web site unique id
			string siteId = web.GetSiteId(itemName);
			if (siteId == null)
				return;
            // Obtaining OperatingSystem service provider id within the context of package.
            int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
            if (osServiceId == 0)
                return;
			//
            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, osServiceId);

            // get site info
            WebSite site = web.GetSite(siteId);
			PackageIPAddress ipMatch = default(PackageIPAddress);

			#region Resolving web site ip
			// Loading package context to evaluate IP Addresses quota
			PackageContext packageCtx = PackageController.GetPackageContext(packageId);

            // We are unable to step further because there are 
            // no bindings on the web site to choose from
            if (site.Bindings == null || site.Bindings.Length == 0)
            {
                TaskManager.WriteError("Could not import the web site because it has no bindings assigned.");
                return;
            }

			// Loading service provider settings
			StringDictionary webSettings = ServerController.GetServiceSettings(serviceId);
			int sharedIpId = Utils.ParseInt(webSettings["SharedIP"], 0);
			IPAddressInfo sharedIp = ServerController.GetIPAddress(sharedIpId);

			// Trying to match site's bindings to against either 
			// external or internal address of the shared ip
			bool sharedIpMatch = Array.Exists(site.Bindings, 
				x => sharedIp != null && (x.IP.Equals(sharedIp.ExternalIP) || x.IP.Equals(sharedIp.InternalIP)));

			// Quering dedicated ips package quota allotted
			bool dedicatedIpsAllotted = Array.Exists(packageCtx.QuotasArray,
				x => x.QuotaName == Quotas.WEB_IP_ADDRESSES && x.QuotaAllocatedValue != 0);

			// By default we fallback to the service provider's shared ip,
			// so the web site being imported is "hooked up" to the proper ip,
			// even if current bindings match different ip for some reason
			if (!dedicatedIpsAllotted || sharedIpMatch)
			{
				site.SiteIPAddressId = sharedIpId;
			}

			// Trying to find a match in dedicated ips list if any.
			if (dedicatedIpsAllotted && !sharedIpMatch)
			{
				// Obtaining first binding with non-empty ip
				ServerBinding binding = Array.Find<ServerBinding>(site.Bindings, x => !String.IsNullOrEmpty(x.IP));
				// No bindings were found - throw an exception
				if (binding == null)
				{
					TaskManager.WriteError(@"Could not import the web site because IP address field of all of its bindings is empty. 
Please ensure the web site has been assigned bindings in the appropriate format and then try to run import procedure once again.");
					return;
				}
				//
				ServiceInfo webService = ServerController.GetServiceInfo(serviceId);
				// Loading ip addresses from Web Sites address pool related to the package
				List<PackageIPAddress> ips = ServerController.GetPackageUnassignedIPAddresses(packageId, IPAddressPool.WebSites);
				// Looking for an entry matching by package and external/internal ip
				ipMatch = Array.Find<PackageIPAddress>(ips.ToArray(),
					x => x.ExternalIP == binding.IP || x.InternalIP == binding.IP);
				// No match has been found - we are in a fault state
				if (ipMatch == null)
				{
					TaskManager.WriteError(@"Could not import the web site because no dedicated IP address match in the target space has been found. 
Please ensure the space has been allocated {0} IP address as a dedicated one and it is free. Then try to run import procedure once again.", binding.IP);
					return;
				}
				//
				site.SiteIPAddressId = ipMatch.AddressID;
			}
			#endregion

            // folders
            UserInfo user = PackageController.GetPackageOwner(packageId);
            UserSettings webPolicy = UserController.GetUserSettings(user.UserId, UserSettings.WEB_POLICY);
            string packageHome = FilesController.GetHomeFolder(packageId);

            // add random string to the domain if specified
            string randDomainName = itemName;
            if (!String.IsNullOrEmpty(webPolicy["AddRandomDomainString"])
                && Utils.ParseBool(webPolicy["AddRandomDomainString"], false))
                randDomainName += "_" + Utils.GetRandomString(DOMAIN_RANDOM_LENGTH);

            // ROOT folder
            string contentPath = GetWebFolder(packageId, WEBSITE_ROOT_FOLDER_PATTERN, randDomainName);
            if (!String.IsNullOrEmpty(webPolicy["WebRootFolder"]))
                contentPath = GetWebFolder(packageId, webPolicy["WebRootFolder"], randDomainName);

            // LOGS folder
            string logsPath = GetWebFolder(packageId, WEBSITE_LOGS_FOLDER_PATTERN, randDomainName);
            if (!String.IsNullOrEmpty(webPolicy["WebLogsFolder"]))
                logsPath = GetWebFolder(packageId, webPolicy["WebLogsFolder"], randDomainName);

            // DATA folder
            string dataPath = GetWebFolder(packageId, WEBSITE_DATA_FOLDER_PATTERN, randDomainName);
            if (!String.IsNullOrEmpty(webPolicy["WebDataFolder"]))
                dataPath = GetWebFolder(packageId, webPolicy["WebDataFolder"], randDomainName);

            // copy site files
			try
			{
				os.CopyFile(site.ContentPath, contentPath);
			}
			catch (Exception ex)
			{
				TaskManager.WriteError(ex, "Can't copy web site files");
			}

            // copy site logs
            try
            {
                string logFolder = (site.IIs7) ? site[WebSite.IIS7_SITE_ID] : "W3SVC" + siteId;
                string logsSrcFolder = Path.Combine(site.LogsPath, logFolder);
                if (os.DirectoryExists(logsSrcFolder))
                    os.CopyFile(logsSrcFolder, Path.Combine(logsPath, logFolder));
            }
			catch (Exception ex)
			{
				TaskManager.WriteError(ex, "Can't copy web site log files");
			}

            // set new folders
            site.ContentPath = contentPath;
            site.LogsPath = logsPath;
            site.DataPath = dataPath;

            // update web site
            web.UpdateSite(site);

            // process virtual directories
            WebVirtualDirectory[] virtDirs = web.GetVirtualDirectories(siteId);
            foreach (WebVirtualDirectory virtDirPointer in virtDirs)
            {
                try
                {
                    // load virtual directory
                    WebVirtualDirectory virtDir = web.GetVirtualDirectory(siteId, virtDirPointer.Name);

                    // copy directory files
                    string vdirPath = Path.Combine(contentPath, virtDir.Name);
                    os.CopyFile(virtDir.ContentPath, vdirPath);

                    virtDir.ContentPath = vdirPath;

                    // update directory
                    web.UpdateVirtualDirectory(siteId, virtDir);
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, String.Format("Error importing '{0}' virtual directory",
                        virtDirPointer.Name));
                    continue;
                }
            }

            // import web site
            site.ServiceId = serviceId;
            site.PackageId = packageId;
            site.Name = itemName;
            site.SiteId = siteId;
            int webSiteId = PackageController.AddPackageItem(site);
			// Assign dedicated IP address to the web site from package context.
			if (ipMatch != null)
			{
				ServerController.AddItemIPAddress(webSiteId, ipMatch.PackageAddressID);
			}

            // restore/update domains
            RestoreDomainsByWebSite(site.Bindings, packageId, webSiteId, itemName);
        }
Esempio n. 36
0
        public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
        {
            if (item is HomeFolder)
            {
                // backup home folder files
                string backupName = String.Format("SpaceFiles_{0}_{1}.zip",
                                                  item.Id, DateTime.Now.Ticks);

                // get the list of remote files
                List <SystemFile> files = FilesController.GetFiles(item.PackageId, "\\", true);

                string[] zipFiles = new string[files.Count];
                for (int i = 0; i < zipFiles.Length; i++)
                {
                    zipFiles[i] = files[i].Name;
                }

                // zip remote files
                FilesController.ZipFiles(item.PackageId, zipFiles, backupName);

                // download zipped file
                string localBackupPath = Path.Combine(tempFolder, backupName);

                byte[]     buffer = null;
                FileStream stream = new FileStream(localBackupPath, FileMode.Create, FileAccess.Write);

                int  offset = 0;
                long length = 0;
                do
                {
                    // read remote content
                    buffer = FilesController.GetFileBinaryChunk(item.PackageId, backupName, offset, FILE_BUFFER_LENGTH);

                    // write remote content
                    stream.Write(buffer, 0, buffer.Length);

                    length += buffer.Length;
                    offset += FILE_BUFFER_LENGTH;
                }while (buffer.Length == FILE_BUFFER_LENGTH);
                stream.Close();

                // delete zipped file
                if (FilesController.FileExists(item.PackageId, backupName))
                {
                    FilesController.DeleteFiles(item.PackageId, new string[] { backupName });
                }

                // add file pointer
                BackupController.WriteFileElement(writer, "SpaceFiles", backupName, length);

                // store meta item
                XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder));
                serializer.Serialize(writer, item);
            }
            else if (item is SystemDSN)
            {
                // backup ODBC DSN
                OS.OperatingSystem os = GetOS(item.ServiceId);

                // read DSN info
                SystemDSN itemDsn = item as SystemDSN;
                SystemDSN dsn     = os.GetDSN(item.Name);
                dsn.DatabasePassword = itemDsn.DatabasePassword;

                XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN));
                serializer.Serialize(writer, dsn);
            }

            return(0);
        }
Esempio n. 37
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);
				TaskManager.ItemId = SecurityContext.User.UserId;

				// get the list of items to backup
				TaskManager.Write("Calculate items to backup");
				List<ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);

				if (items.Count == 0)
					return 0;

				// group items by item types
				Dictionary<int, List<ServiceProviderItem>> groupedItems = new Dictionary<int, List<ServiceProviderItem>>();

				// sort by groups
				foreach (ServiceProviderItem item in items)
				{
					// add to group
					if (!groupedItems.ContainsKey(item.TypeId))
						groupedItems[item.TypeId] = new List<ServiceProviderItem>();

					groupedItems[item.TypeId].Add(item);
				}

				// temp backup folder
				string tempFolder = GetTempBackupFolder();

				// create backup catalog file
				StringWriter sw = new StringWriter();
				XmlTextWriter writer = new XmlTextWriter(sw);

				// write backup file header
				writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
				writer.WriteStartElement("Backup");
				writer.WriteStartElement("Info");
				writer.WriteElementString("Name", backupFileName);
				writer.WriteElementString("Created", DateTime.Now.ToString("r"));
				writer.WriteElementString("User", GetLoggedUsername());
				writer.WriteEndElement(); // Info

				// determine the number of items to backup
				int totalItems = 0;
				foreach (int itemTypeId in groupedItems.Keys)
				{
					// load item type
					ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
					if (!itemType.Backupable)
						continue;

					totalItems += groupedItems[itemTypeId].Count;
				}

				TaskManager.IndicatorMaximum = totalItems + 2;
				TaskManager.IndicatorCurrent = 0;

				// backup grouped items
				writer.WriteStartElement("Items");
				foreach (int itemTypeId in groupedItems.Keys)
				{
					// load item type
					ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
					if (!itemType.Backupable)
						continue;

					// load group
					ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);

					// instantiate controller
					IBackupController controller = null;
					try
					{
						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;
					}
				}

			}
			catch (Exception ex)
			{
				TaskManager.WriteError(ex);
			}
			finally
			{
				TaskManager.CompleteTask();
			}

			return 0;
		}
Esempio n. 38
0
        // This gets the system quota and updates the home folder with the value
        public static void UpdatePackageHardQuota(int packageId)
        {
            // request OS service
            int osId = GetPackageServiceId(packageId, ResourceGroups.Os);
            if (osId == 0)
                return;

            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, osId);

            //Get operating system settings
            StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
            bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false;
            string driveName = osSesstings["LocationDrive"];

            if (!diskQuotaEnabled)
                return;

            string homeFolder = FilesController.GetHomeFolder(packageId);
            FilesController.SetFolderQuota(packageId, homeFolder, driveName, Quotas.OS_DISKSPACE);

        }
        public int InstallWebApplication(InstallationInfo inst)
        {
            // place log record
            TaskManager.StartTask("APP_INSTALLER", "INSTALL_APPLICATION");
            TaskManager.WriteParameter("Virtual directory", inst.VirtualDir);
            TaskManager.WriteParameter("Database group", inst.DatabaseGroup);
            TaskManager.ItemId = inst.PackageId;

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

                TaskManager.ItemName = app.Name;

                // 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();
            }
        }
        private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB

        private static OS.OperatingSystem GetOS(int serviceId)
        {
            OS.OperatingSystem os = new OS.OperatingSystem();
            ServiceProviderProxy.Init(os, serviceId);
            return os;
        }
Esempio n. 41
0
        public static int ApplyEnableHardQuotaFeature(int packageId)
        {
            if (SecurityContext.CheckAccount(DemandAccount.IsActive | DemandAccount.IsAdmin | DemandAccount.NotDemo) != 0)
                throw new Exception("This method could be called by serveradmin only.");

            // place log record
            TaskManager.StartTask("FILES", "APPLY_ENABLEHARDQUOTAFEATURE");

            try
            {

                // request OS service
                //int osId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
                //if (osId == 0)
                //    return -1;

                //OS.OperatingSystem os = new OS.OperatingSystem();
                //ServiceProviderProxy.Init(os, osId);

                ////Get operating system settings
                // StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
                //  bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false;
                //string driveName = osSesstings["LocationDrive"];

                //if (!diskQuotaEnabled)
                //    return -1;


                List<PackageInfo> allPackages = PackageController.GetPackagePackages(packageId, true);

                foreach (PackageInfo childPackage in allPackages)
                {
                    // request OS service
                    int osId = PackageController.GetPackageServiceId(childPackage.PackageId, ResourceGroups.Os);
                    if (osId == 0)
                        continue;

                    OS.OperatingSystem os = new OS.OperatingSystem();
                    ServiceProviderProxy.Init(os, osId);

                    //Get operating system settings
                    StringDictionary osSesstings = ServerController.GetServiceSettings(osId);
                    string driveName = osSesstings["LocationDrive"];

                    if (String.IsNullOrEmpty(driveName))
                        continue;

                    string homeFolder = FilesController.GetHomeFolder(childPackage.PackageId);
                    FilesController.SetFolderQuota(childPackage.PackageId, homeFolder, driveName, Quotas.OS_DISKSPACE);
                }
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }

            return 0;
        }