Esempio n. 1
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("NoteBDD");

            services.AddMvc();

            if (CurrentEnvironment.IsEnvironment("Testing"))
            {
                services.AddDbContext <notepriveeContext>(options => options.UseInMemoryDatabase("FakeDB"));
            }
            else
            {
                services.AddDbContext <notepriveeContext>(options => options.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 21))));
                services.AddMarkdown();
            }

            services.AddControllersWithViews();
            services.AddMvcCore().AddApiExplorer();
            services.AddAuthentication("CookieAuthentication")
            .AddCookie("CookieAuthentication", config =>
            {
                config.Cookie.Name = "UserLoginCookie";
                config.LoginPath   = "/Admin/Login";
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "Note Privée API",
                    Version = "v1"
                });
            });
        }
Esempio n. 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.AddDefaultIdentity <User>(options =>
            {
                options.SignIn.RequireConfirmedAccount  = true;
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
            })
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

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

            // Custom services
            if (CurrentEnvironment.IsDevelopment())
            {
                services.Configure <SmtpSettings>(Configuration.GetSection("SmtpDevelopmentSettings"));
            }
            else
            {
                services.Configure <SmtpSettings>(Configuration.GetSection("SmtpReleaseSettings"));
            }
            services.AddMailer();
            services.AddSession();
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CatalogSettings>(Configuration);

            var connectionString = Configuration["ConnectionString"];

            if (CurrentEnvironment.IsProduction())
            {
                var server   = Configuration["DatabaseServer"];
                var database = Configuration["DatabaseName"];
                var user     = Configuration["DatabaseUser"];
                var password = Configuration["DatabaseNamePassword"];
                connectionString =
                    $"Server={server};Database={database};User Id={user};Password={password};MultipleActiveResultSets=true";
            }

            services.AddDbContext <CatalogContext>(opt => opt.UseSqlServer(connectionString));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(opt =>
            {
                opt.DescribeAllEnumsAsStrings();
                opt.SwaggerDoc("v1", new Info()
                {
                    Title          = "Product Container - Product Catalog HTTP API",
                    Version        = "V1",
                    Description    = "The Product Catalog Microservice HTTP API. This is Data driven/CRUD microservice sample",
                    TermsOfService = "Terms of Service"
                });
            });
        }
Esempio n. 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddReact();
            services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName).AddChakraCore();

            if (CurrentEnvironment.IsEnvironment("Testing"))
            {
                services.AddDbContext <ApplicationDbContext>
                    (options => options.UseInMemoryDatabase("TestingDB"));
            }
            else
            {
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }



            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.WithOrigins("http://localhost:50449", "http://localhost:51158").AllowAnyHeader().AllowAnyMethod();
                });
            });
        }
Esempio n. 5
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddNodeServices(options =>
            {
                if (CurrentEnvironment.IsDevelopment())
                {
                    options.LaunchWithDebugging = true;
                    options.DebuggingPort       = 9229;
                    options.ProjectPath         = "../Frontend/ClientApp";
                }
                else
                {
                    options.ProjectPath = "ClientApp/";
                }
            });

            services.AddSpaPrerenderer();
            services.AddSingleton(GetPrerenderContent());
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });


            var accountOptions = new AccountOptions(
                Configuration[Defaults.ORGANIZATION_ID],
                Configuration[Defaults.TECHNICAL_ACCOUNT_ID],
                Configuration[Defaults.CLIENT_ID],
                Configuration[Defaults.CLIENT_SECRET]);


            var securityKey = GetSecurityKey(Configuration[Defaults.CERTIFICATE_PATH]);
            var reactorApi  = new ReactorApi(accountOptions, securityKey);


            services
            .AddSingleton(reactorApi)
            .AddSingleton <ReactorService>();


            services.AddCors(options =>
            {
                options.AddPolicy(Defaults.ALL_CORS_POLICY,
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
Esempio n. 6
0
        IEnumerator ChangeEnvironment()
        {
            //fade to next environment, then back to first one once you reach the last
            yield return(new WaitForSeconds(10));

            if (!gameOver)
            {
                currentEnvironment = CurrentEnvironment.CITY;
                FadeSprite(forrestSprite, 0, 2f);
                FadeSprite(citySprite, 1, 2f);
                yield return(new WaitForSeconds(10));

                if (!gameOver)
                {
                    currentEnvironment = CurrentEnvironment.TOWN;
                    FadeSprite(citySprite, 0, 2f);
                    FadeSprite(townSprite, 1, 2f);
                    yield return(new WaitForSeconds(10));

                    if (!gameOver)
                    {
                        currentEnvironment = CurrentEnvironment.FORREST;
                        FadeSprite(townSprite, 0, 2f);
                        FadeSprite(forrestSprite, 1, 2f);
                        StartCoroutine("ChangeEnvironment");
                    }
                }
            }
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false).AddNewtonsoftJson().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers();

            var HostURLs = new List <string>();

            Configuration.GetSection("UTAPConfiguration:HostURLs").Bind(HostURLs);
            string[] origins = HostURLs.ToArray();

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins(origins);
            }));
            if (CurrentEnvironment.IsDevelopment())
            {
                services.AddTransient <IAuthorizationHandler, DisableAuthorizationHandler <IAuthorizationRequirement> >();
            }
            else
            {
                services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority            = "http://localhost:4999";
                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";
                });
            }
            services.AddSignalR();
        }
Esempio n. 8
0
 public LoggedInHelper(IHttpContextAccessor httpContextAccessor, CurrentEnvironment environment, IJwtDecoder decoder, ILogger <LoggedInHelper> logger)
 {
     _httpContextAccessor = httpContextAccessor;
     _environment         = environment;
     _decoder             = decoder;
     _logger = logger;
 }
Esempio n. 9
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;
            });

            // Use InMemory in Development
            if (CurrentEnvironment.IsDevelopment())
            {
                services.AddDbContext <AppIdentityDbContext>(options =>
                                                             options.UseInMemoryDatabase("Identity"));
            }
            else
            {
                services.AddDbContext <AppIdentityDbContext>(options =>
                                                             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                                                                  b => b.MigrationsAssembly(typeof(Startup).Assembly.FullName)));
            }

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores <AppIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCors();

            if (CurrentEnvironment.IsDevelopment())
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                services.AddDistributedRedisCache(options =>
                {
                    options.Configuration = "redis";
                    // options.InstanceName = "master";
                });
            }

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Game API", Version = "v1"
                });
            });

            services.AddSingleton <IGameService, GameService>();
            services.AddSingleton <IArmaService, ArmaService>();
            services.AddSingleton <ILocalService, LocalService>();
            services.AddSingleton <ISuspeitoService, SuspeitoService>();
        }
Esempio n. 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddDbContext<MineSweeperContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:LocalDb"]));

//            string connectionString = Environment.GetEnvironmentVariable("DefaultConnection").ToString();
            if (CurrentEnvironment.IsEnvironment("Testing"))
            {
                services.AddDbContext <MineSweeperContext>(options =>
                                                           options.UseInMemoryDatabase("TestingDB"));
            }
            else
            {
                services.AddDbContext <MineSweeperContext>(options =>
                                                           options.UseInMemoryDatabase("TestingDB"));
                //services.AddDbContext<MineSweeperContext>(options =>
                //    options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
                //services.AddDbContext<MineSweeperContext>(options =>
                //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }

            services.AddIdentity <Player, IdentityRole>(options => { options.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultProvider; }).AddEntityFrameworkStores <MineSweeperContext>().AddDefaultTokenProviders();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddScoped <GameFacade>();
            //services.AddSingleton<Games>();
        }
Esempio n. 12
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);
            {
                services.AddMvc();
                if (CurrentEnvironment.IsProduction())
                {
                    Console.WriteLine("Production Mode");
                    services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Grabble.Order.Api")));
                }
                else
                if (CurrentEnvironment.IsStaging())
                {
                    Console.WriteLine("Staging Mode");
                    services.AddDbContext <ApplicationContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
                }
                else
                {
                    Console.WriteLine("Development Mode");
                    services.AddDbContext <ApplicationContext>(options => options.UseMySql(Configuration.GetConnectionString("connDevelopment")));
                }

                services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
                services.AddTransient <IOrderService, OrderService>();
            }
        }
Esempio n. 13
0
        public override SkryptObject VisitAssignNameStatement(SkryptParser.AssignNameStatementContext context)
        {
            var variable = CurrentEnvironment.GetVariable(context.name().GetText());

            if (variable.IsConstant)
            {
                _engine.ErrorHandler.FatalError(context.Start, "Constant cannot be redefined.");
            }

            var value = Visit(context.expression());

            if (value is IValue noref)
            {
                value = noref.Copy();
            }

            var op = ((SkryptParser.AssignOperatorContext)context.assign()).Operator;

            if (op != null)
            {
                value = EvaluateExpression(op.Text, variable.Value, value, op);
            }

            variable.Value = value;

            LastResult = value;

            return(value);
        }
Esempio n. 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddCustomHeaders();

            if (CurrentEnvironment.IsProduction())
            {
                services.Configure <MvcOptions>(options =>
                {
                    options.Filters.Add(new RequireHttpsAttribute());
                });
            }

            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
            services.AddResponseCompression(options =>
            {
                options.MimeTypes      = new[] { "image/png", "image/jpg", "application/font-woff", "application/font-woff2", "application/javascript", "text/plain", "text/css", "text/html", "application/json", "text/json" };
                options.EnableForHttps = true;
            });

            services.Configure <List <Portfolio> >(Configuration.GetSection("Portfolios"));
            services.Configure <List <EnumCategory> >(Configuration.GetSection("EnableCategorys"));
            services.Configure <Settings>(Configuration.GetSection("Settings"));
        }
Esempio n. 15
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(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);;

            var connectionString = Configuration["ConnectionString"];

            if (CurrentEnvironment.IsProduction())
            {
                var server   = Configuration["DatabaseServer"];
                var database = Configuration["DatabaseName"];
                var user     = Configuration["DatabaseUser"];
                var password = Configuration["DatabaseNamePassword"];
                connectionString =
                    $"Server={server};Database={database};User Id={user};Password={password};MultipleActiveResultSets=true";
            }

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer(o => { o.IssuerUri = Configuration["IDENTITY_ISSUER"]; })
            .AddTestUsers(Config.GetUsers())
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
            })
            .AddDeveloperSigningCredential();
            //.AddCorsPolicyService<InMemoryCorsPolicyService>();

            services.AddAuthentication()
            .AddOpenIdConnect("oidc", "OpenID Connect",
                              opt =>
            {
                opt.SignInScheme  = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                opt.SignOutScheme = IdentityServerConstants.SignoutScheme;
                opt.SaveTokens    = true;

                opt.Authority = "https://demo.identityserver.io/";
                opt.ClientId  = "implicit";
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
        }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();
            var builder = services.AddMvc(option => option.EnableEndpointRouting = false)
                          .AddJsonOptions(jsonOptions =>                        //Added to disable camelCasing response
            {
                jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
            })
                          .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddHttpContextAccessor();
            SQLHandlerAsync.Connectionconfig = SQLHandler.Connectionconfig = Configuration.GetConnectionString("CbuilderConnection");
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("CbuilderConnection")));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 6;
                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;
                // User settings
                options.User.RequireUniqueEmail = true;
            });
            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                //options.Cookie.Expiration = TimeSpan.FromDays(150); old way
                options.ExpireTimeSpan = TimeSpan.FromDays(150);
                // If the LoginPath isn't set, ASP.NET Core defaults
                // the path to /Account/Login.
                options.LoginPath = "/Login";
                // If the AccessDeniedPath isn't set, ASP.NET Core defaults
                // the path to /Account/AccessDenied.
                options.AccessDeniedPath  = "/Account/AccessDenied";
                options.SlidingExpiration = true;
            });
            services.RegisterCbuilderServices(CurrentEnvironment);
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
            var razor = services.AddRazorPages();

            if (CurrentEnvironment.IsDevelopment())
            {
                razor.AddRazorRuntimeCompilation();
            }
            builder.LoadApplicationAssembly();
        }
