Esempio n. 1
0
        public async Task <bool> SendCallBackResponse(SalesCatalogueProductResponse salesCatalogueProductResponse, SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage)
        {
            if (!string.IsNullOrWhiteSpace(scsResponseQueueMessage.CallbackUri))
            {
                try
                {
                    ExchangeSetResponse exchangeSetResponse = SetExchangeSetResponse(salesCatalogueProductResponse, scsResponseQueueMessage);

                    CallBackResponse callBackResponse = SetCallBackResponse(exchangeSetResponse);
                    callBackResponse.Subject = essCallBackConfiguration.Value.Subject;

                    if (ValidateCallbackRequestPayload(callBackResponse))
                    {
                        string payloadJson = JsonConvert.SerializeObject(callBackResponse);

                        return(await SendResponseToCallBackApi(false, payloadJson, scsResponseQueueMessage));
                    }
                    else
                    {
                        logger.LogError(EventIds.ExchangeSetCreatedPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} as payload data is incorrect.", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId);
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(EventIds.ExchangeSetCreatedPostCallbackUriNotCalled.ToEventId(), ex, "Post Callback uri is not called after exchange set is created for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} and Exception:{Message}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId, ex.Message);
                    return(false);
                }
            }
            else
            {
                logger.LogInformation(EventIds.ExchangeSetCreatedPostCallbackUriNotProvided.ToEventId(), "Post callback uri was not provided by requestor for successful exchange set creation for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId);
                return(false);
            }
        }
Esempio n. 2
0
        public void WhenIsCancellationRequestedinExchangeSet_ThenThrowCancelledException()
        {
            SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage       = GetScsResponseQueueMessage();
            SalesCatalogueProductResponse             salesCatalogueProductResponse = GetSalesCatalogueResponse();

            string storageAccountConnectionString = "DefaultEndpointsProtocol = https; AccountName = testessdevstorage2; AccountKey =testaccountkey; EndpointSuffix = core.windows.net";

            fakeConfiguration["HOME"] = @"D:\\Downloads";

            A.CallTo(() => fakeScsStorageService.GetStorageAccountConnectionString(null, null))
            .Returns(storageAccountConnectionString);
            var productList = new List <Products> {
                new Products {
                    ProductName   = "DE5NOBRK",
                    EditionNumber = 0,
                    UpdateNumbers = new List <int?> {
                        0, 1
                    },
                    FileSize = 400
                }
            };
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Cancel();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            A.CallTo(() => fakeAzureBlobStorageService.DownloadSalesCatalogueResponse(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(salesCatalogueProductResponse);

            Assert.ThrowsAsync <TaskCanceledException>(async() => await fulfilmentDataService.QueryFileShareServiceFiles(scsResponseQueueMessage, productList, null, cancellationTokenSource, cancellationToken));
        }
Esempio n. 3
0
        private Task <bool> SaveSalesCatalogueStorageDetails(SalesCatalogueProductResponse salesCatalogueResponse, string batchId, string callBackUri, string correlationId, string expiryDate)
        {
            return(logger.LogStartEndAndElapsedTimeAsync(EventIds.SCSResponseStoreRequestStart,
                                                         EventIds.SCSResponseStoreRequestCompleted,
                                                         "SCS response store request for BatchId:{batchId} and _X-Correlation-ID:{CorrelationId}",
                                                         async() =>
            {
                bool result = await exchangeSetStorageProvider.SaveSalesCatalogueStorageDetails(salesCatalogueResponse, batchId, callBackUri, correlationId, expiryDate);

                return result;
            }, batchId, correlationId));
        }
Esempio n. 4
0
        public static long GetFileSize(SalesCatalogueProductResponse salesCatalogueResponse)
        {
            long fileSize = 0;

            if (salesCatalogueResponse != null && salesCatalogueResponse.ProductCounts.ReturnedProductCount > 0)
            {
                foreach (var item in salesCatalogueResponse.Products)
                {
                    fileSize += item.FileSize.Value;
                }
            }
            return(fileSize);
        }
Esempio n. 5
0
        public async Task WhenPostProductVersionsAsyncCallsApi_ThenValidateCorrectParametersArePassed()
        {
            //Data
            string actualAccessToken = "notRequiredDuringTesting";
            var    requestBody       = new List <ProductVersionRequest> {
                new ProductVersionRequest()
                {
                    EditionNumber = 1, ProductName = "TEST1", UpdateNumber = 0
                }
            };
            string postBodyParam = "This should be replaced by actual value";

            //Test variable
            string     accessTokenParam   = null;
            string     uriParam           = null;
            HttpMethod httpMethodParam    = null;
            var        scsResponse        = new SalesCatalogueProductResponse();
            var        jsonString         = JsonConvert.SerializeObject(scsResponse);
            string     correlationIdParam = null;

            //Mock
            A.CallTo(() => fakeAuthScsTokenProvider.GetManagedIdentityAuthAsync(A <string> .Ignored)).Returns(actualAccessToken);
            var httpResponse = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK, Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            };

            A.CallTo(() => fakeSalesCatalogueClient.CallSalesCatalogueServiceApi(A <HttpMethod> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Invokes((HttpMethod method, string postBody, string accessToken, string uri, string correlationId) =>
            {
                accessTokenParam   = accessToken;
                uriParam           = uri;
                httpMethodParam    = method;
                postBodyParam      = postBody;
                correlationIdParam = correlationId;
            })
            .Returns(httpResponse);

            //Method call
            var response = await salesCatalogueService.PostProductVersionsAsync(requestBody, string.Empty);

            //Test
            Assert.AreEqual(response.ResponseCode, HttpStatusCode.OK);
            Assert.AreEqual(HttpMethod.Post, httpMethodParam);
            Assert.AreEqual($"/{fakeSaleCatalogueConfig.Value.Version}/productData/{fakeSaleCatalogueConfig.Value.ProductType}/products/productVersions", uriParam);
            Assert.AreEqual(JsonConvert.SerializeObject(requestBody), postBodyParam);
            Assert.AreEqual(actualAccessToken, accessTokenParam);
        }
Esempio n. 6
0
        public Task <SalesCatalogueProductResponse> DownloadSalesCatalogueResponse(string scsResponseUri, string batchId, string correlationId)
        {
            return(logger.LogStartEndAndElapsedTimeAsync(EventIds.DownloadSalesCatalogueResponseDataStart,
                                                         EventIds.DownloadSalesCatalogueResponseDataCompleted,
                                                         "Sales catalogue response download from blob for scsResponseUri:{scsResponseUri} and BatchId:{batchId} and _X-Correlation-ID:{correlationId}",
                                                         async() => {
                string storageAccountConnectionString = scsStorageService.GetStorageAccountConnectionString();
                CloudBlockBlob cloudBlockBlob = azureBlobStorageClient.GetCloudBlockBlobByUri(scsResponseUri, storageAccountConnectionString);

                var responseFile = await azureBlobStorageClient.DownloadTextAsync(cloudBlockBlob);
                SalesCatalogueProductResponse salesCatalogueProductResponse = JsonConvert.DeserializeObject <SalesCatalogueProductResponse>(responseFile);

                return salesCatalogueProductResponse;
            },
                                                         scsResponseUri, batchId, correlationId));
        }
Esempio n. 7
0
        public async Task <bool> SendCallBackErrorResponse(SalesCatalogueProductResponse salesCatalogueProductResponse, SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage)
        {
            salesCatalogueProductResponse.ProductCounts.ReturnedProductCount         = 0;
            salesCatalogueProductResponse.ProductCounts.RequestedProductsNotReturned = new List <RequestedProductsNotReturned> {
                new RequestedProductsNotReturned {
                    ProductName = null, Reason = essCallBackConfiguration.Value.Reason
                }
            };

            if (!string.IsNullOrWhiteSpace(scsResponseQueueMessage.CallbackUri))
            {
                try
                {
                    ExchangeSetResponse exchangeSetResponse = SetExchangeSetResponse(salesCatalogueProductResponse, scsResponseQueueMessage);
                    exchangeSetResponse.Links.ExchangeSetFileUri      = null;
                    exchangeSetResponse.Links.ExchangeSetErrorFileUri = new LinkSetErrorFileUri {
                        Href = $"{fileShareServiceConfig.Value.PublicBaseUrl}/batch/{scsResponseQueueMessage.BatchId}/files/{fileShareServiceConfig.Value.ErrorFileName}"
                    };

                    CallBackResponse callBackResponse = SetCallBackResponse(exchangeSetResponse);
                    callBackResponse.Subject = essCallBackConfiguration.Value.ErrorSubject;

                    if (ValidateCallbackErrorRequestPayload(callBackResponse))
                    {
                        string payloadJson = JsonConvert.SerializeObject(callBackResponse);

                        return(await SendResponseToCallBackApi(true, payloadJson, scsResponseQueueMessage));
                    }
                    else
                    {
                        logger.LogError(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} as payload data is incorrect.", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId);
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} and Exception:{Message}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId, ex.Message);
                    return(false);
                }
            }
            else
            {
                logger.LogInformation(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotProvided.ToEventId(), "Post callback uri was not provided by requestor for exchange set creation with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId);
                return(false);
            }
        }
Esempio n. 8
0
        public async Task WhenSCSClientReturns200_ThenGetProductsFromSpecificDateAsyncReturns200AndDataInResponse()
        {
            SalesCatalogueProductResponse scsResponse = GetSalesCatalogueServiceResponse();

            var jsonString = JsonConvert.SerializeObject(scsResponse);

            A.CallTo(() => fakeAuthScsTokenProvider.GetManagedIdentityAuthAsync(A <string> .Ignored)).Returns("notRequiredDuringTesting");
            var httpResponse = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK, Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            };

            A.CallTo(() => fakeSalesCatalogueClient.CallSalesCatalogueServiceApi(A <HttpMethod> .Ignored, null, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Returns(httpResponse);
            var response = await salesCatalogueService.GetProductsFromSpecificDateAsync(DateTime.UtcNow.ToString(), string.Empty);

            Assert.AreEqual(HttpStatusCode.OK, response.ResponseCode, $"Expected {HttpStatusCode.OK} got {response.ResponseCode}");
            Assert.AreEqual(jsonString, JsonConvert.SerializeObject(response.ResponseBody));
        }
Esempio n. 9
0
        public async Task WhenCallStoreSaleCatalogueServiceResponseAsync_ThenReturnsTrue()
        {
            string batchId       = "7b4cdf10-adfa-4ed6-b2fe-d1543d8b7272";
            string containerName = "testContainer";
            string callBackUri   = "https://essTest/myCallback?secret=test&po=1234";
            string correlationId = "a6670458-9bbc-4b52-95a2-d1f50fe9e3ae";
            string storageAccountConnectionString = "DefaultEndpointsProtocol = https; AccountName = testessdevstorage2; AccountKey =testaccountkey; EndpointSuffix = core.windows.net";
            SalesCatalogueProductResponse salesCatalogueProductResponse = GetSalesCatalogueServiceResponse();
            CancellationToken             cancellationToken             = CancellationToken.None;

            A.CallTo(() => fakeScsStorageService.GetStorageAccountConnectionString(null, null)).Returns(storageAccountConnectionString);

            A.CallTo(() => fakeAzureBlobStorageClient.GetCloudBlockBlob(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(new CloudBlockBlob(new System.Uri("http://tempuri.org/blob")));

            A.CallTo(() => fakeSmallExchangeSetInstance.GetInstanceNumber(1)).Returns(3);
            var response = await azureBlobStorageService.StoreSaleCatalogueServiceResponseAsync(containerName, batchId, salesCatalogueProductResponse, callBackUri, correlationId, cancellationToken, fakeExpiryDate);

            Assert.IsTrue(response);
        }
Esempio n. 10
0
        public async Task WhenGetProductsFromSpecificDateAsyncCallsApi_ThenValidateCorrectParametersArePassed()
        {
            //Data
            string actualAccessToken = "notRequiredDuringTesting";
            string postBodyParam     = "This should be null when passed to api call";
            string sinceDateTime     = DateTime.UtcNow.ToString();

            //Test variable
            string     accessTokenParam   = null;
            string     uriParam           = null;
            HttpMethod httpMethodParam    = null;
            var        scsResponse        = new SalesCatalogueProductResponse();
            var        jsonString         = JsonConvert.SerializeObject(scsResponse);
            string     correlationIdParam = null;

            //Mock
            A.CallTo(() => fakeAuthScsTokenProvider.GetManagedIdentityAuthAsync(A <string> .Ignored)).Returns(actualAccessToken);
            var httpResponse = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK, Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            };

            A.CallTo(() => fakeSalesCatalogueClient.CallSalesCatalogueServiceApi(A <HttpMethod> .Ignored, null, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Invokes((HttpMethod method, string postBody, string accessToken, string uri, string correlationId) =>
            {
                accessTokenParam   = accessToken;
                uriParam           = uri;
                httpMethodParam    = method;
                postBodyParam      = postBody;
                correlationIdParam = correlationId;
            })
            .Returns(httpResponse);

            //Method call
            var response = await salesCatalogueService.GetProductsFromSpecificDateAsync(sinceDateTime, string.Empty);

            //Test
            Assert.AreEqual(HttpStatusCode.OK, response.ResponseCode);
            Assert.AreEqual(HttpMethod.Get, httpMethodParam);
            Assert.AreEqual($"/{fakeSaleCatalogueConfig.Value.Version}/productData/{fakeSaleCatalogueConfig.Value.ProductType}/products?sinceDateTime={sinceDateTime}", uriParam);
            Assert.IsNull(postBodyParam);
            Assert.AreEqual(actualAccessToken, accessTokenParam);
        }
Esempio n. 11
0
        public void Setup()
        {
            postBodyParam   = "This should be replace by actual value when param passed to api call";
            uriParam        = null;
            httpMethodParam = null;
            salesCatalogueProductResponse = GetSalesCatalogueServiceResponse();
            scsResponseQueueMessage       = GetScsResponseQueueMessage();

            fakeEssCallBackConfiguration = Options.Create(new EssCallBackConfiguration()
            {
            });
            fakeCallBackClient         = A.Fake <ICallBackClient>();
            fakeFileShareServiceConfig = Options.Create(new FileShareServiceConfiguration()
            {
            });
            fakeLogger = A.Fake <ILogger <FulfilmentCallBackService> >();

            fulfilmentCallBackService = new FulfilmentCallBackService(fakeEssCallBackConfiguration, fakeCallBackClient, fakeFileShareServiceConfig, fakeLogger);
        }
Esempio n. 12
0
        public async Task WhenValidMessageQueueTrigger_ThenReturnsExchangeSetCreatedSuccessfully()
        {
            SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage       = GetScsResponseQueueMessage();
            SalesCatalogueProductResponse             salesCatalogueProductResponse = GetSalesCatalogueResponse();

            var fulfilmentDataResponse = new List <FulfilmentDataResponse>()
            {
                new FulfilmentDataResponse {
                    BatchId = "63d38bde-5191-4a59-82d5-aa22ca1cc6dc", EditionNumber = 10, ProductName = "Demo", UpdateNumber = 3, FileUri = new List <string> {
                        "http://ffs-demo.azurewebsites.net"
                    }
                }
            };

            string storageAccountConnectionString = "DefaultEndpointsProtocol = https; AccountName = testessdevstorage2; AccountKey =testaccountkey; EndpointSuffix = core.windows.net";

            fakeConfiguration["HOME"] = @"D:\\Downloads";
            fakeFileShareServiceConfig.Value.ExchangeSetFileFolder = "V01X01";
            fakeFileShareServiceConfig.Value.EncRoot = "ENC_ROOT";
            SalesCatalogueDataResponse salesCatalogueDataResponse = GetSalesCatalogueDataResponse();

            A.CallTo(() => fakeScsStorageService.GetStorageAccountConnectionString(null, null))
            .Returns(storageAccountConnectionString);
            string filePath = @"D:\\Downloads";

            A.CallTo(() => fakeAzureBlobStorageService.DownloadSalesCatalogueResponse(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(salesCatalogueProductResponse);
            A.CallTo(() => fakeQueryFssService.SearchReadMeFilePath(A <string> .Ignored, A <string> .Ignored)).Returns(filePath);
            A.CallTo(() => fakeQueryFssService.DownloadReadMeFile(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(true);
            A.CallTo(() => fakeQueryFssService.CreateZipFileForExchangeSet(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(true);
            A.CallTo(() => fakeQueryFssService.UploadZipFileForExchangeSetToFileShareService(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(true);
            A.CallTo(() => fakeFulfilmentAncillaryFiles.CreateCatalogFile(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, fulfilmentDataResponse, salesCatalogueDataResponse, salesCatalogueProductResponse)).Returns(true);
            A.CallTo(() => fakeFulfilmentSalesCatalogueService.GetSalesCatalogueDataResponse(A <string> .Ignored, A <string> .Ignored)).Returns(salesCatalogueDataResponse);
            A.CallTo(() => fakeFulfilmentAncillaryFiles.CreateProductFile(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, salesCatalogueDataResponse)).Returns(true);
            A.CallTo(() => fakeFulfilmentCallBackService.SendCallBackResponse(A <SalesCatalogueProductResponse> .Ignored, A <SalesCatalogueServiceResponseQueueMessage> .Ignored)).Returns(true);

            string salesCatalogueResponseFile = await fulfilmentDataService.CreateExchangeSet(scsResponseQueueMessage, currentUtcDate);

            Assert.AreEqual("Exchange Set Created Successfully", salesCatalogueResponseFile);
        }
Esempio n. 13
0
 public ExchangeSetResponse SetExchangeSetResponse(SalesCatalogueProductResponse salesCatalogueProductResponse, SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage)
 {
     return(new ExchangeSetResponse()
     {
         Links = new Links()
         {
             ExchangeSetBatchStatusUri = new LinkSetBatchStatusUri {
                 Href = $"{fileShareServiceConfig.Value.PublicBaseUrl}/batch/{scsResponseQueueMessage.BatchId}/status"
             },
             ExchangeSetBatchDetailsUri = new LinkSetBatchDetailsUri {
                 Href = $"{fileShareServiceConfig.Value.PublicBaseUrl}/batch/{scsResponseQueueMessage.BatchId}"
             },
             ExchangeSetFileUri = new LinkSetFileUri {
                 Href = $"{fileShareServiceConfig.Value.PublicBaseUrl}/batch/{scsResponseQueueMessage.BatchId}/files/{fileShareServiceConfig.Value.ExchangeSetFileName}"
             }
         },
         ExchangeSetUrlExpiryDateTime = Convert.ToDateTime(scsResponseQueueMessage.ExchangeSetUrlExpiryDate).ToUniversalTime(),
         RequestedProductCount = salesCatalogueProductResponse.ProductCounts.RequestedProductCount.Value,
         ExchangeSetCellCount = salesCatalogueProductResponse.ProductCounts.ReturnedProductCount.Value,
         RequestedProductsAlreadyUpToDateCount = salesCatalogueProductResponse.ProductCounts.RequestedProductsAlreadyUpToDateCount.Value,
         RequestedProductsNotInExchangeSet = GetRequestedProductsNotInExchangeSet(salesCatalogueProductResponse)
     });
 }
Esempio n. 14
0
        public async Task WhenInvalidMessageQueueTrigger_ThenReturnsExchangeSetIsNotCreated()
        {
            SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage       = GetScsResponseQueueMessage();
            SalesCatalogueProductResponse             salesCatalogueProductResponse = GetSalesCatalogueResponse();
            string storageAccountConnectionString = "DefaultEndpointsProtocol = https; AccountName = testessdevstorage2; AccountKey =testaccountkey; EndpointSuffix = core.windows.net";

            fakeConfiguration["HOME"] = @"D:\\Downloads";
            fakeFileShareServiceConfig.Value.ExchangeSetFileFolder = "V01X01";
            fakeFileShareServiceConfig.Value.EncRoot = "ENC_ROOT";
            A.CallTo(() => fakeScsStorageService.GetStorageAccountConnectionString(null, null))
            .Returns(storageAccountConnectionString);
            string filePath = @"D:\\Downloads";

            A.CallTo(() => fakeAzureBlobStorageService.DownloadSalesCatalogueResponse(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(salesCatalogueProductResponse);
            A.CallTo(() => fakeQueryFssService.SearchReadMeFilePath(A <string> .Ignored, A <string> .Ignored)).Returns(filePath);
            A.CallTo(() => fakeQueryFssService.DownloadReadMeFile(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(true);
            A.CallTo(() => fakeQueryFssService.CreateZipFileForExchangeSet(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(true);
            A.CallTo(() => fakeQueryFssService.UploadZipFileForExchangeSetToFileShareService(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(false);

            string salesCatalogueResponseFile = await fulfilmentDataService.CreateExchangeSet(scsResponseQueueMessage, currentUtcDate);

            Assert.AreEqual("Exchange Set Is Not Created", salesCatalogueResponseFile);
        }
Esempio n. 15
0
        public async Task WhenSCSClientReturns200_ThenPostProductVersionsAsyncReturns200AndDataInResponse()
        {
            SalesCatalogueProductResponse scsResponse = GetSalesCatalogueServiceResponse();

            var jsonString = JsonConvert.SerializeObject(scsResponse);

            A.CallTo(() => fakeAuthScsTokenProvider.GetManagedIdentityAuthAsync(A <string> .Ignored)).Returns("notRequiredDuringTesting");
            var httpResponse = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK, Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            };

            A.CallTo(() => fakeSalesCatalogueClient.CallSalesCatalogueServiceApi(A <HttpMethod> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Returns(httpResponse);
            var response = await salesCatalogueService.PostProductVersionsAsync(new List <ProductVersionRequest> {
                new ProductVersionRequest()
                {
                    EditionNumber = 1, ProductName = "TEST1", UpdateNumber = 0
                }
            }, String.Empty);

            Assert.AreEqual(HttpStatusCode.OK, response.ResponseCode, $"Expected {HttpStatusCode.OK} got {response.ResponseCode}");
            Assert.AreEqual(jsonString, JsonConvert.SerializeObject(response.ResponseBody));
        }
Esempio n. 16
0
        public async Task UploadSalesCatalogueServiceResponseToBlobAsync(CloudBlockBlob cloudBlockBlob, SalesCatalogueProductResponse salesCatalogueResponse)
        {
            var serializeJsonObject = JsonConvert.SerializeObject(salesCatalogueResponse);

            using (var ms = new MemoryStream())
            {
                LoadStreamWithJson(ms, serializeJsonObject);
                await azureBlobStorageClient.UploadFromStreamAsync(cloudBlockBlob, ms);
            }
        }
Esempio n. 17
0
 public async Task AddQueueMessage(string batchId, SalesCatalogueProductResponse salesCatalogueResponse, string callBackUri, string correlationId, CloudBlockBlob cloudBlockBlob, int instanceNumber, string storageAccountConnectionString, string expiryDate)
 {
     SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage = GetSalesCatalogueServiceResponseQueueMessage(batchId, salesCatalogueResponse, callBackUri, correlationId, cloudBlockBlob, expiryDate);
     var scsResponseQueueMessageJSON = JsonConvert.SerializeObject(scsResponseQueueMessage);
     await azureMessageQueueHelper.AddMessage(batchId, instanceNumber, storageAccountConnectionString, scsResponseQueueMessageJSON, correlationId);
 }
Esempio n. 18
0
        public async Task <bool> StoreSaleCatalogueServiceResponseAsync(string containerName, string batchId, SalesCatalogueProductResponse salesCatalogueResponse, string callBackUri, string correlationId, CancellationToken cancellationToken, string expiryDate)
        {
            string uploadFileName        = string.Concat(batchId, ".json");
            long   fileSize              = CommonHelper.GetFileSize(salesCatalogueResponse);
            var    fileSizeInMB          = CommonHelper.ConvertBytesToMegabytes(fileSize);
            var    instanceCountAndType  = GetInstanceCountBasedOnFileSize(fileSizeInMB);
            var    storageAccountWithKey = GetStorageAccountNameAndKeyBasedOnExchangeSetType(instanceCountAndType.Item2);

            string storageAccountConnectionString =
                scsStorageService.GetStorageAccountConnectionString(storageAccountWithKey.Item1, storageAccountWithKey.Item2);
            CloudBlockBlob cloudBlockBlob = await azureBlobStorageClient.GetCloudBlockBlob(uploadFileName, storageAccountConnectionString, containerName);

            cloudBlockBlob.Properties.ContentType = CONTENT_TYPE;

            await UploadSalesCatalogueServiceResponseToBlobAsync(cloudBlockBlob, salesCatalogueResponse);

            logger.LogInformation(EventIds.SCSResponseStoredToBlobStorage.ToEventId(), "Sales catalogue service response stored to blob storage with fileSizeInMB:{fileSizeInMB} for BatchId:{batchId} and _X-Correlation-ID:{CorrelationId} ", fileSizeInMB, batchId, correlationId);

            await AddQueueMessage(batchId, salesCatalogueResponse, callBackUri, correlationId, cloudBlockBlob, instanceCountAndType.Item1, storageAccountConnectionString, expiryDate);

            return(true);
        }
Esempio n. 19
0
        public async Task <bool> CreateCatalogFile(string batchId, string exchangeSetRootPath, string correlationId, List <FulfilmentDataResponse> listFulfilmentData, SalesCatalogueDataResponse salesCatalogueDataResponse, SalesCatalogueProductResponse salesCatalogueProductResponse)
        {
            var catBuilder     = new Catalog031BuilderFactory().Create();
            var readMeFileName = Path.Combine(exchangeSetRootPath, fileShareServiceConfig.Value.ReadMeFileName);
            var outputFileName = Path.Combine(exchangeSetRootPath, fileShareServiceConfig.Value.CatalogFileName);

            if (fileSystemHelper.CheckFileExists(readMeFileName))
            {
                catBuilder.Add(new CatalogEntry()
                {
                    FileLocation   = fileShareServiceConfig.Value.ReadMeFileName,
                    Implementation = "TXT"
                });
            }

            if (listFulfilmentData != null && listFulfilmentData.Any())
            {
                listFulfilmentData = listFulfilmentData.OrderBy(a => a.ProductName).ThenBy(b => b.EditionNumber).ThenBy(c => c.UpdateNumber).ToList();

                List <Tuple <string, string> > orderPreference = new List <Tuple <string, string> > {
                    new Tuple <string, string>("application/s63", "BIN"),
                    new Tuple <string, string>("text/plain", "ASC"), new Tuple <string, string>("text/plain", "TXT"), new Tuple <string, string>("image/tiff", "TIF")
                };

                foreach (var listItem in listFulfilmentData)
                {
                    CreateCatalogEntry(listItem, orderPreference, catBuilder, salesCatalogueDataResponse, salesCatalogueProductResponse, exchangeSetRootPath, batchId, correlationId);
                }
            }

            var cat031Bytes = catBuilder.WriteCatalog(fileShareServiceConfig.Value.ExchangeSetFileFolder);

            fileSystemHelper.CheckAndCreateFolder(exchangeSetRootPath);

            fileSystemHelper.CreateFileContentWithBytes(outputFileName, cat031Bytes);

            await Task.CompletedTask;

            if (fileSystemHelper.CheckFileExists(outputFileName))
            {
                return(true);
            }
            else
            {
                logger.LogError(EventIds.CatalogFileIsNotCreated.ToEventId(), "Error in creating catalog.031 file for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}", batchId, correlationId);
                throw new FulfilmentException(EventIds.CatalogFileIsNotCreated.ToEventId());
            }
        }
Esempio n. 20
0
        private void CreateCatalogEntry(FulfilmentDataResponse listItem, List <Tuple <string, string> > orderPreference, ICatalog031Builder catBuilder, SalesCatalogueDataResponse salesCatalogueDataResponse, SalesCatalogueProductResponse salesCatalogueProductResponse, string exchangeSetRootPath, string batchId, string correlationId)
        {
            int length = 2;

            listItem.Files = listItem.Files.OrderByDescending(
                item => Enumerable.Reverse(orderPreference).ToList().IndexOf(new Tuple <string, string>(item.MimeType.ToLower(), GetMimeType(item.Filename.ToLower(), item.MimeType.ToLower(), batchId, correlationId))));

            foreach (var item in listItem.Files)
            {
                string            fileLocation      = Path.Combine(listItem.ProductName.Substring(0, length), listItem.ProductName, listItem.EditionNumber.ToString(), listItem.UpdateNumber.ToString(), item.Filename);
                string            mimeType          = GetMimeType(item.Filename.ToLower(), item.MimeType.ToLower(), batchId, correlationId);
                string            comment           = string.Empty;
                BoundingRectangle boundingRectangle = new BoundingRectangle();

                if (mimeType == "BIN")
                {
                    var salescatalogProduct = salesCatalogueDataResponse.ResponseBody.Where(s => s.ProductName == listItem.ProductName).Select(s => s).FirstOrDefault();
                    if (salescatalogProduct == null)
                    {
                        logger.LogError(EventIds.SalesCatalogueServiceCatalogueDataNotFoundForProduct.ToEventId(), "Error in sales catalogue service catalogue end point when product details not found for Product:{ProductName} and BatchId:{batchId} and _X-Correlation-ID:{CorrelationId}", listItem.ProductName, batchId, correlationId);
                        throw new FulfilmentException(EventIds.SalesCatalogueServiceCatalogueDataNotFoundForProduct.ToEventId());
                    }

                    comment = SetCatalogFileComment(listItem, salescatalogProduct, salesCatalogueProductResponse);

                    boundingRectangle.LatitudeNorth = salescatalogProduct.CellLimitNorthernmostLatitude;
                    boundingRectangle.LatitudeSouth = salescatalogProduct.CellLimitSouthernmostLatitude;
                    boundingRectangle.LongitudeEast = salescatalogProduct.CellLimitEasternmostLatitude;
                    boundingRectangle.LongitudeWest = salescatalogProduct.CellLimitWesternmostLatitude;
                }

                catBuilder.Add(new CatalogEntry()
                {
                    FileLocation      = fileLocation,
                    FileLongName      = "",
                    Implementation    = mimeType,
                    Crc               = (mimeType == "BIN") ? item.Attributes.Where(a => a.Key == "s57-CRC").Select(a => a.Value).FirstOrDefault() : GetCrcString(Path.Combine(exchangeSetRootPath, fileLocation)),
                    Comment           = comment,
                    BoundingRectangle = boundingRectangle
                });
            }
        }
Esempio n. 21
0
        public async Task <bool> CreateCatalogFile(string batchId, string exchangeSetRootPath, string correlationId, List <FulfilmentDataResponse> listFulfilmentData, SalesCatalogueDataResponse salesCatalogueDataResponse, SalesCatalogueProductResponse salesCatalogueProductResponse)
        {
            bool isFileCreated = false;

            if (!string.IsNullOrWhiteSpace(exchangeSetRootPath))
            {
                DateTime createCatalogFileTaskStartedAt = DateTime.UtcNow;
                isFileCreated = await logger.LogStartEndAndElapsedTimeAsync(EventIds.CreateCatalogFileRequestStart,
                                                                            EventIds.CreateCatalogFileRequestCompleted,
                                                                            "Create catalog file request for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}",
                                                                            async() => {
                    return(await fulfilmentAncillaryFiles.CreateCatalogFile(batchId, exchangeSetRootPath, correlationId, listFulfilmentData, salesCatalogueDataResponse, salesCatalogueProductResponse));
                },
                                                                            batchId, correlationId);

                DateTime createCatalogFileTaskCompletedAt = DateTime.UtcNow;
                monitorHelper.MonitorRequest("Create Catalog File Task", createCatalogFileTaskStartedAt, createCatalogFileTaskCompletedAt, correlationId, null, null, null, batchId);
            }

            return(isFileCreated);
        }
Esempio n. 22
0
        private SalesCatalogueServiceResponseQueueMessage GetSalesCatalogueServiceResponseQueueMessage(string batchId, SalesCatalogueProductResponse salesCatalogueResponse, string callBackUri, string correlationId, CloudBlockBlob cloudBlockBlob, string expiryDate)
        {
            long fileSize = CommonHelper.GetFileSize(salesCatalogueResponse);
            var  scsResponseQueueMessage = new SalesCatalogueServiceResponseQueueMessage()
            {
                BatchId                  = batchId,
                ScsResponseUri           = cloudBlockBlob.Uri.AbsoluteUri,
                FileSize                 = fileSize,
                CallbackUri              = callBackUri == null ? string.Empty : callBackUri,
                CorrelationId            = correlationId,
                ExchangeSetUrlExpiryDate = expiryDate
            };

            return(scsResponseQueueMessage);
        }
Esempio n. 23
0
 public virtual async Task <bool> SaveSalesCatalogueStorageDetails(SalesCatalogueProductResponse salesCatalogueResponse, string batchId, string callBackUri, string correlationId, string expiryDate)
 {
     return(await azureBlobStorageService.StoreSaleCatalogueServiceResponseAsync(storageConfig.Value.StorageContainerName, batchId, salesCatalogueResponse, callBackUri, correlationId, CancellationToken.None, expiryDate));
 }
Esempio n. 24
0
        private async Task CreateAncillaryFiles(string batchId, string exchangeSetPath, string correlationId, List <FulfilmentDataResponse> listFulfilmentData, SalesCatalogueProductResponse salecatalogueProductResponse)
        {
            var exchangeSetRootPath = Path.Combine(exchangeSetPath, fileShareServiceConfig.Value.EncRoot);
            var exchangeSetInfoPath = Path.Combine(exchangeSetPath, fileShareServiceConfig.Value.Info);
            SalesCatalogueDataResponse salesCatalogueDataResponse = await GetSalesCatalogueDataResponse(batchId, correlationId);

            await CreateProductFile(batchId, exchangeSetInfoPath, correlationId, salesCatalogueDataResponse);
            await CreateSerialEncFile(batchId, exchangeSetPath, correlationId);
            await DownloadReadMeFile(batchId, exchangeSetRootPath, correlationId);
            await CreateCatalogFile(batchId, exchangeSetRootPath, correlationId, listFulfilmentData, salesCatalogueDataResponse, salecatalogueProductResponse);
        }
Esempio n. 25
0
        private string SetCatalogFileComment(FulfilmentDataResponse listItem, SalesCatalogueDataProductResponse salescatalogProduct, SalesCatalogueProductResponse salesCatalogueProductResponse)
        {
            string getIssueAndUpdateDate       = null;
            int?   cancelledUpdateNumber       = null;
            var    salescatalogProductResponse = salesCatalogueProductResponse.Products.Where(s => s.ProductName == listItem.ProductName).Where(s => s.EditionNumber == listItem.EditionNumber).Select(s => s).FirstOrDefault();

            if (salescatalogProductResponse.Dates != null)
            {
                var dates = salescatalogProductResponse.Dates.Where(s => s.UpdateNumber == listItem.UpdateNumber).Select(s => s).FirstOrDefault();
                getIssueAndUpdateDate = GetIssueAndUpdateDate(dates);
            }
            if (salescatalogProductResponse.Cancellation != null)
            {
                cancelledUpdateNumber = salescatalogProductResponse.Cancellation.UpdateNumber;
            }

            //BoundingRectangle and Comment only required for BIN
            return(salescatalogProduct.BaseCellEditionNumber == 0 && cancelledUpdateNumber == listItem.UpdateNumber
                ? $"{fileShareServiceConfig.Value.CommentVersion},EDTN={salescatalogProduct.BaseCellEditionNumber},UPDN={listItem.UpdateNumber},{getIssueAndUpdateDate}"
                : $"{fileShareServiceConfig.Value.CommentVersion},EDTN={listItem.EditionNumber},UPDN={listItem.UpdateNumber},{getIssueAndUpdateDate}");
        }
Esempio n. 26
0
        public async Task SendErrorCallBackResponse(SalesCatalogueServiceResponseQueueMessage fulfilmentServiceQueueMessage)
        {
            SalesCatalogueProductResponse salesCatalogueProductResponse = await azureBlobStorageService.DownloadSalesCatalogueResponse(fulfilmentServiceQueueMessage.ScsResponseUri, fulfilmentServiceQueueMessage.BatchId, fulfilmentServiceQueueMessage.CorrelationId);

            await fulfilmentCallBackService.SendCallBackErrorResponse(salesCatalogueProductResponse, fulfilmentServiceQueueMessage);
        }
Esempio n. 27
0
        public List <RequestedProductsNotInExchangeSet> GetRequestedProductsNotInExchangeSet(SalesCatalogueProductResponse salesCatalogueProductResponse)
        {
            var listRequestedProductsNotInExchangeSet = new List <RequestedProductsNotInExchangeSet>();

            foreach (var item in salesCatalogueProductResponse.ProductCounts.RequestedProductsNotReturned)
            {
                var requestedProductsNotInExchangeSet = new RequestedProductsNotInExchangeSet
                {
                    ProductName = item.ProductName,
                    Reason      = item.Reason
                };
                listRequestedProductsNotInExchangeSet.Add(requestedProductsNotInExchangeSet);
            }
            return(listRequestedProductsNotInExchangeSet);
        }