Beispiel #1
0
        private void UpdateSensorValueList(EdbotServerMessage edbotMessage)
        {
            if (!HasEdbots(edbotMessage))
            {
                return;
            }

            foreach (KeyValuePair <string, Edbot> entry in edbotMessage.Edbots)
            {
                if (!EdbotSensorValues.ContainsKey(entry.Key))
                {
                    EdbotSensorValues.Add(entry.Key, new Dictionary <string, int>());
                }

                Reporters reporters = entry.Value.Reporters;
                if (reporters != null)
                {
                    UpdateSensorPort(EdbotSensorValues[entry.Key], "Port1", reporters.Port1);
                    UpdateSensorPort(EdbotSensorValues[entry.Key], "Port2", reporters.Port2);
                    UpdateSensorPort(EdbotSensorValues[entry.Key], "Port3", reporters.Port3);
                    UpdateSensorPort(EdbotSensorValues[entry.Key], "Port4", reporters.Port4);

                    ListedSensors?.Invoke(this, EventArgs.Empty);
                }
            }
        }
Beispiel #2
0
        private (string DashboardApiKey, string ProjectName) ValidateDashboardReporter(string dashboadApiKey, string projectName)
        {
            if (!Reporters.Contains(Reporter.Dashboard))
            {
                return(null, projectName);
            }

            var errorStrings = new StringBuilder();

            if (string.IsNullOrWhiteSpace(dashboadApiKey))
            {
                var environmentApiKey = Environment.GetEnvironmentVariable("STRYKER_DASHBOARD_API_KEY");
                if (!string.IsNullOrWhiteSpace(environmentApiKey))
                {
                    dashboadApiKey = environmentApiKey;
                }
                else
                {
                    errorStrings.AppendLine($"An API key is required when the {Reporter.Dashboard} reporter is turned on! You can get an API key at {DashboardUrl}");
                }
            }

            if (string.IsNullOrWhiteSpace(projectName))
            {
                errorStrings.AppendLine($"A project name is required when the {Reporter.Dashboard} reporter is turned on!");
            }

            if (errorStrings.Length > 0)
            {
                throw new StrykerInputException(errorStrings.ToString());
            }

            return(dashboadApiKey, projectName);
        }
 public void CleanUp(string approved, string received)
 {
     foreach (var cleaner in Reporters.OfType <IApprovalReporterWithCleanUp>())
     {
         cleaner.CleanUp(approved, received);
     }
 }
Beispiel #4
0
 public static void BeforeTestRun()
 {
     Reporters.FixedRunTime = DateTime.MinValue;
     Reporters.Add(new JsonReporter());
     Reporters.Add(new XmlReporter());
     Reporters.Add(new PlainTextReporter());
     IntializeApprovalTests();
 }
Beispiel #5
0
 public void Setup()
 {
     Initialize();
     Instance.Navigate().GoToUrl(BaseAddress);
     Reporters.FixedRunTime = System.DateTime.MinValue;
     Reporters.Add(new JsonReporter());
     ApprovalTests.IntializeApprovalTests();
 }
        public ActionResult DeleteConfirmed(int id)
        {
            Reporters reporters = db.Reporters.Find(id);

            db.Reporters.Remove(reporters);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #7
0
        public static void BeforeTestRun()
        {
            Reporters.Add(new JsonReporter());

            Reporters.FinishedReport += (sender, args) => {
                System.IO.File.WriteAllText(@"report.json", args.Reporter.WriteToString());
            };
        }
Beispiel #8
0
    private void RepopulateReporterGrid()
    {
        Reporters reporters = Reporters.GetAll();

        reporters.Sort();

        this.GridReporters.DataSource = reporters;
        this.GridReporters.DataBind();
    }
        public static void BeforeTestRun()
        {
            Reporters.Add(new JsonReporter());

            Reporters.FinishedReport += (sender, args) =>
            {
                var reportsPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                args.Reporter.WriteToFile($"{reportsPath}/Reports_{DateTime.Now.ToUnixTimestampUtc()}.json");
            };
        }
        // GET: Reporters/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Reporters reporters = db.Reporters.Find(id);

            if (reporters == null)
            {
                return(HttpNotFound());
            }
            return(View(reporters));
        }
Beispiel #11
0
        public static void BeforeTestRun()
        {
            var webApp = new WebAppReporter();

            webApp.Settings.Title = "ConductOfCode.Specs.Api";

            Reporters.Add(webApp);

            Reporters.FinishedReport += (sender, args) =>
            {
                var reporter = args.Reporter as WebAppReporter;
                reporter?.WriteToFolder("ConductOfCode.Specs.Api", true);
            };
        }
        /// <summary>
        /// Applies the settings to the process arguments ready for execution.
        /// </summary>
        /// <param name="args">The builder to apply the settings to.</param>
        protected override void EvaluateCore(ProcessArgumentBuilder args)
        {
            base.EvaluateCore(args);

            if (AutoWatch)
            {
                args.Append("--auto-watch");
            }

            if (NoAutoWatch)
            {
                args.Append("--no-auto-watch");
            }

            if (Detached)
            {
                args.Append("--detached");
            }

            if (SingleRun)
            {
                args.Append("--single-run");
            }

            if (NoSingleRun)
            {
                args.Append("--no-single-run");
            }

            if (CaptureTimeout.HasValue)
            {
                args.AppendSwitch("--capture-timeout", CaptureTimeout.Value.ToString());
            }

            if (ReportSlowerThan.HasValue)
            {
                args.AppendSwitch("--report-slower-than", ReportSlowerThan.Value.ToString());
            }

            if (Reporters != null && Reporters.Count > 0)
            {
                args.AppendSwitch("--reporters", string.Join(",", Reporters.Select(_ => _.ToString().ToLower())));
            }

            if (Browsers != null && Browsers.Count > 0)
            {
                args.AppendSwitch("--browsers", string.Join(",", Browsers));
            }
        }
        // GET: Reporters/Edit/5
        public ActionResult Edit(int?id)
        {
            ViewBag.InquirySources = new SelectList(db.InquirySources.AsEnumerable(), "InquirySourceId", "InquirySourceName");
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Reporters reporters = db.Reporters.Find(id);

            if (reporters == null)
            {
                return(HttpNotFound());
            }
            return(View(reporters));
        }
