コード例 #1
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();
            }
        }
コード例 #2
0
        public override void DoWork()
        {
            BackgroundTask topTask = TaskManager.TopTask;

            List <DomainDnsChanges> domainsChanges = new List <DomainDnsChanges>();
            var domainUsers = new Dictionary <int, UserInfo>();

            // get input parameters
            string dnsServersString = (string)topTask.GetParamValue(DnsServersParameter);
            string serverName       = (string)topTask.GetParamValue(ServerNameParameter);

            int pause;

            // check input parameters
            if (String.IsNullOrEmpty(dnsServersString))
            {
                TaskManager.WriteWarning("Specify 'DNS' task parameter.");
                return;
            }

            if (String.IsNullOrEmpty((string)topTask.GetParamValue("MAIL_TO")))
            {
                TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty.");
                return;
            }


            if (!int.TryParse((string)topTask.GetParamValue(PauseBetweenQueriesParameter), out pause))
            {
                TaskManager.WriteWarning("The 'pause between queries' parameter is not valid.");
                return;
            }

            // find server by name
            ServerInfo server = ServerController.GetServerByName(serverName);

            if (server == null)
            {
                TaskManager.WriteWarning(String.Format("Server with the name '{0}' was not found", serverName));
                return;
            }

            WindowsServer winServer = new WindowsServer();

            ServiceProviderProxy.ServerInit(winServer, server.ServerId);

            var user = UserController.GetUser(topTask.UserId);

            var dnsServers = dnsServersString.Split(';');

            var packages = ObjectUtils.CreateListFromDataReader <PackageInfo>(DataProvider.GetAllPackages());


            foreach (var package in packages)
            {
                var domains = ServerController.GetDomains(package.PackageId);

                domains = domains.Where(x => !x.IsSubDomain && !x.IsDomainPointer).ToList(); //Selecting top-level domains

                //domains = domains.Where(x => x.ZoneItemId > 0).ToList(); //Selecting only dns enabled domains

                foreach (var domain in domains)
                {
                    if (domainsChanges.Any(x => x.DomainName == domain.DomainName))
                    {
                        continue;
                    }

                    if (!domainUsers.ContainsKey(domain.PackageId))
                    {
                        var domainUser = UserController.GetUser(packages.First(x => x.PackageId == domain.PackageId).UserId);

                        domainUsers.Add(domain.PackageId, domainUser);
                    }

                    DomainDnsChanges domainChanges = new DomainDnsChanges();
                    domainChanges.DomainName     = domain.DomainName;
                    domainChanges.PackageId      = domain.PackageId;
                    domainChanges.Registrar      = domain.RegistrarName;
                    domainChanges.ExpirationDate = domain.ExpirationDate;

                    var dbDnsRecords = ObjectUtils.CreateListFromDataReader <DnsRecordInfo>(DataProvider.GetDomainAllDnsRecords(domain.DomainId));

                    //execute server
                    foreach (var dnsServer in dnsServers)
                    {
                        var dnsMxRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.MX, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX).ToList();
                        var dnsNsRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.NS, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS).ToList();

                        FillRecordData(dnsMxRecords, domain, dnsServer);
                        FillRecordData(dnsNsRecords, domain, dnsServer);

                        domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX), dnsMxRecords, dnsServer));
                        domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS), dnsNsRecords, dnsServer));

                        domainChanges.DnsChanges = CombineDnsRecordChanges(domainChanges.DnsChanges, dnsServer).ToList();
                    }

                    domainsChanges.Add(domainChanges);
                }
            }

            var changedDomains = FindDomainsWithChangedRecords(domainsChanges);

            SendMailMessage(user, changedDomains, domainUsers);
        }
コード例 #3
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();
            }
        }
コード例 #4
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, 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();
            }
        }
コード例 #5
0
        public void ImportItem(int packageId, int itemTypeId, Type itemType,
                               ResourceGroupInfo group, string itemName)
        {
            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);

            if (serviceId == 0)
            {
                return;
            }

            if (itemType == typeof(DnsZone))
            {
                // Get ascii form in punycode
                var zoneName = GetAsciiZoneName(itemName);

                // add DNS zone
                DnsZone zone = new DnsZone();
                zone.Name      = zoneName;
                zone.ServiceId = serviceId;
                zone.PackageId = packageId;
                int zoneId = PackageController.AddPackageItem(zone);

                // Add secondary zone(s)
                try
                {
                    // get secondary DNS services
                    var primSettings         = ServerController.GetServiceSettings(serviceId);
                    var secondaryServiceIds  = new List <int>();
                    var strSecondaryServices = primSettings["SecondaryDNSServices"];
                    if (!String.IsNullOrEmpty(strSecondaryServices))
                    {
                        var secondaryServices = strSecondaryServices.Split(',');
                        secondaryServiceIds.AddRange(secondaryServices.Select(strSecondaryId => Utils.ParseInt(strSecondaryId, 0)).Where(secondaryId => secondaryId != 0));
                    }

                    // add secondary zones
                    var secondaryZoneFound = false;

                    foreach (var secondaryId in secondaryServiceIds)
                    {
                        var secDns = GetDNSServer(secondaryId);
                        if (secDns.ZoneExists(zoneName))
                        {
                            secondaryZoneFound = true;

                            var secondaryZone = new SecondaryDnsZone
                            {
                                Name      = zoneName,
                                ServiceId = secondaryId,
                                PackageId = packageId
                            };

                            PackageController.AddPackageItem(secondaryZone);
                        }
                    }

                    if (!secondaryZoneFound)
                    {
                        TaskManager.WriteWarning("No secondary zone(s) found when importing zone " + itemName);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Error importing secondary zone(s)");
                }


                // add/update domains/pointers
                RestoreDomainByZone(itemName, packageId, zoneId);
            }
        }
