Beispiel #1
0
        // Very efficient lookups.
        // Can have multiple dictionaries on a single object collection.
        public void Dictionary()
        {
            // lookup:  O(1)
            // modify:  O(1)

            Console.Out.WriteLine("New");
            var dictionary = new Dictionary <int, Thing>();

            dictionary.Print();

            Console.Out.WriteLine("Populated");
            for (int i = 0; i < size; i++)
            {
                dictionary.Add(i, new Thing(string.Format("Item {0}", i)));
            }
            dictionary.Print();

//            Console.Out.WriteLine("Alternative dictionary creation");
//            var dictionary2 = Enumerable.Range(0, size).ToDictionary(
//                x => x,
//                x => new Thing(string.Format("Item {0}", x)));
//            dictionary2.Print();

            Console.Out.WriteLine("Keys");
            dictionary.Keys.Print();

            Console.Out.WriteLine("Values");
            dictionary.Values.Print();
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;

            var episode4 = new Movie("Star Wars: Episode IV", 1977);
            var episode5 = new Movie("Star Wars: Episode V", 1980);
            var episode6 = new Movie("Star Wars: Episode VI", 1983);
            var episode1 = new Movie("Star Wars: Episode I", 1999);
            var episode2 = new Movie("Star Wars: Episode II", 2002);
            var episode3 = new Movie("Star Wars: Episode III", 2005);
            var episode7 = new Movie("Star Wars: Episode VII", 2015);
            var episode8 = new Movie("Star Wars: Episode VIII", 2017);

            IDictionary <int, Movie> chronology = new Dictionary <int, Movie>();

            chronology.Add(1, episode4);
            chronology.Add(2, episode5);
            chronology.Add(3, episode6);

            chronology.Print();

            Console.WriteLine($"Contains the key 1? {chronology.ContainsKey(1)}");

            Console.WriteLine($"Key: 1 {chronology[1]}");

            chronology.TryGetValue(4, out Movie movie);

            Console.WriteLine($"Is the movie null? {movie == null}");

            Console.WriteLine();

            chronology[4] = episode1;

            chronology.Print();
        }
 public void Ensure()
 {
     var dict = new Dictionary<string, int>();
     dict.Ensure("a", 1);
     Assert.AreEqual("([a,1])", dict.Print());
     dict.Ensure("a", 2);
     Assert.AreEqual("([a,2])", dict.Print());
 }
Beispiel #4
0
        static void TestDictionary()
        {
            Dictionary <string, Student> dic = new Dictionary <string, Student>();

            dic.Add("Ivan", new Student {
                Name = "Ivan", Bday = new DateTime(1998, 10, 23)
            });
            dic.Add("Anna", new Student {
                Name = "Anna", Bday = new DateTime(2010, 10, 23)
            });
            dic.Add("Piter", new Student {
                Name = "Piter", Bday = new DateTime(2013, 10, 23)
            });
            dic.Add("Igor", new Student {
                Name = "Igor", Bday = new DateTime(2000, 10, 23)
            });
            //  dic.Add("Igor", new Student { Name = "Igor", Bday = new DateTime(2000, 10, 23) });

            dic["Stepan"] = new Student {
                Name = "Stepan", Bday = new DateTime(1963, 10, 23)
            };

            dic.Print('\n');

            if (dic.ContainsKey("Igor"))
            {
                Console.WriteLine("yes");
            }
            else
            {
                Console.WriteLine("no");
            }

            if (dic.ContainsValue(new Student {
                Name = "Stepan", Bday = new DateTime(1963, 10, 23)
            }))
            {
                Console.WriteLine("yes");
            }
            else
            {
                Console.WriteLine("no");
            }
            Console.WriteLine(dic.Count);
            dic.Remove("Igor");
            dic.Print('\n');
        }
 public void Assoc_IsImmutable()
 {
     var dict = new Dictionary<string, int>();
     dict.Add("a", 1);
     var other = dict.Assoc("b", 2);
     Assert.AreEqual("([a,1])", dict.Print(),
         "Calling Assoc should not change the original dictionary");
 }
        protected void DominatedRow()
        {
Start:
            while (true)
            {
                foreach (var rowA in source)
                {
                    foreach (var rowB in source.Where(r => r.Key != rowA.Key && !rowA.Value.Except(r.Value).Any()))
                    {
                        source.Remove(rowB.Key);
                        Log.Information($"Dominated Row: {{{rowB.Key}}} {source.Print()}");
                        goto Start;
                    }
                }
                break;
            }
        }
        public void FormatDictionary_Properly()
        {
            var entries = new Dictionary <string, int>();

            entries.Add("Andrew", 19);
            entries.Add("Andrew Jr", 13);
            var expectedFormat =
                "KeyValuePair`2" + Environment.NewLine +
                "\tKey = Andrew" + Environment.NewLine +
                "\tValue = 19" + Environment.NewLine +
                "KeyValuePair`2" + Environment.NewLine +
                "\tKey = Andrew Jr" + Environment.NewLine +
                "\tValue = 13" + Environment.NewLine;

            var resultFormat = entries.Print();

            resultFormat.Should().BeEquivalentTo(expectedFormat);
        }
        protected void DominatedColumn()
        {
Start:
            while (true)
            {
                var revSource = source.Reverse();
                foreach (var rowA in revSource)
                {
                    foreach (var rowB in revSource.Where(r => r.Key != rowA.Key && (!r.Value.Except(rowA.Value).Any() || r.Value.Except(rowA.Value).All(v => v < 0)) && !rowA.Value.Any(v => v < 0)))
                    {
                        revSource.Remove(rowB.Key);
                        source = revSource.Reverse();
                        Log.Information($"Dominated Column: {{{rowB.Key}}} {source.Print()}");
                        goto Start;
                    }
                }
                break;
            }
        }
