Exemple #1
0
        public MessagesHub(IUserIdProvider userIdProvider, IWebConfiguration injected)
        {
            this.userIdProvider = userIdProvider ?? throw new ArgumentNullException(nameof(userIdProvider));
            this.injectedConfig = injected ?? throw new ArgumentNullException(nameof(injected));

            System.Diagnostics.Debug.WriteLine("MessagesHub created.");
        }
        public void ConfigureServices(IServiceCollection services)
        {
            Configuration = ConfigurationService.GetConfig(_config["EnvironmentName"], _config["ConfigurationStorageConnectionString"], Version, ServiceName).Result;
            services.AddMvc()
            .AddControllersAsServices()
            .AddSessionStateTempDataProvider()
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddSingleton <Microsoft.AspNetCore.Mvc.ViewFeatures.IHtmlGenerator, CacheOverrideHtmlGenerator>();

            services.AddAntiforgery(options => options.Cookie = new CookieBuilder()
            {
                Name = ".QnA.Config.Preview.AntiForgery", HttpOnly = true
            });


            services.AddSession(opt =>
            {
                opt.IdleTimeout = TimeSpan.FromHours(1);
                opt.Cookie      = new CookieBuilder()
                {
                    Name     = ".QnA.Config.Preview.Session",
                    HttpOnly = true
                };
            });

            services.AddHealthChecks();
            ConfigureIoc(services);
        }
Exemple #3
0
 public RegisterRepository(IWebConfiguration configuration, ILogger <RegisterRepository> logger)
 {
     _configuration = configuration;
     _logger        = logger;
     SqlMapper.AddTypeHandler(typeof(Api.Types.Models.AO.OrganisationData), new OrganisationDataHandler());
     SqlMapper.AddTypeHandler(typeof(OrganisationStandardData), new OrganisationStandardDataHandler());
 }
Exemple #4
0
 public UserManagmentFacade(IUserProxyServer userProxyServer, IWebConfiguration webConfiguration, IFavoritesStorage <Trigger> triggerFavoritesStorage, IFavoritesStorage <Graph> graphFavoritesStorage)
 {
     _userProxyServer         = userProxyServer;
     _webConfiguration        = webConfiguration;
     _triggerFavoritesStorage = triggerFavoritesStorage;
     _graphFavoritesStorage   = graphFavoritesStorage;
 }
        /// <summary>Looks up <paramref name="connectionStringAppSettingName"/> in <see cref="IWebConfiguration.AppSettings"/> and then uses that value to get the connection-string from <see cref="IWebConfiguration.ConnectionStrings"/>.</summary>
        /// <exception cref="ArgumentNullException">When <paramref name="webConfiguration"/> is null or when <paramref name="connectionStringAppSettingName"/> is null, empty or whitespace.</exception>
        /// <exception cref="InvalidOperationException">When <paramref name="connectionStringAppSettingName"/> cannot be found, or when the connection-string it refers to does not exist or is empty.</exception>
        public static String RequireIndirectConnectionString(this IWebConfiguration webConfiguration, String connectionStringAppSettingName)
        {
            if (webConfiguration == null)
            {
                throw new ArgumentNullException(nameof(webConfiguration));
            }
            if (String.IsNullOrWhiteSpace(connectionStringAppSettingName))
            {
                throw new ArgumentNullException(paramName: nameof(connectionStringAppSettingName));
            }

            //

            if (webConfiguration.AppSettings.TryGetValue(connectionStringAppSettingName, out String connectionStringName))
            {
                if (String.IsNullOrWhiteSpace(connectionStringName))
                {
                    throw new InvalidOperationException("The <appSettings> entry \"" + connectionStringAppSettingName + "\" is empty.");
                }
                else
                {
                    return(RequireConnectionString(webConfiguration, connectionStringAppSettingName));
                }
            }
            else
            {
                throw new InvalidOperationException("The <appSettings> entry \"" + connectionStringAppSettingName + "\" does not exist.");
            }
        }
        /// <summary>Looks up <paramref name="connectionStringName"/> in <see cref="IWebConfiguration.ConnectionStrings"/> and returns the <see cref="ConnectionStringSettings"/>'s <see cref="ConnectionStringSettings.ConnectionString"/> string value. Otherwise throws an exception.</summary>
        /// <exception cref="ArgumentNullException">When <paramref name="webConfiguration"/> is null or when <paramref name="connectionStringName"/> is null, empty or whitespace.</exception>
        /// <exception cref="InvalidOperationException">When <paramref name="connectionStringName"/> cannot be found or is empty.</exception>
        public static String RequireConnectionString(this IWebConfiguration webConfiguration, String connectionStringName)
        {
            if (webConfiguration == null)
            {
                throw new ArgumentNullException(nameof(webConfiguration));
            }
            if (String.IsNullOrWhiteSpace(connectionStringName))
            {
                throw new ArgumentNullException(paramName: nameof(connectionStringName));
            }

            //

            if (webConfiguration.ConnectionStrings.TryGetValue(connectionStringName, out ConnectionStringSettings cs))
            {
                if (cs == null || String.IsNullOrWhiteSpace(cs.ConnectionString))
                {
                    throw new InvalidOperationException("The <connectionStrings> entry \"" + connectionStringName + "\" is empty.");
                }
                else
                {
                    return(cs.ConnectionString);
                }
            }
            else
            {
                throw new InvalidOperationException("The <connectionStrings> entry \"" + connectionStringName + "\" is undefined.");
            }
        }
