public async Task <IActionResult> GetAllPatientJournals([FromBody] GetAllPatientJournalslWithCapViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            HttpParameters httpParameters =
                HttpParametersService
                .GetHttpParameters(
                    model,
                    ConfigHelper.AppSetting(Constants.ServerUrls, Constants.GetAllPatientJournals),
                    HttpMethod.Post,
                    string.Empty,
                    authorization);

            GetAllPatientJournalsResponse getPatientJournalsResult =
                await _gWService.PostTo <GetAllPatientJournalsResponse>(httpParameters);


            if (getPatientJournalsResult.StatusCode == 422)
            {
                return(await ResponseService
                       .GetResponse <UnprocessableEntityObjectResult, GetAllPatientJournalsResponse>(getPatientJournalsResult, ModelState));
            }

            return(new OkObjectResult(getPatientJournalsResult));
        }
        public async Task <IActionResult> GetPatientJournalById([FromQuery] Guid id, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id == Guid.Empty)
            {
                return(new JsonResult(new { error = "error" }));
            }

            HttpParameters httpParameters =
                HttpParametersService.GetHttpParameters(
                    null,
                    ConfigHelper.AppSetting(AerendeConstants.ServerUrls, AerendeConstants.GetPatientJournalById),
                    HttpMethod.Get,
                    id.ToString(),
                    authorization
                    );

            GetPatientJournalResponse patientJournalResponse = await _aerendeService.Get <GetPatientJournalResponse>(httpParameters);

            return(new JsonResult(patientJournalResponse));
        }
        public async Task <IActionResult> GetPatientJournalById(Guid id, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id == Guid.Empty)
            {
                return(BadRequest("id can not be empty"));
            }

            HttpParameters httpParameters =
                HttpParametersService.GetHttpParameters(
                    null,
                    ConfigHelper.AppSetting(Constants.ServerUrls, Constants.GetPatientJournalById),
                    HttpMethod.Get,
                    id.ToString(),
                    authorization
                    );

            GetPatientJournalResponse patientJournalResult = await _gWService.Get <GetPatientJournalResponse>(httpParameters);

            if (patientJournalResult.StatusCode == 400)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, GetPatientJournalResponse>(patientJournalResult, ModelState));
            }
            else if (patientJournalResult.StatusCode == 404)
            {
                return(await ResponseService.GetResponse <NotFoundObjectResult, GetPatientJournalResponse>(patientJournalResult, ModelState));
            }

            return(new OkObjectResult(patientJournalResult));
        }
        // POST api/gateway/login
        public async Task <IActionResult> LogIn([FromBody] LogInViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Prepare httpParameters for request
            HttpParameters httpParameters =
                HttpParametersService.GetHttpParameters(
                    model,
                    ConfigHelper.AppSetting(Constants.ServerUrls, Constants.Auth),
                    HttpMethod.Post,
                    string.Empty);

            //httpclient request from class library
            JwtResponse authResult = await _gWService.PostTo <JwtResponse>(httpParameters);

            if (authResult.StatusCode == 400)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, JwtResponse>(authResult, ModelState));
            }

            //return jwt token
            return(new OkObjectResult(authResult));
        }
        public async Task <IActionResult> GetUserRoles(string id, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                BadRequest(id);
            }

            HttpParameters httpParameters = HttpParametersService
                                            .GetHttpParameters(
                null,
                ConfigHelper.AppSetting(Constants.ServerUrls, Constants.GetUserRoles),
                HttpMethod.Get,
                id,
                authorization
                );

            GetUserRolesResponse getUserRolesResult = await _gWService.Get <GetUserRolesResponse>(httpParameters);


            if (getUserRolesResult.StatusCode == 404)
            {
                return(await ResponseService.GetResponse <NotFoundObjectResult, GetUserRolesResponse>(getUserRolesResult, ModelState));
            }
            else if (getUserRolesResult.StatusCode == 401)
            {
                return(await ResponseService.GetResponse <UnauthorizedObjectResult, GetUserRolesResponse>(getUserRolesResult, ModelState));
            }
            else if (getUserRolesResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, GetUserRolesResponse>(getUserRolesResult, ModelState));
            }


            return(new OkObjectResult(getUserRolesResult));
        }
        public async Task <IActionResult> DeleteUser(DeleteUserViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(model));
            }

            HttpParameters httpParameters = HttpParametersService
                                            .GetHttpParameters(
                model,
                ConfigHelper.AppSetting(Constants.ServerUrls, Constants.DeleteUser),
                HttpMethod.Delete,
                string.Empty,
                authorization
                );

            DeleteUserResponse deleteUserResult = await _gWService.PostTo <DeleteUserResponse>(httpParameters);

            if (deleteUserResult.StatusCode == 404)
            {
                return(await ResponseService.GetResponse <NotFoundObjectResult, DeleteUserResponse>(deleteUserResult, ModelState));
            }
            else if (deleteUserResult.StatusCode == 422)
            {
                return(await ResponseService.GetResponse <UnprocessableEntityObjectResult, DeleteUserResponse>(deleteUserResult, ModelState));
            }
            else if (deleteUserResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, DeleteUserResponse>(deleteUserResult, ModelState));
            }

            return(new OkObjectResult(deleteUserResult));
        }
        // POST api/gateway/addusertorole
        public async Task <IActionResult> AddUserToRole(AddUserToRoleViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            HttpParameters httParameters =
                HttpParametersService
                .GetHttpParameters(
                    model,
                    ConfigHelper.AppSetting(Constants.ServerUrls, Constants.AddUserToRole),
                    HttpMethod.Put,
                    string.Empty,
                    authorization
                    );

            AddUserToRoleResponse addUserToRoleResult = await _gWService.PostTo <AddUserToRoleResponse>(httParameters);

            if (addUserToRoleResult.StatusCode == 401)
            {
                return(await ResponseService.GetResponse <UnauthorizedObjectResult, AddUserToRoleResponse>(addUserToRoleResult, ModelState));
            }
            else if (addUserToRoleResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, AddUserToRoleResponse>(addUserToRoleResult, ModelState));
            }

            return(new OkObjectResult(addUserToRoleResult));
        }
