Advertisement
Guest User

apiapi

a guest
May 6th, 2016
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.28 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.IO;
  5. using Microsoft.VisualBasic.FileIO;
  6.  
  7. namespace WarehouseIntegration
  8. {
  9. class Program
  10. {
  11.  
  12. #region Fields definition
  13. // Panel Login data
  14. private static string panelLogin = "----------------";
  15. private static string panelPassword = "--------------";
  16. private static string shopName = "elampki";
  17.  
  18. // FTP Login data
  19. private static string ftpUsername = "--------------";
  20. private static string ftpPassword = "90QOkK5Mf9";
  21. private static string ftpServer = "ftp://94.152.8.59";
  22.  
  23. // List of products from CSV file
  24. private static List<Product> csvProductList = new List<Product>();
  25.  
  26. // List of products to update
  27. private static List<Product> updatedProductList = new List<Product>();
  28.  
  29. #endregion
  30.  
  31. static void Main(string[] args)
  32. {
  33. LogWriter writer = new LogWriter();
  34. writer.ClearLog();
  35. getProductsFromCSV(getFTPFileURI(ftpServer));
  36. compareWithProductsFromAPI();
  37. foreach(Product p in updatedProductList)
  38. {
  39. //Console.WriteLine(p.EanNumber.ToString() + " " + p.CatalogueNumber.ToString() + " " + p.Quantity.ToString() + " " + Convert.ToString(p.DeliveryDate));
  40. }
  41.  
  42. setProducts.responseType response = updateShopProducts(37);
  43. response.result = new setProducts.resultType();
  44. response.result.products = new setProducts.productResultType[1];
  45. response.result.products[0] = new setProducts.productResultType();
  46. response.result.products[0].details = new setProducts.detailResultType[1];
  47. response.result.products[0].details[0] = new setProducts.detailResultType();
  48. Console.WriteLine(response.result.products[0].details[0].shop_id);
  49. Console.ReadKey();
  50. }
  51.  
  52. // Method for obtaining products
  53. public static getProducts.responseType GetShopProductsByProducer(string producerName)
  54. {
  55. // Service Client Object
  56. getProducts.getProductsService service = new getProducts.getProductsService();
  57.  
  58. // Gateway Service address
  59. service.Url = "http://" + shopName + ".iai-shop.com/edi/api-getproducts.php";
  60.  
  61. // Request Object
  62. getProducts.requestType request = new getProducts.requestType();
  63.  
  64. // Authentication Object
  65. request.authenticate = new getProducts.authenticateType();
  66. request.authenticate.system_login = panelLogin;
  67. request.authenticate.system_key = Authenticate.GenerateKey(Authenticate.HashPassword(panelPassword));
  68.  
  69. // Product Search Parameteters Object
  70. request.@params = new getProducts.paramsType();
  71.  
  72. // Number of products returned in one API request (max: 100)
  73. request.@params.results_limit = 80;
  74. request.@params.results_limitSpecified = true;
  75.  
  76. // Number of page with results
  77. request.@params.results_page = 0;
  78. request.@params.results_pageSpecified = true;
  79.  
  80. // Set parameter for producer ID
  81. request.@params.producers = new getProducts.producerType[1];
  82. request.@params.producers[0] = new getProducts.producerType();
  83. request.@params.producers[0].producer_name = producerName;
  84.  
  85. // Return Products
  86. return (service.getProducts(request));
  87. }
  88.  
  89. public static setProducts.responseType updateShopProducts(int productID)
  90. {
  91. // Service Client object
  92. setProducts.setProductsService service = new setProducts.setProductsService();
  93.  
  94. // Gateway Service address
  95. service.Url = "http://elampki.iai-shop.com/edi/api-setproducts.php";
  96.  
  97. // Request object
  98. setProducts.requestType request = new setProducts.requestType();
  99.  
  100. // Authentication Object
  101. request.authenticate = new setProducts.authenticateType();
  102. request.authenticate.system_login = panelLogin;
  103. request.authenticate.system_key = Authenticate.GenerateKey(Authenticate.HashPassword(panelPassword));
  104.  
  105. // Product Set parameters Object
  106. request.@params = new setProducts.paramsType();
  107.  
  108. // Let only edit products, without creating new ones
  109. request.@params.settings = new setProducts.settingsType();
  110. request.@params.settings.modification_type = "edit";
  111. /*
  112. // Prepare array for each product
  113. request.@params.products = new setProducts.productType[productsToUpdate.Count];
  114.  
  115. // Go through products to update and set aproppriate parameters
  116. for (int i = 0; i < productsToUpdate.Count; i++)
  117. {
  118. request.@params.products[i] = new setProducts.productType();
  119. request.@params.products[i].id = productsToUpdate[i].ID;
  120.  
  121. request.@params.products[i].availability_management_type = new setProducts.stockTypeQuantityMode();
  122. request.@params.products[i].availability_management_type = setProducts.stockTypeQuantityMode.manual;
  123.  
  124. request.@params.products[i].sizes = new setProducts.sizeType[1];
  125. request.@params.products[i].sizes[0] = new setProducts.sizeType();
  126. request.@params.products[i].sizes[0].quantity = new setProducts.quantityType();
  127. request.@params.products[i].sizes[0].quantity.stocks = new setProducts.stockType[1];
  128. request.@params.products[i].sizes[0].quantity.stocks[0] = new setProducts.stockType();
  129. request.@params.products[i].sizes[0].quantity.stocks[0].quantity = -1;
  130.  
  131. request.@params.products[i].delivery_time = new setProducts.deliveryTimeType();
  132. request.@params.products[i].delivery_time.change_mode = setProducts.changeModeType.product;
  133. request.@params.products[i].delivery_time.change_modeSpecified = true;
  134. request.@params.products[i].delivery_time.value = 15;
  135. request.@params.products[i].delivery_time.valueSpecified = true;
  136. }
  137. */
  138. request.@params.products = new setProducts.productType[1] { new setProducts.productType() };
  139.  
  140. return (service.setProducts(request));
  141. }
  142.  
  143. // Method for obtaining dynamic file name from FTP server
  144. public static string getFTPFileURI(string ftpAddress)
  145. {
  146. // Setup FTP Request
  147. FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddress);
  148. ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
  149. ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
  150.  
  151. // Setup Response Stream
  152. FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
  153. Stream responseStream = response.GetResponseStream();
  154. StreamReader reader = new StreamReader(responseStream);
  155.  
  156. // Variable with return value (so I can close the stream and reader)
  157. string output = ftpAddress + "/" + reader.ReadToEnd();
  158.  
  159. // Cleanup and close streams
  160. reader.Close();
  161. responseStream.Close();
  162. response.Close();
  163.  
  164. // Return results
  165. return output;
  166.  
  167. }
  168.  
  169. public static void getProductsFromCSV(string ftpFileAddress)
  170. {
  171. // Setup FTP Request
  172. FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFileAddress);
  173. ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
  174. ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
  175. FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
  176.  
  177. // Setup Response Stream (encoding is ANSI, left as 'Default')
  178. Stream responseStream = response.GetResponseStream();
  179.  
  180. // Text parser
  181. using (TextFieldParser parser = new TextFieldParser(responseStream))
  182. {
  183. // Text parser settings
  184. parser.SetDelimiters(new string[] { "," });
  185. parser.HasFieldsEnclosedInQuotes = false;
  186.  
  187. // Text tokenization logic & file parsing
  188. while (true)
  189. {
  190. //Initialize Field Tokenization
  191. string[] fields = parser.ReadFields();
  192.  
  193. // Escape function, since eof is bugged
  194. // Warning: Corrupted file will fuck up the process!
  195. // Make sure that the file doesn't have white lines in the middle.
  196. if (fields == null)
  197. break;
  198.  
  199. // Define columns
  200. Int64 eanNumber = Int64.Parse(fields[0]);
  201. int catalogueNumber = int.Parse(fields[1]);
  202. double quantity = double.Parse(fields[2], System.Globalization.CultureInfo.InvariantCulture);
  203.  
  204. //Date definition logic; handling NULLs with Nullable<DateTime>
  205. string dateFormat = "dd/MM/yyyy";
  206. Nullable<DateTime> availabilityDate = new Nullable<DateTime>();
  207. DateTime parsedAvailabilityDate = new DateTime();
  208.  
  209. if (!string.IsNullOrEmpty(fields[3]) && Char.Parse(fields[3].Substring(0,1)) != 0x00)
  210. {
  211. DateTime.TryParseExact(fields[3], dateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedAvailabilityDate);
  212. availabilityDate = parsedAvailabilityDate;
  213. }
  214. else
  215. {
  216. availabilityDate = null;
  217. }
  218.  
  219. // Add products to list
  220. Product product = new Product(eanNumber, catalogueNumber, quantity, availabilityDate);
  221. csvProductList.Add(product);
  222. }
  223. }
  224.  
  225. // Clean up and close streams
  226. responseStream.Close();
  227. response.Close();
  228. }
  229.  
  230. // Method for obtaining list of products
  231. public static void compareWithProductsFromAPI()
  232. {
  233. // List that holds products' IDs that failed to parse
  234. List<int> failedProductList = new List<int>();
  235.  
  236. //producer ID for producer: 'Nowodvorski Lighting'
  237. string producerName = "Nowodvorski Lighting";
  238.  
  239. // Call the request method to the API
  240. getProducts.responseType response = GetShopProductsByProducer(producerName);
  241.  
  242. // Go through responses - products in shop
  243. foreach (var productReturn in response.products)
  244. {
  245. // Define product parameters
  246. int id;
  247. Int64 eanNumber;
  248. int catalogueNumber;
  249. double quantity = 0;
  250.  
  251. // Set ID
  252. id = productReturn.id;
  253.  
  254. // Handling empty / bad EAN's
  255. if (!string.IsNullOrEmpty(productReturn.note) && Char.Parse(productReturn.note.Substring(0, 1)) != 0x00)
  256. {
  257. eanNumber = Int64.Parse(productReturn.note);
  258. }
  259. else
  260. {
  261. // Set EAN to 0 to avoid conflict
  262. eanNumber = 0;
  263.  
  264. // Handling message to logs to inform about problem
  265. int shopProductID = productReturn.id;
  266. LogWriter log2 = new LogWriter("Produkt o ID: " + shopProductID + " ma nieprawidłowy numer EAN.");
  267. }
  268.  
  269. // Handling empty / bad product catalogue numbers
  270. if (!string.IsNullOrEmpty(productReturn.code) && Char.Parse(productReturn.code.Substring(0, 1)) != 0x00)
  271. {
  272. catalogueNumber = int.Parse(productReturn.code);
  273. }
  274. else
  275. {
  276. // Set Catalogue number to 0 to avoid conflict
  277. catalogueNumber = 0;
  278.  
  279. // Handling message to logs to inform about problem
  280. LogWriter log2 = new LogWriter("Produkt o ID: " + id + " ma nieprawidłowy numer katalogowy.");
  281. }
  282.  
  283. // No need for a proper availability date - will be changed anyways
  284. Nullable<DateTime> availabilityDate = null;
  285.  
  286. // Construct shop product
  287. Product shopProduct = new Product(eanNumber, catalogueNumber, quantity, availabilityDate);
  288.  
  289. ///Console.WriteLine(shopProduct.EanNumber.ToString() + " " + shopProduct.CatalogueNumber.ToString() + " ");
  290.  
  291. // Find equivalent product in a list from CSV by unique EAN number
  292. Product csvProduct = csvProductList.Find(x => x.EanNumber == shopProduct.EanNumber);
  293.  
  294. // dump CSV data to create an updated product
  295. if (csvProduct != null)
  296. {
  297. quantity = csvProduct.Quantity;
  298. availabilityDate = csvProduct.DeliveryDate;
  299. Product updatedProduct = new Product(id, eanNumber, catalogueNumber, quantity, availabilityDate);
  300. updatedProductList.Add(updatedProduct);
  301. }
  302. // Products were not found in CSV list, thus are incorrect and need to be fixed
  303. // Add to failed list, merge and log later
  304. else
  305. {
  306. failedProductList.Add(productReturn.id);
  307. }
  308. }
  309.  
  310. // Log failed products
  311. string failedIDs = "";
  312. foreach (int shopProductID in failedProductList)
  313. {
  314. failedIDs += shopProductID + ", ";
  315. }
  316. if (failedIDs != "")
  317. {
  318. LogWriter log1 = new LogWriter("ID produktów, których porównanie nie powiodło się: " + failedIDs);
  319. }
  320. }
  321. }
  322. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement