Пример #1
0
        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));
        }
Пример #2
0
        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);
            }
        }
Пример #3
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 isSfB          = Utils.ParseBool(topTask.GetParamValue(SFB_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("isSfB", isSfB);
                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, isSfB);

                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);
                TaskManager.WriteParameter("report.SfBReport.Items.Count", report.SfBReport.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,
                            isSfB && report.SfBReport != null ? report.SfBReport.ToCSV() : string.Empty);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
            }

            TaskManager.Write("End HostedSolutionReportTask");
        }
Пример #4
0
        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);
        }
Пример #5
0
        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);
        }
Пример #6
0
        private void SendMailMessage(UserInfo user, IEnumerable <DomainInfo> domains, Dictionary <int, UserInfo> domainUsers, IEnumerable <DomainInfo> nonExistenDomains, bool includeNonExistenDomains)
        {
            BackgroundTask topTask = TaskManager.TopTask;

            UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.DOMAIN_EXPIRATION_LETTER);

            string from = settings["From"];

            var bcc = 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);
            }

            // input parameters
            string mailTo = (string)topTask.GetParamValue("MAIL_TO");

            Hashtable items = new Hashtable();

            items["user"] = user;

            items["Domains"] = domains.Select(x => new { DomainName             = x.DomainName,
                                                         ExpirationDate         = x.ExpirationDate < DateTime.Now ? "Expired" : x.ExpirationDate.ToString(),
                                                         ExpirationDateOrdering = x.ExpirationDate,
                                                         Registrar = x.RegistrarName,
                                                         Customer  = string.Format("{0} {1}", domainUsers[x.PackageId].FirstName, domainUsers[x.PackageId].LastName) })
                               .OrderBy(x => x.ExpirationDateOrdering).ThenBy(x => x.Customer).ThenBy(x => x.DomainName);

            items["IncludeNonExistenDomains"] = includeNonExistenDomains;

            items["NonExistenDomains"] = nonExistenDomains.Select(x => new
            {
                DomainName = x.DomainName,
                Customer   = string.Format("{0} {1}", domainUsers[x.PackageId].FirstName, domainUsers[x.PackageId].LastName)
            }).OrderBy(x => x.Customer).ThenBy(x => x.DomainName);


            body = PackageController.EvaluateTemplate(body, items);

            // send mail message
            MailHelper.SendMessage(from, mailTo, bcc, subject, body, priority, isHtml);
        }
Пример #7
0
        /// <summary>
        /// Performs actual backup.
        /// </summary>
        public override void DoWork()
        {
            string backupFileName;
            int    storePackageId;
            string storePackageFolder;
            string storeServerFolder;
            bool   deleteTempBackup;

            BackgroundTask topTask = TaskManager.TopTask;

            try
            {
                backupFileName     = (string)topTask.GetParamValue("BACKUP_FILE_NAME");
                storePackageId     = Convert.ToInt32(topTask.GetParamValue("STORE_PACKAGE_ID"));
                storePackageFolder = (string)topTask.GetParamValue("STORE_PACKAGE_FOLDER");
                storeServerFolder  = (string)topTask.GetParamValue("STORE_SERVER_FOLDER");
                deleteTempBackup   = Convert.ToBoolean(topTask.GetParamValue("DELETE_TEMP_BACKUP"));
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex, "Some parameters are absent or have incorrect value.");
                return;
            }

            try
            {
                PackageInfo package = PackageController.GetPackage(topTask.PackageId);
                // We do not take into account service id as long as scheduled tasks run against packages.
                BackupController.Backup(false, "BackupTask", package.UserId, package.PackageId, 0, 0,
                                        backupFileName, storePackageId, storePackageFolder, storeServerFolder, deleteTempBackup);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex, "Failed to do backup.");
            }
        }
Пример #8
0
        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);
                    }
                }
            }
        }
