public void AddEmail(EmailDTO dto) { var entity = dto.ToEntity(); DbProvider.Add(entity); DbProvider.SaveChanges(); new MailSendService().PromoteMailQueueSend(); //初始化队列 }
public IList<EmailDTO> GetMailToSend(int SendRegisterID,int SendContentID, int ConfigID) { List<EmailDTO> listEmail = new List<EmailDTO>(); EmailDTO eDTO = new EmailDTO(); string Subject=""; string Body=""; string EmailFrom=""; string HostName=""; string UserNameSMTP=""; string PasswordSMTP=""; int Port=0; string NameSender=""; bool SSL=false; //Lấy thông tin cấu hình mail gửi DataTable tableConfig = mcBUS.GetByID(ConfigID); if (tableConfig.Rows.Count > 0) { HostName = tableConfig.Rows[0]["Server"].ToString(); EmailFrom = tableConfig.Rows[0]["Email"].ToString(); UserNameSMTP = tableConfig.Rows[0]["username"].ToString(); PasswordSMTP = tableConfig.Rows[0]["Password"].ToString(); Port = int.Parse(tableConfig.Rows[0]["Port"].ToString()); NameSender = tableConfig.Rows[0]["Name"].ToString(); SSL = bool.Parse(tableConfig.Rows[0]["isSSL"].ToString()); } // Lấy nội dung mail DataTable tableContent = scBUS.GetByID(SendContentID); if (tableContent.Rows.Count > 0) { Subject = tableContent.Rows[0]["Subject"].ToString(); Body = tableContent.Rows[0]["Body"].ToString(); } //Lấy nội dung để gửi DataTable table = srdBUS.GetByStatus(false,SendRegisterID); if (table.Rows.Count > 0) { foreach (DataRow rowEmail in table.Rows) { //Thông tin mail gửi eDTO.HostName = HostName; eDTO.MailFrom = EmailFrom; eDTO.UsernameSMTP = UserNameSMTP; eDTO.PasswordSMTP = PasswordSMTP; eDTO.Port = Port; eDTO.SSL = SSL; //Thông tin nội dung string eSubject = Subject.Replace("[khachhang]", rowEmail["CustomerName"].ToString()); string eBody = Body.Replace("[khachhang]", rowEmail["CustomerName"].ToString()); eBody += String.Format("<IMG height=1 src=\"http://EMAILMARKETING.1ONLINEBUSINESSSYSTEM.COM/emailtrack.aspx?emailsentID={0}\" width=1>", rowEmail["SendRegisterDetailId"]); eDTO.Subject = eSubject; eDTO.Content = eBody; eDTO.SendID = int.Parse(rowEmail["SendRegisterDetailId"].ToString()); listEmail.Add(eDTO); } } return listEmail; }
private string ParseSingleTemplate(string template, EmailDTO emailDto) { var dtoStringProperties = emailDto .GetType() .GetProperties() .Where(p => p.PropertyType == typeof(string)); foreach (var singleProperty in dtoStringProperties) { string propertyValue = (string) singleProperty.GetValue(emailDto); template = template.Replace("{{" + singleProperty.Name + "}}", propertyValue); } return template; }
public void UpdateEmail(EmailDTO dto) { var entity = dto.ToEntity(); var data = DbProvider.D<PromoteMsg>().FirstOrDefault(o=>o.InnerMsgType ==(int)MsgType.Email && o.ID == dto.Id); if(data == null) { throw new Exception("你所编辑的邮件不存在!请重新选择"); } data.SmsType = entity.SmsType; data.IsHtml = entity.IsHtml; data.SendTime = entity.SendTime; data.Title = entity.Title; data.Content = entity.Content; data.DealId = entity.DealId; data.SendType = entity.SendType; data.SendTypeId = entity.SendTypeId; data.SendDefineData = entity.SendDefineData; DbProvider.Update(data); DbProvider.SaveChanges(); //OnEmailUpdated; }
public UserDataModel GetUser(UserDTO userDTO) { UserDataModel userDataModel = null; if (userDTO != null) { UserAddressDTO userAddressDTO = (userDTO.UserAddresses != null) ? userDTO.UserAddresses.Where(o => o.IsPrimary).FirstOrDefault() : null; AddressDTO oPrimaryAddressDTO = (userAddressDTO != null) ? userAddressDTO.Address : null; UserAccountDTO userAccountDTO = (userDTO.UserAddresses != null) ? userDTO.UserAccounts.FirstOrDefault(o => o.IsActive == true) : null; UserPhoneDTO userPhoneDTO = (userDTO.UserPhones != null) ? userDTO.UserPhones.Where(o => o.IsPrimary).FirstOrDefault() : null; PhoneDTO oPrimaryPhoneDTO = (userPhoneDTO != null) ? userPhoneDTO.Phone : null; UserEmailDTO userEmailDTO = (userDTO.UserEmails != null) ? userDTO.UserEmails.Where(o => o.IsPrimary).FirstOrDefault() : null; EmailDTO oPrimaryEmailDTO = (userEmailDTO != null) ? userEmailDTO.Email : null; userDataModel = UserDataModelAssembler.ToDataModel(userDTO, userAccountDTO, oPrimaryAddressDTO, oPrimaryPhoneDTO, oPrimaryEmailDTO); userDataModel.UserAddressID = (userAddressDTO != null) ? userAddressDTO.UserAddressID : 0; userDataModel.UserPhoneID = (userPhoneDTO != null) ? userPhoneDTO.UserPhoneID : 0; userDataModel.UserEmailID = (userEmailDTO != null) ? userEmailDTO.UserEmailID : 0; } return(userDataModel); }
public static EmailDTO ToDTO(this ClientEmail entity) { if (entity is null) { return(null); } var email = new EmailDTO { Id = entity.Id, OriginalMailId = entity.OriginalMailId, Subject = entity.Subject, Sender = entity.SenderEmail, DateReceived = entity.DateReceived, Body = entity.Body, EmailStatusId = entity.StatusEmailId, EmailStatusName = entity.Status?.StatusType, ModifiedOnDate = entity.ModifiedOnDate, ModifiedByUserId = entity.ModifiedByUserId, ApplicationStatus = entity.LoanApplication?.ApplicationStatus.ToString() }; return(email); }
public async Task <EmailDTO> UpdateEmailStatus(EmailDTO emailDTO, string newStatusName) { var newEmailStatus = await this.emailStatusService.GetEmailStatusByNameAsync(newStatusName); var email = await this.context.Emails.Include(e => e.Status).FirstOrDefaultAsync(e => e.Id == emailDTO.Id); if (email is null) { Log.Information($"{DateTime.Now} Email with id {emailDTO.Id} has not found."); throw new Exception("Email is not found"); } var oldEmailStatus = email.Status.StatusType; email.StatusEmailId = newEmailStatus.Id; email.ModifiedOnDate = DateTime.Now; email.ModifiedByUserId = null; Log.Information($"{email.ModifiedOnDate} Updated Email with Id: {email.Id}, from: {oldEmailStatus} to {newEmailStatus.StatusType}."); await this.context.SaveChangesAsync(); return(email.ToDTO()); }
public int Insertar(RequerimientoDTO entity) { int retval = 0; if ((retval = daRequerimiento.Insertar(entity)) > 0) { try { using (WSNotificacion.INotificacionServiceChannel wsCliente = ObtenerServicioNotificacion()) { EmailDTO emailDTO = new EmailDTO(); emailDTO.Destinatario = ConfigurationManager.AppSettings.Get("rrhhMail"); emailDTO.Asunto = "Nuevo Requerimiento de Personal"; emailDTO.TipoEmail = TipoMensaje.Requerimiento; emailDTO.Mensaje = string.Format("Se ha generado un requerimiento para el cliente <b>{0}</b> con el perfil de <b>{1}</b> y su fecha de posible ingreso es <b>{2}</b>", entity.Cliente.RazonSocial, entity.Perfil, entity.FechaTentativa.ToString("yyyy-MM-dd")); wsCliente.EnviarEmail(emailDTO); } }catch (Exception ex) { retval = -99; } } return(retval); }
public UserDataModel Get(UserDTO modelDTO) { UserDataModel userDataModel = null; if (modelDTO != null) { UserAddressDTO userAddressDTO = (modelDTO.UserAddresses != null) ? modelDTO.UserAddresses.Where(o => o.IsPrimary).FirstOrDefault() : null; AddressDTO oPrimaryAddressDTO = (userAddressDTO != null) ? userAddressDTO.Address : null; UserAccountDTO userAccountDTO = (modelDTO.UserAccounts != null) ? modelDTO.UserAccounts.FirstOrDefault(o => o.IsActive == true) : null; UserPhoneDTO userPhoneDTO = (modelDTO.UserPhone != null) ? modelDTO.UserPhone.Where(o => o.IsPrimary).FirstOrDefault() : null; PhoneDTO oPrimaryPhoneDTO = (userPhoneDTO != null) ? userPhoneDTO.Phone : null; UserEmailDTO userEmailDTO = (modelDTO.UserEmails != null) ? modelDTO.UserEmails.Where(o => o.IsPrimary).FirstOrDefault() : null; EmailDTO oPrimaryEmailDTO = (userEmailDTO != null) ? userEmailDTO.Email : null; List <ExperienceDTO> userExpriencelDTO = (modelDTO.Experiences != null) ? modelDTO.Experiences.ToList() : null; List <AchievementDTO> userAchievementlDTO = (modelDTO.Achievements != null) ? modelDTO.Achievements.ToList() : null; List <EducationDTO> userEducationlDTO = (modelDTO.Educations != null) ? modelDTO.Educations.ToList() : null; List <SkillDTO> userSkillDTO = (modelDTO.Skills != null) ? modelDTO.Skills.ToList() : null; List <LanguageDTO> userLanguageDTO = (modelDTO.Languages != null) ? modelDTO.Languages.ToList() : null; ImageDTO userImageDTO = (modelDTO.UserImages != null) ? modelDTO.UserImages.Where(x => x.IsPrimary == true).FirstOrDefault().Image : null; //ImageDTO oPrimaryImage = (userImageDTO != null) ? userImageDTO.UserImageID : null; userDataModel = UserDataModelAssembler.ToDataModel(modelDTO, userAccountDTO, oPrimaryAddressDTO, oPrimaryPhoneDTO, oPrimaryEmailDTO, userExpriencelDTO, userAchievementlDTO, userEducationlDTO, userSkillDTO, userLanguageDTO, userImageDTO); userDataModel.UserAddressID = (userAddressDTO != null) ? userAddressDTO.UserAddressID : 0; userDataModel.AddressID = (userAddressDTO != null) ? userAddressDTO.AddressID : 0; userDataModel.UserPhoneID = (userPhoneDTO != null) ? userPhoneDTO.UserPhoneID : 0; userDataModel.PhoneID = (userPhoneDTO != null) ? userPhoneDTO.PhoneID : 0; userDataModel.UserEmailID = (userEmailDTO != null) ? userEmailDTO.UserEmailID : 0; userDataModel.EmailID = (userEmailDTO != null) ? userEmailDTO.EmailID : 0; } return(userDataModel); }
public async Task <IHttpActionResult> PostEmail(Email email) { if (!ModelState.IsValid) { ModelState.AddModelError("Message", "The email details are not valid!"); return(BadRequest(ModelState)); } db.Emails.Add(email); await db.SaveChangesAsync(); Email lastEmail = await db.Emails.OrderByDescending(u => u.id).FirstAsync(); EmailDTO adddto = new EmailDTO(); adddto.id = lastEmail.id; adddto.account = lastEmail.account; adddto.preferredFlag = lastEmail.preferredFlag; adddto.emailTypeId = lastEmail.emailTypeId; adddto.emailType = db.EmailTypes.First(adt => adt.emailTypeId == lastEmail.emailTypeId).emailType; adddto.traderId = lastEmail.traderId; return(Ok <EmailDTO>(adddto)); }
public async Task <ActionResult> SendPasswordResetLinkAsync([FromBody] EmailDTO emailModel, string resetPasswordLink) { try { if (resetPasswordLink == null) { var message = "Password reset link not found"; return(BadRequest(message)); } if (ModelState.IsValid) { UserIdentityDTO user = await userService.GetByEmailAsync(emailModel.Email); if (user == null) { return(NoContent()); } if (!user.EmailConfirmed) { return(Forbid("Not allowed because email not confirmed")); } string token = JwtManager.GenerateToken(user, 0, 1); await EmailService.SendPasswordResetEmail(user.Email, token, resetPasswordLink); var message = "Token successfully sent"; return(Ok(message)); } var mes = "Email is not valid"; return(BadRequest(mes)); } catch (Exception e) { logger.LogInformation("Error : {0}", e.Message); return(StatusCode(500)); } }
public Task SendEmailAsync(EmailDTO emailDto) { var from = _senderOptions.Value.Account; var pass = _senderOptions.Value.Password; var client = new SmtpClient { Host = _senderOptions.Value.Host, Port = _senderOptions.Value.Port, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = _senderOptions.Value.UseDefaultCredentials, Credentials = (!_senderOptions.Value.UseDefaultCredentials) ? new NetworkCredential(@from, pass) : null, EnableSsl = _senderOptions.Value.EnableSsl }; var mail = new MailMessage(@from, emailDto.RecepientEmail) { Subject = emailDto.Subject, Body = emailDto.MessageText, IsBodyHtml = true, }; return(client.SendMailAsync(mail)); }
private void EnviarEmailTransferencia(TransferenciaPrestador transferenciaPrestador, Prestador prestador) { var empresaGrupo = _empresaGrupoService.BuscarNoRMPorId(transferenciaPrestador.IdEmpresaGrupo.GetValueOrDefault()); var filial = _filialService.BuscarFilialNoRm(transferenciaPrestador.IdFilial.GetValueOrDefault(), transferenciaPrestador.IdEmpresaGrupo.GetValueOrDefault()); var cliente = _prestadorRepository.ObterClienteAtivoPorIdCelulaEAcesso( transferenciaPrestador.IdCelula.GetValueOrDefault(), transferenciaPrestador.IdCliente.GetValueOrDefault()); var servico = ObterServicoPorId(transferenciaPrestador.IdServico.GetValueOrDefault()); var localTrabalho = _prestadorRepository.ObterLocalTrabalhoPorId( transferenciaPrestador.IdLocalTrabalho.GetValueOrDefault(), transferenciaPrestador.IdCliente.GetValueOrDefault()); if (empresaGrupo == null || filial == null || cliente == null || servico == null || localTrabalho == null) { return; } var parametros = DefinirParametrosEmail(transferenciaPrestador, prestador, empresaGrupo.Descricao, filial.Descricao, cliente.Descricao, servico.Descricao, localTrabalho.Descricao); var email = new EmailDTO { IdTemplate = 9, RemetenteNome = "Gestão de Transferências", Para = ObterDestinatarioEmail(prestador.Celula.EmailResponsavel), ValoresParametro = parametros }; EnviarEmail(email); }
public static void Send(EmailDTO email, bool sendBccDefault = false, bool sendUsingSpam = false) { InternalSend(email, sendBccDefault, sendUsingSpam); }
public void SendEmail(EmailDTO email) { }
protected string RegistrarEmailQueue(EmailDTO dto) { return(queue.Post(dto)); }
public HttpResponseMessage EmailList([FromBody] EmailDTO cqDTO) { return(Emails(Request, cqDTO)); }
internal HttpResponseMessage Emails(HttpRequestMessage request, EmailDTO cqDTO) { string key; var aur = new AppUserRepository(); var companyId = 0; var userId = aur.ValidateUser(cqDTO.Key, out key, ref companyId); if (userId > 0) { var ur = new EmailRepository(); var u = new Email(); var predicate = ur.GetPredicate(cqDTO, u, companyId); var data = ur.GetByPredicate(predicate); var col = new Collection <Dictionary <string, string> >(); data = data.OrderBy(x => x.EmailAddress).ToList(); foreach (var item in data) { var dic = new Dictionary <string, string>(); dic.Add("EmailID", item.EmailID.ToString()); dic.Add("EmailAddress", item.EmailAddress); dic.Add("ReceiveDailyReport", item.ReceiveDailyReport.ToString()); col.Add(dic); var ufdic = new Dictionary <string, string>(); } var ur2 = new EmailListRepository(); var u2 = new EmailList(); var predicate2 = ur2.GetPredicate(cqDTO, u2, companyId); var data2 = ur2.GetByPredicate(predicate); var col2 = new Collection <Dictionary <string, string> >(); data2 = data2.OrderBy(x => x.EmailListName).ToList(); foreach (var item in data2) { var dic = new Dictionary <string, string>(); dic.Add("EmailListId", item.EmailListId.ToString()); dic.Add("EmailListName", item.EmailListName); col2.Add(dic); var ufdic = new Dictionary <string, string>(); } //var ur3 = new ListEmailRepository(); //var u3 = new ListEmail(); //var predicate3 = ur3.GetPredicate(cqDTO, u3, companyId); //var data3 = ur3.GetByPredicate(predicate); //var col3 = new Collection<Dictionary<string, string>>(); //data3 = data3.ToList(); //foreach (var item in data3) //{ // var dic = new Dictionary<string, string>(); // dic.Add("ListId", item.ListId.ToString()); // dic.Add("EmailId", item.EmailId.ToString()); // col3.Add(dic); // var ufdic = new Dictionary<string, string>(); //} var retValList = new List <GenericDTO>(); var retVal = new GenericDTO { Key = key, ReturnData = col }; retValList.Add(retVal); var retVal2 = new GenericDTO { Key = key, ReturnData = col2 }; retValList.Add(retVal2); //var retVal3 = new GenericDTO //{ // Key = key, // ReturnData = col3 //}; //retValList.Add(retVal3); return(Request.CreateResponse(HttpStatusCode.OK, retValList)); } var message = "validation failed"; return(request.CreateResponse(HttpStatusCode.NotFound, message)); }
private List <DbValidationError> GetValidationErrors(EmailRepository pr, Email contact, EmailDTO cqDto, int YieldID, int userId) { contact.ProcessRecord(cqDto); return(pr.Validate(contact)); }
private HttpResponseMessage ProcessExistingEmailRecord(HttpRequestMessage request, EmailDTO cqDto, int contactId, string key, int EmailId, int userId) { var ur = new EmailRepository(); var user = new Email(); user = ur.GetById(contactId); var validationErrors = GetValidationErrors(ur, user, cqDto, EmailId, userId); if (validationErrors.Any()) { return(ProcessValidationErrors(request, validationErrors, key)); } ur.Save(user); cqDto.Key = key; return(request.CreateResponse(HttpStatusCode.Accepted, cqDto)); }
public Task Send(EmailDTO dados) => Task.Run(() => _observers.ForEach(obs => obs.OnNext(dados)));
/// <summary> /// Invoked when <see cref="ToEntity"/> operation is about to return. /// </summary> /// <param name="entity"><see cref="Email"/> converted from <see cref="EmailDTO"/>.</param> static partial void OnEntity(this EmailDTO dto, Email entity);
public string UpdateEmail(EmailDTO email) { securityService.UpdateUserProfile(new PartyId(ClaimsPrincipal.Current.Identity.Name), email.Email); return("Change password have done successfully"); }
public void OnNext(EmailDTO value) => Enviar(value).Wait();
public Task <bool> Enviar(EmailDTO email) { base.Injector.Rabbit.Producer(email, FilasRabbit.EMAIL_ENVIADOS_COLETA); base.Injector.NetMailService.Enviar(email); return(Task.FromResult(true)); }
public async Task SyncEmails() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var emailListResponse = await GetNewEmails(service); if (emailListResponse != null && emailListResponse.Messages != null) { foreach (var email in emailListResponse.Messages) { var emailInfoRequest = service.Users.Messages.Get("*****@*****.**", email.Id); var emailInfoResponse = await emailInfoRequest.ExecuteAsync(); if (emailInfoResponse != null) { string dateRecieved = emailInfoResponse.Payload.Headers .FirstOrDefault(x => x.Name == "Date") .Value; string sender = emailInfoResponse.Payload.Headers .FirstOrDefault(x => x.Name == "From") .Value; //sender = ParseSender(sender); string subject = emailInfoResponse.Payload.Headers .FirstOrDefault(x => x.Name == "Subject") .Value; //Body var str = new StringBuilder(); var itemToResolve = emailInfoResponse.Payload.Parts[0]; if (itemToResolve.MimeType == "text/plain") { //str.Append(DecodeBody(itemToResolve)); str.Append(itemToResolve.Body.Data); } else { //str.Append(DecodeBody(itemToResolve.Parts[0])); str.Append(itemToResolve.Parts[0].Body.Data); } //Body string body = str.ToString(); ICollection <AttachmentDTO> attachmentsOfEmail = new List <AttachmentDTO>(); if (!(itemToResolve.MimeType == "text/plain")) { attachmentsOfEmail = ParseAttachments(emailInfoResponse); } var emailDTO = new EmailDTO { RecievingDateAtMailServer = dateRecieved, Sender = sender, Subject = subject, Body = body, Attachments = attachmentsOfEmail, Status = EmailStatusesEnum.NotReviewed }; await emailService.CreateAsync(emailDTO); } } } }
/// <summary> /// Invoked when <see cref="ToDTO"/> operation is about to return. /// </summary> /// <param name="dto"><see cref="EmailDTO"/> converted from <see cref="Email"/>.</param> static partial void OnDTO(this Email entity, EmailDTO dto);
public BusinessDataModel Create(BusinessDataModel dataModel) { if (dataModel != null) { BusinessDTO businessDTO = new BusinessDTO(); List <AddressDTO> addressDTO = new List <AddressDTO>(); PhoneDTO phoneDTO = new PhoneDTO(); EmailDTO emailDTO = new EmailDTO(); BusinessUserMapDTO businessUserMapDTO = new BusinessUserMapDTO(); businessDTO = BusinessDataModelAssembler.ToBusinessDTO(dataModel); phoneDTO = BusinessDataModelAssembler.ToPhoneDTO(dataModel); emailDTO = BusinessDataModelAssembler.ToEmailDTO(dataModel); addressDTO = BusinessDataModelAssembler.ToAddressDTO(dataModel); businessUserMapDTO = BusinessDataModelAssembler.ToBusinessUserMapDTO(dataModel); if (businessDTO != null) { businessDTO = businessBL.Create(businessDTO); } dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); if (dataModel.BusinessUserId != 0) { new BusinessUserMapBL().Create(new BusinessUserMapDTO() { BusinessID = dataModel.BusinessID, UserID = dataModel.BusinessUserId, BusinessUserTypeID = dataModel.BusinessUserMapTypeCodeId, IsOwner = true }); } addressDTO = BusinessDataModelAssembler.ToAddressDTO(dataModel); if (addressDTO != null) { List <AddressDTO> addressList = new List <AddressDTO>(); //addressDTO = addressDTO.Select(p => addressBL.Create(p)).ToList(); foreach (var item in addressDTO) { addressList.Add(addressBL.Create(item)); } addressDTO = addressList; } dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); if (dataModel.Addresses.Count() != 0) { new BusinessAddressBL().Create(new BusinessAddressDTO() { BusinessID = dataModel.BusinessID, AddressID = dataModel.Addresses.FirstOrDefault().AddressID, IsPrimary = true }); } if (addressDTO.Count != 0) { phoneDTO = BusinessDataModelAssembler.ToPhoneDTO(dataModel); if (phoneDTO != null) { phoneDTO.AddressbookID = addressDTO.FirstOrDefault().AddressID; phoneDTO = phonesBL.Create(phoneDTO); } dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); new BusinessPhoneBL().Create(new BusinessPhoneDTO() { BusinessID = dataModel.BusinessID, PhoneID = dataModel.BusinessPhoneID, IsPrimary = true }); } dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); emailDTO = BusinessDataModelAssembler.ToEmailDTO(dataModel); if (emailDTO != null) { emailDTO = emailsBL.Create(emailDTO); } dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); new BusinessEmailBL().Create(new BusinessEmailDTO() { BusinessID = dataModel.BusinessID, EmailID = dataModel.BusinessEmailID, IsPrimary = true }); dataModel = BusinessDataModelAssembler.ToDataModel(businessDTO, addressDTO, phoneDTO, emailDTO, null, null, businessUserMapDTO, null); } return(dataModel); }
public async Task <bool> ReceivedBuyer(ReceivedBuyerDTO receivedBuyerDTO) { try { using (var db = new SocialNetworkDeveloperContext()) { using (var transaction = db.Database.BeginTransaction()) { try { var buyOrder = await db.OrdenesCompras.FirstOrDefaultAsync(x => x.IdOrdenCompra == receivedBuyerDTO.IdBuyOrder); if (buyOrder == null) { return(false); } var buyer = await _userServices.GetUserByID((int)buyOrder.IdUsuario); buyOrder.EstadoOrdenCompra = 4; //recibido db.Update(buyOrder).State = EntityState.Modified; await db.SaveChangesAsync(); //actualizacion orden de compra var saleOrder = await db.OrdenesVentas.FirstOrDefaultAsync(x => x.IdOrdenVenta == receivedBuyerDTO.IdSaleOrder); if (saleOrder != null) { saleOrder.EstadoOrdenVenta = 4; //entregado db.Update(saleOrder).State = EntityState.Modified; await db.SaveChangesAsync(); } //inserto raiting de publicacion Rating rating = new Rating() { Rating1 = receivedBuyerDTO.Raiting, FechaHoraCreacion = DateTime.Now, IdPublicacion = buyOrder.IdPublicacion, IdUsuario = buyOrder.IdUsuario }; db.Ratings.Add(rating); await db.SaveChangesAsync(); //actualizar publicación //var publication = await _publicationServices.GetPublicationById((int)buyOrder.IdPublicacion); var publication = await db.Publicaciones.FirstOrDefaultAsync(x => x.IdPublicacion == buyOrder.IdPublicacion); //if (publication != null) //{ // publication.Raiting = receivedBuyerDTO.Raiting; // db.Update(publication).State = EntityState.Modified; // await _context.SaveChangesAsync(); //} var seller = await _userServices.GetUserByID((int)publication.IdUsuario); EmailDTO emailDTO = new EmailDTO() { EmailBuyer = buyer.CorreoElectronico, EmailSeller = seller.CorreoElectronico, Title = string.Format("Su compra/venta de la Publicacion {0} fue Entregada", publication.Titulo), MessagesSeller = string.Format(@"Estimado/a <b>{0}</b> el comprador acaba de confirmar de recibido la mercaderia, gracias por utilizar SNB&S, <br/> Detalle de la Venta <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b> <br/> Cliente: <b>{3}</b> <br/> Telefono: <b>{4}</b> <br/> Total: <b>{5}</b>" , seller.NombreCompleto, publication.Titulo, saleOrder.Cantidad, buyer.NombreCompleto, buyer.TelefonoContacto, saleOrder.TotalVenta), MessagesBuyer = string.Format(@"Estimado/a <b>{0}</b> acaba de confirmar de recibido la mercaderia de su compra, gracias por utilizar SNB&S, <br/> Detalle De la Compra <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b> <br/> Total: <b>{3}</b> <br/> Vendedor: <b>{4}</b> <br/> Telefono: <b>{5}</b>" , buyer.NombreCompleto, publication.Titulo, saleOrder.Cantidad, Math.Round((decimal)saleOrder.TotalVenta, 2), seller.NombreCompleto, seller.TelefonoContacto), }; //si falla envio correo no registrar la aprobacion var email = await _emailServices.SendEmail(emailDTO); if (!email) { throw new Exception(); } //envio sms twilio var smsSeller = await _twilioServices.SendSMS(seller.TelefonoContacto, "Una Venta fue Entregada con Exito en SNB&S"); if (!smsSeller) { throw new Exception(); } var smsBuyer = await _twilioServices.SendSMS(buyer.TelefonoContacto, "Acabas de Confirmar de Recibido tu Compra en SNB&S"); if (!smsBuyer) { throw new Exception(); } await transaction.CommitAsync(); return(true); } catch (Exception e) { transaction.Rollback(); log.ErrorFormat("Error al ejecutar transaccion para confirmar de recibido la mercaderia ReceivedBuyer() {0} : {1} ", e.Source, e.Message); return(false); } } } } catch (Exception e) { log.ErrorFormat("Error al actualizar orden de compra a recibido ReceivedBuyer() {0} : {1} ", e.Source, e.Message); return(false); throw; } }
public async Task <bool> RejectSale(StatusOrderDTO statusOrderDTO) { using (var db = new SocialNetworkDeveloperContext()) { using (var transaction = db.Database.BeginTransaction()) { try { var saleOrder = await db.OrdenesVentas.FirstOrDefaultAsync(x => x.IdOrdenVenta == statusOrderDTO.IdSaleOrder); if (saleOrder == null) { return(false); } var publication = await _publicationServices.GetPublicationById((int)saleOrder.IdPublicacion); var seller = await _userServices.GetUserByID((int)publication.IdUsuario); saleOrder.EstadoOrdenVenta = 3; //rechazada db.Update(saleOrder).State = EntityState.Modified; await db.SaveChangesAsync(); //actualizacion orden de compra var buyOrder = await db.OrdenesCompras.FirstOrDefaultAsync(x => x.IdOrdenCompra == statusOrderDTO.IdBuyOrder); if (buyOrder != null) { buyOrder.EstadoOrdenCompra = 3; //rechazada db.Update(buyOrder).State = EntityState.Modified; await db.SaveChangesAsync(); } var buyer = await _userServices.GetUserByID((int)buyOrder.IdUsuario); EmailDTO emailDTO = new EmailDTO() { EmailBuyer = buyer.CorreoElectronico, EmailSeller = seller.CorreoElectronico, Title = string.Format("Su compra/venta de la Publicaicon {0} fue Rechazada", publication.Titulo), MessagesSeller = string.Format(@"Estimado/a <b>{0}</b> su venta fue <b>rechazada</b> exitosamente, favor notificar al comprador el porque, <br/> Detalle de la Venta <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b> <br/> Cliente: <b>{3}</b> <br/> Telefono: <b>{4}</b> <br/> Total: <b>{5}</b>" , seller.NombreCompleto, publication.Titulo, saleOrder.Cantidad, buyer.NombreCompleto, buyer.TelefonoContacto, Math.Round((decimal)saleOrder.TotalVenta, 2)), MessagesBuyer = string.Format(@"Estimado/a <b>{0}</b> su compra fue <b>rechazada</b> por el vendedor, <br/> Detalle de la Compra <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b> <br/> Total: <b>{3}</b> <br/> Vendedor: <b>{4}</b> <br/> Telefono: <b>{5}</b>" , buyer.NombreCompleto, publication.Titulo, saleOrder.Cantidad, Math.Round((decimal)saleOrder.TotalVenta, 2), seller.NombreCompleto, seller.TelefonoContacto), }; //si falla envio correo no registrar la aprobacion var email = await _emailServices.SendEmail(emailDTO); if (!email) { throw new Exception(); } //envio sms twilio var smsSeller = await _twilioServices.SendSMS(seller.TelefonoContacto, "Acabas de Rechazar una venta en SNB&S"); if (!smsSeller) { throw new Exception(); } var smsBuyer = await _twilioServices.SendSMS(buyer.TelefonoContacto, "Su compra fue Rechazada por el vendedor en SNB&S"); if (!smsBuyer) { throw new Exception(); } await transaction.CommitAsync(); return(true); } catch (Exception e) { transaction.Rollback(); log.ErrorFormat("Error al ejecutar transaccion para rechazar venta RejectSale() {0} : {1} ", e.Source, e.Message); return(false); } } } }
public async Task <ActionResult> RecoverPassword([FromBody] EmailDTO email) { await _userService.RecoverPassword(email.Email); return(NoContent()); }
public async Task <bool> AddSale(SaleOrderDTO saleOrderDTO) { using (var db = new SocialNetworkDeveloperContext()) { using (var transaction = db.Database.BeginTransaction()) { try { var seller = await _userServices.GetUserByID((int)saleOrderDTO.IdUsuario); var buyer = await _userServices.GetUserByID((int)saleOrderDTO.IdComprador); var publication = await _publicationServices.GetPublicationById((int)saleOrderDTO.IdPublicacion); var saleOrder = _mapper.Map <OrdenesVenta>(saleOrderDTO); saleOrder.FechaHoraOrdenVenta = DateTime.Now; //saleOrder.TotalVentaConIva = saleOrderDTO.Cantidad * (publication.Precio + (publication.Precio * 0.13m)); saleOrder.TotalVenta = saleOrderDTO.Cantidad * publication.Precio; saleOrder.EstadoOrdenVenta = 1; //pendiente db.OrdenesVentas.Add(saleOrder); await db.SaveChangesAsync(); //Creacion de orden de compra OrdenesCompra objCompra = new OrdenesCompra() { IdOrdenVenta = saleOrder.IdOrdenVenta, IdPublicacion = publication.IdPublicacion, IdUsuario = buyer.IdUsuario, FechaHoraOrdenCompra = DateTime.Now, //TotalCompraConIva = saleOrderDTO.Cantidad * (publication.Precio + (publication.Precio * 0.13m)), TotalCompra = saleOrderDTO.Cantidad * publication.Precio, EstadoOrdenCompra = 1, //pendiente Cantidad = saleOrderDTO.Cantidad }; db.OrdenesCompras.Add(objCompra); await db.SaveChangesAsync(); EmailDTO emailDTO = new EmailDTO() { EmailBuyer = buyer.CorreoElectronico, EmailSeller = seller.CorreoElectronico, Title = string.Format("Se Realizo una solicitud de compra/venta de la Publicaicon {0}", publication.Titulo), MessagesSeller = string.Format(@"Estimado/a <b>{0}</b> se ha realizado una solicitud de venta a travez de nuestra aplicación, <br/> Detalle De la Venta <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b> <br/> Cliente: <b>{3}</b> <br/> Telefono: <b>{4}</b> <br/> Dirección Entrega: <b>{5}</b> <br/> Comentario: <b>{6}</b>" , seller.NombreCompleto, publication.Titulo, saleOrderDTO.Cantidad, buyer.NombreCompleto, buyer.TelefonoContacto, saleOrderDTO.DireccionEntrega, saleOrderDTO.Comentario), MessagesBuyer = string.Format(@"Estimado/a <b>{0}</b> se ha realizado una solicitud de compra a travez de nuestra aplicación, <br/> Detalle De la Compra <br/> Publicación: <b>{1}</b> <br/> Cantidad: <b>{2}</b>" , buyer.NombreCompleto, publication.Titulo, saleOrderDTO.Cantidad), }; //si falla envio correo no registrar la venta var email = await _emailServices.SendEmail(emailDTO); if (!email) { throw new Exception(); } //envio sms twilio var smsSeller = await _twilioServices.SendSMS(seller.TelefonoContacto, "Se Realizo una solicitud de compra/venta en SNB&S"); if (!smsSeller) { throw new Exception(); } var smsBuyer = await _twilioServices.SendSMS(buyer.TelefonoContacto, "Acabas de realizar una solicitud de compra en SNB&S"); if (!smsBuyer) { throw new Exception(); } await transaction.CommitAsync(); return(true); } catch (Exception) { transaction.Rollback(); return(false); } } } }
static private void ResendThread() { while (cmdStop == false) { try { ParameterServices.Neologize(); Log.WriteMsgLogs("Email Resending Process ..."); Factory.CreateObject(); Factory.SuEmailResendingQuery.DeleteSuccessItem(); IList <SuEmailResending> ResendMails = Factory.SuEmailResendingQuery.FindAllEmailResending(); EmailSerializer serailer = new EmailSerializer(); SMSSerializer smsserialer = new SMSSerializer(); foreach (SuEmailResending item in ResendMails) { bool success; if (item.emailtype.Contains("SMS")) { success = false; item.status = "Retry"; try { SMSContainer sms = smsserialer.DeSerializeObject(item.mailcontent); if (item.emailtype == "SMS") { success = Factory.SMSService.ReSend(sms.sms); } else if (item.emailtype == "SMS+Log") { success = Factory.SMSService.ReSend(sms.sms, sms.SMSLogid); } else if (item.emailtype == "SMS+Notify") { success = Factory.SMSService.ReSend(sms.sms, sms.NotifySMS); } if (success) { item.status = "Success"; } } catch (Exception e) { Log.WriteLogs(e); } } else { try { EmailDTO email = serailer.DeSerializeObject(item.mailcontent); email.Status = 2; item.status = "Retry"; if (IsEmptyMailList(email.MailSendTo)) { AddMailSendTo sendto = new AddMailSendTo(); sendto.Email = SS.DB.Query.ParameterServices.AdminEmailAddress; sendto.Name = SS.DB.Query.ParameterServices.AdminName; email.MailSendTo.Clear(); email.MailSendTo.Add(sendto); email.Remark = "Send to email addresses is empty or invalid email format."; } email.IsMultipleReceiver = true; success = Factory.EmailService.SendEmail(email); if (success) { email.Status = 1; item.status = "Success"; } //send completed then must keep log AddEmailLog(email); } catch (Exception e) { Log.WriteLogs(e); } } item.lastsenddate = DateTime.Now; if (item.status == "Retry") { item.retry++; if (item.retry > ParameterServices.MaxRetry) { item.status = "Fail"; } } Factory.SuEmailResendingService.Update(item); } Log.WriteMsgLogs("Finish"); Thread.Sleep(SS.DB.Query.ParameterServices.EmailFlushingDuration * 60000); } catch (Exception e) { Log.WriteLogs(e); Thread.Sleep(SS.DB.Query.ParameterServices.EmailFlushingDuration * 60000); continue; } } }
private HttpResponseMessage ProcessNewEmailRecord(HttpRequestMessage request, EmailDTO uDto, string key, int EmailId, int userId) { var ur = new EmailRepository(); var user = new Email(); var validationErrors = GetValidationErrors(ur, user, uDto, EmailId, userId); if (validationErrors.Any()) { return(ProcessValidationErrors(request, validationErrors, key)); } user = ur.Save(user); uDto.Key = key; uDto.EmailID = user.EmailID.ToString(); var response = request.CreateResponse(HttpStatusCode.Created, uDto); response.Headers.Location = new Uri(Url.Link("Default", new { id = user.EmailID })); return(response); }