Beispiel #14
0
        public void TestMethod1()
        {
            int abc = 56, def = 23;
            int val = abc + def;

            try
            {
                Console.WriteLine(val);
                Reporters.LogPassingTestStepToBugLogger("Pass");
            }
            catch (Exception)
            {
                Reporters.LogFailingTestStepToBugLogger("Fail");
            }
        }
Beispiel #15
0
        public static void BeforeTestRun()
        {
            if (false)
            {
                var webApp = new WebAppReporter();
                webApp.Settings.Title = "Bowling Calculator Features";

                Reporters.Add(webApp);

                Reporters.FinishedReport += (sender, args) =>
                {
                    var reporter = args.Reporter as WebAppReporter;
                    if (reporter != null)
                    {
                        reporter.WriteToFolder("doc", true);
                    }
                };
            }
            if (false)
            {
                Reporters.Add(new JsonReporter());

                Reporters.FinishedReport += (sender, args) =>
                {
                    var reporter = args.Reporter as JsonReporter;
                    if (reporter != null)
                    {
                        reporter.WriteToFile(@"doc\data.json");
                    }
                };
            }

            if (true)
            {
                Reporters.Add(new PlainTextReporter());

                Reporters.FinishedReport += (sender, args) =>
                {
                    var reporter = args.Reporter as PlainTextReporter;
                    if (reporter != null)
                    {
                        var outputFile = @"doc\data.txt";
                        File.Delete(outputFile);
                        reporter.WriteToFile(outputFile);
                    }
                };
            }
        }
        public ActionResult Edit([Bind(Include = "ReporterID,ReporterName,IsActive,CreatedBy,CreatedOn,ModifiedBy,ModifiedOn,InquirySourceId")] Reporters reporters)
        {
            ViewBag.InquirySources = new SelectList(db.InquirySources.AsEnumerable(), "InquirySourceId", "InquirySourceName");
            if (ModelState.IsValid)
            {
                db.Entry(reporters).State = EntityState.Modified;

                reporters.IsActive   = true;
                reporters.ModifiedBy = 1;
                reporters.ModifiedOn = DateTime.Now;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(reporters));
        }
Beispiel #17
0
        public void LoginCRMApp()
        {
            var client = new WebClient(TestSettings.Options);

            using (var _xrmApp = new XrmApp(client))
                try
                {
                    _xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey);
                    Reporters.LogPassingTestStepToBugLogger("Sub Area Opened successfully");
                }
                catch (Exception)
                {
                    Reporters.LogFailingTestStepToBugLogger("Sub Area not opened");
                    Assert.Fail("Sub Area not opened");
                }
        }
        private void InitializeReporter(ExtentReports extent, string path)
        {
            if (Reporters.Contains("html"))
            {
                var output = path.EndsWith("\\") || path.EndsWith("/") ? path : path + "\\";
                extent.AttachReporter(new ExtentHtmlReporter(output));
                _logger.WriteLine(LoggingLevel.Normal, $"The html report will be output to the folder '{output}'.");
            }

            if (Reporters.Contains("v3html"))
            {
                var output = Path.Combine(path, "index.html");
                extent.AttachReporter(new ExtentV3HtmlReporter(output));
                _logger.WriteLine(LoggingLevel.Normal, $"The v3html report will be output to '{output}'.");
            }
        }
