Beispiel #1
0
        public void CountingEnumerableReturnsExpectedSequence()
        {
            var source = new CountingEnumerable();

            var result = (new int[] { 1, 2, 3, 4, 5 }).SequenceEqual(source as IEnumerable<int>);

            Assert.IsTrue(result);
        }
Beispiel #2
0
    static void Main()
    {
        CountingEnumerable counter = new CountingEnumerable();

        foreach (int x in counter)
        {
            Console.WriteLine(x);
        }
    }
Beispiel #3
0
                static void Main()
                {
                    Console.WriteLine(Marshal.SizeOf(new ClassForSizeof()));
                    System.Collections.ArrayList alb = new System.Collections.ArrayList();
                    alb.Add((byte)25);
                    alb.Add((byte)25);
                    alb.Add((byte)25);
                    Outer <int> .Inner <string, DateTime> .DummyMethod();

                    Outer <string> .Inner <int, int> .DummyMethod();

                    Outer <string> .Inner <int, int> .DummyMethod();//静态构造函数只执行了一次

                    Outer <string> .Inner.DummyMethod();

                    Outer <string> .Inner.DummyMethod();

                    //迭代 http://blog.csdn.net/yangbindxj/article/details/11964343 和 https://msdn.microsoft.com/zh-cn/library/78dfe2yb(v=vs.110).aspx
                    CountingEnumerable counter = new CountingEnumerable();

                    foreach (int v in counter)
                    {
                        Console.WriteLine(v);
                    }
                    //typeof
                    Console.WriteLine($"{typeof(List<>)}:{typeof(List<>).ContainsGenericParameters}");
                    Console.WriteLine($"{typeof(Dictionary<,>)}:{typeof(Dictionary<,>).ContainsGenericParameters}");
                    Console.WriteLine($"{typeof(Dictionary<int,string>)}:{typeof(Dictionary<int,string>).ContainsGenericParameters}");//:False密封的已构造类型
                    string listTypeName   = "System.Collections.Generic.List`1";
                    Type   defByName      = Type.GetType(listTypeName);
                    Type   closedByName   = Type.GetType(listTypeName + "[System.String]");
                    Type   closedByMethod = defByName.MakeGenericType(typeof(string));//填充类型参数,返回一个已构造的类型
                    Type   closedByTypeof = typeof(List <string>);

                    Console.WriteLine(closedByMethod == closedByName);
                    Console.WriteLine(closedByName == closedByTypeof);
                    Type defByTypeof = typeof(List <>);
                    Type defByMethod = closedByName.GetGenericTypeDefinition();

                    Console.WriteLine(defByMethod == defByName);
                    Console.WriteLine(defByName == defByTypeof);
                    //反射调用
                    Type type       = typeof(Reflection);
                    var  definition = type.GetMethod("PrintType");
                    var  cons       = definition.MakeGenericMethod(typeof(string));

                    cons.Invoke(null, null);
                    Console.ReadKey();
                }
        static void Main(string[] args)
        {
            //使用CountWords方法
            string text = @"Do you like green eggs and ham?
                            I do not like them, Sam-I-am.
                            I do not like green eggs and ham.";
            Dictionary <string, int> frequencies = CountWords(text);

            foreach (KeyValuePair <string, int> entry in frequencies)
            {
                string word      = entry.Key;
                int    frequency = entry.Value;
                Console.WriteLine("{0}: {1}", word, frequency);
            }

            ConvertList();
            //使用自定义的泛型方法
            List <string> list = MakeList <string>("Line 1", "Line 2");

            foreach (var x in list)
            {
                Console.WriteLine(x);
            }

            //泛型比较
            string name   = "Jon";
            string intro1 = "My name is " + name;
            string intro2 = "My name is " + name;

            Console.WriteLine(intro1 == intro2);                   //使用string的重载运算符进行比较
            Console.WriteLine(AreReferencesEqual(intro1, intro2)); //编译器无法知道有什么重载类型,返回false

            //使用泛型方法,创建实现的泛型类
            Pair <int, string> pair = Pair.Of(10, "value");

            //封闭类型的静态字段
            TypeField <int> .filed      = "First";
            TypeField <string> .filed   = "Second";
            TypeField <DateTime> .filed = "Third";
            TypeField <int> .PrintField();

            TypeField <string> .PrintField();

            TypeField <DateTime> .PrintField();

            //嵌套泛型类型的静态构造函数
            //第一次调用dummy的时候,不论是什么类型,都会导致inner类型初始化
            //不同类型的实参被看作一个不同的封闭类型
            //相同的封闭类型,只会初始化一次
            Outer <int> .Inner <string, DateTime> .DummyMethod();

            Outer <string> .Inner <int, int> .DummyMethod();

            Outer <object> .Inner <string, object> .DummyMethod();

            Outer <string> .Inner <string, object> .DummyMethod();

            Outer <object> .Inner <object, string> .DummyMethod();

            Outer <string> .Inner <int, int> .DummyMethod(); //封闭成员已经在第二句执行过一次静态构造函数,所以这块不会打印

            //泛型枚举
            CountingEnumerable counter = new CountingEnumerable();

            foreach (int x in counter)
            {
                Console.WriteLine(x);
            }

            //对参数类型使用typeof操作符
            DemonstrateTypeof <int>();

            //获取泛型和已构造Type对象的各种方式
            string listTypeName = "System.Collections.Generic.List`1";
            Type   defByName    = Type.GetType(listTypeName);
            //这将会输出四个true,证明不论怎样获取一个特定对象类型的引用,都只涉及一个这样的对象。
            Type closedByName   = Type.GetType(listTypeName + "[System.String]");
            Type closedByMethod = defByName.MakeGenericType(typeof(string));
            Type closedByTypeof = typeof(List <string>);

            Console.WriteLine(closedByMethod == closedByName);
            Console.WriteLine(closedByName == closedByTypeof);
            Type defByTypeof = typeof(List <>);
            Type defByMethod = closedByName.GetGenericTypeDefinition();

            Console.WriteLine(defByMethod == defByName);
            Console.WriteLine(defByName == defByTypeof);

            //通过反射来获取调用泛型方法
            Type       type       = typeof(Outer <int> .Inner <int, int>);
            MethodInfo definition = type.GetMethod("Dummy");

            definition.Invoke(null, null);
        }
        public override void Execute(DateTime runDate, Action <string> logMessage, CancellationToken cancellationToken)
        {
            using (IDirectoryRepository source = RepositoryFactory.CreateDirectoryRepository(_directoryArgs))
            {
                logMessage($"Connected to source repository '{source.Name}' ({source.ConnectionString})");

                List <String> modified = new List <String>();
                Int32         newCount = 0;

                List <DirectoryObjectMetadata> sourceFiles = source.ListFiles("/").Where(y => y.Name.ToLower().StartsWith("daily_transaction_export_for_vamp") && (y.Name.Contains(".txt") || y.Name.Contains(".csv"))).ToList();

                using (IDatabaseRepository <IHarvesterDataContext> harvester = RepositoryFactory.CreateHarvesterRepository(_harvesterArgs))
                {
                    logMessage($"Connected to database '{harvester.Name}' ({harvester.ConnectionString})");

                    if (OperationID == 0)
                    {
                        logMessage("Warning: OperationID was not set properly. Correcting this.");
                        OperationID = harvester.DataContext.Operations.First(d => d.Name == Name).ID;
                    }
                    Dictionary <String, DirectoryRecord> dictionary = harvester.DataContext.DirectoryRecords.Where(d => d.OperationID == OperationID && d.RepositoryID == harvester.DataContext.Repositories.First(y => y.Name == source.Name).ID).ToDictionary(d => d.FilePath);

                    foreach (DirectoryObjectMetadata file in sourceFiles)
                    {
                        if (!dictionary.ContainsKey(file.Path))
                        {
                            modified.Add(file.Name);
                            newCount++;
                        }
                        else
                        {
                            DirectoryRecord element = dictionary[file.Path];

                            if (file.ModifiedDate > element.FileModifiedDate)
                            {
                                modified.Add(file.Name);
                            }
                        }
                    }
                }

                logMessage($"Discovered {modified.Count} files to be processed ({newCount} new and {modified.Count - newCount} updated).");

                if (modified.Count == 0 && newCount == 0)
                {
                    logMessage("No Records to be processed.");
                    return;
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    source.Dispose();
                    cancellationToken.ThrowIfCancellationRequested();
                }

                using (IDatabaseRepository <IStatisticsDataContext> destination = RepositoryFactory.CreateStatisticsRepository(_databaseArgs))
                {
                    logMessage($"Connected to destination database '{destination.Name}' ({destination.ConnectionString})");

                    var records = modified.Select(file =>
                    {
                        logMessage($"Processing '{file}':");

                        Stream inputStream = source.OpenFile(file);

                        CountingEnumerable <WmsTransactionRecord> counter = new CountingEnumerable <WmsTransactionRecord>(ReadLines(inputStream, GetFileDate(file)));

                        return(Tuple.Create(counter, (Action)(() =>
                        {
                            inputStream.Dispose();
                            logMessage($"\t{counter.Count} records processed.");
                        })));
                    }).SelectMany(i => i).Select(wms => new
                    {
                        wms.EventType,
                        wms.InstitutionName,
                        ItemBarcode = wms.ItemBarcode == "N/A" ? null : wms.ItemBarcode,
                        UserBarcode = wms.UserBarcode == "N/A" ? null : wms.UserBarcode,
                        wms.LoanCheckedOutDate,
                        wms.LoanDueDate,
                        wms.RecordDate
                    }).ToList();

                    logMessage($"Processed {records.Count} records");

                    try
                    {
                        destination.DataContext.BulkImportTransactions(records.ToDataReader(x => new object[] { x.ItemBarcode, x.UserBarcode, x.LoanDueDate, x.LoanCheckedOutDate, runDate, x.EventType, x.InstitutionName, x.RecordDate }));
                        UpdateHarvesterRecord(logMessage, sourceFiles, source.Name, _harvesterArgs);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        throw;
                    }
                    finally
                    {
                        destination.DataContext.Connection.Close();
                        destination.DataContext.Dispose();
                    }
                }
            }
        }