コード例 #1
0
        public ProductsCustomBatchRequest GetCatalogProductsBatchRequest(string catalogId, string categoryId = "")
        {
            var result = _catalogSearchService.Search(new SearchCriteria {
                CatalogId = catalogId, CategoryId = categoryId, ResponseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations
            });
            var retVal = new ProductsCustomBatchRequest();

            foreach (var product in result.Products.Select((value, index) => new { Value = value, Index = index }))
            {
                var converted = product.Value.ToGoogleModel(_assetUrlResolver);
                var prices    = _pricingService.EvaluateProductPrices(new PriceEvaluationContext {
                    ProductIds = new string[] { converted.Id }
                });
                if (prices != null)
                {
                    converted.Price = prices.First(x => x.Currency == "USD").ToGoogleModel();
                    if (retVal.Entries == null)
                    {
                        retVal.Entries = new List <ProductsCustomBatchRequestEntry>();
                    }
                    var val = converted.ToBatchEntryModel();
                    val.BatchId = product.Index + 1;
                    retVal.Entries.Add(val);
                }
            }
            ;
            return(retVal);
        }
コード例 #2
0
        public ProductsCustomBatchRequest GetCatalogProductsBatchRequest(string catalogId, string categoryId = "")
        {
            var retVal = new ProductsCustomBatchRequest
            {
                Entries = new List <ProductsCustomBatchRequestEntry>()
            };

            var searchCriteria = new SearchCriteria
            {
                CatalogId     = catalogId,
                CategoryId    = categoryId,
                ResponseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations
            };
            var result = _catalogSearchService.Search(searchCriteria);

            foreach (var product in result.Products.Select((value, index) => new { Value = value, Index = index }))
            {
                var converted = product.Value.ToGoogleModel(_assetUrlResolver);
                if (!TryGetProductPrice(converted.Id, out var productPrice))
                {
                    continue;
                }

                converted.Price = productPrice;

                var val = converted.ToBatchEntryModel();
                val.BatchId = product.Index + 1;
                retVal.Entries.Add(val);
            }
            ;
            return(retVal);
        }
コード例 #3
0
        /// <inheritdoc/>
        public ChannelReader <(Product product, Errors errors)> UpInsertBatch(ChannelReader <Product> channel, CancellationToken cancellationToken)
        {
            var output = Channel.CreateUnbounded <(Product product, Errors errors)>();

            Task.Run(async() =>
            {
                try
                {
                    async Task <ProductsCustomBatchRequest> RequestAsync(GoogleShoppingOptions options)
                    {
                        var batchRequest = new ProductsCustomBatchRequest
                        {
                            Entries = new List <ProductsCustomBatchRequestEntry>()
                        };

                        var batchId = 0;
                        while (await channel.WaitToReadAsync(cancellationToken))
                        {
                            var item = await channel.ReadAsync(cancellationToken);

                            var entry = new ProductsCustomBatchRequestEntry
                            {
                                BatchId    = batchId,
                                MerchantId = options.MerchantId,
                                Method     = "insert",
                                Product    = item
                            };
                            batchRequest.Entries.Add(entry);
                            ++batchId;
                        }

                        return(batchRequest);
                    }

                    var response = await ExecuteBatchAsync(RequestAsync, cancellationToken);

                    if (response.Kind == "content#productsCustomBatchResponse")
                    {
                        for (var i = 0; i < response.Entries.Count; i++)
                        {
                            var insertedProduct = response.Entries[i].Product;
                            await output.Writer.WriteAsync((insertedProduct, response.Entries[i].Errors), cancellationToken);
                        }
                    }
                    else
                    {
                        _logger.LogInformation("There was an error. Response: {responseCode}", response.ToString());
                    }
                }
                finally
                {
                    output.Writer.Complete();
                }
            });

            return(output);
        }
コード例 #4
0
        /// <inheritdoc/>
        public async Task <IDictionary <long, string> > DeleteBatchAsync(IDictionary <long, string> productIdList, CancellationToken cancellationToken)
        {
            var result = new Dictionary <long, string>();

            ProductsCustomBatchRequest Request(GoogleShoppingOptions options)
            {
                var batchRequest = new ProductsCustomBatchRequest
                {
                    Entries = new List <ProductsCustomBatchRequestEntry>()
                };

                foreach (var item in productIdList)
                {
                    var entry = new ProductsCustomBatchRequestEntry
                    {
                        BatchId    = item.Key,
                        MerchantId = options.MerchantId,
                        Method     = "delete",
                        ProductId  = item.Value
                    };
                    batchRequest.Entries.Add(entry);
                }

                return(batchRequest);
            }

            var response = await ExecuteBatchAsync(Request, cancellationToken);

            if (response.Kind == "content#productsCustomBatchResponse")
            {
                for (var i = 0; i < response.Entries.Count; i++)
                {
                    var errors    = response.Entries[i].Errors;
                    var flatError = string.Empty;
                    if (errors != null)
                    {
                        for (var j = 0; j < errors.ErrorsValue.Count; j++)
                        {
                            flatError += errors.ErrorsValue[j].ToString();
                        }
                    }
                    else
                    {
                        _logger.LogDebug("Product deleted, batchId {0}", response.Entries[i].BatchId);
                    }

                    result.Add(response.Entries[i].BatchId ?? 0, flatError);
                }
            }
            else
            {
                _logger.LogError("There was an error. Response: {response}", response);
            }

            return(result);
        }