Beispiel #19
0
        private BaselineProvider ValidateBaselineProvider(string baselineStorageLocation)
        {
            var normalizedLocation = baselineStorageLocation?.ToLower() ?? "";

            if (string.IsNullOrEmpty(normalizedLocation) && Reporters.Any(x => x == Reporter.Dashboard))
            {
                return(BaselineProvider.Dashboard);
            }

            return(normalizedLocation switch
            {
                "disk" => BaselineProvider.Disk,
                "dashboard" => BaselineProvider.Dashboard,
                "azurefilestorage" => BaselineProvider.AzureFileStorage,
                _ => BaselineProvider.Disk,
            });
Beispiel #20
0
 public void TearDownForEverySingleTestMethod()
 {
     try
     {
         if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed ||
             TestContext.CurrentTestOutcome == UnitTestOutcome.Inconclusive)
         {
             Reporters.ReportTestOutcome(ScreenshotTaker.ScreenshotFilePath);
         }
         else
         {
             Reporters.ReportTestOutcome("");
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        public ActionResult Create([Bind(Include = "ReporterID,ReporterName,IsActive,CreatedBy,CreatedOn,ModifiedBy,ModifiedOn,InquirySourceId")] Reporters reporters)
        {
            string message = "";

            //var valid = true;
            try { //New Try-catch-HP
                ViewBag.InquirySources = new SelectList(db.InquirySources.AsEnumerable(), "InquirySourceId", "InquirySourceName");

                if (ModelState.IsValid)
                {
                    db.Reporters.Add(reporters);

                    reporters.IsActive   = true;
                    reporters.CreatedBy  = 1;
                    reporters.CreatedOn  = DateTime.Now;
                    reporters.ModifiedOn = DateTime.Now;

                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                //valid = false;
                string fileName = "Error.txt";
                message = "Error occurred while adding a Reporter." + ex.Message;
                //string reportServerURL = Convert.ToString(ConfigurationManager.AppSettings["SSRSServer"]);
                string path = Server.MapPath("../") + "Report\\" + fileName;
                ////string logPath = Convert.ToString(ConfigurationManager.AppSettings["logPath"]);

                if (!System.IO.File.Exists(path))
                {
                    System.IO.File.Create(path);
                }
                using (var tw = new StreamWriter(path, true))
                {
                    tw.WriteLine("Error-" + DateTime.Now.ToString("MM/dd/yyyy HH:mm") + "-" + ex.Message);
                    tw.WriteLine(ex.InnerException);
                }
            }
            //End of new code-HP
            return(View(reporters));
        }
Beispiel #22
0
        public static void BeforeTestRun()
        {
            var webApp = new WebAppReporter();

            webApp.Settings.Title = "WebAppReporter Showcase";
            webApp.Settings.StepDetailsTemplateFile = GetAbsolutePath(@"templates\step-details.tpl.html");
            webApp.Settings.CssFile           = GetAbsolutePath(@"templates\styles.css");
            webApp.Settings.DashboardTextFile = GetAbsolutePath(@"templates\dashboard-text.md");

            Reporters.Add(webApp);

            var screenshotFolder = GetAbsolutePath("screenshots");
            var appFolder        = GetAbsolutePath("app");

            if (Directory.Exists(screenshotFolder))
            {
                Directory.Delete(screenshotFolder, true);
            }

            Reporters.FinishedStep += (sender, args) =>
            {
                var path = Path.Combine("screenshots", Guid.NewGuid().ToString() + ".png");
                WebDriver.TakeScreenshot(path);
                args.Step.UserData = new
                {
                    Screenshot = path
                };
            };

            Reporters.FinishedReport += (sender, args) =>
            {
                var reporter = args.Reporter as WebAppReporter;
                if (reporter != null)
                {
                    reporter.WriteToFolder(appFolder, true);

                    Directory.Move(screenshotFolder, Path.Combine(appFolder, "screenshots"));
                }
            };

            WebDriver = new FirefoxDriver();
        }
Beispiel #23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Reporters reporters = Reporters.GetAll();
            reporters.Sort();

            this.GridReporters.DataSource = reporters;

            MediaCategories categories = MediaCategories.GetAll();

            foreach (MediaCategory category in categories)
            {
                this.CheckListCategories.Items.Add(new ListItem(category.Name, category.Identity.ToString()));
            }
        }
        this.GridReporters.Columns.FindByUniqueNameSafe("DeleteCommand").Visible
            = _authority.HasAnyPermission(Permission.CanHandlePress);

        this.ButtonAdd.Enabled = _authority.HasAnyPermission(Permission.CanHandlePress);
    }
Beispiel #24
0
        public IMessage SyncProcessMessage(IMessage msg)
        {
            var methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);

            IMethodReturnMessage mrm = null;

            Reporters.ExecuteStep(
                () =>
            {
                var rtnMsg = NextSink.SyncProcessMessage(msg);
                mrm        = (IMethodReturnMessage)rtnMsg;

                if (mrm.Exception != null)
                {
                    throw mrm.Exception;
                }
            },
                methodMessage.MethodBase,
                methodMessage.Args
                );

            return(mrm);
        }
Beispiel #25
0
        public IMessage SyncProcessMessage(IMessage msg)
        {
            var methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);

            // Avoid reporting proxy method calls for fields injected via the constructor
            // in the step definition classes. This caused some steps to pe reported twice.
            if (methodMessage.MethodName == "FieldGetter")
            {
                return(NextSink.SyncProcessMessage(msg));
            }

            IMethodReturnMessage mrm = null;
            var task = Reporters.ExecuteStep(
                () =>
            {
                mrm = (IMethodReturnMessage)NextSink.SyncProcessMessage(msg);

                if (mrm.Exception != null)
                {
                    return(Task.FromException(mrm.Exception));
                }

                return((mrm.ReturnValue as Task) ?? Task.CompletedTask);
            },
                methodMessage.MethodBase,
                methodMessage.Args
                );

            if (task.IsCompleted)
            {
                return(mrm);
            }
            else
            {
                return(new ReturnMessage(task, null, 0, mrm.LogicalCallContext, methodMessage));
            }
        }
Beispiel #26
0
        public static void BeforeTestRun()
        {
            Reporters.Add(new JsonReporter());

            Reporters.FinishedReport += (sender, args) =>
            {
                var reportsPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                try
                {
                    ScreenshotEmbedder.EmbedScreenshotsForFailedScenarios(args.Reporter.Report.Features, ScenarioScreenshots);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }

                args.Reporter.WriteToFile($"{reportsPath}/TestReports.json");
            };

            AppiumManager.Platform           = Settings.GlobalSettings.Platform == "iOS" ? PlatformEnum.IOS : PlatformEnum.Android;
            AppiumServer.OutputDataReceived += OnOutputDataReceived;
            AppiumServer.StartServerIfShouldRunLocally();
        }