Пример #9
0
        private void SendMailMessage(UserInfo user, IEnumerable <DomainDnsChanges> domainsChanges, Dictionary <int, UserInfo> domainUsers)
        {
            BackgroundTask topTask = TaskManager.TopTask;

            UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.DOMAIN_LOOKUP_LETTER);

            string from = settings["From"];

            var bcc = settings["CC"];

            string subject = settings["Subject"];

            MailPriority priority = MailPriority.Normal;

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

            // input parameters
            string mailTo = (string)topTask.GetParamValue("MAIL_TO");

            string body   = string.Empty;
            bool   isHtml = user.HtmlMail;

            if (domainsChanges.Any())
            {
                body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"];
            }
            else
            {
                body = user.HtmlMail ? settings["NoChangesHtmlBody"] : settings["NoChangesTextBody"];
            }

            Hashtable items = new Hashtable();

            items["user"]        = user;
            items["DomainUsers"] = domainUsers;
            items["Domains"]     = domainsChanges;

            body = PackageController.EvaluateTemplate(body, items);

            // send mail message
            MailHelper.SendMessage(from, mailTo, bcc, subject, body, priority, isHtml);
        }
Пример #10
0
        public override void DoWork()
        {
            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string mailTo           = (string)topTask.GetParamValue("MAIL_TO");
            int    auditLogSeverity = Utils.ParseInt((string)topTask.GetParamValue("AUDIT_LOG_SEVERITY"), -1);
            string auditLogSource   = (string)topTask.GetParamValue("AUDIT_LOG_SOURCE");
            string auditLogTask     = (string)topTask.GetParamValue("AUDIT_LOG_TASK");
            string auditLogDate     = (string)topTask.GetParamValue("AUDIT_LOG_DATE");
            int    showExecutionLog = Utils.ParseInt((string)topTask.GetParamValue("SHOW_EXECUTION_LOG"), 0);

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

            string         mailFrom = null;
            SystemSettings settings = SystemController.GetSystemSettingsInternal(SystemSettings.SMTP_SETTINGS, false);

            if (settings != null)
            {
                mailFrom = settings["SmtpUsername"];
            }
            if (String.IsNullOrEmpty(mailFrom))
            {
                TaskManager.WriteWarning("You need to configure SMTP settings first");
                return;
            }

            DateTime logStart, logEnd;

            switch (auditLogDate)
            {
            case "today":
                logStart = DateTime.Now;
                logEnd   = DateTime.Now;
                break;

            case "yesterday":
                logStart = DateTime.Now.AddDays(-1);
                logEnd   = DateTime.Now.AddDays(-1);
                break;

            case "schedule":
            default:
                logEnd = DateTime.Now;
                ScheduleInfo schedule = SchedulerController.GetSchedule(topTask.ScheduleId);
                switch (schedule.ScheduleTypeId)
                {
                case "Daily":
                    logStart = DateTime.Now.AddDays(-1);
                    break;

                case "Weekly":
                    logStart = DateTime.Now.AddDays(-7);
                    break;

                case "Monthly":
                    logStart = DateTime.Now.AddMonths(-1);
                    break;

                case "Interval":
                    logStart = DateTime.Now.AddSeconds(-schedule.Interval);
                    break;

                case "OneTime":
                default:
                    logStart = DateTime.Now;
                    break;
                }
                break;
            }

            string mailSubject = "Audit Log Report (" + logStart.ToString("MMM dd, yyyy") + " - " + logEnd.ToString("MMM dd, yyyy") + ")";

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<html><head><style>");
            sb.AppendLine("table, th, td { border: 1px solid black; border-collapse: collapse; }");
            sb.AppendLine("th, td { padding: 5px; }");
            sb.AppendLine("th { text-align: left; }");
            sb.AppendLine("</style></head><body>");
            sb.AppendLine("<h2>" + mailSubject + "</h2>");
            sb.AppendFormat("<h3>Source: {0}, Task: {1}, Severity: {2}</h3>", String.IsNullOrEmpty(auditLogSource) ? "All" : auditLogSource,
                            String.IsNullOrEmpty(auditLogTask) ? "All" : auditLogTask, GetAuditLogRecordSeverityName(auditLogSeverity));

            DataTable logs = AuditLog.GetAuditLogRecordsPaged(topTask.EffectiveUserId, 0, 0, null, logStart, logEnd,
                                                              auditLogSeverity, auditLogSource, auditLogTask, "", 0, Int32.MaxValue).Tables[1];

            sb.AppendLine("<p>");
            if (logs.Rows.Count == 0)
            {
                sb.AppendLine("Audit Log is empty.");
            }
            else
            {
                sb.AppendLine("<table>");
                sb.Append("<tr><th>Started</th><th>Finished</th><th>Severity</th><th>Username</th><th>Source</th><th>Task</th><th>Item-Name</th>");
                if (showExecutionLog == 1)
                {
                    sb.AppendLine("<th>Execution-Log</th></tr>");
                }
                else
                {
                    sb.AppendLine("</tr>");
                }
                foreach (DataRow log in logs.Rows)
                {
                    sb.AppendLine("<tr>");
                    // Started
                    sb.AppendFormat("<td>{0}</td>", log["StartDate"].ToString());
                    // Finished
                    sb.AppendFormat("<td>{0}</td>", log["FinishDate"].ToString());
                    // Severity
                    sb.AppendFormat("<td>{0}</td>", GetAuditLogRecordSeverityName((int)log["SeverityID"]));
                    // Username
                    sb.AppendFormat("<td>{0}</td>", log["Username"]);
                    // Source
                    sb.AppendFormat("<td>{0}</td>", log["SourceName"]);
                    // Task
                    sb.AppendFormat("<td>{0}</td>", log["TaskName"]);
                    // Item-Name
                    sb.AppendFormat("<td>{0}</td>", log["ItemName"]);
                    // Execution-Log
                    if (showExecutionLog == 1)
                    {
                        string executionLog = FormatPlainTextExecutionLog(log["ExecutionLog"].ToString());
                        sb.AppendFormat("<td>{0}</td>", executionLog);
                    }
                    sb.AppendLine("</tr>");
                }
                sb.AppendLine("</table>");
            }
            sb.AppendLine("</p></body></html>");

            // send mail message
            int res = MailHelper.SendMessage(mailFrom, mailTo, mailSubject, sb.ToString(), true);

            if (res != 0)
            {
                TaskManager.WriteError("SMTP Error. Code: " + res.ToString());
            }
        }