Beispiel #9
0
        internal void Print_WithVariousDictionaries_ReturnsExpectedString()
        {
            // Arrange
            var dict0 = new Dictionary <string, string>();
            var dict1 = new Dictionary <string, string> {
                { "element", "1" }
            };
            var dict2 = new Dictionary <string, string> {
                { "element1", "1" }, { "element2", "2" }
            };

            // Act
            var result0 = dict0.Print();
            var result1 = dict1.Print();
            var result2 = dict2.Print();

            // Assert
            Assert.Equal("{ }", result0);
            Assert.Equal("{ element: 1 }", result1);
            Assert.Equal("{ element1: 1, element2: 2 }", result2);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            string str = "Hello";

            str.Show();
            str.PrintCol();

            string str1 = Console.ReadLine();

            str1.PrintCol();


            List <string> list = new List <string>
            {
                "banana", "apple", "strawberry", "kiwi"
            };

            list.Print();

            List <int> list2 = new List <int>
            {
                1, 5, 7, 8, 10, 3
            };

            Console.WriteLine(list2.Mult());


            Dictionary <int, string> dict = new Dictionary <int, string>
            {
                { 10, "Ivanov" },
                { 32, "Petrov" },
                { 27, "Sidorov" },
                { 18, "Ivanov" }
            };

            dict.Print();
        }
        public void For()
        {
            var idx = new Dictionary<char, int?>();
            idx.Add('a', null);
            idx.Add('b', null);
            idx.Add('c', null);

            "abc".For((i, c) => idx[c] = i);
            Assert.AreEqual("([a,0],[b,1],[c,2])", idx.Print());
        }
Beispiel #12
0
 public static string Print <K, V>(this Dictionary <K, V> source)
 {
     return(Empty(source) ? "{}" : $"{{\"{string.Join(",", source.Print())}\"}}");
 }
Beispiel #13
0
        static void Test3()
        {
            Dictionary <string, int> dic1 = new Dictionary <string, int>();
            Dictionary <string, int> dic2 = new Dictionary <string, int> {
                { "Ivan", 10 },
                { "Piter", 20 },
                { "Inna", 30 },
                { "Anna", 40 },
            };

            //------
            dic1.Print("dic1");
            //------
            dic2.Add("Petro", 50);
            dic2["Stepan"] = 3;
            dic2["Stepan"]++;
            // dic2["Step"]++;
            dic2.Print("dic2");
            if (dic2.ContainsKey("Petro"))
            {
                Console.WriteLine($"E ");
            }
            else
            {
                Console.WriteLine("HEMA");
            }
            List <Student> gr = new List <Student> {
                new Student {
                    Name = "Mark", Bday = new DateTime(1996, 12, 13)
                },
                new Student {
                    Name = "Ivan", Bday = new DateTime(2013, 10, 25)
                },
                new Student {
                    Name = "Oleg", Bday = new DateTime(2015, 1, 16)
                }
            };
            Random random = new Random();
            Dictionary <Student, List <int> > group = new Dictionary <Student, List <int> >();

            foreach (var item in gr)
            {
                List <int> marks = new List <int>();
                for (int i = 0; i < 5; i++)
                {
                    marks.Add(random.Next(2, 6));
                }
                group.Add(item, marks);
            }
            // group.Print("group");
            Console.WriteLine("group");
            Console.WriteLine(new string('-', 35));
            foreach (var item in group)
            {
                //// 1 варіант
                //Console.Write($"{item.Key}");
                //item.Value.Print("","\t");
                //Console.WriteLine(new string('=', 35));
                // 2 варіант
                Console.Write($"{item.Key} ");
                Console.Write(string.Join(", ", item.Value));
                Console.WriteLine("|");
                Console.WriteLine(new string('=', 35));
            }
            Console.WriteLine();
        }
