public ErrorController(ILogger <ErrorController> logger, IOptions <CompositeSettings> compositeSettings,
                        IDssReader _dssReader, ICosmosService cosmosServiceService, IOptions <CompositeSettings> configuration,
                        IDocumentService <CmsApiSharedContentModel> documentService, IConfiguration config)
     : base(compositeSettings, _dssReader, cosmosServiceService, documentService, config)
 {
     _configuration = configuration.Value;
 }
Beispiel #2
0
            public void Init()
            {
                _settings = Options.Create(new LmiSettings()
                {
                    ApiUrl = "http://thisisarealuri.com"
                });
                var cachedLmiDataModel = new CachedLmiData
                {
                    SocCode     = 2815.ToString(),
                    JobGrowth   = JobGrowth.Increasing,
                    DateWritten = DateTimeOffset.Now
                };
                var cachedLmiData = new StringContent(JsonConvert.SerializeObject(cachedLmiDataModel));
                var mockHandler   = LmiHelpers.GetMockMessageHandler(LmiHelpers.SuccessfulLmiCall());

                _restClient    = new RestClient(mockHandler.Object);
                _cosmosService = Substitute.For <ICosmosService>();
                _cosmosService.ReadItemAsync(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content    = cachedLmiData
                });
                _cosmosService.CreateItemAsync(Arg.Any <object>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage(HttpStatusCode.OK));
                _cosmosService.UpsertItemAsync(Arg.Any <object>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage(HttpStatusCode.OK));
            }
Beispiel #3
0
            public void Init()
            {
                _cosmosSettings = Options.Create(new CosmosSettings()
                {
                    ApiUrl                 = "https://test-account-not-real.documents.azure.com:443/",
                    ApiKey                 = "VGhpcyBpcyBteSB0ZXN0",
                    DatabaseName           = "DatabaseName",
                    UserSessionsCollection = "UserSessions",
                    LmiDataCollection      = "LmiData"
                });
                var cachedLmiDataModel = new CachedLmiData
                {
                    SocCode     = 2815.ToString(),
                    JobGrowth   = JobGrowth.Increasing,
                    DateWritten = DateTimeOffset.Now
                };
                var cachedLmiData = new StringContent(JsonConvert.SerializeObject(cachedLmiDataModel));

                _service = Substitute.For <ICosmosService>();
                _service.ReadItemAsync(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content    = cachedLmiData
                });
                _service.CreateItemAsync(Arg.Any <object>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage(HttpStatusCode.OK));
                _service.UpsertItemAsync(Arg.Any <object>(), Arg.Any <CosmosCollection>())
                .Returns(new HttpResponseMessage(HttpStatusCode.OK));
            }
Beispiel #4
0
            public void WhenItemIsNull_ThrowException()
            {
                var client = Substitute.For <CosmosClient>();

                _service = new CosmosService(_cosmosSettings, client, _logger);
                _service.Invoking(x => x.CreateItemAsync(null, CosmosCollection.Session)).Should().Throw <ArgumentException>();
            }
Beispiel #5
0
            public void Init()
            {
                _cosmosSettings = Options.Create(new CosmosSettings()
                {
                    ApiUrl                 = "https://test-account-not-real.documents.azure.com:443/",
                    ApiKey                 = "VGhpcyBpcyBteSB0ZXN0",
                    DatabaseName           = "DatabaseName",
                    UserSessionsCollection = "UserSessions"
                });
                var dummySession = new DfcUserSession()
                {
                    SessionId = "partitionkey-sessionid"
                };

                _client        = Substitute.For <CosmosClient>();
                _cosmosService = Substitute.For <ICosmosService>();
                _sessionClient = Substitute.For <ISessionClient>();
                _sessionConfig = Options.Create(new SessionConfig()
                {
                    Salt            = "ThisIsASalt",
                    ApplicationName = "matchskills"
                });

                _sessionClient.NewSession().Returns(dummySession);
            }
        public CosmosContainer Convert(CosmosAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            ICosmosService service = configProvider.GetService(
                configProvider.ResolveConnectionString(attribute.ConnectionStringSetting),
                attribute.ApplicationName,
                attribute.ApplicationRegion);

            if (attribute.CreateIfNotExists)
            {
                var context = new CosmosContext
                {
                    ResolvedAttribute = attribute,
                    Service           = service
                };

                CosmosUtility.CreateDatabaseAndContainerNameIfNotExistAsync(context).Wait();
            }

            return(service.GetContainer(attribute.DatabaseName, attribute.ContainerName));
        }
