Exemplo n.º 1
0
        private void SendMessage(Email email)
        {
            var message = new MailMessage(email.from, email.to, email.subject, email.body);
            var client = new SmtpClient
            {
                Host = "smtp.live.com",
                Timeout = 10000,
                Port = 587,
                EnableSsl = true,
                UseDefaultCredentials = false,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("", @"")
            };

            //Host = "smtp.gmail.com",

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in SendMessage(): {0}", ex);
            }
        }
Exemplo n.º 2
0
        public void SendEmail()
        {
            Email email = new Email() { To = "*****@*****.**", Subject = "Unit Test", DeliveryType ="Email", Message = "Test" };

            SendMail sendMail = new SendMail();
            Assert.IsTrue(sendMail.SendEmail(email));
        }
Exemplo n.º 3
0
 public Email CreateValidAltEmail()
 {
     Email email = new Email();
     email.Address = "*****@*****.**";
     email.Type = EmailType.Alt;
     return email;
 }
Exemplo n.º 4
0
    public static Restaurant CreateRestaurant(int userId, string name, string food, string restaurantType, int size, string city, string opening, string meals, string drinks)
    {
        Restaurant restaurant = new Restaurant();
        restaurant.UserId = userId;
        restaurant.Name = name;
        restaurant.Food = food;
        restaurant.RestaurantType = restaurantType;
        restaurant.Size = size;
        restaurant.SquareFootage = size * 15;
        restaurant.City = city;
        restaurant.Opening = opening;
        restaurant.Save();

        Answer.CreateAnswersFromTemplate(restaurant, meals, drinks);

        Users user = Users.LoadById(restaurant.UserId);

        if (ConfigurationManager.AppSettings["IsProduction"] == "true")
        {
            string body = string.Format("{0}<br>UserId: {1}<br>Name: {2}<br>Email: {3}", restaurant.Name, user.Id, user.Name, user.Email);
            Email email = new Email("*****@*****.**", "*****@*****.**", "New Restaurant", body);
            email.Send();
        }
        HttpContext.Current.Session["CurrentUser"] = user;
        HttpContext.Current.Session["CurrentProspect"] = null;

        return restaurant;
    }
Exemplo n.º 5
0
        private static IEnumerable<Email> getEmailDataFromTable()
        {
            SqlCommand command = new SqlCommand(
                string.Format("SELECT Id as IdMail, EMail as SendTo, Theme as Topic, Text as Body FROM {0} WHERE Sended=0", TABLE_NAME),
                connection);
            SqlDataReader reader = command.ExecuteReader();
            List<Email> newMails = new List<Email>();

            while (reader.Read())
            {
                Email mail = new Email
                {
                    IdMail = reader["IdMail"].ToString().Trim(),
                    SendTo = reader["SendTo"].ToString().Trim(),
                    Topic = reader["Topic"].ToString().Trim(),
                    Body = reader["Body"].ToString().Trim()
                };

                Console.WriteLine("--- New e-mail ---");
                Console.WriteLine("SendTo: " + mail.SendTo);
                Console.WriteLine("Topic: " + mail.Topic);
                Console.WriteLine("Body: " + mail.Body);

                newMails.Add(mail);
            }
            reader.Close();

            return newMails;
        }
Exemplo n.º 6
0
 public Email CreateValidWorkEmail()
 {
     Email email = new Email();
     email.Address = "*****@*****.**";
     email.Type = EmailType.Work;
     return email;
 }
Exemplo n.º 7
0
        public void DoAction(WFActivity activity)
        {
            this._activity = activity;
            _mail = new Email();
            foreach (KeyValuePair<string, WFUser> kvUser in activity.WFUsers)
            {
                string mailAddress = String.IsNullOrWhiteSpace(kvUser.Value.Email) ? "" : kvUser.Value.Email.Trim() + ";";
                if (kvUser.Value.IsKeyUser)
                {
                    toUser += kvUser.Value.DisplayName + ",";
                    toMail += mailAddress;
                }
                else if (kvUser.Value.IsApprover && !kvUser.Value.IsKeyUser)
                {
                    continue;
                }
                else
                {
                    ccMail += mailAddress;
                }
            }

            if (AccessControl.IsVendor())
            {
                toUser += AccessControl.CurrentLogonUser.Name + ",";
                toMail += string.IsNullOrEmpty(AccessControl.CurrentLogonUser.Email) ?
                    "" : AccessControl.CurrentLogonUser.Email.Trim() + ";";
            }

            SendMail();
        }
Exemplo n.º 8
0
        public HomeViewModel(ITelephonyService telephonyService = null, IScreen hostScreen = null)
        {
            TelephonyService = telephonyService ?? Locator.Current.GetService<ITelephonyService>();

            HostScreen = hostScreen ?? Locator.Current.GetService<IScreen>();

            var canComposeSMS = this.WhenAny(x => x.Recipient, x => !string.IsNullOrWhiteSpace(x.Value));
            ComposeSMS = ReactiveCommand.CreateAsyncTask(canComposeSMS,
                async _ => { await TelephonyService.ComposeSMS(Recipient); });
            ComposeSMS.ThrownExceptions.Subscribe(
                ex => UserError.Throw("Does this device have the capability to send SMS?", ex));

            var canComposeEmail = this.WhenAny(x => x.Recipient, x => !string.IsNullOrWhiteSpace(x.Value));
            ComposeEmail = ReactiveCommand.CreateAsyncTask(canComposeEmail, async _ =>
            {
                var email = new Email(Recipient);

                await TelephonyService.ComposeEmail(email);
            });
            ComposeEmail.ThrownExceptions.Subscribe(
                ex => UserError.Throw("The recipient is potentially not a well formed email address.", ex));

            var canMakePhoneCall = this.WhenAny(x => x.Recipient, x => !string.IsNullOrWhiteSpace(x.Value));
            MakePhoneCall = ReactiveCommand.CreateAsyncTask(canMakePhoneCall,
                async _ => { await TelephonyService.MakePhoneCall(Recipient); });
            MakePhoneCall.ThrownExceptions.Subscribe(
                ex => UserError.Throw("Does this device have the capability to make phone calls?", ex));

            var canMakeVideoCall = this.WhenAny(x => x.Recipient, x => !string.IsNullOrWhiteSpace(x.Value));
            MakeVideoCall = ReactiveCommand.CreateAsyncTask(canMakeVideoCall,
                async _ => { await TelephonyService.MakeVideoCall(Recipient); });
            MakeVideoCall.ThrownExceptions.Subscribe(
                ex => UserError.Throw("Does this device have the capability to make video calls?", ex));
        }
 public void Send(Email email)
 {
     using (var mailMessage = CreateMailMessage(email))
     {
         _simpleEmailService.SendEmail(CreateSendEmailRequest(mailMessage));
     }
 }
Exemplo n.º 10
0
        public static HttpResponseMessage ValidateModel(Email.Email model)
        {
            var response = new HttpResponseMessage();
            if (!model.DeliveryType.Trim().ToLower().Equals("email"))
            {
                response.StatusCode = HttpStatusCode.NotImplemented;
                response.ReasonPhrase = string.Format("The DeliveryType [{0}] is not implemented.", model.DeliveryType);
                Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(new Exception(string.Format("The DeliveryType [{0}] is not implemented.", model.DeliveryType))));
            }

            if (string.IsNullOrWhiteSpace(model.To))
            {
                response.ReasonPhrase = "The \"To\" value is required";
                response.StatusCode = HttpStatusCode.BadRequest;
            }

            if (string.IsNullOrWhiteSpace(model.Subject))
            {
                response.ReasonPhrase = "The \"Subject\" value is required";
                response.StatusCode = HttpStatusCode.BadRequest;
            }

            try
            {
                var mailAddress = new MailAddress(model.To);
            }
            catch (FormatException)
            {
                response.ReasonPhrase = "The \"To\" value is not a valid email address";
                response.StatusCode = HttpStatusCode.BadRequest;
            }
            return response;
        }
