public bool SendMail(MailSettingModel mail, UserViewModel user) { var settings = _uof.SettingsRepository.GetAll(r => r.IsActive && r.TenantId == user.Company.TenantId && r.CompanyId == user.CompanyId).ToList(); if (settings != null) { if (settings.Any(r => r.Key == "SMTP_From") && !string.IsNullOrEmpty(settings.Find(r => r.Key == "SMTP_From").Value)) { mail.SMTP_From = settings.Find(r => r.Key == "SMTP_From")?.Value; } if (settings.Any(r => r.Key == "SMTP_Host") && !string.IsNullOrEmpty(settings.Find(r => r.Key == "SMTP_Host").Value)) { mail.SMTP_Host = settings.Find(r => r.Key == "SMTP_Host")?.Value; } if (settings.Any(r => r.Key == "SMTP_Port") && !string.IsNullOrEmpty(settings.Find(r => r.Key == "SMTP_Port").Value)) { mail.SMTP_Port = Int32.Parse(settings.Find(r => r.Key == "SMTP_Port").Value); } if (settings.Any(r => r.Key == "SMTP_Username") && !string.IsNullOrEmpty(settings.Find(r => r.Key == "SMTP_Username").Value)) { mail.SMTP_Username = settings.Find(r => r.Key == "SMTP_Username").Value; } if (settings.Any(r => r.Key == "SMTP_Password") && !string.IsNullOrEmpty(settings.Find(r => r.Key == "SMTP_Password").Value)) { mail.SMTP_Password = settings.Find(r => r.Key == "SMTP_Password").Value; } } return(EMailService.SendEmail(mail)); }
public JsonResult GetSMTPInfo() { var eMailService = new EMailService(); var smtpClientConfig = eMailService.SmtpClient; var smtpMailAddressConfig = eMailService.MailMessage; var smtpInfo = new SMTPInfoViewModel(); if (smtpClientConfig.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { smtpInfo.DeliveryMethod = "Directory"; smtpInfo.Directory = smtpClientConfig.PickupDirectoryLocation; } else { smtpInfo.DeliveryMethod = "SMTP Server"; smtpInfo.Host = smtpClientConfig.Host; smtpInfo.Port = smtpClientConfig.Port; smtpInfo.EnableSsl = smtpClientConfig.EnableSsl; smtpInfo.CredentialUsername = ((NetworkCredential)smtpClientConfig.Credentials).UserName; } smtpInfo.DefaultFromAddress = smtpMailAddressConfig.From.Address != null ? smtpMailAddressConfig.From.Address : string.Empty; return(Json(smtpInfo, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Link to page /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e) { if ("Sort".Equals(e.CommandName)) { return; } if (e.CommandArgument.ToString() != "") { int id = Convert.ToInt32(e.CommandArgument); if (e.CommandName == "Select") { EditUser(id); } if (e.CommandName == "DeleteUser") { User user = UserService.GetUser(id); if (user != null) { UserService.DeleteUser(user); LoadUsers(); } } if (e.CommandName == "ChangeStatus") { User user = UserService.GetUser(id); if (user != null) { user.IsDisabled = !user.IsDisabled; UserService.UpdateUser(user); LoadUsers(); } } if (e.CommandName == "ResetPassword") { User user = UserService.GetUser(id); string newPassword = UserService.NewPassword(user); user.IsApproved = false; user.IsDisabled = false; UserService.SaveUser(user); EMailService.SendEmail("Sterling Scholar password reset request", UserService.FormatTemplate(System.Web.HttpContext.Current.Server.MapPath("~/") + "/assets/PasswordResetTemplate.html", user), user.EMail, UserService.AdminEmailAddress, null); } if (e.CommandName == "Unlock") { User user = UserService.GetUser(id); UserService.UnlockUser(user); EMailService.SendEmail("Sterling Scholar Account unlock request", UserService.FormatTemplate(System.Web.HttpContext.Current.Server.MapPath("~/") + "/assets/UnlockTemplate.html", user), user.EMail, UserService.AdminEmailAddress, null); } //if (e.CommandName.Equals("ViewPortfolio")) //{ // StringBuilder sb = new StringBuilder(); // sb.Append("<script language=JavaScript id='openit'>"); // sb.Append("window.open('../ReportView.aspx?report=profile&id=" + e.CommandArgument + "', '', '');"); // sb.Append("</script>"); // if (!ClientScript.IsStartupScriptRegistered("openit")) // { // ClientScript.RegisterStartupScript(this.GetType(), "openit", sb.ToString()); // } //} } }
public void SendMailSchedule() { log.Info("SendMailSchedule start !!" + DateTime.Now); List <SYS_MESSAGE> lst = getTask(); EMailService mailservice = new EMailService(); foreach (SYS_MESSAGE m in lst) { using (var context = new TopmepEntities()) { try { log.Info("send msg=" + m.MSG_ID); if (mailservice.SendMailByGmail(m.FROM_ADDRESS, m.DISPLAY_NAME, m.MAIL_LIST, m.BCC_MAIL_LIST, m.SUBJECT, m.MSG_BODY, null)) { SYS_MESSAGE doneM = context.SYS_MESSAGE.Find(m.MSG_ID); doneM.STATUS = "DONE"; context.SaveChanges(); } } catch (Exception ex) { log.Error(ex.Message + ":" + ex.StackTrace); } } return; } }
ViewModelBase createModel() { var model = new ViewModelBase(); PrepareViewModel(model, EvolutionResources.bnrEMailQueue + " - " + EMailService.GetQueueCount().ToString() + " item(s)"); return(model); }
public CommonController() { _iPatientService = new MMCService.PatientService.PatientServiceClient(); _iCommonService = new MMCService.CommonService.CommonServiceClient(); _storageService = new StorageService(); _mailService = new EMailService(); _iEmailRecordAttachmentService = new MMCService.EmailRecordAttachmentService.EmailRecordAttachmentServiceClient(); }
public InternalBodyArchitectService(ISession session) { Session = session; EMailService = new EMailService(); PushNotificationService = new NotReadedMessagesPushNotification(); configuration = new ServiceConfiguration(); configuration.Payments = InternalBodyArchitectService.PaymentsManager; configuration.MethodInvoker = new ThreadPoolMethodInvoker(); }
public async Task <JsonResult> SendCode(string id) { try { var userStore = NewUserStore(); var user = await userStore.FindByIdAsync(id); if (user == null) { return(Json(new ResponseData() { message = "Kullanıcı bulunamnadu", success = false })); } if (user.EmailConfirmed) { return(Json(new ResponseData() { message = "Kullanıcı zaten e postasını onaylamıs", success = false })); } user.ActivationCode = StringHelpers.GetCode(); await userStore.UpdateAsync(user); userStore.Context.SaveChanges(); string SiteUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); var emailService = new EMailService(); var body = $"Merhaba <b>{user.Name} {user.Surname}</b><br>Hesabınızı aktif etmek için aşadıdaki linke tıklayınız<br> <a href='{SiteUrl}/account/activation?code={user.ActivationCode}' >Aktivasyon Linki </a> "; await emailService.SendAsync(new IdentityMessage() { Body = body, Subject = "Sitemize hoşgeldiniz" }, user.Email); return(Json(new ResponseData() { message = "Kullanıcıya yeni aktivasyon maili gönderildi", success = false })); } catch (Exception ex) { return(Json(new ResponseData() { message = $"Bir hata oluştu: {ex.Message}", success = false })); } }
public NotificationController() { _intakeService = new MMCService.IntakeService.IntakeServiceClient(); _iPreparationService = new MMCService.PreparationService.PreparationServiceClient(); _iNotificationService = new MMCService.NotificationService.NotificationServiceClient(); _iCommonService = new MMCService.CommonService.CommonServiceClient(); _iUserService = new MMCService.UserService.UserServiceClient(); _storageService = new StorageService(); _mailService = new EMailService(); _iCommonService = new MMCService.CommonService.CommonServiceClient(); _iEmailRecordAttachmentService = new MMCService.EmailRecordAttachmentService.EmailRecordAttachmentServiceClient(); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { EMailService service = new EMailService(); await service.SendMessage(EMail.From, EMail.Name, EMail.MsgContent); TempData["email"] = "Ihre Nachricht wurde gesendet"; return(RedirectToPage("./Kontakt")); } return(Page()); }
public ActionResult Delete(int index, int id) { var model = new EMailQueueListModel(); model.GridIndex = index; try { EMailService.DeleteEMailQueue(id); } catch (Exception e1) { model.Error.SetError(e1); } return(Json(model, JsonRequestBehavior.AllowGet)); }
public IMRController() { _iIMRService = new MMCService.IMRService.IMRServiceClient(); _iPreparationService = new MMCService.PreparationService.PreparationServiceClient(); _intakeService = new MMCService.IntakeService.IntakeServiceClient(); _storageService = new StorageService(); _mailService = new EMailService(); _iCommonService = new MMCService.CommonService.CommonServiceClient(); _pdfSplitterService = new PDFSplitterService(); _iUserService = new MMCService.UserService.UserServiceClient(); _iEmailRecordAttachmentService = new MMCService.EmailRecordAttachmentService.EmailRecordAttachmentServiceClient(); }
public async Task <IActionResult> RegisterVoter(InVoterRegisterDTO inVoterRegisterDto) { if (inVoterRegisterDto.Password != inVoterRegisterDto.ConfirmPassword) { return(BadRequest()); } var g = Guid.NewGuid(); var username = Convert.ToBase64String(g.ToByteArray()).Replace("=", string.Empty) .Replace("+", String.Empty).Replace("/", String.Empty); var userDetail = new UserDetail() { CNP = inVoterRegisterDto.CNP, EncryptedPrivateKey = inVoterRegisterDto.EncryptedPrivateKey, PublicKey = inVoterRegisterDto.PublicKey, FirstName = inVoterRegisterDto.FirstName, LastName = inVoterRegisterDto.LastName, Number = inVoterRegisterDto.Number, Series = inVoterRegisterDto.Series }; var user = new User() { Email = inVoterRegisterDto.Email, PhoneNumber = inVoterRegisterDto.Phone, }; user.UserDetail = userDetail; user.UserName = username; var result = await _userManager.CreateAsync(user, inVoterRegisterDto.Password); if (!result.Succeeded) { return(Unauthorized()); } var emailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); var emailHtml = await System.IO.File.ReadAllTextAsync("wwwroot/confirmEmailToken.html"); emailHtml = emailHtml.Replace("{BaseUrl}", "http://localhost:8080/#/verify") .Replace("{EmailToken}", emailToken) .Replace("{UserName}", username); var emailSuccess = await EMailService.SendEmail(inVoterRegisterDto.Email, "EVoting Username and Confirm Email", emailHtml); return(Ok(new BaseResponseDTO <string>() { Success = true, Message = "User registered successfully! Please also verify your email.", Result = username })); }
public async Task <ActionResult> RecoverPassword(RecoverPasswordViewModel model)//RecoverPasswordViewModel içindekileri model nesnemle ulaşabilirim. { try { var userStore = NewUserStore(); var userManager = NewUserManager(); var user = await userStore.FindByEmailAsync(model.Email); if (user == null) { ModelState.AddModelError(string.Empty, $"{model.Email} mail adresine kayıtlı bir üyeliğe erişilemedi"); return(View(model)); } var newPassword = StringHelpers.GetCode().Substring(0, 6);//Yeni şifre veriyoruz ilk 6 hanesini await userStore.SetPasswordHashAsync(user, userManager.PasswordHasher.HashPassword(newPassword)); var result = userStore.Context.SaveChanges(); if (result == 0) { TempData["Model"] = new ErrorViewModel() { Text = $"Bir hata oluştu", ActionName = "RecoverPassword", ControllerName = "Account", ErrorCode = 500 }; return(RedirectToAction("Error", "Home")); } var emailService = new EMailService(); var body = $"Merhaba <b>{user.Name} {user.Surname}</b><br>Hesabınızın parolası sıfırlanmıştır<br> Yeni parolanız: <b>{newPassword}</b> <p>Yukarıdaki parolayı kullanarak sistemize giriş yapabilirsiniz.</p>"; emailService.Send(new IdentityMessage() { Body = body, Subject = $"{user.UserName} Şifre Kurtarma" }, user.Email); } catch (Exception ex) { TempData["Model"] = new ErrorViewModel() { Text = $"Bir hata oluştu {ex.Message}", ActionName = "RecoverPassword", ControllerName = "Account", ErrorCode = 500 }; return(RedirectToAction("Error", "Home")); } return(View()); }
private void SavePortfolio() { UserInput input = null; Portfolio p = PortfolioService.GetPortfolio(PortfolioId); if (null != p) { input = UserService.GetUserProfile(p.User.Id); } else { input = new UserInput(); } input.FullName = txtFullName.Text; input.EMail = txtEmail.Text; input.Comment = txtComment.Text; input.Phone = txtPhone.Text; input.Role = RoleType.Nominee; input.School = GetSchool(); input.Category = CategoryService.GetCategory(input.School.Area.Region, ddlCategory.SelectedValue); MembershipCreateStatus status = UserService.AddNewUser(input); if (status == MembershipCreateStatus.Success) { User user = UserService.GetUser(input.EMail); Portfolio portfolio = PortfolioService.GetPortfolioByUser(user); portfolio.Parents = txtParents.Text; portfolio.Address = txtAddress.Text; portfolio.City = txtCity.Text; portfolio.Zip = txtZip.Text; portfolio.State = ddlState.SelectedValue; portfolio.Sex = (Sexes)Enum.Parse(typeof(Sexes), ddlGender.SelectedValue.ToString()); if (ddlStatus.Enabled) { portfolio.Status = (Status)Enum.Parse(typeof(Status), ddlStatus.SelectedValue); } PortfolioService.Save(portfolio); SaveTestScores(portfolio); if (input.Id <= 0) { EMailService.SendEmail("Sterling Scholar Registration Request", UserService.FormatTemplate(System.Web.HttpContext.Current.Server.MapPath("~/") + "/assets/NewUserTemplate.html", user), user.EMail, UserService.AdminEmailAddress, null); } PortfolioId = portfolio.Id; lnkPicture.Visible = true; lnkTransUpload.Visible = true; } }
public static bool SetEmailAsSent(string GuidId) { bool result = false; try { EMailService _emailService = new EMailService(); result = _emailService.SetMailAsSent(GuidId); } catch (Exception e) { Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "GuidId =" + GuidId.ToString()); } return(result); }
public async Task <JsonResult> SendPassword(string id) { try { var userStore = NewUserStore(); var user = await userStore.FindByIdAsync(id); if (user == null) { return(Json(new ResponseData() { message = "Kullanıcı bulunamadı", success = false })); } var newPassword = StringHelpers.GetCode().Substring(0, 6); await userStore.SetPasswordHashAsync(user, NewUserManager().PasswordHasher.HashPassword(newPassword)); await userStore.UpdateAsync(user); userStore.Context.SaveChanges(); string SiteUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); var emailService = new EMailService(); var body = $"Merhaba <b>{user.Name} {user.Surname}</b><br>Hesabınızın parolası sıfırlanmıştır<br> Yeni parolanız: <b>{newPassword}</b> <p>Yukarıdaki parolayı kullanarak sistemize giriş yapabilirsiniz.</p>"; emailService.Send(new IdentityMessage() { Body = body, Subject = $"{user.UserName} Şifre Kurtarma" }, user.Email); return(Json(new ResponseData() { message = "Şifre sıfırlama maili gönderilmiştir", success = true })); } catch (Exception ex) { return(Json(new ResponseData() { message = $"Bir hata oluştu: {ex.Message}", success = false })); } }
public JsonResult TestSMTP(string destinationAddress) { var resultTest = false; var eMailService = new EMailService(); try { eMailService.SendAsync("Teste de envio de e-mail", "Teste", destinationAddress); resultTest = true; } catch (Exception) { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; resultTest = false; } return(Json(resultTest, JsonRequestBehavior.AllowGet)); }
public ActionResult GetMessageTemplates(int index, int pageNo, int pageSize, string search) { var model = createModel(); var templateList = LookupService.FindMessageTemplatesListModel(model.CurrentCompany.Id, index, pageNo, pageSize, search); Dictionary <string, string> dict = new Dictionary <string, string>(); EMailService.AddOrganisationDetails(dict); EMailService.AddUserDetails(CurrentUser, dict); foreach (var template in templateList.Items) { template.Subject = template.Subject.DoSubstitutions(dict); template.Message = template.Message.DoSubstitutions(dict); } return(Json(templateList, JsonRequestBehavior.AllowGet)); }
public string sendMain() { ///取得寄件者資料 string strSenderAddress = Request["textSenderAddress"]; ///取得收件者資料,有逗號結尾,所以將其移除 string strReceiveAddress = Request["textReceiveAddress"]; if (strReceiveAddress.EndsWith(",")) { strReceiveAddress = strReceiveAddress.Substring(0, strReceiveAddress.Length - 1); } log.Info("send email:strSenderAddress=" + strSenderAddress + ",strReceiveAddress=" + strReceiveAddress); // List<string> MailList = new List<string>(); //MailList.Add(strReceiveAddress); //取得主旨資料 string strSubject = Request["textSubject"]; //取得內容 string strContent = Request["textContent"]; log.Debug("test email sender!"); EMailService es = new EMailService(); //設定附件檔案 string projectid = Request["textProjectId"]; string poid = Request["textPOID"]; string realFilePath = ContextService.strUploadPath + "\\" + projectid + "\\" + ContextService.quotesFolder + "\\" + poid + ".xlsx"; SYS_USER u = (SYS_USER)Session["user"]; log.Debug("Attachment file path=" + realFilePath); if (es.SendMailByGmail(strSenderAddress, u.USER_NAME, strReceiveAddress, null, strSubject, strContent, realFilePath)) { return("發送成功!!"); } else { return("發送失敗!!"); } }
public ActionResult GetEMailQueue(int index, int pageNo, int pageSize, string search) { return(Json(EMailService.FindEMailQueueListModel(index, pageNo, pageSize, search), JsonRequestBehavior.AllowGet)); }
private static void HandleEvents() { EventServiceFactory.EventService.GetEvent <GenericEvent <ActionData> >().Subscribe(x => { if (x.Value.Action.ActionType == "UpdateApplicationSubTitle") { var title = x.Value.GetAsString("Title"); PresentationServices.SubTitle.ApplicationTitle = title; var fontSize = x.Value.GetAsInteger("FontSize"); if (fontSize > 0) { PresentationServices.SubTitle.ApplicationTitleFontSize = fontSize; } var fontColor = x.Value.GetAsString("Color"); if (!string.IsNullOrEmpty(fontColor)) { PresentationServices.SubTitle.ApplicationTitleColor = fontColor; } } if (x.Value.Action.ActionType == "RemoveLastModifier") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket == null) { return; } var ti = x.Value.GetDataValue <TicketItem>("TicketItem"); if (ti == null) { return; } if (ti.Properties.Count > 0) { var prop = ti.LastSelectedProperty ?? ti.Properties.Last(); prop.Quantity--; if (prop.Quantity < 1) { ti.Properties.Remove(prop); } } TicketViewModel.RecalculateTicket(ticket); } if (x.Value.Action.ActionType == "UpdateTicketItemPriceTag") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket == null) { return; } var ti = x.Value.GetDataValue <TicketItem>("TicketItem"); if (ti == null) { return; } var priceTag = x.Value.GetAsString("PriceTag"); var mi = AppServices.DataAccessService.GetMenuItem(ti.MenuItemId); if (mi == null) { return; } var portion = mi.Portions.SingleOrDefault(y => y.Name == ti.PortionName); if (portion == null) { return; } ti.UpdatePortion(portion, priceTag, null); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } if (x.Value.Action.ActionType == "UpdateTicketItemTag") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket == null) { return; } var ti = x.Value.GetDataValue <TicketItem>("TicketItem"); if (ti == null) { return; } var tag = x.Value.GetAsString("Tag"); ti.Tag = tag; decimal val; decimal.TryParse(tag, out val); } if (x.Value.Action.ActionType == "UpdateLastTicketItemPriceTag") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket == null) { return; } var ti = ticket.TicketItems.LastOrDefault(); if (ti == null) { return; } var priceTag = x.Value.GetAsString("PriceTag"); var mi = AppServices.DataAccessService.GetMenuItem(ti.MenuItemId); if (mi == null) { return; } var portion = mi.Portions.SingleOrDefault(y => y.Name == ti.PortionName); if (portion == null) { return; } ti.UpdatePortion(portion, priceTag, null); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } if (x.Value.Action.ActionType == "GiftLastTicketItem") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var ti = ticket.TicketItems.LastOrDefault(); if (ti != null) { decimal quantity; decimal.TryParse(x.Value.Action.GetParameter("Quantity"), out quantity); if (quantity > 0 && ti.Quantity > quantity) { ti.UpdateSelectedQuantity(quantity); ti = ticket.ExtractSelectedTicketItems(new List <TicketItem> { ti }).FirstOrDefault(); if (ti == null) { return; } AppServices.MainDataContext.AddItemToSelectedTicket(ti); } var reasonId = 0; var giftReason = x.Value.Action.GetParameter("GiftReason"); if (!string.IsNullOrEmpty(giftReason)) { var reason = Dao.SingleWithCache <Reason>(u => u.Name == giftReason); if (reason != null) { reasonId = reason.Id; } } ticket.GiftItem(ti, reasonId, AppServices.CurrentLoggedInUser.Id); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } } if (x.Value.Action.ActionType == "UpdateTicketAccount") { Expression <Func <Customer, bool> > qFilter = null; var phoneNumber = x.Value.GetAsString("AccountPhone"); var accountName = x.Value.GetAsString("AccountName"); var note = x.Value.GetAsString("Note"); if (!string.IsNullOrEmpty(phoneNumber)) { qFilter = y => y.PhoneNumber == phoneNumber; } if (!string.IsNullOrEmpty(accountName)) { if (qFilter == null) { qFilter = y => y.Name == accountName; } else { qFilter = qFilter.And(y => y.Name == accountName); } } if (!string.IsNullOrEmpty(note)) { if (qFilter == null) { qFilter = y => y.Note == note; } else { qFilter = qFilter.And(y => y.Note == note); } } if (qFilter != null) { var customer = Dao.Query(qFilter).FirstOrDefault(); if (customer != null) { AppServices.MainDataContext.AssignCustomerToSelectedTicket(customer); } } else { AppServices.MainDataContext.AssignCustomerToSelectedTicket(Customer.Null); } } if (x.Value.Action.ActionType == "UpdateProgramSetting") { SettingAccessor.ResetCache(); var settingName = x.Value.GetAsString("SettingName"); var updateType = x.Value.GetAsString("UpdateType"); if (!string.IsNullOrEmpty(settingName)) { var isLocal = x.Value.GetAsBoolean("IsLocal"); var setting = isLocal ? AppServices.SettingService.ReadLocalSetting(settingName) : AppServices.SettingService.ReadGlobalSetting(settingName); if (updateType == Resources.Increase) { var settingValue = x.Value.GetAsInteger("SettingValue"); if (string.IsNullOrEmpty(setting.StringValue)) { setting.IntegerValue = settingValue; } else { setting.IntegerValue = setting.IntegerValue + settingValue; } } else if (updateType == Resources.Decrease) { var settingValue = x.Value.GetAsInteger("SettingValue"); if (string.IsNullOrEmpty(setting.StringValue)) { setting.IntegerValue = settingValue; } else { setting.IntegerValue = setting.IntegerValue - settingValue; } } else if (updateType == "Multiply") { if (string.IsNullOrEmpty(setting.StringValue)) { setting.DecimalValue = 0; } else { setting.DecimalValue = setting.DecimalValue * x.Value.GetAsDecimal("SettingValue"); } } else if (updateType == "Toggle") { var settingValue = x.Value.GetAsString("SettingValue"); var parts = settingValue.Split(','); if (string.IsNullOrEmpty(setting.StringValue)) { setting.StringValue = parts[0]; } else { for (var i = 0; i < parts.Length; i++) { if (parts[i] == setting.StringValue) { setting.StringValue = (i + 1) < parts.Length ? parts[i + 1] : parts[0]; break; } } } } else { var settingValue = x.Value.GetAsString("SettingValue"); setting.StringValue = settingValue; } if (!isLocal) { AppServices.SettingService.SaveChanges(); } } } if (x.Value.Action.ActionType == "RefreshCache") { MethodQueue.Queue("ResetCache", ResetCache); } if (x.Value.Action.ActionType == "SendMessage") { AppServices.MessagingService.SendMessage("ActionMessage", x.Value.GetAsString("Command")); } if (x.Value.Action.ActionType == "SendEmail") { EMailService.SendEMailAsync(x.Value.GetAsString("SMTPServer"), x.Value.GetAsString("SMTPUser"), x.Value.GetAsString("SMTPPassword"), x.Value.GetAsInteger("SMTPPort"), x.Value.GetAsString("ToEMailAddress"), x.Value.GetAsString("FromEMailAddress"), x.Value.GetAsString("Subject"), x.Value.GetAsString("EMailMessage"), x.Value.GetAsString("FileName"), x.Value.GetAsBoolean("DeleteFile"), x.Value.GetAsBoolean("BypassSslErrors")); } if (x.Value.Action.ActionType == "ExecuteTicketEvent") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var operationName = x.Value.GetAsString("TicketOperation"); if (operationName == Resources.Refresh) { EventServiceFactory.EventService.PublishEvent(EventTopicNames.DisplayTicketView); } if (operationName == Resources.Close) { ticket.PublishEvent(EventTopicNames.PaymentSubmitted); } } } if (x.Value.Action.ActionType == "UpdateTicketVat") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var vatTemplateName = x.Value.GetAsString("VatTemplate"); var vatTemplate = AppServices.MainDataContext.VatTemplates.FirstOrDefault(y => y.Name == vatTemplateName); if (vatTemplate != null) { ticket.UpdateVat(vatTemplate); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } } if (x.Value.Action.ActionType == "UpdateTicketTaxService") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var taxServiceTemplateName = x.Value.GetAsString("TaxServiceTemplate"); var taxServiceTemplate = AppServices.MainDataContext.TaxServiceTemplates.FirstOrDefault( y => y.Name == taxServiceTemplateName); if (taxServiceTemplate != null) { var amount = x.Value.GetAsDecimal("Amount"); ticket.AddTaxService(taxServiceTemplate.Id, taxServiceTemplate.CalculationMethod, amount); TicketViewModel.RecalculateTicket(ticket); } } } if (x.Value.Action.ActionType == "RegenerateTicketVat") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { TicketViewModel.RegenerateVatRates(ticket); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } if (x.Value.Action.ActionType == "AddTicketDiscount") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var percentValue = x.Value.GetAsDecimal("DiscountPercentage"); ticket.AddTicketDiscount(DiscountType.Percent, percentValue, AppServices.CurrentLoggedInUser.Id); TicketViewModel.RecalculateTicket(ticket); } } if (x.Value.Action.ActionType == "AddTicketItem") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var menuItemName = x.Value.GetAsString("MenuItemName"); var menuItem = AppServices.DataAccessService.GetMenuItemByName(menuItemName); var portionName = x.Value.GetAsString("PortionName"); var quantity = x.Value.GetAsDecimal("Quantity"); var gifted = x.Value.GetAsBoolean("Gift"); var giftReason = x.Value.GetAsString("GiftReason"); var tag = x.Value.GetAsString("Tag"); var departmentId = AppServices.CurrentTerminal.DepartmentId > 0 ? AppServices.MainDataContext.SelectedDepartment.Id : ticket.DepartmentId; var ti = ticket.AddTicketItem(AppServices.CurrentLoggedInUser.Id, departmentId, menuItem, portionName, AppServices.MainDataContext.SelectedDepartment.PriceTag, ""); ti.Quantity = quantity; ti.Gifted = gifted; if (gifted && !string.IsNullOrEmpty(giftReason)) { var reason = Dao.SingleWithCache <Reason>(u => u.Name == giftReason); if (reason != null) { ti.ReasonId = reason.Id; } } else { ti.ReasonId = 0; } ti.Tag = tag; TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } if (x.Value.Action.ActionType == "VoidTicketItems") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var menuItemName = x.Value.GetAsString("MenuItemName"); var tag = x.Value.GetAsString("Tag"); if (!string.IsNullOrEmpty(menuItemName) && !string.IsNullOrEmpty(tag)) { var lines = ticket.TicketItems.Where(y => !y.Voided && (string.IsNullOrEmpty(menuItemName) || y.MenuItemName.Contains(menuItemName)) && (y.Tag.Contains(tag) || string.IsNullOrEmpty(tag))).ToList(); lines.ForEach(y => ticket.VoidItem(y, 0, AppServices.CurrentLoggedInUser.Id)); TicketViewModel.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } } if (x.Value.Action.ActionType == "UpdateTicketTag") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var tagName = x.Value.GetAsString("TagName"); var tagValue = x.Value.GetAsString("TagValue"); if (tagValue.Contains(",")) { var ctag = ticket.GetTagValue(tagName); if (!string.IsNullOrEmpty(ctag)) { var nextTag = tagValue.Split(',').SkipWhile(y => y != ctag).Skip(1).FirstOrDefault(); if (string.IsNullOrEmpty(nextTag)) { nextTag = tagValue.Split(',')[0]; } tagValue = nextTag; } } ticket.SetTagValue(tagName, tagValue); var tagData = new TicketTagData { TagName = tagName, TagValue = tagValue }; tagData.PublishEvent(EventTopicNames.TagSelectedForSelectedTicket); } } if (x.Value.Action.ActionType == "UpdatePriceTag") { using (var workspace = WorkspaceFactory.Create()) { var priceTag = x.Value.GetAsString("PriceTag"); var departmentName = x.Value.GetAsString("DepartmentName"); var department = workspace.Single <Department>(y => y.Name == departmentName); if (department != null) { department.PriceTag = priceTag; workspace.CommitChanges(); MethodQueue.Queue("ResetCache", ResetCache); } } } if (x.Value.Action.ActionType == "ExecutePrintJob") { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); var pjName = x.Value.GetAsString("PrintJobName"); var ticketItemTag = x.Value.GetAsString("TicketItemTag"); if (!string.IsNullOrEmpty(pjName)) { var j = AppServices.CurrentTerminal.PrintJobs.SingleOrDefault(y => y.Name == pjName); if (j != null) { if (ticket != null) { AppServices.MainDataContext.UpdateTicketNumber(ticket); if (j.LocksTicket) { ticket.RequestLock(); } var clonedTicket = ObjectCloner.Clone(ticket); clonedTicket.CopyPaidItemsCache(ticket); if (!string.IsNullOrEmpty(ticketItemTag)) { clonedTicket.TicketItems = clonedTicket.TicketItems.Where(y => !string.IsNullOrEmpty(y.Tag) && y.Tag.ToLower().Contains(ticketItemTag.Trim().ToLower())).ToList(); } AppServices.PrintService.ManualPrintTicket(clonedTicket, j); } else { AppServices.PrintService.ExecutePrintJob(j); } } } } }); }
private static void HandleEvents() { EventServiceFactory.EventService.GetEvent <GenericEvent <IActionData> >().Subscribe(x => { if (x.Value.Action.ActionType == ActionNames.DisplayPaymentScreen) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { ticket.PublishEvent(EventTopicNames.MakePayment); } } if (x.Value.Action.ActionType == ActionNames.LockTicket) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { ticket.LockTicket(); } } if (x.Value.Action.ActionType == ActionNames.DisplayTicket) { var ticketId = x.Value.GetAsInteger("TicketId"); if (ticketId > 0) { ExtensionMethods.PublishIdEvent(ticketId, EventTopicNames.DisplayTicket); } } if (x.Value.Action.ActionType == ActionNames.CreateTicket) { EventServiceFactory.EventService.PublishEvent(EventTopicNames.CreateTicket); } if (x.Value.Action.ActionType == ActionNames.UnlockTicket) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { ticket.Locked = false; } EventServiceFactory.EventService.PublishEvent(EventTopicNames.UnlockTicketRequested); } if (x.Value.Action.ActionType == ActionNames.CloseActiveTicket) { EventServiceFactory.EventService.PublishEvent(EventTopicNames.CloseTicketRequested, true); } if (x.Value.Action.ActionType == ActionNames.UpdateResourceState) { var resourceId = x.Value.GetDataValueAsInt("ResourceId"); var resourceTypeId = x.Value.GetDataValueAsInt("ResourceTypeId"); var stateName = x.Value.GetAsString("ResourceState"); var state = CacheService.GetResourceStateByName(stateName); if (state != null) { if (resourceId > 0 && resourceTypeId > 0) { ResourceService.UpdateResourceState(resourceId, state.Id); } else { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var resourceTypeName = x.Value.GetDataValueAsString("ResourceTypeName"); foreach (var ticketResource in ticket.TicketResources) { var resourceType = CacheService.GetResourceTypeById(ticketResource.ResourceTypeId); if (string.IsNullOrEmpty(resourceTypeName.Trim()) || resourceType.Name == resourceTypeName) { ResourceService.UpdateResourceState(ticketResource.ResourceId, state.Id); } } } } } } if (x.Value.Action.ActionType == ActionNames.UpdateTicketAccount) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { Expression <Func <Resource, bool> > qFilter = null; var phoneNumber = x.Value.GetAsString("AccountPhone"); var accountName = x.Value.GetAsString("AccountName"); var note = x.Value.GetAsString("Note"); if (!string.IsNullOrEmpty(phoneNumber)) { qFilter = y => y.SearchString == phoneNumber; } if (!string.IsNullOrEmpty(accountName)) { if (qFilter == null) { qFilter = y => y.Name == accountName; } else { qFilter = qFilter.And(y => y.Name == accountName); } } if (qFilter != null) { var account = Dao.Query(qFilter).FirstOrDefault(); if (account != null) { TicketService.UpdateResource(ticket, account); } } else { TicketService.UpdateResource(ticket, Resource.Null); } } } if (x.Value.Action.ActionType == ActionNames.UpdateProgramSetting) { var settingName = x.Value.GetAsString("SettingName"); var updateType = x.Value.GetAsString("UpdateType"); if (!string.IsNullOrEmpty(settingName)) { var isLocal = x.Value.GetAsBoolean("IsLocal"); var setting = isLocal ? SettingService.ReadLocalSetting(settingName) : SettingService.ReadGlobalSetting(settingName); if (updateType == Resources.Increase) { var settingValue = x.Value.GetAsInteger("SettingValue"); if (string.IsNullOrEmpty(setting.StringValue)) { setting.IntegerValue = settingValue; } else { setting.IntegerValue = setting.IntegerValue + settingValue; } } else if (updateType == Resources.Decrease) { var settingValue = x.Value.GetAsInteger("SettingValue"); if (string.IsNullOrEmpty(setting.StringValue)) { setting.IntegerValue = settingValue; } else { setting.IntegerValue = setting.IntegerValue - settingValue; } } else if (updateType == "Toggle") { var settingValue = x.Value.GetAsString("SettingValue"); var parts = settingValue.Split(','); if (string.IsNullOrEmpty(setting.StringValue)) { setting.StringValue = parts[0]; } else { for (var i = 0; i < parts.Length; i++) { if (parts[i] == setting.StringValue) { setting.StringValue = (i + 1) < parts.Length ? parts[i + 1] : parts[0]; break; } } } } else { var settingValue = x.Value.GetAsString("SettingValue"); setting.StringValue = settingValue; } if (!isLocal) { SettingService.SaveProgramSettings(); } } } if (x.Value.Action.ActionType == ActionNames.RefreshCache) { MethodQueue.Queue("ResetCache", ResetCache); } if (x.Value.Action.ActionType == ActionNames.SendMessage) { AppServices.MessagingService.SendMessage("ActionMessage", x.Value.GetAsString("Command")); } if (x.Value.Action.ActionType == ActionNames.SendEmail) { EMailService.SendEMailAsync(x.Value.GetAsString("SMTPServer"), x.Value.GetAsString("SMTPUser"), x.Value.GetAsString("SMTPPassword"), x.Value.GetAsInteger("SMTPPort"), x.Value.GetAsString("ToEMailAddress"), x.Value.GetAsString("CCEmailAddresses"), x.Value.GetAsString("FromEMailAddress"), x.Value.GetAsString("Subject"), x.Value.GetAsString("EMailMessage"), x.Value.GetAsString("FileName"), x.Value.GetAsBoolean("DeleteFile"), x.Value.GetAsBoolean("BypassSslErrors")); } if (x.Value.Action.ActionType == ActionNames.UpdateTicketTax) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var taxTemplateName = x.Value.GetAsString("TaxTemplate"); var taxTemplate = SettingService.GetTaxTemplateByName(taxTemplateName); if (taxTemplate != null) { ticket.UpdateTax(taxTemplate); TicketService.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } } if (x.Value.Action.ActionType == ActionNames.UpdateTicketCalculation) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var calculationTypeName = x.Value.GetAsString("CalculationType"); var calculationType = SettingService.GetCalculationTypeByName(calculationTypeName); if (calculationType != null) { var amount = x.Value.GetAsDecimal("Amount"); ticket.AddCalculation(calculationType, amount); TicketService.RecalculateTicket(ticket); } } } if (x.Value.Action.ActionType == ActionNames.RegenerateTicketTax) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { TicketService.RegenerateTaxRates(ticket); TicketService.RecalculateTicket(ticket); EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket); } } if (x.Value.Action.ActionType == ActionNames.Addticketdiscount) { //var ticket = x.Value.GetDataValue<Ticket>("Ticket"); //if (ticket != null) //{ // var percentValue = x.Value.GetAsDecimal("DiscountPercentage"); // ticket.AddTicketDiscount(DiscountType.Percent, percentValue, ApplicationState.CurrentLoggedInUser.Id); // TicketService.RecalculateTicket(ticket); //} } if (x.Value.Action.ActionType == ActionNames.Addorder) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var menuItemName = x.Value.GetAsString("MenuItemName"); var menuItem = CacheService.GetMenuItem(y => y.Name == menuItemName); var portionName = x.Value.GetAsString("PortionName"); var quantity = x.Value.GetAsDecimal("Quantity"); var tag = x.Value.GetAsString("Tag"); var order = TicketService.AddOrder(ticket, menuItem.Id, quantity, portionName, null); if (order != null) { order.Tag = tag; } } } if (x.Value.Action.ActionType == ActionNames.UpdateTicketTag) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); if (ticket != null) { var tagName = x.Value.GetAsString("TagName"); var tagValue = x.Value.GetAsString("TagValue"); ticket.SetTagValue(tagName, tagValue); var tagData = new TicketTagData { TagName = tagName, TagValue = tagValue }; tagData.PublishEvent(EventTopicNames.TicketTagSelected); } } if (x.Value.Action.ActionType == ActionNames.TagOrder || x.Value.Action.ActionType == ActionNames.UntagOrder || x.Value.Action.ActionType == ActionNames.RemoveOrderTag) { var order = x.Value.GetDataValue <Order>("Order"); if (order != null) { var tagName = x.Value.GetAsString("OrderTagName"); var orderTag = CacheService.GetOrderTagGroupByName(tagName); if (orderTag != null) { if (x.Value.Action.ActionType == ActionNames.RemoveOrderTag) { var tags = order.OrderTagValues.Where(y => y.OrderTagGroupId == orderTag.Id); tags.ToList().ForEach(y => order.OrderTagValues.Remove(y)); return; } var tagValue = x.Value.GetAsString("OrderTagValue"); var orderTagValue = orderTag.OrderTags.SingleOrDefault(y => y.Name == tagValue); if (orderTagValue != null) { if (x.Value.Action.ActionType == ActionNames.TagOrder) { order.TagIfNotTagged(orderTag, orderTagValue, ApplicationState.CurrentLoggedInUser.Id); } if (x.Value.Action.ActionType == ActionNames.UntagOrder) { order.UntagIfTagged(orderTag, orderTagValue); } } } } } if (x.Value.Action.ActionType == ActionNames.MoveTaggedOrders) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); var orderTagName = x.Value.GetAsString("OrderTagName"); if (ticket != null && !string.IsNullOrEmpty(orderTagName)) { var orderTagValue = x.Value.GetAsString("OrderTagValue"); if (ticket.Orders.Any(y => y.OrderTagValues.Any(z => z.OrderTagGroupName == orderTagName && z.Name == orderTagValue))) { var tid = ticket.Id; EventServiceFactory.EventService.PublishEvent(EventTopicNames.CloseTicketRequested, true); ticket = TicketService.OpenTicket(tid); var orders = ticket.Orders.Where(y => y.OrderTagValues.Any(z => z.OrderTagGroupName == orderTagName && z.Name == orderTagValue)).ToArray(); var commitResult = TicketService.MoveOrders(ticket, orders, 0); if (string.IsNullOrEmpty(commitResult.ErrorMessage) && commitResult.TicketId > 0) { ExtensionMethods.PublishIdEvent(commitResult.TicketId, EventTopicNames.DisplayTicket); } else { ExtensionMethods.PublishIdEvent(tid, EventTopicNames.DisplayTicket); } } } } if (x.Value.Action.ActionType == ActionNames.UpdatePriceTag) { using (var workspace = WorkspaceFactory.Create()) { var priceTag = x.Value.GetAsString("PriceTag"); var departmentName = x.Value.GetAsString("DepartmentName"); var department = workspace.Single <Department>(y => y.Name == departmentName); if (department != null) { department.PriceTag = priceTag; workspace.CommitChanges(); MethodQueue.Queue("ResetCache", ResetCache); } } } if (x.Value.Action.ActionType == ActionNames.ExecutePrintJob) { var ticket = x.Value.GetDataValue <Ticket>("Ticket"); var pjName = x.Value.GetAsString("PrintJobName"); if (!string.IsNullOrEmpty(pjName)) { TicketService.UpdateTicketNumber(ticket, ApplicationState.CurrentDepartment.TicketTemplate.TicketNumerator); var j = CacheService.GetPrintJobByName(pjName); if (j != null) { if (ticket != null) { PrinterService.PrintTicket(ticket, j); } else { PrinterService.ExecutePrintJob(j); } } } } }); }
public EMailServiceIdentity() { eMailService = new EMailService(); }
public async Task <ActionResult> ChangePassword(ProfilePasswordViewModel _model) { var model = _model.ChangePasswordViewModel; try { var user = await _membershipTools.UserManager.GetUserAsync(HttpContext.User); //var id = _membershipTools.IHttpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; //var user = await _membershipTools.UserManager.FindByIdAsync(id); var data = new ChangePasswordViewModel() { OldPassword = model.OldPassword, NewPassword = model.NewPassword, ConfirmNewPassword = model.ConfirmNewPassword }; model = data; if (!ModelState.IsValid) { return(RedirectToAction("Index", "Home")); } var result = await _membershipTools.UserManager.ChangePasswordAsync( await _membershipTools.UserManager.GetUserAsync(HttpContext.User), model.OldPassword, model.NewPassword); if (result.Succeeded) { var emailService = new EMailService(); var body = $"Merhaba <b>{user.Name} {user.Surname}</b><br>Hesabınızın şifresi değiştirilmiştir. <br> Bilginiz dahilinde olmayan değişiklikler için hesabınızı güvence altına almanızı öneririz.</p>"; emailService.Send(new MailModel() { Body = body, Subject = "Şifre Değiştirme hk." }, user.Email); return(RedirectToAction("Logout", "Account")); } else { var err = ""; foreach (var resultError in result.Errors) { err += resultError + " "; } ModelState.AddModelError("", err); return(RedirectToAction("Index", "Home")); } } catch (Exception ex) { TempData["Message"] = new ErrorViewModel() { Text = $"Bir hata oluştu {ex.Message}", ActionName = "ChangePassword", ControllerName = "Account", ErrorCode = 500 }; return(RedirectToAction("Error500", "Home")); } }
public SendEMailToUser() { _emailService = new EMailService(); }
public PasswordRestoreModel(EMailService email, ConfirmationLinksGeneratorService confirmation, ServiceLocator serviceProvider) : base(serviceProvider) { _email = email ?? throw new ArgumentNullException(nameof(email)); _confirmation = confirmation ?? throw new ArgumentNullException(nameof(confirmation)); }
public void OnGet() { EmailService = new EMailService(); }
public async Task <ActionResult> Register(RegisterLoginViewModel model) { if (!ModelState.IsValid) { return(View("Index", model));//ındex view ını modelle çalıştıryprum. } try { var userStore = NewUserStore(); //veritabanı işlemi yapcağımız için Store kullanırız. var userManager = NewUserManager(); //yukarda static kütüphane seklinde tanımlamasaydık MembershipTools.Newusermanager yazardık. var roleManager = NewRoleManager(); //registerviewmodelde propertlere tanımladığımız isim username ... leri formda doldurup rm ye atıyoruz. var rm = model.RegisterViewModel; //Kullanıcı varmı yokmu diye bakmak için kullanıyoruz. var user = await userManager.FindByNameAsync(rm.UserName); //username e göre arıyor. if (user != null) { ModelState.AddModelError("UserName", "Bu kullanıcı daha önce alınmıştır."); return(View("Index", model)); } var newUser = new User()//Kullanıcıyı değişkene atıyprum. { UserName = rm.UserName, Email = rm.Email, Name = rm.Name, Surname = rm.Surname, ActivationCode = StringHelpers.GetCode() }; //Kullanıcı oluşturuyoruz. var result = await userManager.CreateAsync(newUser, rm.Password); //password ü ayrı alıyor çünkü şifrelicek. if (result.Succeeded) //İlk kullanıcıysa admin yapalım. { if (userStore.Users.Count() == 1) { await userManager.AddToRoleAsync(newUser.Id, "Admin");//içine userıd ve role alır. } else//ilk kaydettiğimiz admin oldu sonrakiler user olarak buraya düşüyor. { await userManager.AddToRoleAsync(newUser.Id, "User"); } string SiteUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); var emailService = new EMailService(); var body = $"Merhaba <b>{newUser.Name} {newUser.Surname}</b><br>Hesabınızı aktif etmek için aşadıdaki linke tıklayınız<br> <a href='{SiteUrl}/account/activation?code={newUser.ActivationCode}' >Aktivasyon Linki </a> "; await emailService.SendAsync(new IdentityMessage() { Body = body, Subject = "Sitemize Hoşgeldiniz" }, newUser.Email); //mailin gitmesi için newUser.Email eklemeliyiz. } else { var err = ""; foreach (var resultError in result.Errors) { err += resultError + " "; } ModelState.AddModelError("", err); return(View("Index", model)); } TempData["Message"] = "Kaydınız basarıyla alınmıştır"; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["Model"] = new ErrorViewModel() { Text = $"Bir hata oluştu {ex.Message}", ActionName = "Index", ControllerName = "Account", ErrorCode = 500 }; return(RedirectToAction("Error", "Home")); } }