示例#1
0
        public void ItSetsConfigDataAndUserPropertiesInServiceModel()
        {
            // Arrange
            DiagnosticsEventsApiModel target = new DiagnosticsEventsApiModel();

            target.SessionId = 123;

            ServicesConfig config = new ServicesConfig
            {
                DeploymentId   = "Id1",
                SolutionType   = "Sample",
                SolutionName   = "SampleSolution",
                IoTHubName     = "SampleHub",
                CloudType      = "Public",
                SubscriptionId = "12345"
            };

            // Act
            DiagnosticsEventsServiceModel model = target.ToServiceModel(config);

            // Assert
            Assert.Equal(config.DeploymentId, model.DeploymentId);
            Assert.Equal(config.SolutionType, model.SolutionType);
            Assert.Equal(target.SessionId, model.SessionId);
            Assert.Equal(config.SubscriptionId, model.UserProperties["SubscriptionId"]);
            Assert.Equal(config.SolutionName, model.UserProperties["SolutionName"]);
            Assert.Equal(config.CloudType, model.UserProperties["CloudType"]);
            Assert.Equal(config.IoTHubName, model.UserProperties["IoTHubName"]);
        }
示例#2
0
        public BaseService(HttpClient client, ServicesConfig configService)
        {
            this.client        = client;
            this.configService = configService;

            Configure();
        }
        public async Task GetActionsReturnsListOfActions()
        {
            // Arrange
            using (var mockContext = new MockHttpContext())
            {
                this.controller.ControllerContext.HttpContext = mockContext.Object;

                var config      = new ServicesConfig();
                var action      = new EmailActionSettings(this.mockResourceManagementClient.Object, config, this.mockLogger.Object);
                var actionsList = new List <IActionSettings>
                {
                    action
                };
                this.mockActions
                .Setup(x => x.GetListAsync())
                .ReturnsAsync(actionsList);

                // Act
                var result = await this.controller.GetActionsSettingsAsync();

                // Assert
                this.mockActions.Verify(x => x.GetListAsync(), Times.Once);

                Assert.NotEmpty(result.Items);
                Assert.Equal(actionsList.Count, result.Items.Count);
            }
        }
示例#4
0
        public void HttpConfiguration_ReplaceServices()
        {
            var configuration = new HttpConfiguration();

            ServicesConfig.Register(configuration);
            Assert.That(configuration.Services.GetExceptionLoggers(), Has.Some.TypeOf <ErrorsHandling.ExceptionLogger>());
            Assert.That(configuration.Services.GetExceptionHandler(), Is.TypeOf <ErrorsHandling.ExceptionHandler>());
        }
 public ServiceInvoker(IOptions <ServicesConfig> configOptions)
 {
     if (configOptions == null)
     {
         throw new ArgumentNullException(nameof(configOptions));
     }
     this._servicesConfig = configOptions.Value;
 }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SubscriptionBenefitService"/> class.
 /// </summary>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">The logger.</param>
 public SubscriptionBenefitService(
     IHttpClientFactory httpClientFactory,
     ServicesConfig servicesConfig,
     ILogger logger)
 {
     this.httpClientFactory = httpClientFactory;
     this.servicesConfig    = servicesConfig;
     this.logger            = logger;
 }
示例#7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServicesService"/> class.
 /// </summary>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">The logger.</param>
 public ServicesService(
     IHttpClientFactory httpClientFactory,
     ServicesConfig servicesConfig,
     ILogger logger)
 {
     this.httpClientFactory = httpClientFactory;
     this.servicesConfig    = servicesConfig;
     this.logger            = logger;
 }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string conn = Configuration.GetConnectionString("DefaultConnection");

            if (conn.Contains("%CONTENTROOTPATH%"))
            {
                conn = conn.Replace("%CONTENTROOTPATH%", _contentRootPath);
            }
            DbConfig.ConfigureDb(services, conn);
            RepositoriesConfig.ConfigureRepositories(services);
            ServicesConfig.ConfigureServices(services);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.Configure <AuthTokenOptions>(Configuration.GetSection("Authorization:Jwt"));
            var authTokenOptions = services.BuildServiceProvider().GetService <IOptions <AuthTokenOptions> >().Value;

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(10);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <SimContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = authTokenOptions.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = authTokenOptions.Audience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = authTokenOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero
                };
            });


            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });
        }
        public AlarmsTest()
        {
            var servicesConfig = new ServicesConfig
            {
                AlarmsConfig = new AlarmsConfig("database", "collection", 3)
            };

            this.storageClient = new Mock <IStorageClient>();
            this.logger        = new Mock <ILogger>();
            this.alarms        = new Alarms(servicesConfig, this.storageClient.Object, this.logger.Object);
        }
