Пример #1
0
        public void TestRunInvBlock()
        {
            var b1 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore).Block;

            _blockChain.Add(b1);

            var prev = TestUtils.MakeSolvedTestBlock(_unitTestParams, _blockStore);
            var b2   = TestUtils.MakeSolvedTestBlock(_unitTestParams, prev);
            var b3   = TestUtils.MakeSolvedTestBlock(_unitTestParams, b2);

            _control.Setup(x => x.WriteMessage(It.IsAny <Message>())).Verifiable();

            var inv  = new InventoryMessage(_unitTestParams);
            var item = new InventoryItem(InventoryItem.ItemType.Block, b3.Hash);

            inv.AddItem(item);

            _control.Setup(x => x.ReadMessage()).Returns(() => b2, () => inv, ReadFinalMessage).Verifiable();

            var message = CaptureGetDataMessage();

            RunPeerAndVerify();

            var items = message.Value.Items;

            Assert.AreEqual(1, items.Count);
            Assert.AreEqual(b3.Hash, items[0].Hash);
            Assert.AreEqual(InventoryItem.ItemType.Block, items[0].Type);
        }
Пример #2
0
        public override void Run()
        {
            Trace.WriteLine("Starting processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            Client.OnMessage((receivedMessage) =>
            {
                try
                {
                    var messagebody = receivedMessage.GetBody <byte[]>();
                    // var obj = JsonConvert.DeserializeObject(Encoding.UTF8.GetString( messagebody));
                    InventoryMessage obj = JsonConvert.DeserializeObject <InventoryMessage>(Encoding.UTF8.GetString(messagebody));
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    if (obj is InventoryMessage)
                    {
                        InventoyServiceAgent inventoyServiceAgent = new InventoyServiceAgent();
                        inventoyServiceAgent.SendToInventory(obj);
                    }
                    Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
                }
                catch (Exception e)
                {
                    Trace.WriteLine(e.Message);
                    // Handle any message processing specific exceptions here
                }
            });

            CompletedEvent.WaitOne();
        }
Пример #3
0
        private Message Execute(InventoryMessage msg)
        {
            var blockChain  = _blockChainStore.GetBlockChain();
            var inventories = new List <Inventory>();

            if (msg.Inventories.Any())
            {
                foreach (var inventory in msg.Inventories)
                {
                    bool addIntoInventory = false;
                    switch (inventory.Type)
                    {
                    case InventoryTypes.MSG_TX:
                        addIntoInventory = !MemoryPool.Instance().GetTransactions().Any(t => t.Transaction.GetTxId() == inventory.Hash);
                        break;

                    case InventoryTypes.MSG_BLOCK:
                        addIntoInventory = !blockChain.ContainsBlock(inventory.Hash);
                        break;
                    }

                    if (addIntoInventory)
                    {
                        inventories.Add(new Inventory(inventory.Type, inventory.Hash));
                    }
                }
            }

            if (inventories.Any())
            {
                return(new GetDataMessage(inventories, msg.MessageHeader.Network));
            }

            return(null);
        }
Пример #4
0
        // POST: IMMessage/Create
        public void Post([FromBody] InventoryMessage value)
        {
            WebRole webRole = new WebRole();

            webRole.AddMessage(value);
            webRole.Send();
        }
Пример #5
0
        public void TestRunInvTickle()
        {
            var b1 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore).Block;

            _blockChain.Add(b1);

            var prev  = TestUtils.MakeSolvedTestBlock(_unitTestParams, _blockStore);
            var block = TestUtils.MakeSolvedTestBlock(_unitTestParams, prev);

            var inv  = new InventoryMessage(_unitTestParams);
            var item = new InventoryItem(InventoryItem.ItemType.Block, block.Hash);

            inv.AddItem(item);

            _control.Setup(x => x.ReadMessage()).Returns(() => block, () => inv, ReadFinalMessage).Verifiable();

            var message = CaptureGetBlocksMessage();

            RunPeerAndVerify();

            var expectedLocator = new List <Sha256Hash>();

            expectedLocator.Add(b1.Hash);
            expectedLocator.Add(_unitTestParams.GenesisBlock.Hash);

            Assert.AreEqual(message.Value.Locator, expectedLocator);
            Assert.AreEqual(message.Value.StopHash, block.Hash);
        }
 protected virtual void HandleInventoryMessage(InventoryMessage Message)
 {
     foreach (ObjectBase obj in Message.InventoryObjects)
     {
         obj.ResolveResources(resourceManager, false);
         obj.DecompressResources();
     }
 }
Пример #7
0
        public async Task <bool> CompleteCart(string sessionId)
        {
            _logger.LogInformation($"CompleteCart: Beginning complete cart action for {sessionId}.");
            var serviceBusConfig = _config.GetSection("ServiceBusConfiguration").Get <ServiceBusConfiguration>();

            ConnectionFactory connectionFactory = new ConnectionFactory
            {
                HostName = serviceBusConfig.HostName,
                UserName = serviceBusConfig.UserName,
                Password = serviceBusConfig.Password
            };

            var cartItems = await GetItemsInCart(sessionId);

            foreach (var cartItem in cartItems)
            {
                InventoryMessage inventoryMessage = new InventoryMessage
                {
                    CarId           = cartItem.CarId,
                    StockAdjustment = cartItem.Count
                };

                using (var connection = connectionFactory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: "cmd-inventory",
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        var body = JsonSerializer.SerializeToUtf8Bytes(inventoryMessage);

                        try
                        {
                            channel.BasicPublish(exchange: "",
                                                 routingKey: "cmd-inventory",
                                                 basicProperties: null,
                                                 body: body);
                        }
                        catch (RabbitMQClientException ex)
                        {
                            _logger.LogError($"CompleteCart: RabbitMQ error: {ex.Message}");
                            return(false);
                        }

                        _logger.LogInformation($"CompleteCart: Sent message to cmd-inventory to adjust stock for {inventoryMessage.CarId} by {inventoryMessage.StockAdjustment}");
                    }

                _logger.LogInformation($"CompleteCart: Removing {inventoryMessage.CarId} from cart {cartItem.SessionId}");
                await DeleteFromCart(cartItem.SessionId, cartItem.CarId);
            }

            return(true);
        }
Пример #8
0
        protected virtual void HandleInventoryMessage(InventoryMessage Message)
        {
            double tick = GameTick.GetUpdatedTick();

            foreach (ObjectBase obj in Message.InventoryObjects)
            {
                obj.ResolveResources(resourceManager, false);
                obj.DecompressResources();
            }

            double span = GameTick.GetUpdatedTick() - tick;

            Logger.Log(MODULENAME, LogType.Info, "Loaded BP_INVENTORY: " + span.ToString() + " ms");
        }
Пример #9
0
        private void Launch(PeerConnector peerConnector, InventoryMessage message)
        {
            var payload  = peerConnector.Execute(message.Serialize()); // S : INVENTORY.
            var response = _messageParser.Parse(payload.ToArray());

            if (response.GetCommandName() == Constants.MessageNames.GetData) // R : GETDATA.
            {
                var inventories = Execute(response as GetDataMessage);
                foreach (var inventory in inventories)
                {
                    peerConnector.Execute(inventory.Serialize()); // S : TX & B.
                }
            }
        }
        public void Broadcast(BaseTransaction transaction, IEnumerable <byte> excludedIp = null)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            var inventory        = new Inventory(InventoryTypes.MSG_TX, transaction.GetTxId());
            var inventoryMessage = new InventoryMessage(new[] { inventory }, _network);

            foreach (var activePeer in _peers.Where(p => excludedIp != null && !p.GetCurrentIpAddress().Ipv6.SequenceEqual(excludedIp)))
            {
                activePeer.Execute(inventoryMessage.Serialize());
            }
        }
Пример #11
0
        private bool Check(PeerConnection peer, InventoryMessage message)
        {
            InventoryType type = message.InventoryType;
            int           size = message.GetHashList().Count;

            if (peer.IsNeedSyncFromPeer || peer.IsNeedSyncUs)
            {
                Logger.Warning(
                    string.Format("Drop inv: {0} size: {1} from Peer {2}, syncFromUs: {3}, syncFromPeer: {4}.",
                                  type,
                                  size,
                                  peer.Address.ToString(),
                                  peer.IsNeedSyncUs,
                                  peer.IsNeedSyncFromPeer));

                return(false);
            }

            if (type == InventoryType.Trx)
            {
                int count = peer.NodeStatistics.MessageStatistics.MineralInTrxInventory.GetCount(10);
                if (count > max_count)
                {
                    Logger.Warning(
                        string.Format("Drop inv: {0} size: {1} from Peer {2}, Inv count: {3} is overload.",
                                      type,
                                      size,
                                      peer.Address,
                                      count));

                    return(false);
                }

                if (Manager.Instance.TransactionHandler.IsBusy)
                {
                    Logger.Warning(
                        string.Format("Drop inv: {0} size: {1} from Peer {2}, transactionsMsgHandler is busy.",
                                      type,
                                      size,
                                      peer.Address));

                    return(false);
                }
            }

            return(true);
        }