Exemplo n.º 11
0
        public void TestMethod1()
        {
            /*var res = ArticuloLogica.Instancia.ingresarBodega(1, "Bodega San Pedro", "123");
            var result = ArticuloLogica.Instancia.obtenerBodegas(1);
            var result = ArticuloLogica.Instancia.ingresarArticulo(1, "100213", "Lápices Mongol", "unidad", "Son chinos", Convert.FromBase64String(""), 1);*/
            //var res = ArticuloLogica.Instancia.obtenerArticulosBodega("Bodega San Pedro");
            var orden = new Documento() {
                Fecha1= System.DateTime.Now,
                IdSocio = 2,
                TipoDocumento = 1,
                TotalAI = 1300
            };
            var detalle = new DocumentoDetalle(){
                NumeroDocumento = 22,
                IdArticulo = 1,
                Cantidad = 10,
                Descripcion = "Lapices Mongol",
                IdBodega = 1,
                Impuesto = 13,
                Precio = 130,
                TipoDocumento = 1

            };
            Email email = new Email();
            email.EnviarCorreo("*****@*****.**", orden, detalle);
        }
        public EmailSendAttempt Send(Email email)
        {
            email.Sender = email.Sender ?? Configuration.EmailSender;
            var attempt = new EmailSendAttempt
                  {
                      Date = DateTime.UtcNow,
                      Server = Smtp.Host,
                      Success = true,
                  };
            try
            {
                Smtp.Send(email.ToMailMessage());
                email.Sent = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                attempt.Success = false;
                attempt.Error = ex.Message;
            }

            email.Tenant = Tenant.Document.Id;
            email.AddAttempt(attempt);
            Emails.Save(email);
            return attempt;
        }
 private bool ValidateEmail()
 {
     var email = new Email(_emailCandidate.Text);
     if(String.IsNullOrEmpty(_emailCandidate.Text)) _emailCandidate.SetError(GetString(Resource.String.field_not_fill), _errorDrawable);
     if(!email.IsValid ()) _emailCandidate.SetError(GetString(Resource.String.invalid_email), _errorDrawable);
     return email.IsValid ();
 }
Exemplo n.º 14
0
        /// <summary>
        /// Report a member
        /// </summary>
        /// <param name="report"></param>
        public void MemberReport(Report report)
        {
            var sb = new StringBuilder();
            var email = new Email();

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>",
                string.Concat(_settingsService.GetSettings().ForumUrl.TrimEnd('/'), report.Reporter.NiceUrl),
                report.Reporter.UserName,
                _localizationService.GetResourceString("Report.Reporter"));

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>",
                string.Concat(_settingsService.GetSettings().ForumUrl.TrimEnd('/'), report.ReportedMember.NiceUrl),
                report.ReportedMember.UserName,
                _localizationService.GetResourceString("Report.MemberReported"));

            sb.Append($"<p>{_localizationService.GetResourceString("Report.Reason")}:</p>");
            sb.Append($"<p>{report.Reason}</p>");

            email.EmailTo = _settingsService.GetSettings().AdminEmailAddress;
            email.Subject = _localizationService.GetResourceString("Report.MemberReport");
            email.NameTo = _localizationService.GetResourceString("Report.Admin");

            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
            _emailService.SendMail(email);
        }
Exemplo n.º 15
0
        // Methods
        public Task SendEmailAsync(Email email)
        {
            return Task.Run(() =>
                {
                    try
                    {
                        MailMessage mail = new MailMessage
                        {
                            From = new MailAddress(email.From),
                            Subject = email.Subject,
                            Body = email.Body,
                            IsBodyHtml = true
                        };

                        mail.To.Add(email.To);

                        SmtpClient smtp = new SmtpClient
                        {
                            Host = authentication.Host,
                            Port = authentication.Port,
                            UseDefaultCredentials = false,
                            Credentials = new System.Net.NetworkCredential(authentication.UserName, authentication.Password),
                            EnableSsl = true
                        };

                        smtp.Send(mail);
                    }
                    catch
                    {
                    }
                }
            );
        }
Exemplo n.º 16
0
    public void SavePessoaEmail(Pessoa pessoa)
    {
        var emailCount = int.Parse(Request["hiddenEmailCount"]);
        var emailsInvalidos = new List<string>();
        for (int i = 0; i < emailCount; i++)
        {
            if (string.IsNullOrEmpty(Request["txtEmail-" + i])) continue;
            if (!Funcoes.ValidateEmail(Request["txtEmail-" + i]))
                emailsInvalidos.Add(Request["txtEmail-" + i]);
        }

        if (emailsInvalidos.Count > 0)
            throw new TradeVisionValidationError("Endereço de email inválido\n( " + string.Join(",", emailsInvalidos.ToArray()) + " )");

        var emailDel = new Email();
        emailDel.Pessoa = pessoa;
        emailDel.Delete();

        for (int i = 0; i < emailCount; i++)
        {
            if (string.IsNullOrEmpty(Request["txtEmail-" + i])) continue;
            var email = new Email();
            email.Pessoa = pessoa;
            if (!string.IsNullOrEmpty(Request["ddlTiposEmail-" + i]))
                email.IDTipoEmail = int.Parse(Request["ddlTiposEmail-" + i]);
            email.EnderecoEmail = Request["txtEmail-" + i];
            email.Save();
        }
    }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            string f = "image/";

            IAvatarFolder folder = new AvatarFolder(f);

            int width = 250;

            IEmail email = new Email("*****@*****.**");

            IAvatarConfiguration configuration =
                new AvatarConfiguration(
                    email,
                    folder,
                    width,
                    AvatarImageExtension.Jpeg,
                    AvatarRating.R);

            IAvatar avatar = new Avatar(configuration);

            if (avatar.Exists() == false)
            {
                avatar.Save();
                System.Console.WriteLine("Foto gravada com sucesso !!!");
            }
            else
            {

                System.Console.WriteLine("Foto existente !!!");
            }

            System.Console.ReadKey();
        }
Exemplo n.º 18
0
 public void GetRequestsByUser()
 {
     IRequestRepository requestRepository = RequestRepository.Instance;
     IUserRepository userRepository = UserRepository.Instance;
     Email email1 = new Email("*****@*****.**");
     Email email2 = new Email("*****@*****.**");
     User user1 = new User(new Email("*****@*****.**"), new UserName("User1", "Last"), "pwd", null);
     User user2 = new User(new Email("*****@*****.**"), new UserName("User2", "Last"), "pwd", null);
     userRepository.SaveUser(user1);
     userRepository.SaveUser(user2);
     Request request1 = new Request(user1, new Package("test pkg", "1kg", "1x1x1kg"),
                                    new Location("London", new TravelDate(DateTime.Now)),
                                    new Location("Paris", new TravelDate(DateTime.Now)));
     Request request2 = new Request(user2, new Package("test pkg", "1kg", "1x1x1kg"),
                                    new Location("London", new TravelDate(DateTime.Now)),
                                    new Location("Paris", new TravelDate(DateTime.Now)));
     requestRepository.Save(request1);
     requestRepository.Save(request2);
     IEnumerable<Request> requests = requestRepository.SearchByUser(user1.EmailAddress);
     try
     {
         Assert.True(requests.Contains(request1));
         Assert.False(requests.Contains(request2));
     }
     finally
     {
         requestRepository.Delete(request1);
         requestRepository.Delete(request2);
     }
 }
Exemplo n.º 19
0
        public Email Post(Email email)
        {
            try
            {
                repository.Add(email);

                foreach (var file in email.Attachments)
                {
                    if (!string.IsNullOrEmpty(file.Content))
                    {
                        if (File.Exists(attachmentSaveFolder + file.Name))
                            File.Delete(attachmentSaveFolder + file.Name);

                        byte[] filebytes = Convert.FromBase64String(file.Content);
                        FileStream fs = new FileStream(attachmentSaveFolder + file.Name,
                                                       FileMode.CreateNew,
                                                       FileAccess.Write,
                                                       FileShare.None);
                        fs.Write(filebytes, 0, filebytes.Length);
                        fs.Close();
                    }
                }
                return email;
            }
            catch (HttpRequestException e)
            {
                // !!!
                // HttpResponseExceptions are not properly returned yet. It's a known bug in WCF WebAPI preview 6. I'm hoping it's fixed in a subsequent release.
                // !!!
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(e.InnerException.ToString()) });
            }
        }
Exemplo n.º 20
0
        public ActionResult Create(PFModel model)
        {
            try
            {
                PF pfData = new PF();
                int idPF = pfData.Inserir(model);

                List<EmailModel> listaEmail = new List<EmailModel>();
                if (Session["EmailPF"] != null)
                    listaEmail = (List<EmailModel>)Session["EmailPF"];

                List<TelefoneModel> listaTelefone = new List<TelefoneModel>();
                if (Session["TelefonePF"] != null)
                    listaTelefone = (List<TelefoneModel>)Session["TelefonePF"];

                List<EnderecoModel> listaEndereco = new List<EnderecoModel>();
                if (Session["EnderecoPF"] != null)
                    listaEndereco = (List<EnderecoModel>)Session["EnderecoPF"];

                List<PF_PJModel> listaEmpresa = new List<PF_PJModel>();
                if (Session["EmpresaPF"] != null)
                    listaEmpresa = (List<PF_PJModel>)Session["EmpresaPF"];

                Email _dataEmail = new Email();
                foreach (EmailModel item in listaEmail)
                {
                    item.IdPessoa = idPF;
                    _dataEmail.Inserir(item);
                }

                Telefone _dataTel = new Telefone();
                foreach (TelefoneModel item in listaTelefone)
                {
                    item.IdPessoa = idPF;
                    _dataTel.Inserir(item);
                }

                Endereco _dataEndereco = new Endereco();
                foreach (EnderecoModel item in listaEndereco)
                {
                    item.IdPessoa = idPF;
                    _dataEndereco.Inserir(item);
                }
                
                foreach (PF_PJModel item in listaEmpresa)
                {
                    pfData.InsereEmpresa(idPF, item.PJ.Id, item.Cargo.Id, item.Departamento.Id);
                }

                Session["EnderecoPF"] = null;
                Session["TelefonePF"] = null;
                Session["EmailPF"] = null;

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public EmailToAccountMapQueryModel(Email email, Guid accountId)
        {
            Contract.Argument(() => email, () => accountId).NotNullOrDefault();

            Email = email;
            AccountId = accountId;
        }
Exemplo n.º 22
0
 public Email CreateValidHomeEmail()
 {
     Email email = new Email();
     email.Address = "*****@*****.**";
     email.Type = EmailType.Home;
     return email;
 }
        public PartialViewResult Create(ProgramSubscription p)
        {
            p.ProgrammId = i;

            var slist = pm.GetAll();

            if (slist.Contains(slist.FirstOrDefault(q => q._User.MailId==p._User.MailId && q.ProgrammId==p.ProgrammId)))
            {
                ViewBag.ErrorMessage = "you already Subscribed to this program";
                return PartialView("_Create");
            }
            p.SubscriptionDate = DateTime.Now.Date;
            pm.AddProgramSubscription(p);

            Email mail = new Email();
            mail.FromAddress = "*****@*****.**";
            mail.ToAddress = p._User.MailId;
            mail.Subject = "Thank you for subscribing to updates from Right to Live";
            mail.Body = "Hi\n" + p._User.MailId + ",\n\nYou have successfully subscribed to the program " + programname + ". \n\nWe will start updating you on this program soon.\nFor any further information, please visit our site.\n\nIn case you want to unsubscribe from receiving updates, please send us a mail to [email protected] with the subject as 'Unsubscribe'\n\nHave a great day,\nRight to Live Team";

            if (es.SendMail(mail))
            {
                ViewBag.ErrorMessage = "You are succesfully subscribed to this program";
                return PartialView("_Create");
            }
            else
            {
                ViewBag.ErrorMessage = "Sorry,We are unable to connect to the Network";
                return PartialView("_Create");
            }
        }
		private static TriggeredSendDefinition GetSendDefinition(string strGUID, int etEmailId, string toEmail, string emailName)
		{
			//Create TriggeredSendDefinition object [Messages > Email > Triggered]
			TriggeredSendDefinition tsd = new TriggeredSendDefinition();
			//tsd.Email.HTMLBody
			tsd.Name = strGUID;//required
			tsd.CustomerKey = strGUID;//recommended or the application will assign a number
			tsd.Description = emailName + " to " + toEmail;//recommended or the Description will default to the Name

			//Set to delivery both Text and HTML versions.
			tsd.IsMultipart = true;//recommended as a best practice
			tsd.IsMultipartSpecified = true;//required

			//Set to track the links found in the email
			tsd.IsWrapped = true;//recommended to take advantage of ExactTarget's tracking
			tsd.IsWrappedSpecified = true;//required

			//Create Email object to refer to pre-create Email
			Email em = new Email();
			em.ID = etEmailId;
			//em.ID = 620046;//required //Available in the ET UI [Content > My Emails > Properties]
			em.IDSpecified = true;//required

			//Apply Email object to the TriggeredSendDefinition object
			tsd.Email = em;//required
			tsd.Email.IsHTMLPaste = true;

			//Create SendClassification
			tsd.SendClassification = new SendClassification();
			// tsd.SendClassification.CustomerKey = "201";//required //Available in the ET UI [Admin > Send Management > Send Classifications > Edit Item > External Key]
			tsd.SendClassification.CustomerKey = ConfigurationManager.AppSettings["ExactTargetCustomerKey"];
			return tsd;
		}
		public static void SendEmail(Email email)
		{
#if UNITY_IOS && !UNITY_EDITOR
			_opencodingConsoleBeginEmail(email.ToAddress, email.Subject, email.Message, email.IsHTML);
			foreach (var attachment in email.Attachments)
			{
				_opencodingConsoleAddAttachment(attachment.Data, attachment.Data.Length, attachment.MimeType, attachment.Filename);
			}
			_opencodingConsoleFinishEmail();
#elif UNITY_ANDROID && !UNITY_EDITOR
			AndroidJavaClass androidEmailClass = new AndroidJavaClass("net.opencoding.console.Email");
			
			androidEmailClass.CallStatic("beginEmail", email.ToAddress, email.Subject, email.Message, email.IsHTML);
			var emailAttachmentsDirectory = Path.Combine(Application.temporaryCachePath, "EmailAttachments");
			Directory.CreateDirectory(emailAttachmentsDirectory);
			foreach (var attachment in email.Attachments)
			{
				var attachmentPath = Path.Combine(emailAttachmentsDirectory, attachment.Filename);
				File.WriteAllBytes(attachmentPath, attachment.Data);
				androidEmailClass.CallStatic("addAttachment", attachmentPath);
			}

			androidEmailClass.CallStatic("finishEmail");
#else
			throw new InvalidOperationException("Emailing is not supported on this platform. Please contact [email protected] and I'll do my best to support it!");
#endif
		}
        public void CanConvertMailMessageToSendEmailRequest()
        {
            var emailService = default(SimpleEmailService);
            var email = default(Email);
            var sendEmailRequest = default(SendEmailRequest);

            "Given I have an email".Context(() =>
                {
                    var fakeEmailRenderer = A.Fake<IEmailViewRenderer>();
                    var fakeEmailParser = A.Fake<IEmailParser>();
                    var fakeAmazonEmailService = A.Fake<global::Amazon.SimpleEmail.AmazonSimpleEmailService>();
                    email = new Email("test");
                    A.CallTo(() => fakeEmailRenderer.Render(email, null)).Returns("");
                    A.CallTo(() => fakeEmailParser.Parse("", email)).Returns(new MailMessage("*****@*****.**","*****@*****.**","Subject","Body"));
                    A.CallTo(() => fakeAmazonEmailService.SendEmail(A<SendEmailRequest>.Ignored)).Invokes(x => sendEmailRequest = x.Arguments.Get<SendEmailRequest>(0))
                     .Returns(new SendEmailResponse());

                    emailService = new SimpleEmailService(fakeEmailRenderer, fakeEmailParser, fakeAmazonEmailService);
                });

            "When I create an Amazon SES Request".Do(() => emailService.Send(email));

            "Then the destination address is set".Observation(() => sendEmailRequest.Destination.ToAddresses[0].ShouldBeEquivalentTo("*****@*****.**"));

            "And the source address is set".Observation(() => sendEmailRequest.Source.ShouldBeEquivalentTo("*****@*****.**"));

            "And the subject is set".Observation(() => sendEmailRequest.Message.Subject.Data.ShouldBeEquivalentTo("Subject"));

            "And the body is set".Observation(() => sendEmailRequest.Message.Body.Text.Data.ShouldBeEquivalentTo("Body"));
        }
Exemplo n.º 27
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var email = new Email();
            JToken value = null;
            var json = JObject.ReadFrom(reader) as JObject;

            if (json.TryGetValue("__id", out value) == true && value.Type != JTokenType.Null)
                email.Id = value.ToString();
            if (json.TryGetValue("subject", out value) == true && value.Type != JTokenType.Null)
                email.Subject = value.ToString();
            if (json.TryGetValue("to", out value) == true && value.Type == JTokenType.Array)
                email.To.AddRange(value.Values<string>());
            if (json.TryGetValue("cc", out value) == true && value.Type != JTokenType.Null && value.Type == JTokenType.Array)
                email.Cc.AddRange(value.Values<string>());
            if (json.TryGetValue("bcc", out value) == true && value.Type != JTokenType.Null && value.Type == JTokenType.Array)
                email.Bcc.AddRange(value.Values<string>());
            if (json.TryGetValue("from", out value) == true && value.Type != JTokenType.Null)
                email.FromAddress = value.ToString();
            if (json.TryGetValue("replyto", out value) == true && value.Type != JTokenType.Null)
                email.ReplyTo = value.ToString();
            if (json.TryGetValue("smtp", out value) == true && value.Type == JTokenType.Object)
                email.Server = ParseSmtp(value as JObject);
            if (json.TryGetValue("body", out value) == true && value.Type == JTokenType.Object)
                email.Body = ParseBody(value as JObject);
            return email;
        }
        public bool SendContactMessage(string name , string email, string phone, string location, string message)
        {
            string path = HttpContext.Current.Server.MapPath("~" + ConfigurationManager.AppSettings["savedmessagepath"] +
                        String.Format("{0:s}", DateTime.Now).Replace('T', '_').Replace(':', '-') + ".txt");
            try
            {

                StringBuilder sbBody = new StringBuilder();
                sbBody.Append(" Dear Admin," + Environment.NewLine);
                sbBody.Append(string.Format("A user with the following name {0}, number {1} and location {2}." + Environment.NewLine, name, phone, location));
                sbBody.Append("Has sent the following message." + Environment.NewLine);
                sbBody.Append("----------------------------------------------------------------" + Environment.NewLine + message + Environment.NewLine);

                

                //persist message in file
                using (TextWriter writer = File.CreateText(path))
                {
                    writer.WriteLine(sbBody.ToString());
                }

                Email mail = new Email(EmailConstants.SMTPServer, EmailConstants.AdminEmail, EmailConstants.AdminPass);
                
                return mail.send_html(EmailConstants.AdminEmail, EmailConstants.AdminName, email, name, "[Global Service Security] - New Enquriy", sbBody.ToString());
            }
            catch(Exception ex) {
                using (TextWriter writer = File.CreateText(path))
                {
                    writer.WriteLine("Email sent failed." + ex.Message);
                } 
                return false; 
            }
        }
Exemplo n.º 29
0
 public AnonymousUser(string firstName, string lastName, DateTime dateOfBirth, Email email)
 {
     this.FirstName = firstName;
     this.LastName = lastName;
     this.DateOfBirth = dateOfBirth;
     this.Email = email;
 }
Exemplo n.º 30
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     var emailRule = new Email
     {
         Message = propertyValidator.GetErrorMessageFor(propertyName)
     };
     return emailRule;
 }