Exemple #7
0
 public MongoHelper(MongoClient client, CloudStorageAccount storage, IWebConfiguration config)
 {
     this.blobName     = config.BlobName;
     this.databaseName = config.MongoDatabaseName;
     this.client       = client;
     this.storage      = storage;
 }
        /// <summary>Looks up <paramref name="appSettingName"/> in <see cref="IWebConfiguration.AppSettings"/> and throws <see cref="InvalidOperationException"/> if the specified <paramref name="appSettingName"/> does not exist or has an empty value, otherwise it returns it.</summary>
        /// <exception cref="ArgumentNullException">When <paramref name="webConfiguration"/> is null or when <paramref name="appSettingName"/> is null, empty or whitespace.</exception>
        /// <exception cref="InvalidOperationException">When <paramref name="appSettingName"/> cannot be found or is empty.</exception>
        public static String RequireAppSetting(this IWebConfiguration webConfiguration, String appSettingName)
        {
            if (webConfiguration == null)
            {
                throw new ArgumentNullException(nameof(webConfiguration));
            }
            if (String.IsNullOrWhiteSpace(appSettingName))
            {
                throw new ArgumentNullException(paramName: nameof(appSettingName));
            }

            //

            if (webConfiguration.AppSettings.TryGetValue(appSettingName, out String value))
            {
                if (String.IsNullOrWhiteSpace(value))
                {
                    throw new InvalidOperationException("The <appSettings> entry \"" + appSettingName + "\" is empty.");
                }
                else
                {
                    return(value);
                }
            }
            else
            {
                throw new InvalidOperationException("The <appSettings> entry \"" + appSettingName + "\" is undefined.");
            }
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IWebConfiguration webConfig = IocContainer.Instance.Resolve <IWebConfiguration>();
            var response = filterContext.HttpContext.Response;

            response.Cookies.Remove(webConfig.AuthenticationCookieName);
        }
