示例#1
0
        public ErrorBE SendPassword(String CorreoElectronico)
        {
            try
            {
                Usuario objUsuario = _UsuarioService.UsuarioPorCorreo(CorreoElectronico);

                if (objUsuario == null)
                {
                    return(new ErrorBE("El correo electrónico no se encuentra registrado en el sistema."));
                }

                Usuario objNewUsuario = new Usuario();
                objNewUsuario.UsuarioId = objUsuario.UsuarioId;
                objNewUsuario.Password  = Guid.NewGuid().ToString().Replace("-", String.Empty).Substring(0, 8);
                _UsuarioService.UpdatePassword(objNewUsuario);

                try
                {
                    var emailLogic = new EmailLogic();
                    emailLogic.SendEmailResetPassword(objUsuario.UsuarioId);
                }
                catch
                {
                    return(new ErrorBE("El correo electrónico ingresado es incorrecto."));
                }

                return(new ErrorBE());
            }
            catch (Exception ex)
            {
                return(new ErrorBE(ex.Message.ToString()));
            }
        }
示例#2
0
 public ReallyPaidModel(CarServiceDbContext context, IEmailSender emailSender)
 {
     _workSheetLogic = new WorkSheetLogic(context);
     _emailLogic     = new EmailLogic(context, emailSender);
     _userLogic      = new UserLogic(context);
     _companyLogic   = new CompanyLogic(context);
 }
示例#3
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ResetPasswordRequestEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.RequestDate,
                    e.Code,
                    e.User,
                    e.User.Email
                });

                EmailLogic.AssertStarted(sb);

                EmailModelLogic.RegisterEmailModel <ResetPasswordRequestEmail>(() => new EmailTemplateEntity
                {
                    Messages = CultureInfoLogic.ForEachCulture(culture => new EmailTemplateMessageEmbedded(culture)
                    {
                        Text = "<p>{0}</p>".FormatWith(AuthEmailMessage.YouRecentlyRequestedANewPassword.NiceToString()) +
                               "<p>{0} @[User.UserName]</p>".FormatWith(AuthEmailMessage.YourUsernameIs.NiceToString()) +
                               "<p>{0}</p>".FormatWith(AuthEmailMessage.YouCanResetYourPasswordByFollowingTheLinkBelow.NiceToString()) +
                               "<p><a href=\"@[m:Url]\">@[m:Url]</a></p>",
                        Subject = AuthEmailMessage.ResetPasswordRequestSubject.NiceToString()
                    }).ToMList()
                });
            }
        }
示例#4
0
        public ActionResult EmailVisita(Int32 VisitaCorretajeId)
        {
            try
            {
                VisitaCorretaje visita = context.VisitaCorretaje.FirstOrDefault(x => x.VisitaCorretajeId == VisitaCorretajeId);

                var        usuario   = context.Usuario.FirstOrDefault(x => x.UsuarioId == 1531);
                EmailLogic mailLogic = new EmailLogic();
                ViewModel.Templates.infoViewModel model = new ViewModel.Templates.infoViewModel();
                model.Mensaje = "Estimado Usuario\nSe adjunta la constancia de visita realizada.";
                model.Firma   = usuario.Firma;

                if (!String.IsNullOrEmpty(visita.Correo))
                {
                    mailLogic.SendEmailMasivoVisita("Constancia de Visita " + visita.Fecha.ToString("dd/MM/yyyy"), "info", usuario.Email
                                                    , usuario.NombreRemitente, visita.Correo, model, null
                                                    , null,
                                                    visita);
                }
                PostMessage(MessageType.Success);
            }
            catch (Exception ex)
            {
                PostMessage(MessageType.Error, ex.Message + (ex.InnerException != null ? ex.InnerException.Message : String.Empty));
            }

            return(RedirectToAction("LstVisitas"));
        }
示例#5
0
        private void AddOrUpdateUser(User user, bool isUpdate = false, bool generatePassword = true)
        {
            string messagePart = "";

            if (generatePassword)
            {
                user.PasswordHash = GenerateRandomNumber();
                messagePart       = string.Format("Kullanıcı Kodunuz: {0}\nŞifreniz: {1}\n\n", user.UserName, user.PasswordHash);
                HashPassword(user, user.PasswordHash);
            }

            if (isUpdate)
            {
                UserDao.Update(user);
            }
            else
            {
                UserDao.Add(user);
            }

            if (generatePassword)
            {
                //send an e-mail to the user to inform a new password generated and available to enter to the system
                try
                {
                    EmailLogic.MessageTemplate = string.Format(ConfigurationManager.AppSettings.Get("PasswordNotificationTemplate").ToString(), DateTime.Now, "{0}");
                    EmailLogic.SendNewPasswordNotification(user.Email, messagePart);
                }
                catch (Exception ex)
                {
                    mLogger.Error(ex.ToString());
                }
            }
        }
