Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.IO;
- using Microsoft.VisualBasic.FileIO;
- namespace WarehouseIntegration
- {
- class Program
- {
- #region Fields definition
- // Panel Login data
- private static string panelLogin = "----------------";
- private static string panelPassword = "--------------";
- private static string shopName = "elampki";
- // FTP Login data
- private static string ftpUsername = "--------------";
- private static string ftpPassword = "90QOkK5Mf9";
- private static string ftpServer = "ftp://94.152.8.59";
- // List of products from CSV file
- private static List<Product> csvProductList = new List<Product>();
- // List of products to update
- private static List<Product> updatedProductList = new List<Product>();
- #endregion
- static void Main(string[] args)
- {
- LogWriter writer = new LogWriter();
- writer.ClearLog();
- getProductsFromCSV(getFTPFileURI(ftpServer));
- compareWithProductsFromAPI();
- foreach(Product p in updatedProductList)
- {
- //Console.WriteLine(p.EanNumber.ToString() + " " + p.CatalogueNumber.ToString() + " " + p.Quantity.ToString() + " " + Convert.ToString(p.DeliveryDate));
- }
- setProducts.responseType response = updateShopProducts(37);
- response.result = new setProducts.resultType();
- response.result.products = new setProducts.productResultType[1];
- response.result.products[0] = new setProducts.productResultType();
- response.result.products[0].details = new setProducts.detailResultType[1];
- response.result.products[0].details[0] = new setProducts.detailResultType();
- Console.WriteLine(response.result.products[0].details[0].shop_id);
- Console.ReadKey();
- }
- // Method for obtaining products
- public static getProducts.responseType GetShopProductsByProducer(string producerName)
- {
- // Service Client Object
- getProducts.getProductsService service = new getProducts.getProductsService();
- // Gateway Service address
- service.Url = "http://" + shopName + ".iai-shop.com/edi/api-getproducts.php";
- // Request Object
- getProducts.requestType request = new getProducts.requestType();
- // Authentication Object
- request.authenticate = new getProducts.authenticateType();
- request.authenticate.system_login = panelLogin;
- request.authenticate.system_key = Authenticate.GenerateKey(Authenticate.HashPassword(panelPassword));
- // Product Search Parameteters Object
- request.@params = new getProducts.paramsType();
- // Number of products returned in one API request (max: 100)
- request.@params.results_limit = 80;
- request.@params.results_limitSpecified = true;
- // Number of page with results
- request.@params.results_page = 0;
- request.@params.results_pageSpecified = true;
- // Set parameter for producer ID
- request.@params.producers = new getProducts.producerType[1];
- request.@params.producers[0] = new getProducts.producerType();
- request.@params.producers[0].producer_name = producerName;
- // Return Products
- return (service.getProducts(request));
- }
- public static setProducts.responseType updateShopProducts(int productID)
- {
- // Service Client object
- setProducts.setProductsService service = new setProducts.setProductsService();
- // Gateway Service address
- service.Url = "http://elampki.iai-shop.com/edi/api-setproducts.php";
- // Request object
- setProducts.requestType request = new setProducts.requestType();
- // Authentication Object
- request.authenticate = new setProducts.authenticateType();
- request.authenticate.system_login = panelLogin;
- request.authenticate.system_key = Authenticate.GenerateKey(Authenticate.HashPassword(panelPassword));
- // Product Set parameters Object
- request.@params = new setProducts.paramsType();
- // Let only edit products, without creating new ones
- request.@params.settings = new setProducts.settingsType();
- request.@params.settings.modification_type = "edit";
- /*
- // Prepare array for each product
- request.@params.products = new setProducts.productType[productsToUpdate.Count];
- // Go through products to update and set aproppriate parameters
- for (int i = 0; i < productsToUpdate.Count; i++)
- {
- request.@params.products[i] = new setProducts.productType();
- request.@params.products[i].id = productsToUpdate[i].ID;
- request.@params.products[i].availability_management_type = new setProducts.stockTypeQuantityMode();
- request.@params.products[i].availability_management_type = setProducts.stockTypeQuantityMode.manual;
- request.@params.products[i].sizes = new setProducts.sizeType[1];
- request.@params.products[i].sizes[0] = new setProducts.sizeType();
- request.@params.products[i].sizes[0].quantity = new setProducts.quantityType();
- request.@params.products[i].sizes[0].quantity.stocks = new setProducts.stockType[1];
- request.@params.products[i].sizes[0].quantity.stocks[0] = new setProducts.stockType();
- request.@params.products[i].sizes[0].quantity.stocks[0].quantity = -1;
- request.@params.products[i].delivery_time = new setProducts.deliveryTimeType();
- request.@params.products[i].delivery_time.change_mode = setProducts.changeModeType.product;
- request.@params.products[i].delivery_time.change_modeSpecified = true;
- request.@params.products[i].delivery_time.value = 15;
- request.@params.products[i].delivery_time.valueSpecified = true;
- }
- */
- request.@params.products = new setProducts.productType[1] { new setProducts.productType() };
- return (service.setProducts(request));
- }
- // Method for obtaining dynamic file name from FTP server
- public static string getFTPFileURI(string ftpAddress)
- {
- // Setup FTP Request
- FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddress);
- ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
- ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
- // Setup Response Stream
- FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
- Stream responseStream = response.GetResponseStream();
- StreamReader reader = new StreamReader(responseStream);
- // Variable with return value (so I can close the stream and reader)
- string output = ftpAddress + "/" + reader.ReadToEnd();
- // Cleanup and close streams
- reader.Close();
- responseStream.Close();
- response.Close();
- // Return results
- return output;
- }
- public static void getProductsFromCSV(string ftpFileAddress)
- {
- // Setup FTP Request
- FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFileAddress);
- ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
- ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
- FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
- // Setup Response Stream (encoding is ANSI, left as 'Default')
- Stream responseStream = response.GetResponseStream();
- // Text parser
- using (TextFieldParser parser = new TextFieldParser(responseStream))
- {
- // Text parser settings
- parser.SetDelimiters(new string[] { "," });
- parser.HasFieldsEnclosedInQuotes = false;
- // Text tokenization logic & file parsing
- while (true)
- {
- //Initialize Field Tokenization
- string[] fields = parser.ReadFields();
- // Escape function, since eof is bugged
- // Warning: Corrupted file will fuck up the process!
- // Make sure that the file doesn't have white lines in the middle.
- if (fields == null)
- break;
- // Define columns
- Int64 eanNumber = Int64.Parse(fields[0]);
- int catalogueNumber = int.Parse(fields[1]);
- double quantity = double.Parse(fields[2], System.Globalization.CultureInfo.InvariantCulture);
- //Date definition logic; handling NULLs with Nullable<DateTime>
- string dateFormat = "dd/MM/yyyy";
- Nullable<DateTime> availabilityDate = new Nullable<DateTime>();
- DateTime parsedAvailabilityDate = new DateTime();
- if (!string.IsNullOrEmpty(fields[3]) && Char.Parse(fields[3].Substring(0,1)) != 0x00)
- {
- DateTime.TryParseExact(fields[3], dateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedAvailabilityDate);
- availabilityDate = parsedAvailabilityDate;
- }
- else
- {
- availabilityDate = null;
- }
- // Add products to list
- Product product = new Product(eanNumber, catalogueNumber, quantity, availabilityDate);
- csvProductList.Add(product);
- }
- }
- // Clean up and close streams
- responseStream.Close();
- response.Close();
- }
- // Method for obtaining list of products
- public static void compareWithProductsFromAPI()
- {
- // List that holds products' IDs that failed to parse
- List<int> failedProductList = new List<int>();
- //producer ID for producer: 'Nowodvorski Lighting'
- string producerName = "Nowodvorski Lighting";
- // Call the request method to the API
- getProducts.responseType response = GetShopProductsByProducer(producerName);
- // Go through responses - products in shop
- foreach (var productReturn in response.products)
- {
- // Define product parameters
- int id;
- Int64 eanNumber;
- int catalogueNumber;
- double quantity = 0;
- // Set ID
- id = productReturn.id;
- // Handling empty / bad EAN's
- if (!string.IsNullOrEmpty(productReturn.note) && Char.Parse(productReturn.note.Substring(0, 1)) != 0x00)
- {
- eanNumber = Int64.Parse(productReturn.note);
- }
- else
- {
- // Set EAN to 0 to avoid conflict
- eanNumber = 0;
- // Handling message to logs to inform about problem
- int shopProductID = productReturn.id;
- LogWriter log2 = new LogWriter("Produkt o ID: " + shopProductID + " ma nieprawidłowy numer EAN.");
- }
- // Handling empty / bad product catalogue numbers
- if (!string.IsNullOrEmpty(productReturn.code) && Char.Parse(productReturn.code.Substring(0, 1)) != 0x00)
- {
- catalogueNumber = int.Parse(productReturn.code);
- }
- else
- {
- // Set Catalogue number to 0 to avoid conflict
- catalogueNumber = 0;
- // Handling message to logs to inform about problem
- LogWriter log2 = new LogWriter("Produkt o ID: " + id + " ma nieprawidłowy numer katalogowy.");
- }
- // No need for a proper availability date - will be changed anyways
- Nullable<DateTime> availabilityDate = null;
- // Construct shop product
- Product shopProduct = new Product(eanNumber, catalogueNumber, quantity, availabilityDate);
- ///Console.WriteLine(shopProduct.EanNumber.ToString() + " " + shopProduct.CatalogueNumber.ToString() + " ");
- // Find equivalent product in a list from CSV by unique EAN number
- Product csvProduct = csvProductList.Find(x => x.EanNumber == shopProduct.EanNumber);
- // dump CSV data to create an updated product
- if (csvProduct != null)
- {
- quantity = csvProduct.Quantity;
- availabilityDate = csvProduct.DeliveryDate;
- Product updatedProduct = new Product(id, eanNumber, catalogueNumber, quantity, availabilityDate);
- updatedProductList.Add(updatedProduct);
- }
- // Products were not found in CSV list, thus are incorrect and need to be fixed
- // Add to failed list, merge and log later
- else
- {
- failedProductList.Add(productReturn.id);
- }
- }
- // Log failed products
- string failedIDs = "";
- foreach (int shopProductID in failedProductList)
- {
- failedIDs += shopProductID + ", ";
- }
- if (failedIDs != "")
- {
- LogWriter log1 = new LogWriter("ID produktów, których porównanie nie powiodło się: " + failedIDs);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement