Пример #1
0
        public void GetInventoriesWithRequestAsync(InventoryRequest request)
        {
            if (request == null)
            {
                throw new NullReferenceException("request is null");
            }

            if (this.GetInventoriesWithRequestCompleted != null)
            {
                this.GetInventoriesWithRequestCompleted(null, new GetInventoriesWithRequestCompletedEventArgs(new object[] { GetInventoriesResult }, null, false, null));
            }
        }
        public Boolean Delete(int id)
        {
            InventoryRequest delRequest = GetById(id);

            if (delRequest == null)
            {
                return(false);
            }

            _dbContext.InventoryRequests.Remove(delRequest);
            _dbContext.SaveChanges();

            return(true);
        }
        public InventoryRequest GetById(int id)
        {
            InventoryRequest request = _dbContext.InventoryRequests.FirstOrDefault(ir => ir.Id == id);

            if (request == null)
            {
                return(null);
            }

            return(_dbContext.InventoryRequests
                   .Include(ir => ir.User)
                   .Include(ir => ir.ResourceType)
                   .FirstOrDefault(ir => ir.Id == id));
        }
Пример #4
0
        static void Main(string[] args)
        {
            InventoryRequest request = GenerateHeader();

            BuildLine(request, "00030291053409", "1");
            ImWrapper     imWrapper = new ImWrapper();
            string        message;
            XmlSerializer x = new XmlSerializer(request.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                x.Serialize(textWriter, request);
                message = textWriter.ToString();
            }
            imWrapper.Execute(message);
        }
Пример #5
0
        public async Task <Tagge.Common.Models.InventoryResponse> SaveOrUpdate(InventoryRequest request, string tableName, string internalId, Guid trackingGuid)
        {
            var response = new Tagge.Common.Models.InventoryResponse();

            if (request.Id.HasValue && request.Id.Value > 0)
            {
                // Update
                response = await Update(request, request.Id.Value, trackingGuid);
            }
            else
            {
                // Add
                response = await Save(request, tableName, internalId, trackingGuid);
            }

            return(response);
        }
Пример #6
0
        public void SendToInventory(object obj)
        {
            InventoryMessage inventoryMessage = (InventoryMessage)obj;
            InventoryRequest request          = GenerateHeader(inventoryMessage.BusinessUnit);

            BuildLine(request, inventoryMessage.ProductId, inventoryMessage.Inventoy);
            ImWrapper     imWrapper = new ImWrapper();
            string        message;
            XmlSerializer x = new XmlSerializer(request.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                x.Serialize(textWriter, request);
                message = textWriter.ToString();
            }
            imWrapper.Execute(message);
        }
        public InventoryRequest Update(InventoryRequest updatedInventoryRequest)
        {
            InventoryRequest currentRequest = _dbContext.InventoryRequests.FirstOrDefault(ir => ir.Id == updatedInventoryRequest.Id);

            if (currentRequest == null)
            {
                return(null);
            }

            _dbContext.Entry(currentRequest)
            .CurrentValues
            .SetValues(updatedInventoryRequest);

            _dbContext.InventoryRequests.Update(currentRequest);
            _dbContext.SaveChanges();

            return(currentRequest);
        }
Пример #8
0
        public async void CanUpdateInventoryItemEmptied()
        {
            await _task.AddInventory();

            var items = await _task.GetInventory();

            var item = items.InventoryItems[0];

            item.Empty = true;
            var request = new InventoryRequest();

            request.items = new List <InventoryItem>();
            request.items.Add(item);
            await _task.UpdateInventory(request);

            var itemsAgain = await _task.GetInventory();

            Assert.NotNull(itemsAgain);
            Assert.False(itemsAgain.success);
        }