示例#6
0
 public WorkSheetModel(CarServiceDbContext context, IEmailSender emailSender)
 {
     _appUserLogic     = new UserLogic(context);
     _appointmentLogic = new AppointmentLogic(context);
     _calendarLogic    = new WorkSheetLogic(context);
     _workLogic        = new WorkLogic(context);
     _emailLogic       = new EmailLogic(context, emailSender);
 }
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ResetPasswordRequestEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.RequestDate,
                    e.Code,
                    e.User,
                    e.User.Email
                });

                EmailLogic.AssertStarted(sb);

                EmailModelLogic.RegisterEmailModel <ResetPasswordRequestEmail>(() => new EmailTemplateEntity
                {
                    DisableAuthorization = true,
                    Messages             = CultureInfoLogic.ForEachCulture(culture => new EmailTemplateMessageEmbedded(culture)
                    {
                        Text = "<p>{0}</p>".FormatWith(AuthEmailMessage.YouRecentlyRequestedANewPassword.NiceToString()) +
                               "<p>{0} @[User.UserName]</p>".FormatWith(AuthEmailMessage.YourUsernameIs.NiceToString()) +
                               "<p>{0}</p>".FormatWith(AuthEmailMessage.YouCanResetYourPasswordByFollowingTheLinkBelow.NiceToString()) +
                               "<p><a href=\"@[m:Url]\">@[m:Url]</a></p>",
                        Subject = AuthEmailMessage.ResetPasswordRequestSubject.NiceToString()
                    }).ToMList()
                });



                new Graph <ResetPasswordRequestEntity> .Execute(ResetPasswordRequestOperation.Execute)
                {
                    CanBeNew      = false,
                    CanBeModified = false,
                    CanExecute    = (e) => e.Lapsed == false ? null : AuthEmailMessage.YourResetPasswordRequestHasExpired.NiceToString(),
                    Execute       = (e, args) =>
                    {
                        string password = args.GetArg <string>();
                        e.Lapsed = true;
                        var user = e.User;

                        var error = UserEntity.OnValidatePassword(password);
                        if (error != null)
                        {
                            throw new ApplicationException(error);
                        }

                        user.PasswordHash = Security.EncodePassword(password);
                        using (AuthLogic.Disable())
                            user.Execute(UserOperation.Save);
                    }
                }

                .Register();
            }
        }