Пример #12
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);
        }
Пример #13
0
        public void ProcessMessage(PeerConnection peer, MineralMessage message)
        {
            InventoryMessage inventory_message = (InventoryMessage)message;
            InventoryType    type = inventory_message.InventoryType;

            if (!Check(peer, inventory_message))
            {
                return;
            }

            foreach (SHA256Hash id in inventory_message.GetHashList())
            {
                Item item = new Item(id, type);
                peer.AddInventoryReceive(item, Helper.CurrentTimeMillis());
                Manager.Instance.AdvanceService.AddInventory(item);
            }
        }
Пример #14
0
        private void AddTcpMessage(Message message, bool flag)
        {
            if (flag)
            {
                MineralInMessage.Add();
            }
            else
            {
                MineralOutMessage.Add();
            }

            switch (message.Type)
            {
            case MessageTypes.MsgType.P2P_HELLO:
                if (flag)
                {
                    P2pInHello.Add();
                }
                else
                {
                    P2pOutHello.Add();
                }
                break;

            case MessageTypes.MsgType.P2P_PING:
                if (flag)
                {
                    P2pInPing.Add();
                }
                else
                {
                    P2pOutPing.Add();
                }
                break;

            case MessageTypes.MsgType.P2P_PONG:
                if (flag)
                {
                    P2pInPong.Add();
                }
                else
                {
                    P2pOutPong.Add();
                }
                break;

            case MessageTypes.MsgType.P2P_DISCONNECT:
                if (flag)
                {
                    P2pInDisconnect.Add();
                }
                else
                {
                    P2pOutDisconnect.Add();
                }
                break;

            case MessageTypes.MsgType.SYNC_BLOCK_CHAIN:
                if (flag)
                {
                    MineralInSyncBlockChain.Add();
                }
                else
                {
                    MineralOutSyncBlockChain.Add();
                }
                break;

            case MessageTypes.MsgType.BLOCK_CHAIN_INVENTORY:
                if (flag)
                {
                    MineralInBlockChainInventory.Add();
                }
                else
                {
                    MineralOutBlockChainInventory.Add();
                }
                break;

            case MessageTypes.MsgType.INVENTORY:
                InventoryMessage inventory_message = (InventoryMessage)message;
                int inventory_count = inventory_message.Inventory.Ids.Count;
                if (flag)
                {
                    if (inventory_message.InventoryMessageType == MessageTypes.MsgType.TX)
                    {
                        MineralInTrxInventory.Add();
                        MineralInTrxInventoryElement.Add(inventory_count);
                    }
                    else
                    {
                        MineralInBlockInventory.Add();
                        MineralInBlockInventoryElement.Add(inventory_count);
                    }
                }
                else
                {
                    if (inventory_message.InventoryMessageType == MessageTypes.MsgType.TX)
                    {
                        MineralOutTrxInventory.Add();
                        MineralOutTrxInventoryElement.Add(inventory_count);
                    }
                    else
                    {
                        MineralOutBlockInventory.Add();
                        MineralOutBlockInventoryElement.Add(inventory_count);
                    }
                }
                break;

            case MessageTypes.MsgType.FETCH_INV_DATA:
                FetchInventoryDataMessage fetch_inventory_message = (FetchInventoryDataMessage)message;
                int fetch_count = fetch_inventory_message.Inventory.Ids.Count;
                if (flag)
                {
                    if (fetch_inventory_message.InventoryMessageType == MessageTypes.MsgType.TX)
                    {
                        MineralInTrxFetchInvData.Add();
                        MineralInTrxFetchInvDataElement.Add(fetch_count);
                    }
                    else
                    {
                        MineralInBlockFetchInvData.Add();
                        MineralInBlockFetchInvDataElement.Add(fetch_count);
                    }
                }
                else
                {
                    if (fetch_inventory_message.InventoryMessageType == MessageTypes.MsgType.TX)
                    {
                        MineralOutTrxFetchInvData.Add();
                        MineralOutTrxFetchInvDataElement.Add(fetch_count);
                    }
                    else
                    {
                        MineralOutBlockFetchInvData.Add();
                        MineralOutBlockFetchInvDataElement.Add(fetch_count);
                    }
                }
                break;

            case MessageTypes.MsgType.TXS:
                TransactionsMessage transactionsMessage = (TransactionsMessage)message;
                if (flag)
                {
                    MineralInTrxs.Add();
                    MineralInTrx.Add(transactionsMessage.Transactions.Transactions_.Count);
                }
                else
                {
                    MineralOutTrxs.Add();
                    MineralOutTrx.Add(transactionsMessage.Transactions.Transactions_.Count);
                }
                break;

            case MessageTypes.MsgType.TX:
                if (flag)
                {
                    MineralInMessage.Add();
                }
                else
                {
                    MineralOutMessage.Add();
                }
                break;

            case MessageTypes.MsgType.BLOCK:
                if (flag)
                {
                    MineralInBlock.Add();
                }
                MineralOutBlock.Add();
                break;

            default:
                break;
            }
        }
Пример #15
0
        public Message Parse(byte[] payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (payload.Length < 24)
            {
                throw new ParseMessageException(ErrorCodes.InvalidCommandLength);
            }

            var header             = payload.Take(40); // Extract the header.
            var startStringPayload = header.Take(4);
            var network            = Networks.MainNet;

            if (startStringPayload.SequenceEqual(new byte[] { 0xf9, 0xbe, 0xb4, 0xd9 }))
            {
                network = Networks.MainNet;
            }
            else if (startStringPayload.SequenceEqual(new byte[] { 0x0b, 0x11, 0x09, 0x07 }))
            {
                network = Networks.TestNet;
            }
            else if (startStringPayload.SequenceEqual(new byte[] { 0xfa, 0xbf, 0xb5, 0xda }))
            {
                network = Networks.RegTest;
            }
            else
            {
                throw new ParseMessageException(ErrorCodes.InvalidStartString);
            }

            var commandNamePayload = header.Skip(4).Take(12).Where(b => b != 0x00).ToArray();
            var commandName        = System.Text.Encoding.ASCII.GetString(commandNamePayload);
            var ipv6 = header.Skip(16).Take(16);
            var payloadSizePayload = header.Skip(32).Take(4).ToArray();
            var payloadSize        = BitConverter.ToInt32(payloadSizePayload, 0);
            var checkSum           = header.Skip(36).Take(4);

            byte[] contentPayload = null;
            if (payloadSize > 0)
            {
                contentPayload = payload.Skip(40).Take(payloadSize).ToArray();
                SHA256 mySHA256    = SHA256.Create();
                var    newCheckSum = mySHA256.ComputeHash(mySHA256.ComputeHash(contentPayload)).Take(4);
                if (!newCheckSum.SequenceEqual(checkSum))
                {
                    throw new ParseMessageException(ErrorCodes.InvalidChecksum);
                }
            }
            else if (!checkSum.SequenceEqual(new byte[] { 0x5d, 0xf6, 0xe0, 0xe2 }))
            {
                throw new ParseMessageException(ErrorCodes.InvalidChecksum);
            }

            if (!Constants.MessageNameLst.Contains(commandName))
            {
                throw new ParseMessageException(ErrorCodes.InvalidCommandName);
            }

            Message message = null;

            if (commandName == Constants.MessageNames.Ping)
            {
                var nonce = BitConverter.ToUInt64(contentPayload, 0);
                message = new PingMessage(nonce, network);
            }
            else if (commandName == Constants.MessageNames.Addr)
            {
                message = AddrMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Version)
            {
                message = VersionMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Verack)
            {
                message = new VerackMessage(network);
            }
            else if (commandName == Constants.MessageNames.GetAddr)
            {
                message = new GetAddressMessage(network);
            }
            else if (commandName == Constants.MessageNames.Inventory)
            {
                message = InventoryMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Transaction)
            {
                message = TransactionMessage.Deserialize(contentPayload, network, Transactions.TransactionTypes.NoneCoinbase);
            }
            else if (commandName == Constants.MessageNames.Pong)
            {
                var nonce = BitConverter.ToUInt64(contentPayload, 0);
                message = new PongMessage(nonce, network);
            }
            else if (commandName == Constants.MessageNames.MemPool)
            {
                message = new MemPoolMessage(network);
            }
            else if (commandName == Constants.MessageNames.GetData)
            {
                message = GetDataMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Block)
            {
                message = BlockMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.GetBlocks)
            {
                message = GetBlocksMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.NotFound)
            {
                message = NotFoundMessage.Deserialize(contentPayload, network);
            }

            message.MessageHeader.Ipv6 = ipv6.ToArray();
            return(message);
        }
        public static InventoryMessage ToEdgeInventoryExportMessage(this Product product, string providerCode,
                                                                    string xrefMerchantId, IList <LocationInventory> locations)
        {
            var message = new InventoryMessage();

            var head = new MessageHead
            {
                Sender      = new MessageHeadSender[1],
                Recipient   = new MessageHeadRecipient[1],
                Messageid   = Guid.NewGuid().ToString(),
                Messagetype = "Inventoryimport",
                Date        = DateTime.Now.ToString(CultureInfo.InvariantCulture)
            };
            var sender = new MessageHeadSender {
                Systemid = providerCode
            };

            head.Sender[0] = sender;

            var recipient = new MessageHeadRecipient {
                Companyid = xrefMerchantId
            };

            head.Recipient[0] = recipient;
            message.Items     = new object[2];
            message.Items[0]  = head;

            var status         = StatusCode.Active;
            var prodInCatatlog = product.ProductInCatalogs.FirstOrDefault();

            if (prodInCatatlog != null)
            {
                status = prodInCatatlog.IsActive.GetValueOrDefault() ? StatusCode.Active : StatusCode.Inactive;
            }

            var body = new InventoryMessageBody {
                Inventoryimport = new MessageBodyInventoryimport[1]
            };

            var inventoryImport = new MessageBodyInventoryimport
            {
                Sku                                                                    = product.ProductCode,
                Description                                                            = product.Content.ProductName,
                Skutypecode                                                            = "Standard",
                Manufacturername                                                       = product.GetPropertyStringLabel(AttributeConstants.Brand) ?? String.Empty,
                Uomname                                                                = product.GetPropertyStringLabel(AttributeConstants.UnitOfMeasure) ?? String.Empty,
                Manufacturerpartno                                                     = product.SupplierInfo.MfgPartNumber ?? String.Empty,//TODO:Check the actual mapping
                Width                                                                  = product.PackageWidth != null?Convert.ToString(product.PackageWidth.Value) : "0.1",
                                                      Cost                             = product.SupplierInfo.Cost.Cost.ToString(),
                                                      Reorderpoint                     = String.Empty,
                                                      Maxbuildqty                      = String.Empty,
                                                      Qtyperpackage                    = String.Empty,
                                                      Leadtime                         = String.Empty,
                                                      Allowbackorder                   = product.InventoryInfo.OutOfStockBehavior == "AllowBackOrder" ? "1" : "0",
                                                      Statuscode                       = Enum.GetName(typeof(StatusCode), status),
                                                      Statusdate                       = String.Empty,
                                                      Custodianusername                = "******",
                                                      Parentsku                        = String.Empty,
                                                      Inventory                        = "1",
                                                      Returnable                       = "1",
                                                      Refundable                       = "1",
                                                      Restockable                      = "1",
                                                      Obsolete                         = "0",
                                                      Weight                           = product.PackageWeight != null?Convert.ToString(product.PackageWeight.Value) : "0.1",
                                                                                Length = product.PackageLength != null?Convert.ToString(product.PackageLength.Value) : "0.1",
                                                                                             Height = product.PackageHeight != null?Convert.ToString(product.PackageHeight.Value) : "0.1",
                                                                                                          Lwhunit          = String.Empty,
                                                                                                          Upcnumber        = product.Upc ?? String.Empty,//TODO:Check what should be the value if null
                                                                                                          Trademarkname    = String.Empty,
                                                                                                          Legacynumber     = String.Empty,
                                                                                                          Hazardclass      = product.GetPropertyBooleanValue(AttributeConstants.Hazardous) ? "1" : "0",
                                                                                                          Packaginggroup   = String.Empty,
                                                                                                          Colorname        = String.Empty,
                                                                                                          Sizename         = String.Empty,
                                                                                                          Stylename        = String.Empty,
                                                                                                          InventoryNotes   = String.Empty,
                                                                                                          Skuplacementcode = String.Empty,
                                                                                                          Forecasteddate   = String.Empty,
                                                                                                          Reorderrulecode  = String.Empty,
                                                                                                          Reorderqty       = String.Empty,
                                                                                                          Avgdailyusage    = String.Empty,
                                                                                                          Secureshipment   = String.Empty,
                                                                                                          Graceperiod      = String.Empty,
                                                                                                          Docktostock      = String.Empty,
                                                                                                          Minbuildqty      = String.Empty,
                                                                                                          Startdate        = DateTime.Today.ToString("yyyy-MM-dd"),
                                                                                                          Enddate          = String.Empty,
                                                                                                          Categories       = new MessageBodyInventoryimportCategoriesCategoryCode[]
                {
                },
                Providers = new MessageBodyInventoryimportProviders(),
                Suppliers = new MessageBodyInventoryimportSuppliers[] {  },
                Projects  = new[] { new MessageBodyInventoryimportProjectsProject {
                                        Value = "Aubuchon"
                                    } },
                Locales = new[] { new MessageBodyInventoryimportLocalesLocale
                                  {
                                      LocaleCode                      = "en-US",
                                      Description                     = product.Content.ProductName,
                                      InventoryNotes                  = product.Content.ProductShortDescription,
                                      RetailPrice                     = Convert.ToString(product.Price.Price),
                                      SalePrice                       = product.Price.SalePrice == null?Convert.ToString(product.Price.Price) : Convert.ToString(product.Price.SalePrice),
                                                                 Cost = Convert.ToString(product.SupplierInfo.Cost.Cost)
                                  } },
                Dynamicfields = new MessageBodyInventoryimportDynamicfieldsDynamicfield[] { },
            };

            if (product.Content.ProductImages != null)
            {
                inventoryImport.Filenames =
                    new MessageBodyInventoryimportFilenamesFilename[product.Content.ProductImages.Count];

                for (var i = 0; product.Content.ProductImages != null && i < product.Content.ProductImages.Count; i++)
                {
                    inventoryImport.Filenames[i] = new MessageBodyInventoryimportFilenamesFilename
                    {
                        Default = i == 0 ? "1" : "0",
                        Value   = product.Content.ProductImages[i].ImageLabel
                    };
                }
            }

            if (locations != null)
            {
                inventoryImport.Providers = new MessageBodyInventoryimportProviders
                {
                    ProviderCode = new MessageBodyInventoryimportProvidersProviderCode[locations.Count]
                };
                for (var i = 0; i < locations.Count; i++)
                {
                    inventoryImport.Providers.ProviderCode[i] = new MessageBodyInventoryimportProvidersProviderCode
                    {
                        ProviderCode = locations[i].LocationCode
                    };
                }
            }

            //inventoryImport.Suppliers = new MessageBodyInventoryimportSuppliers[1];
            //inventoryImport.Suppliers[0] = new MessageBodyInventoryimportSuppliers();

            //inventoryImport.Projects = new MessageBodyInventoryimportProjectsProject[1];
            //inventoryImport.Projects[0] = new MessageBodyInventoryimportProjectsProject();

            //inventoryImport.Locales = new MessageBodyInventoryimportLocalesLocale[1];

            //inventoryImport.Locales[0] = new MessageBodyInventoryimportLocalesLocale
            //{
            //    LocaleCode = "US-EN",
            //    Description = product.Content.ProductShortDescription,
            //    InventoryNotes = "test note",//TODO: Check the right mapping value as it is required
            //    RetailPrice = Convert.ToString(product.Price.Price),
            //    SalePrice = Convert.ToString(product.Price.SalePrice ?? product.Price.Price) //TODO:Check what should be passed if SalePrice is null
            //};

            //inventoryImport.Dynamicfields = new MessageBodyInventoryimportDynamicfieldsDynamicfield[1];
            body.Inventoryimport[0] = inventoryImport;
            message.Items[1]        = body;

            return(message);
        }
Пример #17
0
        public IActionResult UpdateStock([FromHeader(Name = "X-CarsUnlimited-InventoryApiKey")] string inventoryApiKey, InventoryMessage inventoryMessage)
        {
            if (!string.IsNullOrWhiteSpace(inventoryApiKey) && inventoryApiKey == _config.GetValue <string>("InventoryApiKey"))
            {
                _logger.LogInformation($"UpdateStock: Looking up item {inventoryMessage.Id}");

                var inventoryItem = _inventoryService.Get(inventoryMessage.Id);

                if (inventoryItem is null)
                {
                    _logger.LogInformation($"UpdateStock: No item found with ID {inventoryMessage.Id}");
                    return(NotFound());
                }

                inventoryItem.InStock -= inventoryMessage.StockAdjustment;

                try
                {
                    _inventoryService.Update(inventoryItem);
                }
                catch (MongoDB.Driver.MongoException ex)
                {
                    _logger.LogError($"UpdateStock: Error encountered attemping stock update: {ex.Message}");
                    return(StatusCode(500));
                }
            }
            else
            {
                return(StatusCode(401));
            }
            return(NoContent());
        }