Beispiel #27
0
        public StrykerOptions(
            ILogger logger                    = null,
            IFileSystem fileSystem            = null,
            string basePath                   = "",
            string[] reporters                = null,
            string projectUnderTestNameFilter = "",
            int additionalTimeoutMS           = 5000,
            string[] excludedMutations        = null,
            string[] ignoredMethods           = null,
            string logLevel                   = "info",
            bool logToFile                    = false,
            bool devMode                    = false,
            string coverageAnalysis         = "perTest",
            bool abortTestOnFail            = true,
            bool disableSimultaneousTesting = false,
            int?maxConcurrentTestRunners    = null,
            int thresholdHigh               = 80,
            int thresholdLow                = 60,
            int thresholdBreak              = 0,
            string[] filesToExclude         = null,
            string[] mutate                 = null,
            string testRunner               = "vstest",
            string solutionPath             = null,
            string languageVersion          = "latest",
            bool diff = false,
            bool compareToDashboard        = false,
            string gitDiffTarget           = "master",
            string dashboardApiKey         = null,
            string dashboardUrl            = "https://dashboard.stryker-mutator.io",
            string projectName             = null,
            string moduleName              = null,
            string projectVersion          = null,
            string fallbackVersion         = null,
            string baselineStorageLocation = null,
            string azureSAS                   = null,
            string azureFileStorageUrl        = null,
            IEnumerable <string> testProjects = null,
            string mutationLevel              = null,
            string[] diffIgnoreFiles          = null)
        {
            _logger     = logger;
            _fileSystem = fileSystem ?? new FileSystem();

            var outputPath = ValidateOutputPath(basePath);

            IgnoredMethods             = ValidateIgnoredMethods(ignoredMethods ?? Array.Empty <string>());
            BasePath                   = basePath;
            CompareToDashboard         = compareToDashboard;
            OutputPath                 = outputPath;
            Reporters                  = ValidateReporters(reporters);
            ProjectUnderTestNameFilter = projectUnderTestNameFilter;
            AdditionalTimeoutMS        = additionalTimeoutMS;
            ExcludedMutations          = ValidateExcludedMutations(excludedMutations).ToList();
            LogOptions                 = new LogOptions(ValidateLogLevel(logLevel), logToFile, outputPath);
            DevMode = devMode;
            ConcurrentTestrunners             = ValidateConcurrentTestrunners(maxConcurrentTestRunners);
            Optimizations                     = ValidateMode(coverageAnalysis) | (abortTestOnFail ? OptimizationFlags.AbortTestOnKill : 0) | (disableSimultaneousTesting ? OptimizationFlags.DisableTestMix : 0);
            Thresholds                        = ValidateThresholds(thresholdHigh, thresholdLow, thresholdBreak);
            FilePatterns                      = ValidateFilePatterns(mutate, filesToExclude);
            TestRunner                        = ValidateTestRunner(testRunner);
            SolutionPath                      = ValidateSolutionPath(basePath, solutionPath);
            LanguageVersion                   = ValidateLanguageVersion(languageVersion);
            OptimizationMode                  = coverageAnalysis;
            DiffEnabled                       = diff || compareToDashboard;
            CompareToDashboard                = compareToDashboard;
            GitDiffSource                     = ValidateGitDiffTarget(gitDiffTarget);
            TestProjects                      = ValidateTestProjects(testProjects);
            DashboardUrl                      = dashboardUrl;
            (DashboardApiKey, ProjectName)    = ValidateDashboardReporter(dashboardApiKey, projectName);
            (ProjectVersion, FallbackVersion) = ValidateCompareToDashboard(projectVersion, fallbackVersion, gitDiffTarget);
            DiffIgnoreFiles                   = ValidateDiffIgnoreFiles(diffIgnoreFiles);
            ModuleName                        = !Reporters.Contains(Reporter.Dashboard) ? null : moduleName;
            BaselineProvider                  = ValidateBaselineProvider(baselineStorageLocation);
            (AzureSAS, AzureFileStorageUrl)   = ValidateAzureFileStorage(azureSAS, azureFileStorageUrl);
            MutationLevel                     = ValidateMutationLevel(mutationLevel ?? MutationLevel.Standard.ToString());
        }