コード例 #6
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);
        }
コード例 #7
0
        public ServiceProviderItemDiskSpace[] CalculateItems(int serviceId, List <ServiceProviderItem> items)
        {
            // convert items to SoapObjects
            List <SoapServiceProviderItem> objItems = new List <SoapServiceProviderItem>();

            //hack for organization... Refactoring!!!


            List <ServiceProviderItemDiskSpace> organizationDiskSpaces = new List <ServiceProviderItemDiskSpace>();

            foreach (ServiceProviderItem item in items)
            {
                long size = 0;
                if (item is Organization)
                {
                    Organization org = (Organization)item;

                    //Exchange DiskSpace
                    if (!string.IsNullOrEmpty(org.GlobalAddressList))
                    {
                        int exchangeServiceId = GetExchangeServiceID(org.PackageId);
                        if (exchangeServiceId > 0)
                        {
                            ServiceProvider exchangeProvider = ExchangeServerController.GetExchangeServiceProvider(exchangeServiceId, item.ServiceId);

                            SoapServiceProviderItem        soapOrg        = SoapServiceProviderItem.Wrap(org);
                            ServiceProviderItemDiskSpace[] itemsDiskspace =
                                exchangeProvider.GetServiceItemsDiskSpace(new SoapServiceProviderItem[] { soapOrg });

                            if (itemsDiskspace != null && itemsDiskspace.Length > 0)
                            {
                                size += itemsDiskspace[0].DiskSpace;
                            }
                        }
                    }

                    // Crm DiskSpace
                    if (org.CrmOrganizationId != Guid.Empty)
                    {
                        //CalculateCrm DiskSpace
                    }

                    //SharePoint DiskSpace

                    int res;

                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    if (cntx.Groups.ContainsKey(ResourceGroups.SharepointFoundationServer))
                    {
                        SharePointSiteDiskSpace[] sharePointSiteDiskSpaces =
                            HostedSharePointServerController.CalculateSharePointSitesDiskSpace(org.Id, out res);
                        if (res == 0)
                        {
                            foreach (SharePointSiteDiskSpace currecnt in sharePointSiteDiskSpaces)
                            {
                                size += currecnt.DiskSpace;
                            }
                        }
                    }

                    if (cntx.Groups.ContainsKey(ResourceGroups.SharepointEnterpriseServer))
                    {
                        SharePointSiteDiskSpace[] sharePointSiteDiskSpaces =
                            HostedSharePointServerEntController.CalculateSharePointSitesDiskSpace(org.Id, out res);
                        if (res == 0)
                        {
                            foreach (SharePointSiteDiskSpace currecnt in sharePointSiteDiskSpaces)
                            {
                                size += currecnt.DiskSpace;
                            }
                        }
                    }

                    ServiceProviderItemDiskSpace tmp = new ServiceProviderItemDiskSpace();
                    tmp.ItemId    = item.Id;
                    tmp.DiskSpace = size;
                    organizationDiskSpaces.Add(tmp);
                }
                else
                {
                    objItems.Add(SoapServiceProviderItem.Wrap(item));
                }
            }


            int attempt  = 0;
            int ATTEMPTS = 3;

            while (attempt < ATTEMPTS)
            {
                // increment attempt
                attempt++;

                try
                {
                    // send packet for calculation
                    // invoke service provider
                    //TaskManager.Write(String.Format("{0} - Invoke GetServiceItemsDiskSpace method ('{1}' items) - {2} attempt",
                    //    DateTime.Now, objItems.Count, attempt));

                    if (objItems.Count > 0)
                    {
                        ServiceProvider prov = new ServiceProvider();
                        ServiceProviderProxy.Init(prov, serviceId);
                        ServiceProviderItemDiskSpace[] itemsDiskSpace = prov.GetServiceItemsDiskSpace(objItems.ToArray());
                        if (itemsDiskSpace != null && itemsDiskSpace.Length > 0)
                        {
                            organizationDiskSpaces.AddRange(itemsDiskSpace);
                        }
                    }

                    return(organizationDiskSpaces.ToArray());
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex.ToString());
                }
            }

            throw new Exception("The number of attemtps has been reached. The package calculation has been aborted.");
        }
コード例 #8
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);
        }
コード例 #9
0
        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();
            }
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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);
        }
コード例 #12
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);
        }
コード例 #13
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);
        }