Пример #1
0
        public EmailSender(IOptions <AuthMessageSenderOptions> optionsAccessor)
        {
            var path = "./wwwroot/templates";

            this.options = optionsAccessor.Value;
            this.emailConfirmationTemplate = File.ReadAllTextAsync($"{path}/confirm-email.htm");
            this.passwordResetTemplate     = File.ReadAllTextAsync($"{path}/reset-password.htm");
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            services.AddCors(o => o.AddPolicy("DefaultCorsPolicy", pol =>
            {
                pol.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddDefaultIdentity <ApplicationUser>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;

                options.SignIn.RequireConfirmedAccount     = false;
                options.SignIn.RequireConfirmedEmail       = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;

                options.User.RequireUniqueEmail = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddIdentityServer()
            .AddApiAuthorization <ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
            .AddIdentityServerJwt();

            var sendGridConfig = new AuthMessageSenderOptions();

            Configuration.GetSection(nameof(AuthMessageSenderOptions)).Bind(sendGridConfig);

            //services.AddTransient<IEmailSender, EmailSenderService>(x => new EmailSenderService(sendGridConfig));
            services.AddTransient <IRestApiService, RestApiService>();

            var externalApiUrl = Configuration.GetValue <string>("externalWeatherApiUrl");

            services.AddTransient <IWeatherForecastDataProvider, WeatherForecastDataProvider>(b =>
            {
                return(new WeatherForecastDataProvider(b.GetService <IRestApiService>(), externalApiUrl));
            });

            services.AddControllersWithViews();
            services.AddRazorPages();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Пример #3
0
 public UsersController(UserManager <HRSIdentityUser> userManager, IMapper mapper, ILogger <UsersController> log, IEmailSender emailSender, SignInManager <HRSIdentityUser> signInManager, IOptions <AuthMessageSenderOptions> optionsAccessor)
 {
     _userManager   = userManager;
     _mapper        = mapper;
     _emailSender   = emailSender;
     _signInManager = signInManager;
     _log           = log;
     Options        = optionsAccessor.Value;
 }
Пример #4
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext context,
                              UserManager <ApplicationUser> userManager,
                              RoleManager <IdentityRole> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            if (env.IsProduction())
            {
                app.UseKissLogMiddleware(options =>
                {
                    options.Listeners.Add(new KissLogApiListener(new KissLog.Apis.v1.Auth.Application(
                                                                     Configuration["KissLog.OrganizationId"],
                                                                     Configuration["KissLog.ApplicationId"])
                                                                 ));
                });
            }


            var authMsgSenderOpt = new AuthMessageSenderOptions
            {
                SendGridUser = Configuration["SendGridUser"],
                SendGridKey  = Configuration["SendGridKey"]
            };

            //CriaUsersAndRoles.Seed(context, userManager, roleManager).Wait();
            //app.UseMiddleware<DefaultUsersAndRolesMiddeware>();
            //app.UseAddUserAndRoles();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapRazorPages();
            });
        }
Пример #5
0
 public EmailSender(IOptions <AuthMessageSenderOptions> options)
 {
     _config      = options.Value;
     _fromAddress = new MailAddress(_config.User, "Best Clip Of The Week");
     _client      = new SmtpClient
     {
         Host           = "smtp.gmail.com",
         Port           = 587,
         EnableSsl      = true,
         DeliveryMethod = SmtpDeliveryMethod.Network,
         Credentials    = new NetworkCredential(_fromAddress.Address, _config.Password),
         Timeout        = 20000
     };
 }
Пример #6
0
        public IActionResult EmailContact(string userId, IFormCollection fc)
        {
            var Option = new AuthMessageSenderOptions
            {
                SendGridKey  = context.Parameters.Find("2").Value,
                SendGridUser = context.Parameters.Find("1").Value
            };

            var mailSender = new EmailSender(Option);


            mailSender.SendEmailAsync("*****@*****.**", fc["TieuDe"].ToString(), fc["NoiDung"]);

            return(RedirectToAction("Contact", "Home").WithSuccess("", "Gửi email thành công, chúng tôi sẽ phản hồi sớm nhất"));
        }
Пример #7
0
        public EmailSender(IOptions <AuthMessageSenderOptions> optionsAccessor,
                           RazorViewToStringRenderer renderer,
                           IConfiguration Configuration,
                           IHostingEnvironment Env,
                           ApplicationDbContext context)
        {
            env           = Env;
            configuration = Configuration;

            _optionsAccessor = optionsAccessor.Value;
            _renderer        = renderer;
            //_sender = new MailboxAddress("Taqweem", "*****@*****.**");
            _sender = new MailboxAddress(configuration.GetValue <string>("MailboxAddressName"), configuration.GetValue <string>("MailboxAddress"));

            _context   = context;
            Repository = new EFRepository(_context);
        }
Пример #8
0
        static async Task Execute(AuthMessageSenderOptions options, string subject, string message, string email)
        {
            var client = new SendGridClient(options.SendGridKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", options.SendGridUser),
                ReplyTo          = new EmailAddress("*****@*****.**", options.SendGridUser),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(email));

            // Disable click tracking.
            msg.SetClickTracking(false, false);

            await client.SendEmailAsync(msg);
        }
 public VriendschapController(PollContext context, IOptions <AuthMessageSenderOptions> authMessageSenderOptions)
 {
     _context = context;
     _authMessageSenderOptions = authMessageSenderOptions.Value;
 }
Пример #10
0
 public HomeController(INewsRepository newsRepository, UserManager <User> userManager, IOptions <AuthMessageSenderOptions> optionsAccessor)
 {
     _options        = optionsAccessor.Value;
     _newsRepository = newsRepository;
     _userManager    = userManager;
 }
 public EmailSender(IOptions <AuthMessageSenderOptions> senderOptions)
 {
     _senderOptions = senderOptions.Value;
 }
Пример #12
0
 public EmailSender(AuthMessageSenderOptions optionsAccessor)
 {
     Options = optionsAccessor;
 }
 public EmailSender(IOptions <AuthMessageSenderOptions> optionsAccessor)
 {
     Options       = optionsAccessor.Value;
     semaphoreSlim = new SemaphoreSlim(1, 1);
 }
Пример #14
0
 public EmailSenderService(IOptions <AuthMessageSenderOptions> options)
 {
     this.options = options.Value;
 }
Пример #15
0
 public MailKitEmailService(IOptions <AuthMessageSenderOptions> authOptions)
 {
     _authOptions = authOptions.Value;
 }
Пример #16
0
 public EmailSender(IOptions <AuthMessageSenderOptions> options)
 {
     Options = options.Value;
 }
Пример #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );


            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                    builder.AllowCredentials();
                });
            });

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
            });

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(p =>
            {
                p.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info {
                    Title = "Boiler Plate API", Version = "v1"
                });

                Dictionary <string, IEnumerable <string> > security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                p.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                p.AddSecurityRequirement(security);
            });

            //Sql Server
            services.AddDbContext <BoilerPlateDbContext>(options =>
            {
                options.EnableSensitiveDataLogging();
                options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("WebBackendBoilerPlate"));

                options.ConfigureWarnings(c => c.Log(CoreEventId.DetachedLazyLoadingWarning));
            }
                                                         );


            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("WebBackendBoilerPlate")));
            services.AddDefaultIdentity <ApplicationUser>().AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;

                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 1;
                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;
                // User settings
                options.User.RequireUniqueEmail = true;
            });

            JwtConfiguration jwtConfig = new JwtConfiguration();

            CouchyBaseConfig couchyBaseConfig = new CouchyBaseConfig();

            AuthMessageSenderOptions authMessageSenderOptions = new AuthMessageSenderOptions();


            Configuration.GetSection("SendGrid").Bind(authMessageSenderOptions);

            Configuration.GetSection("CouchyBaseCacheConfig").Bind(couchyBaseConfig);

            Configuration.GetSection("JWT").Bind(jwtConfig);
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                SymmetricSecurityKey serverSecret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.ServerSecret));
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = serverSecret,
                    ValidIssuer              = jwtConfig.Issuer,
                    ValidAudience            = jwtConfig.Audience,
                    ClockSkew                = TimeSpan.Zero,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                };
            });


            services.AddCouchbase(opt =>
            {
                opt.Servers = new List <Uri>
                {
                    new Uri("http://127.0.0.1:8091")
                };

                opt.Username = couchyBaseConfig.Username;
                opt.Password = couchyBaseConfig.Password;
            });

            services.AddDistributedCouchbaseCache(couchyBaseConfig.BucketName, opt => { });



            if (Env.IsDevelopment())
            {
            }
            else if (Env.IsProduction())
            {
            }
            else if (Env.IsStaging())
            {
            }
            IServiceScopeFactory scopeFactory = services
                                                .BuildServiceProvider()
                                                .GetRequiredService <IServiceScopeFactory>();

            services.AddHangfire(
                x =>
            {
                x.UseActivator(new ContainerJobActivator(scopeFactory));
                x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"));
            }
                );


            //D.I
            services.AddTransient <JwtAuthenticator>();
            services.AddSingleton(jwtConfig);
            services.AddSingleton(authMessageSenderOptions);

            services.AddTransient <IEmailConfirmationService, EmailConfirmationService>();

            services.AddTransient <IRegistrationService, RegistrationService>();
            services.AddTransient <ILoginService, LoginService>();
            services.AddTransient <IPasswordService, PasswordService>();

            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IIdentityUserService, IdentityUserService>();
            services.AddTransient <IJWTService, JWTService>();
            services.AddTransient <IRefreshTokenService, RefreshTokenService>();

            services.AddTransient <IIdentityUserService, IdentityUserService>();

            services.AddScoped <IUnitOfWork, UnitOfWork <BoilerPlateDbContext> >();
            services.AddTransient <IEmailSender, EmailSender>();
        }
