示例#1
0
        static void Main(string[] args)
        {
            var nemoConfig = ConfigurationFactory.Configure()
                             .SetDefaultChangeTrackingMode(ChangeTrackingMode.Debug)
                             .SetDefaultMaterializationMode(MaterializationMode.Partial)
                             .SetDefaultCacheRepresentation(CacheRepresentation.None)
                             .SetDefaultSerializationMode(SerializationMode.Compact)
                             .SetOperationNamingConvention(OperationNamingConvention.PrefixTypeName_Operation)
                             .SetOperationPrefix("spDTO_")
                             .SetAutoTypeCoercion(true)
                             .SetIgnoreInvalidParameters(true)
                             .SetLogging(false);

            //// Simple retrieve with dynamic parameters
            //var retrieve_customer_test = ObjectFactory.Retrieve<Customer>(parameters: new { CustomerID = "ALFKI" }).FirstOrDefault();

            var person_legacy = new PersonLegacy {
                person_id = 12345, name = "John Doe", DateOfBirth = new DateTime(1980, 1, 10)
            };
            var person_anonymous = new { person_id = 12345, name = "John Doe" };

            var dict = person_anonymous.ToDictionary();

            var company = new Company {
                Name = "Test Company"
            };

            company.Contacts.Add(new Manager {
                Name = "Manager 1", HireDate = new DateTime(1990, 12, 20)
            });
            company.Contacts.Add(new Manager {
                Name = "Manager 2", HireDate = new DateTime(1990, 12, 20)
            });

            var manager = (Manager)company.Contacts[0];

            manager.Employees.Add(new Employee {
                Name = "Employee 1.1", HireDate = new DateTime(1990, 12, 20)
            });
            manager.Employees.Add(new Employee {
                Name = "Employee 1.2", HireDate = new DateTime(1990, 12, 20)
            });

            //manager.Employees[0].Manager = manager;
            //manager.Employees[1].Manager = manager;

            var packedJson   = company.ToJson();
            var unpackedJson = packedJson.FromJson <Company>();

            var packedXml   = company.ToXml();
            var unpackedXml = packedXml.FromXml <Company>();

            var packed   = company.Serialize();
            var unpacked = packed.Deserialize <Company>();

            // Create an instance
            var created     = ObjectFactory.Create <ICustomer>();
            var created_new = ObjectFactory.Create <Customer>();

            // Binding to a legacy object
            var bound_legacy = ObjectFactory.Bind <IPerson>(person_legacy);

            // Binding to an anonymous object
            var bound_anonymous = ObjectFactory.Bind <IPersonReadOnly>(person_anonymous);

            // Mapping to a legacy object
            var mapped_legacy = ObjectFactory.Map <PersonLegacy, IPerson>(person_legacy);

            // Mapping from an anonymous object uses reflection
            var mapped_anonymous_null = ObjectFactory.Map <IPerson>(person_anonymous);

            // Mapping from an anonymous object via binding
            var mapped_anonymous = ObjectFactory.Map <IPerson>(ObjectFactory.Bind <IPersonReadOnly>(person_anonymous));

            // Dynamic select
            var selected_customers_10 = ObjectFactory.Select <Customer>(page: 1, pageSize: 10).ToList();
            //var selected_customers_10_repeat = ObjectFactory.Select<Customer>(page: 1, pageSize: 10).ToList();
            var selected_customers_A = ObjectFactory.Select <ICustomer>(c => c.CompanyName.StartsWith("A"), page: 1, pageSize: 2);

            var max1 = ObjectFactory.Max <Order, int>(o => o.OrderId, o => o.CustomerId == "ALFKI");
            var max2 = new NemoQueryable <Order>().Max(o => o.OrderId);
            var max3 = new NemoQueryable <Order>().Where(o => o.CustomerId == "ALFKI").Max(o => o.OrderId);

            var maxAsync = new NemoQueryableAsync <Order>().MaxAsync(o => o.OrderId).Result;

            var count1 = new NemoQueryable <Customer>().Count(c => c.Id == "ALFKI");
            var count2 = new NemoQueryable <Customer>().Where(c => c.Id == "ALFKI").Count();

            var selected_customers_A_count = ObjectFactory.Count <ICustomer>(c => c.CompanyName.StartsWith("A"));
            var linqCustomers      = new NemoQueryable <Customer>().Where(c => c.Id == "ALFKI").Take(10).Skip(selected_customers_A_count).OrderBy(c => c.Id).ToList();
            var linqCustomersQuery = (from c in new NemoQueryable <Customer>()
                                      where c.Id == "ALFKI"
                                      orderby c.Id ascending
                                      select c).Take(10).Skip(selected_customers_A_count).ToList();

            var allCustomers = new NemoQueryable <Customer>().ToList();

            var linqCustomer = new NemoQueryable <Customer>().FirstOrDefault(c => c.Id == "ALFKI");

            var linqCustomersAsync = new NemoQueryableAsync <Customer>().Where(c => c.Id == "ALFKI").Take(10).Skip(selected_customers_A_count).OrderBy(c => c.Id).FirstOrDefaultAsync().Result;

            var selected_customers_with_orders = ObjectFactory.Select <ICustomer>(c => c.Orders.Count > 0);

            var selected_customers_and_orders_include = ObjectFactory.Select <ICustomer>(c => c.Orders.Count > 0).Include <ICustomer, IOrder>((c, o) => c.Id == o.CustomerId).ToList();

            // Simple retrieve with dynamic parameters
            var retrieve_customer_dyn = ObjectFactory.Retrieve <Customer>(parameters: new { CustomerID = "ALFKI" }).FirstOrDefault();

            // Simple retrieve with actual parameters
            var retrieve_customer = ObjectFactory.Retrieve <ICustomer>(parameters: new[] { new Param {
                                                                                               Name = "CustomerID", Value = "ALFKI"
                                                                                           } }).FirstOrDefault();

            // Simple retrieve with dynamic parameters and custom operation name
            var retrieve_customers_by_country = ObjectFactory.Retrieve <ICustomer>(operation: "RetrieveByCountry", parameters: new ParamList {
                Country => "USA", State => "PA"
            }).Memoize();

            if (retrieve_customers_by_country.Any())
            {
                var stream_customer_count = retrieve_customers_by_country.Count();
            }

            var stream_customer = retrieve_customers_by_country.FirstOrDefault();

            // Simple retrieve with sql statement operation
            var retrieve_customer_sql = ObjectFactory.Retrieve <ICustomer>(sql: "select * from Customers where CustomerID = @CustomerID", parameters: new ParamList {
                CustomerID => "ALFKI"
            });

            // Advanced!
            // Retrieve customers with orders as object graph
            var retrieve_customer_with_orders_graph = ((IMultiResult)ObjectFactory.Retrieve <Customer, Order>(
                                                           sql: @"select * from Customers where CustomerID = @CustomerID; 
                                                                                        select * from Orders where CustomerID = @CustomerID",
                                                           parameters: new ParamList {
                CustomerId => "ALFKI"
            })).Aggregate <Customer>();

            var customer = retrieve_customer_with_orders_graph.First();

            // Advanced!
            // Retrieve orders with customer as a single row mapping
            var retrieve_orders_with_customer = ObjectFactory.Retrieve <IOrder, ICustomer>(
                sql: @"select c.CustomerID, c.CompanyName, o.OrderID, o.ShipPostalCode from Customers c
                                                                                        left join Orders o on o.CustomerID = c.CustomerID 
                                                                                        where c.CustomerID = @CustomerID",
                parameters: new ParamList {
                CustomerId => "ALFKI"
            },
                map: (o, c) => { o.Customer = c; return(o); });
            var orders = retrieve_orders_with_customer.ToList();
            var same   = orders[0].Customer == orders[1].Customer;

            // Advanced!
            // Retrieve customers with orders as a single row mapping
            var aggregate_mapper = new DefaultAggregatePropertyMapper <ICustomer, IOrder>();
            var retrieve_customer_with_orders = ObjectFactory.Retrieve <ICustomer, IOrder>(
                sql: @"select c.CustomerID, c.CompanyName, o.OrderID, o.ShipPostalCode from Customers c
                                                                                        left join Orders o on o.CustomerID = c.CustomerID 
                                                                                        where c.CustomerID = @CustomerID",
                parameters: new ParamList {
                CustomerId => "ALFKI"
            },
                map: aggregate_mapper.Map).FirstOrDefault();

            // Advanced!
            // Retrieve customers with orders as multi-result
            var retrieve_customer_with_orders_lazy = ObjectFactory.Retrieve <ICustomer, IOrder>(
                sql: @"select * from Customers where CustomerID = @CustomerID;
                                                                                        select * from Orders where CustomerID = @CustomerID",
                parameters: new ParamList {
                CustomerId => "ALFKI"
            });

            var lazy_customer = retrieve_customer_with_orders_lazy.FirstOrDefault(); // ((IMultiResult)retrieve_customer_with_orders_lazy).Retrieve<ICustomer>().FirstOrDefault();
            var lazy_orders   = ((IMultiResult)retrieve_customer_with_orders_lazy).Retrieve <IOrder>().ToList();

            // UnitOfWork example
            //customer.Orders.Do(o => o.Customer = null).Consume();
            using (ObjectScope.New(customer, autoCommit: false, config: nemoConfig))
            {
                customer.CompanyName += "Test";
                customer.Orders[0].ShipPostalCode = "11111";
                customer.Orders.RemoveAt(1);

                var o = ObjectFactory.Create <Order>();
                o.CustomerId     = customer.Id;
                o.ShipPostalCode = "19115";
                o.GenerateKey(nemoConfig);
                customer.Orders.Add(o);

                //var previos = customer.Old();

                //customer_uow.Rollback();
                customer.Commit();
            }

            //// UnitOfWork example: manual change tracking
            //using (new ObjectScope(customer, mode: ChangeTrackingMode.Manual))
            //{
            //    item.CompanyName += "Test";
            //    item.Orders[0].ShipPostalCode = "11111";
            //    item.Orders[0].Update();

            //    var o1 = item.Orders[1];
            //    if (o1.Delete())
            //    {
            //        item.Orders.RemoveAt(1);
            //    }

            //    var o2 = ObjectFactory.Create<IOrder>();
            //    o2.CustomerId = item.Id;
            //    o2.ShipPostalCode = "19115";
            //    if (o2.Insert())
            //    {
            //        item.Orders.Add(o2);
            //    }

            //    item.Commit();
            //}

            // Passing open connection into the method
            using (var test_connection = DbFactory.CreateConnection(ConfigurationManager.ConnectionStrings[ConfigurationFactory.Get <ICustomer>().DefaultConnectionName].ConnectionString))
            {
                test_connection.Open();
                var retrieve_customer_sql_wth_open_connection = ObjectFactory.Retrieve <ICustomer>(connection: test_connection, sql: "select * from Customers where CustomerID = @CustomerID", parameters: new ParamList {
                    CustomerID => "ALFKI"
                });
            }

            var read_only    = retrieve_customer.AsReadOnly();
            var is_read_only = read_only.IsReadOnly();

            var json = retrieve_customer.ToJson();
            var customer_from_json = json.FromJson <ICustomer>();

            Console.WriteLine();
            Console.WriteLine("JSON DOM Parsing");

            RunJsonParser(json, 500);
            RunJsonNetParser(json, 500);
            RunSystemJsonParser(json, 500);
            // ServiceStack does not support DOM parsing
            // RunServiceStackJsonParser<Customer>(new Customer(customer), 500);

            var xsd = Xsd <ICustomer> .Text;
            var xml = retrieve_customer.ToXml();

            using (var reader = XmlReader.Create(new StringReader(xml)))
            {
                var customer_from_xml = reader.FromXml <ICustomer>();
            }

            Console.WriteLine();
            Console.WriteLine("Object Fetching and Materialization");

            //RunEF(500, false);
            RunNative(500);
            RunExecute(500);
            RunDapper(500);
            RunRetrieve(500, false, nemoConfig);
            RunNativeWithMapper(500);
            RunSelect(500, nemoConfig);
            RunRetrieveComplex(500, nemoConfig);

            return;

            //var buffer = customer.Serialize();
            //var new_customer = SerializationExtensions.Deserialize<ICustomer>(buffer);

            Console.WriteLine();
            Console.WriteLine("Simple Object Serialization Benchmark");

            var simpleObjectList = GenerateSimple(100000);

            var dcsSimple  = new DataContractSerializer(typeof(SimpleObject));
            var dcjsSimple = new DataContractJsonSerializer(typeof(SimpleObject));
            var binform    = new BinaryFormatter();

            RunSerializationBenchmark(simpleObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, s);
                    var data = stream.ToArray();
                    return(data);
                }
            },
                                      s => ProtoBuf.Serializer.Deserialize <SimpleObject>(new MemoryStream(s)), "ProtoBuf", s => s.Length);

            RunSerializationBenchmark(simpleObjectList, s => s.Serialize(SerializationMode.Compact), s => s.Deserialize <SimpleObject>(), "ObjectSerializer", s => s.Length);
            RunSerializationBenchmark(simpleObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    binform.Serialize(stream, s);
                    return(stream.ToArray());
                }
            },
                                      s => (SimpleObject)binform.Deserialize(new MemoryStream(s)), "BinaryFormatter", s => s.Length);

            RunSerializationBenchmark(simpleObjectList, s => s.ToXml(), s => s.FromXml <SimpleObject>(), "ObjectXmlSerializer", s => s.Length);
            RunSerializationBenchmark(simpleObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    dcsSimple.WriteObject(stream, s);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
                {
                    return((SimpleObject)dcsSimple.ReadObject(stream));
                }
            }, "DataContractSerializer", s => s.Length);

            RunSerializationBenchmark(simpleObjectList, s => s.ToJson(), s => s.FromJson <SimpleObject>(), "ObjectJsonSerializer", s => s.Length);
            RunSerializationBenchmark(simpleObjectList, ServiceStack.Text.JsonSerializer.SerializeToString,
                                      ServiceStack.Text.JsonSerializer.DeserializeFromString <SimpleObject>, "ServiceStack.Text", s => s.Length);
            RunSerializationBenchmark(simpleObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    dcjsSimple.WriteObject(stream, s);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
                {
                    return((SimpleObject)dcjsSimple.ReadObject(stream));
                }
            }, "DataContractJsonSerializer", s => s.Length);

            Console.WriteLine();
            Console.WriteLine("Complex Object Serialization Benchmark");

            var complexObjectList = GenerateComplex(10000);
            var dcsComplex        = new DataContractSerializer(typeof(ComplexObject));
            var dcjsComplex       = new DataContractJsonSerializer(typeof(ComplexObject));

            RunSerializationBenchmark(complexObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize <ComplexObject>(stream, s);
                    var data = stream.ToArray();
                    return(data);
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(s))
                {
                    return(ProtoBuf.Serializer.Deserialize <ComplexObject>(stream));
                }
            }, "ProtoBuf", s => s.Length);

            RunSerializationBenchmark(complexObjectList, s => s.Serialize(SerializationMode.Compact), s => s.Deserialize <ComplexObject>(), "ObjectSerializer", s => s.Length);
            RunSerializationBenchmark(complexObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    binform.Serialize(stream, s);
                    return(stream.ToArray());
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(s))
                {
                    return((ComplexObject)binform.Deserialize(stream));
                }
            }, "BinaryFormatter", s => s.Length);

            RunSerializationBenchmark(complexObjectList, s => s.ToXml(), s => s.FromXml <ComplexObject>(), "ObjectXmlSerializer", s => s.Length);
            RunSerializationBenchmark(complexObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    dcsComplex.WriteObject(stream, s);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
                {
                    return((ComplexObject)dcsComplex.ReadObject(stream));
                }
            }, "DataContractSerializer", s => s.Length);


            RunSerializationBenchmark(complexObjectList, s => s.ToJson(), s => s.FromJson <ComplexObject>(), "ObjectJsonSerializer", s => s.Length);
            RunSerializationBenchmark(complexObjectList, ServiceStack.Text.JsonSerializer.SerializeToString,
                                      ServiceStack.Text.JsonSerializer.DeserializeFromString <ComplexObject>, "ServiceStack.Text", s => s.Length);
            RunSerializationBenchmark(complexObjectList,
                                      s =>
            {
                using (var stream = new MemoryStream())
                {
                    dcjsComplex.WriteObject(stream, s);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            },
                                      s =>
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
                {
                    return((ComplexObject)dcjsComplex.ReadObject(stream));
                }
            }, "DataContractJsonSerializer", s => s.Length);

            Console.ReadLine();
        }