示例#10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LeadService"/> class.
 /// </summary>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="distributedCache">The distributed cache.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">The logger.</param>
 public LeadService(
     IHttpClientFactory httpClientFactory,
     IDistributedCache distributedCache,
     ServicesConfig servicesConfig,
     ILogger logger)
 {
     this.httpClientFactory = httpClientFactory;
     this.distributedCache  = distributedCache;
     this.servicesConfig    = servicesConfig;
     this.logger            = logger;
 }
 /// <summary>
 /// Initializes the insatnce of the class
 /// </summary>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">Represents the logger</param>
 /// <param name="authorizationConfig">The authorization configuration.</param>
 public UserIdExistsRequirementHandler(
     IHttpClientFactory httpClientFactory,
     ServicesConfig servicesConfig,
     ILogger <UserIdExistsRequirementHandler> logger,
     AuthorizationConfig authorizationConfig)
 {
     this.httpClientFactory   = httpClientFactory;
     this.servicesConfig      = servicesConfig;
     this.logger              = logger;
     this.authorizationConfig = authorizationConfig;
 }
示例#12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StoryService" /> class.
 /// </summary>
 /// <param name="usernameUpdateSender">The username update sender.</param>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">The logger.</param>
 public UserService(
     IUsernameUpdateSender usernameUpdateSender,
     IHttpClientFactory httpClientFactory,
     ServicesConfig servicesConfig,
     ILogger logger)
 {
     this.usernameUpdateSender = usernameUpdateSender;
     this.httpClientFactory    = httpClientFactory;
     this.servicesConfig       = servicesConfig;
     this.logger = logger;
 }
示例#13
0
    public void Invalid_Definitition_Throws_InvalidServiceDefinitionException(string definition)
    {
        // Arrange

        // Act
        var action = void() => ServicesConfig.SplitDefinition(definition);

        // Assert
        var ex = Assert.Throws <InvalidServiceDefinitionException>(action);

        Assert.Equal(string.Format(InvalidServiceDefinitionException.Format, definition), ex.Message);
    }
示例#14
0
        private static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ServicesConfig.Initialize(); // create instance

            IArithmeticOperationsRepo operationsRepo = ServicesConfig.OperationsRepo;

            //inject dependency
            Application.Run(new Calculator(operationsRepo));
        }
示例#15
0
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ServicesConfig.Initialize();
            IUserRepository userRepo = ServicesConfig.userRepository;
            IAuthRepository authRepo = ServicesConfig.authRepository;


            Application.Run(new Address(userRepo, authRepo));
        }
示例#16
0
        public MessagesTest()
        {
            var servicesConfig = new ServicesConfig()
            {
                MessagesConfig = new StorageConfig("database", "collection"),
                StorageType    = "tsi"
            };

            this.storageClient    = new Mock <IStorageClient>();
            this.timeSeriesClient = new Mock <ITimeSeriesClient>();
            this.logger           = new Mock <ILogger>();
            this.messages         = new Messages(servicesConfig, this.storageClient.Object, this.timeSeriesClient.Object, this.logger.Object);
        }
