예제 #1
0
        public EmailUtilities ExecuteNonQuery(string storedProcedureName, params SqlParameter[] arrParam)
        {
            SqlParameter firstOutputParameter = null;
            SqlParameter charOutputParameter  = null;
            Int64        retVal   = 0;
            string       retvalue = "";
            var          objStaus = new EmailUtilities();
            var          lSqlCon  = new SqlConnection(MstrConnectionString);

            try
            {
                objStaus = OpenSQLConnection(lSqlCon, true);
                long       lngRowsaffected;
                SqlCommand lSqlComm;
                using (lSqlComm = new SqlCommand())
                {
                    lSqlComm.Connection     = lSqlCon;
                    lSqlComm.CommandText    = storedProcedureName;
                    lSqlComm.CommandType    = CommandType.StoredProcedure;
                    lSqlComm.CommandTimeout = 0;

                    if (arrParam != null)
                    {
                        foreach (SqlParameter param in arrParam)
                        {
                            lSqlComm.Parameters.Add(param);
                            if (firstOutputParameter == null && param.Direction == ParameterDirection.Output && param.SqlDbType == SqlDbType.BigInt)
                            {
                                firstOutputParameter = param;
                            }

                            if (charOutputParameter == null && param.Direction == ParameterDirection.Output && param.SqlDbType == SqlDbType.VarChar)
                            {
                                charOutputParameter = param;
                            }
                        }
                    }
                    lngRowsaffected = lSqlComm.ExecuteNonQuery();
                    if (firstOutputParameter != null)
                    {
                        retVal = (Int64)firstOutputParameter.Value;
                    }
                    if (charOutputParameter != null)
                    {
                        retvalue = charOutputParameter.Value.ToString();
                    }
                }

                objStaus = CloseSQLConnection(lSqlCon, true);
                objStaus.SetMessage("Success", "Data Updated", "Total no. of Rows affected " + lngRowsaffected,
                                    storedProcedureName, retvalue != "" ? retvalue : retVal.ToString());
            }
            catch (Exception exp)
            {
                _wslog.WriteLog("ERR", exp.Message);
                objStaus.SetMessage("Error", exp.Source, exp.Message, exp.StackTrace,
                                    retvalue != "" ? retvalue : retVal.ToString());
            }
            return(objStaus);
        }
예제 #2
0
        public EmailUtilities ExecuteNonQuery(string storedProcedureName)
        {
            Int64  retVal   = 0;
            string retvalue = "";
            var    objStaus = new EmailUtilities();
            var    lSqlCon  = new SqlConnection(MstrConnectionString);

            try
            {
                objStaus = OpenSQLConnection(lSqlCon, true);
                long       lngRowsaffected;
                SqlCommand lSqlComm;
                using (lSqlComm = new SqlCommand())
                {
                    lSqlComm.Connection     = lSqlCon;
                    lSqlComm.CommandText    = storedProcedureName;
                    lSqlComm.CommandType    = CommandType.StoredProcedure;
                    lSqlComm.CommandTimeout = 0;

                    lngRowsaffected = lSqlComm.ExecuteNonQuery();
                }

                objStaus = CloseSQLConnection(lSqlCon, true);
                objStaus.SetMessage("Success", storedProcedureName + " : Job Executed Successfully.", "Total no. of Rows affected " + lngRowsaffected,
                                    storedProcedureName, retvalue != "" ? retvalue : retVal.ToString());
            }
            catch (Exception exp)
            {
                _wslog.WriteLog("ERR", exp.Message);
                objStaus.SetMessage("Error", exp.Source, exp.Message, exp.StackTrace,
                                    retvalue != "" ? retvalue : retVal.ToString());
            }

            return(objStaus);
        }
예제 #3
0
        public EmailUtilities RetrieveDataTable_by_SQLCommand(SqlCommand cmd)
        {
            var popIrmsStatus = new EmailUtilities();

            try
            {
                using (var lDTable = new DataTable())
                {
                    var lSqlCon = new SqlConnection();
                    popIrmsStatus   = OpenSQLConnection(lSqlCon, true);
                    cmd.Connection  = lSqlCon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    var lDa = new SqlDataAdapter(cmd)
                    {
                        SelectCommand = { CommandTimeout = 0 }
                    };
                    lDa.Fill(lDTable);
                    lDa.Dispose();
                    popIrmsStatus = CloseSQLConnection(lSqlCon, true);
                    popIrmsStatus.SetMessage("Success", "Popultate DataTable", "DataTable has been populated successfully.", "DBA -> DBACCESS", "Populating SQL query", "Asked operation completed", lDTable);
                }
            }
            catch (Exception exp)
            {
                _wslog = new Log();
                var msg = exp.Message;
                _wslog.WriteLog("ERR", msg);
                popIrmsStatus.SetMessage("Error", exp.Source, exp.Message, exp.StackTrace);
            }
            return(popIrmsStatus);
        }
예제 #4
0
        public EmailUtilities SaveEmailDownloadDate(DateTime emailDownloadDate, string smptpFromAddress)
        {
            var resultemailDownload = new EmailUtilities();
            var sqlParametersList   = new List <SqlParameter>
            {
                new SqlParameter("@emailDownloadDate", emailDownloadDate)
                {
                    SqlDbType = SqlDbType.DateTime
                },
                new SqlParameter("@SmptpFromAddress", smptpFromAddress)
                {
                    SqlDbType = SqlDbType.NVarChar
                }
            };

            try
            {
                resultemailDownload = SaveData("usp_SaveEmailDownloadDate", sqlParametersList);
            }
            catch (Exception ex)
            {
                wslog.WriteLog("ERR", ex.Message.ToString());
                throw new ArgumentException(resultemailDownload.Description, "Error");
            }
            return(resultemailDownload);
        }
예제 #5
0
        public List <SystemTestResult> Execute(SystemTestCategories systemTestCategory)
        {
            var         results     = new List <SystemTestResult>();
            MailMessage mailMessage = new MailMessage()
            {
                Subject    = "Test email",
                Sender     = new MailAddress(Globals.EngineeringEmailAddress),
                From       = new MailAddress(Globals.EngineeringEmailAddress),
                Body       = "Test email",
                IsBodyHtml = false,
            };

            mailMessage.To.Add(new MailAddress(Globals.EngineeringEmailAddress));

            try
            {
                IEmailConnection emailConnection = EmailUtilities.GetEmailConnection(_applicationConfiguration);
                emailConnection.SendEmail(mailMessage);

                results.Add(new SystemTestResult(SystemTestResult.ResultTypes.Warning, _category, "Email test OK.", ""));  // Email passed to server, we don't know for certain that it will arrive
            }
            catch (System.Exception exception)
            {
                results.Add(new SystemTestResult(SystemTestResult.ResultTypes.Warning, _category, String.Format("Error sending test email: {0}. Notifications will not work. Please check the configuration.", exception.Message), ""));
            }
            return(results);
        }
예제 #6
0
        private static EmailUtilities GetData(string procedureName, List <SqlParameter> parameterList)
        {
            var emailStatusUtility = new EmailUtilities();
            var dbs   = new DataBaseServices();
            var wslog = new Log();

            try
            {
                var cmd = new SqlCommand(procedureName)
                {
                    CommandType = CommandType.StoredProcedure
                };
                if (parameterList != null)
                {
                    cmd.Parameters.AddRange(parameterList.ToArray());
                }
                emailStatusUtility = dbs.RetrieveDataTable_by_SQLCommand(cmd);
                if (emailStatusUtility.OperationStatus != "Success")
                {
                    wslog.WriteLog("ERR", emailStatusUtility.Description);
                    throw new ArgumentException(emailStatusUtility.Description, "Error");
                }
            }
            catch (Exception exp)
            {
                wslog.WriteLog("ERR", exp.Message.ToString());
            }
            return(emailStatusUtility);
        }
예제 #7
0
        public EmailUtilities CloseSQLConnection(SqlConnection sqlCon, bool dispose)
        {
            var closeIrmsStatus = new EmailUtilities();

            try
            {
                if (sqlCon.State != ConnectionState.Closed)
                {
                    sqlCon.Close();
                    if (dispose)
                    {
                        sqlCon.Dispose();
                    }
                }
                closeIrmsStatus.SetMessage("Success", "Connection closed", "Connection has been closed successfully.", "DBA -> DBACCESS", "Close established connection between Business Component and Database Server", "Asked operation completed");
            }
            catch (Exception ex)
            {
                _wslog = new Log();
                var msg = ex.Message + " " + ex.InnerException.Message + " Operation failed : Closing establised connection between Business Component and Database Server";
                _wslog.WriteLog("ERR", msg);
                closeIrmsStatus.SetMessage("Error", ex.Message, ex.InnerException.Message, "DBA -> DBACCESS", "Closing establised connection between Business Component and Database Server", "Operation failed");
            }
            return(closeIrmsStatus);
        }
예제 #8
0
        public EmailUtilities GetEmailInformation(InformationTypeEnum informationType, string ReceivingEMailID)
        {
            var resultemail       = new EmailUtilities();
            var sqlParametersList = new List <SqlParameter>
            {
                new SqlParameter("@informationType", informationType)
                {
                    SqlDbType = SqlDbType.VarChar
                },

                new SqlParameter("@receivingEMailID", ReceivingEMailID)
                {
                    SqlDbType = SqlDbType.VarChar
                }
            };

            try
            {
                resultemail = GetData("usp_GetEmailInformation", sqlParametersList);
            }
            catch (Exception ex)
            {
                wslog.WriteLog("ERR", ex.Message.ToString());
                throw new ArgumentException(resultemail.Description, "Error");
            }
            return(resultemail);
        }
예제 #9
0
        public EmailUtilities PopulateDataSet(string tsqlQuery)
        {
            var popIrmsStatus = new EmailUtilities();

            try
            {
                using (var lDSet = new DataSet())
                {
                    var lSqlCon = new SqlConnection();
                    popIrmsStatus = OpenSQLConnection(lSqlCon, true);
                    var lDa = new SqlDataAdapter(tsqlQuery, lSqlCon)
                    {
                        SelectCommand = { CommandTimeout = 0 }
                    };
                    lDa.Fill(lDSet);
                    lDa.Dispose();
                    popIrmsStatus = CloseSQLConnection(lSqlCon, true);
                    popIrmsStatus.SetMessage("Success", "Popultate Dataset", "Dataset has been populated successfully.", "DBA -> DBACCESS", "Populating SQL query", "Asked operation completed", lDSet);
                }
            }
            catch (Exception exp)
            {
                _wslog = new Log();
                var msg = exp.Message + " " + exp.InnerException.Message;
                _wslog.WriteLog("ERR", msg);
                popIrmsStatus.SetMessage("Error", exp.Source, exp.Message, exp.StackTrace, "");
            }

            return(popIrmsStatus);
        }
예제 #10
0
        public EmailUtilities InsertTotalEmailCountOnServer(long TotalEmailCount, long TotalEmailsAndMuidDiff, string ReceivingEMailID)
        {
            var resultemaillist   = new EmailUtilities();
            var sqlParametersList = new List <SqlParameter>
            {
                new SqlParameter("@TotalEmailCount", TotalEmailCount)
                {
                    SqlDbType = SqlDbType.BigInt
                },
                new SqlParameter("@TotalEmailsAndMuidDiff", TotalEmailsAndMuidDiff)
                {
                    SqlDbType = SqlDbType.BigInt
                },
                new SqlParameter("@ReceivingEMailID", ReceivingEMailID)
                {
                    SqlDbType = SqlDbType.VarChar
                }
            };

            try
            {
                resultemaillist = SaveData("InsertTotalEmailCountOnServer", sqlParametersList);
            }
            catch (Exception ex)
            {
                wslog.WriteLog("ERR", ex.Message.ToString());
                throw new ArgumentException(resultemaillist.Description, "Error");
            }
            return(resultemaillist);
        }
예제 #11
0
        public void ExecuteScheduledJob(string ProcedureName, int refreshType = 0)
        {
            var emailStatusUtility = new EmailUtilities();
            var dbs               = new DataBaseServices();
            var wslog             = new Log();
            var sqlParametersList = new List <SqlParameter>
            {
                new SqlParameter("@refreshtype", refreshType)
                {
                    SqlDbType = SqlDbType.NVarChar
                }
            };

            try
            {
                if (refreshType == 0)
                {
                    emailStatusUtility = dbs.ExecuteNonQuery(ProcedureName);
                }
                else
                {
                    emailStatusUtility = dbs.ExecuteNonQuery(ProcedureName, sqlParametersList.ToArray());
                }
                if (emailStatusUtility.OperationStatus != "Success")
                {
                    wslog.WriteLog("ERR", emailStatusUtility.Description);
                    throw new ArgumentException(emailStatusUtility.Description, "Error");
                }
            }
            catch (Exception exp)
            {
                wslog.WriteLog("ERR", exp.Message.ToString());
            }
        }
예제 #12
0
        public EmailUtilities InsertPop3MessageGuid(int ID, string ReceivingEMailID = "")
        {
            var resultemaillist   = new EmailUtilities();
            var sqlParametersList = new List <SqlParameter>
            {
                new SqlParameter("@uid", ID)
                {
                    SqlDbType = SqlDbType.BigInt
                },
                new SqlParameter("@receivingEMailID", ReceivingEMailID)
                {
                    SqlDbType = SqlDbType.NVarChar
                }
            };

            try
            {
                resultemaillist = SaveData("insertPOP3MessageGUID", sqlParametersList);
            }
            catch (Exception ex)
            {
                wslog.WriteLog("ERR", ex.Message.ToString());
                throw new ArgumentException(resultemaillist.Description, "Error");
            }
            return(resultemaillist);
        }
예제 #13
0
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.


            return(EmailUtilities.SendEmailAsync(message.Destination, message.Subject, message.Body));
        }
예제 #14
0
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            EmailUtilities.SendEmailAsync("*****@*****.**", "ssl li", "sslsslsl");

            return(View());
        }
        /// <summary>
        ///     Emails from from master.
        /// </summary>
        /// <param name = "variables">The variables lust of string to be replace ie Nate Priddy with {!from}.</param>
        /// <param name = "subject">The subject.</param>
        /// <param name = "to">To.</param>
        /// <param name = "cc">The cc.</param>
        /// <datetime>6/17/2011-10:16 AM</datetime>
        /// <author>
        ///     nate
        /// </author>
        public static void EmailFromFromMaster(IEnumerable <KeyValuePair <string, string> > variables, string subject, User to, IEnumerable <int> cc)
        {
            var html = GetHtmlTemplate();
            var text = "";

            EmailUtilities.Replacer(variables, ref html, ref text, ref subject);
            EmailUtilities.SendEmail(html, text, subject, to.FirstName + " " + to.LastName, to.Email, cc);
        }
예제 #16
0
        public override void EmailAlert()
        {
            string subject = "[MPAS Announcement] " + Title;
            string body    = content;

            foreach (Mentee m in Group.Mentees)
            {
                EmailUtilities.Email(m.StudentNumber + "@myuct.ac.za", subject, body);
            }
        }
