public static UserInfo GetUserByUsernamePassword(string username, string password, string ip) { // place log record TaskManager.StartTask("USER", "GET_BY_USERNAME_PASSWORD", 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("Account not found"); return(null); } // compare user passwords if (user.Password == password) { return(user); } return(null); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } }
public static int ChangeUserPassword(string username, string oldPassword, string newPassword, string ip) { // place log record TaskManager.StartTask("USER", "CHANGE_PASSWORD_BY_USERNAME_PASSWORD", username); TaskManager.WriteParameter("IP", ip); try { UserInfo user = GetUserByUsernamePassword(username, oldPassword, ip); if (user == null) { TaskManager.WriteWarning("Account not found"); return(BusinessErrorCodes.ERROR_USER_NOT_FOUND); } // change password DataProvider.ChangeUserPassword(-1, user.UserId, CryptoUtils.Encrypt(newPassword)); return(0); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } }
internal static int SetupControlPanelAccounts(string passwordA, string passwordB, string ip) { try { TaskManager.StartTask("SYSTEM", "COMPLETE_SCPA"); // TaskManager.WriteParameter("Password A", passwordA); TaskManager.WriteParameter("Password B", passwordB); TaskManager.WriteParameter("IP Address", ip); // var enabledScpaMode = GetSystemSetupMode(); // if (enabledScpaMode == false) { // TaskManager.WriteWarning("Attempt to execute SCPA procedure for an uknown reason"); // return(BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION); } // Entering the security context into Supervisor mode SecurityContext.SetThreadSupervisorPrincipal(); // var accountA = UserController.GetUserInternally("serveradmin"); var accountB = UserController.GetUserInternally("admin"); // var resultCodeA = UserController.ChangeUserPassword(accountA.UserId, passwordA); // if (resultCodeA < 0) { TaskManager.WriteParameter("Result Code A", resultCodeA); // return(resultCodeA); } // var resultCodeB = UserController.ChangeUserPassword(accountB.UserId, passwordB); // if (resultCodeB < 0) { TaskManager.WriteParameter("Result Code B", resultCodeB); // return(resultCodeB); } // Disable SCPA mode SetSystemSettings(SystemSettings.SETUP_SETTINGS, SystemSettings.Empty); // Operation has succeeded return(0); } catch (Exception ex) { TaskManager.WriteError(ex); // return(BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION); } finally { TaskManager.CompleteTask(); } }
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 override void DoWork() { BackgroundTask topTask = TaskManager.TopTask; int daysBeforeNotify; // check input parameters if (!int.TryParse((string)topTask.GetParamValue(DaysBeforeNotify), out daysBeforeNotify)) { TaskManager.WriteWarning("Specify 'Notify before (days)' task parameter"); return; } OrganizationController.DeleteAllExpiredTokens(); var owner = UserController.GetUser(topTask.EffectiveUserId); var packages = PackageController.GetMyPackages(topTask.EffectiveUserId); foreach (var package in packages) { var organizations = ExchangeServerController.GetExchangeOrganizations(package.PackageId, true); foreach (var organization in organizations) { var usersWithExpiredPasswords = OrganizationController.GetOrganizationUsersWithExpiredPassword(organization.Id, daysBeforeNotify); var generalSettings = OrganizationController.GetOrganizationGeneralSettings(organization.Id); var logoUrl = generalSettings != null ? generalSettings.OrganizationLogoUrl : string.Empty; foreach (var user in usersWithExpiredPasswords) { user.ItemId = organization.Id; if (string.IsNullOrEmpty(user.PrimaryEmailAddress)) { TaskManager.WriteWarning(string.Format("Unable to send email to {0} user (organization: {1}), user primary email address is not set.", user.DisplayName, organization.OrganizationId)); continue; } OrganizationController.SendUserExpirationPasswordEmail(owner, user, "Scheduler Password Expiration Notification", user.PrimaryEmailAddress, logoUrl); } } } }
public override void DoWork() { // Input parameters: // - SERVER_NAME // - EXECUTABLE_PATH BackgroundTask topTask = TaskManager.TopTask; // get input parameters string serverName = (string)topTask.GetParamValue("SERVER_NAME"); string execPath = (string)topTask.GetParamValue("EXECUTABLE_PATH"); string execParams = (string)topTask.GetParamValue("EXECUTABLE_PARAMS"); if (execParams == null) { execParams = ""; } // check input parameters if (String.IsNullOrEmpty(serverName)) { TaskManager.WriteWarning("Specify 'Server Name' task parameter"); return; } if (String.IsNullOrEmpty(execPath)) { TaskManager.WriteWarning("Specify 'Executable Path' task parameter"); return; } // find server by name ServerInfo server = ServerController.GetServerByName(serverName); if (server == null) { TaskManager.WriteWarning(String.Format("Server with the name '{0}' was not found", serverName)); return; } // execute system command WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, server.ServerId); TaskManager.Write(winServer.ExecuteSystemCommand(execPath, execParams)); }
private void SendEmail(string from, string to, string bcc, string subject, string body, bool isHtml) { // check input parameters if (String.IsNullOrEmpty(from)) { TaskManager.WriteWarning("Specify 'Mail From' task parameter"); return; } if (String.IsNullOrEmpty(to)) { TaskManager.WriteWarning("Specify 'Mail To' task parameter"); return; } // send mail message MailHelper.SendMessage(from, to, bcc, subject, body, isHtml); }
private void SendMailMessage(string url, string message, string content) { BackgroundTask topTask = TaskManager.TopTask; // input parameters string mailFrom = (string)topTask.GetParamValue("MAIL_FROM"); string mailTo = (string)topTask.GetParamValue("MAIL_TO"); string mailSubject = (string)topTask.GetParamValue("MAIL_SUBJECT"); string mailBody = (string)topTask.GetParamValue("MAIL_BODY"); if (String.IsNullOrEmpty(mailTo)) { TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty."); } else { if (String.IsNullOrEmpty(mailFrom)) { mailFrom = "automatic@localhost"; } if (!String.IsNullOrEmpty(mailSubject)) { mailSubject = Utils.ReplaceStringVariable(mailSubject, "url", url); } if (!String.IsNullOrEmpty(mailBody)) { mailBody = Utils.ReplaceStringVariable(mailBody, "url", url); mailBody = Utils.ReplaceStringVariable(mailBody, "message", message); mailBody = Utils.ReplaceStringVariable(mailBody, "content", content); } else { mailBody = message; } // send mail message MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false); } }
public override void DoWork() { // Input parameters: // - FOLDER // - ZIP_FILE BackgroundTask topTask = TaskManager.TopTask; // get input parameters string filesList = (string)topTask.GetParamValue("FOLDER"); string zipFile = (string)topTask.GetParamValue("ZIP_FILE"); // check input parameters if (String.IsNullOrEmpty(filesList)) { TaskManager.WriteWarning("Specify 'Files List' task parameter"); return; } if (String.IsNullOrEmpty(zipFile)) { TaskManager.WriteWarning("Specify 'Zip File' task parameter"); return; } // substitute parameters DateTime d = DateTime.Now; string date = d.ToString("yyyyMMdd"); string time = d.ToString("HHmm"); filesList = Utils.ReplaceStringVariable(filesList, "date", date); filesList = Utils.ReplaceStringVariable(filesList, "time", time); zipFile = Utils.ReplaceStringVariable(zipFile, "date", date); zipFile = Utils.ReplaceStringVariable(zipFile, "time", time); // zip files and folders FilesController.ZipFiles(topTask.PackageId, new string[] { filesList }, zipFile); }
public override void DoWork() { // Input parameters: // - MAIL_FROM // - MAIL_TO // - MAIL_SUBJECT // - MAIL_BODY BackgroundTask topTask = TaskManager.TopTask; // get input parameters string mailFrom = (string)topTask.GetParamValue("MAIL_FROM"); string mailTo = (string)topTask.GetParamValue("MAIL_TO"); string mailSubject = (string)topTask.GetParamValue("MAIL_SUBJECT"); string mailBody = (string)topTask.GetParamValue("MAIL_BODY"); // check input parameters if (String.IsNullOrEmpty(mailFrom)) { TaskManager.WriteWarning("Specify 'Mail From' task parameter"); return; } if (String.IsNullOrEmpty(mailTo)) { TaskManager.WriteWarning("Specify 'Mail To' task parameter"); return; } if (String.IsNullOrEmpty(mailSubject)) { TaskManager.WriteWarning("Specify 'Mail Subject' task parameter"); return; } // send mail message MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false); }
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 override void DoWork() { BackgroundTask topTask = TaskManager.TopTask; var domainUsers = new Dictionary <int, UserInfo>(); var checkedDomains = new List <DomainInfo>(); var expiredDomains = new List <DomainInfo>(); var nonExistenDomains = new List <DomainInfo>(); var allDomains = new List <DomainInfo>(); var allTopLevelDomains = new List <DomainInfo>(); // get input parameters int daysBeforeNotify; bool sendEmailNotifcation = Convert.ToBoolean(topTask.GetParamValue(EnableNotification)); bool includeNonExistenDomains = Convert.ToBoolean(topTask.GetParamValue(IncludeNonExistenDomains)); // check input parameters if (String.IsNullOrEmpty((string)topTask.GetParamValue("MAIL_TO"))) { TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty."); return; } int.TryParse((string)topTask.GetParamValue(DaysBeforeNotify), out daysBeforeNotify); var user = UserController.GetUser(topTask.EffectiveUserId); var packages = GetUserPackages(user.UserId, user.Role); foreach (var package in packages) { var domains = ServerController.GetDomains(package.PackageId); allDomains.AddRange(domains); domains = domains.Where(x => !x.IsSubDomain && !x.IsDomainPointer).ToList(); //Selecting top-level domains allTopLevelDomains.AddRange(domains); var domainUser = UserController.GetUser(package.UserId); if (!domainUsers.ContainsKey(package.PackageId)) { domainUsers.Add(package.PackageId, domainUser); } foreach (var domain in domains) { if (checkedDomains.Any(x => x.DomainId == domain.DomainId)) { continue; } checkedDomains.Add(domain); ServerController.UpdateDomainWhoisData(domain); if (CheckDomainExpiration(domain.ExpirationDate, daysBeforeNotify)) { expiredDomains.Add(domain); } if (domain.ExpirationDate == null && domain.CreationDate == null) { nonExistenDomains.Add(domain); } Thread.Sleep(100); } } var subDomains = allDomains.Where(x => !checkedDomains.Any(z => z.DomainId == x.DomainId && z.ExpirationDate != null)).GroupBy(p => p.DomainId).Select(g => g.First()).ToList(); foreach (var subDomain in subDomains) { var mainDomain = checkedDomains.Where(x => subDomain.DomainId != x.DomainId && subDomain.DomainName.ToLowerInvariant().Contains(x.DomainName.ToLowerInvariant())).OrderByDescending(s => s.DomainName.Length).FirstOrDefault();; if (mainDomain != null) { ServerController.UpdateDomainWhoisData(subDomain, mainDomain.CreationDate, mainDomain.ExpirationDate, mainDomain.RegistrarName); var nonExistenDomain = nonExistenDomains.FirstOrDefault(x => subDomain.DomainId == x.DomainId); if (nonExistenDomain != null) { nonExistenDomains.Remove(nonExistenDomain); } Thread.Sleep(100); } } expiredDomains = expiredDomains.GroupBy(p => p.DomainId).Select(g => g.First()).ToList(); if (expiredDomains.Count > 0 && sendEmailNotifcation) { SendMailMessage(user, expiredDomains, domainUsers, nonExistenDomains, includeNonExistenDomains); } }
public override void DoWork() { // Input parameters: // - URL // - USERNAME // - PASSWORD // - RESPONSE_STATUS // - RESPONSE_CONTAIN // - RESPONSE_DOESNT_CONTAIN // - MAIL_FROM // - MAIL_TO // - MAIL_SUBJECT // - MAIL_BODY BackgroundTask topTask = TaskManager.TopTask; // get input parameters string url = (string)topTask.GetParamValue("URL"); string username = (string)topTask.GetParamValue("USERNAME"); string password = (string)topTask.GetParamValue("PASSWORD"); string strResponseStatus = (string)topTask.GetParamValue("RESPONSE_STATUS"); string responseContains = (string)topTask.GetParamValue("RESPONSE_CONTAIN"); string responseNotContains = (string)topTask.GetParamValue("RESPONSE_DOESNT_CONTAIN"); bool useResponseStatus = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_STATUS")); bool useResponseContains = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_CONTAIN")); bool useResponseDoesntContain = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_DOESNT_CONTAIN")); // check input parameters if (String.IsNullOrEmpty(url)) { TaskManager.WriteWarning("Specify 'Web Site URL' task parameter."); return; } if ((String.IsNullOrEmpty(strResponseStatus) || !useResponseStatus) && (String.IsNullOrEmpty(responseContains) || !useResponseContains) && (String.IsNullOrEmpty(responseNotContains) || !useResponseDoesntContain)) { TaskManager.WriteWarning("Specify one of 'Response Status', 'Response Contain' or 'Response Doesn't Contain' parameters."); return; } int responseStatus = Utils.ParseInt(strResponseStatus, -1); if (!String.IsNullOrEmpty(strResponseStatus) && responseStatus == -1) { TaskManager.WriteWarning("Specify correct response HTTP status, e.g. 404, 500, 503, etc."); return; } // load web site WebSiteResponse resp = GetWebDocument(url, username, password); // check if there was a generic error if (resp.Status == -1) { SendMailMessage(url, resp.Text, ""); } bool sendMessage = false; // check status if (responseStatus != -1) { sendMessage |= ((resp.Status == responseStatus) && useResponseStatus); } // check "contains" if (!String.IsNullOrEmpty(responseContains)) { sendMessage |= ((resp.Text.ToLower().IndexOf(responseContains.ToLower()) != -1) && useResponseContains); } // check "not contains" if (!String.IsNullOrEmpty(responseNotContains)) { sendMessage |= ((resp.Text.ToLower().IndexOf(responseNotContains.ToLower()) == -1) && useResponseDoesntContain); } if (sendMessage) { SendMailMessage(url, "", resp.Text); } }
public void ImportItem(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group, string itemName) { // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) { return; } if (itemType == typeof(DnsZone)) { // Get ascii form in punycode var zoneName = GetAsciiZoneName(itemName); // add DNS zone DnsZone zone = new DnsZone(); zone.Name = zoneName; zone.ServiceId = serviceId; zone.PackageId = packageId; int zoneId = PackageController.AddPackageItem(zone); // Add secondary zone(s) try { // get secondary DNS services var primSettings = ServerController.GetServiceSettings(serviceId); var secondaryServiceIds = new List <int>(); var strSecondaryServices = primSettings["SecondaryDNSServices"]; if (!String.IsNullOrEmpty(strSecondaryServices)) { var secondaryServices = strSecondaryServices.Split(','); secondaryServiceIds.AddRange(secondaryServices.Select(strSecondaryId => Utils.ParseInt(strSecondaryId, 0)).Where(secondaryId => secondaryId != 0)); } // add secondary zones var secondaryZoneFound = false; foreach (var secondaryId in secondaryServiceIds) { var secDns = GetDNSServer(secondaryId); if (secDns.ZoneExists(zoneName)) { secondaryZoneFound = true; var secondaryZone = new SecondaryDnsZone { Name = zoneName, ServiceId = secondaryId, PackageId = packageId }; PackageController.AddPackageItem(secondaryZone); } } if (!secondaryZoneFound) { TaskManager.WriteWarning("No secondary zone(s) found when importing zone " + itemName); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing secondary zone(s)"); } // add/update domains/pointers RestoreDomainByZone(itemName, packageId, zoneId); } }
public 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 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(); } }
public override void DoWork() { // Input parameters: // - FILE_PATH // - FTP_SERVER // - FTP_USERNAME // - FTP_PASSWORD // - FTP_FOLDER // get input parameters string filePath = (string)TaskManager.TaskParameters["FILE_PATH"]; string ftpServer = (string)TaskManager.TaskParameters["FTP_SERVER"]; string ftpUsername = (string)TaskManager.TaskParameters["FTP_USERNAME"]; string ftpPassword = (string)TaskManager.TaskParameters["FTP_PASSWORD"]; string ftpFolder = (string)TaskManager.TaskParameters["FTP_FOLDER"]; // check input parameters if (String.IsNullOrEmpty(filePath)) { TaskManager.WriteWarning("Specify 'File' task parameter"); return; } if (String.IsNullOrEmpty(ftpServer)) { TaskManager.WriteWarning("Specify 'FTP Server' task parameter"); return; } // substitute parameters DateTime d = DateTime.Now; string date = d.ToString("yyyyMMdd"); string time = d.ToString("HHmm"); filePath = Utils.ReplaceStringVariable(filePath, "date", date); filePath = Utils.ReplaceStringVariable(filePath, "time", time); // build FTP command file StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); // FTP server writer.WriteLine("open " + ftpServer); // check if anonymous mode if (String.IsNullOrEmpty(ftpUsername)) { ftpUsername = "******"; ftpPassword = "******"; } // FTP username/password writer.WriteLine(ftpUsername); writer.WriteLine(ftpPassword); // check if we need to change remote folder if (!String.IsNullOrEmpty(ftpFolder)) { writer.WriteLine("cd " + ftpFolder.Replace("\\", "/")); } // file to send writer.WriteLine("binary"); writer.WriteLine("put " + FilesController.GetFullPackagePath(TaskManager.PackageId, filePath)); // bye writer.WriteLine("bye"); string cmdBatch = sb.ToString(); // create temp file in user space string cmdPath = Utils.GetRandomString(10) + ".txt"; string fullCmdPath = FilesController.GetFullPackagePath(TaskManager.PackageId, cmdPath); // upload batch FilesController.UpdateFileBinaryContent(TaskManager.PackageId, cmdPath, Encoding.UTF8.GetBytes(cmdBatch)); // execute system command // load OS service int serviceId = PackageController.GetPackageServiceId(TaskManager.PackageId, ResourceGroups.Os); // load service ServiceInfo service = ServerController.GetServiceInfo(serviceId); if (service == null) { return; } WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, service.ServerId); TaskManager.Write(winServer.ExecuteSystemCommand("ftp.exe", "-s:" + fullCmdPath)); // delete batch file FilesController.DeleteFiles(TaskManager.PackageId, new string[] { cmdPath }); }
public override void DoWork() { BackgroundTask topTask = TaskManager.TopTask; List <DomainDnsChanges> domainsChanges = new List <DomainDnsChanges>(); var domainUsers = new Dictionary <int, UserInfo>(); // get input parameters string dnsServersString = (string)topTask.GetParamValue(DnsServersParameter); string serverName = (string)topTask.GetParamValue(ServerNameParameter); int pause; // check input parameters if (String.IsNullOrEmpty(dnsServersString)) { TaskManager.WriteWarning("Specify 'DNS' task parameter."); return; } if (String.IsNullOrEmpty((string)topTask.GetParamValue("MAIL_TO"))) { TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty."); return; } if (!int.TryParse((string)topTask.GetParamValue(PauseBetweenQueriesParameter), out pause)) { TaskManager.WriteWarning("The 'pause between queries' parameter is not valid."); return; } // find server by name ServerInfo server = ServerController.GetServerByName(serverName); if (server == null) { TaskManager.WriteWarning(String.Format("Server with the name '{0}' was not found", serverName)); return; } WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, server.ServerId); var user = UserController.GetUser(topTask.UserId); var dnsServers = dnsServersString.Split(';'); var packages = ObjectUtils.CreateListFromDataReader <PackageInfo>(DataProvider.GetAllPackages()); foreach (var package in packages) { var domains = ServerController.GetDomains(package.PackageId); domains = domains.Where(x => !x.IsSubDomain && !x.IsDomainPointer).ToList(); //Selecting top-level domains //domains = domains.Where(x => x.ZoneItemId > 0).ToList(); //Selecting only dns enabled domains foreach (var domain in domains) { if (domainsChanges.Any(x => x.DomainName == domain.DomainName)) { continue; } if (!domainUsers.ContainsKey(domain.PackageId)) { var domainUser = UserController.GetUser(packages.First(x => x.PackageId == domain.PackageId).UserId); domainUsers.Add(domain.PackageId, domainUser); } DomainDnsChanges domainChanges = new DomainDnsChanges(); domainChanges.DomainName = domain.DomainName; domainChanges.PackageId = domain.PackageId; domainChanges.Registrar = domain.RegistrarName; domainChanges.ExpirationDate = domain.ExpirationDate; var dbDnsRecords = ObjectUtils.CreateListFromDataReader <DnsRecordInfo>(DataProvider.GetDomainAllDnsRecords(domain.DomainId)); //execute server foreach (var dnsServer in dnsServers) { var dnsMxRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.MX, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX).ToList(); var dnsNsRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.NS, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS).ToList(); FillRecordData(dnsMxRecords, domain, dnsServer); FillRecordData(dnsNsRecords, domain, dnsServer); domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX), dnsMxRecords, dnsServer)); domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS), dnsNsRecords, dnsServer)); domainChanges.DnsChanges = CombineDnsRecordChanges(domainChanges.DnsChanges, dnsServer).ToList(); } domainsChanges.Add(domainChanges); } } var changedDomains = FindDomainsWithChangedRecords(domainsChanges); SendMailMessage(user, changedDomains, domainUsers); }
public static int AddUser(UserInfo user, bool sendLetter) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) { return(accountCheck); } string pattern = @"[\\/:*?<>|""]+"; if (String.IsNullOrEmpty(user.Username)) { return(BusinessErrorCodes.ERROR_INVALID_USER_NAME); } if (Regex.IsMatch(user.Username, pattern)) { return(BusinessErrorCodes.ERROR_INVALID_USER_NAME); } if (UserExists(user.Username)) { return(BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS); } // only administrators can set admin role if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) && user.Role == UserRole.Administrator) { user.Role = UserRole.User; } // check integrity when creating a user account if (user.Role == UserRole.User) { user.EcommerceEnabled = false; } // place log record TaskManager.StartTask("USER", "ADD", user.Username); try { // add user to database int userId = DataProvider.AddUser( SecurityContext.User.UserId, user.OwnerId, user.RoleId, user.StatusId, user.IsDemo, user.IsPeer, user.Comments, user.Username.Trim(), CryptoUtils.Encrypt(user.Password), user.FirstName, user.LastName, user.Email, user.SecondaryEmail, user.Address, user.City, user.Country, user.State, user.Zip, user.PrimaryPhone, user.SecondaryPhone, user.Fax, user.InstantMessenger, user.HtmlMail, user.CompanyName, user.EcommerceEnabled); if (userId == -1) { TaskManager.WriteWarning("Account with such username already exists"); return(BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS); } TaskManager.ItemId = userId; TaskManager.TaskParameters["SendLetter"] = sendLetter; return(userId); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } }
public override void DoWork() { // Input parameters: // - DATABASE_GROUP // - DATABASE_NAME // - BACKUP_FOLDER // - BACKUP_NAME // - ZIP_BACKUP string databaseGroup = (string)TaskManager.TaskParameters["DATABASE_GROUP"]; string databaseName = (string)TaskManager.TaskParameters["DATABASE_NAME"]; string backupFolder = (string)TaskManager.TaskParameters["BACKUP_FOLDER"]; string backupName = (string)TaskManager.TaskParameters["BACKUP_NAME"]; string strZipBackup = (string)TaskManager.TaskParameters["ZIP_BACKUP"]; // check input parameters if (String.IsNullOrEmpty(databaseName)) { TaskManager.WriteWarning("Specify 'Database Name' task parameter."); return; } bool zipBackup = (strZipBackup.ToLower() == "true"); if (String.IsNullOrEmpty(backupName)) { backupName = databaseName + (zipBackup ? ".zip" : ".bak"); } else { // check extension string ext = Path.GetExtension(backupName); if (zipBackup && String.Compare(ext, ".zip", true) != 0) { // change extension to .zip backupName = Path.GetFileNameWithoutExtension(backupName) + ".zip"; } } // try to find database SqlDatabase item = (SqlDatabase)PackageController.GetPackageItemByName(TaskManager.PackageId, databaseGroup, databaseName, typeof(SqlDatabase)); if (item == null) { TaskManager.WriteError("Database with the specified name was not found in the current hosting space."); return; } if (String.IsNullOrEmpty(backupFolder)) { backupFolder = "\\"; } // substitute parameters DateTime d = DateTime.Now; string date = d.ToString("yyyyMMdd"); string time = d.ToString("HHmm"); backupFolder = Utils.ReplaceStringVariable(backupFolder, "date", date); backupFolder = Utils.ReplaceStringVariable(backupFolder, "time", time); backupName = Utils.ReplaceStringVariable(backupName, "date", date); backupName = Utils.ReplaceStringVariable(backupName, "time", time); // backup database DatabaseServerController.BackupSqlDatabase(item.Id, backupName, zipBackup, false, backupFolder); }
private void ProcessServiceItems(bool changeState, bool enabled, int serviceId, List <ServiceProviderItem> items) { string methodName = changeState ? "ChangeServiceItemsState" : "DeleteServiceItems"; int PACKET_SIZE = 10; int ATTEMPTS = 3; TaskManager.Write(String.Format("Start analyze {0} service ({1} items)", serviceId, items.Count)); try { // convert items to SoapObjects by packets of 0 int startItem = 0; List <SoapServiceProviderItem> objItems = new List <SoapServiceProviderItem>(); for (int i = 0; i < items.Count; i++) { // add to the packet objItems.Add(SoapServiceProviderItem.Wrap(items[i])); if (((i > 0) && (i % PACKET_SIZE == 0)) || i == (items.Count - 1)) // packet is ready { if (objItems.Count == 0) { continue; } int attempt = 0; bool success = false; while (attempt < ATTEMPTS) { // increment attempt attempt++; try { // send packet for calculation // invoke service provider TaskManager.Write(String.Format("Invoke {0} method ('{1}' - '{2}' items) - {3} attempt", methodName, items[startItem].Name, items[i].Name, attempt)); ServiceProvider prov = new ServiceProvider(); ServiceProviderProxy.Init(prov, serviceId); if (changeState) { prov.ChangeServiceItemsState(objItems.ToArray(), enabled); } else { prov.DeleteServiceItems(objItems.ToArray()); } // exit from the loop success = true; break; } catch (Exception ex) { TaskManager.WriteWarning(ex.ToString()); } } if (!success) { throw new Exception("The number of attemtps has been reached. The whole operation aborted."); } // reset packet counter startItem = i + 1; objItems.Clear(); } } // end for items } catch (Exception ex) { // log exception TaskManager.WriteWarning(ex.ToString()); } TaskManager.Write(String.Format("End analyze {0} service ({1} items)", serviceId, items.Count)); }
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(); } }