Пример #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            AppSetting appSetting = new AppSetting();
            AuthMessageSenderOptions senderOptions = new AuthMessageSenderOptions();

            _Configuration.GetSection("AppSetting").Bind(appSetting);
            services.ConfigureCustomAppService(appSetting);
            services.IoCRootResolver(appSetting);

            //sendgrid
            _Configuration.GetSection("SendGrid").Bind(senderOptions);
            services.AddSingleton(senderOptions);


            services.AddAutoMapper(

                opt =>
            {
                opt.AllowNullCollections = true;
            }, new List <Type> {
                typeof(AutoMapperMappings)
            }, ServiceLifetime.Transient

                );

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(
                options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }
                );

            services.RegisterSwagger();

            //Sql Server
            services.AddDbContext <XendDbContext>(options =>
            {
                options.EnableSensitiveDataLogging();
                options.UseLazyLoadingProxies().UseSqlServer(_Configuration.GetValue <string>("ConnectionString:DefaultConnection"), b => b.MigrationsAssembly("Xend.CRM.WebApi"));

                options.ConfigureWarnings(c => c.Log(CoreEventId.DetachedLazyLoadingWarning));
            }
                                                  );

            string connectstring = _Configuration.GetValue <string>("ConnectionString:DefaultConnection");



            //Mass Transit Config
            services.AddScoped <DummyConsumer>();
            //services.AddMassTransit(c =>
            //{
            //    c.AddConsumer<DummyConsumer>();
            //});
            //services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(
            //                         cfg =>
            //                         {
            //                             IRabbitMqHost host = cfg.Host("localhost", "/", h => { });

            //                             cfg.ReceiveEndpoint(host, "xend-boilerplate", e =>
            //                             {
            //                                 e.PrefetchCount = 16;
            //                                 e.UseMessageRetry(x => x.Interval(2, 100));

            //                                 e.LoadFrom(provider);
            //                                 EndpointConvention.Map<DummyConsumer>(e.InputAddress);


            //                             });
            //                         }));

            //services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
            //services.AddHostedService<BusService>();


            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder => {
                    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                });
            });


            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
            });
        }
 public EmailSenderService(IOptions <AuthMessageSenderOptions> optionsAccessor)
 {
     Options = optionsAccessor.Value;
     this.optionsAccessor = optionsAccessor;
 }