Example #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //AppHttpContext.Services = app.ApplicationServices;
            app.UseSession();
            if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }



            app.UseStaticFiles();
            NLog.GlobalDiagnosticsContext.Set("defaultConnection", ConfigHelper.AppSetting("PORTAL_LOG"));
            NLog.LogManager.LoadConfiguration(env.ContentRootPath + "\\NLog.config");
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Vehicle}/{action=Index}/{id?}");
            });
        }
Example #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Bind JwtIssuerOptions to C# class
            IConfigurationSection JwtIssuerOptionsSection = Configuration.GetSection(Constants.JwtIssuer.JwtIssuerOptions);

            services.Configure <JwtIssuerOptions>(JwtIssuerOptionsSection);
            JwtIssuerOptions JwtIssuerOptionsSectionSettings = JwtIssuerOptionsSection.Get <JwtIssuerOptions>();

            //Bind JwtIssuerOptions to C# class

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            //Get Symetrickey (!Should be Readonly Private!)
            SymmetricSecurityKey _signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(
                        ConfigHelper.AppSetting(
                            Constants.AppSettingStrings.AppSettings,
                            Constants.AppSettingStrings.Secret
                            )));

            //Moved JWT validation to a ClassLibrary. So it can be reused.
            services.AddValidationParameters(
                JwtIssuerOptionsSectionSettings.Issuer,
                JwtIssuerOptionsSectionSettings.Audience,
                _signingKey
                );

            //Services
            services.AddScoped <IHttpRepo, HttpRepo>();
            services.AddScoped <IGWService, GWService>();
        }
Example #10
0
        public string BuildToken(UserPrepareTokenModel user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                new Claim(JwtRegisteredClaimNames.Email, user.Email ?? ""),
                new Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Name)
            };

            if (user.IsAdministrator)
            {
                claims.Add(new Claim("role", "Administrator"));
            }
            string jwtKey = ConfigHelper.AppSetting("Jwt", "Key");
            var    key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
            var    creds  = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                null, null,
                claims,
                expires: DateTime.Now.AddMinutes(250),
                signingCredentials: creds);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        // POST api/gateway/signup
        public async Task <IActionResult> SignUp([FromBody] RegistrationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                BadRequest(ModelState);
            }

            //Prepare httpParameters for request
            HttpParameters httParameters =
                HttpParametersService.GetHttpParameters(
                    model,
                    ConfigHelper.AppSetting(Constants.ServerUrls, Constants.SignUp),
                    HttpMethod.Post,
                    string.Empty
                    );

            SignUpResponse signUpResult = await _gWService.PostTo <SignUpResponse>(httParameters);

            if (signUpResult.StatusCode == 422)
            {
                return(await ResponseService.GetResponse <UnprocessableEntityObjectResult, SignUpResponse>(signUpResult, ModelState));
            }
            else if (signUpResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, SignUpResponse>(signUpResult, ModelState));
            }

            return(new OkObjectResult(signUpResult));
        }
