public static ResultObject DeleteOrganizationDomain(int itemId, string domainName)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

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

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

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

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

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

                // delete domain
                exchange.DeleteOrganizationDomain(item.Name, domainName);

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

                // exit with error code
                return(Error <ResultObject>(DeleteDomainError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 2
0
 internal static void TraceGalleryAppPackInfo(GalleryApplication webAppPack)
 {
     if (webAppPack != null)
     {
         //
         TaskManager.WriteParameter("Title", webAppPack.Title);
         TaskManager.WriteParameter("Version", webAppPack.Version);
         TaskManager.WriteParameter("Download URL", webAppPack.DownloadUrl);
         TaskManager.WriteParameter("Author", webAppPack.AuthorName);
         TaskManager.WriteParameter("Last Updated", webAppPack.LastUpdated);
     }
 }
Esempio n. 3
0
        public static int DeleteWebPartsPackage(int itemId, string packageName)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

            if (item == null)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND);
            }

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

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

            // place log record
            TaskManager.StartTask("SHAREPOINT", "UNINSTALL_WEBPARTS", item.Name);
            TaskManager.ItemId = itemId;
            TaskManager.WriteParameter("Package name", packageName);

            try
            {
                SharePointServer sps = GetSharePoint(item.ServiceId);

                // uninstall webparts
                if (!String.IsNullOrEmpty(packageName))
                {
                    sps.DeleteWebPartsPackage(item.Name, packageName);
                }

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int UpdateSqlDatabase(SqlDatabase item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

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

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

            // place log record
            TaskManager.StartTask("SQL_DATABASE", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;
            TaskManager.WriteParameter("Provider", origItem.GroupName);

            try
            {
                // get service
                DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);

                // update service item
                sql.UpdateDatabase(item);
                return(0);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                // Return a generic error instead of re-throwing an exception
                return(BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 5
0
        public override void DoWork()
        {
            try
            {
                TaskManager.Write("Start HostedSolutionReportTask");

                BackgroundTask topTask = TaskManager.TopTask;

                bool isExchange     = Utils.ParseBool(topTask.GetParamValue(EXCHANGE_REPORT), false);
                bool isSharePoint   = Utils.ParseBool(topTask.GetParamValue(SHAREPOINT_REPORT), false);
                bool isLync         = Utils.ParseBool(topTask.GetParamValue(LYNC_REPORT), false);
                bool isCRM          = Utils.ParseBool(topTask.GetParamValue(CRM_REPORT), false);
                bool isOrganization = Utils.ParseBool(topTask.GetParamValue(ORGANIZATION_REPORT), false);

                string email = topTask.GetParamValue(EMAIL).ToString();

                TaskManager.WriteParameter("isExchange", isExchange);
                TaskManager.WriteParameter("isSharePoint", isSharePoint);
                TaskManager.WriteParameter("isLync", isLync);
                TaskManager.WriteParameter("isCRM", isCRM);
                TaskManager.WriteParameter("isOrganization", isOrganization);
                TaskManager.WriteParameter("email", email);

                UserInfo user = PackageController.GetPackageOwner(topTask.PackageId);

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

                EnterpriseSolutionStatisticsReport report =
                    ReportController.GetEnterpriseSolutionStatisticsReport(user.UserId, isExchange, isSharePoint, isCRM,
                                                                           isOrganization, isLync);

                TaskManager.WriteParameter("report.ExchangeReport.Items.Count", report.ExchangeReport.Items.Count);
                TaskManager.WriteParameter("report.SharePointReport.Items.Count", report.SharePointReport.Items.Count);
                TaskManager.WriteParameter("report.CRMReport.Items.Count", report.CRMReport.Items.Count);
                TaskManager.WriteParameter("report.OrganizationReport.Items.Count", report.OrganizationReport.Items.Count);
                TaskManager.WriteParameter("report.LyncReport.Items.Count", report.LyncReport.Items.Count);

                SendMessage(user, email, isExchange && report.ExchangeReport != null ? report.ExchangeReport.ToCSV() : string.Empty,
                            isSharePoint && report.SharePointReport != null ? report.SharePointReport.ToCSV() : string.Empty,
                            isCRM && report.CRMReport != null ? report.CRMReport.ToCSV() : string.Empty,
                            isOrganization && report.OrganizationReport != null ? report.OrganizationReport.ToCSV() : string.Empty,
                            isLync && report.LyncReport != null ? report.LyncReport.ToCSV() : string.Empty);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
            }

            TaskManager.Write("End HostedSolutionReportTask");
        }
Esempio n. 6
0
        public static int AuthenticateUser(string username, string password, string ip)
        {
            // start task
            TaskManager.StartTask("USER", "AUTHENTICATE", username);
            TaskManager.WriteParameter("IP", ip);

            try
            {
                // try to get user from database
                UserInfo user = GetUserInternally(username);

                // check if the user exists
                if (user == null)
                {
                    TaskManager.WriteWarning("Wrong username");
                    return(BusinessErrorCodes.ERROR_USER_WRONG_USERNAME);
                }

                // compare user passwords
                if (user.Password != password)
                {
                    TaskManager.WriteWarning("Wrong password");
                    return(BusinessErrorCodes.ERROR_USER_WRONG_PASSWORD);
                }

                // check status
                if (user.Status == UserStatus.Cancelled)
                {
                    TaskManager.WriteWarning("Account cancelled");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED);
                }

                if (user.Status == UserStatus.Pending)
                {
                    TaskManager.WriteWarning("Account pending");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING);
                }

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public void DeletePackagesServiceItems()
        {
            // impersonate thread
            if (userId != -1)
            {
                SecurityContext.SetThreadPrincipal(userId);
            }


            // delete package by package
            foreach (PackageInfo package in packages)
            {
                TaskManager.StartTask("SPACE", "DELETE_ITEMS", package.PackageName);
                TaskManager.WriteParameter("User", package.UserId);

                // get package service items
                List <ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
                    0, package.PackageId, false, false, false, true); // disposable items

                // order items by service
                Dictionary <int, List <ServiceProviderItem> > orderedItems =
                    PackageController.OrderServiceItemsByServices(items);

                // delete service items by service sets
                foreach (int serviceId in orderedItems.Keys)
                {
                    ServiceInfo service = ServerController.GetServiceInfo(serviceId);
                    //Delete Exchange Organization
                    if (service.ProviderId == 103 /*Organizations*/)
                    {
                        OrganizationController.DeleteOrganization(orderedItems[serviceId][0].Id);
                        //int exchangeId = PackageController.GetPackageServiceId(package.PackageId, ResourceGroups.Exchange2007);
                        //ExchangeServerController.DeleteOrganization(orderedItems[serviceId][0].Id);
                    }
                    else
                    {
                        ProcessServiceItems(false, false, serviceId, orderedItems[serviceId]);
                    }
                }

                // delete package from database
                DataProvider.DeletePackage(SecurityContext.User.UserId, package.PackageId);
            }

            // add log record
            TaskManager.CompleteTask();
        }
Esempio n. 8
0
        private void SendMessage(UserInfo user, string email, string exchange_csv, string sharepoint_csv, string crm_csv, string organization_csv, string lync_csv)
        {
            TaskManager.Write("SendMessage");

            List <Attachment> attacments = new List <Attachment>();

            PrepareAttament("exchange.csv", exchange_csv, attacments);
            PrepareAttament("sharepoint.csv", sharepoint_csv, attacments);
            PrepareAttament("lync.csv", lync_csv, attacments);
            PrepareAttament("crm.csv", crm_csv, attacments);
            PrepareAttament("organization.csv", organization_csv, attacments);

            // get letter settings
            UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.HOSTED_SOLUTION_REPORT);

            string from    = settings["From"];
            string cc      = settings["CC"];
            string subject = settings["Subject"];
            string body    = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
            bool   isHtml  = user.HtmlMail;

            MailPriority priority = MailPriority.Normal;

            TaskManager.WriteParameter("from", from);
            TaskManager.WriteParameter("email", email);
            TaskManager.WriteParameter("subject", subject);
            TaskManager.WriteParameter("body", body);


            int res = MailHelper.SendMessage(from, email, cc, subject, body, priority, isHtml, attacments.ToArray());

            if (res == 0)
            {
                TaskManager.Write("SendMessage OK");
            }
            else
            {
                TaskManager.WriteError("SendMessage error ", "error code", res.ToString());
            }

            TaskManager.WriteParameter("", res);

            TaskManager.Write("End SendMessage");
        }
Esempio n. 9
0
 public void DownloadGalleryWebApplication()
 {
     SecurityContext.SetThreadPrincipal(UserId);
     //
     TaskManager.StartTask(WebAppGalleryController.TASK_MANAGER_SOURCE, "DOWNLOAD_WEB_APP", GalleryApp.Title);
     TaskManager.WriteParameter("Version", GalleryApp.Version);
     TaskManager.WriteParameter("Download URL", GalleryApp.DownloadUrl);
     TaskManager.WriteParameter("Author", GalleryApp.AuthorName);
     TaskManager.WriteParameter("Last Updated", GalleryApp.LastUpdated);
     TaskManager.WriteParameter("Web App ID", WebAppId);
     //
     try
     {
         //
         WebServer webServer = WebAppGalleryController.GetAssociatedWebServer(PackageId);
         //
         TaskManager.Write("Application package download has been started");
         //
         GalleryWebAppStatus appStatus = webServer.DownloadGalleryApplication(WebAppId);
         //
         if (appStatus == GalleryWebAppStatus.Failed)
         {
             TaskManager.WriteError("Could not download application package requested");
             TaskManager.WriteError("Please check WebsitePanel Server log for further information on this issue");
             TaskManager.WriteParameter("Status returned", appStatus);
             return;
         }
         //
         TaskManager.Write("Application package download has been started successfully");
     }
     catch (Exception ex)
     {
         TaskManager.WriteError(ex);
     }
     finally
     {
         //
         TaskManager.CompleteTask();
     }
 }
Esempio n. 10
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. 11
0
        public static int AddSite(SharePointSite 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.SHAREPOINT_SITES);

            if (quota.QuotaExhausted)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_QUOTA_LIMIT);
            }

            // check if stats resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.SharePoint);

            if (serviceId == 0)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_UNAVAILABLE);
            }

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(SharePointSite)) != null)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_EXISTS);
            }

            // place log record
            TaskManager.StartTask("SHAREPOINT", "ADD_SITE", item.Name);
            TaskManager.WriteParameter("Database group", item.DatabaseGroupName);
            TaskManager.WriteParameter("Database name", item.DatabaseName);
            TaskManager.WriteParameter("Database user", item.DatabaseUser);

            int databaseItemId     = 0;
            int databaseUserItemId = 0;

            try
            {
                // load web site
                WebSite siteItem = (WebSite)PackageController.GetPackageItemByName(item.PackageId,
                                                                                   item.Name, typeof(WebSite));

                if (siteItem == null)
                {
                    return(BusinessErrorCodes.ERROR_WEB_SITE_SERVICE_UNAVAILABLE);
                }

                // get service web site
                WebServer web = new WebServer();
                ServiceProviderProxy.Init(web, siteItem.ServiceId);
                WebSite site = web.GetSite(siteItem.SiteId);

                /////////////////////////////////////////
                //
                //  PREPARE SHAREPOINT SITE INSTALLATION
                //

                ServiceInfo wssService = ServerController.GetServiceInfo(serviceId);
                bool        wss30      = (wssService.ProviderId == 23);     // WSS 3.0

                // remember original web site bindings
                ServerBinding[] bindings = site.Bindings;

                // set application pool and root folder
                item.ApplicationPool = site.ApplicationPool;
                item.RootFolder      = site.ContentPath;

                // change web site .NET framework if required
                bool siteUpdated = false;
                if (!wss30 && (site.AspNetInstalled != "1" ||
                               site.DedicatedApplicationPool))
                {
                    site.AspNetInstalled          = "1";
                    site.DedicatedApplicationPool = false;
                    web.UpdateSite(site);

                    siteUpdated = true;
                }

                if (wss30 && site.AspNetInstalled != "2")
                {
                    site.AspNetInstalled = "2";
                    web.UpdateSite(site);

                    siteUpdated = true;
                }

                if (siteUpdated)
                {
                    site = web.GetSite(siteItem.SiteId);
                    item.ApplicationPool = site.ApplicationPool;
                }

                if (site.FrontPageInstalled)
                {
                    // remove FrontPage
                    web.UninstallFrontPage(siteItem.SiteId, siteItem.FrontPageAccount);
                }

                // create SQL database
                SqlDatabase database = new SqlDatabase();
                database.PackageId = item.PackageId;
                database.Name      = item.DatabaseName;
                databaseItemId     = DatabaseServerController.AddSqlDatabase(database, item.DatabaseGroupName);
                if (databaseItemId < 0)
                {
                    return(databaseItemId);
                }

                // create SQL user
                SqlUser dbUser = new SqlUser();
                dbUser.PackageId   = item.PackageId;
                dbUser.Name        = item.DatabaseUser;
                dbUser.Password    = item.DatabasePassword;
                databaseUserItemId = DatabaseServerController.AddSqlUser(dbUser, item.DatabaseGroupName);
                if (databaseUserItemId < 0)
                {
                    return(databaseUserItemId);
                }

                // delete SQL database from service
                // and change database user role
                int sqlServiceId = PackageController.GetPackageServiceId(item.PackageId, item.DatabaseGroupName);
                if (sqlServiceId < 0)
                {
                    return(BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE);
                }

                // load server settings
                StringDictionary sqlSettings = ServerController.GetServiceSettings(sqlServiceId);
                item.DatabaseServer = sqlSettings["ExternalAddress"];

                DatabaseServer dbServer = new DatabaseServer();
                ServiceProviderProxy.Init(dbServer, sqlServiceId);

                // delete database from service
                dbServer.DeleteDatabase(database.Name);

                // give SQL user "db_creator" role
                dbServer.ExecuteSqlNonQuery("master", String.Format(
                                                "sp_addsrvrolemember '{0}', 'dbcreator'\nGO", dbUser.Name));

                // install SharePoint site
                SharePointServer sps = GetSharePoint(serviceId);
                sps.ExtendVirtualServer(item);

                // remove SQL user from "db_creator" role
                dbServer.ExecuteSqlNonQuery("master", String.Format(
                                                "sp_dropsrvrolemember '{0}', 'dbcreator'\nGO", dbUser.Name));

                // restore original web site bindings
                web.UpdateSiteBindings(site.SiteId, bindings);

                // save statistics item
                item.ServiceId = serviceId;
                int itemId = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;

                return(itemId);
            }
            catch (Exception ex)
            {
                // delete database if required
                if (databaseItemId > 0)
                {
                    DatabaseServerController.DeleteSqlDatabase(databaseItemId);
                }

                // delete user if required
                if (databaseUserItemId > 0)
                {
                    DatabaseServerController.DeleteSqlUser(databaseUserItemId);
                }

                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 12
0
        public static int SendPasswordReminder(string username, string ip)
        {
            // place log record
            TaskManager.StartTask("USER", "SEND_REMINDER", username);
            TaskManager.WriteParameter("IP", ip);

            try
            {
                // try to get user from database
                UserInfo user = GetUserInternally(username);
                if (user == null)
                {
                    TaskManager.WriteWarning("Account not found");
                    // Fix for item #273 (NGS-9)
                    //return BusinessErrorCodes.ERROR_USER_NOT_FOUND;
                    return(0);
                }

                UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.PASSWORD_REMINDER_LETTER);
                string       from     = settings["From"];
                string       cc       = settings["CC"];
                string       subject  = settings["Subject"];
                string       body     = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
                bool         isHtml   = user.HtmlMail;

                MailPriority priority = MailPriority.Normal;
                if (!String.IsNullOrEmpty(settings["Priority"]))
                {
                    priority = (MailPriority)Enum.Parse(typeof(MailPriority), settings["Priority"], true);
                }

                if (body == null || body == "")
                {
                    return(BusinessErrorCodes.ERROR_SETTINGS_PASSWORD_LETTER_EMPTY_BODY);
                }

                // set template context items
                Hashtable items = new Hashtable();
                items["user"]  = user;
                items["Email"] = true;

                // get reseller details
                UserInfo reseller = UserController.GetUser(user.OwnerId);
                if (reseller != null)
                {
                    reseller.Password = "";
                    items["reseller"] = reseller;
                }

                subject = PackageController.EvaluateTemplate(subject, items);
                body    = PackageController.EvaluateTemplate(body, items);

                // send message
                MailHelper.SendMessage(from, user.Email, cc, subject, body, priority, isHtml);

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

            result.IsSuccess = true;

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

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

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

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

                // check quotas
                UpdateOrganizationQuotas(item);

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

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

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

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

                // exit with error code
                return(Error <ResultObject>(UpdateQuotasError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 14
0
        public static int AddFtpAccount(FtpAccount item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

            // check quota
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.FTP_ACCOUNTS);

            if (quota.QuotaExhausted)
            {
                return(BusinessErrorCodes.ERROR_FTP_RESOURCE_QUOTA_LIMIT);
            }

            // check if FTP account already exists
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Ftp);

            if (serviceId == 0)
            {
                return(BusinessErrorCodes.ERROR_FTP_RESOURCE_UNAVAILABLE);
            }

            // place log record
            TaskManager.StartTask("FTP_ACCOUNT", "ADD", item.Name);
            TaskManager.WriteParameter("Folder", item.Folder);
            TaskManager.WriteParameter("CanRead", item.CanRead);
            TaskManager.WriteParameter("CanWrite", item.CanWrite);


            try
            {
                // check package items
                if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(FtpAccount)) != null)
                {
                    return(BusinessErrorCodes.ERROR_FTP_PACKAGE_ITEM_EXISTS);
                }

                // check service items
                FTPServer ftp = new FTPServer();
                ServiceProviderProxy.Init(ftp, serviceId);
                if (ftp.AccountExists(item.Name))
                {
                    return(BusinessErrorCodes.ERROR_FTP_SERVICE_ITEM_EXISTS);
                }

                // store original path
                string origFolder = item.Folder;

                // convert folder
                StringDictionary ftpSettings = ServerController.GetServiceSettings(serviceId);
                if (Utils.ParseBool(ftpSettings["BuildUncFilesPath"], false))
                {
                    // UNC
                    // get OS service
                    int osServiceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Os);
                    item.Folder = FilesController.GetFullUncPackagePath(item.PackageId, osServiceId, item.Folder);
                }
                else
                {
                    // Absolute
                    item.Folder = FilesController.GetFullPackagePath(item.PackageId, item.Folder);
                }

                item.Enabled = true;

                // add service item
                ftp.CreateAccount(item);

                // save item
                item.Password  = CryptoUtils.Encrypt(item.Password);
                item.ServiceId = serviceId;
                item.Folder    = (origFolder == "") ? "\\" : origFolder;
                int itemId = PackageController.AddPackageItem(item);
                TaskManager.ItemId = itemId;
                return(itemId);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                throw;
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 15
0
        public static int UpdateFtpAccount(FtpAccount item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

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

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

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

            TaskManager.WriteParameter("Folder", item.Folder);
            TaskManager.WriteParameter("CanRead", item.CanRead);
            TaskManager.WriteParameter("CanWrite", item.CanWrite);

            try
            {
                // get service
                FTPServer ftp = new FTPServer();
                ServiceProviderProxy.Init(ftp, origItem.ServiceId);

                // store original folder
                string origFolder = item.Folder;

                // convert folder
                StringDictionary ftpSettings = ServerController.GetServiceSettings(origItem.ServiceId);
                if (Utils.ParseBool(ftpSettings["BuildUncFilesPath"], false))
                {
                    // UNC
                    // get OS service
                    int osServiceId = PackageController.GetPackageServiceId(origItem.PackageId, ResourceGroups.Os);
                    item.Folder = FilesController.GetFullUncPackagePath(origItem.PackageId, osServiceId, item.Folder);
                }
                else
                {
                    // Absolute
                    item.Folder = FilesController.GetFullPackagePath(origItem.PackageId, item.Folder);
                }

                item.Enabled = true;

                // add service item
                ftp.UpdateAccount(item);

                // save item
                item.Password = String.IsNullOrEmpty(item.Password) ? origItem.Password : CryptoUtils.Encrypt(item.Password);
                item.Folder   = (origFolder == "") ? "\\" : origFolder;
                PackageController.UpdatePackageItem(item);

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 16
0
        public static StringResultObject Install(int packageId, string webAppId, string siteName, string virtualDir, List <DeploymentParameter> updatedParameters)
        {
            StringResultObject result = new StringResultObject();
            //
            int                 dbItemResult = -1, dbUserResult = -1;
            WebSite             webSite       = default(WebSite);
            WebVirtualDirectory webVirtualDir = default(WebVirtualDirectory);
            WebVirtualDirectory iisAppNode    = default(WebVirtualDirectory);

            //
            try
            {
                SecurityContext.SetThreadSupervisorPrincipal();
                //
                TaskManager.StartTask(TASK_MANAGER_SOURCE, "INSTALL_WEB_APP");
                //
                TaskManager.WriteParameter("Package ID", packageId);
                TaskManager.WriteParameter("Site Name", siteName);

                //
                WebServer webServer = GetAssociatedWebServer(packageId);

                // ERROR: WAG is not available
                if (!webServer.IsMsDeployInstalled())
                {
                    return(WAG_MODULE_NOT_AVAILABLE <StringResultObject>());
                }

                //
                GalleryApplicationResult appResult = webServer.GetGalleryApplication(webAppId);

                #region Preparations and tracing
                // Trace at least Web Application Id for troubleshooting purposes
                if (!appResult.IsSuccess || appResult.Value == null)
                {
                    TaskManager.WriteError("Could not find an application to install with ID: {0}.", webAppId);
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Assign web app pack title to the currently running task
                TaskManager.ItemName = appResult.Value.Title;
                // Trace additional details from the feed
                TraceGalleryAppPackInfo(appResult.Value);

                // Trace out all deployment parameters
                Array.ForEach <DeploymentParameter>(updatedParameters.ToArray(), p => TaskManager.WriteParameter(p.Name, p.Value));
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    TaskManager.WriteError("Account check has been failed. Status: {0};", accountCheck.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Check package
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    TaskManager.WriteError("Package check has been failed. Status: {0};", packageCheck.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Check web site for existence
                webSite = WebServerController.GetWebSite(packageId, siteName);
                if (webSite == null)
                {
                    TaskManager.WriteError("Web site check has been failed. Status: {0};", BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                #endregion

                DeploymentParametersResult appParamsResult = GetGalleryApplicationParamsInternally(packageId, webAppId);

                //
                if (!appParamsResult.IsSuccess)
                {
                    foreach (string errorMessage in appParamsResult.ErrorCodes)
                    {
                        TaskManager.WriteError(errorMessage);
                    }
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }

                List <DeploymentParameter> origParams = appParamsResult.Value;
                //
                if (Array.Exists <DeploymentParameter>(origParams.ToArray(),
                                                       p => MatchParameterTag(p, DeploymentParameter.SQL_PARAM_TAG) ||
                                                       MatchParameterTag(p, DeploymentParameter.MYSQL_PARAM_TAG)))
                {
                    // Match input parameters from the client
                    DeploymentParameter dbNameParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                       p => MatchParameterByNames(p, DeploymentParameter.DATABASE_NAME_PARAMS) ||
                                                                                       MatchParameterTag(p, DeploymentParameter.DB_NAME_PARAM_TAG));
                    //
                    DeploymentParameter dbUserParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                       p => MatchParameterByNames(p, DeploymentParameter.DATABASE_USERNAME_PARAMS) ||
                                                                                       MatchParameterTag(p, DeploymentParameter.DB_USERNAME_PARAM_TAG));
                    //
                    DeploymentParameter dbUserPwParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                         p => MatchParameterByNames(p, DeploymentParameter.DATABASE_USERPWD_PARAMS) ||
                                                                                         MatchParameterTag(p, DeploymentParameter.DB_PASSWORD_PARAM_TAG));

                    #region Pre-conditions verification...
                    //
                    if (dbNameParam == null)
                    {
                        //
                        TaskManager.WriteError(PARAMETER_IS_NULL_OR_EMPTY, DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (String.IsNullOrEmpty(dbNameParam.Tags))
                    {
                        //
                        TaskManager.WriteError("{0} parameter tags does not contain information about the database resource group should be used", DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    int dbServiceId = PackageController.GetPackageServiceId(packageId, dbNameParam.Tags);
                    //
                    if (dbServiceId <= 0)
                    {
                        //
                        TaskManager.WriteError("{0} parameter tags contains wrong information about the database resource group should be used. Resource group: " + dbNameParam.Tags, DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion
                    //
                    DeploymentParameter dbServerParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                         p => MatchParameterByNames(p, DeploymentParameter.DB_SERVER_PARAMS) ||
                                                                                         MatchParameterTag(p, DeploymentParameter.DB_SERVER_PARAM_TAG));
                    //
                    DeploymentParameter dbAdminParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                        p => MatchParameterByNames(p, DeploymentParameter.DB_ADMIN_PARAMS) ||
                                                                                        MatchParameterTag(p, DeploymentParameter.DB_ADMIN_USERNAME_PARAM_TAG));
                    //
                    DeploymentParameter dbAdminPwParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                          p => MatchParameterByNames(p, DeploymentParameter.DB_ADMINPWD_PARAMS) ||
                                                                                          MatchParameterTag(p, DeploymentParameter.DB_ADMIN_PASSWORD_PARAM_TAG));

                    #region Pre-conditions verification...
                    //
                    if (dbAdminParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_ADMIN_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (dbServerParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_SERVER_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (dbAdminPwParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_ADMINPWD_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion

                    #region Read & substitute database server settings
                    //
                    StringDictionary dbSettings = ServerController.GetServiceSettingsAdmin(dbServiceId);

                    // InternalAddress setting is common for all DB service providers
                    dbServerParam.Value = dbSettings["InternalAddress"];
                    // Set database administrator login
                    if (!String.IsNullOrEmpty(dbSettings["RootLogin"]))
                    {
                        dbAdminParam.Value = dbSettings["RootLogin"];
                    }
                    else if (!String.IsNullOrEmpty(dbSettings["SaLogin"]))
                    {
                        dbAdminParam.Value = dbSettings["SaLogin"];
                    }
                    else
                    {
                        //
                        TaskManager.WriteError(CANNOT_SET_PARAMETER_VALUE, dbAdminParam.Name);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    // Set database administrator password
                    if (!String.IsNullOrEmpty(dbSettings["RootPassword"]))
                    {
                        dbAdminPwParam.Value = dbSettings["RootPassword"];
                    }
                    else if (!String.IsNullOrEmpty(dbSettings["SaPassword"]))
                    {
                        dbAdminPwParam.Value = dbSettings["SaPassword"];
                    }
                    else
                    {
                        //
                        TaskManager.WriteError(CANNOT_SET_PARAMETER_VALUE, dbAdminPwParam.Name);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion

                    //
                    updatedParameters.AddRange(new List <DeploymentParameter> {
                        dbServerParam, dbAdminParam, dbAdminPwParam
                    });

                    #region Create database and db user account if new selected
                    //
                    SqlDatabase db = PackageController.GetPackageItemByName(packageId, dbNameParam.Value,
                                                                            typeof(SqlDatabase)) as SqlDatabase;
                    //
                    if (db == null)
                    {
                        db           = new SqlDatabase();
                        db.PackageId = packageId;
                        db.Name      = dbNameParam.Value;
                        //
                        dbItemResult = DatabaseServerController.AddSqlDatabase(db, dbNameParam.Tags);
                        //
                        if (dbItemResult < 0)
                        {
                            // Put specific error message into the trace log
                            TaskManager.WriteError("Could not create {0} database. Error code: {1}.", dbNameParam.Tags, dbItemResult.ToString());
                            // Return generic error
                            return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                        }
                    }

                    //
                    SqlUser user = PackageController.GetPackageItemByName(packageId, dbUserParam.Value,
                                                                          typeof(SqlUser)) as SqlUser;
                    //
                    if (user == null)
                    {
                        user           = new SqlUser();
                        user.PackageId = packageId;
                        user.Name      = dbUserParam.Value;
                        user.Databases = new string[] { dbNameParam.Value };
                        user.Password  = dbUserPwParam.Value;
                        //
                        dbUserResult = DatabaseServerController.AddSqlUser(user, dbNameParam.Tags);
                        //
                        if (dbUserResult < 0)
                        {
                            // Rollback and remove db if created
                            if (dbItemResult > 0)
                            {
                                DatabaseServerController.DeleteSqlDatabase(dbItemResult);
                            }
                            // Put specific error message into the trace log
                            TaskManager.WriteError("Could not create {0} user account. Error code: {1}.", dbNameParam.Tags, dbUserResult.ToString());
                            // Return generic error
                            return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                        }
                    }
                    #endregion
                }

                //
                DeploymentParameter appPathParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                    p => MatchParameterName(p, DeploymentParameter.APPICATION_PATH_PARAM) ||
                                                                                    MatchParameterTag(p, DeploymentParameter.IISAPP_PARAM_TAG));
                //
                if (String.IsNullOrEmpty(virtualDir))
                {
                    appPathParam.Value = siteName;
                }
                else
                {
                    appPathParam.Value = String.Format("{0}/{1}", siteName, virtualDir);
                }
                //
                updatedParameters.Add(appPathParam);

                //
                result = webServer.InstallGalleryApplication(webAppId, updatedParameters.ToArray());
                //
                #region Rollback in case of failure
                // Rollback - remove resources have been created previously
                if (!result.IsSuccess)
                {
                    //
                    if (dbUserResult > 0)
                    {
                        DatabaseServerController.DeleteSqlUser(dbUserResult);
                    }
                    //
                    if (dbItemResult > 0)
                    {
                        DatabaseServerController.DeleteSqlDatabase(dbItemResult);
                    }
                    //
                    foreach (string errorCode in result.ErrorCodes)
                    {
                        TaskManager.WriteError(errorCode);
                    }
                    //
                    return(result);
                }
                #endregion

                // Reload web site details
                webSite = WebServerController.GetWebSite(packageId, siteName);
                // Reload virtual directory defaults
                if (!String.IsNullOrEmpty(virtualDir))
                {
                    webVirtualDir = WebServerController.GetVirtualDirectory(webSite.Id, virtualDir);
                }

                // We are going to install application on website or virtual directory
                iisAppNode = (webVirtualDir != null) ? webVirtualDir : webSite;
                // Put correct ASP.NET version depending on a web server's version
                iisAppNode.AspNetInstalled = (iisAppNode.IIs7) ? "2I" : "2";

                //
                if (MatchParticularAppDependency(appResult.Value.Dependency, SupportedAppDependencies.PHP_SCRIPTING))
                {
                    // Enable PHP 5 extensions for web site
                    iisAppNode.PhpInstalled = "5";
                    // Set the correct default document for PHP apps
                    if (iisAppNode.DefaultDocs.IndexOf("index.php", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        iisAppNode.DefaultDocs += ",index.php";
                    }
                    //
                    int docsResult = 0;
                    //
                    if (webVirtualDir == null)
                    {
                        docsResult = WebServerController.UpdateWebSite(webSite);
                    }
                    else
                    {
                        docsResult = WebServerController.UpdateVirtualDirectory(webSite.Id, webVirtualDir);
                    }
                    //
                    if (docsResult < 0)
                    {
                        TaskManager.WriteWarning("Could not update website/virtual directory default documents with the value of index.php. Result code: {0}", docsResult.ToString());
                    }
                }
                //
                if (MatchParticularAppDependency(appResult.Value.Dependency, SupportedAppDependencies.ASPNET_SCRIPTING))
                {
                    // Set the correct default document for ASP.NET apps
                    if (iisAppNode.DefaultDocs.IndexOf("Default.aspx", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        iisAppNode.DefaultDocs += ",Default.aspx";
                    }
                    //
                    int aspnetResult = 0;
                    //
                    if (webVirtualDir == null)
                    {
                        aspnetResult = WebServerController.UpdateWebSite(webSite);
                    }
                    else
                    {
                        aspnetResult = WebServerController.UpdateVirtualDirectory(webSite.Id, webVirtualDir);
                    }
                    //
                    if (aspnetResult < 0)
                    {
                        TaskManager.WriteWarning("Could not set default documents/enable ASP.NET 2.0 (Integrated Mode) for website/virtual directory. Result code: {0}", aspnetResult.ToString());
                    }
                }

                //
                return(result);
            }
            catch (Exception ex)
            {
                //
                TaskManager.WriteError(ex);
                //
                return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static IntResult CreateOrganization(int packageId, string organizationId,
                                                   string domain, string adminName, string adminEmail, string adminPassword)
        {
            IntResult result = new IntResult();

            result.IsSuccess = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                #endregion

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

                // exit with error code
                return(Error <IntResult>(GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int AddSqlUser(SqlUser item, string groupName)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

            // check quota
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, groupName + ".Users");

            if (quota.QuotaExhausted)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_USERS_RESOURCE_QUOTA_LIMIT);
            }

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, groupName);

            if (serviceId == 0)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE);
            }

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, groupName, item.Name, typeof(SqlUser)) != null)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_USERS_PACKAGE_ITEM_EXISTS);
            }

            // place log record
            TaskManager.StartTask("SQL_USER", "ADD", item.Name);
            TaskManager.WriteParameter("Provider", groupName);

            int itemId = default(int);

            try
            {
                // check service items
                DatabaseServer sql = GetDatabaseServer(serviceId);
                if (sql.UserExists(item.Name))
                {
                    return(BusinessErrorCodes.ERROR_MSSQL_USERS_SERVICE_ITEM_EXISTS);
                }

                // add service item
                sql.CreateUser(item, item.Password);

                // save item
                item.Password  = CryptoUtils.Encrypt(item.Password);
                item.ServiceId = serviceId;
                itemId         = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                //
                if (ex.Message.Contains("INVALID_USERNAME"))
                {
                    return(BusinessErrorCodes.ERROR_MYSQL_INVALID_USER_NAME);
                }
                // Return a generic error instead of default(int)
                itemId = BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            return(itemId);
        }
        public static ResultObject UpdateOrganizationCatchAllAddress(int itemId, string catchAllEmail)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

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

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

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

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

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

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

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

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

                // exit with error code
                return(Error <ResultObject>(UpdateCatchAllError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int AddSqlDatabase(SqlDatabase item, string groupName)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

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

            // check quota
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, groupName + ".Databases");

            if (quota.QuotaExhausted)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_DATABASES_RESOURCE_QUOTA_LIMIT);
            }

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, groupName);

            if (serviceId == 0)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE);
            }

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, groupName, item.Name, typeof(SqlDatabase)) != null)
            {
                return(BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_EXISTS);
            }

            // place log record
            TaskManager.StartTask("SQL_DATABASE", "ADD", item.Name);
            TaskManager.WriteParameter("Provider", groupName);

            int itemId = default(int);

            //
            try
            {
                // check service items
                DatabaseServer sql = GetDatabaseServer(serviceId);
                if (sql.DatabaseExists(item.Name))
                {
                    return(BusinessErrorCodes.ERROR_MSSQL_DATABASES_SERVICE_ITEM_EXISTS);
                }

                // calculate database location
                StringDictionary settings = ServerController.GetServiceSettings(serviceId);
                UserInfo         user     = PackageController.GetPackageOwner(item.PackageId);
                if (settings["UseDefaultDatabaseLocation"] != null &&
                    !Utils.ParseBool(settings["UseDefaultDatabaseLocation"], false))
                {
                    item.Location = Utils.ReplaceStringVariable(settings["DatabaseLocation"], "user_name", user.Username);
                }

                // set database size
                item.DataSize = GetMaxDatabaseSize(item.PackageId, groupName);


                // set log size
                item.LogSize = GetMaxLogSize(item.PackageId, groupName);

                // add service item
                sql.CreateDatabase(item);

                // save item
                item.ServiceId = serviceId;
                itemId         = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                //
                if (ex.Message.Contains("INVALID_DATABASE_NAME"))
                {
                    return(BusinessErrorCodes.ERROR_MYSQL_INVALID_DATABASE_NAME);
                }
                // Return a generic error instead of default(int)
                itemId = BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            return(itemId);
        }
        public static ResultObject UpdateOrganizationServicePlan(int itemId, int newServiceId)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

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

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

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

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

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

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

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

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

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

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

                // exit with error code
                return(Error <ResultObject>(UpdateServicePlanError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static ResultObject AddOrganizationDomain(int itemId, string domainName)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

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

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

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

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

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

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

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

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

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

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

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

                    // add domain
                    domain.DomainId = domainId;
                }

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

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

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

                // exit with error code
                return(Error <ResultObject>(AddDomainError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 23
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. 24
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();
            }
        }
Esempio n. 25
0
        public static int InstallWebPartsPackage(int itemId, string uploadedFile, string packageFile)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

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

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

            if (item == null)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND);
            }

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

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

            // place log record
            TaskManager.StartTask("SHAREPOINT", "INSTALL_WEBPARTS", item.Name);
            TaskManager.ItemId = itemId;
            TaskManager.WriteParameter("Package file", packageFile);

            try
            {
                SharePointServer sps = GetSharePoint(item.ServiceId);

                string backupFile = null;
                if (!String.IsNullOrEmpty(packageFile))
                {
                    // copy package files to the remote SharePoint Server
                    string path   = null;
                    byte[] buffer = null;

                    int offset = 0;
                    do
                    {
                        // read package file
                        buffer = FilesController.GetFileBinaryChunk(item.PackageId, packageFile, offset, FILE_BUFFER_LENGTH);

                        // write remote backup file
                        string tempPath = sps.AppendTempFileBinaryChunk(Path.GetFileName(packageFile), path, buffer);
                        if (path == null)
                        {
                            path       = tempPath;
                            backupFile = path;
                        }

                        offset += FILE_BUFFER_LENGTH;
                    }while (buffer.Length == FILE_BUFFER_LENGTH);
                }
                else if (!String.IsNullOrEmpty(uploadedFile))
                {
                    // upladed files
                    backupFile = uploadedFile;
                }

                // restore
                if (!String.IsNullOrEmpty(backupFile))
                {
                    sps.InstallWebPartsPackage(item.Name, backupFile);
                }

                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static StringResultObject Install(int packageId, string webAppId, string siteName, string virtualDir, List <DeploymentParameter> parameters)
        {
            StringResultObject result = new StringResultObject();

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

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

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

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

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

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

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

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

                #region Trace app details

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

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

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

                // elevate security context
                SecurityContext.SetThreadSupervisorPrincipal();

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

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

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

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

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

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

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

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

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

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

                    #region Create database and db user account if new selected

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

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

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

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

                    // 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));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 27
0
        public static int AuthenticateUser(string username, string password, string ip)
        {
            // start task
            TaskManager.StartTask("USER", "AUTHENTICATE", username);
            TaskManager.WriteParameter("IP", ip);

            try
            {
                int result = 0;

                // try to get user from database
                UserInfoInternal user = GetUserInternally(username);

                // check if the user exists
                if (user == null)
                {
                    TaskManager.WriteWarning("Wrong username");
                    return(BusinessErrorCodes.ERROR_USER_WRONG_USERNAME);
                }

                // check if the user is disabled
                if (user.LoginStatus == UserLoginStatus.Disabled)
                {
                    TaskManager.WriteWarning("User disabled");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_DISABLED);
                }

                // check if the user is locked out
                if (user.LoginStatus == UserLoginStatus.LockedOut)
                {
                    TaskManager.WriteWarning("User locked out");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_LOCKEDOUT);
                }

                //Get the password policy
                UserSettings userSettings = UserController.GetUserSettings(user.UserId, UserSettings.WEBSITEPANEL_POLICY);
                int          lockOut      = -1;

                if (!string.IsNullOrEmpty(userSettings["PasswordPolicy"]))
                {
                    string passwordPolicy = userSettings["PasswordPolicy"];
                    try
                    {
                        // parse settings
                        string[] parts = passwordPolicy.Split(';');
                        lockOut = Convert.ToInt32(parts[7]);
                    }
                    catch { /* skip */ }
                }


                // compare user passwords
                if ((CryptoUtils.SHA1(user.Password) == password) || (user.Password == password))
                {
                    switch (user.OneTimePasswordState)
                    {
                    case OneTimePasswordStates.Active:
                        result = BusinessSuccessCodes.SUCCESS_USER_ONETIMEPASSWORD;
                        OneTimePasswordHelper.FireSuccessAuth(user);
                        break;

                    case OneTimePasswordStates.Expired:
                        if (lockOut >= 0)
                        {
                            DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, false);
                        }
                        TaskManager.WriteWarning("Expired one time password");
                        return(BusinessErrorCodes.ERROR_USER_EXPIRED_ONETIMEPASSWORD);

                        break;
                    }
                }
                else
                {
                    if (lockOut >= 0)
                    {
                        DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, false);
                    }

                    TaskManager.WriteWarning("Wrong password");
                    return(BusinessErrorCodes.ERROR_USER_WRONG_PASSWORD);
                }

                DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, true);

                // check status
                if (user.Status == UserStatus.Cancelled)
                {
                    TaskManager.WriteWarning("Account cancelled");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED);
                }

                if (user.Status == UserStatus.Pending)
                {
                    TaskManager.WriteWarning("Account pending");
                    return(BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING);
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static ResultObject SendExchangeOrganizationSummary(int itemId, string toEmail)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

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

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

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

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

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

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

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

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

                // exit with error code
                return(Error <ResultObject>(SendOrganizationSummaryError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }