Esempio n. 1
0
 public AkeneoCategory CreateNewCategory(AkeneoCategory category, AkeneoProduct product)
 {
     try
     {
         _logger.info($"Creating category {category.CategoryName} : {product.productName} -> start");
         IBaseRequestHandler <NameValueCollection, WebClientHeader> httpManager = new BaseWebClientWriter();
         var _c = new AkeneoBaseCategoriesIndexerConverter();
         category.CategoryId = category.CategoryName.Trim().ToLower().Replace(" ", "_").Replace("-", "_").Replace("/", "_").Replace("?", "_").Replace(".", "_").Replace(",", "_").Replace("&", "_");
         AkeneoIndexedCategoriesDtoEmbedCollectionItem dtoCat = _c.ConvertToDtoEntity(category);
         if (!ReferenceEquals(dtoCat, null) &&
             !ReferenceEquals(dtoCat.CategoryCode, null) &&
             !ReferenceEquals(dtoCat.CategoriesLocales, null) &&
             !ReferenceEquals(dtoCat.CategoriesLocales.Count, 0))
         {
             var EncodedContent = JsonConvert.SerializeObject(dtoCat);
             httpManager.AddHeader(new WebClientHeader("Authorization", $"Bearer {akeneoAuthInfo.access_token}"));
             httpManager.AddBodyParameter(EncodedContent);
             httpManager.PostDataAsStringContext($"{Akeneo.BaseAkeneoUrl}{Akeneo.AkeneoCategoryListUrl}");
             return(category);
         }
         return(null);
         //AkeneoIndexedCategoriesDtoEmbedCollectionItem
     }
     catch (Exception e)
     {
         _logger.error($"{category.CategoryName} -> {product.productName} Error in creating akeneo category: {e.Message} -> {e.StackTrace}");
         return(null);
     }
 }
Esempio n. 2
0
        private void Connect(object obj)
        {
            _logger.info("Akeneo -> connecting");
            IBaseRequestHandler <NameValueCollection, WebClientHeader> httpManager = new BaseWebClientWriter();

            akeneoStatus = BaseServicesStatuses.ServiceLaunching;
            var bytes = System.Text.Encoding.UTF8.GetBytes($"{Akeneo.BaseAkeneoClientId}:{Akeneo.BaseAkeneoSecretKey}");
            var auth  = System.Convert.ToBase64String(bytes).ToString();

            var auth_data = new NameValueCollection();

            auth_data.Add("grant_type", Akeneo.AkeneoPasswordGrantType);
            auth_data.Add("username", Akeneo.BaseAkeneoUserName);
            auth_data.Add("password", Akeneo.BaseAkeneoPassword);

            httpManager.AddBodyParameter(auth_data);
            httpManager.AddHeader(new WebClientHeader("Authorization", $"Basic {auth}"));

            var akeneoBaseResponse = String.Empty;

            try
            {
                akeneoBaseResponse = httpManager.PostData($"{Akeneo.BaseAkeneoUrl}{Akeneo.AkeneoAuthUrl}");
            }
            catch (Exception e)
            {
                akeneoStatus = BaseServicesStatuses.ServiceError;
                _logger.error(e.Message);
                return;
            }

            try
            {
                var akeneoJson =
                    JsonConvert.DeserializeObject <AkeneoAuthEntity>(akeneoBaseResponse);
                if (akeneoJson.access_token.Equals(String.Empty) || akeneoJson.access_token == null)
                {
                    akeneoStatus = BaseServicesStatuses.ServiceError;
                    _logger.error("Cannot obtain new token from Akeneo's API!");
                }
                else
                {
                    akeneoStatus = BaseServicesStatuses.ServiceLaunched;
                    var timer = new TimerCallback(Connect);
                    AkeneoUpdaterTimer = new Timer(timer, null, akeneoJson.expires_in * 1000 - 1, akeneoJson.expires_in * 1000);
                    akeneoAuthInfo     = akeneoJson;
                }
            }
            catch (Exception e)
            {
                akeneoStatus = BaseServicesStatuses.ServiceError;
                _logger.error(e.Message);
            }
        }
Esempio n. 3
0
 public bool BaseGet(AkeneoProduct product, string requestUrl)
 {
     try
     {
         IBaseRequestHandler <NameValueCollection, WebClientHeader> httpManager = new BaseWebClientWriter();
         httpManager.GetData(requestUrl, new WebClientHeader("", ""));
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public void ListenerThread(string requestUrl)
        {
            ProcessStatus = (int)AkeneoProductIndexerStatuses.ListingInProgress;
            HttpManager   = new BaseWebClientWriter();
            try
            {
                var response = HttpManager.GetData(requestUrl, new WebClientHeader("Authorization", $"Bearer {AuthToken}"));
                AkeneoIndexedProductDto dto = JsonConvert.DeserializeObject <AkeneoIndexedProductDto>(response);
                if (dto.LinksCollection.NextLink != null)
                {
                    var thread = new Thread(() =>
                    {
                        ListenerThread(dto.LinksCollection.NextLink.Href);
                    });
                    thread.Start();
                }

                if (dto.Embed.ItemsCollection != null && dto.Embed.ItemsCollection.Count > 0)
                {
                    var converter = new AkeneoBaseProductIndexerConverter();
                    foreach (var selected in dto.Embed.ItemsCollection)
                    {
                        try
                        {
                            var tempProductStorage = converter.ConvertToApplicationEntity(selected);
                            lock (RequestList)
                            {
                                RequestList.Add(tempProductStorage);
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.error(
                                $"(AkeneoBaseProductIndexerConverter exception): Cannot convert dto entity:  {e.Message}");
                        }
                    }
                }

                if (dto.LinksCollection.NextLink == null)
                {
                    ProcessStatus = (int)AkeneoProductIndexerStatuses.ListingFinished;
                    InvokeOnFinishedListing();
                }
            }
            catch (Exception e)
            {
                _logger.error(e.Message);
            }
        }
 public void ListenerThread(string requestUrl)
 {
     ProcessStatus = AkeneoProductIndexerStatuses.ListingInProgress;
     HttpManager   = new BaseWebClientWriter();
     try
     {
         var data = HttpManager.GetData(requestUrl, new WebClientHeader("Authorization", $"Bearer {AuthToken}"));
         AkeneoIndexedCategoriesDto dto = JsonConvert.DeserializeObject <AkeneoIndexedCategoriesDto>(data);
         if (!ReferenceEquals(dto.LinksCollection.NextLink, null))
         {
             new Thread(() => {
                 ListenerThread(dto.LinksCollection.NextLink.Href);
             }).Start();
         }
         if (dto.Embed.ItemsCollection.Count > 0)
         {
             foreach (var selected in dto.Embed.ItemsCollection)
             {
                 var _c = new AkeneoBaseCategoriesIndexerConverter();
                 try
                 {
                     var _t = _c.ConvertToApplicationEntity(selected);
                     lock (RequestList)
                     {
                         RequestList.Add(_t);
                     }
                 }
                 catch (Exception e)
                 {
                     _l.error($"AkeneoBaseCategoriesListener exception: cannot convert dto entity to application entity: {e.Message} -> {e.StackTrace}");
                 }
             }
         }
         if (ReferenceEquals(dto.LinksCollection.NextLink, null))
         {
             ProcessStatus = AkeneoProductIndexerStatuses.ListingFinished;
             InvokeOnFinishedListing();
         }
     }
     catch (Exception e)
     {
         _l.error($"Akeneo categories indexer: error occured - {e.Message} -> {e.StackTrace}");
     }
 }
Esempio n. 6
0
        public AkeneoBaseWriter(LogsWriter logger, List <CollectionsAsignerEntity> collectionRules, List <VendorsAssignerEntity> vendorsRules)
        {
            ServiceName  = "AkeneoService";
            akeneoStatus = BaseServicesStatuses.ServiceNotLaunched;
            _logger      = logger;

            httpManager = new BaseWebClientWriter();

            Akeneo = new AkeneoBaseInformation();
            Akeneo.BaseAkeneoUrl       = "http://localhost:8080/";
            Akeneo.BaseAkeneoUserName  = "******";
            Akeneo.BaseAkeneoPassword  = "******";
            Akeneo.BaseAkeneoClientId  = "1_3001g7f521uso44g0ggk8wk04c0ws0co8cc0ok0g08skg8k4k0";
            Akeneo.BaseAkeneoSecretKey = "4yde7syn96w448cockwwoo0oso00cskckkkwk888w40888gcg8";

            Connect(new object());

            CategoriesListener = new AkeneoBaseCategoriesListener(Akeneo, akeneoAuthInfo.access_token, logger);
            CategoriesListener.OnFinishedListing += AkeneoCategoriesListingCallback;

            ProductIndexer = new AkeneoBaseProductIndexer(Akeneo, akeneoAuthInfo.access_token, logger);
            ProductIndexer.OnFinishedListing += AkeneoListingReadyCallback;

            if (!ReferenceEquals(collectionRules, null))
            {
                CollectionRules = collectionRules;
            }
            else
            {
                collectionRules = new List <CollectionsAsignerEntity>();
                _logger.warn("Akeneo: Empty collections rules received.");
            }

            if (!ReferenceEquals(vendorsRules, null))
            {
                VendorsRules = vendorsRules;
            }
            else
            {
                vendorsRules = new List <VendorsAssignerEntity>();
                _logger.warn("Akeneo: Empty vendors rules received");
            }
        }
Esempio n. 7
0
 protected bool MakeProductOutOfStock(BaseShopifyProductEntity product)
 {
     _l.info($"Shopify service -> WebClient: start.");
     try
     {
         _l.info($"Shopify service -> WebClient: started with success code.");
         var httpManager = new BaseWebClientWriter();
         _l.info($"Shopify service -> WebClient: creating auth credentials");
         var credentials = new NetworkCredential(Settings.ShopifyApiKey, Settings.ShopifyApiToken);
         _l.info($"Shopify service -> WebClient: auth credentials successfully created");
         _l.info($"Shopify service -> WebClient: sending request to {Settings.ShopifyApiProtocol}{Settings.ShopifyStoreUrl}{Settings.ShopifyBaseProuctsUpdateUrl}{product.ProductId}{Settings.ShopifyBaseProuctsUpdateUrlExtension}");
         string productEncoded = httpManager.GetData($"{Settings.ShopifyApiProtocol}{Settings.ShopifyStoreUrl}{Settings.ShopifyBaseProuctsUpdateUrl}{product.ProductId}{Settings.ShopifyBaseProuctsUpdateUrlExtension}", credentials);
         _l.info("Shopify service -> request finished, checking results...");
         if (!ReferenceEquals(productEncoded, null) && !productEncoded.Equals(String.Empty))
         {
             _l.info("Shopify service: decoding json string to application dto");
             ShopifyBaseDtoObject productS = JsonConvert.DeserializeObject <ShopifyBaseDtoObject>(productEncoded);
             _l.info("Shopify service: json string successfully decoded to application dto");
             _l.info($"Shopify service: creating body for request.");
             string body = String.Concat("{\"product\":{\"id\":", product.ProductId, ", \"variants\":[{", $"\"id\":{productS.Product.ProductVariants.FirstOrDefault().VariantIdentifier}, \"inventory_policy\": \"deny\", \"inventory_quantity\":0, \"inventory_management\": \"shopify\"", "}]}}");
             _l.info($"Shopify service: body request successfuly created -> {body}");
             _l.info($"Shopify service -> WebClient: adding string body context to the request.");
             httpManager.AddBodyParameter(body);
             _l.info($"Shopify service -> WebClient: body context successfully added to the request.");
             _l.info($"Shopify service -> WebClient: sending request to the shopify");
             var response = httpManager.PutData($"{Settings.ShopifyApiProtocol}{Settings.ShopifyStoreUrl}{Settings.ShopifyBaseProuctsUpdateUrl}{product.ProductId}{Settings.ShopifyBaseProuctsUpdateUrlExtension}", credentials);
             _l.info($"Shopify service -> WebClient: request successfully processed with success code!");
             return(true);
         }
         else
         {
             _l.error($"Shopify service: fatal, cannot vaidate response from {Settings.ShopifyApiProtocol}{Settings.ShopifyStoreUrl}{Settings.ShopifyBaseProuctsUpdateUrl}{product.ProductId}{Settings.ShopifyBaseProuctsUpdateUrlExtension}");
             return(false);
         }
     }
     catch (Exception e)
     {
         _l.error($"Shopify service: fatal, {e.Message} -> {e.StackTrace}");
         return(false);
     }
 }
Esempio n. 8
0
        public bool BaseSend(AkeneoProduct product, string requestUrl, string protocol)
        {
            IBaseRequestHandler <NameValueCollection, WebClientHeader> httpManager = new BaseWebClientWriter();
            var EntitiesConverter = new AkeneoBaseProductEntityConverter();
            var AkeneoProductDto  = EntitiesConverter.ConvertToDtoEntity(product);

            try
            {
                var EncodedContent = JsonConvert.SerializeObject(AkeneoProductDto);
                httpManager.AddHeader(new WebClientHeader("Authorization", $"Bearer {akeneoAuthInfo.access_token}"));
                httpManager.AddBodyParameter(EncodedContent);
                var akeneoBaseResponse = String.Empty;
                try
                {
                    switch (protocol)
                    {
                    case "POST":
                        akeneoBaseResponse = httpManager.PostDataAsStringContext($"{Akeneo.BaseAkeneoUrl}{Akeneo.AkeneoProductCreateUrl}");
                        break;

                    case "PATCH":
                        akeneoBaseResponse = httpManager.PatchData(requestUrl);
                        break;
                    }

                    _logger.info($"(Creating) Product {product.productName} successfully created! Akeneo response is: {akeneoBaseResponse}");
                }
                catch (Exception e)
                {
                    _logger.error($"(Creating) Some error detected during creating product ({product.productName}), Akeneo response is: {e.Message}. ({product.productName})");
                    return(false);
                }
                return(true);
            }
            catch (Exception e)
            {
                _logger.error($"(Creating): (Exception): error detected, during preparing information for product {product.productName} -> {e.Message}.");
                return(false);
            }
        }
Esempio n. 9
0
        public void ProductsListenerThread(string requestUrl)
        {
            var httpManager = new BaseWebClientWriter();

            try
            {
                var credentials     = new NetworkCredential(Settings.ShopifyApiKey, Settings.ShopifyApiToken);
                var ShopifyResponse = httpManager.GetData(requestUrl, credentials);
                var lastHeader      = httpManager.LastHeader;
                if (lastHeader.Contains("next"))
                {
                    string next = lastHeader.Replace("<", "").Replace(">; rel=\"next\"", "");
                    new Thread(() => {
                        ProductsListenerThread(next);
                    }).Start();
                }
                if (!ShopifyResponse.Equals(String.Empty))
                {
                    var productsList = JsonConvert.DeserializeObject <ShopifyBaseDtoObject>(ShopifyResponse);
                    if (!ReferenceEquals(productsList.ProductsCollection, null) && productsList.ProductsCollection.Count > 0)
                    {
                        foreach (var product in productsList.ProductsCollection)
                        {
                            ShopifyEntitesBaseConverter _c = new ShopifyEntitesBaseConverter();
                            ShopifyProductsList.Add(_c.ConvertToApplicationEntity(product));
                        }
                    }
                }
                if (!lastHeader.Contains("next"))
                {
                    InvokeOnShopifyIndexationFinished();
                }
            } catch (Exception e)
            {
                _l.error($"Error during sending request to {requestUrl} -> {e.Message} : {e.StackTrace}");
            }
        }