Beispiel #14
0
        /// <summary>
        /// Запуска примера работы со словарем
        /// </summary>
        public static void RunDictionary()
        {
            var dictionary = new Dictionary <IPerson, IPhone>
            {
                {
                    new Employee {
                        Name = "Иван", SurName = "Иванов", Position = "Секретарь"
                    },
                    new Phone {
                        Model = "PXFGH1345", Name = "Philips"
                    }
                },
                {
                    new Employee {
                        Name = "Петр", SurName = "Петров", Position = "Директор"
                    },
                    new Phone {
                        Model = "PXFGH1345", Name = "Philips"
                    }
                },
                {
                    new Student {
                        Name = "Семен", SurName = "Овечкин", Course = 1, Group = "AМ1"
                    },
                    new SmartPhone {
                        Model = "P40 Pro", Name = "Huawei", Os = "Harmony"
                    }
                },
                {
                    new Student {
                        Name = "Ольга", SurName = "Корженова", Course = 1, Group = "AМ1"
                    },
                    new SmartPhone {
                        Model = "10 Max", Name = "IPhone", Os = "IOS"
                    }
                },
                {
                    new Student {
                        Name = "Екатерина", SurName = "Иванова", Course = 4, Group = "BМ1"
                    },
                    new SmartPhone {
                        Model = "S10", Name = "Samsung", Os = "Android"
                    }
                }
            };

            dictionary.Print("Вывод Dictionary");

            var employee = new Employee {
                Name = "Имя1", SurName = "Фамилия1", Position = "Должность1"
            };
            var smartPhone = new SmartPhone {
                Model = "S20", Name = "Samsung", Os = "Android"
            };

            dictionary.Add(employee, smartPhone);

            dictionary.Print("Вывод Dictionary после добавления нового ключа");

            // Попытка вставить дубликат ключа
            try
            {
                var smartPhone1 = new SmartPhone {
                    Model = "7 Pro", Name = "OnePlus", Os = "Adroid"
                };
                dictionary.Add(employee, smartPhone1);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ошибка добавления ключа в словарь - {ex.Message}");
            }

            dictionary.Remove(employee);

            dictionary.Print("Вывод Dictionary после удаления по ключу");
        }
        public void SetVal()
        {
            var dict = new Dictionary<int, string>();
            dict.Add(1, "1");

            dict.SetVal(2, "2");
            Assert.AreEqual("([1,1],[2,2])", dict.Print());
            dict.SetVal(1, "3");
            Assert.AreEqual("([1,3],[2,2])", dict.Print());
        }
 public void Print()
 {
     var d = new Dictionary<string, object>();
     d.Ensure("foo", 1);
     d.Ensure("bar", true);
     // Note - Print should alphabetize the keys
     Assert.AreEqual("([bar,True],[foo,1])", d.Print());
 }
Beispiel #17
0
        public IList <IDictionary <string, object> > GetMainInfoDicList(string html, Action <IDictionary <string, object> > insetTable, bool isFirstPage)
        {
            IList <IDictionary <string, object> > dicList = new List <IDictionary <string, object> >();
            JObject jObject = JObject.Parse(html);
            JArray  jArray;

            if (isFirstPage)
            {
                jArray = JArray.Parse(jObject["ListOrdersResponse"]["ListOrdersResult"]["Orders"]["Order"].ToString());
            }
            else
            {
                jArray = JArray.Parse(jObject["ListOrdersByNextTokenResponse"]["ListOrdersByNextTokenResult"]["Orders"]["Order"].ToString());
            }
            foreach (var jToken in jArray)
            {
                var latestShipDate         = jToken["LatestShipDate"]?.ToString();
                var orderType              = jToken["OrderType"]?.ToString();
                var purchaseDate           = jToken["PurchaseDate"]?.ToString();
                var buyerEmail             = jToken["BuyerEmail"]?.ToString();
                var amazonOrderId          = jToken["AmazonOrderId"]?.ToString();
                var lastUpdateDate         = jToken["LastUpdateDate"]?.ToString();
                var isReplacementOrder     = jToken["IsReplacementOrder"]?.ToString();
                var shipServiceLevel       = jToken["ShipServiceLevel"]?.ToString();
                var numberOfItemsShipped   = jToken["NumberOfItemsShipped"]?.ToString();
                var orderStatus            = jToken["OrderStatus"]?.ToString();
                var salesChannel           = jToken["SalesChannel"]?.ToString();
                var isBusinessOrder        = jToken["IsBusinessOrder"]?.ToString();
                var numberOfItemsUnshipped = jToken["NumberOfItemsUnshipped"]?.ToString();
                var paymentMethodDetails   = jToken["PaymentMethodDetails"]?.ToString();
                var buyerName              = jToken["BuyerName"]?.ToString();
                var orderTotal             = jToken["OrderTotal"]?.ToString();
                var isPremiumOrder         = jToken["IsPremiumOrder"]?.ToString();
                var earliestShipDate       = jToken["EarliestShipDate"]?.ToString();
                var marketplaceId          = jToken["MarketplaceId"]?.ToString();
                var fulfillmentChannel     = jToken["FulfillmentChannel"]?.ToString();
                var paymentMethod          = jToken["PaymentMethod"]?.ToString();
                var shippingAddress        = jToken["ShippingAddress"]?.ToString();
                var isPrime = jToken["IsPrime"]?.ToString();
                var shipmentServiceLevelCategory = jToken["ShipmentServiceLevelCategory"]?.ToString();
                var sellerOrderId = jToken["SellerOrderId"]?.ToString();

                IDictionary <string, object> dic = new Dictionary <string, object>
                {
                    { "latestShipDate", latestShipDate },
                    { "orderType", orderType },
                    { "purchaseDate", purchaseDate },
                    { "buyerEmail", buyerEmail },
                    { "amazonOrderId", amazonOrderId },
                    { "lastUpdateDate", lastUpdateDate },
                    { "isReplacementOrder", isReplacementOrder },
                    { "shipServiceLevel", shipServiceLevel },
                    { "numberOfItemsShipped", numberOfItemsShipped },
                    { "orderStatus", orderStatus },
                    { "salesChannel", salesChannel },
                    { "isBusinessOrder", isBusinessOrder },
                    { "numberOfItemsUnshipped", numberOfItemsUnshipped },
                    { "paymentMethodDetails", paymentMethodDetails },
                    { "buyerName", buyerName },
                    { "orderTotal", orderTotal },
                    { "isPremiumOrder", isPremiumOrder },
                    { "earliestShipDate", earliestShipDate },
                    { "marketplaceId", marketplaceId },
                    { "fulfillmentChannel", fulfillmentChannel },
                    { "paymentMethod", paymentMethod },
                    { "shippingAddress", shippingAddress },
                    { "isPrime", isPrime },
                    { "shipmentServiceLevelCategory", shipmentServiceLevelCategory },
                    { "sellerOrderId", sellerOrderId },
                };


                dic.Print();
                //调用委托
                insetTable?.Invoke(dic);

                dicList.Add(dic);
            }

            return(dicList);
        }
Beispiel #18
0
        public void Process(Action <Exception> writeLog, Action adsl)
        {
            Func <DateTime, string> dateTimeToIso8601 = dateTime => dateTime.ToString("yyyy-MM-ddTHH:mm:sszzzz", DateTimeFormatInfo.InvariantInfo);

            const string  taskTableName = "amazon_mws_key";
            MySqlHelper   taskHelper    = new MySqlHelper("127.0.0.1", "zhanxian", "root", "root");
            MySqlHelper   resultHelper  = new MySqlHelper("127.0.0.1", "zhanxian", "root", "root");
            TaskDbHandler taskDbHandler = new AmazonTaskDbHandler(taskHelper);

            //设置任务表名
            taskDbHandler.TableName = taskTableName;

            ResultDbHandler resultDbHandler = new AmazonResultDbHandler(resultHelper);

            string accountId = null;

            try
            {
                //var dic =
                //    taskDbHandler.GetSelectDicBySql(
                //        $"SELECT account_id,sellerId,awsAccessKeyId,secertKey,marketPlace,queryDateSpan FROM {taskTableName} WHERE taskstatue = 1");

                //取任务为1的
                var dic =
                    taskDbHandler.GetSelectDicBySqlWithLock(
                        $"SELECT account_id,sellerId,awsAccessKeyId,secertKey,marketPlace,queryDateSpan FROM {taskTableName} WHERE taskstatue = 1 ORDER BY id LIMIT 1",
                        "key_db.amazon_mws_key.taskStatueEqual1",
                        id => taskDbHandler.Start(id));
                dic.Print();
                ICollection <string> keys = dic.Keys;
                int rowCount = dic.GetRowCount();

                //如果没有任务为1的 取任务为6的
                if (rowCount == 0)
                {
                    dic = taskDbHandler.GetSelectDicBySqlWithLock(
                        $"SELECT account_id,sellerId,awsAccessKeyId,secertKey,marketPlace,queryDateSpan FROM {taskTableName} WHERE taskstatue = 6 ORDER BY id LIMIT 1",
                        "key_db.amazon_mws_key.taskStatueEqual6",
                        id => taskDbHandler.Start(id));
                    dic.Print();
                    keys     = dic.Keys;
                    rowCount = dic.GetRowCount();
                }

                for (int i = 0; i < rowCount; i++)
                {
                    try
                    {
                        IDictionary <string, object> curDic = new Dictionary <string, object>();
                        foreach (var key in keys)
                        {
                            curDic.Add(key, dic[key][i]);
                        }
                        curDic.Print();

                        accountId = curDic["account_id"].ToString();

                        string sellerId      = curDic["sellerId"].ToString();
                        string accessKey     = curDic["awsAccessKeyId"].ToString();
                        string secretKey     = curDic["secertKey"].ToString();
                        string marketPlace   = curDic["marketPlace"].ToString();
                        int    queryDateSpan = int.Parse(curDic["queryDateSpan"].ToString());
                        string tableName     = $"order_{accountId}";
                        ////设置任务表名
                        //taskDbHandler.TableName = taskTableName;
                        ////任务表设置开始状态
                        //taskDbHandler.Start(accountId);
                        OrderListHandler orderListHandler = new OrderListHandler(marketPlace, accessKey, sellerId,
                                                                                 secretKey);
                        string createAfter;
                        if (resultDbHandler.TableIfExists(tableName))
                        {
                            string purchaseDate = resultDbHandler.GetEndDate(tableName, "purchaseDate");
                            if (string.IsNullOrEmpty(purchaseDate))
                            {
                                createAfter = dateTimeToIso8601(DateTime.Now.AddDays(-queryDateSpan));
                            }
                            else
                            {
                                createAfter = dateTimeToIso8601(DateTime.Parse(purchaseDate));
                            }
                        }
                        else
                        {
                            resultDbHandler.CreateTable(tableName);
                            createAfter = dateTimeToIso8601(DateTime.Now.AddDays(-queryDateSpan));
                        }


                        bool isFirstPage = true;
                        //第一次设置不为空的任意值
                        string nextToken = "We Will See";
                        while (!string.IsNullOrEmpty(nextToken))
                        {
                            //var parameterDic = isFirstPage
                            //    ? orderListHandler.GetParameterDic(createAfter)
                            //    : orderListHandler.GetNextTokenParameterDic(nextToken);

                            //string html = orderListHandler.GetOrderListHtml(parameterDic);

                            string html = GetHtmlByPostTryThreeTimes(isFirstPage, createAfter, nextToken, orderListHandler, writeLog);

                            nextToken = isFirstPage
                                ? JObject.Parse(html)["ListOrdersResponse"]?["ListOrdersResult"]?["NextToken"]?.ToString
                                            ()
                                : JObject.Parse(html)["ListOrdersByNextTokenResponse"]?["ListOrdersByNextTokenResult"]?[
                                "NextToken"]?.ToString();

                            orderListHandler.GetMainInfoDicList(html, infoDic =>
                            {
                                resultHelper.InsertTableWithDicExistsUpdate(infoDic, tableName);
                            }, isFirstPage);
                            //翻页休息1分钟
                            Thread.Sleep(60 * 1000 + new Random().Next(5000));
                            if (isFirstPage)
                            {
                                isFirstPage = false;
                            }
                        }

                        //订单数据导入成功操作
                        resultDbHandler.OrderImportSuccessfullyExistsUpdate(accountId,
                                                                            Convert.ToDateTime(createAfter).ToString("yyyy/MM/dd hh:mm:ss"), "0",
                                                                            DateTime.Now.ToString(CultureInfo.CurrentCulture), "成功");
                        //任务表设置成功状态
                        taskDbHandler.Succeed(accountId);
                    }
                    catch (Exception e)
                    {
                        //任务表设置失败状态
                        taskDbHandler.Failed(accountId, e);
                        //写错误日志
                        writeLog?.Invoke(e);
                    }
                    //adsl换ip
                    adsl?.Invoke();
                }
            }
            catch (Exception exception)
            {
                //写错误日志
                writeLog?.Invoke(exception);
            }
        }
Beispiel #19
0
        static void interact(Dictionary dict)
        {
            while (true)
            {
                Console.WriteLine("search, insert or delete element or print {0}", dict.GetType().Name);

                Console.Write(prompt);

                string selection = Console.ReadLine();

                Console.WriteLine();

                if (selection == null)
                {
                    continue;
                }

                string[] words = selection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (words.Length == 0)
                {
                    continue;
                }

                if (words[0] == backCode)
                {
                    return;
                }
                else if (words[0] == "print")
                {
                    dict.Print();
                }
                else if (words.Length == 2)
                {
                    int number;

                    if (!Int32.TryParse(words[1], out number))
                    {
                        Console.WriteLine("\"{0}\" is not a number\n", words[1]);
                        continue;
                    }

                    if (words[0] == "search")
                    {
                        if (dict.Search(number))
                        {
                            Console.WriteLine("found {0}", number);
                        }
                        else
                        {
                            Console.WriteLine("not found {0}", number);
                        }
                    }
                    else if (words[0] == "insert")
                    {
                        if (dict.Insert(number))
                        {
                            Console.WriteLine("inserted {0}", number);
                        }
                        else
                        {
                            Console.WriteLine("did not insert {0}", number);
                        }
                    }
                    else if (words[0] == "delete")
                    {
                        if (dict.Delete(number))
                        {
                            Console.WriteLine("deleted {0}", number);
                        }
                        else
                        {
                            Console.WriteLine("did not delete {0}", number);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("invalid action");
                }

                Console.WriteLine();
            }
        }
 public void Print()
 {
     var list = new Dictionary<string, object>[]
     {
         new Dictionary<string, object> { { "name", "George" }, { "size", 34 } },
         new Dictionary<string, object> { { "name", "Alice" }, { "size", 29 } },
         new Dictionary<string, object> { { "name", "Dan" }, { "size", 30 } },
     };
     Assert.AreEqual(
         "(([name,George],[size,34]),([name,Alice],[size,29]),([name,Dan],[size,30]))",
         list.Print());
 }
Beispiel #21
0
        private void Process(Action <Exception> writeLog, Action adsl, string taskTableName)
        {
            MySqlHelper   taskHelper    = new MySqlHelper("127.0.0.1", "zhanxian", "root", "root");
            MySqlHelper   resultHelper  = new MySqlHelper("127.0.0.1", "zhanxian", "root", "root");
            TaskDbHandler taskDbHandler = new AliExpressTaskDbHandler(taskHelper);

            //设置任务表名
            taskDbHandler.TableName = taskTableName;

            ResultDbHandler resultDbHandler = new AliExpressResultDbHandler(resultHelper);
            string          accountId       = null;

            try
            {
                //var dic =
                //    taskDbHandler.GetSelectDicBySql(
                //        $"SELECT account_id,client_id,client_secret,refresh_token,queryDateSpan FROM {taskTableName} WHERE taskstatue = 1");


                var dic =
                    taskDbHandler.GetSelectDicBySqlWithLock(
                        $"SELECT account_id,client_id,client_secret,refresh_token,queryDateSpan FROM {taskTableName} WHERE taskstatue = 1 ORDER BY id LIMIT 1",
                        $"key_db.{taskTableName}.taskStatueEqual1",
                        id => taskDbHandler.Start(id)
                        );
                //dic输出
                dic.Print();
                ICollection <string> keys = dic.Keys;
                int rowCount = dic.GetRowCount();

                if (rowCount == 0)
                {
                    dic =
                        taskDbHandler.GetSelectDicBySqlWithLock(
                            $"SELECT account_id,client_id,client_secret,refresh_token,queryDateSpan FROM {taskTableName} WHERE taskstatue = 6 ORDER BY id LIMIT 1",
                            $"key_db.{taskTableName}.taskStatueEqual6",
                            id => taskDbHandler.Start(id)
                            );
                    //dic输出
                    dic.Print();
                    keys     = dic.Keys;
                    rowCount = dic.GetRowCount();
                }


                //数据库表一行一行处理
                for (var i = 0; i < rowCount; i++)
                {
                    try
                    {
                        var curDic = new Dictionary <string, object>();
                        foreach (var key in keys)
                        {
                            curDic.Add(key, dic[key][i]);
                        }
                        curDic.Print();
                        accountId = curDic["account_id"].ToString();

                        string clientId      = curDic["client_id"].ToString();
                        string clientSecret  = curDic["client_secret"].ToString();
                        string refreshToken  = curDic["refresh_token"].ToString();
                        string queryDateSpan = curDic["queryDateSpan"].ToString();
                        string tableName     = $"order_{accountId}";
                        ////设置任务表名
                        //taskDbHandler.TableName = taskTableName;
                        ////任务表设置开始状态
                        //taskDbHandler.Start(accountId);
                        string startDate;
                        string endDate;
                        //表存在处理
                        if (resultDbHandler.TableIfExists(tableName))
                        {
                            //读出lastDate,不存在则设置为当前时间
                            string lastDateInDb = resultDbHandler.GetEndDate(tableName, "gmtCreate");
                            endDate = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
                            if (string.IsNullOrEmpty(lastDateInDb))
                            {
                                startDate = GetDateTimeByDateSpan(endDate, queryDateSpan);
                            }
                            else
                            {
                                //var endDate = "20120801154220368+0800";
                                string   lastDateFormat = Regex.Match(lastDateInDb, @"\d{14}").Value;
                                DateTime dateTime       = DateTime.ParseExact(lastDateFormat, "yyyyMMddHHmmss",
                                                                              CultureInfo.CurrentCulture);
                                startDate = dateTime.ToString("MM/dd/yyyy hh:mm:ss");
                            }
                        }
                        //表不存在处理
                        else
                        {
                            //创建表
                            resultDbHandler.CreateTable(tableName);
                            endDate   = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
                            startDate = GetDateTimeByDateSpan(endDate, queryDateSpan);
                        }


                        OrderListHandler orderListHandler = new OrderListHandler(clientId, clientSecret, refreshToken);
                        var urlList = orderListHandler.GetFindOrderListQueryUrlIList(startDate, endDate);
                        foreach (var url in urlList)
                        {
                            HttpHelper httpHelper = new HttpHelper();
                            string     html       = httpHelper.GetHtmlByGet(url);

                            IList <IDictionary <string, object> > list = orderListHandler.GetMainInfoDicList(html,
                                                                                                             infoDic =>
                            {
                                resultDbHandler.InsertTableWithDicExistsUpdate(infoDic, tableName);
                            });
                        }

                        //订单数据导入成功操作
                        resultDbHandler.OrderImportSuccessfullyExistsUpdate(accountId,
                                                                            Convert.ToDateTime(startDate).ToString("yyyy/MM/dd hh:mm:ss"), "0",
                                                                            DateTime.Now.ToString(CultureInfo.CurrentCulture), "成功");
                        //任务表设置成功状态
                        taskDbHandler.Succeed(accountId);
                    }
                    catch (Exception e)
                    {
                        //任务表设置失败状态
                        taskDbHandler.Failed(accountId, e);
                        //写错误日志
                        writeLog?.Invoke(e);
                    }
                    //adsl换ip
                    adsl?.Invoke();
                }
            }
            catch (Exception exception)
            {
                //写错误日志
                writeLog?.Invoke(exception);
            }
        }
Beispiel #22
0
        /// <summary>
        /// GetMainInfoDicList
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public IList <Dictionary <string, string> > GetMainInfoDicList(string html)
        {
            IList <Dictionary <string, string> > dicList = new List <Dictionary <string, string> >();
            JObject jObject = JObject.Parse(html);
            JArray  jArray  = JArray.Parse(jObject["orderList"].ToString());

            foreach (var jToken in jArray)
            {
                var amount               = jToken["payAmount"]["amount"]?.ToString();
                var cent                 = jToken["payAmount"]["cent"]?.ToString();
                var currencyCode         = jToken["payAmount"]["currencyCode"]?.ToString();
                var sellerSignerFullname = jToken["sellerSignerFullname"]?.ToString();
                var buyerLoginId         = jToken["buyerLoginId"]?.ToString();
                var paymentType          = jToken["paymentType"]?.ToString();
                var orderStatus          = jToken["orderStatus"]?.ToString();
                var orderId              = jToken["orderId"]?.ToString();
                var issueStatus          = jToken["issueStatus"]?.ToString();
                var sendGoodsTime        = jToken["gmtSendGoodsTime"]?.ToString();
                var gmtPayTime           = jToken["gmtPayTime"]?.ToString();
                var gmtCreate            = jToken["gmtCreate"]?.ToString();
                var fundStatus           = jToken["fundStatus"]?.ToString();
                var frozenStatus         = jToken["frozenStatus"]?.ToString();
                var loanAmount           = jToken["loanAmount"]?.ToString();
                var escrowFee            = jToken["escrowFee"]?.ToString();
                var buyerSignerFullname  = jToken["buyerSignerFullname"]?.ToString();
                var bizType              = jToken["bizType"]?.ToString();
                //var freightCommitDay = jToken["logisticsServiceName"]["freightCommitDay"]?.ToString();
                var productList = jToken["productList"].ToString();

                Dictionary <string, string> dic = new Dictionary <string, string>
                {
                    { "amount", amount },
                    { "cent", cent },
                    { "currencyCode", currencyCode },
                    { "sellerSignerFullname", sellerSignerFullname },
                    { "buyerLoginId", buyerLoginId },
                    { "paymentType", paymentType },
                    { "orderStatus", orderStatus },
                    { "orderId", orderId },
                    { "issueStatus", issueStatus },
                    { "sendGoodsTime", sendGoodsTime },
                    { "gmtPayTime", gmtPayTime },
                    { "gmtCreate", gmtCreate },
                    { "fundStatus", fundStatus },
                    { "frozenStatus", frozenStatus },
                    { "loanAmount", loanAmount },
                    { "escrowFee", escrowFee },
                    { "buyerSignerFullname", buyerSignerFullname },
                    { "bizType", bizType },
                    { "productList", productList }
                };


                dic.Print();

                MySqlHelper mySqlHelper = new MySqlHelper();
                mySqlHelper.InsertTableWithDic(dic, "aliexpressOrderList1");

                dicList.Add(dic);
            }

            return(dicList);
        }
Beispiel #23
0
        /// <summary>
        /// insetTable
        /// </summary>
        /// <param name="html"></param>
        /// <param name="insetTable"></param>
        /// <returns></returns>
        public IList <IDictionary <string, object> > GetMainInfoDicList(string html, Action <IDictionary <string, object> > insetTable)
        {
            IList <IDictionary <string, object> > dicList = new List <IDictionary <string, object> >();
            JObject jObject = JObject.Parse(html);
            JArray  jArray  = JArray.Parse(jObject["orderList"].ToString());

            foreach (var jToken in jArray)
            {
                var amount               = jToken["payAmount"]["amount"]?.ToString();
                var cent                 = jToken["payAmount"]["cent"]?.ToString();
                var currencyCode         = jToken["payAmount"]["currencyCode"]?.ToString();
                var sellerSignerFullname = jToken["sellerSignerFullname"]?.ToString();
                var buyerLoginId         = jToken["buyerLoginId"]?.ToString();
                var paymentType          = jToken["paymentType"]?.ToString();
                var orderStatus          = jToken["orderStatus"]?.ToString();
                var orderId              = jToken["orderId"]?.ToString();
                var issueStatus          = jToken["issueStatus"]?.ToString();
                var sendGoodsTime        = jToken["gmtSendGoodsTime"]?.ToString();
                var gmtPayTime           = jToken["gmtPayTime"]?.ToString();
                var gmtCreate            = jToken["gmtCreate"]?.ToString();
                var fundStatus           = jToken["fundStatus"]?.ToString();
                var frozenStatus         = jToken["frozenStatus"]?.ToString();
                var loanAmount           = jToken["loanAmount"]?.ToString();
                var escrowFee            = jToken["escrowFee"]?.ToString();
                var buyerSignerFullname  = jToken["buyerSignerFullname"]?.ToString();
                var bizType              = jToken["bizType"]?.ToString();
                var productList          = jToken["productList"].ToString();

                IDictionary <string, object> dic = new Dictionary <string, object>
                {
                    { "amount", amount },
                    { "cent", cent },
                    { "currencyCode", currencyCode },
                    { "sellerSignerFullname", sellerSignerFullname },
                    { "buyerLoginId", buyerLoginId },
                    { "paymentType", paymentType },
                    { "orderStatus", orderStatus },
                    { "orderId", orderId },
                    { "issueStatus", issueStatus },
                    { "sendGoodsTime", sendGoodsTime },
                    { "gmtPayTime", gmtPayTime },
                    { "gmtCreate", gmtCreate },
                    { "fundStatus", fundStatus },
                    { "frozenStatus", frozenStatus },
                    { "loanAmount", loanAmount },
                    { "escrowFee", escrowFee },
                    { "buyerSignerFullname", buyerSignerFullname },
                    { "bizType", bizType },
                    { "productList", productList }
                };


                dic.Print();
                //调用委托
                insetTable?.Invoke(dic);

                dicList.Add(dic);
            }

            return(dicList);
        }