Beispiel #7
0
        internal CosmosClient BindForClient(CosmosAttribute attribute)
        {
            string         resolvedConnectionString = ResolveConnectionString(attribute.ConnectionStringSetting);
            ICosmosService service = GetService(resolvedConnectionString, attribute.ApplicationName, attribute.ApplicationRegion);

            return(service.GetClient());
        }
        private static async Task <CosmosContainer> CreateContainerIfNotExistsAsync(
            ICosmosService service,
            CosmosDatabase database,
            string containerName,
            string partitionKey,
            int?throughput)
        {
            string partitionKeyPath = null;

            if (!string.IsNullOrEmpty(partitionKey))
            {
                if (!partitionKey.StartsWith("/"))
                {
                    partitionKeyPath = $"/{partitionKey}";
                }
            }

            if (throughput == 0)
            {
                throughput = null;
            }

            return(await service.CreateContainerIfNotExistsAsync(
                       database,
                       new ContainerProperties { Id = containerName, PartitionKeyPath = partitionKeyPath },
                       throughput));
        }
        public void Init()
        {
            _settings               = Options.Create(new ServiceTaxonomySettings());
            _compositeSettings      = Options.Create(new CompositeSettings());
            _settings.Value.ApiUrl  = "https://dev.api.nationalcareersservice.org.uk/servicetaxonomy";
            _settings.Value.ApiKey  = "mykeydoesnotmatterasitwillbemocked";
            _settings.Value.EscoUrl = "http://data.europa.eu/esco";
            _settings.Value.SearchOccupationInAltLabels = "true";
            const string skillsJson  = "{\"occupations\": [{\"uri\": \"http://data.europa.eu/esco/occupation/114e1eff-215e-47df-8e10-45a5b72f8197\",\"occupation\": \"renewable energy consultant\",\"alternativeLabels\": [\"alt 1\"],\"lastModified\": \"03-12-2019 00:00:01\"}]}";
            var          handlerMock = MockHelpers.GetMockMessageHandler(skillsJson);
            var          restClient  = new RestClient(handlerMock.Object);

            _serviceTaxonomyRepository = new ServiceTaxonomyRepository(restClient);

            //Cosmos  Settings
            _cosmosSettings = Options.Create(new CosmosSettings()
            {
                ApiUrl                 = "https://test-account-not-real.documents.azure.com:443/",
                ApiKey                 = "VGhpcyBpcyBteSB0ZXN0",
                DatabaseName           = "DatabaseName",
                UserSessionsCollection = "UserSessions"
            });
            _client        = new Mock <CosmosClient>();
            _cosmosService = Substitute.For <ICosmosService>();

            //Session Settings
            _sessionService = Substitute.For <ISessionService>();
            _sessionConfig  = Options.Create(new SessionConfig()
            {
                Salt = "ThisIsASalt"
            });
        }
 public LmiService(IRestClient restClient, IOptions <LmiSettings> lmiSettings, ICosmosService cosmosService)
 {
     _restClient    = restClient ?? new RestClient();
     _cosmosService = cosmosService;
     Throw.IfNullOrWhiteSpace(lmiSettings.Value.ApiUrl, nameof(lmiSettings.Value.ApiUrl));
     Throw.IfLessThan(0, lmiSettings.Value.CacheLifespan, nameof(lmiSettings.Value.CacheLifespan));
     _lmiSettings = lmiSettings;
 }
Beispiel #11
0
 public MovieDomainService(ICosmosService <Movie> movieCosmosHandler, ICosmosService <ProductionCompany> productionCompanyCosmosHandler,
                           ICosmosService <Genre> genreCosmosHandler, IServiceScopeFactory serviceScopeFactory, IMovieAPI movieAPI)
 {
     _movieCosmosHandler             = movieCosmosHandler;
     _productionCompanyCosmosHandler = productionCompanyCosmosHandler;
     _genreCosmosHandler             = genreCosmosHandler;
     _serviceScopeFactory            = serviceScopeFactory;
     _movieAPI = movieAPI;
 }
Beispiel #12
0
            public void WhenContainerIsNull_ThrowError()
            {
                var client = Substitute.For <CosmosClient>();

                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.UserSessionsCollection)
                .ReturnsNullForAnyArgs();
                _service = new CosmosService(_cosmosSettings, client, _logger);
                _service.Invoking(x => x.CreateItemAsync(new UserSession(), CosmosCollection.Session)).Should().Throw <ArgumentException>();
            }