Пример #20
0
        private void ConfigureApplicationAuthenticationServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString(_authConnectionName));
            });

            var amso = AuthMessageSenderOptions.GetFromConfig(Configuration);

            services.Configure <AuthMessageSenderOptions>(o => o.SetFromOther(amso));



            services
            .AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
                //config.SignIn.RequireConfirmedPhoneNumber = true;

                config.User.RequireUniqueEmail = true;


                // Lockout settings
                config.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                config.Lockout.MaxFailedAccessAttempts = 10;
                config.Lockout.AllowedForNewUsers      = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.TryAddScoped <IAuthDbInitializer, AuthDbInitializer>();

            if (amso != null)
            {
                if (!string.IsNullOrEmpty(amso.FacebookAppId))
                {
                    services.AddAuthentication().AddFacebook(facebookOptions =>
                    {
                        facebookOptions.AppId     = amso.FacebookAppId;
                        facebookOptions.AppSecret = amso.FacebookSecret;
                        //facebookOptions.CallbackPath
                    });
                }
                if (!string.IsNullOrEmpty(amso.GoogleClientId))
                {
                    services.AddAuthentication().AddGoogle(googleOptions =>
                    {
                        googleOptions.ClientId     = amso.GoogleClientId;
                        googleOptions.ClientSecret = amso.GoogleClientSecret;
                    });
                }
                if (!string.IsNullOrEmpty(amso.MicrosoftClientId))
                {
                    services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
                    {
                        microsoftOptions.ClientId     = amso.MicrosoftClientId;
                        microsoftOptions.ClientSecret = amso.MicrosoftSecret;
                    });
                }
            }
            else
            {
                //todo error secrets didn't set in instatse, for some services will be error
            }



            services.ConfigureApplicationCookie(options =>
            {
                var lang = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower();

                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.Cookie.Expiration = TimeSpan.FromMinutes(30);
                options.LoginPath         =
                    $"/{lang}/Account/Login";        // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath =
                    $"/{lang}/Account/Logout";       // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath =
                    $"/{lang}/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;
            });


            //vk https://vk.com/pages?oid=-17680044&p=Authorizing_Sites
            //https://vknet.github.io/vk/authorize/
            //https://github.com/khrabrovart/Citrina
            //https://vk.com/dev/access_token

            services.TryAddTransient <IEmailSender, EmailSender>();
        }