Exemple #10
0
        public static IWebConfiguration GetConfiguration()
        {
            lock (_lock)
            {
                if (_webConfiguration == null)
                {
                    var serviceName = "SFA.DAS.AssessorService";
                    var version     = "1.0";

                    var connection = CloudStorageAccount.Parse(
                        CloudConfigurationManager.GetSetting("ConfigurationStorageConnectionString"));
                    var tableClient = connection.CreateCloudTableClient();
                    var table       = tableClient.GetTableReference("Configuration");

                    var operation = TableOperation.Retrieve(
                        CloudConfigurationManager.GetSetting("EnvironmentName"),
                        $"{serviceName}_{version}");
                    var result = table.ExecuteAsync(operation).Result;
                    if (result.Result is DynamicTableEntity dynResult)
                    {
                        var data = dynResult.Properties["Data"].StringValue;
                        _webConfiguration = JsonConvert.DeserializeObject <WebConfiguration>(data);
                    }
                    else
                    {
                        throw new ApplicationException("Cannot Deserialise Configuration Entry");
                    }
                }
            }

            return(_webConfiguration);
        }
        private static void BuildConfiguration()
        {
            try
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json");

                var localConfiguration = builder.Build();

                //IWebConfiguration Configuration { get; }
                Configuration = ConfigurationService.GetConfig(
                    localConfiguration["EnvironmentName"],
                    localConfiguration["ConfigurationStorageConnectionString"],
                    localConfiguration["Version"],
                    localConfiguration["ServiceName"])
                                .Result;

                Console.WriteLine($"Retrieved configuration . NServiceBus endpoint is {Configuration.NServiceBus.Endpoint}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemple #12
0
 public SandboxDbRepository(IWebConfiguration config, ILogger <SandboxDbRepository> logger)
 {
     _config          = config;
     _logger          = logger;
     _bulkCopyOptions = SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls |
                        SqlBulkCopyOptions.TableLock;
 }
 public ProvideFeedbackService(IWebConfiguration configuration, HttpClient client, IAzureClientCredentialHelper azureClientCredentialHelper)
 {
     _configuration               = configuration;
     _client                      = client;
     _client.BaseAddress          = new Uri(_configuration.ProvideFeedbackApiConfiguration.Url);
     _azureClientCredentialHelper = azureClientCredentialHelper;
 }
        // ReSharper disable UseObjectOrCollectionInitializer
        // ReSharper disable FunctionNeverReturns
        protected static void InitializeSweeper()
        {
            IWebConfiguration webConfig = IocContainer.Instance.Resolve <IWebConfiguration>();

            if (!webConfig.RunSweeper)
            {
                return;
            }

            ILog sweeperLogger = LogManager.GetLogger(typeof(ISweeper));

            ISweeper sweeper       = IocContainer.Instance.Resolve <ISweeper>();
            TimeSpan timeout       = webConfig.SweeperTimeout;
            Thread   sweeperThread = new Thread(() =>
            {
                while (true)
                {
                    Thread.Sleep(timeout);
                    try
                    {
                        sweeper.CleanUp();
                    }
                    catch (Exception ex)
                    {
                        sweeperLogger.Error(ex);
                    }
                }
            });


            sweeperThread.IsBackground = true;
            sweeperThread.Start();
        }
Exemple #15
0
 public UkrlpApiClient(ILogger <UkrlpApiClient> logger, IWebConfiguration config, HttpClient httpClient, IUkrlpSoapSerializer serializer)
 {
     _logger     = logger;
     _config     = config;
     _httpClient = httpClient;
     _serializer = serializer;
 }
Exemple #16
0
        void application_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            //updating locale cookies
            IWebConfiguration webConfiguration = IocContainer.Instance.Resolve <IWebConfiguration>();
            var trackingService = IocContainer.Instance.Resolve <ITrackingService>();

            trackingService.SetLocaleTracking(application.Context);

            HttpStatusCode code = (HttpStatusCode)application.Response.StatusCode;

            if (code == HttpStatusCode.Unauthorized)
            {
                if (!application.Context.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
                {
                    application.Response.Redirect("~/account/logon");
                    return;
                }
                string returnUrl = Uri.EscapeUriString(application.Context.Request.Url.PathAndQuery);
                if (returnUrl.Equals("/", StringComparison.OrdinalIgnoreCase))
                {
                    application.Response.Redirect("~/account/logon");
                }
                else
                {
                    application.Response.Redirect("~/account/logon?returnUrl=" + returnUrl);
                }
            }
        }
 public Startup(IConfiguration config)
 {
     Configuration = ConfigurationService.GetConfig(config["EnvironmentName"],
                                                    config["ConfigurationStorageConnectionString"],
                                                    config["Version"],
                                                    config["ServiceName"]).Result;
 }
 public ApiValidationService(IWebConfiguration config, ITokenService tokenService, ILogger <ApiValidationService> logger)
 {
     _config       = config;
     _tokenService = tokenService;
     _logger       = logger;
     _clientApiCallValidationName = "ClientApiCall";
 }
Exemple #19
0
 public FileTransferClient(
     IAggregateLogger aggregateLogger,
     IWebConfiguration webConfiguration)
 {
     _aggregateLogger  = aggregateLogger;
     _webConfiguration = webConfiguration;
 }
 public CompaniesHouseApiClient(HttpClient client, ILogger <CompaniesHouseApiClient> logger,
                                IWebConfiguration configurationService)
 {
     _client = client;
     _logger = logger;
     _config = configurationService;
 }
        public static IServiceCollection AddDasHealthChecks(this IServiceCollection services,
                                                            IWebConfiguration config, bool isDevelopment)
        {
            services.AddHealthChecks()
            .AddCheck <ApplyApiHealthCheck>("Apply API Health Check");

            return(services);
        }
        public OrganisationService(IHttpClient httpClient, IWebConfiguration config)
        {
            _httpClient = httpClient;
            _config     = config;
            var apiServiceHost = _config.Api.ApiBaseAddress;

            _remoteServiceBaseUrl = $"{apiServiceHost}/api/v1/assessment-providers";
        }
 public ReturnApplicationSequenceHandler(IApplyRepository applyRepository, IEMailTemplateQueryRepository eMailTemplateQueryRepository, IContactQueryRepository contactQueryRepository, IWebConfiguration config, IMediator mediator)
 {
     _applyRepository = applyRepository;
     _mediator        = mediator;
     _eMailTemplateQueryRepository = eMailTemplateQueryRepository;
     _contactQueryRepository       = contactQueryRepository;
     _config = config;
 }
Exemple #24
0
 public LibroLibWebClient(
     IWebClientFactory webClientFactory,
     IWebConfiguration configuration,
     IFileSystem fileSystem)
 {
     this.webClientFactory = webClientFactory;
     this.configuration    = configuration;
     this.fileSystem       = fileSystem;
 }
 public PrintingJsonCreator(
     IAggregateLogger aggregateLogger,
     IFileTransferClient fileTransferClient,
     IWebConfiguration webConfiguration)
 {
     _aggregateLogger    = aggregateLogger;
     _fileTransferClient = fileTransferClient;
     _webConfiguration   = webConfiguration;
 }
        public ExternalApiDataSyncCommand(IWebConfiguration config, IAggregateLogger aggregateLogger)
        {
            _aggregateLogger = aggregateLogger;

            _allowDataSync               = config.ExternalApiDataSync.IsEnabled;
            _sourceConnectionString      = config.SqlConnectionString;
            _destinationConnectionString = config.SandboxSqlConnectionString;
            _bulkCopyOptions             = SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.TableLock;
        }
        public ApplyRepository(IWebConfiguration configuration, ILogger <ApplyRepository> logger)
        {
            _configuration = configuration;
            _logger        = logger;

            SqlMapper.AddTypeHandler(typeof(ApplyData), new ApplyDataHandler());
            SqlMapper.AddTypeHandler(typeof(FinancialGrade), new FinancialGradeHandler());
            SqlMapper.AddTypeHandler(typeof(FinancialEvidence), new FinancialEvidenceHandler());
        }
        public static void AddAndConfigureAuthentication(this IServiceCollection services, IWebConfiguration configuration, IEmployerAccountService accountsSvc)
        {
            _configuration = configuration;

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultSignInScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                sharedOptions.DefaultSignOutScheme   = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddOpenIdConnect(options =>
            {
                options.ClientId     = _configuration.Identity.ClientId;
                options.ClientSecret = _configuration.Identity.ClientSecret;
                options.Authority    = _configuration.Identity.Authority;
                options.ResponseType = "code";
                options.UsePkce      = false;

                var scopes = GetScopes();
                foreach (var scope in scopes)
                {
                    options.Scope.Add(scope);
                }

                var mapUniqueJsonKeys = GetMapUniqueJsonKey();
                options.ClaimActions.MapUniqueJsonKey(mapUniqueJsonKeys[0], mapUniqueJsonKeys[1]);
                options.Events.OnTokenValidated = async(ctx) => await PopulateAccountsClaim(ctx, accountsSvc);

                options.Events.OnRemoteFailure = c =>
                {
                    if (c.Failure.Message.Contains("Correlation failed"))
                    {
                        c.Response.Redirect("/");
                        c.HandleResponse();
                    }

                    return(Task.CompletedTask);
                };
            })
            .AddCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Service/AccessDenied");
                options.ExpireTimeSpan   = TimeSpan.FromHours(1);
                switch (configuration.SessionStore.Type)
                {
                case "Redis":
                    options.SessionStore = new RedisCacheTicketStore(configuration.SessionStore.Connectionstring);
                    break;

                case "Default":
                    break;
                }

                options.Events.OnRedirectToAccessDenied = RedirectToAccessDenied;
            });
        }
 public ManageUsersController(IWebConfiguration config, IContactsApiClient contactsApiClient,
                              IHttpContextAccessor contextAccessor, IOrganisationsApiClient organisationsApiClient, IEmailApiClient emailApiClient)
 {
     _contactsApiClient      = contactsApiClient;
     _contextAccessor        = contextAccessor;
     _organisationsApiClient = organisationsApiClient;
     _emailApiClient         = emailApiClient;
     _config = config;
 }
Exemple #30
0
 public RequestForPrivilegeHandler(IMediator mediator, IContactQueryRepository contactQueryRepository,
                                   IOrganisationQueryRepository organisationQueryRepository, IWebConfiguration config, IContactRepository contactRepository)
 {
     _mediator = mediator;
     _contactQueryRepository      = contactQueryRepository;
     _organisationQueryRepository = organisationQueryRepository;
     _config            = config;
     _contactRepository = contactRepository;
 }
 public MembershipService(IUserService userService, 
     ITemplateEngine templateEngine,
     IMessageDeliveryService mailService,
     IWebConfiguration webConfiguration,
     IPasswordHasher passwordHasher,
     ILocaleProvider localeProvider,
     ITimeZonesProvider timeZonesProvider,
     IConnectionProvider connectionProvider)
 {
     _userService = userService;
     _templateEngine = templateEngine;
     _mailService = mailService;
     _webConfiguration = webConfiguration;
     _passwordHasher = passwordHasher;
     _localeProvider = localeProvider;
     _timeZonesProvider = timeZonesProvider;
     _connectionProvider = connectionProvider;
 }
        /// <summary>
        /// Creates the configured web application dependencies container.
        /// </summary>
        /// <returns>The container builder.</returns>
        public static ContainerBuilder InitializeContainer(ContainerBuilder builder = null, IWebConfiguration configuration = null)
        {
            if (builder == null)
            {
                builder = new ContainerBuilder();
            }

            if (configuration != null)
            {
                Config = configuration;
            }

            builder = ApplicationContext.InitializeContainer(builder, Config);

            builder.RegisterType<DefaultWebModulesRegistration>()
                .As<IModulesRegistration>()
                .As<IWebModulesRegistration>()
                .SingleInstance();

            builder.RegisterType<DefaultWebControllerFactory>().SingleInstance();
            builder.RegisterType<DefaultEmbeddedResourcesProvider>().As<IEmbeddedResourcesProvider>().SingleInstance();
            builder.RegisterType<DefaultHttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
            builder.RegisterType<DefaultControllerExtensions>().As<IControllerExtensions>().SingleInstance();
            builder.RegisterType<DefaultCommandResolver>().As<ICommandResolver>().InstancePerLifetimeScope();
            builder.RegisterInstance(new DefaultRouteTable(RouteTable.Routes)).As<IRouteTable>().SingleInstance();
            builder.RegisterType<PerWebRequestContainerProvider>().InstancePerLifetimeScope();
            builder.RegisterType<DefaultWebPrincipalProvider>().As<IPrincipalProvider>().SingleInstance();
            builder.RegisterType<DefaultWebAssemblyManager>().As<IAssemblyManager>().SingleInstance();
            builder.RegisterType<HttpRuntimeCacheService>().As<ICacheService>().SingleInstance();
            builder.RegisterType<DefaultWebApplicationHost>().As<IWebApplicationHost>().SingleInstance();

            if (Config != null)
            {
                builder.RegisterInstance(Config)
                    .As<IConfiguration>()
                    .As<IWebConfiguration>()
                    .SingleInstance();
            }

            return builder;
        }
		///	<summary> This method copy's each database field into the <paramref name="target"/> interface. </summary>
		public void Copy_To(IWebConfiguration target, bool includePrimaryKey = false)
		{
			if (includePrimaryKey) target.Name = this.Name;
			target.Value = this.Value;
			target.ChangedTime = this.ChangedTime;
			target.CreationTime = this.CreationTime;
		}
		///	<summary> This method copy's each database field from the <paramref name="source"/> interface to this data row.</summary>
		public void Copy_From(IWebConfiguration source, bool includePrimaryKey = false)
		{
			if (includePrimaryKey) this.Name = source.Name;
			this.Value = source.Value;
			this.ChangedTime = source.ChangedTime;
			this.CreationTime = source.CreationTime;
		}
		///	<summary> 
		///		This method copy's each database field which is in the <paramref name="includedColumns"/> 
		///		from the <paramref name="source"/> interface to this data row.
		/// </summary>
		public void Copy_From_But_TakeOnly(IWebConfiguration source, params string[] includedColumns)
		{
			if (includedColumns.Contains(WebConfigurationsTable.NameCol)) this.Name = source.Name;
			if (includedColumns.Contains(WebConfigurationsTable.ValueCol)) this.Value = source.Value;
			if (includedColumns.Contains(WebConfigurationsTable.ChangedTimeCol)) this.ChangedTime = source.ChangedTime;
			if (includedColumns.Contains(WebConfigurationsTable.CreationTimeCol)) this.CreationTime = source.CreationTime;
		}
 public CookieTrackingService(ILocaleProvider localeProvider, IWebConfiguration webConfiguration)
 {
     _localeProvider = localeProvider;
     _webConfiguration = webConfiguration;
 }
 public FormsAuthenticationService(IUserService userService, ISessionService sessionService, IWebConfiguration webConfiguration)
 {
     _userService = userService;
     _sessionService = sessionService;
     _webConfiguration = webConfiguration;
 }