Esempio n. 1
0
        private bool TryToLogMessage(ref Message reply)
        {
            try
            {
                if (this.LogRawMessages)
                {
                    var buffer = reply.CreateBufferedCopy(int.MaxValue);
                    reply = buffer.CreateMessage();
                    var originalMessage   = buffer.CreateMessage();
                    var messageSerialized = originalMessage.ToString();

                    var httpPropertyName = HttpResponseMessageProperty.Name.ToString();
                    if (originalMessage.Properties.ContainsKey(httpPropertyName))
                    {
                        var property = originalMessage.Properties[httpPropertyName] as HttpResponseMessageProperty;
                        if (property != null)
                        {
                            messageSerialized = "HttpStatusCode: " + property.StatusCode.ToString() + ", message:" + messageSerialized;
                        }
                    }
                    MagentoLogger.LogTraceResponseMessage(messageSerialized);
                    return(true);
                }
            }
            catch
            {
            }
            return(false);
        }
Esempio n. 2
0
        public virtual async Task <bool> PutStockItemsAsync(List <PutStockItem> stockItems, Mark markForLog = null)
        {
            var methodParameters = stockItems.ToJson();

            try
            {
                var stockItemsProcessed = stockItems.Select(x =>
                {
                    var catalogInventoryStockItemUpdateEntity = (x.Qty > 0) ?
                                                                new catalogInventoryStockItemUpdateEntity()
                    {
                        is_in_stock = 1, is_in_stockSpecified = true, qty = x.Qty.ToString()
                    } :
                    new catalogInventoryStockItemUpdateEntity()
                    {
                        is_in_stock = 0, is_in_stockSpecified = false, qty = x.Qty.ToString()
                    };
                    return(Tuple.Create(x, catalogInventoryStockItemUpdateEntity));
                });

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var res           = false;
                var privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl);

                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    if (privateClient.State != CommunicationState.Opened &&
                        privateClient.State != CommunicationState.Created &&
                        privateClient.State != CommunicationState.Opening)
                    {
                        privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl);
                    }

                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                    {
                        MagentoLogger.LogTraceStarted(CreateMethodCallInfo(methodParameters, markForLog));

                        var temp = await privateClient.catalogInventoryStockItemMultiUpdateAsync(sessionId.SessionId, stockItemsProcessed.Select(x => x.Item1.ItemId).ToArray(), stockItemsProcessed.Select(x => x.Item2).ToArray()).ConfigureAwait(false);

                        res = temp.result;

                        var updateBriefInfo = string.Format("{{Success:{0}}}", res);
                        MagentoLogger.LogTraceEnded(CreateMethodCallInfo(methodParameters, markForLog, methodResult: updateBriefInfo));
                    }
                }).ConfigureAwait(false);

                return(res);
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException(string.Format("An error occured during PutStockItemsAsync({0})", methodParameters), exc);
            }
        }
Esempio n. 3
0
        public virtual async Task <GetMagentoInfoResponse> GetMagentoInfoAsync(bool suppressException, Mark mark = null)
        {
            try
            {
                // Magento doesn't provide method to receive magento vesrion, since Magento2.0 thats why we use backEndMoodules API

                var sessionIdRespnse = await this.GetSessionId(!suppressException).ConfigureAwait(false);

                if (sessionIdRespnse == null)
                {
                    MagentoLogger.LogTrace("Can't get session id. Possible reasons: incorrect credentials, user was blocked.");
                    return(null);
                }
                //var modules = await this.GetBackEndModulesAsync().ConfigureAwait( false );
                var getOrdersResponse = await this.GetOrdersAsync(DateTime.Now, DateTime.Now.AddHours(1)).ConfigureAwait(false);

                var getProductsRes = await this.GetProductsAsync(1, null, false, null).ConfigureAwait(false);

                //var saveMethodResult = await this.SaveOrderMethodExistAsync().ConfigureAwait( false );
                return /*modules?.Modules != null && modules.Modules.Count > 0 &&*/ (getOrdersResponse.Orders.Count() >= 0 && getProductsRes.Products.Count() >= 0 ? new GetMagentoInfoResponse("2.0.2.0", "CE") : null);
            }
            catch (Exception exc)
            {
                if (suppressException)
                {
                    return(null);
                }
                throw new MagentoSoapException(string.Format("An error occured during GetMagentoInfoAsync()"), exc);
            }
        }
Esempio n. 4
0
        public async Task <Stream> GetResponseStreamAsync(WebRequest webRequest, Mark mark = null)
        {
            try
            {
                using (var response = ( HttpWebResponse )await webRequest.GetResponseAsync().ConfigureAwait(false))
                    using (var dataStream = await new TaskFactory <Stream>().StartNew(() => response != null ? response.GetResponseStream() : null).ConfigureAwait(false))
                    {
                        var memoryStream = new MemoryStream();
                        if (dataStream != null)
                        {
                            await dataStream.CopyToAsync(memoryStream, 0x100).ConfigureAwait(false);

                            memoryStream.Position = 0;
                            MagentoLogger.LogTraceResponseMessage(new StreamReader(memoryStream).ReadToEnd(), mark);
                        }

                        memoryStream.Position = 0;
                        return(memoryStream);
                    }
            }
            catch (Exception ex)
            {
                var webrequestUrl = PredefinedValues.NotAvailable;

                if (webRequest?.RequestUri?.AbsoluteUri != null)
                {
                    webrequestUrl = webRequest.RequestUri.AbsoluteUri;
                }

                throw new MagentoWebException($"Exception occured on GetResponseStreamAsync( webRequest:{webrequestUrl})", ex);
            }
        }
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            //trace
            if (this.LogRawMessages)
            {
                var buffer = reply.CreateBufferedCopy(int.MaxValue);
                reply = buffer.CreateMessage();
                var originalMessage   = buffer.CreateMessage();
                var messageSerialized = originalMessage.ToString();
                var property          = originalMessage.Properties[HttpResponseMessageProperty.Name.ToString()] as HttpResponseMessageProperty;
                if (property != null)
                {
                    messageSerialized = "HttpStatusCode: " + property.StatusCode.ToString() + ", message:" + messageSerialized;
                }
                MagentoLogger.LogTraceResponseMessage(messageSerialized);
            }

            var prop =
                reply.Properties[HttpResponseMessageProperty.Name.ToString()] as HttpResponseMessageProperty;

            if (prop != null)
            {
                // get the content type headers
                var contentType = prop.Headers["Content-Type"];
            }
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //trace
            if (this.LogRawMessages)
            {
                var buffer = request.CreateBufferedCopy(int.MaxValue);
                request = buffer.CreateMessage();
                var originalMessage   = buffer.CreateMessage();
                var messageSerialized = originalMessage.ToString();
                MagentoLogger.LogTraceRequestMessage(messageSerialized);
            }

            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                if (string.IsNullOrEmpty(httpRequestMessage.Headers["Accept-Encoding"]))
                {
                    httpRequestMessage.Headers.Remove("Accept-Encoding");
                }
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                httpRequestMessage.Headers.Add("Accept-Encoding", "");
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }

            return(null);
        }
Esempio n. 7
0
        public virtual async Task <bool> PutStockItemAsync(PutStockItem putStockItem, Mark markForLog)
        {
            try
            {
                var methodParameters = new List <PutStockItem> {
                    putStockItem
                }.ToJson();

                var catalogInventoryStockItemUpdateEntity = (putStockItem.Qty > 0) ?
                                                            new catalogInventoryStockItemUpdateEntity()
                {
                    is_in_stock = 1, is_in_stockSpecified = true, qty = putStockItem.Qty.ToString()
                } :
                new catalogInventoryStockItemUpdateEntity()
                {
                    is_in_stock = 0, is_in_stockSpecified = false, qty = putStockItem.Qty.ToString()
                };

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 120000;

                var res           = false;
                var privateClient = this._clientFactory.GetClient();


                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    privateClient = this._clientFactory.RefreshClient(privateClient);
                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                    {
                        MagentoLogger.LogTraceStarted(CreateMethodCallInfo(methodParameters, markForLog));

                        var temp = await privateClient.catalogInventoryStockItemUpdateAsync(sessionId.SessionId, putStockItem.ProductId, catalogInventoryStockItemUpdateEntity).ConfigureAwait(false);

                        res = temp.result > 0;

                        var updateBriefInfo = string.Format("{{Success:{0}}}", res);
                        MagentoLogger.LogTraceEnded(CreateMethodCallInfo(methodParameters, markForLog, methodResult: updateBriefInfo));
                    }
                }).ConfigureAwait(false);

                return(res);
            }
            catch (Exception exc)
            {
                var productsBriefInfo = new List <PutStockItem> {
                    putStockItem
                }.ToJson();
                throw new MagentoSoapException($"An error occured during PutStockItemsAsync({productsBriefInfo})", exc);
            }
        }
        public virtual async Task <IEnumerable <RpcInvoker.RpcRequestResponse <PutStockItem, object> > > PutStockItemsAsync(List <PutStockItem> stockItems, Mark mark = null)
        {
            var methodParameters = stockItems.ToJson();

            try
            {
                var stockItemsProcessed = stockItems.Select(x =>
                {
                    var catalogInventoryStockItemUpdateEntity = (x.Qty > 0) ?
                                                                new catalogInventoryStockItemUpdateEntity()
                    {
                        is_in_stock = 1, is_in_stockSpecified = true, qty = x.Qty.ToString()
                    } :
                    new catalogInventoryStockItemUpdateEntity()
                    {
                        is_in_stock = 0, is_in_stockSpecified = false, qty = x.Qty.ToString()
                    };
                    return(Tuple.Create(x, catalogInventoryStockItemUpdateEntity));
                });

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var privateClient = this._clientFactory.GetClient();

                RpcInvoker.RpcResponse <catalogInventoryStockItemMultiUpdateResponse> serverResponse = null;
                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    privateClient = this._clientFactory.RefreshClient(privateClient);

                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                    {
                        MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(methodParameters, mark));

                        var catalogInventoryStockItemUpdateEntities = stockItemsProcessed.Select(x => x.Item2).ToArray();

                        serverResponse = await RpcInvoker.SuppressExceptions(async() => await privateClient.catalogInventoryStockItemMultiUpdateAsync(sessionId.SessionId, stockItemsProcessed.Select(x => x.Item1.ProductId).ToArray(), catalogInventoryStockItemUpdateEntities).ConfigureAwait(false)).ConfigureAwait(false);

                        var updateBriefInfo = string.Format("{{Success:{0}}}", serverResponse.Result.result);
                        MagentoLogger.LogTraceEnded(CreateMethodCallInfo(methodParameters, mark: mark, methodResult: updateBriefInfo));
                    }
                }).ConfigureAwait(false);

                var result = stockItems.Select(y => new RpcInvoker.RpcRequestResponse <PutStockItem, object>(y, new RpcInvoker.RpcResponse <object>(serverResponse?.ErrorCode ?? RpcInvoker.SoapErrorCode.Unknown, serverResponse?.Result, serverResponse?.Exception)));
                return(result);
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException($"An error occured during PutStockItemsAsync({methodParameters})", exc);
            }
        }
        public MagentoServiceLowLevel()
        {
            this.RepeatOnAuthProblemAsync = ActionPolicyAsync.From((exception =>
            {
                var webException = (exception as MagentoWebException)?.InnerException as WebException;
                if (webException == null)
                {
                    return(false);
                }

                switch (webException.Status)
                {
                case WebExceptionStatus.ProtocolError:
                    var response = webException.Response as HttpWebResponse;
                    if (response == null)
                    {
                        return(false);
                    }
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.Unauthorized:
                        return(true);

                    default:
                        return(false);
                    }

                default:
                    return(false);
                }
            }))
                                            .RetryAsync(3, async(ex, i) =>
            {
                await this._reauthorizeLock.WaitAsync();
                var reauthorizationsCountPropagation = this.reauthorizationsCount;
                this._reauthorizeLock.Release();
                await this._reauthorizeLock.WaitAsync();
                try
                {
                    if (reauthorizationsCountPropagation != this.reauthorizationsCount)
                    {
                        return;
                    }
                    Interlocked.Increment(ref this.reauthorizationsCount);
                    MagentoLogger.Log().Trace(ex, "Retrying Magento API call due to authorization problem for the {0} time", i);
                    await this.ReauthorizeAsync().ConfigureAwait(false);
                    await Task.Delay(TimeSpan.FromSeconds(0.5 + i)).ConfigureAwait(false);
                }
                finally
                {
                    this._reauthorizeLock.Release();
                }
            });
        }
Esempio n. 10
0
        public async Task <Stream> RunAsync(Mark mark = null)
        {
            var webRequestServices = new WebRequestServices();
            var serviceUrl         = this.Url.ToString().TrimEnd('/') + MagentoRestPath + this.MagentoServicePath.ToString();
            var body       = this.Body.ToString();
            var method     = this.MagentoWebRequestMethod.ToString();
            var parameters = this.Parameters?.ToString();
            var rawHeaders = new Dictionary <string, string> {
                { "Authorization", $"Bearer {this.AuthorizationToken}" }
            };
            var requestAsync = await webRequestServices.CreateCustomRequestAsync(
                serviceUrl,
                body,
                rawHeaders,                 //TODO:create VO with builder!!!
                method,
                parameters).ConfigureAwait(false);

            MagentoLogger.LogTraceRequestMessage($"method:'{method}',url:'{serviceUrl}',parameters:'{parameters}',headers:{rawHeaders.ToJson()},body:'{body}'", mark);
            return(await webRequestServices.GetResponseStreamAsync(requestAsync, mark).ConfigureAwait(false));
        }
Esempio n. 11
0
 private void LogTraceGetResponseException(Exception exception)
 {
     MagentoLogger.Log().Trace(exception, "[magento] SOAP throw an exception.");
 }
        public virtual async Task <IEnumerable <RpcInvoker.RpcRequestResponse <PutStockItem, object> > > PutStockItemsAsync(List <PutStockItem> stockItems, Mark mark = null)
        {
            var methodParameters = stockItems.ToJson();

            try
            {
                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var magentoStockItemsResponse = await this.GetStockItemsOldAsync(stockItems.Select(item => item.Sku)).ConfigureAwait(false);

                var magentoStockItems = magentoStockItemsResponse.Responses.Select(item => item as CatalogInventoryDataStockItemInterface).Where(item => item != null);

                var privateClient = this._clientFactory.CreateMagentoCatalogInventoryStockServiceClient();

                var res = new ConcurrentQueue <RpcInvoker.RpcRequestResponse <PutStockItem, object> >();

                await stockItems.DoInBatchAsync(10, async x =>
                {
                    await ActionPolicies.GetAsync.Do(async() =>
                    {
                        var statusChecker = new StatusChecker(maxCheckCount);
                        TimerCallback tcb = statusChecker.CheckStatus;

                        privateClient = this._clientFactory.RefreshMagentoCatalogInventoryStockServiceClient(privateClient);

                        using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        {
                            MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(methodParameters, mark: mark));

                            var productId = int.Parse(x.ProductId);
                            var catalogInventoryDataStockItemInterface = magentoStockItems.FirstOrDefault(i => i.productId == productId);
                            if (catalogInventoryDataStockItemInterface == null)
                            {
                                MagentoLogger.LogTrace($"PutStockItemsAsync. Can't find StockItem with ProductId={x.ProductId} (SKU={x.Sku}).", mark);
                                catalogInventoryDataStockItemInterface = new CatalogInventoryDataStockItemInterface
                                {
                                    productId                      = productId,
                                    productIdSpecified             = true,
                                    isInStock                      = false,
                                    isQtyDecimal                   = false,
                                    showDefaultNotificationMessage = false,
                                    useConfigMinQty                = true,
                                    minQty = 0,
                                    useConfigMinSaleQty     = 1,
                                    minSaleQty              = 1,
                                    useConfigMaxSaleQty     = true,
                                    maxSaleQty              = 10000,
                                    useConfigBackorders     = true,
                                    backorders              = 0,
                                    useConfigNotifyStockQty = true,
                                    notifyStockQty          = 1,
                                    useConfigQtyIncrements  = true,
                                    qtyIncrements           = 0,
                                    useConfigEnableQtyInc   = false,
                                    enableQtyIncrements     = false,
                                    useConfigManageStock    = true,
                                    manageStock             = true,
                                    //lowStockDate = "2016-02-29 20:48:26",
                                    isDecimalDivided       = false,
                                    stockStatusChangedAuto = 1
                                };
                            }
                            catalogInventoryDataStockItemInterface.qty        = x.Qty.ToString();
                            catalogInventoryDataStockItemInterface.isInStock |= x.Qty > 0;

                            var catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest = new CatalogInventoryStockRegistryV1UpdateStockItemBySkuRequest()
                            {
                                productSku = x.Sku,
                                stockItem  = catalogInventoryDataStockItemInterface
                            };

                            RpcInvoker.IRpcResponse <object> response = await RpcInvoker.SuppressExceptions(async() => await privateClient.catalogInventoryStockRegistryV1UpdateStockItemBySkuAsync(catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest).ConfigureAwait(false)).ConfigureAwait(false);
                            var reqResp = new RpcInvoker.RpcRequestResponse <PutStockItem, object>(x, response);
                            res.Enqueue(reqResp);
                        }
                    }).ConfigureAwait(false);
                }).ConfigureAwait(false);

                MagentoLogger.LogTraceEnded(this.CreateMethodCallInfo(methodParameters, mark: mark, methodResult: res.ToJson()));
                //return errors count instead of true false;
                return(res);
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException($"An error occured during PutStockItemsAsync({methodParameters})", exc);
            }
        }
        public virtual async Task <bool> PutStockItemAsync(PutStockItem putStockItem, Mark markForLog)
        {
            var productsBriefInfo = new List <PutStockItem> {
                putStockItem
            }.ToJson();

            try
            {
                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 120000;

                var res           = false;
                var privateClient = this._clientFactory.CreateMagentoCatalogInventoryStockServiceClient();

                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    privateClient = this._clientFactory.RefreshMagentoCatalogInventoryStockServiceClient(privateClient);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                    {
                        MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(productsBriefInfo, markForLog));

                        var catalogInventoryDataStockItemInterface = new CatalogInventoryDataStockItemInterface()
                        {
                            qty                            = putStockItem.Qty.ToString(),
                            productId                      = int.Parse(putStockItem.ProductId),
                            productIdSpecified             = true,
                            isInStock                      = putStockItem.Qty > 0,
                            isQtyDecimal                   = false,
                            showDefaultNotificationMessage = false,
                            useConfigMinQty                = true,
                            minQty                         = 0,
                            useConfigMinSaleQty            = 1,
                            minSaleQty                     = 1,
                            useConfigMaxSaleQty            = true,
                            maxSaleQty                     = 10000,
                            useConfigBackorders            = true,
                            backorders                     = 0,
                            useConfigNotifyStockQty        = true,
                            notifyStockQty                 = 1,
                            useConfigQtyIncrements         = true,
                            qtyIncrements                  = 0,
                            useConfigEnableQtyInc          = false,
                            enableQtyIncrements            = false,
                            useConfigManageStock           = true,
                            manageStock                    = true,
                            //lowStockDate = "2016-02-29 20:48:26",
                            isDecimalDivided       = false,
                            stockStatusChangedAuto = 1
                        };
                        var catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest = new CatalogInventoryStockRegistryV1UpdateStockItemBySkuRequest()
                        {
                            //productSku = x.Sku,
                            stockItem = catalogInventoryDataStockItemInterface
                        };

                        var temp = await privateClient.catalogInventoryStockRegistryV1UpdateStockItemBySkuAsync(catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest).ConfigureAwait(false);

                        res = temp.catalogInventoryStockRegistryV1UpdateStockItemBySkuResponse.result > 0;

                        var updateBriefInfo = string.Format("{{ErrorCode:{0}}}", res);
                        MagentoLogger.LogTraceEnded(this.CreateMethodCallInfo(productsBriefInfo, markForLog, methodResult: updateBriefInfo));
                    }
                }).ConfigureAwait(false);

                return(res);
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException($"An error occured during PutStockItemsAsync({productsBriefInfo})", exc);
            }
        }
Esempio n. 14
0
        public async Task <int> CreateProduct(string storeId, string name, string sku, int isInStock, string productType, Mark markForLog)
        {
            var stockItem        = new CreatteProductModel(name, sku, isInStock, productType);
            var methodParameters = stockItem.ToJson();

            try
            {
                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var privateClient = this._clientFactory.CreateMagentoCatalogProductRepositoryServiceClient();

                var res        = new List <RpcInvoker.RpcResponse <catalogProductRepositoryV1SaveResponse1> >();
                var stockItems = new List <CreatteProductModel> {
                    stockItem
                };

                await stockItems.DoInBatchAsync(10, async x =>
                {
                    await ActionPolicies.GetAsync.Do(async() =>
                    {
                        var statusChecker = new StatusChecker(maxCheckCount);
                        TimerCallback tcb = statusChecker.CheckStatus;

                        privateClient = this._clientFactory.RefreshMagentoCatalogProductRepositoryServiceClient(privateClient);

                        using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        {
                            MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(methodParameters, mark: markForLog));

                            var catalogInventoryDataStockItemInterface = new CatalogDataProductInterface()
                            {
                                sku                     = x.Sku,
                                name                    = x.Name,
                                price                   = "1",
                                priceSpecified          = true,
                                status                  = 1,
                                statusSpecified         = true,
                                typeId                  = productType,
                                attributeSetId          = 4,
                                attributeSetIdSpecified = true,
                                weight                  = "1",
                                weightSpecified         = true,
                            };
                            if (productType == "bundle")
                            {
                                catalogInventoryDataStockItemInterface.customAttributes = new[]
                                {
                                    new FrameworkAttributeInterface {
                                        value = "1", attributeCode = "price_view"
                                    },
                                    new FrameworkAttributeInterface {
                                        value = "1", attributeCode = "price_type"
                                    }
                                };
                            }
                            var catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest = new CatalogProductRepositoryV1SaveRequest()
                            {
                                product = catalogInventoryDataStockItemInterface
                            };

                            var temp = await privateClient.catalogProductRepositoryV1SaveAsync(catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest).ConfigureAwait(false);

                            var updateResult = new RpcInvoker.RpcResponse <catalogProductRepositoryV1SaveResponse1>(RpcInvoker.SoapErrorCode.Success, temp, null);
                            res.Add(updateResult);
                        }
                    }).ConfigureAwait(false);
                }).ConfigureAwait(false);

                MagentoLogger.LogTraceEnded(this.CreateMethodCallInfo(methodParameters, mark: markForLog, methodResult: res.ToJson()));

                return(res.First().Result.catalogProductRepositoryV1SaveResponse.result.id);
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException($"An error occured during PutStockItemsAsync({methodParameters})", exc);
            }
        }
Esempio n. 15
0
        public virtual async Task <bool> PutStockItemsAsync(List <PutStockItem> stockItems, Mark markForLog = null)
        {
            var methodParameters = stockItems.ToJson();

            try
            {
                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var privateClient = this.CreateMagentoCatalogInventoryStockServiceClient(this.BaseMagentoUrl);

                var res = new List <UpdateRessult>();

                await stockItems.DoInBatchAsync(10, async x =>
                {
                    await ActionPolicies.GetAsync.Do(async() =>
                    {
                        var statusChecker = new StatusChecker(maxCheckCount);
                        TimerCallback tcb = statusChecker.CheckStatus;

                        if (privateClient.State != CommunicationState.Opened &&
                            privateClient.State != CommunicationState.Created &&
                            privateClient.State != CommunicationState.Opening)
                        {
                            privateClient = this.CreateMagentoCatalogInventoryStockServiceClient(this.BaseMagentoUrl);
                        }

                        var updateResult = new UpdateRessult(x, 0);
                        res.Add(updateResult);

                        using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        {
                            MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(methodParameters, mark: markForLog));

                            var catalogInventoryDataStockItemInterface = new CatalogInventoryDataStockItemInterface()
                            {
                                qty                            = x.Qty.ToString(),
                                productId                      = int.Parse(x.ProductId),
                                productIdSpecified             = true,
                                isInStock                      = x.Qty > 0,
                                isQtyDecimal                   = false,
                                showDefaultNotificationMessage = false,
                                useConfigMinQty                = true,
                                minQty                         = 0,
                                useConfigMinSaleQty            = 1,
                                minSaleQty                     = 1,
                                useConfigMaxSaleQty            = true,
                                maxSaleQty                     = 10000,
                                useConfigBackorders            = true,
                                backorders                     = 0,
                                useConfigNotifyStockQty        = true,
                                notifyStockQty                 = 1,
                                useConfigQtyIncrements         = true,
                                qtyIncrements                  = 0,
                                useConfigEnableQtyInc          = false,
                                enableQtyIncrements            = false,
                                useConfigManageStock           = true,
                                manageStock                    = true,
                                //lowStockDate = "2016-02-29 20:48:26",
                                isDecimalDivided       = false,
                                stockStatusChangedAuto = 1
                            };
                            var catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest = new CatalogInventoryStockRegistryV1UpdateStockItemBySkuRequest()
                            {
                                productSku = x.Sku,
                                stockItem  = catalogInventoryDataStockItemInterface
                            };

                            var temp = await privateClient.catalogInventoryStockRegistryV1UpdateStockItemBySkuAsync(catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest).ConfigureAwait(false);

                            updateResult.Success = temp.catalogInventoryStockRegistryV1UpdateStockItemBySkuResponse.result;
                        }
                    }).ConfigureAwait(false);
                }).ConfigureAwait(false);

                MagentoLogger.LogTraceEnded(this.CreateMethodCallInfo(methodParameters, mark: markForLog, methodResult: res.ToJson()));

                return(res.All(x => x.Success > 0));
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException(string.Format("An error occured during PutStockItemsAsync({0})", methodParameters), exc);
            }
        }