Esempio n. 17
0
 void UIDesigner_Shown(object sender, EventArgs e)
 {
     CurrentScheme = new SchemeSerialization();
     if (!CurrentEnvironment.LoadScheme(CurrentScheme, CurrentEnvironment.AccountCoverFilename))
     {
         CurrentEnvironment.CreateScheme(CurrentScheme);
     }
     InitSuitItems();
 }
Esempio n. 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            // OPFC unit of work
            services.AddSingleton <IOpfcUow, OpfcUow>();
            services.AddSingleton <IServiceUow, ServiceUow>();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "OPFC API", Version = "v1"
                });
                c.MapType <System.Int64>(() => new Schema {
                    Type = "long"
                });
                c.MapType <System.Int32>(() => new Schema {
                    Type = "int"
                });
            });

            services.AddMvc();

            var key = Encoding.ASCII.GetBytes(OPFC.Constants.AppSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // configure dotenv
            services.AddEnv(builder => {
                builder
                .AddEnvFile(CurrentEnvironment.IsDevelopment() ? ".env.development" : ".env")
                .AddThrowOnError(false)
                .AddEncoding(Encoding.ASCII);
            });

            System.Console.WriteLine("BACKEND_BASE_URL: " + AppSettings.BACKEND_BASE_URL);
            System.Console.WriteLine("FRONTEND_BASE_URL: " + AppSettings.FRONTEND_BASE_URL);

            // configure DI for application services
            services.AddScoped <IUserService, UserService>();
        }
Esempio n. 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddDbContext <A2spaContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Register the Identity services.
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <A2spaContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Subject;
                //options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            // Register the OpenIddict services.
            services.AddOpenIddict(options =>
            {
                // Register the Entity Framework stores.
                options.AddEntityFrameworkCoreStores <A2spaContext>();

                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.AddMvcBinders();

                // Enable the authorization, logout, token or userinfo endpoints here:
                options.EnableTokenEndpoint("/connect/token");

                options.AllowPasswordFlow();

                // When request caching is enabled, authorization and logout requests are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using an external authentication provider like Google, Facebook or Twitter.
                // options.EnableRequestCaching();

                // During development, you can disable the HTTPS requirement.
                if (CurrentEnvironment.IsDevelopment())
                {
                    options.DisableHttpsRequirement();
                }
            });
        }
Esempio n. 20
0
        private string GetConnectionString()
        {
            if (CurrentEnvironment.IsDevelopment())
            {
                return(Configuration.GetConnectionString("Develop"));
            }

            return(ConnectionString);
        }