示例#8
0
        public bool SendNotificationAboutNewOrUpdatedWorkload(string uniqueName, int newOrUpdate)
        {
            EmailLogic clientEmail = new EmailLogic();

            // Mounting parameters and message.
            string ToName  = Util.GetUserAlias(uniqueName);
            string ToEmail = uniqueName;
            string Subject = "";

            StringBuilder StructureModified = new StringBuilder();

            StructureModified = EmailMessages.GetEmailMessageStructure();

            // Replacing the generic title by the customized.
            StructureModified.Replace("[MessageTitle]", "Hi " + ToName + ", we have news to you: ");

            if (newOrUpdate == 0) // new workload
            {
                Subject += "[ARDA] New workload available to you";

                // Replacing the generic subtitle by the customized.
                StructureModified.Replace("[MessageSubtitle]", "A new <strong>Workload</strong> was created and signed to you.");

                // Replacing the generic message body by the customized.
                StructureModified.Replace("[MessageBody]", "To see your new workload, please, click on the link bellow.");
            }
            else
            {
                Subject += "[ARDA] Existing workload has been updated";

                // Replacing the generic subtitle by the customized.
                StructureModified.Replace("[MessageSubtitle]", "A existent <strong>Workload</strong> signed to you was updated.");

                // Replacing the generic message body by the customized.
                StructureModified.Replace("[MessageBody]", "To see your workload updated, please, click on the link bellow.");
            }

            // Replacing the generic callout box.
            StructureModified.Replace("[MessageCallout]", "Dashboard (Kanban): <a href='/Dashboard/Index'>My workloads</a>");

            // Creating a object that will send the message.
            EmailLogic EmailObject = new EmailLogic();

            try
            {
                var EmailTask = EmailObject.SendEmailAsync(ToName, ToEmail, Subject, StructureModified.ToString());
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#9
0
        public async Task <ActionResult> EmailReceiverAsync(EmailReceverViewModel emailRecever)
        {
            //if(!ModelState.IsValid)
            //{

            //}
            EmailLogic email = new EmailLogic();

            await email.EmailReceiverAsync(emailRecever.From, emailRecever.Subject, emailRecever.Body);


            return(View("Success"));
        }
示例#10
0
 public void EnviarCorreoUsuarioPasswordNuevo(string USR_PASSWORD)
 {
     try
     {
         string USR_USERNAME = this.CambiarClaveUsernameTxt.Text;
         EmailLogic.EnviarCorreoUsuarioPasswordNuevo(USR_USERNAME, USR_PASSWORD, this.docConfiguracion);
     }
     catch (Exception ex)
     {
         log.Fatal("Error fatal al enviar correo de password nuevo.", ex);
         throw;
     }
 }
示例#11
0
        public void EnviarCorreoPrivilegiosNuevos()
        {
            try
            {
                int           ROL_ID    = Convert.ToInt32(this.EditIdTxt.Value);
                List <string> privsList = this.PrivilegiosNoDeRolSelectionM.SelectedRows.Select(s => s.RecordID).ToList <string>();

                EmailLogic.EnviarCorreosPrivilegiosNuevos(Convert.ToInt32(ROL_ID), privsList, this.docConfiguracion);
            }
            catch (Exception ex)
            {
                log.Fatal("Error fatal al enviar correo de rol nuevo.", ex);
                throw;
            }
        }
示例#12
0
        public UsuarioBE SaveUsuario(UsuarioBE objUsuarioBE)
        {
            try
            {
                Usuario objUsuario = _UsuarioService.UsuarioPorCorreo(objUsuarioBE.CorreoElectronico.Trim()); //context.Usuario.FirstOrDefault(x => x.CorreoElectronico == objUsuarioBE.CorreoElectronico.Trim());

                if (objUsuario != null)
                {
                    return(new UsuarioBE("El usuario ya se encuentra registrado."));
                }

                objUsuario = new Usuario();
                objUsuario.ApellidoMaterno   = objUsuarioBE.ApellidoMaterno;
                objUsuario.ApellidoPaterno   = objUsuarioBE.ApellidoPaterno;
                objUsuario.CorreoElectronico = objUsuarioBE.CorreoElectronico;
                objUsuario.DistritoId        = objUsuarioBE.DistritoId;
                objUsuario.DNI                = objUsuarioBE.DNI;
                objUsuario.EspecialidadId     = objUsuarioBE.EspecialidadId;
                objUsuario.EsTrabajador       = objUsuarioBE.EsTrabajador;
                objUsuario.strFechaNacimiento = objUsuarioBE.strFechaNacimiento;
                objUsuario.Nombres            = objUsuarioBE.Nombres;
                objUsuario.NumeroContacto1    = objUsuarioBE.NumeroContacto1;
                objUsuario.NumeroContacto2    = objUsuarioBE.NumeroContacto2;
                objUsuario.TieneEstudios      = objUsuarioBE.TieneEstudios;
                objUsuario.Password           = objUsuarioBE.Password;
                objUsuario.Estado             = "REG";
                objUsuario.DeviceToken        = objUsuario.DeviceToken;
                objUsuario.Origen             = objUsuario.Origen;
                objUsuario.UsuarioIDExterno   = objUsuario.UsuarioIDExterno;
                _UsuarioService.Insert(objUsuario);

                try
                {
                    var emailLogic = new EmailLogic();
                    emailLogic.SendEmailVerificacionCorreo(objUsuario.UsuarioId);
                }
                catch
                {
                    return(new UsuarioBE("El correo electrónico ingresado es incorrecto."));
                }

                return(objUsuarioBE);
            }
            catch
            {
                return(new UsuarioBE("Por favor, ingrese todos los campos completos."));
            }
        }
示例#13
0
        private static void SendEmailAfterCreatingTeam(TeamModel team)
        {
            string        toAddress = "*****@*****.**";
            string        subject   = "New Team Has Been Created";
            StringBuilder body      = new StringBuilder();

            body.AppendLine("<h1> You have created a new team</h1>");
            body.Append("<strong>Name: </strong>");
            body.Append(team.TeamName);
            body.AppendLine();
            body.AppendLine();
            body.AppendLine("Have a greate time!");
            body.AppendLine("~Tournament Tracker");

            EmailLogic.SendEmail(toAddress, subject, body.ToString());
        }
示例#14
0
        public ActionResult Insert(VMUsuarioExterno model)
        {
            var result = new Resultado();

            try
            {
                if (string.IsNullOrEmpty(model.Usuario.ApellidoPaterno) ||
                    string.IsNullOrEmpty(model.Usuario.ApellidoMaterno) ||
                    string.IsNullOrEmpty(model.Usuario.Nombres) ||
                    string.IsNullOrEmpty(model.Usuario.DNI) ||
                    string.IsNullOrEmpty(model.Usuario.NumeroContacto1) ||
                    string.IsNullOrEmpty(model.Usuario.strFechaNacimiento))
                {
                    return(View(model));
                }
                model.Usuario.Estado = "REG";
                var Resultado = _UsuarioService.Insert(model.Usuario);
                result.Codigo = Resultado.UsuarioId;

                try
                {
                    if (result.Codigo != 0)
                    {
                        var emailLogic = new EmailLogic();
                        emailLogic.SendEmailVerificacionCorreo(result.Codigo);
                    }
                }
                catch (Exception ex)
                {
                    result.EsExito = false;
                    result.Mensaje = ex.Message;
                    return(View());
                }

                VMDatosUsuarioExterno.SetValueLogin(model.Usuario.Nombres, model.Usuario.CorreoElectronico, "", null, result.Codigo.ToString(), "REG", model.Usuario.DNI);
                FormsAuthentication.SetAuthCookie(VMDatosUsuarioExterno.GetUserAlias(), false);
            }
            catch (System.Exception ex)
            {
                result.EsExito = false;
                result.Mensaje = ex.Message;
                return(View());
            }
            return(Json(result));
        }
        private void SendOrderToChef(OrderModel o)
        {
            string to      = chef.EmailAddress;
            string subject = "New Order";

            StringBuilder body = new StringBuilder();

            body.AppendLine("<h1>You have a new order</h1>");
            body.AppendLine($"<br><strong>Table: { o.TableNumber }</strong></br>");
            body.AppendLine($"<br><strong>Attendant: { o.Attendant }</strong></br>");
            body.AppendLine("...............................................................");

            foreach (FoodModel f in o.FoodOrdered)
            {
                body.Append($"<br><strong>{ f.FoodName }:  { f.Quantity }</stong></br>");
            }

            EmailLogic.SendEmail(to, subject, body.ToString());
        }
示例#16
0
        public void EnviarCorreoRolesNuevos()
        {
            try
            {
                string USR_USERNAME = this.EditUsernameTxt.Text;

                List <string> rolesList = this.RolesNoDeUsuarioSelectionM.SelectedRows.Select(s => s.RecordID).ToList <string>();

                foreach (string r in rolesList)
                {
                    EmailLogic.EnviarCorreoRolNuevo(USR_USERNAME, Convert.ToInt32(r), this.docConfiguracion);
                }
            }
            catch (Exception ex)
            {
                log.Fatal("Error fatal al enviar correo de roles nuevos.", ex);
                throw;
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            Account account = new Account(collection["Voornaam"], collection["Tussenvoegsel"], collection["Achternaam"], Convert.ToInt32(collection["Telefoonnummer"]), collection["Gebruikersnaam"], collection["Wachtwoord"], collection["Email"], MD5.CreateMD5(collection["Email"]), 0);

            try
            {
                // TODO: Add insert logic here
                accountrepo.InsertAccount(account);
                Models.Email mail = new Models.Email("Activeer uw account", "inhoud", "*****@*****.**");
                //EmailLogic.SendEmail(mail);
                EmailLogic.SendEmailNew(mail, account.Activatiehash, account.Voornaam);

                return(RedirectToAction("Create", "Account"));
            }
            catch
            {
                throw;
                //return View();
            }
        }
示例#18
0
        public bool SendNotificationOfNewUserByEmail(string uniqueName)
        {
            EmailLogic clientEmail = new EmailLogic();

            // Mounting parameters and message.
            var Configuration = new ConfigurationBuilder().AddJsonFile("secrets.json").Build();
            var admin         = Configuration["Email:Administrator"];

            string ToName  = "Arda Administrator";
            string ToEmail = admin;
            string Subject = "[ARDA] A new user has been logged @ Arda";

            StringBuilder StructureModified = new StringBuilder();

            StructureModified = EmailMessages.GetEmailMessageStructure();

            // Replacing the generic title by the customized.
            StructureModified.Replace("[MessageTitle]", "Hi " + ToName + ", someone requested access to the system");

            // Replacing the generic subtitle by the customized.
            StructureModified.Replace("[MessageSubtitle]", "Who did the request was <strong>" + uniqueName + "</strong>. If you deserve, can access 'Users' area and distribute the appropriated permissions.");

            // Replacing the generic message body by the customized.
            StructureModified.Replace("[MessageBody]", "Details about the request: </br></br><ul><li>Email: " + uniqueName + "</li><li>Date/time access: " + DateTime.Now + "</li></ul>");

            // Replacing the generic callout box.
            StructureModified.Replace("[MessageCallout]", "For more details about the request, send a message to <strong>[email protected]</strong>.");

            // Creating a object that will send the message.
            EmailLogic EmailObject = new EmailLogic();

            try
            {
                var EmailTask = EmailObject.SendEmailAsync(ToName, ToEmail, Subject, StructureModified.ToString());
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#19
0
        /// <summary>
        /// Obtiene un logic de correo apartir de su request
        /// </summary>
        /// <param name="parametroRequest">Request de correo</param>
        /// <returns>Logic del correoo</returns>
        public static EmailLogic ObtenerEmail(EmailRequest request)
        {
            var logic = new EmailLogic();

            logic.Para     = new List <DireccionesLogic>();
            logic.ConCopia = new List <DireccionesLogic>();
            logic.Adjuntos = new List <AdjuntosLogic>();
            if (request.Para != null)
            {
                foreach (DireccionesRequest item in request.Para)
                {
                    logic.Para.Add(new DireccionesLogic()
                    {
                        Email = item.Email, NombreCompleto = item.NombreCompleto
                    });
                }
            }
            if (request.ConCopia != null)
            {
                foreach (DireccionesRequest item in request.ConCopia)
                {
                    logic.ConCopia.Add(new DireccionesLogic()
                    {
                        Email = item.Email, NombreCompleto = item.NombreCompleto
                    });
                }
            }
            if (request.Adjuntos != null)
            {
                foreach (AdjuntosRequest item in request.Adjuntos)
                {
                    logic.Adjuntos.Add(new AdjuntosLogic()
                    {
                        Archivo = item.Archivo, NombreArchivo = item.NombreArchivo
                    });
                }
            }
            logic.Asunto  = request.Asunto;
            logic.Mensaje = request.Mensaje;
            return(logic);
        }
        private void BuildEmail()
        {
            List <ProductModel> allProducts           = GlobalConfig.Connection.GetAllProducts();
            List <ProductModel> productsNeedingRefill = new List <ProductModel>();

            allProducts.ForEach(product =>
            {
                if (product.NeedsRefill)
                {
                    productsNeedingRefill.Add(product);
                }
            });

            StringBuilder body = new StringBuilder();

            productsNeedingRefill.ForEach(product => body.AppendLine(product.Name));



            EmailLogic.SendEmail(GlobalConfig.AppKeyLookup("recieverEmail"), $"Shopping List - {DateTime.UtcNow.Date:d}", body.ToString());
        }
示例#21
0
        public ActionResult RecuperarClave(VMUsuarioExterno model)
        {
            var result = new Resultado();

            try
            {
                Usuario objUsuario = _UsuarioService.UsuarioPorCorreo_Sin_RedesSociales(model.Usuario.CorreoElectronico);

                if (objUsuario == null)
                {
                    result.Codigo = -1;
                    return(View());
                }

                Usuario objNewUsuario = new Usuario();
                objNewUsuario.UsuarioId = objUsuario.UsuarioId;
                objNewUsuario.Password  = Guid.NewGuid().ToString().Replace("-", String.Empty).Substring(0, 8);
                _UsuarioService.UpdatePassword(objNewUsuario);

                try
                {
                    var emailLogic = new EmailLogic();
                    emailLogic.SendEmailResetPassword(objUsuario.UsuarioId);
                }
                catch (Exception ex)
                {
                    result.Codigo  = 0;
                    result.EsExito = false;
                    result.Mensaje = ex.Message;
                    return(View());
                }
            }
            catch (System.Exception ex)
            {
                result.EsExito = false;
                result.Mensaje = ex.Message;
                return(View());
            }
            return(Json(result));
        }
        private void buttonSendMail_Click(object sender, EventArgs e)
        {
            string        subject = textBoxSubject.Text;
            StringBuilder body    = new StringBuilder();

            body.Append("<h1>New Message from:</h1>");
            body.Append(comboBoxIme.Text);
            body.AppendLine();
            body.AppendLine();
            body.Append("<strong>Computer UserName is: </strong>");
            body.Append(Environment.UserName);
            body.AppendLine();
            body.AppendLine();
            body.Append("<strong>Message Body:</strong>");
            body.Append(textBoxBody.Text);
            //try
            //{
            //    EmailLogic email = new EmailLogic(this);
            //    email.SendEmail(body.ToString(), subject);
            //    //EmailLogic.SendEmail(body.ToString(), subject);
            //}
            //catch (Exception ex)
            //{

            //    MessageBox.Show("Nesto nije u redu sa mejl serverom, poruka je sledeca: " + ex,"Obavestenj!", MessageBoxButtons.OK,MessageBoxIcon.Information);
            //}

            if (textBoxSubject.Text != "" || comboBoxIme.Text != "" || textBoxBody.Text != "")
            {
                EmailLogic email = new EmailLogic(this);
                email.SendEmail(body.ToString(), subject);
            }
            else
            {
                MessageBox.Show("Mortate popuniti sva polja. ", "Greska!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            //MessageBox.Show("Mejl je uspesno prosledjen developeru. ","Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //this.Close();
        }
        public ActionResult EnviarCorreoPendiente()
        {
            int Resultado      = 0;
            var paginateParams = new PaginateParams
            {
                IsPaginate = false, PageIndex = 0, RowsPerPage = 0, SortColumn = "", SortDirection = ""
            };

            List <Usuario> _ListUsuario = _UsuarioService.List_Usuario_Paginate(paginateParams).Where(x => x.Estado == "Registrado").ToList();

            foreach (var item in _ListUsuario)
            {
                try
                {
                    if (item.UsuarioId != 0)
                    {
                        var emailLogic = new EmailLogic();
                        emailLogic.SendEmailVerificacionCorreo(item.UsuarioId);
                    }
                }
                catch (Exception ex)
                {
                    //result.EsExito = false;
                    //result.Mensaje = ex.Message;
                    //return View();
                }
                Resultado = 1;
            }

            if (Resultado == 0)
            {
                Resultado = 2;
            }
            return(new JsonResult()
            {
                Data = new { Codigo = Resultado }
            });
        }
示例#24
0
        public ActionResult _ForgotPassword(_ForgotPasswordViewModel model)
        {
            try
            {
                EmailLogic mailLogic = new EmailLogic(this, CargarDatosContext());
                ViewModel.Templates.infoViewModel mailModel = new ViewModel.Templates.infoViewModel();

                var Lstusuario = context.Usuario.Where(x => x.Email == model.Email).ToList();
                if (Lstusuario.Count == 0)
                {
                    PostMessage(MessageType.Error, "El correo " + model.Email + " no se encuentra registrado en el sistema. Intente nuevamente ingresando un correo registrado en el sistema.");
                    return(RedirectToAction("Login", "Home"));
                }
                var Mensaje = String.Empty;
                foreach (var item in Lstusuario)
                {
                    if (item.Departamento != null)
                    {
                        Mensaje += "Edificio: " + item.Departamento.Edificio.Nombre + " - Departamento: " + item.Departamento.Numero + "<br/>";
                        Mensaje += "Usuario: " + item.Codigo + "<br/>";
                        Mensaje += "Contraseña: " + item.Password + "<br/>";
                        Mensaje += "---------------------------------<br/>";
                    }
                }
                mailModel.Mensaje = Mensaje;
                mailModel.Titulo  = "Recuperar Contraseña";

                mailLogic.SendEmail("Recuperar Contraseña", "ForgorPassword", "*****@*****.**", "Afari", model.Email, mailModel, null);
                PostMessage(MessageType.Success, "Se envió un email con los datos de acceso a " + model.Email);
                return(RedirectToAction("Login", "Home"));
            }
            catch (Exception ex)
            {
                PostMessage(MessageType.Error, "No se pudo enviar email.");
                return(RedirectToAction("Login", "Home"));
            }
        }
示例#25
0
        private void SendBillToAttendant(OrderModel o)
        {
            string to      = (GlobalConfig.Connection.GetPersonByFullName(o.Attendant)).EmailAddress;
            string subject = "Bill";

            StringBuilder body = new StringBuilder();

            body.AppendLine($"<h1>{ o.Attendant }, A bill is ready to pay</h1>");
            body.AppendLine($"<h2><strong>Table: { o.TableNumber }</strong></h2>");
            body.AppendLine(".......................................................................");

            foreach (FoodModel f in o.FoodOrdered)
            {
                body.Append($"<br><strong>{ f.FoodType } &emsp { f.FoodName }: &emsp { f.Price } &emsp { f.Quantity }</stong></br>");
            }

            body.AppendLine(".......................................................................");

            body.Append($"<br><strong>Subtotal: &emsp { subTotal }</strong></br>");
            body.Append($"<br><strong>Tax: &emsp { tax }</strong></br>");
            body.Append($"<br><strong>Total: &emsp { total }</strong></br>");

            EmailLogic.SendEmail(to, subject, body.ToString());
        }
示例#26
0
        private void sendEmailsButton_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.emailContent == null)
            {
                LogLabel(logLabel, "Compose email first.", Color.Red);

                return;
            }

            if (employeeList.Count == 0)
            {
                LogLabel(logLabel, "Add employee to list first.", Color.Red);

                return;
            }

            if (passwordBox.TextLength == 0)
            {
                LogLabel(logLabel, "Enter password.", Color.Red);

                return;
            }

            List <PersonModel> selectedEmployees = new List <PersonModel>();

            if (!sendToTeamsCheckbox.Checked)
            {
                if (employeeListbox.SelectedItems.Count == 0)
                {
                    selectedEmployees = employeeList.ToList();
                }
                else
                {
                    foreach (PersonModel item in employeeListbox.SelectedItems)
                    {
                        selectedEmployees.Add(item);
                    }
                }
            }
            else
            {
                List <TeamModel> selectedTeams = new List <TeamModel>();

                if (teamListbox.SelectedItems.Count == 0)
                {
                    selectedTeams = teamList.ToList();
                }
                else
                {
                    foreach (TeamModel t in teamListbox.SelectedItems)
                    {
                        foreach (PersonModel p in t.TeamMembers)
                        {
                            selectedEmployees.Add(p);
                        }
                    }
                }
            }

            try
            {
                using (SmtpClient smtp = EmailLogic.CreateSmtp(Properties.Settings.Default.smtp,
                                                               int.Parse(Properties.Settings.Default.smtpPort), Properties.Settings.Default.email, passwordBox.Text))
                {
                    foreach (PersonModel p in selectedEmployees)
                    {
                        EmailLogic.logs.Add($"Sending Email to {p.FullName}");
                        logListbox.Refresh();
                        logListbox.TopIndex = logListbox.Items.Count - 1;

                        EmailLogic.logs.Add(EmailLogic.SendEmail(Properties.Settings.Default.emailContent, p, smtp, Properties.Settings.Default.email));
                        logListbox.Refresh();
                        logListbox.TopIndex = logListbox.Items.Count - 1;
                    }
                }
            }
            catch (Exception exc)
            {
                EmailLogic.logs.Add("Something went wrong. ");
                EmailLogic.logs.Add(exc.Message);

                logListbox.Refresh();
                logListbox.TopIndex = logListbox.Items.Count - 1;
            }

            passwordBox.Text = "";
        }
示例#27
0
    protected void lnkBtnUpdate_Click(object sender, EventArgs e)
    {
        BusinessLogic objBus  = new BusinessLogic();
        DBManager     manager = new DBManager(DataProvider.SqlServer);

        manager.ConnectionString = objBus.CreateConnectionString(System.Configuration.ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ConnectionString);

        string enabledate = string.Empty;

        enabledate = rdvoudateenable.SelectedValue;

        try
        {
            manager.Open();
            manager.ExecuteNonQuery(CommandType.Text, "Update last_recon Set recon_date='" + Convert.ToDateTime(txtReconDate.Text).ToString("yyyy-MM-dd") + "'");

            manager.ExecuteNonQuery(CommandType.Text, "UPDATE tblSettings SET KEYVALUE = '" + enabledate.ToString() + "' WHERE KEYNAME='ENBLDATE' ");

            string salestype  = string.Empty;
            int    ScreenNo   = 0;
            string ScreenName = string.Empty;

            salestype  = "Lock Transaction";
            ScreenName = "Lock Transaction";


            string usernam = Request.Cookies["LoggedUserName"].Value;

            bool          mobile       = false;
            bool          Email        = false;
            string        emailsubject = string.Empty;
            string        connection   = Request.Cookies["Company"].Value;
            BusinessLogic bl           = new BusinessLogic();

            string emailcontent = string.Empty;
            if (hdEmailRequired.Value == "YES")
            {
                var   toAddress     = "";
                var   toAdd         = "";
                Int32 ModeofContact = 0;
                int   ScreenType    = 0;



                DataSet dsdd = bl.GetDetailsForScreenNo(connection, ScreenName, "");
                if (dsdd != null)
                {
                    if (dsdd.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow dr in dsdd.Tables[0].Rows)
                        {
                            ScreenType   = Convert.ToInt32(dr["ScreenType"]);
                            mobile       = Convert.ToBoolean(dr["mobile"]);
                            Email        = Convert.ToBoolean(dr["Email"]);
                            emailsubject = Convert.ToString(dr["emailsubject"]);
                            emailcontent = Convert.ToString(dr["emailcontent"]);

                            if (ScreenType == 1)
                            {
                                toAddress = toAdd;
                            }
                            else
                            {
                                toAddress = dr["EmailId"].ToString();
                            }
                            if (Email == true)
                            {
                                string body = "\n";

                                int index123 = emailcontent.IndexOf("@Branch");
                                body = Request.Cookies["Company"].Value;
                                if (index123 >= 0)
                                {
                                    emailcontent = emailcontent.Remove(index123, 7).Insert(index123, body);
                                }

                                int index312 = emailcontent.IndexOf("@User");
                                body = usernam;
                                if (index312 >= 0)
                                {
                                    emailcontent = emailcontent.Remove(index312, 5).Insert(index312, body);
                                }

                                int index2 = emailcontent.IndexOf("@Date");
                                body = txtReconDate.Text;
                                if (index2 >= 0)
                                {
                                    emailcontent = emailcontent.Remove(index2, 5).Insert(index2, body);
                                }

                                string smtphostname = ConfigurationManager.AppSettings["SmtpHostName"].ToString();
                                int    smtpport     = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPortNumber"]);
                                var    fromAddress  = ConfigurationManager.AppSettings["FromAddress"].ToString();

                                string fromPassword = ConfigurationManager.AppSettings["FromPassword"].ToString();

                                EmailLogic.SendEmail(smtphostname, smtpport, fromAddress, toAddress, emailsubject, emailcontent, fromPassword);

                                //ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Email sent successfully')", true);
                            }
                        }
                    }
                }
            }

            string     conn    = bl.CreateConnectionString(Request.Cookies["Company"].Value);
            UtilitySMS utilSMS = new UtilitySMS(conn);
            string     UserID  = Page.User.Identity.Name;

            string smscontent = string.Empty;
            if (hdSMSRequired.Value == "YES")
            {
                var   toAddress     = "";
                var   toAdd         = "";
                Int32 ModeofContact = 0;
                int   ScreenType    = 0;

                DataSet dsdd = bl.GetDetailsForScreenNo(connection, ScreenName, "");
                if (dsdd != null)
                {
                    if (dsdd.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow dr in dsdd.Tables[0].Rows)
                        {
                            ScreenType = Convert.ToInt32(dr["ScreenType"]);
                            mobile     = Convert.ToBoolean(dr["mobile"]);
                            smscontent = Convert.ToString(dr["smscontent"]);

                            if (ScreenType == 1)
                            {
                                toAddress = toAdd;
                            }
                            else
                            {
                                toAddress = dr["mobile"].ToString();
                            }
                            if (mobile == true)
                            {
                                string body = "\n";

                                int index123 = smscontent.IndexOf("@Branch");
                                body = Request.Cookies["Company"].Value;
                                if (index123 >= 0)
                                {
                                    smscontent = emailcontent.Remove(index123, 7).Insert(index123, body);
                                }

                                int index312 = smscontent.IndexOf("@User");
                                body = usernam;
                                if (index312 >= 0)
                                {
                                    smscontent = smscontent.Remove(index312, 5).Insert(index312, body);
                                }

                                int index2 = smscontent.IndexOf("@Date");
                                body = txtReconDate.Text;
                                if (index2 >= 0)
                                {
                                    smscontent = smscontent.Remove(index2, 5).Insert(index2, body);
                                }

                                if (Session["Provider"] != null)
                                {
                                    utilSMS.SendSMS(Session["Provider"].ToString(), Session["Priority"].ToString(), Session["SenderID"].ToString(), Session["UserName"].ToString(), Session["Password"].ToString(), toAddress, smscontent, true, UserID);
                                }
                            }
                        }
                    }
                }
            }


            //errorDisplay.AddItem("Recon Date updated successfully." , DisplayIcons.GreenTick,false);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Recon Date updated successfully.');", true);
            return;
        }
        catch (Exception ex)
        {
            TroyLiteExceptionManager.HandleException(ex);
        }
    }
示例#28
0
        public static void Start(string connectionString)
        {
            using (HeavyProfiler.Log("Start"))
                using (var initial = HeavyProfiler.Log("Initial"))
                {
                    StartParameters.IgnoredDatabaseMismatches = new List <Exception>();
                    StartParameters.IgnoredCodeErrors         = new List <Exception>();

                    string?logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log");

                    SchemaBuilder sb = new CustomSchemaBuilder {
                        LogDatabaseName = logDatabase, Tracer = initial
                    };
                    sb.Schema.Version          = typeof(Starter).Assembly.GetName().Version;
                    sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US");

                    MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>();
                    MixinDeclarations.Register <UserEntity, UserEmployeeMixin>();

                    OverrideAttributes(sb);

                    var detector = SqlServerVersionDetector.Detect(connectionString);
                    Connector.Default = new SqlConnector(connectionString, sb.Schema, detector !.Value);

                    CacheLogic.Start(sb);

                    DynamicLogicStarter.Start(sb);
                    DynamicLogic.CompileDynamicCode();

                    DynamicLogic.RegisterMixins();
                    DynamicLogic.BeforeSchema(sb);

                    TypeLogic.Start(sb);

                    OperationLogic.Start(sb);
                    ExceptionLogic.Start(sb);

                    MigrationLogic.Start(sb);

                    CultureInfoLogic.Start(sb);
                    FilePathEmbeddedLogic.Start(sb);
                    SmtpConfigurationLogic.Start(sb);
                    EmailLogic.Start(sb, () => Configuration.Value.Email, (et, target) => Configuration.Value.SmtpConfiguration);

                    AuthLogic.Start(sb, "System", null);

                    AuthLogic.StartAllModules(sb);
                    ResetPasswordRequestLogic.Start(sb);
                    UserTicketLogic.Start(sb);
                    SessionLogLogic.Start(sb);

                    ProcessLogic.Start(sb);
                    PackageLogic.Start(sb, packages: true, packageOperations: true);

                    SchedulerLogic.Start(sb);

                    QueryLogic.Start(sb);
                    UserQueryLogic.Start(sb);
                    UserQueryLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    UserQueryLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    ChartLogic.Start(sb);


                    UserChartLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    UserChartLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    DashboardLogic.Start(sb);
                    DashboardLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    DashboardLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    ViewLogLogic.Start(sb, new HashSet <Type> {
                        typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity)
                    });
                    DiffLogLogic.Start(sb, registerAll: true);
                    ExcelLogic.Start(sb, excelReport: true);
                    ToolbarLogic.Start(sb);

                    SMSLogic.Start(sb, null, () => Configuration.Value.Sms);
                    SMSLogic.RegisterPhoneNumberProvider <PersonEntity>(p => p.Phone, p => null);
                    SMSLogic.RegisterDataObjectProvider((PersonEntity p) => new { p.FirstName, p.LastName, p.Title, p.DateOfBirth });
                    SMSLogic.RegisterPhoneNumberProvider <CompanyEntity>(p => p.Phone, p => null);

                    NoteLogic.Start(sb, typeof(UserEntity), /*Note*/ typeof(OrderEntity));
                    AlertLogic.Start(sb, typeof(UserEntity), /*Alert*/ typeof(OrderEntity));
                    FileLogic.Start(sb);

                    TranslationLogic.Start(sb, countLocalizationHits: false);
                    TranslatedInstanceLogic.Start(sb, () => CultureInfo.GetCultureInfo("en"));

                    HelpLogic.Start(sb);
                    WordTemplateLogic.Start(sb);
                    MapLogic.Start(sb);
                    PredictorLogic.Start(sb, () => new FileTypeAlgorithm(f => new PrefixPair(Starter.Configuration.Value.Folders.PredictorModelFolder)));
                    PredictorLogic.RegisterAlgorithm(CNTKPredictorAlgorithm.NeuralNetwork, new CNTKNeuralNetworkPredictorAlgorithm());
                    PredictorLogic.RegisterPublication(ProductPredictorPublication.MonthlySales, new PublicationSettings(typeof(OrderEntity)));

                    RestLogLogic.Start(sb);
                    RestApiKeyLogic.Start(sb);

                    WorkflowLogicStarter.Start(sb, () => Starter.Configuration.Value.Workflow);

                    EmployeeLogic.Start(sb);
                    ProductLogic.Start(sb);
                    CustomerLogic.Start(sb);
                    OrderLogic.Start(sb);
                    ShipperLogic.Start(sb);

                    StartSouthwindConfiguration(sb);

                    TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.UserEntities, o => o.Employee == EmployeeEntity.Current);
                    TypeConditionLogic.Register <EmployeeEntity>(SouthwindGroup.UserEntities, e => EmployeeEntity.Current.Is(e));

                    TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.CurrentCustomer, o => o.Customer == CustomerEntity.Current);
                    TypeConditionLogic.Register <PersonEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);
                    TypeConditionLogic.Register <CompanyEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);

                    ProfilerLogic.Start(sb,
                                        timeTracker: true,
                                        heavyProfiler: true,
                                        overrideSessionTimeout: true);

                    DynamicLogic.StartDynamicModules(sb);
                    DynamicLogic.RegisterExceptionIfAny();

                    SetupCache(sb);

                    Schema.Current.OnSchemaCompleted();
                }
        }
 public EmailController(EmailLogic _emailMethods)
 {
     emailMethods = _emailMethods;
 }