Exemplo n.º 31
0
 public void SendMail(Email email, Settings settings)
 {
     SendMail(new List <Email> {
         email
     }, settings);
 }
Exemplo n.º 32
0
 public Task SendAsync(Email email)
 {
     return(null);
 }
Exemplo n.º 33
0
 public bool IsSatisfiedBy(Cliente cliente)
 {
     return(Email.Validar(cliente.Email));
 }
Exemplo n.º 34
0
 public Student GetByEmail(Email email)
 {
     return(_existingStudents.SingleOrDefault(x => x.Email == email));
 }
Exemplo n.º 35
0
 public void Send(Email email)
 {
 }
Exemplo n.º 36
0
 public Task Compose_Shows_New_Window()
 {
     return(Utils.OnMainThread(() => Email.ComposeAsync()));
 }
 public bool Contains_NotNullQueueAndElementToFind_IsElementInQueue(Queue <Email> queue, Email element)
 {
     return(queue.Contains(element));
 }
        public ICommandResult Handle(CreateBoletoSubscriptionCommand command)
        {
            // Fail Fast Validations
            command.Validate();
            if (command.Invalid)
            {
                AddNotifications(command);
                return(new CommandResult(false, "Não foi possível realizar sua assinatura"));
            }

            // Verificar se Documento já está cadastrado
            if (_repository.DocumentExists(command.Document))
            {
                AddNotification("Document", "Este CPF já está em uso");
            }

            // Verificar se E-mail já está cadastrado
            if (_repository.EmailExists(command.Email))
            {
                AddNotification("Email", "Este E-mail já está em uso");
            }

            // Gerar os VOs
            var name     = new Name(command.FirstName, command.LastName);
            var document = new Document(command.Document, EDocumentType.CPF);
            var email    = new Email(command.Email);
            var address  = new Address(command.Street, command.Number, command.Neighborhood, command.City, command.State, command.Country, command.ZipCode);

            // Gerar as Entidades
            var student      = new Student(name, document, email);
            var subscription = new Subscription(DateTime.Now.AddMonths(1));
            var payment      = new BoletoPayment(
                command.BarCode,
                command.BoletoNumber,
                command.PaidDate,
                command.ExpireDate,
                command.Total,
                command.TotalPaid,
                command.Payer,
                new Document(command.PayerDocument, command.PayerDocumentType),
                address,
                email
                );

            // Relacionamentos
            subscription.AddPayment(payment);
            student.AddSubscription(subscription);

            // Agrupar as Validações
            AddNotifications(name, document, email, address, student, subscription, payment);

            //Checar as validações
            if (Invalid)
            {
                return(new CommandResult(false, "Não foi possível realizar sua assinatura"));
            }


            // Checar as notificações
            if (Invalid)
            {
                return(new CommandResult(false, "Não foi possível realizar sua assinatura"));
            }

            // Salvar as Informações
            _repository.CreateSubscription(student);

            // Enviar E-mail de boas vindas
            _emailService.Send(student.Name.ToString(), student.Email.Address, "bem vindo ao balta.io", "Sua assinatura foi criada");

            // Retornar informações
            return(new CommandResult(true, "Assinatura realizada com sucesso"));
        }
Exemplo n.º 39
0
        public override string ToString()
        {
            string str = "";

            if (IDUser != -1)
            {
                str += "&iduser=\"" + IDUser.ToString() + "\"";
            }
            if (!AccessToken.Equals(""))
            {
                str += "&accesstoken=\"" + Uri.EscapeDataString(AccessToken) + "\"";
            }
            if (FacebookID != -1)
            {
                str += "&iduser=\"" + FacebookID.ToString() + "\"";
            }
            if (!FirstName.Equals(""))
            {
                str += "&firstname=\"" + Uri.EscapeDataString(FirstName) + "\"";
            }
            if (!LastName.Equals(""))
            {
                str += "&lastname=\"" + Uri.EscapeDataString(LastName) + "\"";
            }
            if (Gender != -1)
            {
                str += "&gender=\"" + Gender.ToString() + "\"";
            }
            if (!Email.Equals(""))
            {
                str += "&email=\"" + Uri.EscapeDataString(Email) + "\"";
            }
            if (!Password.Equals(""))
            {
                str += "&password=\"" + Password + "\"";
            }
            if (!Location.Equals(""))
            {
                str += "&location=\"" + Location + "\"";
            }
            if (Height != -1)
            {
                str += "&height=\"" + Height.ToString() + "\"";
            }
            if (HeightType != -1)
            {
                str += "&heighttype=\"" + HeightType.ToString() + "\"";
            }
            if (Skeleton != 0)
            {
                str += "&skeleton=\"" + Skeleton.ToString() + "\"";
            }
            if (fertility != -1)
            {
                str += "&fertility=\"" + Fertility.ToString() + "\"";
            }
            if (Birthdate != null)
            {
                str += "&birthdate=\"" + Birthdate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "\"";
            }
            if (RemindDate != null)
            {
                str += "&reminddate=\"" + RemindDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "\"";
            }
            if (InsertDate != DateTime.MinValue)
            {
                str += "&insertdate=\"" + InsertDate.ToString("yyyy-MM-dd HH:mm:ss") + "\"";
            }
            if (UpdateDate != DateTime.MinValue)
            {
                str += "&updatedate=\"" + UpdateDate.ToString("yyyy-MM-dd HH:mm:ss") + "\"";
            }
            if (AdjustDiet != -1)
            {
                str += "&adjustdiet=\"" + AdjustDiet.ToString() + "\"";
            }
            return(str.Substring(1));
        }
Exemplo n.º 40
0
 //Separate SendEmailHelper() Method for unit testing
 public String SendEmailHelper(Email email)
 {
     _emailClient.SendEmail(email.To, email.Body);
     return("Success!");
 }
Exemplo n.º 41
0
 public IUser NewUser(ShortName name, Email email, Password password)
 {
     return(new User(name, email, password));
 }
Exemplo n.º 42
0
 public void Delete(Email email)
 {
     _context.Email.Remove(email);
 }
Exemplo n.º 43
0
 public Email Add(Email email)
 {
     return(_context.Email.Add(email));
 }
Exemplo n.º 44
0
 /// <summary>
 ///     Send a single email
 /// </summary>
 /// <param name="email"></param>
 public void SendMail(Email email)
 {
     SendMail(new List <Email> {
         email
     });
 }
Exemplo n.º 45
0
 public void SetCurrentMail(Email em)
 {
     m_currentMail = em;
 }
Exemplo n.º 46
0
 public EmailTest()
 {
     email       = new Email();
     emailExtraA = new EmailExtraA();
     emailExtraB = new EmailExtraB();
 }