Пример #9
0
        public async Task <Inventory> addToInventoryAsync(InventoryRequest request)
        {
            using (SqlConnection db = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
            {
                await db.OpenAsync();

                string sql          = "exec [AddToInventory] @ProductId,@Quantity,@PurchasePrice,@PurchaseDate";
                int    rowsModified = await db.ExecuteAsync(sql, request);

                if (rowsModified > 0)
                {
                    string    getInv = "SELECT * FROM Inventory WHERE Id = (SELECT MAX(Id) FROM Inventory)";
                    Inventory inv    = (await db.QueryAsync <Inventory>(getInv)).FirstOrDefault();
                    return(inv);
                }
                else
                {
                    return(null);
                }
            }
        }
 public static InventoryRequestApiModel ToApiModel(this InventoryRequest request)
 {
     return(new InventoryRequestApiModel
     {
         Id = request.Id,
         UserId = request.UserId,
         User = request.User != null
             ? request.User.FullName
             : null,
         companyId = request.CompanyId,
         Company = request.Company != null
             ? request.Company.Name
             : null,
         ResourceTypeId = request.ResourceTypeId,
         ResourceType = request.ResourceType != null
             ? request.ResourceType.Name
             : null,
         Date = request.Date,
         Details = request.Details,
         Complete = request.Complete
     });
 }
Пример #11
0
        public ActionResult CancelRequest(string code)
        {
            // use the "key" ... "WH-location", entry & Qty are irrelevant as the "key" governs what has happend
            // all are overlooked even if entered

            List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items"
            InventoryRequestItem        requestItem  = new InventoryRequestItem();

            // calls for some logic
            requestItem.RequestType  = InventoryRequestType.Cancel; //
            requestItem.OperationKey = TempData["key"] as string;

            requestItems.Add(requestItem);

            InventoryRequest  inventoryRequest  = new InventoryRequest(DateTime.UtcNow, requestItems, null);
            InventoryResponse inventoryResponse = inventoryService.Service.Request(inventoryRequest);

            return(RedirectToAction("Index", "Variation"));

            // Check the "Complete-method"
            // ...no time-limited reservation (allthough it´s a custom implementation of "the provider")
            // ......could do a work-around with a timer counting down... and then cancel in code
        }
Пример #12
0
        public ActionResult SimulatePurchase(InventoryDemoViewModel viewModel)
        {
            var request = new InventoryRequest()
            {
                RequestDateUtc = DateTime.UtcNow,
                Items          = new[]
                {
                    new InventoryRequestItem
                    {
                        RequestType      = InventoryRequestType.Purchase,
                        CatalogEntryCode = "Long Sleeve Shirt White Small_1",
                        WarehouseCode    = viewModel.SelectedWarehouseCode,
                        Quantity         = viewModel.PurchaseQuantity,
                        ItemIndex        = 0,
                    }
                }
            };

            InventoryResponse resp = _inventoryService.Request(request);

            if (resp.IsSuccess)
            {
                viewModel.OperationKeys = new List <string>();
                foreach (var item in resp.Items)
                {
                    viewModel.OperationKeys.Add(item.OperationKey);
                }
            }
            else if (resp.Items[0].ResponseType == InventoryResponseType.NotEnough)
            {
                viewModel.MessageOutput = "Not enough inventory for the request!";
            }

            ModelFiller(viewModel);

            return(View("Index", viewModel));
        }
Пример #13
0
        public ActionResult <InventoryResponse> Inventory([FromBody] InventoryRequest request)
        {
            if (request == null)
            {
                Log(InfoMessage.ERROR_MSG_INVALID_INVENTORY_REQUEST);
                return(BadRequest(InfoMessage.ERROR_MSG_INVALID_INVENTORY_REQUEST));
            }

            if (!ModelState.IsValid)
            {
                Log(InfoMessage.ERROR_MSG_INVALID_INVENTORY_REQUEST_MODEL);
                return(BadRequest(ModelState));
            }

            var inventoryResponseEntity = _orderService.GetInventory(request);

            if (inventoryResponseEntity == null)
            {
                Log(InfoMessage.ERROR_MSG_UNABLE_TO_GET_INVENTORY_RESPONSE);
                NotFound(InfoMessage.ERROR_MSG_UNABLE_TO_GET_INVENTORY_RESPONSE);
            }

            return(Ok(inventoryResponseEntity));
        }
Пример #14
0
 public IAsyncResult BeginGetInventoriesWithRequest(InventoryRequest request, AsyncCallback callback, object asyncState)
 {
     throw new NotImplementedException();
 }
Пример #15
0
        public PageResult <InventoryResult> ProductStock(int pageSize, int pageIndex, InventoryRequest requestParams)
        {
            WarehouseManager warehouse = new WarehouseManager();
            var result = warehouse.CheckedInventory(requestParams.StoreId, requestParams.MachineSn, requestParams.CID, requestParams.DeviceSn, requestParams.CategorySns, requestParams.Keyword, requestParams.Price, pageSize, pageIndex);

            return(result);
        }
Пример #16
0
 public NewIntersightInventoryRequest()
 {
     ApiInstance = new InventoryApi(Config);
     ModelObject = new InventoryRequest();
     MethodName  = "CreateInventoryRequestWithHttpInfo";
 }
Пример #17
0
        public BaseResponse AddMagicBoxInventory(InventoryRequest inventoryRequest)
        {
            BaseResponse response = new BaseResponse();

            bool             isSuccess = true;
            string           code      = "00";
            string           message   = string.Empty;
            OracleConnection con       = null;
            OracleCommand    cmd       = null;

            try
            {
                //    using (cmd = new NpgsqlCommand("CALL  PRC_RETAILER_LOGIN_INFO_SAVE(@PRETAILERCNIC,@PRETAILERID,@PRETAILERREGION,@PFSRETAILERID,@PFUNDAMOPOS,@PEAgreementState,@PBVMT_Agent_Sent,@PBVMT_Agent_Receive,@PWIFI_FALLBACK,@PSMS_FALLBACK,@PUPSELL,@pDAP,@PIRCASHWITHDRAWL,@PIRBVSVERIFICATION,@PIRPULLFUND,@P4GUPSELLCHECK,@PDAPACCUPSELL,@PRETAILER_CREATE,@PRSO_TYPE,@PRETAILER_CREATE_TYPE,@PREPEAT_RECHARGE,@PEASY_BAZAR,@PRETAILER_REGISTRATION,@POTP,@PCOMPLIANCE_PASSWORD,@P789_SIM_REPLACEMENT,@PACCESSRIGHTS,@PCREATEDBY)", connection = new NpgsqlConnection(_Configuration.GetConnectionString("DefaultConnection")))
                // using (connection = new OracleConnection("data source=10.0.1.192:1521/demoaksa; User ID=MBPU_STG; Password=mbpu321;"))

                using (con = new OracleConnection(_connectionString))
                {
                    using (cmd = new OracleCommand("PKG_MAGICBOX_INVENTORY.PRC_MAGICBOX_INVENTORY_SAVE", con))
                    {
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pMbid", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pMb_ID
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pMbmsisdnno", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pMbmsisdnno
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pIccid", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pIccid
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pIsissued", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pIsissued
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pUnitid", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pUnitid
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pBidnings", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.pBidnings
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "pCreatedBy", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Input, Value = inventoryRequest.UserNameCreatedBy
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "PCODE", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Output, Size = 1000
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "PDESC", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Output, Size = 1000
                        });
                        cmd.Parameters.Add(new OracleParameter {
                            ParameterName = "PMSG", OracleDbType = OracleDbType.Varchar2, Direction = ParameterDirection.Output, Size = 1000
                        });
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();

                        if (Convert.ToString(cmd.Parameters["PCODE"].Value) == "00" || Convert.ToString(cmd.Parameters["PCODE"].Value) == "0")
                        {
                            response.Message = cmd.Parameters["PDESC"].Value.ToString();
                        }
                        else
                        {
                            response.Message = cmd.Parameters["PDESC"].Value.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                try
                {
                    if (con != null && con.State != ConnectionState.Closed)
                    {
                        con.Close();
                        con.Dispose();
                    }
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                }
                catch { }
            }
            return(new BaseResponse {
                Code = code, IsSuccess = isSuccess, Message = message
            });
        }
Пример #18
0
 public double GetCartTotal([FromBody] InventoryRequest inventoryRequest)
 {
     return(_inventory.GetCartTotal(inventoryRequest.items));
 }
Пример #19
0
        /// <summary>
        /// Löst den Warenausgang aus.
        /// </summary>
        /// <param name='body'>
        /// Input ist ein Order-JSON File
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> InventorypostWithHttpMessagesAsync(InventoryRequest body = default(InventoryRequest), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Inventorypost", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri.AbsoluteUri;
            var _url     = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "inventory").ToString();
            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(body, this.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (this.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 405)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #20
0
        private void mainFunction(Order order)
        {
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": POST Request received. OrderId: " + order.OrderID.Value.ToString());
            }

            //write data in DB
            MySqlConnection con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"insert into shopdb.controller(OrderID,CustomerName,CustomerAddress,CustomerEmail,ArticleId,Quantity,Price,OrderSize,OrderWeight) values('" + order.OrderID + "','" + order.CustomerName + "','" + order.CustomerAddress + "','" + order.CustomerEMail + "','" + order.ArticleID + "','" + order.Quantity + "','" + order.Price + "','" + order.OrderSize + "','" + order.OrderWeight + "');";
            MySqlCommand command = new MySqlCommand(Query, con);

            command.ExecuteReader();
            con.Close();

            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - initial Request");
            }

            //new Invoice Request
            InvoiceRequest invRequest = new InvoiceRequest(order.OrderID, order.Price, order.CustomerName, order.CustomerAddress);

            httpMachine.Invoicepost(invRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Invoice API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Invoice Request abgeschlossen ist
            InvoiceState invState = httpMachine.Invoiceget(order.OrderID.Value);

            while (!invState.PaymentState.Equals("completed"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Invoice not paid yet, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                invState = httpMachine.Invoiceget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Invoice paid");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set PaymentState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command2 = new MySqlCommand(Query, con);

            command2.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - InvoiceState");
            }

            //new Inventory Request
            InventoryRequest ivtRequest = new InventoryRequest(order.OrderID, order.ArticleID, order.Quantity);

            httpMachine.Inventorypost(ivtRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Inventory API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Inventory Request abgeschlossen ist
            InventoryState ivtState = httpMachine.Inventoryget(order.OrderID.Value);

            while (!ivtState.InventoryStateProperty.Equals("completed"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Inventory not yet commissioned, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                ivtState = httpMachine.Inventoryget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Inventory commissioned");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set InventoryState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command3 = new MySqlCommand(Query, con);

            command3.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - InventoryState");
            }

            //new Shipment Request
            ShipmentRequest shpRequest = new ShipmentRequest(order.OrderID, order.OrderSize, order.OrderWeight, order.CustomerName, order.CustomerAddress, order.CustomerEMail);

            httpMachine.Shipmentpost(shpRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Shipment API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Shipment Request abgeschlossen ist
            ShipmentState shpState = httpMachine.Shipmentget(order.OrderID.Value);

            while (!shpState.Status.Equals("Delivered"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Shipment not completed, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                shpState = httpMachine.Shipmentget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Shipment completed");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set ShipmentState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command4 = new MySqlCommand(Query, con);

            command4.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - ShipmentState");
            }

            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": _________________");
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Request completed");
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": _________________");
            }
        }
Пример #21
0
        /// <summary>
        /// Updates an existing inventory
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <param name="fromController"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.InventoryResponse> Update(InventoryRequest request, long id, Guid trackingGuid, bool fromController = false)
        {
            var response  = new Tagge.Common.Models.InventoryResponse();
            var companyId = context.Security.GetCompanyId();

            try
            {
                // MongoDB Settings
                var    database       = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar");
                string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Inventory").Name;

                // Get MongoDB
                var db = context.Database;
                var inventoryCollection = db.GetCollection <Deathstar.Data.Models.PC_Inventory>(collectionName);

                // Filter
                var filters = Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.Id, id);

                filters = filters & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true);

                filters = filters & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                // Inventory table
                string inventoryTable = string.Empty;

                // Webhook Scope
                string scope = string.Empty;

                // Word
                var dbInventory = new Deathstar.Data.Models.PC_Inventory();

                // Check to see if the Inventory exists
                var existsfilter = Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.Id, id);

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true);

                var existsInventory = inventoryCollection.Find(existsfilter).FirstOrDefault();

                if (existsInventory == null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Inventory not found by Id: {id}"
                          }
                }
                ;

                // Validate Product/Variant and set inventory table
                if (existsInventory.ST_TableName == "PC_Product")
                {
                    inventoryTable = "PC_ProductInventory";
                    scope          = "product";
                }
                else
                {
                    inventoryTable = "PC_ProductVariantInventory";
                    scope          = "product/variant";
                }

                // Verify Locations
                await LocationModel.Validate(request.LocationId, context, trackingGuid);

                // Convert to DB Object
                dbInventory.ConvertToDatabaseObject(companyId.ToString(), existsInventory.ST_TableName, request);

                // Add Updated By & Timestamp
                dbInventory.UpdatedBy       = context.Security.GetEmail();
                dbInventory.UpdatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");

                // Custom Fields
                if (request.CustomFields != null && request.CustomFields.Count > 0)
                {
                    dbInventory.CustomFields = await _customFieldModel.SaveOrUpdateGenericCustomFields(request.CustomFields, dbInventory.CustomFields, inventoryTable, id.ToString(), trackingGuid);
                }

                // Update
                var serializerSettings = new JsonSerializerSettings()
                {
                    NullValueHandling    = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore
                };

                var update = new BsonDocument()
                {
                    { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(dbInventory, serializerSettings)) }
                };

                // Update database record
                await inventoryCollection.UpdateOneAsync(filters, update);

                // Convert To Response
                response = dbInventory.ConvertToResponse();

                // Add Id
                response.Id = id;

                // Add back the Parent Id
                response.ParentId = Convert.ToInt64(existsInventory.InternalId);

                // ExternalIds
                if (request.ExternalIds != null && request.ExternalIds.Count > 0)
                {
                    response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, inventoryTable, id.ToString(), trackingGuid);
                }

                // Only send webhooks when making a direct call from the controller
                if (fromController)
                {
                    // Build the Webhook event
                    var whRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId = companyId.ToString(),
                        Type      = "Inventory",
                        Scope     = $"{scope}/inventory/updated",
                        Id        = response.Id.ToString()
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid);
                }

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                throw;
            }
            catch (Exception ex)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "InventoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);
                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Пример #22