Beispiel #13
0
 public void Init()
 {
     _cosmosService = Substitute.For <ICosmosService>();
     _sessionConfig = Options.Create(new SessionConfig()
     {
         Salt = "ThisIsASalt"
     });
     _sessionClient = Substitute.For <ISessionClient>();
 }
 public SessionService(ICosmosService cosmosService, IOptions <SessionConfig> sessionConfig,
                       ISessionClient sessionClient)
 {
     Throw.IfNull(cosmosService, nameof(cosmosService));
     Throw.IfNull(sessionConfig, nameof(sessionConfig));
     Throw.IfNullOrWhiteSpace(sessionConfig.Value.Salt, nameof(sessionConfig.Value.Salt));
     _cosmosService = cosmosService;
     _sessionConfig = sessionConfig;
     _sessionClient = sessionClient;
 }
Beispiel #15
0
 public HttpExample(
     ILogger <HttpExample> logger,
     ICosmosService cosmosService,
     IOptions <CosmosSettings> dbSettings
     )
 {
     this.cosmos     = cosmosService.CosmosClient;
     this.dbSettings = dbSettings.Value;
     this.logger     = logger;
 }
        internal static async Task CreateDatabaseAndContainerNameIfNotExistAsync(
            ICosmosService service,
            string databaseName,
            string containerName,
            string partitionKey,
            int?databaseThroughput  = null,
            int?containerThroughput = null)
        {
            var database = await service.CreateDatabaseIfNotExistsAsync(databaseName, databaseThroughput);

            await CreateContainerIfNotExistsAsync(service, database, containerName, partitionKey, containerThroughput);
        }
Beispiel #17
0
        internal CosmosContext CreateContext(CosmosAttribute attribute)
        {
            string resolvedConnectionString = ResolveConnectionString(attribute.ConnectionStringSetting);

            ICosmosService service = GetService(resolvedConnectionString, attribute.ApplicationName, attribute.ApplicationRegion);

            return(new CosmosContext
            {
                Service = service,
                ResolvedAttribute = attribute,
            });
        }
Beispiel #18
0
            public async Task WhenBadRequestIsMade_ReturnNull()
            {
                var client    = Substitute.For <CosmosClient>();
                var container = Substitute.For <Container>();

                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.UserSessionsCollection).ReturnsForAnyArgs(container);
                _service = new CosmosService(_cosmosSettings, client, _logger);
                var result = await _service.CreateItemAsync(new UserSession(), CosmosCollection.Session);

                var expected = new HttpResponseMessage(HttpStatusCode.InternalServerError);

                result.StatusCode.Should().Be(expected.StatusCode);
            }
Beispiel #19
0
            public async Task WhenBadRequestIsMade_ReturnNull()
            {
                var client    = Substitute.For <CosmosClient>();
                var container = Substitute.For <Container>();

                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.UserSessionsCollection).ReturnsForAnyArgs(container);
                _service = new CosmosService(_cosmosSettings, client);
                var result = await _service.ReadItemAsync("id", "partitionKey", CosmosCollection.Session);

                var expected = new HttpResponseMessage(HttpStatusCode.NotFound);

                result.StatusCode.Should().Be(expected.StatusCode);
            }
Beispiel #20
0
        public CosmosClient Convert(CosmosAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            ICosmosService service = configProvider.GetService(
                configProvider.ResolveConnectionString(attribute.ConnectionStringSetting),
                attribute.ApplicationName,
                attribute.ApplicationRegion);

            return(service.GetClient());
        }
 public CheckYourAnswersController(ILogger <CheckYourAnswersController> logger, ISubmissionService submissionService,
                                   ICosmosService cosmosService, INotificationService notificationService,
                                   IDocumentService documentService, ISessionService sessionService,
                                   IPageHelper pageHelper, IConfiguration configuration)
 {
     _logger              = logger;
     _submissionService   = submissionService;
     _cosmosService       = cosmosService;
     _notificationService = notificationService;
     _documentService     = documentService;
     _sessionService      = sessionService;
     _pageHelper          = pageHelper;
     _configuration       = configuration;
 }
Beispiel #22
0
        public static async Task <List <T> > GetDataSample <T>(ICosmosService <T> _service)
        {
            var file = $"{Startup.PATH}/Statics/{typeof(T).Name}_SEED.json";

            if (File.Exists(file))
            {
                var data = JsonSerializer.Deserialize <List <T> >(File.ReadAllText(file));
                foreach (T item in data)
                {
                    await _service.AddItemAsync(item);
                }
                return(data);
            }
            return(new List <T>());
        }
Beispiel #23
0
            public async Task WhenItemNotFound_ReturnNotFound()
            {
                var client    = Substitute.For <CosmosClient>();
                var container = Substitute.For <Container>();

                container.ReadItemAsync <object>(Arg.Any <string>(), Arg.Any <PartitionKey>())
                .Returns(Task.FromException <ItemResponse <object> >(new Exception("404 Not found")));
                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.LmiDataCollection).ReturnsForAnyArgs(container);
                _service = new CosmosService(_cosmosSettings, client);
                var result = await _service.ReadItemAsync("id", "partitionKey", CosmosCollection.Session);

                var expected = new HttpResponseMessage(HttpStatusCode.NotFound);

                result.StatusCode.Should().Be(expected.StatusCode);
            }