Пример #11
0
        public override void DoWork()
        {
            // Input parameters:
            //  - DATABASE_GROUP
            //  - DATABASE_NAME
            //  - BACKUP_FOLDER
            //  - BACKUP_NAME
            //  - ZIP_BACKUP

            BackgroundTask topTask = TaskManager.TopTask;

            string databaseGroup = (string)topTask.GetParamValue("DATABASE_GROUP");
            string databaseName  = (string)topTask.GetParamValue("DATABASE_NAME");
            string backupFolder  = (string)topTask.GetParamValue("BACKUP_FOLDER");
            string backupName    = (string)topTask.GetParamValue("BACKUP_NAME");
            string strZipBackup  = (string)topTask.GetParamValue("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(topTask.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);
        }
        public override void DoWork()
        {
            // Input parameters:
            //  - DISKSPACE_OVERUSED
            //  - BANDWIDTH_OVERUSED

            BackgroundTask topTask = TaskManager.TopTask;

            // get the list of all packages
            List <PackageInfo> packages = PackageController.GetPackagePackages(topTask.PackageId, false);

            TaskManager.Write("Packages to verify: " + packages.Count.ToString());

            bool checkMSSQL   = (String.Compare((string)topTask.GetParamValue("MSSQL_OVERUSED"), "true", true) == 0);
            bool checkMySQL   = (String.Compare((string)topTask.GetParamValue("MYSQL_OVERUSED"), "true", true) == 0);
            bool checkMariaDB = (String.Compare((string)topTask.GetParamValue("MARIADB_OVERUSED"), "true", true) == 0);

            bool   sendWarningEmail       = Convert.ToBoolean(topTask.GetParamValue("SEND_WARNING_EMAIL"));
            bool   sendOverusedEmail      = Convert.ToBoolean(topTask.GetParamValue("SEND_OVERUSED_EMAIL"));
            int    warningUsageThreshold  = Convert.ToInt32(topTask.GetParamValue("WARNING_USAGE_THRESHOLD"));
            int    overusedUsageThreshold = Convert.ToInt32(topTask.GetParamValue("OVERUSED_USAGE_THRESHOLD"));
            string warningMailFrom        = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_FROM"));
            string warningMailBcc         = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BCC"));
            string warningMailSubject     = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_SUBJECT"));
            string warningMailBody        = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BODY"));
            string overusedMailFrom       = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_FROM"));
            string overusedMailBcc        = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_BCC"));
            string overusedMailSubject    = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_SUBJECT"));
            string overusedMailBody       = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_BODY"));

            int overusedPackages = 0;

            foreach (PackageInfo package in packages)
            {
                UserInfo userInfo = UserController.GetUser(package.UserId);

                List <DatabaseQuota> quotaMSSQL   = new List <DatabaseQuota>();
                List <DatabaseQuota> quotaMYSQL   = new List <DatabaseQuota>();
                List <DatabaseQuota> quotaMARIADB = new List <DatabaseQuota>();

                if (checkMSSQL || checkMySQL || checkMariaDB)
                {
                    QuotaValueInfo dsQuota   = null;
                    DataSet        Diskspace = PackageController.GetPackageDiskspace(package.PackageId);
                    foreach (DataRow spaceRow in Diskspace.Tables[0].Rows)
                    {
                        string groupName = spaceRow["GroupName"].ToString();
                        if (checkMSSQL && groupName.ToUpper().Contains("MSSQL"))
                        {
                            dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize");
                            if (dsQuota.QuotaAllocatedValue > 0)
                            {
                                int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue;
                                quotaMSSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MSSQL", "SQL Server "),
                                                                 Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue,
                                                                 databaseSpaceUsage < warningUsageThreshold,
                                                                 databaseSpaceUsage < overusedUsageThreshold));
                            }
                        }
                        if (checkMySQL && groupName.ToUpper().Contains("MYSQL"))
                        {
                            dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize");
                            if (dsQuota.QuotaAllocatedValue > 0)
                            {
                                int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue;
                                quotaMYSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MYSQL", "MySQL "),
                                                                 Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue,
                                                                 databaseSpaceUsage < warningUsageThreshold,
                                                                 databaseSpaceUsage < overusedUsageThreshold));
                            }
                        }
                        if (checkMariaDB && groupName.ToUpper().Contains("MARIADB"))
                        {
                            dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize");
                            if (dsQuota.QuotaAllocatedValue > 0)
                            {
                                int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue;
                                quotaMARIADB.Add(new DatabaseQuota(groupName.ToUpper().Replace("MARIADB", "MariaDB "),
                                                                   Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue,
                                                                   databaseSpaceUsage < warningUsageThreshold,
                                                                   databaseSpaceUsage < overusedUsageThreshold));
                            }
                        }
                    }

                    string        userName                = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email);
                    bool          notifyOverusedByMail    = false;
                    bool          notifyWarningByMail     = false;
                    List <string> formatItems             = new List <string>();
                    List <string> formatWarningThreshold  = new List <string>();
                    List <string> formatOverusedThreshold = new List <string>();
                    // add Microsoft SQL usage if enabled
                    if (checkMSSQL)
                    {
                        foreach (DatabaseQuota q in quotaMSSQL)
                        {
                            if (!q.BelowWarningThreshold || !q.BelowUsageThreshold)
                            {
                                formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, q.SpaceUsed * 100 / q.SpaceAllocated));
                            }
                            if (!q.BelowWarningThreshold)
                            {
                                formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyWarningByMail = true;
                            }
                            if (!q.BelowUsageThreshold)
                            {
                                formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyOverusedByMail = true;
                            }
                        }
                    }

                    // add MySQL usage if enabled
                    if (checkMySQL)
                    {
                        foreach (DatabaseQuota q in quotaMYSQL)
                        {
                            if (!q.BelowWarningThreshold || !q.BelowUsageThreshold)
                            {
                                formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, (q.SpaceUsed * 100) / q.SpaceAllocated));
                            }
                            if (!q.BelowWarningThreshold)
                            {
                                formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyWarningByMail = true;
                            }
                            if (!q.BelowUsageThreshold)
                            {
                                formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyOverusedByMail = true;
                            }
                        }
                    }

                    // add MariaDB usage if enabled
                    if (checkMariaDB)
                    {
                        foreach (DatabaseQuota q in quotaMARIADB)
                        {
                            if (!q.BelowWarningThreshold || !q.BelowUsageThreshold)
                            {
                                formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, (q.SpaceUsed * 100) / q.SpaceAllocated));
                            }
                            if (!q.BelowWarningThreshold)
                            {
                                formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyWarningByMail = true;
                            }
                            if (!q.BelowUsageThreshold)
                            {
                                formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated));
                                notifyOverusedByMail = true;
                            }
                        }
                    }

                    // build usage strings
                    string usage         = String.Join("\n", formatItems.ToArray());
                    string usageWarning  = String.Join("\n", formatWarningThreshold.ToArray());
                    string usageOverused = String.Join("\n", formatOverusedThreshold.ToArray());

                    string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, usageWarning, usage, package.PackageName, userName);
                    string warningMailBodyProcessed    = ReplaceVariables(warningMailBody, usageWarning, usage, package.PackageName, userName);

                    string overusedMailSubjectProcessed = ReplaceVariables(overusedMailSubject, usageOverused, usage, package.PackageName, userName);
                    string overusedMailBodyProcessed    = ReplaceVariables(overusedMailBody, usageOverused, usage, package.PackageName, userName);


                    // Send email notifications
                    if (sendWarningEmail && notifyWarningByMail)
                    {
                        // Send warning email.
                        this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false);
                    }

                    if (sendOverusedEmail && notifyOverusedByMail)
                    {
                        // Send overused email.
                        this.SendEmail(overusedMailFrom, userInfo.Email, overusedMailBcc, overusedMailSubjectProcessed, overusedMailBodyProcessed, false);
                    }
                    if (notifyOverusedByMail)
                    {
                        overusedPackages++;
                    }
                }
            }

            // log results
            TaskManager.Write("Total packages overused: " + overusedPackages.ToString());
        }