0
 /// <summary>
 /// Create an instance of &#39;inventoryRequest&#39;
 /// </summary>
 /// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="body">inventoryRequest to add</param>
 /// <returns>Task of void</returns>
 public async System.Threading.Tasks.Task InventoryRequestsPostAsync(InventoryRequest body)
 {
     await InventoryRequestsPostAsyncWithHttpInfo(body);
 }
Пример #23
0
 public async Task <JsonResponse> UpdateInventory(InventoryRequest update)
 {
     return(await _invCtrl.Put(update));
 }
Пример #24
0
 /// <summary>
 /// Löst den Warenausgang aus.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// Input ist ein Order-JSON File
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task InventorypostAsync(this IShopStantlyGroup3 operations, InventoryRequest body = default(InventoryRequest), CancellationToken cancellationToken = default(CancellationToken))
 {
     await operations.InventorypostWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
 }
Пример #25
0
 /// <summary>
 /// Löst den Warenausgang aus.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// Input ist ein Order-JSON File
 /// </param>
 public static void Inventorypost(this IShopStantlyGroup3 operations, InventoryRequest body = default(InventoryRequest))
 {
     Task.Factory.StartNew(s => ((IShopStantlyGroup3)s).InventorypostAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        //Injected<IOrderGroupFactory> _ogf;
        public ActionResult RequestInventory(string code) // step through this
        {
            // from Fund, maybe not what we want - heve more in Tran-Scope in CheckOutController
            //IOrderGroup c = _orderRepository.Create<ICart>(""); //
            //c.AdjustInventoryOrRemoveLineItems();
            //c.UpdateInventoryOrRemoveLineItems()

            // Get the WH
            string warehouseCode = "Nashua"; // a bit hard-coded
            //string warehouseCode = "Stocholm"; // a bit hard-coded here too

            // somewhat hard-coded...  no "Loader" though
            // could of course get info from the Market--> Country --> City etc.
            string warehouseCode2 = _warehouseRepository.List()
                                    .Where(w => w.ContactInformation.City == "Nashua")
                                    .First().Code;

            // can get several, should have some Geo-LookUp or alike to get the nearest WH
            IEnumerable <string> www = GetLocalMarketWarehouses();

            // Get the actual record in focus
            InventoryRecord inventoryRecord = _inventoryService.Get(code, warehouseCode);

            // could have some decisions made by the following props... just havinga look here
            decimal available          = inventoryRecord.PurchaseAvailableQuantity;
            decimal requested          = inventoryRecord.PurchaseRequestedQuantity;
            decimal backOrderAvailable = inventoryRecord.BackorderAvailableQuantity;
            decimal backOrderRequested = inventoryRecord.BackorderRequestedQuantity;

            List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items"
            InventoryRequestItem        requestItem  = new InventoryRequestItem();        // The one we use now

            requestItem.CatalogEntryCode = code;
            requestItem.Quantity         = 3M;
            requestItem.WarehouseCode    = warehouseCode;
            // ...no time-out ootb --> custom coding... like for consert tickets

            // calls for some logic
            requestItem.RequestType = InventoryRequestType.Purchase; // reserve for now

            requestItems.Add(requestItem);

            InventoryRequest inventoryRequest =
                new InventoryRequest(DateTime.UtcNow, requestItems, null);
            InventoryResponse inventoryResponse = _inventoryService.Request(inventoryRequest);

            // pseudo-code for the "key" below
            //requestItem.OperationKey = requestItem.WarehouseCode + requestItem.CatalogEntryCode + requestItem.Quantity.ToString();

            if (inventoryResponse.IsSuccess)
            {
                TempData["key"] = inventoryResponse.Items[0].OperationKey; // bad place, just for demo
                // Storage is prepared in [dbo].[Shipment] ... or done "custom"
                // [OperationKeys] NVARCHAR (MAX)   NULL,
                // methods for management sits on the Shipment
                //      Serialized, InMemory and OldSchool
            }
            else
            {
                // could start to adjust Pre/Back-Order-qty
                InventoryRequestItem backOrderRequestItem = new InventoryRequestItem();
                backOrderRequestItem.CatalogEntryCode = code;
                backOrderRequestItem.Quantity         = 3M;
                backOrderRequestItem.WarehouseCode    = warehouseCode;
                backOrderRequestItem.RequestType      = InventoryRequestType.Backorder; // ...if enabled
                //Metadata below
                //backOrderRequestItem.OperationKey = backOrderRequestItem.RequestType + backOrderRequestItem.WarehouseCode + backOrderRequestItem.CatalogEntryCode + backOrderRequestItem.Quantity.ToString();

                List <InventoryRequestItem> backOrderRequestItems = new List <InventoryRequestItem>(); // holds the "items"
                backOrderRequestItems.Add(backOrderRequestItem);

                InventoryRequest backOrderRequest = new InventoryRequest(DateTime.UtcNow, backOrderRequestItems, null);

                InventoryResponse backOrderInventoryResponse =
                    _inventoryService.Request(backOrderRequest);
            }

            // dbo.InventoryService - table gets the requests and accumulate
            // inventoryService.Service.Request(requestItem);
            // and it increases in reserved until you can´t reserve more --> "Not Success"

            return(RedirectToAction("Index", "Variation"));
        }
Пример #27
0
 /// <summary>
 /// Create an instance of &#39;inventoryRequest&#39;
 /// </summary>
 /// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="body">inventoryRequest to add</param>
 /// <returns></returns>
 public void InventoryRequestsPost(InventoryRequest body)
 {
     InventoryRequestsPostWithHttpInfo(body);
 }
Пример #28
0
 public ActionResult <string> Get([FromQuery] InventoryRequest request)
 {
     return(Ok("Hello world"));
 }
Пример #29
0
        public List<StoreWithInventory> GetInventoriesWithRequest(InventoryRequest request)
        {
            List<StoreWithInventory> result = new List<StoreWithInventory>();
            // The result dictionary - key is the store ID, value is the store
            Dictionary<int, StoreWithInventory> resultStores = new Dictionary<int, StoreWithInventory>();

            using (traceManager.StartTrace("General"))
            {
                var userEntity = this.GetUserEntity();
                var productsToFind = request.GetProductIdsToFind(userEntity);

                // Get the results from the LCBO website
                List<LcboInventoryData2> lcboInventory = this.lcboService.RetrieveMatches(productsToFind);

                // Detect new and changed stores
                this.DetectNewAndChangedStores(lcboService, lcboInventory);

                // Get the store Ids
                var storeids = request.GetStoreNumbersToFind(this.domainContext, userEntity);

                //TODO: filter by store/product selection

                Dictionary<int, ProductListItem> productDictionary = new Dictionary<int, ProductListItem>();

                // The LCBO results filtered by the stores in the request
                var lcboInventoriesFiltered = from l in lcboInventory where storeids.Contains(l.StoreNumber) select l;

                foreach (var lcboInventoryItem in lcboInventoriesFiltered)
                {
                    StoreWithInventory currentStoreWithInventory;
                    if (resultStores.ContainsKey(lcboInventoryItem.StoreNumber))
                    {
                        // The current store is in the result dictionary, so set currentStore to it.
                        currentStoreWithInventory = resultStores[lcboInventoryItem.StoreNumber];
                    }
                    else
                    {
                        // The current store is not in the result dictionary.
                        // Set currentStore to be a new store
                        var Store = this.domainContext.Stores.Single(s => s.Id == lcboInventoryItem.StoreNumber);
                        var store = new InvStore()
                        {
                            Address = Store.Address,
                            City = Store.City,
                            Hours = Store.Hours,
                            Latitude = Store.Latitude,
                            Longitude = Store.Longitude,
                            StoreNumber = Store.Id
                        };

                        currentStoreWithInventory = new StoreWithInventory() { Store = store };
                        resultStores.Add(lcboInventoryItem.StoreNumber, currentStoreWithInventory);
                    }

                    // Inventory.CreateInventory(lcboInventoryItem.StoreNumber, lcboInventoryItem.ProductId);
                    // Set its level to that of the lcbo result value
                    ProductListItem productsVm = null;
                    if (productDictionary.ContainsKey(lcboInventoryItem.ProductId))
                    {
                        // Current product ID is in the dictionary, so set currentProduct to it
                        productsVm = productDictionary[lcboInventoryItem.ProductId];
                    }
                    else
                    {
                        // Current product ID is not in the dictionary
                        var product = this.domainContext.Products.Where(p => p.Id == lcboInventoryItem.ProductId).Include("Substance").Include("Container").First();
                        productsVm = new ProductListItem() { Name = product.Name };
                        productDictionary.Add(lcboInventoryItem.ProductId, productsVm);
                    }

                    // Create an inventory item
                    InventoryInfo currentInventory = new InventoryInfo
                    {
                        NumberInStock = lcboInventoryItem.NumberInStock,
                        Product = productsVm
                    };

                    // Set the current inventory's product to a new product based on the current product
                    // Attach the inventory item to the current store.  So we have Store.Inventory.Product and Store.Inventory.InventoryLevel.
                    currentStoreWithInventory.Inventory.Add(currentInventory);
                }

            }

            result = new List<StoreWithInventory>(resultStores.Values);

            return result;
        }
Пример #30
0
        public ActionResult RequestInventory(string code) // step through this
        {
            string warehouseCode = "Stockholm";           // a bit hard-coded
            //string warehouseCode = "Nashua"; // a bit hard-coded

            InventoryRecord inventoryRecord    = inventoryService.Service.Get(code, warehouseCode);
            decimal         available          = inventoryRecord.PurchaseAvailableQuantity;
            decimal         requested          = inventoryRecord.PurchaseRequestedQuantity;
            decimal         backOrderAvailable = inventoryRecord.BackorderAvailableQuantity;
            decimal         backOrderRequested = inventoryRecord.BackorderRequestedQuantity;

            List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items"
            InventoryRequestItem        requestItem  = new InventoryRequestItem();

            requestItem.CatalogEntryCode = code;
            requestItem.Quantity         = 3M;
            // ...no time-out --> custom

            // calls for some logic
            requestItem.WarehouseCode = warehouseCode;
            requestItem.RequestType   = InventoryRequestType.Purchase; // reserve for now

            // pseudo-code below
            //requestItem.OperationKey = requestItem.WarehouseCode + requestItem.CatalogEntryCode + requestItem.Quantity.ToString();

            requestItems.Add(requestItem);

            InventoryRequest  inventoryRequest  = new InventoryRequest(DateTime.UtcNow, requestItems, null);
            InventoryResponse inventoryResponse = inventoryService.Service.Request(inventoryRequest);

            if (inventoryResponse.IsSuccess)
            {
                TempData["key"] = inventoryResponse.Items[0].OperationKey; // bad place, just for demo
                // Storage in [dbo].[Shipment]  or "custom"
                // [OperationKeys] NVARCHAR (MAX)   NULL,
            }
            else
            {
                // could start to adjust Pre/Back-Order-qty
                InventoryRequestItem backOrderRequestItem = new InventoryRequestItem();
                backOrderRequestItem.CatalogEntryCode = code;
                backOrderRequestItem.Quantity         = 3M;
                backOrderRequestItem.WarehouseCode    = warehouseCode;
                backOrderRequestItem.RequestType      = InventoryRequestType.Backorder; // ...if enabled
                backOrderRequestItem.OperationKey     = backOrderRequestItem.RequestType + backOrderRequestItem.WarehouseCode + backOrderRequestItem.CatalogEntryCode + backOrderRequestItem.Quantity.ToString();

                List <InventoryRequestItem> backOrderRequestItems = new List <InventoryRequestItem>(); // holds the "items"
                backOrderRequestItems.Add(backOrderRequestItem);

                InventoryRequest backOrderRequest = new InventoryRequest(DateTime.UtcNow, backOrderRequestItems, null);

                InventoryResponse backOrderInventoryResponse =
                    inventoryService.Service.Request(backOrderRequest); //
            }

            // ...gets
            //dbo.InventoryService - table gets the requests and accumulate

            //inventoryService.Service.Request(requestItem);
            // request it...
            // and it increases in reserved until you can´t reserve more --> "!Success"
            // ...and decreases available

            return(RedirectToAction("Index", "Variation"));
        }
Пример #31
0
 public List<StoreWithInventory> GetInventoriesWithRequest(InventoryRequest request)
 {
     return this.InventoryController.GetInventoriesWithRequest(request);
 }
Пример #32
0
        /// <summary>
        /// Save a new inventory
        /// </summary>
        /// <param name="request"></param>
        /// <param name="tableName"></param>
        /// <param name="internalId"></param>
        /// <param name="trackingGuid"></param>
        /// <param name="context"></param>
        /// <param name="fromController"></param>
        /// <returns></returns>
        public async Task <Tagge.Common.Models.InventoryResponse> Save(InventoryRequest request, string tableName, string internalId, Guid trackingGuid, bool fromController = false)
        {
            var  response  = new Tagge.Common.Models.InventoryResponse();
            var  companyId = context.Security.GetCompanyId();
            long id        = 0;

            try
            {
                // MongoDB Settings
                var    database       = context.MongoDbSettings.Value.Databases.FirstOrDefault(x => x.Name == "DeathStar");
                string collectionName = database.Collections.FirstOrDefault(x => x.Name == "PC_Inventory").Name;

                // Get MongoDB
                var db = context.Database;
                var inventoryCollection = db.GetCollection <Deathstar.Data.Models.PC_Inventory>(collectionName);
                var counterCollection   = db.GetCollection <Deathstar.Data.Models.Counter>("Counters");

                // Inventory table
                string inventoryTable = string.Empty;

                // Webhook Scope
                string scope = string.Empty;

                // Verify Locations
                await LocationModel.Validate(request.LocationId, context, trackingGuid);

                // Validate Product/Variant and set inventory table
                if (tableName == "PC_Product")
                {
                    await ProductModel.ValidateById(internalId, context, trackingGuid);

                    inventoryTable = "PC_ProductInventory";
                    scope          = "product";
                }
                else
                {
                    await VariantModel.ValidateById(internalId, context, trackingGuid);

                    inventoryTable = "PC_ProductVariantInventory";
                    scope          = "product/variant";
                }

                // Check to see if the Inventory exists
                var existsfilter = Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.DV_CompanyId, companyId.ToString());

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.InternalId, internalId); // Product/Variant Id

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.PC_LocationId, request.LocationId);

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.ST_TableName, inventoryTable);

                existsfilter = existsfilter & Builders <Deathstar.Data.Models.PC_Inventory> .Filter.Eq(x => x.IsActive, true);

                var dbExistingInventory = inventoryCollection.Find(existsfilter).FirstOrDefault();

                if (dbExistingInventory != null)
                {
                    throw new HttpResponseException()
                          {
                              StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound, ReasonPhrase = $"Inventory record already exists. Use PUT to update the inventory. (Id = {dbExistingInventory.Id})!"
                          }
                }
                ;

                // Word
                var dbInventory = new Deathstar.Data.Models.PC_Inventory();

                // Save Inventory
                // filter
                var filter = Builders <Deathstar.Data.Models.Counter> .Filter.Eq(x => x.Id, "inventory_id");

                var update = Builders <Deathstar.Data.Models.Counter> .Update.Inc("Seq", 1);

                // Get Id
                id = counterCollection.FindOneAndUpdate(filter, update).Seq;

                // Convert request to Inventory
                dbInventory.ConvertToDatabaseObject(companyId.ToString(), tableName, request);

                // Custom Fields
                if (request.CustomFields != null && request.CustomFields.Count > 0)
                {
                    dbInventory.CustomFields = await _customFieldModel.SaveGenericCustomField(request.CustomFields, inventoryTable, id.ToString(), trackingGuid);
                }

                // Add Id
                dbInventory.Id = id;

                // Add Product/Variant Id
                dbInventory.InternalId = internalId;

                // Add Created By & Timestamp
                dbInventory.CreatedBy       = context.Security.GetEmail();
                dbInventory.CreatedDateTime = DateTimeOffset.Now.ToString("yyyy/MM/dd HH:mm:ss.fff zzz");
                dbInventory.IsActive        = true;

                // Insert
                await inventoryCollection.InsertOneAsync(dbInventory);

                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory (id: {dbInventory.Id}) successfully saved.", "Save Inventory", LT319.Common.Utilities.Constants.TrackingStatus.Complete, context, trackingGuid);

                // Building the Response
                response = dbInventory.ConvertToResponse();

                // ExternalIds
                if (request.ExternalIds != null && request.ExternalIds.Count > 0)
                {
                    response.ExternalIds = await _externalIdModel.SaveOrUpdateGenericExternalId(request.ExternalIds, inventoryTable, id.ToString(), trackingGuid);
                }

                // Build the Webhook event
                if (fromController)
                {
                    var whRequest = new Sheev.Common.Models.WebhookResponse()
                    {
                        CompanyId = companyId.ToString(),
                        Type      = "Inventory",
                        Scope     = $"{scope}/inventory/created",
                        Id        = response.Id.ToString()
                    };

                    // Trigger the Webhook event
                    await _webHookModel.FireWebhookEvent(whRequest, context, trackingGuid);
                }

                return(response);
            }
            catch (HttpResponseException webEx)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Inventory failed to save! Reason: {webEx.ReasonPhrase}", $"Status Code: {webEx.StatusCode}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);

                // Rollback the inventory to a failure
                await RollbackInventory(id, tableName);

                throw;
            }
            catch (Exception ex)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "InventoryModel.Save()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                // Rollback the inventory due to a failure
                await RollbackInventory(id, tableName);

                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Пример #33
0
        /// <summary>
        /// Create an instance of &#39;inventoryRequest&#39;
        /// </summary>
        /// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">inventoryRequest to add</param>
        /// <returns>Task of ApiResponse</returns>
        public async System.Threading.Tasks.Task <ApiResponse <Object> > InventoryRequestsPostAsyncWithHttpInfo(InventoryRequest body)
        {
            // verify the required parameter 'body' is set
            if (body == null)
            {
                throw new ApiException(400, "Missing required parameter 'body' when calling InventoryRequestApi->InventoryRequestsPost");
            }

            var    localVarPath         = "/inventory/Requests";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new Dictionary <String, String>();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (body != null && body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("InventoryRequestsPost", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <Object>(localVarStatusCode,
                                            localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                            null));
        }