Esempio n. 21
0
        void ExecEvEdit()
        {
            if (!(EVarsList.SelectedItem is EVar sev))
            {
                return;
            }

            var ev = sev.Clone();

            var evbox = new EVarBox(CurrentEnvironment.FNames)
            {
                Title       = "Edit Environment Variable",
                DataContext = ev
            };

            evbox.Closing += (sender, args) => {
                var evb = (EVarBox)sender;

                if (evb.DialogResult != true)
                {
                    return;
                }

                if (EVars.Where(e => !e.Equals(sev)).Any(e => e.Name.Equals(ev.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    MessageBox.Show(
                        $"Variable '{ev.Name}' is already defined.\nPlease choose a different name.",
                        Strings.APP_NAME,
                        MessageBoxButton.OK,
                        MessageBoxImage.Error
                        );
                    args.Cancel = true;
                }
            };

            if (evbox.ShowDialog() != true)
            {
                return;
            }

            if (ev.Framework == sev.Framework)
            {
                sev.SetValue(ev);
                EVarsList.Items.Refresh();
            }
            else
            {
                CurrentEnvironment.Remove(sev);
                CurrentEnvironment.Add(ev, null);
                CurrentEnvironment.Render(EVars);
                EVarsList.SelectedItem = EVars.First(e => e.Name == ev.Name);
            }
            CurrentEnvironment.Dirty = true;

            UpdateColumnWidths(EVarsList);
        }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(setupAction =>
            {
                // If you ask for XML, but we don't support that you will get a 406
                setupAction.ReturnHttpNotAcceptable = true;
            })
            // Needed for Json Patch Document reading
            .AddNewtonsoftJson(setupAction =>
            {
                setupAction.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
            })
            .AddXmlDataContractSerializerFormatters()     // Add support for XML (Add this second so JSON is the default, it will use whatever comes first)
            .ConfigureApiBehaviorOptions(setupAction =>
            {
                setupAction.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetails = new ValidationProblemDetails(context.ModelState)
                    {
                        Type     = "https:courselibrary.com/modelvalidationproblem",
                        Title    = "One or more model validation errors occured.",
                        Status   = StatusCodes.Status422UnprocessableEntity,
                        Detail   = "See the errors property for details.",
                        Instance = context.HttpContext.Request.Path
                    };

                    problemDetails.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);

                    return(new UnprocessableEntityObjectResult(problemDetails)
                    {
                        ContentTypes = { "application/problem+json" }
                    });
                };
            });

            // Library used to map objects to DTOs
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddScoped <ICourseLibraryRepository, CourseLibraryRepository>();

            services.AddDbContext <CourseLibraryContext>(options =>
            {
                if (CurrentEnvironment.IsDevelopment())
                {
                    // Use local Docker DB
                    options.UseSqlServer(Configuration.GetConnectionString("CourseLibraryDB"));
                }
                else
                {
                    // In Prod use the Docker-Compose database
                    var connection = @"Server=db;Database=CourseLibraryDB;User=sa;Password=abcABC123;";
                    options.UseSqlServer(connection);
                }
            });
        }
Esempio n. 23
0
 public static IHostBuilder UseEnvironment(this IHostBuilder builder, string plugin, string config, string log)
 {
     builder.ConfigureService(services =>
     {
         IServiceCollection pool     = services.GetService(typeof(IServiceCollection)) as IServiceCollection;
         ICurrentEnvironment currenv = new CurrentEnvironment(plugin, config, log);
         pool.Add(ServiceDescriptor.Singleton <ICurrentEnvironment>(currenv));
     });
     return(builder);
 }
Esempio n. 24
0
        void ExecAiMoveUp()
        {
            if (!(AddinsList.SelectedItem is Addin ai))
            {
                return;
            }

            CurrentEnvironment.MoveUp(ai);
            CurrentEnvironment.Render(Addins);
            AddinsList.SelectedItem = Addins.First(a => a.Path == ai.Path);
        }
Esempio n. 25
0
        void ExecEvMoveUp()
        {
            if (!(EVarsList.SelectedItem is EVar ev))
            {
                return;
            }

            CurrentEnvironment.MoveUp(ev);
            CurrentEnvironment.Render(EVars);
            EVarsList.SelectedItem = EVars.First(e => e.Name == ev.Name);
        }
        // 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.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromDays(7);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

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

            // Use MS SQL in development
            // Allows use of VS SQL Server explorer
            if (CurrentEnvironment.IsDevelopment())
            {
                services.AddDbContext <WaitlistDataContext>(options =>
                                                            options.UseSqlServer(Configuration.GetConnectionString("MsSqlConnection")), ServiceLifetime.Scoped);
            }
            // Use MySQL on linux based testing & Production servers
            else
            {
                services.AddDbContext <WaitlistDataContext>(options =>
                                                            options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));
            }


            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath        = "/auth/gice";
                options.AccessDeniedPath = "/";
            });

            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, CorporationService>();
            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, AllianceService>();
            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, WaitlistService>();
            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, FleetService>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