示例#30
0
        public static void Start(string connectionString, bool isPostgres, bool includeDynamic = true, bool detectSqlVersion = true)
        {
            using (HeavyProfiler.Log("Start"))
                using (var initial = HeavyProfiler.Log("Initial"))
                {
                    StartParameters.IgnoredDatabaseMismatches = new List <Exception>();
                    StartParameters.IgnoredCodeErrors         = new List <Exception>();

                    string?logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log");

                    SchemaBuilder sb = new CustomSchemaBuilder {
                        LogDatabaseName = logDatabase, Tracer = initial
                    };
                    sb.Schema.Version          = typeof(Starter).Assembly.GetName().Version !;
                    sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US");

                    MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>();
                    MixinDeclarations.Register <UserEntity, UserEmployeeMixin>();
                    MixinDeclarations.Register <OrderDetailEmbedded, OrderDetailMixin>();
                    MixinDeclarations.Register <BigStringEmbedded, BigStringMixin>();

                    ConfigureBigString(sb);
                    OverrideAttributes(sb);

                    if (!isPostgres)
                    {
                        var sqlVersion = detectSqlVersion ? SqlServerVersionDetector.Detect(connectionString) : SqlServerVersion.AzureSQL;
                        Connector.Default = new SqlServerConnector(connectionString, sb.Schema, sqlVersion !.Value);
                    }
                    else
                    {
                        var postgreeVersion = detectSqlVersion ? PostgresVersionDetector.Detect(connectionString) : null;
                        Connector.Default = new PostgreSqlConnector(connectionString, sb.Schema, postgreeVersion);
                    }

                    CacheLogic.Start(sb, cacheInvalidator: sb.Settings.IsPostgres ? new PostgresCacheInvalidation() : null);

                    DynamicLogicStarter.Start(sb);
                    if (includeDynamic)//Dynamic
                    {
                        DynamicLogic.CompileDynamicCode();

                        DynamicLogic.RegisterMixins();
                        DynamicLogic.BeforeSchema(sb);
                    }//Dynamic

                    // Framework modules

                    TypeLogic.Start(sb);

                    OperationLogic.Start(sb);
                    ExceptionLogic.Start(sb);
                    QueryLogic.Start(sb);

                    // Extensions modules

                    MigrationLogic.Start(sb);

                    CultureInfoLogic.Start(sb);
                    FilePathEmbeddedLogic.Start(sb);
                    BigStringLogic.Start(sb);
                    EmailLogic.Start(sb, () => Configuration.Value.Email, (template, target, message) => Configuration.Value.EmailSender);

                    AuthLogic.Start(sb, "System", "Anonymous"); /* null); anonymous*/

                    AuthLogic.StartAllModules(sb);
                    ResetPasswordRequestLogic.Start(sb);
                    UserTicketLogic.Start(sb);
                    SessionLogLogic.Start(sb);
                    WebAuthnLogic.Start(sb, () => Configuration.Value.WebAuthn);

                    ProcessLogic.Start(sb);
                    PackageLogic.Start(sb, packages: true, packageOperations: true);

                    SchedulerLogic.Start(sb);
                    OmniboxLogic.Start(sb);

                    UserQueryLogic.Start(sb);
                    UserQueryLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    UserQueryLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    UserQueryLogic.RegisterTranslatableRoutes();

                    ChartLogic.Start(sb, googleMapsChartScripts: false /*requires Google Maps API key in ChartClient */);
                    UserChartLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    UserChartLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    UserChartLogic.RegisterTranslatableRoutes();

                    DashboardLogic.Start(sb);
                    DashboardLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    DashboardLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    DashboardLogic.RegisterTranslatableRoutes();
                    ViewLogLogic.Start(sb, new HashSet <Type> {
                        typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity)
                    });
                    DiffLogLogic.Start(sb, registerAll: true);
                    ExcelLogic.Start(sb, excelReport: true);
                    ToolbarLogic.Start(sb);
                    ToolbarLogic.RegisterTranslatableRoutes();
                    FileLogic.Start(sb);

                    TranslationLogic.Start(sb, countLocalizationHits: false);
                    TranslatedInstanceLogic.Start(sb, () => CultureInfo.GetCultureInfo("en"));

                    HelpLogic.Start(sb);
                    WordTemplateLogic.Start(sb);
                    MapLogic.Start(sb);
                    RestLogLogic.Start(sb);
                    RestApiKeyLogic.Start(sb);

                    WorkflowLogicStarter.Start(sb, () => Starter.Configuration.Value.Workflow);

                    ProfilerLogic.Start(sb,
                                        timeTracker: true,
                                        heavyProfiler: true,
                                        overrideSessionTimeout: true);

                    // RG2 modules

                    EmployeeLogic.Start(sb);
                    ProductLogic.Start(sb);
                    CustomerLogic.Start(sb);
                    OrderLogic.Start(sb);
                    ShipperLogic.Start(sb);
                    ItemLogic.Start(sb);
                    ItemCategoryLogic.Start(sb);

                    StartRG2Configuration(sb);

                    TypeConditionLogic.Register <OrderEntity>(RG2Group.UserEntities, o => o.Employee == EmployeeEntity.Current);
                    TypeConditionLogic.Register <EmployeeEntity>(RG2Group.UserEntities, e => EmployeeEntity.Current.Is(e));

                    TypeConditionLogic.Register <OrderEntity>(RG2Group.CurrentCustomer, o => o.Customer == CustomerEntity.Current);
                    TypeConditionLogic.Register <PersonEntity>(RG2Group.CurrentCustomer, o => o == CustomerEntity.Current);
                    TypeConditionLogic.Register <CompanyEntity>(RG2Group.CurrentCustomer, o => o == CustomerEntity.Current);

                    if (includeDynamic)//2
                    {
                        DynamicLogic.StartDynamicModules(sb);
                    }//2

                    SetupCache(sb);

                    Schema.Current.OnSchemaCompleted();

                    if (includeDynamic)//3
                    {
                        DynamicLogic.RegisterExceptionIfAny();
                    }//3
                }
        }