Beispiel #24
0
        public QueryDialog(ICosmosService cosmosDbService)
            : base(nameof(QueryDialog))
        {
            _cosmosService = cosmosDbService;

            var waterfallSteps = new WaterfallStep[]
            {
                AppNameStepAsync,
                DisplayResultsAsync
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #25
0
 public void Init()
 {
     _cosmosSettings = Options.Create(new CosmosSettings()
     {
         ApiUrl                 = "https://test-account-not-real.documents.azure.com:443/",
         ApiKey                 = "VGhpcyBpcyBteSB0ZXN0",
         DatabaseName           = "DatabaseName",
         UserSessionsCollection = "UserSessions"
     });
     _client        = Substitute.For <CosmosClient>();
     _cosmosService = Substitute.For <ICosmosService>();
     _sessionClient = Substitute.For <ISessionClient>();
     _sessionConfig = Options.Create(new SessionConfig()
     {
         Salt = "ThisIsASalt"
     });
 }
Beispiel #26
0
            public async Task WhenCorrectRequestMade_ReturnSuccessCode()
            {
                var client = Substitute.For <CosmosClient>();

                var container = Substitute.For <Container>();

                var response = Substitute.For <ItemResponse <object> >();

                response.StatusCode.ReturnsForAnyArgs(HttpStatusCode.Created);
                container.CreateItemAsync(Arg.Any <object>()).Returns(Task.FromResult(response));

                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.UserSessionsCollection).ReturnsForAnyArgs(container);
                _service = new CosmosService(_cosmosSettings, client, _logger);
                var result = await _service.CreateItemAsync(new UserSession(), CosmosCollection.Session);

                var expected = new HttpResponseMessage(HttpStatusCode.Created);

                result.StatusCode.Should().Be(expected.StatusCode);
            }
Beispiel #27
0
            public async Task WhenCorrectRequestMade_ReturnSuccessCode()
            {
                var client = Substitute.For <CosmosClient>();

                var container = Substitute.For <Container>();

                var response = Substitute.For <ItemResponse <object> >();

                response.StatusCode.ReturnsForAnyArgs(HttpStatusCode.OK);
                response.Resource.ReturnsForAnyArgs(JsonConvert.SerializeObject(new UserSession()));
                container.ReadItemAsync <object>(Arg.Any <string>(), Arg.Any <PartitionKey>()).Returns(Task.FromResult(response));

                client.GetContainer(_cosmosSettings.Value.DatabaseName, _cosmosSettings.Value.UserSessionsCollection).ReturnsForAnyArgs(container);
                _service = new CosmosService(_cosmosSettings, client);
                var result = await _service.ReadItemAsync("Id", "partitionKey", CosmosCollection.Session);

                var expected = new HttpResponseMessage(HttpStatusCode.OK);

                result.StatusCode.Should().Be(expected.StatusCode);
            }
Beispiel #28
0
        public void SetupBase()
        {
            user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, "example name"),
                new Claim(ClaimTypes.NameIdentifier, "1"),
                new Claim("CustomerId", new Guid().ToString()),
            }, "mock"));



            _compositeSettings = Options.Create(new CompositeSettings
            {
                Cdn  = "cdn",
                Path = "Path"
            });

            _dssReader     = Substitute.For <IDssReader>();
            _dssWriter     = Substitute.For <IDssWriter>();
            _cosmosService = Substitute.For <ICosmosService>();
            _authSettings  = Options.Create(new AuthSettings
            {
            });

            var customer = new Customer
            {
                CustomerId = new Guid("c2e27821-cc60-4d3d-b4f0-cbe20867897c"),
                FamilyName = "familyName",
                GivenName  = "givenName"
            };
            var adviser = new Adviser
            {
                AdviserDetailId          = new Guid().ToString(),
                AdviserName              = null,
                AdviserEmailAddress      = null,
                AdviserContactNumber     = null,
                LastModifiedDate         = default,
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Restore"/> class.
 /// </summary>
 public Restore(ICosmosService cosmosService, IBlobService blobService)
 {
     _cosmosService = cosmosService;
     _blobService   = blobService;
 }
Beispiel #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoadTestingCleanup"/> class.
 /// </summary>
 /// <param name="cosmosService">The Cosmos DB service.</param>
 /// <param name="blobService">The blob service.</param>
 public LoadTestingCleanup(ICosmosService cosmosService, IBlobService blobService)
 {
     _cosmosService = cosmosService;
     _blobService   = blobService;
 }