Example #12
0
        private static void TestAuthorization(string authorization)
        {
            (string username, string password) = BasicAuthHelper.GetUsernameAndPasswordFromAuthorizeHeader(authorization);
            string properUsername = ConfigHelper.AppSetting("BasicAuth", "Username");
            string properPassword = ConfigHelper.AppSetting("BasicAuth", "Password");

            if (username != properUsername || password != properPassword)
            {
                throw new System.Exception("Unauthorized");
            }
        }
Example #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            //AddFluentValidation
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>())
            //Ignore when JSON contains Self referanceLoop
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            //Seeders
            services.AddScoped <IInvoiceSeeder, InvoiceSeeder>();
            services.AddScoped <IAerendeSeeder, AerendeSeeder>();
            services.AddScoped <ITypeOfSeeder, TypeOfSeeder>();

            //Repositories
            services.AddScoped <IAerendeRepository, AerendeRepository>();
            //AerendeServices
            services.AddScoped <IAerendeService, AerendeService>();

            //InvoiceContext
            services.AddDbContext <InvoiceContext>(config =>
            {
                config.UseSqlServer(ConfigHelper.AppSetting(DatabaseConstants.Connectionstrings, DatabaseConstants.InvoiceConnectionString));
            });

            //AerendeContext
            services.AddDbContext <AerendeContext>(config =>
            {
                config.UseSqlServer(ConfigHelper.AppSetting(DatabaseConstants.Connectionstrings, DatabaseConstants.AerendeConnectionString));
            });

            //TypeOfContext
            services.AddDbContext <TypeOfContext>(config =>
            {
                config.UseSqlServer(ConfigHelper.AppSetting(DatabaseConstants.Connectionstrings, DatabaseConstants.TypeOfConnectionString));
            });

            //Get Symetrickey (!Should be Readonly Private!)
            SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(ConfigHelper.AppSetting(DatabaseConstants.AppSettnings, DatabaseConstants.Secret)));

            var signingCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);

            var issuer   = ConfigHelper.AppSetting(DatabaseConstants.JwtIssuerOptions, DatabaseConstants.Issuer);
            var audience = ConfigHelper.AppSetting(DatabaseConstants.JwtIssuerOptions, DatabaseConstants.Audience);

            //Moved JWT validation to a ClassLibrary. So it can be reused.
            services.AddValidationParameters(issuer, audience, _signingKey);
        }
Example #14
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public Log4NetAdapter()
        {
            var logConfigPath = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config");

            if (logConfigPath.Exists)
            {
                XmlConfigurator.ConfigureAndWatch(logConfigPath);
            }
            else
            {
                XmlConfigurator.Configure();
            }
            var logName = ConfigHelper.AppSetting("LoggerName", "DefaultLog");

            _log = LogManager.GetLogger(logName);
        }
Example #15
0
        public SmtpService()
        {
            _logger = new Log4NetAdapter();
            //配置文件虚拟路径
            var path = ConfigHelper.AppSetting("EmailConfigPath", "");

            filePath = HttpContext.Current.Server.MapPath(path == null ? "~/Config/EmailConfig.json" : path);
            try
            {
                var config = FileHelper.ReadFile(filePath);
                email = JsonConvert.DeserializeObject <EmailAccount>(config);
            }
            catch (Exception ex)
            {
                _logger.Error("读取配置文件出错,请检查配置文件是否存在!", ex);
            }
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            //Get Symetrickey (!Should be Readonly Private!)
            SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(ConfigHelper.AppSetting(AerendeConstants.AppSettnings, AerendeConstants.Secret)));

            var issuer   = ConfigHelper.AppSetting(AerendeConstants.JwtIssuerOptions, AerendeConstants.Issuer);
            var audience = ConfigHelper.AppSetting(AerendeConstants.JwtIssuerOptions, AerendeConstants.Audience);

            //Moved JWT validation to a ClassLibrary. So it can be reused.
            services.AddValidationParameters(issuer, audience, _signingKey);

            services.AddScoped <IAerendeRepository, AerendeRepository>();
            services.AddScoped <IAerendeService, AerendeService>();
        }
        public FakeDynamicMailManager()
        {
            var type = ConfigHelper.AppSetting("FakeMailerType", FakeMailType.File);

            switch (type)
            {
            case FakeMailType.Console: mailer = new FakeConsoleMailManager(); break;

            case FakeMailType.Debug: mailer = new FakeDebugMailManager(); break;

            case FakeMailType.Trace: mailer = new FakeTraceMailManager(); break;

            case FakeMailType.File: mailer = new FakeFileMailManager(); break;

            case FakeMailType.None: mailer = null; break;

            default:
                throw new Exception("invalid fake mailer type: " + type);
            }
        }
        public async Task <IActionResult> GetAllUsers([FromHeader] string authorization)
        {
            HttpParameters httpParameters = HttpParametersService
                                            .GetHttpParameters(
                null,
                ConfigHelper.AppSetting(Constants.ServerUrls, Constants.GetAllUsers),
                HttpMethod.Get,
                string.Empty,
                authorization
                );

            GetAllUsersResponse getAllRolesResult = await _gWService.Get <GetAllUsersResponse>(httpParameters);

            if (getAllRolesResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, GetAllUsersResponse>(getAllRolesResult, ModelState));
            }

            return(new OkObjectResult(getAllRolesResult));
        }
        public FakeDynamicSmsService()
        {
            var type = ConfigHelper.AppSetting("FakeSmsServiceType", FakeSmsServiceType.File);

            switch (type)
            {
            case FakeSmsServiceType.Console: sender = new FakeConsoleSmsService(); break;

            case FakeSmsServiceType.Debug: sender = new FakeDebugSmsService(); break;

            case FakeSmsServiceType.Trace: sender = new FakeTraceSmsService(); break;

            case FakeSmsServiceType.File: sender = new FakeFileSmsService(); break;

            case FakeSmsServiceType.None: sender = null; break;

            default:
                throw new Exception("invalid fake sms service type: " + type);
            }
        }
        public async Task <IActionResult> GetAllPatientJournals(GetAllPatientJournalslWithCapViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            HttpParameters httpParameters =
                HttpParametersService.GetHttpParameters(
                    model,
                    ConfigHelper.AppSetting(AerendeConstants.ServerUrls, AerendeConstants.PatientJournals),
                    HttpMethod.Post,
                    string.Empty,
                    authorization
                    );

            GetAllPatientJournalsResponse getPatientJournalsResult = await _aerendeService.PostTo <GetAllPatientJournalsResponse>(httpParameters);

            return(new JsonResult(getPatientJournalsResult));
        }