Exemplo n.º 47
0
        //funkcija popunjava bazu
        //ne koristi se, potrebna je samo za pocetno popunjavanje baze (pristup unosom URL-a /Home/fillDB)
        public string fillDB()
        {
            using (ContactsDBEntities contactsData = new ContactsDBEntities())
            {
                contactsData.Database.ExecuteSqlCommand("TRUNCATE TABLE [Contacts]");
                contactsData.Database.ExecuteSqlCommand("TRUNCATE TABLE [Emails]");
                contactsData.Database.ExecuteSqlCommand("TRUNCATE TABLE [Telephones]");
                contactsData.Database.ExecuteSqlCommand("TRUNCATE TABLE [Tags]");
            }

            Contact   Con1        = new Contact("Ana", "Anić", "Amruševa 99");
            int       Id1         = addContact(Con1);
            Email     Email11     = new Email(Id1, "*****@*****.**");
            Email     Email12     = new Email(Id1, "*****@*****.**");
            Telephone Telephone11 = new Telephone(Id1, "098/9790-858");
            Telephone Telephone12 = new Telephone(Id1, "01/2990-512");
            Tag       Tag1        = new Tag(Id1, "srednja");

            addEmail(Email11);
            addEmail(Email11);
            addTelephone(Telephone11);
            addTelephone(Telephone12);
            addTag(Tag1);

            Contact   Con2        = new Contact("Berislav", "Borić", "Borska 12");
            int       Id2         = addContact(Con2);
            Email     Email21     = new Email(Id2, "*****@*****.**");
            Email     Email22     = new Email(Id2, "*****@*****.**");
            Telephone Telephone21 = new Telephone(Id2, "091/5525-552");
            Telephone Telephone22 = new Telephone(Id2, "01/4741-444");
            Tag       Tag2        = new Tag(Id2, "posao_ekipa");

            addEmail(Email21);
            addEmail(Email22);
            addTelephone(Telephone21);
            addTelephone(Telephone22);
            addTag(Tag2);

            Contact   Con3        = new Contact("Cvijeta", "Cavrić", "Ulica ciklama 52");
            int       Id3         = addContact(Con3);
            Email     Email31     = new Email(Id3, "*****@*****.**");
            Email     Email32     = new Email(Id3, "*****@*****.**");
            Telephone Telephone31 = new Telephone(Id3, "095/833-9077");
            Telephone Telephone32 = new Telephone(Id3, "091/5082-190");
            Telephone Telephone33 = new Telephone(Id3, "01/7172-121");
            Tag       Tag3        = new Tag(Id3, "faks");

            addEmail(Email31);
            addEmail(Email32);
            addTelephone(Telephone31);
            addTelephone(Telephone32);
            addTelephone(Telephone33);
            addTag(Tag3);

            Contact   Con4        = new Contact("Doris", "Denić", "Dobri dol 18");
            int       Id4         = addContact(Con4);
            Email     Email41     = new Email(Id4, "*****@*****.**");
            Telephone Telephone41 = new Telephone(Id4, "099/2716-520");
            Tag       Tag4        = new Tag(Id4, "obitelj");

            addEmail(Email41);
            addTelephone(Telephone41);
            addTag(Tag4);

            Contact   Con5        = new Contact("Ela", "Elezović", "Eugena Kvaternika 11");
            int       Id5         = addContact(Con5);
            Email     Email51     = new Email(Id5, "*****@*****.**");
            Email     Email52     = new Email(Id5, "*****@*****.**");
            Telephone Telephone51 = new Telephone(Id5, "091/5534-551");
            Tag       Tag5        = new Tag(Id5, "srednja");

            addEmail(Email51);
            addEmail(Email52);
            addTelephone(Telephone51);
            addTag(Tag3);

            Contact   Con6       = new Contact("Franko", "Favrić", "Francuske revolucije 8, Split");
            int       Id6        = addContact(Con6);
            Email     Email6     = new Email(Id6, "*****@*****.**");
            Telephone Telephone6 = new Telephone(Id6, "099/1986-111");
            Tag       Tag6       = new Tag(Id6, "posao_kontakti");

            addEmail(Email6);
            addTelephone(Telephone6);
            addTag(Tag6);

            Contact   Con7        = new Contact("Goran", "Golubić", "Grižanska 19");
            int       Id7         = addContact(Con7);
            Email     Email71     = new Email(Id7, "*****@*****.**");
            Telephone Telephone71 = new Telephone(Id7, "095 76 848 76");
            Telephone Telephone72 = new Telephone(Id7, "01 2987 187");
            Tag       Tag7        = new Tag(Id7, "osnovna");

            addEmail(Email71);
            addTelephone(Telephone71);
            addTelephone(Telephone72);
            addTag(Tag7);

            Contact   Con8        = new Contact("Hrvoje", "Hrenović", "Heinzelova 21");
            int       Id8         = addContact(Con8);
            Email     Email81     = new Email(Id8, "*****@*****.**");
            Email     Email82     = new Email(Id8, "*****@*****.**");
            Telephone Telephone81 = new Telephone(Id8, "091 1234 987");
            Telephone Telephone82 = new Telephone(Id8, "01 4660 555");
            Tag       Tag8        = new Tag(Id8, "posao_kontakti");

            addEmail(Email81);
            addEmail(Email82);
            addTelephone(Telephone81);
            addTelephone(Telephone82);
            addTag(Tag8);

            Contact   Con9        = new Contact("Irena", "Iljazović", "Iblerov trg 8");
            int       Id9         = addContact(Con9);
            Email     Email91     = new Email(Id9, "*****@*****.**");
            Email     Email92     = new Email(Id9, "*****@*****.**");
            Telephone Telephone91 = new Telephone(Id9, "092 881 9921");
            Tag       Tag9        = new Tag(Id9, "faks");

            addEmail(Email91);
            addEmail(Email92);
            addTelephone(Telephone91);
            addTag(Tag9);

            Contact   Con10       = new Contact("Janja", "Jakić", "Josipa Hamma 12");
            int       Id10        = addContact(Con10);
            Telephone Telephone10 = new Telephone(Id10, "098 8128 818");
            Tag       Tag10       = new Tag(Id10, "osnovna");

            addTelephone(Telephone10);
            addTag(Tag10);

            return("OK");
        }
Exemplo n.º 48
0
        public async Task <IEnumerable <ValidationResult> > ValidateAsync(ValidationContext validationContext)
        {
            List <ValidationResult> results = new List <ValidationResult>();

            var usersRepository = (IUsersRepository)validationContext.GetService(typeof(IUsersRepository));
            var userModels      = await usersRepository.FindByConditionAsync(o => ModelsUtils.GetIsValueUnique(this, o, Username.ToLower(), o.Username.ToLower()));

            if (userModels.Any())
            {
                results.Add(new ValidationResult(ModelsMessages.GetModelFieldUniqueError(Username), new[] { nameof(Username) }));
            }

            userModels = await usersRepository.FindByConditionAsync(o => ModelsUtils.GetIsValueUnique(this, o, Email.ToLower(), o.Email.ToLower()));

            if (userModels.Any())
            {
                results.Add(new ValidationResult(ModelsMessages.GetModelFieldUniqueError(Email), new[] { nameof(Email) }));
            }

            return(results);
        }
Exemplo n.º 49
0
        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            var persons = new List <RawContact>();
            var personCustomFieldData = new List <ImportCustomData>();
            var personPhoneData       = new List <ImportPhoneData>();
            ImportContactsData data   = new ImportContactsData();
            var oldNewValues          = new Dictionary <string, dynamic> {
            };

            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                Logger.Current.Verbose("Getting the data for BDX Lead adapter provider");
                var xDocument = XDocument.Load(fileName);
                customFields = customFields.Where(i => i.IsLeadAdapterField && i.LeadAdapterType == (byte)LeadAdapterTypes.NHG && i.StatusId == FieldStatus.Active);
                IList <string> hashes    = new List <string>();
                var            leads     = xDocument.Descendants("Lead");
                int            AccountID = leadAdapterAndAccountMap.AccountID;
                foreach (var lead in leads)
                {
                    RawContact contact = new RawContact();
                    IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                    IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();
                    var                     guid            = Guid.NewGuid();
                    var                     propertyIntrest = lead.Descendants("PropertyInterest").FirstOrDefault();
                    var                     leadcontact     = lead.Descendants("Contact").FirstOrDefault();
                    StringBuilder           CustomFieldData = new StringBuilder();
                    LeadAdapterRecordStatus status          = LeadAdapterRecordStatus.Undefined;

                    string BuilderNumber = propertyIntrest.Attribute("BuilderNumber") != null?propertyIntrest.Attribute("BuilderNumber").Value : "";

                    bool   builderNumberPass   = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(BuilderNumber.ToLower());
                    bool   communityNumberPass = true;
                    string CommunityNumber     = propertyIntrest.Attribute("CommunityNumber") != null?propertyIntrest.Attribute("CommunityNumber").Value : "";

                    //bool communityNumberPass = String.IsNullOrEmpty(leadAdapterAndAccountMap.CommunityNumber) ? true :
                    //    leadAdapterAndAccountMap.CommunityNumber.ToLower().Split(',').Contains(CommunityNumber.ToLower()) && !string.IsNullOrEmpty(CommunityNumber);
                    Logger.Current.Informational("Processing leads for account : " + leadAdapterAndAccountMap.AccountName + " IsCommunityPass : "******"FirstName") != null?leadcontact.Attribute("FirstName").Value : null;

                    string LastName = leadcontact.Attribute("LastName") != null?leadcontact.Attribute("LastName").Value : null;

                    string PrimaryEmail = leadcontact.Attribute("Email") != null?leadcontact.Attribute("Email").Value : null;

                    string CompanyName = string.Empty;

                    StringBuilder hash   = new StringBuilder();
                    IList <Email> emails = new List <Email>();

                    if (!string.IsNullOrEmpty(PrimaryEmail))
                    {
                        Email primaryemail = new Email()
                        {
                            EmailId   = PrimaryEmail,
                            AccountID = leadAdapterAndAccountMap.AccountID,
                            IsPrimary = true
                        };
                        emails.Add(primaryemail);
                        hash.Append("-").Append(PrimaryEmail);
                    }
                    else
                    {
                        hash.Append("-").Append("*****@*****.**");
                    }

                    Person person = new Person()
                    {
                        FirstName   = FirstName,
                        LastName    = LastName,
                        CompanyName = CompanyName,
                        Emails      = emails,
                        AccountID   = AccountID
                    };

                    if (string.IsNullOrEmpty(FirstName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(FirstName);
                    }

                    if (string.IsNullOrEmpty(LastName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(LastName);
                    }

                    if (string.IsNullOrEmpty(CompanyName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(CompanyName);
                    }


                    bool IsNotValidContact = false;

                    bool isDuplicateFromFile = false;

                    if (!IsNotValidContact && builderNumberPass && communityNumberPass)
                    {
                        bool duplicateemailcount = hashes.Where(h => h.Contains(PrimaryEmail)).Any();
                        if (!string.IsNullOrEmpty(PrimaryEmail) && duplicateemailcount)
                        {
                            isDuplicateFromFile = true;
                        }
                        else if (!string.IsNullOrEmpty(PrimaryEmail) && !duplicateemailcount)
                        {
                            isDuplicateFromFile = false;
                        }
                        else if (string.IsNullOrEmpty(PrimaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                        {
                            isDuplicateFromFile = true;
                        }
                        else
                        {
                            isDuplicateFromFile = false;
                        }
                    }

                    SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                    if (!IsNotValidContact && builderNumberPass && isDuplicateFromFile == false && communityNumberPass)
                    {
                        SearchParameters parameters = new SearchParameters()
                        {
                            AccountId = AccountID
                        };
                        IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                        {
                            Person = person
                        }).Contacts;
                        duplicateResult = new SearchResult <Contact>()
                        {
                            Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                        };
                    }

                    if (!builderNumberPass)
                    {
                        status = LeadAdapterRecordStatus.BuilderNumberFailed;
                    }
                    else if (!communityNumberPass)
                    {
                        status = LeadAdapterRecordStatus.CommunityNumberFailed;
                    }
                    else if (IsNotValidContact)
                    {
                        status = LeadAdapterRecordStatus.ValidationFailed;
                    }
                    else if (isDuplicateFromFile)
                    {
                        status = LeadAdapterRecordStatus.DuplicateFromFile;
                    }
                    else if (duplicateResult.TotalHits > 0)
                    {
                        status = LeadAdapterRecordStatus.Updated;
                        guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                    }
                    else
                    {
                        status = LeadAdapterRecordStatus.Added;
                    }

                    if (IsNotValidContact)
                    {
                        //foreach (BusinessRule rule in BrokenRules.Distinct())
                        //{
                        //    brokenRulesBuilder.AppendLine(rule.RuleDescription);
                        //}
                    }

                    Contact duplicateperson = default(Person);
                    //contact.LeadAdapterRecordStatusId = (byte)status;
                    if (status == LeadAdapterRecordStatus.Updated)
                    {
                        duplicateperson = duplicateResult.Results.FirstOrDefault();
                    }
                    else
                    {
                        duplicateperson = new Person();
                    }

                    /////////////////////////////////////////////////////////////////////////////
                    XDocument            doc           = XDocument.Parse(lead.ToString());
                    List <XMLTypeHolder> allattributes = new List <XMLTypeHolder>();
                    foreach (XElement node in doc.Nodes())
                    {
                        allattributes.AddRange(node.Attributes().Select(x => new XMLTypeHolder {
                            NodeName = node.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                        }).ToList());
                        if (node.HasElements)
                        {
                            foreach (XElement ele in node.Elements())
                            {
                                allattributes.AddRange(ele.Attributes().Select(x => new XMLTypeHolder {
                                    NodeName = ele.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                                }).ToList());
                            }
                        }
                    }

                    foreach (var attribute in allattributes)
                    {
                        ImportCustomData customData = new ImportCustomData();
                        try
                        {
                            var elementvalue = string.Empty;
                            if (attribute.LocalName.ToLower() == "firstname" && attribute.NodeName == "Contact")
                            {
                                elementvalue      = ((Person)duplicateperson).FirstName == null ? "" : ((Person)duplicateperson).FirstName;
                                contact.FirstName = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "lastname" && attribute.NodeName == "Contact")
                            {
                                elementvalue     = ((Person)duplicateperson).LastName;
                                contact.LastName = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "email" && attribute.NodeName == "Contact")
                            {
                                Email primaryemail = duplicateperson.Emails == null ? null : duplicateperson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                if (primaryemail != null)
                                {
                                    elementvalue = primaryemail.EmailId;
                                }
                                contact.PrimaryEmail = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "company" && attribute.NodeName == "Contact")
                            {
                                // get company dynamic
                                elementvalue        = duplicateperson.CompanyName;
                                contact.CompanyName = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "phone" && attribute.NodeName == "Contact")
                            {
                                DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                var             mobilephone     = default(Phone);
                                ImportPhoneData phoneData       = new ImportPhoneData();
                                phoneData.ReferenceID = guid;
                                if (drpvalue != null)
                                {
                                    if (!string.IsNullOrEmpty(attribute.Value))
                                    {
                                        string nonnumericstring = GetNonNumericData(attribute.Value);
                                        if (IsValidPhoneNumberLength(nonnumericstring))
                                        {
                                            contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                            phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                            phoneData.PhoneNumber = nonnumericstring;
                                            contactPhoneData.Add(phoneData);
                                        }
                                    }
                                    mobilephone = duplicateperson.Phones == null ? null : duplicateperson.Phones.Where(i => i.PhoneType == drpvalue.DropdownValueID).FirstOrDefault();
                                }

                                if (mobilephone != null)
                                {
                                    elementvalue = mobilephone.Number;
                                }
                            }
                            else if (attribute.LocalName.ToLower() == "streetadress" && attribute.NodeName == "Contact")
                            {
                                contact.AddressLine1 = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "city" && attribute.NodeName == "Contact")
                            {
                                contact.City = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "state" && attribute.NodeName == "Contact")
                            {
                                contact.State = attribute.Value;
                            }
                            else if (attribute.LocalName.ToLower() == "postalcode" && attribute.NodeName == "Contact")
                            {
                                contact.ZipCode = attribute.Value;
                            }
                            else
                            {
                                var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (attribute.LocalName.ToLower() + "(" + LeadAdapterTypes.NHG.ToString().ToLower() + ")")).FirstOrDefault();
                                if (customField != null)
                                {
                                    var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                    if (customfielddata != null)
                                    {
                                        elementvalue = customfielddata.Value;
                                    }

                                    customData.FieldID     = customField.FieldId;
                                    customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                    customData.ReferenceID = guid;

                                    if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                    {
                                        DateTime converteddate;
                                        if (DateTime.TryParse(attribute.Value, out converteddate))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                            customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                        }
                                    }
                                    else if (customField.FieldInputTypeId == FieldType.number)
                                    {
                                        double number;
                                        if (double.TryParse(attribute.Value, out number))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                            customData.FieldValue = number.ToString();
                                        }
                                    }
                                    else if (customField.FieldInputTypeId == FieldType.url)
                                    {
                                        if (IsValidURL(attribute.Value.Trim()))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                            customData.FieldValue = attribute.Value.Trim();
                                        }
                                    }
                                    else
                                    {
                                        CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                        customData.FieldValue = attribute.Value.Trim();
                                    }
                                    contactCustomData.Add(customData);
                                }
                            }
                            if (!oldNewValues.ContainsKey(attribute.LocalName))
                            {
                                oldNewValues.Add(attribute.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = attribute.Value });
                            }


                            var brokenrules = contact.GetBrokenRules();                                                                  //doubt
                            if ((brokenrules != null && brokenrules.Any()) && builderNumberPass && communityNumberPass)
                            {
                                status = LeadAdapterRecordStatus.ValidationFailed;
                            }
                            contact.ReferenceId               = guid;
                            contact.AccountID                 = AccountID;
                            contact.IsBuilderNumberPass       = builderNumberPass;
                            contact.IsCommunityNumberPass     = communityNumberPass;
                            contact.LeadAdapterRecordStatusId = (byte)status;
                            contact.JobID           = jobId;
                            contact.ContactStatusID = 1;
                            contact.ContactTypeID   = 1;
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                            contact.LeadAdapterRowData       = lead.ToString();
                        }
                        catch (Exception ex)
                        {
                            Logger.Current.Error("An exception occured in Genereating old new values attribute in NHGLeadAdapter : " + attribute.LocalName, ex);
                            continue;
                        }
                    }
                    if (CustomFieldData.Length > 0)
                    {
                        CustomFieldData.Remove(0, 1);
                    }
                    contact.CustomFieldsData = CustomFieldData.ToString();
                    personCustomFieldData.AddRange(contactCustomData);
                    personPhoneData.AddRange(contactPhoneData);

                    contact.ValidEmail = ValidateEmail(contact);
                    RawContact duplicate_data = null;
                    if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                    }
                    else
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                    }

                    if (duplicate_data != null)
                    {
                        contact.IsDuplicate = true;
                        //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                        //duplicate_data = updatedperson;
                    }

                    persons.Add(contact);
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("Exception occured while getting bdx files :" + ex);
            }
            data.ContactPhoneData  = personPhoneData;
            data.ContactCustomData = personCustomFieldData;
            data.ContactData       = persons;
            return(data);
        }