示例#17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <SurveyContext>(opt =>
                                                  opt.UseSqlServer(Configuration.GetConnectionString("SurveyContext"), ssopt => ssopt.CommandTimeout(300))
                                                  //opt.UseInMemoryDatabase("StudentSurveySystemDb")
                                                  );
            services.AddControllers().AddControllersAsServices().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling  = DateTimeZoneHandling.Utc;
            });
            //Cross origin...
            services.AddCors(options =>
            {
                //may need to switch on prod to defined cors
                options.AddDefaultPolicy(builder =>
                                         builder.AllowAnyOrigin()
                                         .AllowAnyHeader()
                                         .AllowAnyMethod());
            });

            var key = Encoding.ASCII.GetBytes(Configuration["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
                };
            });


            //swagger config
            SwaggerConfig.Setup(services);

            // configure DI for application services
            ServicesConfig.Setup(services);

            services.AddSwaggerGenNewtonsoftSupport();
        }
        public ActionManagerTest()
        {
            Mock <ILogger> loggerMock = new Mock <ILogger>();

            this.httpClientMock = new Mock <IHttpClient>();
            IServicesConfig servicesConfig = new ServicesConfig
            {
                LogicAppEndpointUrl = "https://azure.com",
                SolutionUrl         = "test",
                TemplateFolder      = ".\\data\\"
            };

            this.actionManager = new ActionManager(loggerMock.Object, servicesConfig, this.httpClientMock.Object);
        }
示例#19
0
    public void Service_Does_Not_Exist_Returns_Default_Instance()
    {
        // Arrange
        var config        = new ServicesConfig();
        var name          = Rnd.Str;
        var defaultConfig = new ConsoleConfig();

        // Act
        var result = config.GetServiceConfig(x => x.Console, name);

        // Assert
        Assert.Equal(defaultConfig.AddPrefix, result.AddPrefix);
        Assert.Equal(defaultConfig.Template, result.Template);
    }
示例#20
0
    public void Splits_Definition_Unknown_Service_Type_Throws_UnsupportedServiceException()
    {
        // Arrange
        var config = new ServicesConfig();
        var type   = Rnd.Str;

        // Act
        var action = void() => config.GetServiceConfig($"{type}.{Rnd.Str}");

        // Assert
        var ex = Assert.Throws <UnsupportedServiceException>(action);

        Assert.Equal(string.Format(UnsupportedServiceException.Format, type), ex.Message);
    }
示例#21
0
        public void Container_ReturnsTheSameInstanceOfTypeRegisteredAsSingletonOnEachCall()
        {
            var configuration = new HttpConfiguration();

            ServicesConfig.Register(configuration);

            IUnityContainer container = configuration.DependencyResolver.GetService <IUnityContainer>();

            container.RegisterType <IFoo, Foo>(new ContainerControlledLifetimeManager());

            var a = configuration.DependencyResolver.GetService <IFoo>();
            var b = configuration.DependencyResolver.GetService <IFoo>();

            Assert.AreSame(a, b);
        }