コード例 #5
0
        private ProductsCustomBatchResponse PerformBatchProductsUpdate(ProductsCustomBatchRequest productsUpdateRequest)
        {
            foreach (var entry in productsUpdateRequest.Entries)
            {
                entry.MerchantId = _settingsManager.MerchantId;
            }

            var request  = _contentService.Products.Custombatch(productsUpdateRequest);
            var response = request.Execute();

            return(response);
        }
コード例 #6
0
 public ProductsCustomBatchRequest GetProductsBatchRequest(IEnumerable<string> ids)
 {
     var retVal = new ProductsCustomBatchRequest();
     var products = GetProductUpdates(ids);
     retVal.Entries = new List<ProductsCustomBatchRequestEntry>();
     foreach(var prod in products.Select((value, index) => new {Value = value, Index = index}))
     {
         var val = prod.Value.ToBatchEntryModel();
         val.BatchId = prod.Index+1;
         retVal.Entries.Add(val); 
     };
     return retVal;
 }
コード例 #7
0
        public ProductsCustomBatchRequest GetProductsBatchRequest(IEnumerable <string> ids)
        {
            var retVal   = new ProductsCustomBatchRequest();
            var products = GetProductUpdates(ids);

            retVal.Entries = new List <ProductsCustomBatchRequestEntry>();
            foreach (var prod in products.Select((value, index) => new { Value = value, Index = index }))
            {
                var val = prod.Value.ToBatchEntryModel();
                val.BatchId = prod.Index + 1;
                retVal.Entries.Add(val);
            }
            ;
            return(retVal);
        }
コード例 #8
0
        /// <summary>
        /// Deletes several products from the specified account, using custombatch.
        /// </summary>
        private void DeleteProductCustombatch(ulong merchantId, List <String> productList)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Deleting products using custombatch");
            Console.WriteLine("=================================================================");

            ProductsCustomBatchRequest batchRequest = new ProductsCustomBatchRequest();

            batchRequest.Entries = new List <ProductsCustomBatchRequestEntry>();
            for (int i = 0; i < productList.Count; i++)
            {
                ProductsCustomBatchRequestEntry entry = new ProductsCustomBatchRequestEntry();
                entry.BatchId    = i;
                entry.MerchantId = merchantId;
                entry.Method     = "delete";
                entry.ProductId  = productList[i]; // Use the full product ID here, not the OfferId
                batchRequest.Entries.Add(entry);
            }

            ProductsCustomBatchResponse response = service.Products.Custombatch(batchRequest).Execute();

            if (response.Kind == "content#productsCustomBatchResponse")
            {
                for (int i = 0; i < response.Entries.Count; i++)
                {
                    Errors errors = response.Entries[i].Errors;
                    if (errors != null)
                    {
                        for (int j = 0; j < errors.ErrorsValue.Count; j++)
                        {
                            Console.WriteLine(errors.ErrorsValue[j].ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Product deleted, batchId {0}", response.Entries[i].BatchId);
                    }
                }
            }
            else
            {
                Console.WriteLine(
                    "There was an error. Response: {0}",
                    response);
            }
        }
コード例 #9
0
        /// <inheritdoc/>
        public async Task <IDictionary <long, (Product product, Errors errors)> > UpInsertBatchAsync(
            IDictionary <long, Product> productList,
            CancellationToken cancellationToken)
        {
            var result = new Dictionary <long, (Product product, Errors errors)>();

            ProductsCustomBatchRequest Request(GoogleShoppingOptions options)
            {
                var batchRequest = new ProductsCustomBatchRequest
                {
                    Entries = new List <ProductsCustomBatchRequestEntry>()
                };

                foreach (var item in productList)
                {
                    var entry = new ProductsCustomBatchRequestEntry
                    {
                        BatchId    = item.Key,
                        MerchantId = options.MerchantId,
                        Method     = "insert",
                        Product    = item.Value
                    };
                    batchRequest.Entries.Add(entry);
                }

                return(batchRequest);
            }

            var response = await ExecuteBatchAsync(Request, cancellationToken);

            if (response.Kind == "content#productsCustomBatchResponse")
            {
                for (var i = 0; i < response.Entries.Count; i++)
                {
                    var insertedProduct = response.Entries[i].Product;
                    result.Add(response.Entries[i].BatchId ?? 0, (insertedProduct, response.Entries[i].Errors));
                }
            }
            else
            {
                _logger.LogInformation("There was an error. Response: {responseCode}", response.ToString());
            }

            return(result);
        }
コード例 #10
0
        /// <summary>
        /// Inserts several products to the specified account, using custombatch.
        /// </summary>
        /// <returns>The list of product IDs, which can be used to get or delete them.</returns>
        private List <String> InsertProductCustombatch(ulong merchantId, string websiteUrl)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Inserting products using custombatch");
            Console.WriteLine("=================================================================");

            ProductsCustomBatchRequest batchRequest = new ProductsCustomBatchRequest();

            batchRequest.Entries = new List <ProductsCustomBatchRequestEntry>();
            for (int i = 0; i < 3; i++)
            {
                ProductsCustomBatchRequestEntry entry = new ProductsCustomBatchRequestEntry();
                entry.BatchId    = i;
                entry.MerchantId = merchantId;
                entry.Method     = "insert";
                entry.Product    = GenerateProduct(websiteUrl);
                batchRequest.Entries.Add(entry);
            }

            ProductsCustomBatchResponse response = service.Products.Custombatch(batchRequest).Execute();
            List <String> productsInserted       = new List <String>();

            if (response.Kind == "content#productsCustomBatchResponse")
            {
                for (int i = 0; i < response.Entries.Count; i++)
                {
                    Product product = response.Entries[i].Product;
                    productsInserted.Add(product.Id);
                    Console.WriteLine(
                        "Product inserted with ID \"{0}\" and title \"{1}\".",
                        product.OfferId,
                        product.Title);
                    shoppingUtil.PrintWarnings(product.Warnings);
                }
            }
            else
            {
                Console.WriteLine(
                    "There was an error. Response: {0}",
                    response.ToString());
            }
            return(productsInserted);
        }
コード例 #11
0
 public ProductsCustomBatchRequest GetCatalogProductsBatchRequest(string catalogId, string categoryId = "")
 {
     var result = _catalogSearchService.Search(new SearchCriteria { CatalogId = catalogId, CategoryId = categoryId, ResponseGroup = ResponseGroup.WithProducts | ResponseGroup.WithVariations });
     var retVal = new ProductsCustomBatchRequest();
     foreach (var product in result.Products.Select((value, index) => new { Value = value, Index = index }))
     {
         var converted = product.Value.ToGoogleModel(_assetUrlResolver);
         var prices = _pricingService.EvaluateProductPrices(new PriceEvaluationContext { ProductIds = new string[] { converted.Id } });
         if (prices != null)
         {
             converted.Price = prices.First(x => x.Currency == CurrencyCodes.USD).ToGoogleModel();
             if (retVal.Entries == null)
                 retVal.Entries = new List<ProductsCustomBatchRequestEntry>();
             var val = converted.ToBatchEntryModel();
             val.BatchId = product.Index + 1;
             retVal.Entries.Add(val);
         }
     };
     return retVal;
 }
コード例 #12
0
        /// <summary>
        /// Retrieves, inserts, and deletes multiple products in a single request. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/products/custombatch
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated ShoppingContent service.</param>
        /// <param name="body">A valid ShoppingContent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>        /// <returns>ProductsCustomBatchResponseResponse</returns>
        public static ProductsCustomBatchResponse Custombatch(ShoppingContentService service, ProductsCustomBatchRequest body, ProductsCustombatchOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }

                // Building the initial request.
                var request = service.Products.Custombatch(body);

                // Applying optional parameters to the request.
                request = (ProductsResource.CustombatchRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Products.Custombatch failed.", ex);
            }
        }
コード例 #13
0
        /// <inheritdoc/>
        public ChannelReader <(long batchId, string productId)> Delete(ChannelReader <string> channel, CancellationToken cancellationToken)
        {
            var output = Channel.CreateUnbounded <(long batchId, string productId)>();

            Task.Run(async() =>
            {
                try
                {
                    async Task <ProductsCustomBatchRequest> RequestAsync(GoogleShoppingOptions options)
                    {
                        var batchRequest = new ProductsCustomBatchRequest
                        {
                            Entries = new List <ProductsCustomBatchRequestEntry>()
                        };

                        var batchId = 0;
                        while (await channel.WaitToReadAsync(cancellationToken))
                        {
                            var item = await channel.ReadAsync(cancellationToken);

                            var entry = new ProductsCustomBatchRequestEntry
                            {
                                BatchId    = batchId,
                                MerchantId = options.MerchantId,
                                Method     = "delete",
                                ProductId  = item
                            };
                            batchRequest.Entries.Add(entry);
                            ++batchId;
                        }

                        return(batchRequest);
                    }

                    var response = await ExecuteBatchAsync(RequestAsync, cancellationToken);

                    if (response.Kind == "content#productsCustomBatchResponse")
                    {
                        for (var i = 0; i < response.Entries.Count; i++)
                        {
                            var errors    = response.Entries[i].Errors;
                            var flatError = string.Empty;
                            if (errors != null)
                            {
                                for (var j = 0; j < errors.ErrorsValue.Count; j++)
                                {
                                    flatError += errors.ErrorsValue[j].ToString();
                                }
                            }
                            else
                            {
                                _logger.LogDebug("Product deleted, batchId {0}", response.Entries[i].BatchId);
                            }

                            await output.Writer.WriteAsync((response.Entries[i].BatchId ?? 0, flatError), cancellationToken);
                        }
                    }
                    else
                    {
                        _logger.LogError("There was an error. Response: {response}", response);
                    }
                }
                finally
                {
                    output.Writer.Complete();
                }
            });

            return(output);
        }