Beispiel #1
0
        public async Task <HttpResponseMessage> ReserveProduct(PostProductModel model)
        {
            Logger.Debug(nameof(this.ReserveProduct));
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            try
            {
                IStockService stockService = ConnectionFactory.CreateStockService(model.ProductId);

                // stockLeft == -1 means reserving stock failed
                int stockLeft = await stockService.PurchaseProduct(model.ProductId, model.Quantity);

                if (stockLeft == -1)
                {
                    return(this.Request.CreateResponse <string>(HttpStatusCode.NoContent, string.Format("Failure: not enough stock left={0}", stockLeft)));
                }

                return(this.Request.CreateResponse <string>(HttpStatusCode.OK, string.Format("Success: stock left={0}", stockLeft)));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, nameof(this.ReserveProduct));
                return(this.Request.CreateResponse <string>(HttpStatusCode.NoContent, ex.ToString()));
            }
        }
Beispiel #2
0
        /// <summary>
        /// IWebSocketListener.ProcessWsMessageAsync
        /// </summary>
        public async Task <byte[]> ProcessWsMessageAsync(byte[] wsrequest, CancellationToken cancellationToken)
        {
            Logger.Debug(nameof(this.ProcessWsMessageAsync));

            ProtobufWsSerializer mserializer = new ProtobufWsSerializer();

            WsRequestMessage mrequest = await mserializer.DeserializeAsync <WsRequestMessage>(wsrequest);

            switch (mrequest.Operation)
            {
            case WSOperations.AddItem:
            {
                IWsSerializer    pserializer = SerializerFactory.CreateSerializer();
                PostProductModel payload     = await pserializer.DeserializeAsync <PostProductModel>(mrequest.Value);

                await this.PurchaseProduct(payload.ProductId, payload.Quantity);
            }
            break;
            }

            WsResponseMessage mresponse = new WsResponseMessage
            {
                Result = WsResult.Success
            };

            return(await mserializer.SerializeAsync(mresponse));
        }
        public async Task <string> ExecutePostAsync(string url, PostProductModel postProductModel)
        {
            string result = "";

            try
            {
                using (StringContent theContent = new StringContent(
                           JsonConvert.SerializeObject(postProductModel),
                           System.Text.Encoding.UTF8,
                           "application/json"))
                {
                    using (HttpResponseMessage rsp = await this.httpClient.PostAsync(url, theContent))
                    {
                        result = await rsp.Content.ReadAsStringAsync();

                        if (!rsp.IsSuccessStatusCode)
                        {
                            Logger.Warning("Error={0} {1}", rsp.IsSuccessStatusCode, result);

                            throw new ApplicationException(string.Format("SendJSON Failed IsSuccessStatusCode={0}", rsp.IsSuccessStatusCode));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = result + " " + ex.ToString();
                Logger.Error(ex, nameof(PublicGatewayHttpClient));
            }

            return(result);
        }
 //[EnableCors("AllowOrigin")]
 public ActionResult <PostProductModel> PostProduct(PostProductModel product)
 {
     try
     {
         _context.Add_Product(product);
         return(product);
     }
     catch (System.Exception)
     {
         throw new System.Exception();
     }
 }
Beispiel #5
0
        public string Add_Product(PostProductModel model)
        {
            try
            {
                using (dbContext)
                {
                    if ((model.Name != null) &&
                        (model.Group != null) &&
                        (model.Price != 0))
                    {
                        var product = new Product
                        {
                            Id          = model.Id,
                            Name        = model.Name,
                            Description = model.Description,
                            Group       = model.Group,
                            SubGroup    = model.SubGroup,
                            Image       = model.Image,
                            Price       = Convert.ToDouble(model.Price.ToString()),
                            Quantity    = model.Quantity,
                            Status      = "InStock",
                            CreatedBy   = "Prince Lunga",
                            DateCreated = DateTime.Now,
                            Discount    = model.Discount,
                            Vat         = model.Vat
                        };

                        dbContext.Products.Add(product);
                        dbContext.SaveChanges();
                        return("Product Successfully Added");
                    }
                    else
                    {
                        return("Failed to Post when model is null");
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }
        }
Beispiel #6
0
        /// <summary>
        /// IWebSocketListener.ProcessWsMessageAsync 消息分发过来进行处理
        /// </summary>
        public async Task <byte[]> ProcessWsMessageAsync(byte[] wsrequest, CancellationToken cancellationToken)
        {
            Logger.Debug(nameof(this.ProcessWsMessageAsync));

            ProtobufWsSerializer mserializer = new ProtobufWsSerializer();

            WsRequestMessage mrequest = await mserializer.DeserializeAsync <WsRequestMessage>(wsrequest);

            ///事件集中在这里处理  并且可以保存状态
            switch (mrequest.Operation)
            {
            case WSOperations.AddItem:
            {
                IWsSerializer    pserializer = SerializerFactory.CreateSerializer();
                PostProductModel payload     = await pserializer.DeserializeAsync <PostProductModel>(mrequest.Value); //取值

                await this.PurchaseProduct(payload.ProductId, payload.Quantity);                                      //数据处理
            }
            break;
            }

            PostProductModel m = new PostProductModel();

            m.ProductId = 100;
            m.Quantity  = 200;
            var m1 = await mserializer.SerializeAsync(m);

            //构造返回值
            WsResponseMessage mresponse = new WsResponseMessage
            {
                Result = WsResult.Success,
                Value  = m1
            };

            return(await mserializer.SerializeAsync(mresponse));
        }
Beispiel #7
0
        public async Task <int> DoWorkAsyncHttp(int iterationsMax, int threadId, int threadCount, int maxProductsPerThread, int delayMs)
        {
            int iterations    = 0;
            int failedCounter = 0;

            try
            {
                Random rnd = new Random((threadId + 1) * DateTime.UtcNow.Millisecond);

                Stopwatch sw            = Stopwatch.StartNew();
                long      executionTime = sw.ElapsedMilliseconds;

                // Partition the Product Ids per thread
                int productListOffsetMin = (this.ProductIdsToPurchase.Count / threadCount) * threadId;
                int productListOffsetMax = (this.ProductIdsToPurchase.Count / threadCount) * (threadId + 1) - 1;
                // Use Max Products Per Thread?
                if (maxProductsPerThread > 0)
                {
                    maxProductsPerThread--;
                    if (productListOffsetMin + maxProductsPerThread < productListOffsetMax)
                    {
                        productListOffsetMax = productListOffsetMin + maxProductsPerThread;
                    }
                }
                //Console.WriteLine("{0} to {1} to {2}", threadId, productListOffsetMin, productListOffsetMax);

                int productId         = 0;
                int immediateQuantity = 0;

                while (iterations < iterationsMax)
                {
                    productId         = this.ProductIdsToPurchase[rnd.Next(productListOffsetMin, productListOffsetMax)];
                    immediateQuantity = rnd.Next(1, 4);

                    // Report status every X seconds
                    if ((sw.ElapsedMilliseconds - executionTime) > ReportStatusMs)
                    {
                        Console.WriteLine(OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations, sw.ElapsedMilliseconds));
                        executionTime = sw.ElapsedMilliseconds;
                    }

                    PostProductModel postProductModel = new PostProductModel
                    {
                        // generating new user id for every iteration
                        ProductId = productId,
                        Quantity  = immediateQuantity
                    };

                    string result = await this.client.ExecutePostAsync(ConnectionFactory.ReserveStockApiController, postProductModel);

                    if (!result.ToLower().Contains("success"))
                    {
                        failedCounter++;
                    }

                    iterations++;

                    if (delayMs > -1 && iterations < iterationsMax)
                    {
                        await Task.Delay(delayMs);
                    }
                }
                Console.WriteLine(
                    "Completed: " + OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations - 1, sw.ElapsedMilliseconds));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(iterations);
        }
Beispiel #8
0
        public async Task <int> DoWorkAsyncWebSocket(int iterationsMax, int threadId, int threadCount, int maxProductsPerThread, int delayMs)
        {
            int iterations    = 0;
            int failedCounter = 0;

            try
            {
                Random rnd = new Random((threadId + 1) * DateTime.UtcNow.Millisecond);

                Stopwatch sw            = Stopwatch.StartNew();
                long      executionTime = sw.ElapsedMilliseconds;

                // Partition the Product Ids per thread
                int productListOffsetMin = (this.ProductIdsToPurchase.Count / threadCount) * threadId;
                int productListOffsetMax = (this.ProductIdsToPurchase.Count / threadCount) * (threadId + 1) - 1;
                // Use Max Products Per Thread?
                if (maxProductsPerThread > 0)
                {
                    maxProductsPerThread--;
                    if (productListOffsetMin + maxProductsPerThread < productListOffsetMax)
                    {
                        productListOffsetMax = productListOffsetMin + maxProductsPerThread;
                    }
                }
                //Console.WriteLine("{0} to {1} to {2}", threadId, productListOffsetMin, productListOffsetMax);

                int productId         = 0;
                int immediateQuantity = 0;

                // Websocket client to public gateway
                using (PublicGatewayWebSocketClient websocketClient = new PublicGatewayWebSocketClient())
                {
                    await websocketClient.ConnectAsync(ConnectionFactory.WebSocketServerName);

                    while (iterations < iterationsMax)
                    {
                        productId         = this.ProductIdsToPurchase[rnd.Next(productListOffsetMin, productListOffsetMax)];
                        immediateQuantity = rnd.Next(1, 4);

                        // Report status every X seconds
                        if ((sw.ElapsedMilliseconds - executionTime) > ReportStatusMs)
                        {
                            Console.WriteLine(OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations, sw.ElapsedMilliseconds));
                            executionTime = sw.ElapsedMilliseconds;
                        }

                        // Serialize PostDataModel
                        PostProductModel postProductModel = new PostProductModel
                        {
                            // generating new user id for every iteration
                            ProductId = productId,
                            Quantity  = immediateQuantity
                        };

                        IWsSerializer serializer = SerializerFactory.CreateSerializer();
                        byte[]        payload    = await serializer.SerializeAsync(postProductModel);

                        // Websocket send & receive message spec
                        WsRequestMessage mreq = new WsRequestMessage
                        {
                            PartitionKey = productId,
                            Operation    = WSOperations.AddItem,
                            Value        = payload
                        };

                        WsResponseMessage mresp = await websocketClient.SendReceiveAsync(mreq, CancellationToken.None);

                        if (mresp.Result == WsResult.Error)
                        {
                            Console.WriteLine("Error: {0}", Encoding.UTF8.GetString(mresp.Value));
                        }

                        if (mresp.Result != WsResult.Success)
                        {
                            failedCounter++;
                        }

                        iterations++;

                        if (delayMs > -1 && iterations < iterationsMax)
                        {
                            await Task.Delay(delayMs);
                        }
                    }
                    Console.WriteLine(
                        "Completed: " + OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations - 1, sw.ElapsedMilliseconds));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(iterations);
        }