Beispiel #28
0
        private static void CheckOneFeed(string readerUrl, string persistAsKey, int orgIdForTemplate)
        {
            string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey);

            DateTime highWaterMark = DateTime.MinValue;

            RssReader reader = null;

            try
            {
                string highWaterMarkString = Persistence.Key[persistenceKey];

                if (string.IsNullOrEmpty(highWaterMarkString))
                {
                    //Initialize highwatermark if never used
                    highWaterMark = DateTime.Now;
                    Persistence.Key[persistenceKey] = DateTime.Now.ToString();
                }
                else
                {
                    try
                    {
                        highWaterMark = DateTime.Parse(highWaterMarkString);
                    }
                    catch (Exception ex)
                    {
                        HeartBeater.Instance.SuggestRestart();
                        throw new Exception(
                                  "Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" +
                                  persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " +
                                  DateTime.Now, ex);
                    }
                }
                DateTime storedHighWaterMark = highWaterMark;
                reader = new RssReader(readerUrl);
                Rss rss = reader.Read();

                foreach (RssChannelItem item in rss.Channel.Items)
                {
                    // Ignore any items older than the highwater mark.
                    // Also ignore if older than two days

                    if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays(-2))
                    {
                        continue;
                    }

                    // This is an item we should publish.

                    // Set highwater datetime mark. We do this first, BEFORE processing, as a defense against mail floods,
                    // if should something go wrong and unexpected exceptions happen.

                    // We used to add 70 minutes as a defense against mistakes on DST switch in spring and fall (yes, it has happened), but have reduced to two.

                    if (item.PubDate > storedHighWaterMark)
                    {
                        Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(2).ToString();
                        storedHighWaterMark             = item.PubDate.AddMinutes(2);

                        // Verify that it was written correctly to database. This is defensive programming to avoid a mail flood,
                        // in case we can't write to the database for some reason.
                        string newStoredHighWaterString = "";
                        try
                        {
                            newStoredHighWaterString = Persistence.Key[persistenceKey];
                            DateTime temp = DateTime.Parse(newStoredHighWaterString);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(
                                      "Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" +
                                      newStoredHighWaterString + "'", ex);
                        }

                        if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate)
                        {
                            throw new Exception(
                                      "Unable to commit new highwater mark to database in PressReleaseChecker.Run()");
                        }
                    }

                    bool            allReporters  = false;
                    bool            international = false;
                    MediaCategories categories    = new MediaCategories();

                    foreach (RssCategory category in item.Categories)
                    {
                        if (category.Name == "Alla")
                        {
                            allReporters = true;
                        }
                        else if (category.Name == "Uncategorized")
                        {
                        }
                        else
                        {
                            try
                            {
                                MediaCategory mediaCategory = MediaCategory.FromName(category.Name);
                                categories.Add(mediaCategory);

                                if (category.Name.StartsWith("International"))
                                {
                                    international = true;
                                }
                            }
                            catch (Exception)
                            {
                                ExceptionMail.Send(
                                    new Exception("Unrecognized media category in press release: " + category.Name));
                            }
                        }
                    }

                    string mailText = Blog2Mail(item.Content);

                    // Create recipient list of relevant reporters

                    Reporters reporters = null;

                    if (allReporters)
                    {
                        reporters = Reporters.GetAll();
                    }
                    else
                    {
                        reporters = Reporters.FromMediaCategories(categories);
                    }

                    // Add officers if not int'l

                    People officers = new People();
                    Dictionary <int, bool> officerLookup = new Dictionary <int, bool>();

                    if (!international)
                    {
                        int[] officerIds = Roles.GetAllDownwardRoles(1, 1);
                        foreach (int officerId in officerIds)
                        {
                            officerLookup[officerId] = true;
                        }
                    }
                    else
                    {
                        officerLookup[1] = true;
                    }


                    // Send press release

                    //TODO: hardcoded  geo ... using  World
                    Organization     org = Organization.FromIdentity(orgIdForTemplate);
                    Geography        geo = Geography.Root;
                    PressReleaseMail pressreleasemail = new PressReleaseMail();

                    pressreleasemail.pSubject     = item.Title;
                    pressreleasemail.pDate        = DateTime.Now;
                    pressreleasemail.pBodyContent = Blog2Mail(item.Content);
                    pressreleasemail.pOrgName     = org.MailPrefixInherited;
                    if (allReporters)
                    {
                        pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE
                    }
                    else if (international)
                    {
                        pressreleasemail.pPostedToCategories = "International/English"; // TODO: THIS IS HARDCODED
                    }
                    else
                    {
                        pressreleasemail.pPostedToCategories =
                            PressReleaseMail.GetConcatenatedCategoryString(categories);
                    }

                    OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService,
                                                                                         OutboundMail.PriorityHighest, org, geo);

                    int recipientCount = 0;
                    foreach (Reporter recipient in reporters)
                    {
                        if (!Formatting.ValidateEmailFormat(recipient.Email))
                        {
                            continue;
                        }
                        ++recipientCount;
                        newMail.AddRecipient(recipient);
                    }
                    foreach (int key in officerLookup.Keys)
                    {
                        Person recipient = Person.FromIdentity(key);
                        if (!Formatting.ValidateEmailFormat(recipient.Mail))
                        {
                            continue;
                        }
                        ++recipientCount;
                        newMail.AddRecipient(recipient, true);
                    }

                    newMail.SetRecipientCount(recipientCount);
                    newMail.SetResolved();
                    newMail.SetReadyForPickup();
                }
            }
            catch (Exception ex)
            {
                ExceptionMail.Send(
                    new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
            }
            finally
            {
                reader.Close();
            }
        }