Example #21
0
        static WebConstants()
        {
            MultiLanguageRouting = ConfigHelper.AppSetting <MultiLanguageRoutingOptions>("MultiLanguageRoutingOption");
            MultiLanguageAreas   = ConfigHelper.AppSetting <MultiLanguageRoutingOptions>("MultiLanguageAreasOption", MultiLanguageRouting);
            MultiLanguageClientAwareController = ConfigHelper.AppSetting <MultiLanguageRoutingOptions>("MultiLanguageClientAwareControllerOption", MultiLanguageRouting);

            SeparateClientSideResourcesByLanguage       = ConfigHelper.AppSetting <bool>("SeparateClientSideResourcesByLanguage");
            SeparateClientSideDynamicFilesByLanguage    = ConfigHelper.AppSetting <bool>("SeparateClientSideDynamicFilesByLanguage");
            SeparateClientSideStaticFilesByLanguage     = ConfigHelper.AppSetting <bool>("SeparateClientSideStaticFilesByLanguage");
            SeparateClientSideRazorViewsByLanguage      = ConfigHelper.AppSetting <bool>("SeparateClientSideRazorViewsByLanguage");
            SeparateClientSideDatabaseRecordsByLanguage = ConfigHelper.AppSetting <bool>("SeparateClientSideDatabaseRecordsByLanguage");

            CssStaticResourceDefaultBasePath          = WebConfigurationManager.AppSettings[CSS_STATIC_RESOURCE_PATH_KEY]?.Trim();
            CssDynamicResourceDefaultBasePath         = WebConfigurationManager.AppSettings[CSS_DYNAMIC_RESOURCE_BASEPATH_KEY]?.Trim();
            CssDynamicResourceResourceDefaultBasePath = WebConfigurationManager.AppSettings[CSS_DYNAMIC_RESOURCE_RESOURCE_BASEPATH_KEY]?.Trim();
            JsStaticResourceDefaultBasePath           = WebConfigurationManager.AppSettings[JS_STATIC_RESOURCE_PATH_KEY]?.Trim();
            JsDynamicResourceDefaultBasePath          = WebConfigurationManager.AppSettings[JS_DYNAMIC_RESOURCE_BASEPATH_KEY]?.Trim();
            JsDynamicResourceResourceDefaultBasePath  = WebConfigurationManager.AppSettings[JS_DYNAMIC_RESOURCE_RESOURCE_BASEPATH_KEY]?.Trim();

            MinifyCss = WebConfigurationManager.AppSettings["MinifyCss"]?.Trim();
            MinifyJs  = WebConfigurationManager.AppSettings["MinifyJs"]?.Trim();
        }
        // PUT api/gateway/removeuserfromrole
        public async Task <IActionResult> RemoveUserFromRole(RemoveUserfromRoleViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            HttpParameters httpParameters = HttpParametersService
                                            .GetHttpParameters(
                model,
                ConfigHelper.AppSetting(Constants.ServerUrls, Constants.RemoveUserFromRole),
                HttpMethod.Put,
                string.Empty,
                authorization
                );

            RemoveUserfromRoleResponse removeUserFromRoleResult =
                await _gWService.PostTo <RemoveUserfromRoleResponse>(httpParameters);

            if (removeUserFromRoleResult.StatusCode == 404)
            {
                return(await
                       ResponseService.GetResponse <NotFoundObjectResult, RemoveUserfromRoleResponse>(removeUserFromRoleResult, ModelState));
            }
            else if (removeUserFromRoleResult.StatusCode == 422)
            {
                return(await ResponseService.GetResponse <UnprocessableEntityObjectResult, RemoveUserfromRoleResponse>(removeUserFromRoleResult, ModelState));
            }
            else if (removeUserFromRoleResult.StatusCode == 401)
            {
                return(await ResponseService.GetResponse <UnauthorizedObjectResult, RemoveUserfromRoleResponse>(removeUserFromRoleResult, ModelState));
            }
            else if (removeUserFromRoleResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, RemoveUserfromRoleResponse>(removeUserFromRoleResult, ModelState));
            }

            return(new OkObjectResult(removeUserFromRoleResult));
        }
