Exemple #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ErrorHandlingMiddleware" /> class.
 /// </summary>
 /// <param name="requestDelegate">Next middleware.</param>
 /// <param name="logger">Logger instance.</param>
 /// <param name="applicationSettings">Options accessor.</param>
 public ErrorHandlingMiddleware(RequestDelegate requestDelegate, ILogger <ErrorHandlingMiddleware> logger, IOptions <ApplicationSettings> applicationSettings)
 {
     NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
     this.requestDelegate = requestDelegate;
     this.logger          = logger;
     this.includeExceptionDetailsInResponse = applicationSettings.Value.IncludeExceptionStackInResponse;
 }
Exemple #2
0
        /// <inheritdoc/>
        public async Task <InvoiceDetailsViewModel> AddInvoiceAsync(InvoiceDetailsViewModel invoice)
        {
            NotNullValidator.ThrowIfNull(invoice, nameof(invoice));
            invoice.Id     = Guid.NewGuid().ToString();
            invoice.SoldBy = new SoldByViewModel()
            {
                Email      = "*****@*****.**",
                Phone      = "9876543210",
                SellerName = "Packt",
            };
            using var invoiceRequest = new StringContent(JsonSerializer.Serialize(invoice), Encoding.UTF8, ContentType);
            var invoiceResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.Value.DataStoreEndpoint}api/invoice"), invoiceRequest).ConfigureAwait(false);

            if (!invoiceResponse.IsSuccessStatusCode)
            {
                await this.ThrowServiceToServiceErrors(invoiceResponse).ConfigureAwait(false);
            }

            var createdInvoiceDAO = await invoiceResponse.Content.ReadFromJsonAsync <Packt.Ecommerce.Data.Models.Invoice>().ConfigureAwait(false);

            // Mapping
            var createdInvoice = this.autoMapper.Map <InvoiceDetailsViewModel>(createdInvoiceDAO);

            return(createdInvoice);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ECommerceService"/> class.
        /// </summary>
        /// <param name="httpClientFactory">The HTTP client factory.</param>
        /// <param name="applicationSettings">The application settings.</param>
        public ECommerceService(IHttpClientFactory httpClientFactory, IOptions <ApplicationSettings> applicationSettings)
        {
            NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
            IHttpClientFactory httpclientFactory = httpClientFactory;

            this.httpClient          = httpclientFactory.CreateClient();
            this.applicationSettings = applicationSettings.Value;
        }
        /// <inheritdoc/>
        public async Task <T> DeserializeEntityAsync <T>(byte[] entity, CancellationToken cancellationToken = default)
        {
            NotNullValidator.ThrowIfNull(entity, nameof(entity));

            using MemoryStream memoryStream = new MemoryStream(entity);
            var value = await JsonSerializer.DeserializeAsync <T>(memoryStream, cancellationToken : cancellationToken);

            return(value);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductsService"/> class.
        /// </summary>
        /// <param name="httpClientFactory">The HTTP Client factory.</param>
        /// <param name="applicationSettings">The application settings.</param>
        /// <param name="autoMapper">The mapper.</param>
        /// <param name="cacheService">cache service.</param>
        public ProductsService(IHttpClientFactory httpClientFactory, IOptions <ApplicationSettings> applicationSettings, IMapper autoMapper, IDistributedCacheService cacheService)
        {
            NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
            IHttpClientFactory httpclientFactory = httpClientFactory;

            this.applicationSettings = applicationSettings;
            this.httpClient          = httpclientFactory.CreateClient();
            this.autoMapper          = autoMapper;
            this.cacheService        = cacheService;
        }
        /// <inheritdoc/>
        public async Task <OrderDetailsViewModel> AddOrderAsync(OrderDetailsViewModel order)
        {
            NotNullValidator.ThrowIfNull(order, nameof(order));

            // Order entity is used for Shopping cart and at any point as there can only be one shopping cart, checking for existing shopping cart
            var getExistingOrder = await this.GetOrdersAsync($" e.UserId = '{order.UserId}' and e.OrderStatus = '{OrderStatus.Cart}' ").ConfigureAwait(false);

            OrderDetailsViewModel existingOrder = getExistingOrder.FirstOrDefault();

            if (existingOrder != null)
            {
                order.Id   = existingOrder.Id;
                order.Etag = existingOrder.Etag;
                if (order.OrderStatus == OrderStatus.Submitted.ToString())
                {
                    order.OrderPlacedDate = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
                    order.DeliveryDate    = DateTime.UtcNow.AddDays(5).ToString(CultureInfo.InvariantCulture);
                    Random trackingId = new Random();
                    order.TrackingId = trackingId.Next(int.MaxValue); // generating random tracking number
                }
                else
                {
                    order.Products.AddRange(existingOrder.Products); // For cart append products
                    order.OrderStatus = OrderStatus.Cart.ToString();
                }

                order.OrderTotal = order.Products.Sum(x => x.Price);
                await this.UpdateOrderAsync(order).ConfigureAwait(false);

                return(order);
            }
            else
            {
                order.OrderStatus      = OrderStatus.Cart.ToString();
                order.Id               = Guid.NewGuid().ToString();
                order.OrderTotal       = order.Products.Sum(x => x.Price);
                using var orderRequest = new StringContent(JsonSerializer.Serialize(order), Encoding.UTF8, ContentType);
                var orderResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.Value.DataStoreEndpoint}api/orders"), orderRequest).ConfigureAwait(false);

                if (!orderResponse.IsSuccessStatusCode)
                {
                    await this.ThrowServiceToServiceErrors(orderResponse).ConfigureAwait(false);
                }

                var createdOrderDAO = await orderResponse.Content.ReadFromJsonAsync <Packt.Ecommerce.Data.Models.Order>().ConfigureAwait(false);

                // Mapping
                var createdOrder = this.autoMapper.Map <OrderDetailsViewModel>(createdOrderDAO);
                return(createdOrder);
            }
        }
        /// <inheritdoc/>
        public async Task <OrderDetailsViewModel> CreateOrUpdateOrder(OrderDetailsViewModel order)
        {
            NotNullValidator.ThrowIfNull(order, nameof(order));
            using var orderRequest = new StringContent(JsonSerializer.Serialize(order), Encoding.UTF8, ContentType);
            var orderResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.OrdersApiEndpoint}"), orderRequest).ConfigureAwait(false);

            if (!orderResponse.IsSuccessStatusCode)
            {
                await this.ThrowServiceToServiceErrors(orderResponse).ConfigureAwait(false);
            }

            var createdOrder = await orderResponse.Content.ReadFromJsonAsync <OrderDetailsViewModel>().ConfigureAwait(false);

            return(createdOrder);
        }
        /// <inheritdoc/>
        public async Task <ProductDetailsViewModel> AddProductAsync(ProductDetailsViewModel product)
        {
            NotNullValidator.ThrowIfNull(product, nameof(product));
            product.CreatedDate      = DateTime.UtcNow;
            using var productRequest = new StringContent(JsonSerializer.Serialize(product), Encoding.UTF8, ContentType);
            var productResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.Value.DataStoreEndpoint}api/products"), productRequest).ConfigureAwait(false);

            if (!productResponse.IsSuccessStatusCode)
            {
                await this.ThrowServiceToServiceErrors(productResponse).ConfigureAwait(false);
            }

            var createdProductDAO = await productResponse.Content.ReadFromJsonAsync <Packt.Ecommerce.Data.Models.Product>().ConfigureAwait(false);

            // clearning the cache
            await this.cacheService.RemoveCacheAsync("products").ConfigureAwait(false);

            // Mapping
            var createdProduct = this.autoMapper.Map <ProductDetailsViewModel>(createdProductDAO);

            return(createdProduct);
        }