Beispiel #1
0
        public async Task TestNuGetEmail()
        {
            // Create debug log and fake SendGrid key
            var debugLog        = new Log(LogDestination.Debug, Log.DefaultCategoryName);
            var fakeSendGridKey = TestUtilities.CreateUniqueDigits();

            // Initalize email class
            var emailSender = new SendGridEmail(debugLog, fakeSendGridKey);

            // Create an email message with a To: field set to null
            IEmail emailMsg = new Email()
            {
                To = null
            };

            // Check that this raises the correct exception. Since EMail raises a generic exception,
            // we catch the exception here and test that it includes the expected error message
            try
            {
                await emailSender.SendEmail(emailMsg);
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message.Contains("got empty email address list"));
                return;
            }

            // Code should never each here
            Assert.IsTrue(false);
        }
        public async Task <HttpResponseMessage> GetByEmailAsync(string email)
        {
            try
            {
                ItemResponse <EmailViewModel> resp = new ItemResponse <EmailViewModel>();
                resp.Item = _userService.GetByEmail(email);
                var Id = resp.Item.Id;

                if (resp.Item.isConfirmed == false)
                {
                    var AuthTokenID       = _userService.AuthorizationToken(Id);
                    var ConfirmationToken = AuthTokenID.ConfirmationToken;
                    var SendEmail         = _userService.GetEmail(ConfirmationToken, email);
                    int authTokenId       = _userService.CreateAuthToken(AuthTokenID);

                    var response = await SendGridEmail.SendEmail(SendEmail);

                    return(Request.CreateResponse(HttpStatusCode.OK, resp));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, resp));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Beispiel #3
0
        public ActionResult RcoverPwd(string txtUserName)
        {
            var user = _userRepo.GetUserByName(txtUserName);

            if (user != null)
            {
                string url  = "http://localhost:62710/User/ChangePassword/" + user.Id;
                string body = "<p>You have requested for reset password.</p><p>Click here to <a href='" + url + "'>Change Password</a></p>";  // link for small page
                SendGridEmail.SendEmail(user.Email, "Change Password", body);
                return(RedirectToAction("SuccessMessage", "User", new { }));
            }
            else
            {
                return(RedirectToAction("Login", "User", new { }));
            }
        }
        public async Task <HttpResponseMessage> Post(RegistrationAddRequest model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var    webClient         = new WebClient();
                    string verification      = webClient.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", _configService.ConvertConfigValue_String("Google_Recaptcha"), model.recaptchaResponse));
                    var    recaptchaResponse = (JObject.Parse(verification)["success"].Value <bool>());

                    if (recaptchaResponse == true)
                    {
                        int id    = _userService.Create(model);
                        var email = model.Email;

                        var AuthTokenID       = _userService.AuthorizationToken(id);
                        var ConfirmationToken = AuthTokenID.ConfirmationToken;
                        var SendEmail         = _userService.GetEmail(ConfirmationToken, email);
                        int authTokenId       = _userService.CreateAuthToken(AuthTokenID);

                        ItemResponse <int> resp = new ItemResponse <int>();
                        var response            = await SendGridEmail.SendEmail(SendEmail);

                        return(Request.CreateResponse(HttpStatusCode.OK, resp));
                    }
                    else
                    {
                        ErrorResponse resp = new ErrorResponse("Uncessful Registration Attempt");
                        return(Request.CreateResponse(HttpStatusCode.OK, resp));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
        /// <summary>
        /// Method to format test result messages and send them in an email
        /// Note that this is done only for failed tests
        /// </summary>
        /// <param name="runId">run id</param>
        /// <param name="hasTestFailed">flag to check of any test has failed</param>
        /// <param name="testResultMessages">test result messages for failed tests</param>
        private static void FormatResultAndSendEmail(int runId, bool hasTestFailed, IEnumerable <string> testResultMessages)
        {
            // If any tests failed during this run, check whether we should send e-mail about them
            if (hasTestFailed && sendEmailOnTestFailure)
            {
                Email msg = new Email();
                try
                {
                    msg.Subject = string.Format("Failed tests during run#:{0} out of {1}", runId, numberOfRuns);
                    msg.To      = new List <string>()
                    {
                        TestConstants.FailedTestsEmail
                    };
                    msg.Category = "EndToEnd Testing";
                    msg.HtmlBody = string.Join("<br><br>", testResultMessages);
                    string        configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
                    string        sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);
                    var           log            = new Log(LogDestination.Console, Log.DefaultCategoryName);
                    SendGridEmail sendingClient  = new SendGridEmail(log, sendGridKey);
                    sendingClient.SendEmail(msg).Wait();
                }
                catch (Exception e)
                {
                    // SendEmail failed. Report the error on the console and move on.
                    System.ConsoleColor oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Encountered an error during SendEmail:");
                    Console.WriteLine(e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine(e.InnerException.Message);
                    }

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine();
                    Console.WriteLine("Tried to send the following message:");
                    Console.WriteLine(msg.Subject);
                    Console.WriteLine(msg.HtmlBody);
                    Console.ForegroundColor = oldColor;
                }
            }
        }
        public void SendOneEmail()
        {
            var    log            = new Log(LogDestination.Debug, Log.DefaultCategoryName);
            string configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
            string sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);

            // setup the email to send
            Email email = new Email();

            email.To = new List <string>();
            email.To.Add(TestConstants.FailedTestsEmail);
            email.Subject  = "testing SendGrid";
            email.HtmlBody = "<html><H1>not much here</H1></html>";
            email.TextBody = "not much here";
            email.Category = "UnitTest";

            // send the email
            SendGridEmail emailSender = new SendGridEmail(log, sendGridKey);

            emailSender.SendEmail(email).Wait();
        }
Beispiel #7
0
 public void SendEmail(string to, string subject, string body)
 {
     SendGridEmail.SendEmail(to, subject, body);
 }
Beispiel #8
0
        /// <summary>
        /// Runs tests one-by-one in a loop
        /// </summary>
        /// <param name="args">Argument list</param>
        private static void Main(string[] args)
        {
            ParseArgs(args);

            bool  hasTestFailed = false;
            Email msg           = new Email();

            foreach (var v in TestClasses)
            {
                var kvFactory = new KVFactory();
                foreach (IKV kv in kvFactory.CreateKV())
                {
                    // Make a test class object
                    var      currentAssembly   = Assembly.GetExecutingAssembly();
                    var      currentNamespace  = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
                    object[] constructorParams = new object[1] {
                        kv
                    };
                    object classInstance = ReflectionUtils.CreateClassInstance(currentAssembly, currentNamespace, v, constructorParams);

                    if (classInstance == null)
                    {
                        Console.WriteLine("Error: couldn't find the class with the parameter types specified!!!");
                        throw new Exception("Could not find test class with the parameter types specified in code!");
                    }

                    // For each method of the class labelled with TestMethod attribute
                    foreach (var testMethod in ReflectionUtils.GetMethodsWithTypeTAttribute(classInstance.GetType(), typeof(TestMethodAttribute)))
                    {
                        DateTime testStartTime = DateTime.Now;

                        Console.WriteLine(testMethod.Name + " started against " + TestUtilities.PrettyServerName(TestConstants.ServerApiBaseUrl));
                        try
                        {
                            Task test = (Task)testMethod.Invoke(classInstance, null);

                            // Check whether the test terminates on time
                            if (test.Wait(secsPerTest * 1000))
                            {
                                Console.WriteLine(testMethod.Name + " finished within {0} secs.", DateTime.Now.Subtract(testStartTime).Seconds);
                            }
                            else
                            {
                                Console.WriteLine(testMethod.Name + " has not finished within {0} secs. Moved on.", secsPerTest);
                                throw new Exception(string.Format(testMethod.Name + " has not finished within {0} secs. Moved on.", secsPerTest));
                            }
                        }
                        catch (Exception ex)
                        {
                            // Write the error to the console
                            Console.WriteLine(ex.ToString());

                            // If this test is the first failed test in this run, create a new email, otherwise just appent to the message
                            if (!hasTestFailed)
                            {
                                msg.Subject = "Failed unit tests";
                                msg.To      = new List <string>()
                                {
                                    TestConstants.FailedTestsEmail
                                };
                                msg.Category = "Unit Testing";
                                msg.HtmlBody = TestUtilities.Exception2HtmlEmail(testMethod.Name, ex);
                            }
                            else
                            {
                                msg.HtmlBody += "<br><br>" + TestUtilities.Exception2HtmlEmail(testMethod.Name, ex);
                            }

                            hasTestFailed = true;
                        }
                    }
                }
            }

            // If any tests failed during this run, check whether we should send e-mail about them
            if (hasTestFailed && sendEmailOnTestFailure)
            {
                string configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
                string sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);

                try
                {
                    var           log           = new Log(LogDestination.Console, Log.DefaultCategoryName);
                    SendGridEmail sendingClient = new SendGridEmail(log, sendGridKey);
                    sendingClient.SendEmail(msg).Wait();
                }
                catch (Exception e)
                {
                    // SendEmail failed. Report the error on the console and move on.
                    System.ConsoleColor oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Encountered an error during SendEmail:");
                    Console.WriteLine(e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine(e.InnerException.Message);
                    }

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine();
                    Console.WriteLine("Tried to send the following message:");
                    Console.WriteLine(msg.Subject);
                    Console.WriteLine(msg.HtmlBody);
                    Console.ForegroundColor = oldColor;
                }
            }
        }