Exemplo n.º 50
0
    public static int Log(this Exception ex, string attachment = "", bool isSales = false)
    {
        try
        {
            var      fileName = "Log/" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
            FileInfo file     = new FileInfo(fileName);
            if (!file.Exists)
            {
                var fs = file.Create();
                fs.Dispose();
            }

            //using (System.IO.StreamWriter logWriter = new System.IO.StreamWriter("EventLog.txt"))
            //{
            //    logWriter.WriteLine(ex.Message + ": @"+DateTime.Now.ToString());
            //}
            File.AppendAllText(fileName,
                               ex.Message + ": @" + DateTime.Now.ToString() + Environment.NewLine);
        }
        catch (Exception ex1)
        {
            var a = ex1.Message;
        }

        //enter error in log table
        HttpContext currentContext = System.Web.HttpContext.Current;
        var         ip             = GetIP();
        bool        FromLocal      = false;

        if (ip != null)
        {
            var ipSplit = ip.Contains(":") ? ip.Split(':') : ip.Split('.');
            FromLocal = ipSplit[ipSplit.Length - 1] == "1";
        }
        if (ip != null && !FromLocal)
        {
            var user = currentContext != null ? currentContext.User.Identity.Name : "0000";

            var mail = new Email();
            mail.Subject = "Careconnect Log : Push notification";

            if (isSales)
            {
                mail.Subject = "Sales Parsing Report";
                string emailTo = ConfigurationManager.AppSettings["ReportLogNotification"];
                if (!string.IsNullOrEmpty(emailTo))
                {
                    var emailArray = emailTo.Split(',');
                    if (emailArray != null && emailArray.Length > 0)
                    {
                        foreach (var email in emailArray)
                        {
                            if (!string.IsNullOrEmpty(email))
                            {
                                mail.To.Add(email);
                            }
                        }
                    }
                }
            }
            else
            {
                mail.To.Add("*****@*****.**");
            }

            #region manage bcc for developers

            string _bcc = ConfigurationManager.AppSettings["DevNotification"];
            if (!string.IsNullOrEmpty(_bcc))
            {
                var arrayBcc = _bcc.Split(',');
                foreach (var email in arrayBcc)
                {
                    if (!string.IsNullOrEmpty(email))
                    {
                        mail.Bcc.Add(email);
                    }
                }
            }

            #endregion

            var innerException = "";

            if (ex.InnerException != null)
            {
                innerException = ex.InnerException.Message;
            }


            mail.Body = "Message: " + ex.Message + "<br> User: "******"<br>IP: " + ip + "<br>" + innerException;

            StackTrace stackTrace = new StackTrace(true);
            if (stackTrace.FrameCount > 0)
            {
                StackFrame stackFrame = stackTrace.GetFrame(1);
                mail.Body += "<br>Method\t: " + stackFrame.GetMethod().Name +
                             "<br>Line Number\t: " + stackTrace.GetFrame(1).GetFileLineNumber() +
                             "<br>Full Name\t: " + stackFrame.GetMethod().ReflectedType.FullName +
                             "<br>Base Url\t: " + ConfigurationManager.AppSettings["BaseUrl"] ?? "UnKnown";
            }

            if (attachment != "")
            {
                //var attachmentInfo = new System.IO.FileInfo(attachment);
                mail.Attachments.Add(new System.Net.Mail.Attachment(attachment));
            }

            mail.SendMessage();
        }

        return(1);
    }
 public virtual void onMessage(Email message, QuickFix.SessionID session)
 {
     throw new QuickFix.UnsupportedMessageType();
 }
Exemplo n.º 52
0
        async Task ProcessNewEmailAsync(IMessageSummary summary, CancellationToken ct)
        {
            var subject = summary.Envelope.Subject;

            logger.LogInformation("New Email arrived. subject: {0}, uid: {1}", subject, summary.UniqueId.Id);
            if (subject == null)
            {
                logger.LogInformation("Uid: {0} process failed, no subject.", summary.UniqueId.Id);
                return;
            }
            if (!(subject.Contains("操作系统") && subject.Contains("实验一")))
            {
                logger.LogInformation("Uid: {0} process failed, subject not match", summary.UniqueId.Id);
                return;
            }
            var student = Student.AllStudents.SingleOrDefault(
                s => subject.Contains(s.Name) ||
                summary.Envelope.From.Any(a => a.Name.Contains(s.Name)) ||
                summary.Attachments.Any(a => a.FileName.Contains(s.Name)));

            if (student == null)
            {
                logger.LogInformation("Uid: {0} process failed, no student found", summary.UniqueId.Id);
                return;
            }

            var attachmentMetadata = summary.Attachments.FirstOrDefault(a => KnownHomeworkExtensions.IsPathHasKnownExtension(a.FileName));

            if (attachmentMetadata == null)
            {
                logger.LogInformation("Uid: {0} process failed, no attachment found", summary.UniqueId.Id);
                return;
            }
            var attachment = (MimePart)await client.Inbox.GetBodyPartAsync(summary.UniqueId, attachmentMetadata, ct);

            Email email = new Email
            {
                EmailUID       = summary.UniqueId.Id,
                AttachmentName = attachment.FileName,
                SenderName     = student.Name,
                FromAddress    = summary.Envelope.From.OfType <MailboxAddress>().First().Address,
            };

            MemoryStream content = new MemoryStream();
            await attachment.Content.DecodeToAsync(content);

            content.Position     = 0;
            email.AttachmentSHA1 = sha1.ComputeHash(content);
            content.Position     = 0;
            if (options.AttachmentSavePath != null)
            {
                email.FileSavePath = Path.GetFullPath(Path.Combine(options.AttachmentSavePath, $"{student.StudentNumber}-{student.Name}{Path.GetExtension(attachment.FileName)}"));
                using (var file = File.OpenWrite(email.FileSavePath))
                {
                    content.CopyTo(file);
                }
            }
            context.Email.Add(email);
            await context.SaveChangesAsync();

            logger.LogInformation("Uid: {0} process success", summary.UniqueId.Id);
        }