Beispiel #29
0
        public static void Send(string title, bool sendToAll, MediaCategories categories, string mailText,
                                Reporters reporters)
        {
            string directory = "content" + Path.DirectorySeparatorChar + "pressreleasetemplate-1";

            string htmlTemplate = "Failed to read HTML mail template.";

            using (
                StreamReader reader = new StreamReader(directory + Path.DirectorySeparatorChar + "template.html",
                                                       Encoding.GetEncoding(1252)))
            {
                htmlTemplate = reader.ReadToEnd();
            }

            /*
             * using (StreamReader reader = new StreamReader(textTemplateFile, System.Text.Encoding.Default))
             * {
             *  textTemplate = reader.ReadToEnd();
             * }*/

            // PREPARE DATE

            // assume Swedish

            CultureInfo culture = new CultureInfo("sv-SE");
            string      date    = DateTime.Today.ToString("d MMMM yyyy", culture);
            string      time    = DateTime.Now.ToString("HH:mm");

            string categoriesSentTo = "Alla kategorier";

            if (!sendToAll)
            {
                categoriesSentTo = GetConcatenatedCategoryString(categories);
            }

            // PREPARE HTML VIEW:

            // Write in the title, intro, and body

            htmlTemplate = htmlTemplate.
                           Replace("%TITLE%", HttpUtility.HtmlEncode(title.ToUpper())).
                           Replace("%title%", HttpUtility.HtmlEncode(title)).
                           Replace("%date%", HttpUtility.HtmlEncode(date)).
                           Replace("%DATE%", HttpUtility.HtmlEncode(date.ToUpper())).
                           Replace("%time%", HttpUtility.HtmlEncode(time)).
                           Replace("%postedtocategories%", HttpUtility.HtmlEncode(categoriesSentTo));

            string body = mailText;

            body = body.
                   Replace("<", "({[(").
                   Replace(">", ")}])").
                   Replace("\"", "quotQUOTquot");

            body = HttpUtility.HtmlEncode(body);

            body = body.
                   Replace("({[(", "<").
                   Replace(")}])", ">").
                   Replace("quotQUOTquot", "\"").
                   Replace("&amp;#", "&#");

            htmlTemplate = htmlTemplate.Replace("%body%", body);

            // Embed any inline images directly into the message

            string newsletterIdentifier = DateTime.Now.ToString("yyyyMMddhhMMssfff") + "@piratpartiet.se";

            // TODO: Read the replacements from a config file

            htmlTemplate = htmlTemplate.Replace("header-pp-logo.png", "cid:pplogo" + newsletterIdentifier);


            /*
             * htmlTemplate = htmlTemplate.Replace("TopRight.png", "cid:topright" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("MiddleRight.png", "cid:middleright" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("BottomRight.png", "cid:bottomright" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("TopLeft.png", "cid:topleft" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("MiddleLeft.png", "cid:middleleft" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("BottomLeft.png", "cid:bottomleft" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("TopMiddle.png", "cid:topmiddle" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("BottomMiddle.png", "cid:bottommiddle" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("PPShield.png", "cid:ppshield" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("Rick.png", "cid:rick" + newsletterIdentifier);
             * htmlTemplate = htmlTemplate.Replace("RFe-signature.gif", "cid:rick-signature" + newsletterIdentifier);*/


            // MemoryStream memStream = new MemoryStream();

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlTemplate,
                                                                                 new ContentType(
                                                                                     MediaTypeNames.Text.Html));

            htmlView.TransferEncoding = TransferEncoding.Base64;

            /*
             * LinkedResource image = new LinkedResource(directory + Path.DirectorySeparatorChar + "header-pp-logo.png");
             * image.ContentId = "pplogo" + newsletterIdentifier;
             * htmlView.LinkedResources.Add(image);*/


            /*
             * -- DISABLED -- code writing a forum-style text file
             *
             *
             * // PREPARE FORUM FILE:
             *
             * string forumTemplate = textTemplate.
             *  Replace("%TITLE%", "[h1]" + title.ToUpper() + "[/h1]").
             *  Replace("%title%", "[h1]" + title + "[/h1]").
             *  Replace("%intro%", intro).
             *  Replace("%body%", mailBody);
             *
             * // Replace "<a href="http://link">Text</a>" with "Text (http://link)"
             *
             * Regex regexLinksForum = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline);
             *
             * forumTemplate = regexLinksForum.Replace(forumTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInForum));
             *
             * using (StreamWriter writer = new StreamWriter(directory + "\\" + "forum.txt", false, System.Text.Encoding.Default))
             * {
             *  writer.WriteLine(forumTemplate);
             * }*/


            /*
             *  -- DISABLED -- no text view
             *
             *
             *
             * // PREPARE TEXT VIEW:
             *
             * // Write in the title, intro, and body
             *
             * textTemplate = textTemplate.
             *  Replace("%TITLE%", title.ToUpper()).
             *  Replace("%title%", title).
             *  Replace("%intro%", intro).
             *  Replace("%body%", mailBody);
             *
             * // Replace "<a href="http://link">Text</a>" with "Text (http://link)"
             *
             * Regex regexLinks = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline);
             *
             * textTemplate = regexLinks.Replace(textTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInText));
             *
             * Regex regexHtmlCodes = new Regex("(?s)\\[[^\\[]+\\]", RegexOptions.Multiline);
             *
             * textTemplate = regexHtmlCodes.Replace(textTemplate, string.Empty);
             *
             * ContentType typeUnicode = new ContentType(MediaTypeNames.Text.Plain);
             * typeUnicode.CharSet = "utf-8";
             *
             * AlternateView textUnicodeView = AlternateView.CreateAlternateViewFromString(textTemplate, typeUnicode);
             *
             * ContentType typeIsoLatin1 = new ContentType(MediaTypeNames.Text.Plain);
             * typeIsoLatin1.CharSet = "iso-8859-1";
             *
             * AlternateView textHotmailView = new AlternateView(new MemoryStream(Encoding.Default.GetBytes(textTemplate)), typeIsoLatin1);
             *
             * */

            foreach (Reporter reporter in reporters)
            {
                //Console.Write (recipient.Name + "(#" + recipient.Identity.ToString() + ")... ");

                try
                {
                    SmtpClient client = new SmtpClient(Config.SmtpHost, Config.SmtpPort);
                    client.Credentials = null;

                    MailMessage message = new MailMessage(
                        new MailAddress("*****@*****.**", "Piratpartiet Press"),
                        new MailAddress(reporter.Email, reporter.Name, Encoding.UTF8));

                    message.Subject = "PP-Press: " + title;

                    string individualBody = htmlTemplate;

                    individualBody = individualBody.
                                     Replace("%reportername%", HttpUtility.HtmlEncode(reporter.Name)).
                                     Replace("%reporteremail%", HttpUtility.HtmlEncode(reporter.Email)).
                                     Replace("%reportercategories%",
                                             HttpUtility.HtmlEncode(GetConcatenatedCategoryString(reporter.MediaCategories)));

                    message.Body         = individualBody;
                    message.BodyEncoding = Encoding.ASCII;
                    message.IsBodyHtml   = true;

                    // COMPENSATE FOR MONO BUG -- put logo online instead of attached

                    message.Body = message.Body.Replace("cid:pplogo" + newsletterIdentifier,
                                                        "http://docs.piratpartiet.se/banners/newsletter-banner-pp-logo.png");

                    /*
                     * Attachment attachment = new Attachment(directory + Path.DirectorySeparatorChar + "header-pp-logo.png", "image/png");
                     * attachment.ContentId = "pplogo" + newsletterIdentifier;
                     * attachment.ContentDisposition.Inline = true;
                     * message.Attachments.Add(attachment);*/

                    bool successOrPermanentFail = false;

                    while (!successOrPermanentFail)
                    {
                        try
                        {
                            client.Send(message);
                            successOrPermanentFail = true;
                        }
                        catch (SmtpException e)
                        {
                            if (!(e.ToString().StartsWith("System.Net.Mail.SmtpException: 4")))
                            {
                                // This is NOT a temporary error (SMTP 4xx). Fail.

                                successOrPermanentFail = true;
                                throw e;
                            }

                            // Otherwise, sleep for a while and try again.

                            Thread.Sleep(1000);
                        }
                    }

                    //Console.WriteLine("ok");

                    //Console.WriteLine("ok");
                }
                catch (Exception e)
                {
                    //Console.WriteLine("FAIL! <" + recipient.Email + ">");
                    ExceptionMail.Send(
                        new Exception("Error sending press release to " + reporter.Name + " <" + reporter.Email + ">:",
                                      e), true);
                }
            }
        }
        public static void Send (string title, bool sendToAll, MediaCategories categories, string mailText,
                                 Reporters reporters)
        {
            string directory = "content" + Path.DirectorySeparatorChar + "pressreleasetemplate-1";

            string htmlTemplate = "Failed to read HTML mail template.";

            using (
                StreamReader reader = new StreamReader(directory + Path.DirectorySeparatorChar + "template.html",
                                                       System.Text.Encoding.GetEncoding(1252)))
            {
                htmlTemplate = reader.ReadToEnd();
            }

            /*
            using (StreamReader reader = new StreamReader(textTemplateFile, System.Text.Encoding.Default))
            {
                textTemplate = reader.ReadToEnd();
            }*/

            // PREPARE DATE

            // assume Swedish

            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("sv-SE");
            string date = DateTime.Today.ToString("d MMMM yyyy", culture);
            string time = DateTime.Now.ToString("HH:mm");

            string categoriesSentTo = "Alla kategorier";

            if (!sendToAll)
            {
                categoriesSentTo = GetConcatenatedCategoryString(categories);
            }

            // PREPARE HTML VIEW:

            // Write in the title, intro, and body

            htmlTemplate = htmlTemplate.
                Replace("%TITLE%", HttpUtility.HtmlEncode(title.ToUpper())).
                Replace("%title%", HttpUtility.HtmlEncode(title)).
                Replace("%date%", HttpUtility.HtmlEncode(date)).
                Replace("%DATE%", HttpUtility.HtmlEncode(date.ToUpper())).
                Replace("%time%", HttpUtility.HtmlEncode(time)).
                Replace("%postedtocategories%", HttpUtility.HtmlEncode(categoriesSentTo));

            string body = mailText;

            body = body.
                Replace("<", "({[(").
                Replace(">", ")}])").
                Replace("\"", "quotQUOTquot");

            body = HttpUtility.HtmlEncode(body);

            body = body.
                Replace("({[(", "<").
                Replace(")}])", ">").
                Replace("quotQUOTquot", "\"").
                Replace("&amp;#", "&#");

            htmlTemplate = htmlTemplate.Replace("%body%", body);

            // Embed any inline images directly into the message

            string newsletterIdentifier = DateTime.Now.ToString("yyyyMMddhhMMssfff") + "@piratpartiet.se";

            // TODO: Read the replacements from a config file

            htmlTemplate = htmlTemplate.Replace("header-pp-logo.png", "cid:pplogo" + newsletterIdentifier);


            /*
            htmlTemplate = htmlTemplate.Replace("TopRight.png", "cid:topright" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("MiddleRight.png", "cid:middleright" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("BottomRight.png", "cid:bottomright" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("TopLeft.png", "cid:topleft" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("MiddleLeft.png", "cid:middleleft" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("BottomLeft.png", "cid:bottomleft" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("TopMiddle.png", "cid:topmiddle" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("BottomMiddle.png", "cid:bottommiddle" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("PPShield.png", "cid:ppshield" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("Rick.png", "cid:rick" + newsletterIdentifier);
            htmlTemplate = htmlTemplate.Replace("RFe-signature.gif", "cid:rick-signature" + newsletterIdentifier);*/


            // MemoryStream memStream = new MemoryStream();

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlTemplate,
                                                                                 new ContentType(
                                                                                     MediaTypeNames.Text.Html));
            htmlView.TransferEncoding = TransferEncoding.Base64;

            /*
            LinkedResource image = new LinkedResource(directory + Path.DirectorySeparatorChar + "header-pp-logo.png");
            image.ContentId = "pplogo" + newsletterIdentifier;
            htmlView.LinkedResources.Add(image);*/


            /*
             * -- DISABLED -- code writing a forum-style text file
             * 

            // PREPARE FORUM FILE:

            string forumTemplate = textTemplate.
                Replace("%TITLE%", "[h1]" + title.ToUpper() + "[/h1]").
                Replace("%title%", "[h1]" + title + "[/h1]").
                Replace("%intro%", intro).
                Replace("%body%", mailBody);

            // Replace "<a href="http://link">Text</a>" with "Text (http://link)"

            Regex regexLinksForum = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline);

            forumTemplate = regexLinksForum.Replace(forumTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInForum));

            using (StreamWriter writer = new StreamWriter(directory + "\\" + "forum.txt", false, System.Text.Encoding.Default))
            {
                writer.WriteLine(forumTemplate);
            }*/


            /*
             *  -- DISABLED -- no text view
             * 
             * 

            // PREPARE TEXT VIEW:

            // Write in the title, intro, and body

            textTemplate = textTemplate.
                Replace("%TITLE%", title.ToUpper()).
                Replace("%title%", title).
                Replace("%intro%", intro).
                Replace("%body%", mailBody);

            // Replace "<a href="http://link">Text</a>" with "Text (http://link)"

            Regex regexLinks = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline);

            textTemplate = regexLinks.Replace(textTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInText));

            Regex regexHtmlCodes = new Regex("(?s)\\[[^\\[]+\\]", RegexOptions.Multiline);

            textTemplate = regexHtmlCodes.Replace(textTemplate, string.Empty);

            ContentType typeUnicode = new ContentType(MediaTypeNames.Text.Plain);
            typeUnicode.CharSet = "utf-8";

            AlternateView textUnicodeView = AlternateView.CreateAlternateViewFromString(textTemplate, typeUnicode);

            ContentType typeIsoLatin1 = new ContentType(MediaTypeNames.Text.Plain);
            typeIsoLatin1.CharSet = "iso-8859-1";

            AlternateView textHotmailView = new AlternateView(new MemoryStream(Encoding.Default.GetBytes(textTemplate)), typeIsoLatin1);
             * 
             * */

            foreach (Reporter reporter in reporters)
            {
                //Console.Write (recipient.Name + "(#" + recipient.Identity.ToString() + ")... ");

                try
                {
                    SmtpClient client = new SmtpClient(Config.SmtpHost, Config.SmtpPort);
                    client.Credentials = null;

                    MailMessage message = new MailMessage(
                        new MailAddress("*****@*****.**", "Piratpartiet Press"),
                        new MailAddress(reporter.Email, reporter.Name, Encoding.UTF8));

                    message.Subject = "PP-Press: " + title;

                    string individualBody = htmlTemplate;

                    individualBody = individualBody.
                        Replace("%reportername%", HttpUtility.HtmlEncode(reporter.Name)).
                        Replace("%reporteremail%", HttpUtility.HtmlEncode(reporter.Email)).
                        Replace("%reportercategories%",
                                HttpUtility.HtmlEncode(GetConcatenatedCategoryString(reporter.MediaCategories)));

                    message.Body = individualBody;
                    message.BodyEncoding = Encoding.ASCII;
                    message.IsBodyHtml = true;

                    // COMPENSATE FOR MONO BUG -- put logo online instead of attached

                    message.Body = message.Body.Replace("cid:pplogo" + newsletterIdentifier,
                                                        "http://docs.piratpartiet.se/banners/newsletter-banner-pp-logo.png");

                    /*
                    Attachment attachment = new Attachment(directory + Path.DirectorySeparatorChar + "header-pp-logo.png", "image/png");
                    attachment.ContentId = "pplogo" + newsletterIdentifier;
                    attachment.ContentDisposition.Inline = true;
                    message.Attachments.Add(attachment);*/

                    bool successOrPermanentFail = false;

                    while (!successOrPermanentFail)
                    {
                        try
                        {
                            client.Send(message);
                            successOrPermanentFail = true;
                        }
                        catch (SmtpException e)
                        {
                            if (!(e.ToString().StartsWith("System.Net.Mail.SmtpException: 4")))
                            {
                                // This is NOT a temporary error (SMTP 4xx). Fail.

                                successOrPermanentFail = true;
                                throw e;
                            }

                            // Otherwise, sleep for a while and try again.

                            System.Threading.Thread.Sleep(1000);
                        }
                    }

                    //Console.WriteLine("ok");

                    //Console.WriteLine("ok");
                }
                catch (Exception e)
                {
                    //Console.WriteLine("FAIL! <" + recipient.Email + ">");
                    ExceptionMail.Send(
                        new Exception("Error sending press release to " + reporter.Name + " <" + reporter.Email + ">:",
                                      e),true);
                }
            }
        }
Beispiel #31
0
 public void SetupForEverySingleTestMethod()
 {
     Reporters.AddTestCaseMetadataToHtmlReport(TestContext);
 }