示例#22
0
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="conversationState">The managed conversation state.</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> that is hooked to the Azure App Service provider.</param>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
        public ProxiCallBot(BotServices services, StateAccessors accessors, IOptions <ServicesConfig> options, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
        {
            _accessors       = accessors ?? throw new System.ArgumentNullException(nameof(accessors));
            _serviceProvider = serviceProvider;
            _loggerFactory   = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            _services        = services ?? throw new ArgumentNullException(nameof(services));

            _servicesConfig = options.Value;

            _accountService = (AccountService)_serviceProvider.GetService(typeof(AccountService));

            Dialogs = new DialogSet(_accessors.DialogStateAccessor);
            Dialogs.Add(ActivatorUtilities.CreateInstance <SearchLeadDataDialog>(_serviceProvider));
            Dialogs.Add(ActivatorUtilities.CreateInstance <SearchCompanyDataDialog>(_serviceProvider));
            Dialogs.Add(ActivatorUtilities.CreateInstance <CreateOpportunityDialog>(_serviceProvider));
        }
示例#23
0
    public void Invalid_Config_Throws_InvalidServiceConfigurationException()
    {
        // Arrange
        var config = new ServicesConfig();
        var name   = Rnd.Str;

        config.Seq.Add(name, new SeqConfig());

        // Act
        var action = void() => config.GetServiceConfig(x => x.Seq, name);

        // Assert
        var ex = Assert.Throws <InvalidServiceConfigurationException>(action);

        Assert.Equal(string.Format(InvalidServiceConfigurationException.Format, name, typeof(SeqConfig)), ex.Message);
    }
        public ActionManagerTest()
        {
            Mock <ILogger> loggerMock = new Mock <ILogger>();

            this.httpClientMock = new Mock <IHttpClient>();

            char            pathSeparator  = Path.DirectorySeparatorChar;
            IServicesConfig servicesConfig = new ServicesConfig
            {
                LogicAppEndpointUrl = "https://azure.com",
                SolutionUrl         = "test",
                TemplateFolder      = $".{pathSeparator}data{pathSeparator}"
            };

            this.actionManager = new ActionManager(loggerMock.Object, servicesConfig, this.httpClientMock.Object);
        }
示例#25
0
        public ConnectionStringsTest()
        {
            this.config = new ServicesConfig();
            this.connectionStringValidation = new Mock <IConnectionStringValidation>();
            this.mockLogger            = new Mock <ILogger>();
            this.mockDiagnosticsLogger = new Mock <IDiagnosticsLogger>();
            this.mainStorage           = new Mock <IEngine>();
            this.enginesFactory        = new Mock <IEngines>();
            this.enginesFactory.Setup(x => x.Build(It.IsAny <Config>())).Returns(this.mainStorage.Object);

            this.target = new ConnectionStrings(
                this.config,
                this.connectionStringValidation.Object,
                this.enginesFactory.Object,
                this.mockDiagnosticsLogger.Object,
                this.mockLogger.Object);
        }
示例#26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            _services = services;
            RepositoryConfig.Configure(_services, Configuration);
            ServicesConfig.Configure(_services);
        }
示例#27
0
    public void Returns_Split_Definition()
    {
        // Arrange
        var type = Rnd.Str;
        var name = Rnd.Str;
        var d0   = $"{type}.{name}";
        var d1   = $"{type}";

        // Act
        var(t0, n0) = ServicesConfig.SplitDefinition(d0);
        var(t1, n1) = ServicesConfig.SplitDefinition(d1);

        // Assert
        Assert.Equal(type, t0);
        Assert.Equal(name, n0);
        Assert.Equal(type, t1);
        Assert.Equal(string.Empty, n1);
    }
示例#28
0
    public void Splits_Definition_And_Returns_ServiceConfig()
    {
        // Arrange
        var config  = new ServicesConfig();
        var name    = Rnd.Str;
        var service = new SeqConfig
        {
            Server = "https://www.contoso.com",
            ApiKey = Rnd.Str
        };

        config.Seq.Add(name, service);

        // Act
        var result = config.GetServiceConfig($"seq.{name}");

        // Assert
        Assert.Equal(service, result);
    }
示例#29
0
    public void Returns_ServiceConfig()
    {
        // Arrange
        var config  = new ServicesConfig();
        var name    = Rnd.Str;
        var service = new SeqConfig
        {
            Server = "https://www.contoso.com",
            ApiKey = Rnd.Str
        };

        config.Seq.Add(name, service);

        // Act
        var result = config.GetServiceConfig(x => x.Seq, name);

        // Assert
        Assert.Equal(service, result);
    }
示例#30
0
        public void ItSetsConfigDataInServiceModel()
        {
            // Arrange
            DiagnosticsEventsApiModel target = new DiagnosticsEventsApiModel();
            ServicesConfig            config = new ServicesConfig
            {
                DeploymentId = "Id1",
                SolutionType = "Sample"
            };

            // Act
            DiagnosticsEventsServiceModel model = target.ToServiceModel(config);

            // Assert
            Assert.Equal(config.DeploymentId, model.DeploymentId);
            Assert.Equal(config.SolutionType, model.SolutionType);

            Assert.Null(model.SessionId);
        }