Пример #21
0
        public IActionResult CheckOut(IFormCollection fc)
        {
            var dh = new DonHang();

            if (!string.IsNullOrEmpty(fc["Id"].ToString()))
            {
                if (context.AspNetUsers.Find(fc["Id"]) != null)
                {
                    dh.MaKh = fc["Id"];
                    var a = dataAccess.GetUser(dh.MaKh);
                    dh.HoTen     = a.HoTen;
                    dh.Dienthoai = a.PhoneNumber;
                    dh.Ghichu    = fc["GhiChu"];
                    dh.Email     = a.Email;
                    dh.Diachi    = a.DiaChi;
                    HttpContext.Session.SetObjectAsJson("MaKh", fc["Id"]);
                }
                else
                {
                    dh.MaKh      = "null" + (context.DonHang.Count() + 1);
                    dh.HoTen     = fc["HoTen"];
                    dh.Diachi    = fc["DiaChi"];
                    dh.Ghichu    = fc["GhiChu"];
                    dh.Email     = fc["Email"];
                    dh.Dienthoai = fc["DienThoai"];
                }
            }
            else
            {
                dh.MaKh      = "null" + (context.DonHang.Count() + 1);
                dh.HoTen     = fc["HoTen"];
                dh.Diachi    = fc["DiaChi"];
                dh.Ghichu    = fc["GhiChu"];
                dh.Email     = fc["Email"];
                dh.Dienthoai = fc["DienThoai"];
            }

            dh.NgayDatMua   = DateTime.Now;
            dh.PhiVanChuyen = 1000000;
            dh.TinhTrangDh  = 0;
            dh.Tongtien     = double.Parse(fc["GiaTriDonHang"]);
            dh.GiamGia      = double.Parse(fc["GiamGia"]);

            dh.Ghichu      = fc["GhiChu"];
            dh.TinhTrangDh = 1;
            //dh.Diachi = fc["DiaChi"];
            context.DonHang.Add(dh);
            context.SaveChanges();

            _repository.NotifyDonHang();
            var content = System.IO.File.ReadAllText("GioHang.html");

            content = content.Replace("{{Hoten}}", dh.HoTen);

            var strCtdh = "";
            var index   = 0;
            var gh      = HttpContext.Session.GetObjectFromJson <List <ChiTietDonHang> >("GioHang");

            foreach (var item in gh)
            {
                item.MaCtdh = (context.ChiTietDonHang.ToList().Count + 1).ToString();
                item.MaDh   = dh.MaDh;
                context.SanPham.Find(item.MaSp).SoLuong =
                    context.SanPham.Find(item.MaSp).SoLuong - item.SoLuong;
                context.ChiTietDonHang.Add(item);
                context.SaveChanges();
                strCtdh = strCtdh + "<tr>";
                strCtdh = strCtdh + "<td style='text-align:center'>" + ++index + "</td><td>" +
                          context.SanPham.Find(item.MaSp).TenSp + "</td><td  style='text-align:center'>"
                          + item.SoLuong + "</td><td  style='text-align:center'>"
                          + ((context.SanPham.Find(item.MaSp).GiaGoc *item.SoLuong).HasValue
                              ? (context.SanPham.Find(item.MaSp).GiaGoc *item.SoLuong)?.ToString("N0")
                              : "NULL") + "</td><tr>";
            }

            content = content.Replace("{{thongtindonhang}}", HtmlEncoder.Default.Encode(strCtdh));
            content = content.Replace("{{madh}}", dh.MaDh.ToUpper());
            content = content.Replace("{{diachi}}", dh.Diachi);
            content = content.Replace("{{thanhtien}}",
                                      dh.Tongtien.Value.ToString("N0"));
            content = content.Replace("{{sdt}}", dh.Dienthoai);
            content = content.Replace("{{giamgia}}", dh.GiamGia.Value.ToString("N0"));
            content = content.Replace("{{thanhtoan}}", (-dh.GiamGia.Value + dh.Tongtien.Value).ToString("N0"));
            var Option = new AuthMessageSenderOptions
            {
                SendGridKey  = context.Parameters.Find("2").Value,
                SendGridUser = context.Parameters.Find("1").Value
            };

            var mailSender = new EmailSender(Option);


            mailSender.SendEmailAsync(dh.Email, "Chi tiết đơn hàng ", $"{WebUtility.HtmlDecode(content)}");

            HttpContext.Session.DeleteAllSession();

            return(RedirectToAction("ChiTietDonHang", "GioHang", new { id = dh.MaDh })
                   .WithSuccess("Đặt hàng thành công", ""));
        }
 public EmailSender(IOptions <SmtpConfiguration> options)
 {
     _options = options.Value.AuthMessageSenderOptions;
     _sender  = options.Value.UserEmail;
 }
Пример #23
0
 public EmailSender(AuthMessageSenderOptions senderOptions)
 {
     Options = senderOptions;
 }
 public GebruikerController(PollContext context, IGebruikerService gebruikerService, IOptions <AuthMessageSenderOptions> authMessageSenderOptions)
 {
     _context                  = context;
     _gebruikerService         = gebruikerService;
     _authMessageSenderOptions = authMessageSenderOptions.Value;
 }
Пример #25
0
 public EmailSender(IOptions <AuthMessageSenderOptions> optionsAccessor)
 {
     _options = optionsAccessor.Value;
 }
Пример #26
0
 public EmailService(IHostingEnvironment hostingEnvironment, AuthMessageSenderOptions authMessageSenderOptions)
 {
     HostingEnvironment       = hostingEnvironment;
     AuthMessageSenderOptions = authMessageSenderOptions;
 }