Example #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IUserService, UserService>();

            services.AddMvc(
                config =>
            {
                config.Filters.Add(typeof(ExceptionHandler));
            }
                );
            services.Configure <AppSetting>(Configuration.GetSection("AppSettings"));
            ServiceConfig.ServiceUrl        = new Uri(ConfigHelper.AppSetting("ServiceUrl"));
            ServiceConfig.WebApplicationUrl = new Uri(ConfigHelper.AppSetting("WebApplicationUrl"));
            ServiceConfig.CommonServiceUrl  = new Uri(ConfigHelper.AppSetting("CommonServiceUrl"));
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(20);
            });
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});
        }
        public DynamicExceptionLogger()
        {
            var type = ConfigHelper.AppSetting("ExceptionLogger.Type", ExceptionLoggerType.Null);

            switch (type)
            {
            case ExceptionLoggerType.Null:
                Instance = new NullExceptionLogger();
                break;

            case ExceptionLoggerType.Console:
                Instance = new ConsoleExceptionLogger();
                break;

            case ExceptionLoggerType.Debug:
                Instance = new DebugExceptionLogger();
                break;

            case ExceptionLoggerType.File:
                Instance = CreateFileExceptionLogger();
                break;

            case ExceptionLoggerType.Memory:
                Instance = new MemoryExceptionLogger(CreateMemoryLogger());
                break;

            case ExceptionLoggerType.SqlServer:
                CreateSqlServerExceptionLogger();
                break;

            case ExceptionLoggerType.SqlServerNull:
                CreateSqlServerExceptionLogger(new NullExceptionLogger());
                break;

            case ExceptionLoggerType.SqlServerConsoleNull:
                CreateSqlServerExceptionLogger(new ConsoleExceptionLogger(new NullExceptionLogger()));
                break;

            case ExceptionLoggerType.SqlServerDebugNull:
                CreateSqlServerExceptionLogger(new DebugExceptionLogger(new NullExceptionLogger()));
                break;

            case ExceptionLoggerType.SqlServerFileConsoleNull:
                CreateSqlServerExceptionLogger(CreateFileExceptionLogger(new ConsoleExceptionLogger(new NullExceptionLogger())));
                break;

            case ExceptionLoggerType.SqlServerFileDebugNull:
                CreateSqlServerExceptionLogger(CreateFileExceptionLogger(new DebugExceptionLogger(new NullExceptionLogger())));
                break;

            case ExceptionLoggerType.SqlServerFileMemoryConsoleNull:
                CreateSqlServerExceptionLogger(CreateFileExceptionLogger(new MemoryExceptionLogger(CreateMemoryLogger(), new ConsoleExceptionLogger(new NullExceptionLogger()))));
                break;

            case ExceptionLoggerType.SqlServerFileMemoryDebugNull:
                CreateSqlServerExceptionLogger(CreateFileExceptionLogger(new MemoryExceptionLogger(CreateMemoryLogger(), new DebugExceptionLogger(new NullExceptionLogger()))));
                break;

            case ExceptionLoggerType.FileNull:
                Instance = CreateFileExceptionLogger(new NullExceptionLogger());
                break;

            case ExceptionLoggerType.FileConsoleNull:
                Instance = CreateFileExceptionLogger(new ConsoleExceptionLogger(new NullExceptionLogger()));
                break;

            case ExceptionLoggerType.FileDebugNull:
                Instance = CreateFileExceptionLogger(new DebugExceptionLogger(new NullExceptionLogger()));
                break;

            default:
                throw new Exception("invalid exception logger type: " + type);
            }
        }
Example #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Astro API V1");
                c.RoutePrefix = string.Empty;
            });

            NLog.GlobalDiagnosticsContext.Set("defaultConnection", ConfigHelper.AppSetting("PORTAL_LOG", CommonConstants.connectionStrings));

            NLog.LogManager.LoadConfiguration(env.ContentRootPath + "\\NLog.config");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //CultureInfo cultureInfo = new CultureInfo("en-US");
                //cultureInfo.DateTimeFormat.ShortDatePattern = ConfigHelper.AppSetting("DateFormat", CommonConstants.AppSettings);
                //app.UseRequestLocalization(new RequestLocalizationOptions()
                //{
                //    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(cultureInfo, cultureInfo),
                //    SupportedCultures = new List<CultureInfo>() { cultureInfo },
                //    SupportedUICultures = new List<CultureInfo>() { cultureInfo }
                //});
                app.UseSession();

                //app.UseCors("_myAllowSpecificOrigins");

                app.UseCors(builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
                app.UseAuthentication();



                //app.UseStaticFiles();// For the wwwroot folder

                //app.UseStaticFiles(new StaticFileOptions
                //{
                //    FileProvider = new PhysicalFileProvider(
                //                Path.Combine(Directory.GetCurrentDirectory(),
                //                "Attachments")),
                //    RequestPath = "/Attachments"
                //});



                ////Enable directory browsing
                //app.UseDirectoryBrowser(new DirectoryBrowserOptions
                //{
                //    FileProvider = new PhysicalFileProvider(
                //                Path.Combine(Directory.GetCurrentDirectory(), "Attachments")),
                //    RequestPath = "/Attachments"
                //});

             

                app.UseMvc();
                app.UseCors(CorsPolicy);
                //app.UseEndpoint(endpoints =>
                //{
                //    endpoints.MapControllers();
                //    endpoints.MapHub<CallHub>("/coolmessages");
                //})
            }
        }