Пример #13
0
        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);
            }
        }
Пример #14
0
        public override void DoWork()
        {
            BackgroundTask topTask = TaskManager.TopTask;

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

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

            int pause;

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

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


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

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

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

            WindowsServer winServer = new WindowsServer();

            ServiceProviderProxy.ServerInit(winServer, server.ServerId);

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

                    domainsChanges.Add(domainChanges);
                }
            }

            var changedDomains = FindDomainsWithChangedRecords(domainsChanges);

            SendMailMessage(user, changedDomains, domainUsers);
        }
        public override void DoWork()
        {
            // Input parameters:
            //  - DISKSPACE_OVERUSED
            //  - BANDWIDTH_OVERUSED

            BackgroundTask topTask = TaskManager.TopTask;

            // get the list of all packages
            List <PackageInfo> packages = PackageController.GetPackagePackages(topTask.PackageId, false);

            TaskManager.Write("Packages to verify: " + packages.Count.ToString());

            bool checkDiskspace = (String.Compare((string)topTask.GetParamValue("DISKSPACE_OVERUSED"), "true", true) == 0);
            bool checkBandwidth = (String.Compare((string)topTask.GetParamValue("BANDWIDTH_OVERUSED"), "true", true) == 0);

            bool suspendOverused = Convert.ToBoolean(topTask.GetParamValue("SUSPEND_OVERUSED"));

            bool   sendWarningEmail         = Convert.ToBoolean(topTask.GetParamValue("SEND_WARNING_EMAIL"));
            bool   sendSuspensionEmail      = Convert.ToBoolean(topTask.GetParamValue("SEND_SUSPENSION_EMAIL"));
            int    warningUsageThreshold    = Convert.ToInt32(topTask.GetParamValue("WARNING_USAGE_THRESHOLD"));
            int    suspensionUsageThreshold = Convert.ToInt32(topTask.GetParamValue("SUSPENSION_USAGE_THRESHOLD"));
            string warningMailFrom          = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_FROM"));
            string warningMailBcc           = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BCC"));
            string warningMailSubject       = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_SUBJECT"));
            string warningMailBody          = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BODY"));
            string suspensionMailFrom       = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_FROM"));
            string suspensionMailBcc        = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_BCC"));
            string suspensionMailSubject    = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_SUBJECT"));
            string suspensionMailBody       = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_BODY"));

            int suspendedPackages = 0;

            foreach (PackageInfo package in packages)
            {
                bool isBandwidthBelowWarningThreshold    = true;
                bool isBandwidthBelowSuspensionThreshold = true;
                bool isDiskSpaceBelowWarningThreshold    = true;
                bool isDiskSpaceBelowSuspensionThreshold = true;

                UserInfo userInfo = UserController.GetUser(package.UserId);

                int diskSpaceUsage = 0;
                int bandwidthUsage = 0;
                // disk space
                if (checkDiskspace)
                {
                    QuotaValueInfo dsQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_DISKSPACE);
                    if (dsQuota.QuotaAllocatedValue > 0)
                    {
                        diskSpaceUsage = (dsQuota.QuotaUsedValue * 100 / dsQuota.QuotaAllocatedValue);
                        isDiskSpaceBelowWarningThreshold    = diskSpaceUsage < warningUsageThreshold;
                        isDiskSpaceBelowSuspensionThreshold = diskSpaceUsage < suspensionUsageThreshold;
                    }
                }

                // bandwidth
                if (checkBandwidth)
                {
                    QuotaValueInfo bwQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_BANDWIDTH);
                    if (bwQuota.QuotaAllocatedValue > 0)
                    {
                        bandwidthUsage = (bwQuota.QuotaUsedValue * 100 / bwQuota.QuotaAllocatedValue);
                        isBandwidthBelowWarningThreshold    = bandwidthUsage < warningUsageThreshold;
                        isBandwidthBelowSuspensionThreshold = bandwidthUsage < suspensionUsageThreshold;
                    }
                }

                string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email);
                //
                List <string> formatItems = new List <string>();
                // add diskspace usage if enabled
                if (checkDiskspace)
                {
                    formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, diskSpaceUsage));
                }
                // add bandwidth usage if enabled
                if (checkBandwidth)
                {
                    formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, bandwidthUsage));
                }
                // build usage string
                string usage = String.Join(", ", formatItems.ToArray());

                // cleanup items
                formatItems.Clear();
                // add diskspace warning max usage
                if (checkDiskspace)
                {
                    formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, warningUsageThreshold));
                }
                // add bandwidth warning max usage
                if (checkBandwidth)
                {
                    formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, warningUsageThreshold));
                }
                // build warning max usage string
                string warningMaxUsage = String.Join(", ", formatItems.ToArray());

                // cleanup items
                formatItems.Clear();
                // add diskspace suspension max usage
                if (checkDiskspace)
                {
                    formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, suspensionUsageThreshold));
                }
                // add bandwidth suspension max usage
                if (checkBandwidth)
                {
                    formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, suspensionUsageThreshold));
                }
                // build suspension max usage string
                string suspensionMaxUsage = String.Join(", ", formatItems.ToArray());

                string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, warningMaxUsage, usage, package.PackageName, userName);
                string warningMailBodyProcessed    = ReplaceVariables(warningMailBody, warningMaxUsage, usage, package.PackageName, userName);

                string suspensionMailSubjectProcessed = ReplaceVariables(suspensionMailSubject, suspensionMaxUsage, usage, package.PackageName, userName);
                string suspensionMailBodyProcessed    = ReplaceVariables(suspensionMailBody, suspensionMaxUsage, usage, package.PackageName, userName);


                // Send email notifications
                if (sendWarningEmail && (!isDiskSpaceBelowWarningThreshold || !isBandwidthBelowWarningThreshold))
                {
                    // Send warning email.
                    this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false);
                }

                if (sendSuspensionEmail && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
                {
                    // Send suspension email.
                    this.SendEmail(suspensionMailFrom, userInfo.Email, suspensionMailBcc, suspensionMailSubjectProcessed, suspensionMailBodyProcessed, false);
                }

                // suspend package if required
                if (suspendOverused && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold))
                {
                    suspendedPackages++;

                    // load user details
                    UserInfo user = PackageController.GetPackageOwner(package.PackageId);

                    TaskManager.Write(String.Format("Suspend space '{0}' of user '{1}'",
                                                    package.PackageName, user.Username));

                    try
                    {
                        PackageController.ChangePackageStatus(null, package.PackageId, PackageStatus.Suspended, false);
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError("Error while changing space status: " + ex.ToString());
                    }
                }
            }

            // log results
            TaskManager.Write("Total packages suspended: " + suspendedPackages.ToString());
        }
Пример #16
0
        public override void DoWork()
        {
            // Input parameters:
            //  - FILE_PATH
            //  - FTP_SERVER
            //  - FTP_USERNAME
            //  - FTP_PASSWORD
            //  - FTP_FOLDER

            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string filePath    = (string)topTask.GetParamValue("FILE_PATH");
            string ftpServer   = (string)topTask.GetParamValue("FTP_SERVER");
            string ftpUsername = (string)topTask.GetParamValue("FTP_USERNAME");
            string ftpPassword = (string)topTask.GetParamValue("FTP_PASSWORD");
            string ftpFolder   = (string)topTask.GetParamValue("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(topTask.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(topTask.PackageId, cmdPath);

            // upload batch
            FilesController.UpdateFileBinaryContent(topTask.PackageId, cmdPath, Encoding.UTF8.GetBytes(cmdBatch));

            // execute system command
            // load OS service
            int serviceId = PackageController.GetPackageServiceId(topTask.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(topTask.PackageId, new string[] { cmdPath });
        }
Пример #17
0
        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);
            }
        }