Esempio n. 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var dataDatabaseConnection = Configuration.GetConnectionString("DataDatabaseConnection");
            var authDatabaseConnection = Configuration.GetConnectionString("AuthenticationDatabaseConnection");

            services.AddDbContext <CursedDataContext>(options => options.UseSqlServer(dataDatabaseConnection));
            services.AddDbContext <CursedAuthenticationContext>(options => options.UseSqlServer(authDatabaseConnection));

            services.AddControllersWithViews();
            services.AddHttpContextAccessor();
            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(15);
            });

            services.AddSingleton <ILicenseValidation, LicenseValidation>();
            services.AddSingleton <IErrorHandlerFactory, StatusMessageFactory>();
            services.AddSingleton <IGenPasswordHash, PasswordHash>();
            services.AddScoped <IOperationDataValidation, OperationDataValidation>();
            services.AddTransient <ILogProvider <CursedAuthenticationContext>, LogProvider>();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath        = new PathString("/login");
                options.AccessDeniedPath = new PathString("/access-denied");
                options.LogoutPath       = new PathString("/login");
                options.ExpireTimeSpan   = TimeSpan.FromDays(10);
            });

            services.AddAuthorization();

            // initialize databases if we're in development
            if (CurrentEnvironment.IsDevelopment())
            {
                string dbAuthDirectory = Path.Combine(Environment.CurrentDirectory, "Properties", "dbAuth");
                string dbDataDirectory = Path.Combine(Environment.CurrentDirectory, "Properties", "dbData");

                var localServerConnection = Configuration.GetConnectionString("LocalServerConnection");

                // initialize data database
                DatabaseInitializer.ExecuteScript(localServerConnection, Path.Combine(dbDataDirectory, "createDB.sql"));
                DatabaseInitializer.ExecuteScript(dataDatabaseConnection, Path.Combine(dbDataDirectory, "scheme.sql"));
                DatabaseInitializer.ExecuteScript(dataDatabaseConnection, Path.Combine(dbDataDirectory, "data.sql"));
                // initialize auth database
                DatabaseInitializer.ExecuteScript(localServerConnection, Path.Combine(dbAuthDirectory, "createDB.sql"));
                DatabaseInitializer.ExecuteScript(authDatabaseConnection, Path.Combine(dbAuthDirectory, "scheme.sql"));
                DatabaseInitializer.ExecuteScript(authDatabaseConnection, Path.Combine(dbAuthDirectory, "data.sql"));
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory logging)
        {
            ServiceProvider = app.ApplicationServices;

            if (CurrentEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionHandler(options =>
            {
                options.Run(async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "text/html";
                    var ex = context.Features.Get <IExceptionHandlerFeature>();
                    if (ex != null)
                    {
                        var logger = ServiceProvider.GetService <ILogger <Startup> >();
                        var err    = $"Error: {ex.Error.Message}{Environment.NewLine}{ex.Error.StackTrace }";
                        logger.LogError(err);
                        if (CurrentEnvironment.IsDevelopment())
                        {
                            await context.Response.WriteAsync(err).ConfigureAwait(false);
                        }
                    }
                });
            }
                                    );

            app.UseAuthentication();

            if (CurrentEnvironment.IsDevelopment())
            {
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(opts =>
                {
#pragma warning disable S1075 // URIs should not be hardcoded
                    opts.SwaggerEndpoint("/swagger/v1/swagger.json", "Buying Catalog API V1");
                    opts.SwaggerEndpoint("/swagger/porcelain/swagger.json", "Buying Catalog API V1 Porcelain");
#pragma warning restore S1075 // URIs should not be hardcoded

                    opts.DocExpansion(DocExpansion.None);
                });
            }

            app.UseStaticFiles();
            app.UseMvc();
        }
Esempio n. 29
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     if (CurrentEnvironment.IsEnvironment("Testing"))
     {
         services.AddDbContext <ApplicationDbContext>
             (options => options.UseInMemoryDatabase("TestingDB"));
     }
     else
     {
         services.AddDbContext <ApplicationDbContext>
             (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     }
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 }
Esempio n. 30
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app)
 {
     if (CurrentEnvironment.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseDefaultFiles();
     app.UseStaticFiles(new StaticFileOptions
     {
         ServeUnknownFileTypes = true
     });
     app.UseCors("AllowSpecificOrigin");
     app.UseMvc();
 }