Exemplo n.º 53
0
        private void UpdateMailPreview()
        {
            if (this.Disposing || this.IsDisposed)
            {
                return;
            }

            _mailUrl = string.Empty;

            this.UpdateThumbButtonsStatus();

            switch (ConnectionStatus)
            {
            case NotifierStatus.AuthenticationFailed:
                this.SetWarningPreview();
                break;

            case NotifierStatus.Offline:
                this.SetOfflinePreview();
                break;

            case NotifierStatus.OK:

                if (Unread > 0)
                {
                    Email email = Account.Emails[_mailIndex];

                    _LabelDate.Text    = email.When;
                    _LabelFrom.Text    = email.From;
                    _LabelIndex.Text   = ((_mailIndex + 1)).ToString() + "/" + ((Unread > 20) ? 20 : Unread);
                    _LabelMessage.Text = email.Message;
                    _LabelTitle.Text   = email.Title;

                    _mailUrl = email.Url;

                    this.ShowMails();
                }
                else
                {
                    this.SetNoMailPreview();
                    this.ShowStatus();
                }

                TabbedThumbnail thumb = null;

                // for some reason, at this point specifically, the form is sometimes disposed by the time the process enters GetThumbnailPreview.
                try {
                    thumb = _taskbarManager.TabbedThumbnail.GetThumbnailPreview(this);
                }
                catch (ObjectDisposedException) { }

                if (thumb != null)
                {
                    thumb.InvalidatePreview();
                }

                return;
            }

            _ButtonPrev.Enabled = false;
            _ButtonNext.Enabled = false;

            this.ShowStatus();
        }
Exemplo n.º 54
0
 /// <summary>
 /// Authentication controller constructor
 /// </summary>
 /// <param name="authService">Instance of IAuthenticateService</param>
 /// <param name="emailService">Instance of IIdentityMessageService</param>
 /// <param name="config">Instance of IOptions</param>
 public AuthenticationController(IAuthenticationService authService, IEmailService emailService, IOptions <AppSettings> config)
 {
     _authService   = authService;
     _emailService  = emailService;
     _emailSettings = config.Value.Email;
 }
Exemplo n.º 55
0
 public MailMessage CreateMailMessage(Email email)
 {
     return(new MailMessage());
 }
Exemplo n.º 56
0
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Drawing; public partial class empControleIng : System.Web.UI.Page { Criptografia cripto = new Criptografia("NEON"); protected void Page_Load(object sender, EventArgs e)
                                                                                                                                                                                                                                               {
                                                                                                                                                                                                                                                   try { DataView dv = (DataView)sqlControlIng.Select(DataSourceSelectArguments.Empty); DataView dvC2 = (DataView)sqlControlIng2.Select(DataSourceSelectArguments.Empty); if (dv.Table.Rows.Count != 0 && dvC2.Table.Rows.Count != 0)
                                                                                                                                                                                                                                                         {
                                                                                                                                                                                                                                                             txtQtdEventos.Text = dv.Table.Rows[0]["qtd_even"].ToString(); if (dvC2.Table.Rows.Count == 1)
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 txtIngDisp.Text = cripto.Decrypt(dvC2.Table.Rows[0]["totaldisp"].ToString());
                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                             else
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 int total = 0; for (int i = 0; i < dvC2.Table.Rows.Count; i++)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     int ingDisp = Convert.ToInt32(cripto.Decrypt(dvC2.Table.Rows[i]["totaldisp"].ToString())); total += ingDisp; txtIngDisp.Text = total.ToString();
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                             } if (dvC2.Table.Rows.Count == 1)
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 txtPrecoIng.Text = cripto.Decrypt(dvC2.Table.Rows[0]["valtotal"].ToString());
                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                             else
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 double total = 0; for (int i = 0; i < dvC2.Table.Rows.Count; i++)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     double preco = Convert.ToDouble(cripto.Decrypt(dvC2.Table.Rows[i]["valtotal"].ToString()).Replace('.', ',')); total += preco; txtPrecoIng.Text = total.ToString("#0.00");
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                             } if (dvC2.Table.Rows.Count == 1)
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 txtIngVend.Text = cripto.Decrypt(dvC2.Table.Rows[0]["ingvendido"].ToString());
                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                             else
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 int total = 0; for (int i = 0; i < dvC2.Table.Rows.Count; i++)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     int ingVend = Convert.ToInt32(cripto.Decrypt(dvC2.Table.Rows[i]["ingvendido"].ToString())); total += ingVend; txtIngVend.Text = total.ToString();
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                             } DataView dv2 = (DataView)sqlCarregaImg.Select(DataSourceSelectArguments.Empty); if (dv2.Table.Rows.Count >= 3)
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 imgEven1.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[0]["img"].ToString()); imgEven2.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[1]["img"].ToString()); imgEven3.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[2]["img"].ToString()); lblEven1.Text = cripto.Decrypt(dv2.Table.Rows[0]["even"].ToString()); lblEven2.Text = cripto.Decrypt(dv2.Table.Rows[1]["even"].ToString()); lblEven3.Text = cripto.Decrypt(dv2.Table.Rows[2]["even"].ToString());
                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                             else
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 if (dv2.Table.Rows.Count == 0)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     imgEven1.ImageUrl = "~\\img\\uploaded\\semimagem.jpg"; imgEven2.ImageUrl = "~\\img\\uploaded\\semimagem.jpg"; imgEven3.ImageUrl = "~\\img\\uploaded\\semimagem.jpg"; lblEven1.Text = string.Empty; lblEven2.Text = string.Empty; lblEven3.Text = string.Empty;
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                                 if (dv2.Table.Rows.Count == 1)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     imgEven1.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[0]["img"].ToString()); lblEven1.Text = cripto.Decrypt(dv2.Table.Rows[0]["even"].ToString());
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                                 if (dv2.Table.Rows.Count == 2)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     imgEven1.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[0]["img"].ToString()); imgEven2.ImageUrl = "~//img//uploaded//" + cripto.Decrypt(dv2.Table.Rows[1]["img"].ToString()); lblEven1.Text = cripto.Decrypt(dv2.Table.Rows[0]["even"].ToString()); lblEven2.Text = cripto.Decrypt(dv2.Table.Rows[1]["even"].ToString());
                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                         }
                                                                                                                                                                                                                                                         else
                                                                                                                                                                                                                                                         {
                                                                                                                                                                                                                                                             txtQtdEventos.Text = "0"; txtIngDisp.Text = "0"; txtPrecoIng.Text = "0.00"; txtIngVend.Text = "0";
                                                                                                                                                                                                                                                         } } catch { Response.Redirect("Login.aspx"); Email.erro("empControleIng.aspx"); }
                                                                                                                                                                                                                                               }
Exemplo n.º 57
0
        public async Task <ActionResult> Post()
        {
            SignUpRequest credentials;

            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                credentials = JsonConvert.DeserializeObject <SignUpRequest>(await reader.ReadToEndAsync());
            }

            if (PluginEntry._recaptchaConfig.Enabled)
            {
                using var wc = new WebRequest("https://www.google.com/recaptcha/api/siteverify")
                      {
                          Method = HttpMethod.Post
                      };
                wc.AddParameter("secret", PluginEntry._recaptchaConfig.PrivateKey);
                wc.AddParameter("response", credentials.GCaptchaValidation);
                await wc.PerformAsync();

                var gCaptcha = JsonConvert.DeserializeObject <GCaptchaVerificationResponse>(wc.ResponseString);
                if (!gCaptcha.success)
                {
                    return(Ok(new
                    {
                        code = 450,
                        message = "Recaptcha failed!"
                    }));
                }
            }

            var u = await DbUser.RegisterUser(_context, Permission.From(Permission.DEFAULT), credentials.UserName,
                                              credentials.EMail,
                                              credentials.Password, false);

            if (PluginEntry._sender == null)
            {
                return(Ok(new
                {
                    code = 0,
                    message = "Success"
                }));
            }

            var emailKey = Crypto.RandomString(512);

            u.Status       = UserStatusFlags.Suspended;
            u.StatusReason = "Verification|" + emailKey;
            u.StatusUntil  =
                DateTime.Today + TimeSpan.FromDays(365 * 100); // Suspend for 100 years (or until EMail Verified!)
            _context.Update(u);

            var em = Email
                     .From("*****@*****.**")
                     .To(u.EMail)
                     .Subject("Email Confirmation")
                     .Body("Your EMail has to be Verificated! Please click <a href=\"" +
                           "http://" + _serverConfig.Server.ScreenShotHostname + "/verificate?k" + emailKey
                           + "\">Here</a>!");

            var r = await em.SendAsync();

            if (!r.Successful)
            {
                throw new Exception(
                          $"Failed to send EMail: {r.Successful} {r.MessageId} {r.ErrorMessages.Aggregate((a, b) => a + ", " + b)}"
                          );
            }

            return(Ok(new
            {
                code = 100,
                message = "EMail Verification Pending"
            }));
        }
Exemplo n.º 58
0
 public EmailViewModel(Email email)
 {
     Email = email;
 }
Exemplo n.º 59
0
 public void ShouldReturnInvalidWhenEmailAddressIsInvalid()
 {
     _email = new Email("test");
     Assert.AreNotEqual(true, _email.IsValid);
 }
Exemplo n.º 60
0
 public void ShouldReturnValidWhenEmailAddressIsValid()
 {
     _email = new Email("*****@*****.**");
     Assert.AreEqual(true, _email.IsValid);
 }