예제 #17
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser newUser = new AppIdentityUser()
                {
                    Email       = model.Email,
                    ClassId     = model.ClassId,
                    UserName    = model.Email,
                    FirstName   = model.FirstName,
                    MiddleName  = model.MiddleName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber
                };
                var result = await _userManager.CreateAsync(user : newUser, password : model.Password);

                if (result.Succeeded)
                {
                    string code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

                    string linkConfirm = Url.Action(action: "VerifyEmail",
                                                    controller: "Account",
                                                    new { userId = newUser.Id, code = code },
                                                    Request.Scheme,
                                                    Request.Host.ToString());
                    EmailUtilities.SendConfirmEmail(newUser, linkConfirm);
                    if (model.RoleIds.Any() && model.RoleIds != null)
                    {
                        List <string> rolesName = new List <string>();
                        foreach (string roleId in model.RoleIds)
                        {
                            var role = await _roleManager.FindByIdAsync(roleId);

                            rolesName.Add(role.Name);
                        }
                        var addRoleResult = await _userManager.AddToRolesAsync(newUser, rolesName);

                        if (addRoleResult.Succeeded)
                        {
                            return(RedirectToAction(actionName: "Manage"));
                        }
                        foreach (var error in addRoleResult.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                        return(View(model));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(model));
        }
예제 #18
0
        public void EmailSearchMatch(string expr, string result)
        {
            var mock = new Mock <ILogger <EmailUtilities> >();
            ILogger <EmailUtilities> logger = mock.Object;

            var    _emailUtilitiy = new EmailUtilities(logger);
            string message        = "Ask Tractor MikeNew Order: #33477You’ve received the following order from Eric Weinmann:[Order #33477] (June 8, 2021)ProductQuantityPriceRhinoHide Tractor Canopy - Removable1$265.00Subtotal:$265.00Shipping:$56.00 via Shipping &amp; HandlingTax:$0.00Payment method:PayPalTotal:$321.00Order NotesThere are no notes for this order yet.Billing addressEric Weinmann5705 Fawnridge RdAuburn, CA [email protected] addressBob Weinmann217 N 19th StreetCanon City, CO 81212Tractor Mike and his family thank you for your order…it’s a pleasure doing business with you!";
            string orderPerson    = _emailUtilitiy.EmailSearch(message, expr);

            Assert.Equal(result, orderPerson);
        }
예제 #19
0
        public EmailUtilities OpenSQLConnection(SqlConnection sqlCon, bool useExistingConnection)
        {
            EmailUtilities openIrmsStatus = new EmailUtilities();

            try
            {
                if (sqlCon == null)
                {
                    sqlCon = new SqlConnection();
                }
                sqlCon.ConnectionString = MstrConnectionString;
                sqlCon.Open();
                switch (sqlCon.State)
                {
                case ConnectionState.Broken:
                    sqlCon.Close();
                    sqlCon.Open();
                    break;

                case ConnectionState.Closed:
                    sqlCon.Open();
                    break;

                case ConnectionState.Open:
                    if (!useExistingConnection)
                    {
                        sqlCon.Close();
                        sqlCon.Open();
                    }
                    break;

                default:
                    sqlCon.Open();
                    break;
                }
                openIrmsStatus.SetMessage("Success", "Connection established", "Connection has been established successfully.", "DBA -> DBACCESS", "Establish connection between Business Component and Database Server", "Asked operation completed");
            }
            catch (Exception ex)
            {
                _wslog = new Log();
                var msg = ex.Message + " " + ex.InnerException.Message + " Operation failed : Establish connection between Business Component and Database Server";
                _wslog.WriteLog("ERR", msg);
                openIrmsStatus.SetMessage("Error", ex.Message, ex.InnerException.Message, "DBA -> DBACCESS", "Establish connection between Business Component and Database Server", "Operation failed");
            }
            return(openIrmsStatus);
        }
        public int RegisterPerson(Person p)
        {
            int result = da.AddPerson(p);

            if (result == 1)
            {
                EmailUtilities.SendEmail(ConfigurationManager.AppSettings["EmailUsername"],
                                         p.Email,
                                         "Registration to Speakcore Conference",
                                         $"<p>Dear {p.FirstName},</p><p></p>" +
                                         "<p>On behalf of Pharma Company, Inc., thank you for registering for the Speaker Training Meeting.</p><p></p>" +
                                         "<p>You will receive a formal confirmatiomn email within the next 3 to 5 business days, including " +
                                         "information for booking your travel.</p><p></p>" +
                                         "<p>Regards,</p><p>The SpeakCore Team</p>");
            }

            return(result); // What if registration succeeded and email send failed?
        }
예제 #21
0
        public EmailUtilities AddAutoResponseRecord(string FromMailID, string ReceivingMailID, string Subject, string ThreadID, DateTime MessageCreatedDate, string AutoResponseID)
        {
            var AutoRecord        = new EmailUtilities();
            var sqlParametersList = new List <SqlParameter>
            {
                new SqlParameter("@FromMailID", FromMailID)
                {
                    SqlDbType = SqlDbType.NVarChar
                },
                new SqlParameter("@ReceivingMailID", ReceivingMailID)
                {
                    SqlDbType = SqlDbType.NVarChar
                },
                new SqlParameter("@Subject", Subject)
                {
                    SqlDbType = SqlDbType.NVarChar
                },
                new SqlParameter("@ThreadID", ThreadID)
                {
                    SqlDbType = SqlDbType.NVarChar
                },
                new SqlParameter("@MessageCreatedDate", MessageCreatedDate)
                {
                    SqlDbType = SqlDbType.DateTime
                },
                new SqlParameter("@AutoResponseID", AutoResponseID)
                {
                    SqlDbType = SqlDbType.NVarChar
                }
            };

            try
            {
                AutoRecord = SaveData("[dbo].[usp_AddAutoResponseID]", sqlParametersList);
            }
            catch (Exception exp)
            {
                wslog.WriteLog("ERR", exp.Message.ToString());
                throw new ArgumentException(AutoRecord.Description, "Error");
            }
            return(AutoRecord);
        }
예제 #22
0
        public EmailUtilities SaveData(string procedureName, List <SqlParameter> sqlparameterList)
        {
            var emailStatusUtility = new EmailUtilities();
            var dbs   = new DataBaseServices();
            var wslog = new Log();

            try
            {
                emailStatusUtility = dbs.ExecuteNonQuery(procedureName, sqlparameterList.ToArray());
                if (emailStatusUtility.OperationStatus != "Success")
                {
                    wslog.WriteLog("ERR", emailStatusUtility.Description);
                    throw new ArgumentException(emailStatusUtility.Description, "Error");
                }
            }
            catch (Exception exp)
            {
                wslog.WriteLog("ERR", exp.Message.ToString());
            }
            return(emailStatusUtility);
        }
예제 #23
0
        public async Task <IActionResult> Register(RegisterAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser newUser = new AppIdentityUser()
                {
                    UserName    = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    MiddleName  = model.MiddleName,
                    Email       = model.Email,
                    PhoneNumber = model.PhoneNumber,
                    ClassId     = model.ClassId
                };
                var result = await _userManager.CreateAsync(newUser, model.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user : newUser, role : "Normal User");

                    string code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

                    string linkConfirm = Url.Action(action: "VerifyEmail",
                                                    controller: "Account",
                                                    new { userId = newUser.Id, code = code },
                                                    Request.Scheme,
                                                    Request.Host.ToString());
                    EmailUtilities.SendConfirmEmail(newUser, linkConfirm);
                    return(RedirectToAction(actionName: "SentConfirmEmail"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            model.Classes = _context.Classes.Select(e => e).ToList();
            return(View(model));
        }
예제 #24
0
        // Technical Debt: should be named ForgottenMail

        public override object Execute(Content content, params object[] parameters)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            // Load user if we can
            string useremail = parameters[0] as string;

            // Check if caller user is in the proper group and gets target company
            // User must have been a member of Security Editors of the given company or a system administrator
            if (!string.IsNullOrWhiteSpace(useremail))
            {
                Content loadedUserContent = null;
                using (new SystemAccount())
                {
                    loadedUserContent = Content.All.DisableAutofilters().Where(u => u.Type("RorWebUser") && (string)u["Email"] == useremail).FirstOrDefault();
                    if (loadedUserContent != null)
                    {
                        //loadedUserContent["Enabled"] = false;
                        string confirmationGuid = Guid.NewGuid().ToString();
                        loadedUserContent["PasswordResetGuid"]      = confirmationGuid;
                        loadedUserContent["RequestChangePasswDate"] = DateTime.UtcNow;
                        loadedUserContent.Save();

                        string fromEmail = Settings.GetValue <string>(EmailSettingsName, "EmailNotificationFrom");
                        var    addresses = Settings.GetValue <string[]>(EmailSettingsName, "EmailNotificationTo");
                        string subject   = Settings.GetValue <string>(EmailSettingsName, "EmailChangePassSubject");
                        // Technical Debt: guid msut be injected to email body
                        string emailTemplatePath         = Settings.GetValue <string>(EmailSettingsName, "EmailForgottenBodyTemplatePath");
                        string emailTemplatePathForAdmin = Settings.GetValue <string>(EmailSettingsName, "EmailForgottenBodyTemplatePathForAdmin");
                        //emailTemplatePath = "/Root/Skins/rorweb/Templates/EmailTemplates/ConfirmationMail.html";
                        Node   emailTemplateNode         = Node.LoadNodeByIdOrPath(emailTemplatePath);
                        Node   emailTemplateNodeForAdmin = Node.LoadNodeByIdOrPath(emailTemplatePathForAdmin);
                        string emailTemplate             = emailTemplateNode?.GetBinaryToString();
                        string emailTemplateForAdmin     = emailTemplateNodeForAdmin?.GetBinaryToString();
                        emailTemplate         = emailTemplate.Replace("{User.UserName}", loadedUserContent["LoginName"] as string);
                        emailTemplate         = emailTemplate.Replace("{User.DisplayName}", loadedUserContent["DisplayName"] as string);
                        emailTemplate         = emailTemplate.Replace("{User.ConfirmationGuid}", loadedUserContent["PasswordResetGuid"] as string);
                        emailTemplate         = emailTemplate.Replace("{Site.Url}", HttpContext.Current.Request.Url.Host);
                        emailTemplateForAdmin = emailTemplateForAdmin.Replace("{User.UserName}", loadedUserContent["LoginName"] as string);
                        emailTemplateForAdmin = emailTemplateForAdmin.Replace("{User.ConfirmationGuid}", loadedUserContent["PasswordResetGuid"] as string);
                        emailTemplateForAdmin = emailTemplateForAdmin.Replace("{Site.Url}", HttpContext.Current.Request.Url.Host);

                        string toEmail = loadedUserContent["Email"] as string;
                        if (string.IsNullOrWhiteSpace(toEmail))
                        {
                            toEmail = "*****@*****.**";
                            subject = subject + " (no email!)";
                        }


                        Parallel.ForEach(addresses, x =>
                        {
                            //bool validUser = SenseNet.ContentRepository.Content.All.DisableAutofilters().DisableLifespan().Any(c => c.TypeIs("User") && (string)c["Email"] == x.UserEmail);
                            //if (validUser)
                            {
                                EmailUtilities.SendEmail(
                                    new System.Net.Mail.MailAddress(fromEmail, fromEmail),
                                    x,
                                    null,
                                    subject,
                                    emailTemplateForAdmin);
                            }
                        });

                        EmailUtilities.SendEmail(
                            new System.Net.Mail.MailAddress(fromEmail, fromEmail),
                            toEmail,
                            null,
                            subject,
                            emailTemplate);
                    }
                    else
                    {
                        // usser does not exist, but no problem
                    }
                }
            }
            else
            {
                throw new Exception("Valamit elfelejtettel!");
            }

            return(JsonConvert.SerializeObject(result, new KeyValuePairConverter()));;
        }
예제 #25
0
 public Task SendAsync(IdentityMessage message)
 {
     // E-posta göndermek için e-posta hizmetinizi buraya bağlayın.
     return(EmailUtilities.SendEmailAsync(message.Destination, message.Subject, message.Body));
 }
예제 #26
0
        public async Task <IActionResult> Edit(EditAccountViewModel model)
        {
            AppIdentityUser user = await _userManager.FindByIdAsync(model.UserId);

            if (user == null)
            {
                return(NotFound());
            }
            user.FirstName  = model.FirstName;
            user.MiddleName = model.MiddleName;
            user.LastName   = model.LastName;
            user.ClassId    = model.ClassId;
            model.Classes   = _context.Classes.Select(e => e).ToList();
            if (String.IsNullOrEmpty(model.PhoneNumber))
            {
                model.PhoneNumber = user.PhoneNumber;
            }
            if (String.IsNullOrEmpty(model.Email))
            {
                model.Email = user.Email;
            }
            var compareUser = await _userManager.FindByEmailAsync(model.Email);

            if (compareUser != null && compareUser.Id != user.Id)
            {
                ModelState.AddModelError("", errorMessage: "Email is used by another account");

                return(View(model));
            }
            //when change email must confirm link in old email
            if (user.Email != model.Email)
            {
                string tokenChangeEmail = await _userManager.GenerateChangeEmailTokenAsync(user, model.Email);

                string linkConfirm = Url.Action(action: "VerifyEmailChange",
                                                controller: "Account",
                                                new { userId = user.Id, newEmail = model.Email, code = tokenChangeEmail },
                                                Request.Scheme,
                                                Request.Host.ToString());
                EmailUtilities.SendConfirmChangeEmail(user, linkConfirm);
                ViewData["Sendmail"] = "We have sent an email to confirm your action";
            }
            //when change phone number must confirm link in mail
            if (model.PhoneNumber != user.PhoneNumber && !String.IsNullOrEmpty(model.PhoneNumber))
            {
                string tokenPhoneNumber = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);

                string linkConfirm = Url.Action(action: "VerifyPhoneNumberChange",
                                                controller: "Account",
                                                new { userId = user.Id, newPhoneNumber = model.PhoneNumber, code = tokenPhoneNumber },
                                                Request.Scheme,
                                                Request.Host.ToString());
                EmailUtilities.SendConfirmChangePhoneNumber(user, linkConfirm);
                ViewData["Sendmail"] = "We have sent an email to confirm your action";
            }
            if (String.IsNullOrEmpty(model.OldPassword) && !String.IsNullOrEmpty(model.NewPassword))
            {
                ModelState.AddModelError("", errorMessage: "If you want to change password, please enter old password correctly");
                return(View(model));
            }
            bool check = await _userManager.CheckPasswordAsync(user, model.OldPassword);

            bool check1 = !String.IsNullOrEmpty(model.NewPassword);

            if (await _userManager.CheckPasswordAsync(user, model.OldPassword) && !String.IsNullOrEmpty(model.NewPassword))
            {
                var resultChangePass = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);

                if (resultChangePass.Succeeded)
                {
                    await _signInManager.SignOutAsync();

                    return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                }
                foreach (var error in resultChangePass.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
                return(View(model));
            }
            if (await _userManager.CheckPasswordAsync(user, model.OldPassword) == false && !String.IsNullOrEmpty(model.NewPassword))
            {
                ModelState.AddModelError("", "Wrong current password");
                return(View(model));
            }
            var resultEditUser = await _userManager.UpdateAsync(user);

            if (resultEditUser.Succeeded)
            {
                return(RedirectToAction(actionName: "Profile", new { userId = model.UserId }));
            }
            foreach (var error in resultEditUser.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }
            return(View(model));
        }
예제 #27
0
    private void SendNotificationsConcerso()
    {
        try
        {
            string nombre  = "";
            string email   = "";
            string mensaje = "";
            if (!string.IsNullOrEmpty(nombretxt.Text))
            {
                nombre = nombretxt.Text;
            }
            else
            {
                errorNombre.Visible = true;
                return;
            }

            if (!string.IsNullOrEmpty(Emailtxt.Text))
            {
                email = Emailtxt.Text;
            }
            else
            {
                errorEmail.Visible = true;
                return;
            }


            if (!string.IsNullOrEmpty(mensajeTxt.Text))
            {
                mensaje = mensajeTxt.Text;
            }
            else
            {
                errorMensaje.Visible = true;
                return;
            }

            string        text    = System.IO.File.ReadAllText(Server.MapPath("~/Email/EnvioEmail.html"));
            StringBuilder message = new StringBuilder(text);
            message.Replace("<%Name%>", nombre);

            message.Replace("<%mensaje%>", mensaje);

            string root = HttpContext.Current.Request.Url.Scheme + "://" +
                          HttpContext.Current.Request.Url.Authority +
                          HttpContext.Current.Request.ApplicationPath;

            string link = root + "/Conserso.aspx";
            message.Replace("<%Link%>", link);

            //Notificar al cliente
            EmailUtilities.SendEmail(email, "Conserso - Consulta cliente", message.ToString());
            mensajeTxt.Text = "";
            nombretxt.Text  = "";
            Emailtxt.Text   = "";
        }
        catch (Exception ex)
        {
            throw ex;
            //log.Error("Error sending email to client", ex);
        }
    }
예제 #28
0
 public Task SendAsync(IdentityMessage message)
 {
     return(EmailUtilities.SendMailAsync(message.Destination, message.Subject, message.Body));
 }
예제 #29
0
        public async Task <IActionResult> Edit(EditUserViewModel model)
        {
            AppIdentityUser user = await _userManager.FindByIdAsync(model.UserId);

            if (user == null)
            {
                return(NotFound());
            }
            user.FirstName   = model.FirstName;
            user.MiddleName  = model.MiddleName;
            user.LastName    = model.LastName;
            user.ClassId     = model.ClassId;
            user.PhoneNumber = model.PhoneNumber;
            //when change email must confirm link in old email
            if (user.Email != model.Email)
            {
                string tokenChangeEmail = await _userManager.GenerateChangeEmailTokenAsync(user, model.Email);

                string linkConfirm = Url.Action(action: "VerifyEmailChange",
                                                controller: "Account",
                                                new { userId = user.Id, newEmail = model.Email, code = tokenChangeEmail },
                                                Request.Scheme,
                                                Request.Host.ToString());
                EmailUtilities.SendConfirmEmail(user, linkConfirm);
            }
            if (model.RoleIds.Any() && model.RoleIds != null)
            {
                List <string> rolesName = new List <string>();
                foreach (string roleId in model.RoleIds)
                {
                    var role = await _roleManager.FindByIdAsync(roleId);

                    rolesName.Add(role.Name);
                }
                IEnumerable <string> userRolesName = await _userManager.GetRolesAsync(user);

                if (userRolesName.Any() && userRolesName != null)
                {
                    var removeRoleResult = await _userManager.RemoveFromRolesAsync(user, userRolesName);

                    if (!removeRoleResult.Succeeded)
                    {
                        foreach (var error in removeRoleResult.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
                var addRoleResult = await _userManager.AddToRolesAsync(user, rolesName);

                if (addRoleResult.Succeeded)
                {
                    return(RedirectToAction(actionName: "Manage"));
                }
                foreach (var error in addRoleResult.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
                return(View(model));
            }
            var resultEditUser = await _userManager.UpdateAsync(user);

            if (resultEditUser.Succeeded)
            {
                return(RedirectToAction(actionName: "Manage"));
            }
            foreach (var error in resultEditUser.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }
            return(View(model));
        }
예제 #30
0
    protected void ResetButton_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        string emailAddress = EmailTextBox.Text;

        string userName = Membership.GetUserNameByEmail(emailAddress);

        if (String.IsNullOrEmpty(userName))
        {
            // This should not have happened.
            //log.Error("Failed to find the specified email address in our system: " + emailAddress);
            ErrorLabel.Text      = Resources.LoginGlossary.MensajeUsuarioNoEncontrado;
            ErrorLabel.ForeColor = System.Drawing.Color.Red;
            return;
        }

        string newPass = "";

        try
        {
            MembershipUser user = Membership.GetUser(userName, false);
            if (user == null)
            {
                ErrorLabel.Text      = Resources.LoginGlossary.MensajeUsuarioNoEncontrado;
                ErrorLabel.ForeColor = System.Drawing.Color.Red;
                return;
            }

            user.IsApproved = true;
            newPass         = user.ResetPassword();

            if (string.IsNullOrEmpty(newPass))
            {
                log.Error("No se genero la nueva contraseña.");
                ErrorLabel.Text      = Resources.LoginGlossary.MensajeErrorContraseñaVacia;
                ErrorLabel.ForeColor = System.Drawing.Color.Red;
                return;
            }

            Membership.UpdateUser(user);
        }
        catch
        {
            ErrorLabel.Text      = "No se pudo cambiar la constraseña del usuario. Comuníquese con el Administrador del Sistema.";
            ErrorLabel.ForeColor = System.Drawing.Color.Red;
            return;
        }

        StringBuilder mailText = new StringBuilder();

        try
        {
            // Ok.  Get the template for the email
            string emailFile = HttpContext.Current.Server.MapPath(Resources.Files.NewPasswordFileLocation);
            using (System.IO.StreamReader sr = System.IO.File.OpenText(emailFile))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    mailText.Append(s);
                }
            }
        }
        catch
        {
            ErrorLabel.Text      = Resources.LoginGlossary.MensajeNoEnvioMail;
            ErrorLabel.ForeColor = System.Drawing.Color.Red;
            return;
        }

        mailText.Replace("{UserName}", userName);
        mailText.Replace("{Password}", newPass);

        try
        {
            EmailUtilities.SendEmail(emailAddress, Configuration.GetConfirmationPasswordSubject(), mailText.ToString());
        }
        catch (Exception q)
        {
            //log.Error("Failed to send email with validation code for user " + userName, q);
            ErrorLabel.Text      = Resources.LoginGlossary.MensajeNoEnvioMail + ": " + q.Message;;
            ErrorLabel.ForeColor = System.Drawing.Color.Red;
            return;
        }

        ErrorLabel.Text      = Resources.LoginGlossary.MensajeEnvioMail;
        ErrorLabel.ForeColor = System.Drawing.Color.Black;

        Response.Redirect("~/Authentication/ConfirmarReseteo.aspx");
    }