Пример #1
0
        public void MongoQueryExplainsExecutionPlansForFlyweightQueries()
        {
            using (var session = new Session())
            {
                session.Add(new Product
                                {
                                    Name = "ExplainProduct",
                                    Price = 10,
                                    Supplier = new Supplier { Name = "Supplier", CreatedOn = DateTime.Now }
                                });

                // NOTE: these unit tests aren't 100% valid since adding an index in code isn't
                // supported yet.  In order to see meaningful results you have to manually
                // add an index for now.

                // Run the following command in Mongo.exe against the Product collection
                // db.Product.ensureIndex({"Supplier.Name":1})

                // Then you can run this command to see a hydrated explain plan
                // db.Product.find({"Supplier.Name":"abc"})

                // The following is the same as runging:   db.Product.find({"Supplier.Name":"abc"}).explain()

                var query = new Flyweight();
                query["Supplier.Name"] = Q.Equals("Supplier");

                var result = session.Provider.DB.GetCollection<Product>().Explain(query);

                Assert.NotNull(result.cursor);
            }
        }
Пример #2
0
        public void MongoQueryExplainsExecutionPlansForFlyweightQueries()
        {
            using (var session = new Session())
            {
                session.Drop<TestProduct>();

                session.Provider.DB.GetCollection<TestProduct>().CreateIndex(p => p.Supplier.Name, "TestIndex", true, IndexOption.Ascending);

                session.Add(new TestProduct
                                {
                                    Name = "ExplainProduct",
                                    Price = 10,
                                    Supplier = new Supplier { Name = "Supplier", CreatedOn = DateTime.Now }
                                });

                // To see this manually you can run the following command in Mongo.exe against
                //the Product collection db.Product.ensureIndex({"Supplier.Name":1})

                // Then you can run this command to see a detailed explain plan
                // db.Product.find({"Supplier.Name":"abc"})

                // The following query is the same as running: db.Product.find({"Supplier.Name":"abc"}).explain()
                var query = new Flyweight();
                query["Supplier.Name"] = Q.Equals("Supplier");

                var result = session.Provider.DB.GetCollection<TestProduct>().Explain(query);

                Assert.Equal("BtreeCursor TestIndex", result.Cursor);
            }
        }
Пример #3
0
 /// <summary>
 /// Translates LINQ to MongoDB.
 /// </summary>
 /// <param name="exp">The expression.</param>
 /// <returns>The translate.</returns>
 public string Translate(Expression exp)
 {
     sb = new StringBuilder();
     sbIndexed = new StringBuilder();
     FlyWeight = new Flyweight();
     Visit(exp);
     return sb.ToString();
 }
Пример #4
0
 public string Translate(Expression exp)
 {
     this.sb = new StringBuilder();
     sbIndexed = new StringBuilder();
     fly = new Flyweight();
     this.Visit(exp);
     return sb.ToString();
 }
Пример #5
0
        public void BasicQueryUsingChildProperty()
        {
            _collection.Insert(new Person { Name = "Joe Cool", Address = { Street = "123 Main St", City = "Anytown", State = "CO", Zip = "45123" } });
            _collection.Insert(new Person { Name = "Sam Cool", Address = { Street = "300 Main St", City = "Anytown", State = "CO", Zip = "45123" } });

            var query = new Flyweight();
            query["Address.City"] = Q.Equals<string>("Anytown");

            var results = _collection.Find(query);
            Assert.Equal(2, results.Count());
        }
Пример #6
0
        public void WhereExpressionShouldWorkWithFlyweight()
        {
            _collection.Insert(new TestClass {ADouble = 1d});
            _collection.Insert(new TestClass {ADouble = 2d});
            _collection.Insert(new TestClass {ADouble = 3d});
            _collection.Insert(new TestClass {ADouble = 4d});

            var count = _collection.Find();
            Assert.Equal(4, count.Count());

            var query = new Flyweight();
            query["$where"] = " function(){return this.ADouble > 1;} ";
            var results = _collection.Find(query);
            Assert.Equal(3, results.Count());
        }
Пример #7
0
        public void BasicUsageOfUpdateOne()
        {
            var aPerson = new CheeseClubContact { Name = "Joe", FavoriteCheese = "Cheddar" };
            _collection.Insert(aPerson);

            var count = _collection.Find();
            Assert.Equal(1, count.Count());

            var matchDocument = new { Name = "Joe" };
            aPerson.FavoriteCheese = "Gouda";

            _collection.UpdateOne(matchDocument, aPerson);

            var query = new Flyweight();
            query["Name"] = Q.Equals<string>("Joe");

            var retreivedPerson = _collection.FindOne(query);

            Assert.Equal("Gouda", retreivedPerson.FavoriteCheese);
        }
Пример #8
0
        public void BasicUsageOfUpdateOneUsingObjectId()
        {
            var aPerson = new CheeseClubContact { Name = "Joe", FavoriteCheese = "American" };
            _collection.Insert(aPerson);

            var results = _collection.Find();
            Assert.Equal(1, results.Count());

            var matchDocument = new { _id = aPerson.Id };
            aPerson.FavoriteCheese = "Velveeta";

            _collection.UpdateOne(matchDocument, aPerson);

            var query = new Flyweight();
            query["_id"] = Q.Equals<ObjectId>(aPerson.Id);

            var retreivedPerson = _collection.FindOne(query);

            Assert.Equal("Velveeta", retreivedPerson.FavoriteCheese);
        }
Пример #9
0
    // Entry point into console application.
    static void Main()
    {
        // Arbitrary extrinsic state
        int extrinsic_state = 22;

        factory = new FlyweightFactory();

        // Work with different flyweight instances

        ch = factory.GetFlyweight("X");
        ch.Operation(--extrinsic_state);

        ch = factory.GetFlyweight("Y");
        ch.Operation(--extrinsic_state);

        ch = factory.GetFlyweight("Z");
        ch.Operation(--extrinsic_state);

        ch = new UnsharedConcreteFlyweight();
        ch.Operation(--extrinsic_state);

        // Wait for user
        Console.ReadKey();
    }
Пример #10
0
        public Flyweight GetByKey(char key)
        {
            // Uses "lazy initialization"
            Flyweight valueByKay = null;

            if (_initialized.ContainsKey(key))
            {
                valueByKay = _initialized[key];
            }
            else
            {
                switch (key)
                {
                case 'A': valueByKay = new FlyweightForAImpl(); break;

                case 'B': valueByKay = new FlyweightForBImpl(); break;

                //...
                case 'Z': valueByKay = new FlyweightForZImpl(); break;
                }
                _initialized.Add(key, valueByKay);
            }
            return(valueByKay);
        }
Пример #11
0
    private void Start()
    {
        // Arbitrary extrinsic state(外部状态)
        int externalState = 22;

        FlyweightFactory factory = new FlyweightFactory();

        // Work with different flyweight instances
        Flyweight fx = factory.GetFlyweight("X");

        fx.Operation(--externalState);

        Flyweight fy = factory.GetFlyweight("Y");

        fy.Operation(--externalState);

        Flyweight fz = factory.GetFlyweight("Z");

        fz.Operation(--externalState);

        UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();

        fu.Operation(--externalState);
    }
Пример #12
0
        static void Main(string[] args)
        {
            // 定义外部状态,例如字母的位置等信息。
            int externalstate = 10;
            // 初始化享元工厂
            FlyweightFactory factory = new FlyweightFactory();
            // 判断是否已经创建了字母A,如果已经创建就直接使用创建的对象A。
            Flyweight fa = factory.GetFlyweight("A");

            // 把外部状态作为享元对象的方法调用参数
            fa?.Operation(--externalstate);
            // 判断是否已经创建了字母B
            Flyweight fb = factory.GetFlyweight("B");

            fb?.Operation(--externalstate);
            // 判断是否已经创建了字母C
            Flyweight fc = factory.GetFlyweight("C");

            fc?.Operation(--externalstate);
            // 判断是否已经创建了字母D
            Flyweight fd = factory.GetFlyweight("D");

            if (fd != null)
            {
                fd.Operation(--externalstate);
            }
            else
            {
                Console.WriteLine("驻留池中不存在字符串D");
                // 这时候就需要创建一个对象并放入驻留池中
                ConcreteFlyweight d = new ConcreteFlyweight("D");
                factory.Flyweights.Add("D", d);
            }

            Console.Read();
        }
Пример #13
0
 public void SerializationOfFlyweightIsNotLossy()
 {
     var testObj = new Flyweight();
     testObj["astring"] = "stringval";
     var testBytes = BsonSerializer.Serialize(testObj);
     var hydrated = BsonDeserializer.Deserialize<Flyweight>(testBytes);
     Assert.Equal(testObj["astring"], hydrated["astring"]);
 }
Пример #14
0
        public void MongoQuerySupportsHintsForLinqQueries()
        {
            using (var session = new Session())
            {
                session.Drop<TestProduct>();

                session.Add(new TestProduct
                                {
                                    Name = "ExplainProduct",
                                    Price = 10,
                                    Supplier = new Supplier {Name = "Supplier", CreatedOn = DateTime.Now}
                                });

                var query = new Flyweight();
                query["Supplier.Name"] = Q.Equals("Supplier");

                var result = session.Provider.DB
                    .GetCollection<TestProduct>()
                    .Find(query)
                    .Hint(p => p.Name, IndexOption.Ascending);

                Assert.Equal(1, result.Count());
            }
        }
Пример #15
0
 /// <summary>TODO::Description.</summary>
 public string Translate(Expression exp, bool useScopedQualifier)
 {
     UseScopedQualifier = useScopedQualifier;
     _sb = new StringBuilder();
     _sbIndexed = new StringBuilder();
     FlyWeight = new Flyweight();
     SortFly = new Flyweight();
     Visit(exp);
     return _sb.ToString();
 }
Пример #16
0
    // Entry point into console application.
    static void Main()
    {
        // Arbitrary extrinsic state
        int extrinsic_state = 22;

        factory = new FlyweightFactory();

        // Work with different flyweight instances

        ch = factory.GetFlyweight("X");
        ch.Operation(--extrinsic_state);

        ch = factory.GetFlyweight("Y");
        ch.Operation(--extrinsic_state);

        ch = factory.GetFlyweight("Z");
        ch.Operation(--extrinsic_state);

        ch = new UnsharedConcreteFlyweight();
        ch.Operation(--extrinsic_state);

        // Wait for user
        Console.ReadKey();
    }
Пример #17
0
 private void TransformToFlyWeightWhere()
 {
     var where = WhereExpression;
     if (!string.IsNullOrEmpty(where) && IsComplex)
     {
         // reset - need to use the where statement generated
         // instead of the props set on the internal flyweight
         FlyWeight = new Flyweight();
         if (where.StartsWith("function"))
         {
             FlyWeight["$where"] = where;
         }
         else
         {
             FlyWeight["$where"] = " function(){return " + where + ";}";
         }
     }
 }
Пример #18
0
        public void Serialization_Of_Flyweight_Is_Not_Lossy()
        {
            var testObj = new Flyweight();
            testObj["astring"] = "stringval";
            var testBytes = BSONSerializer.Serialize(testObj);
            var hydrated = BSONSerializer.Deserialize<Flyweight>(testBytes);

            Assert.AreEqual(testObj["astring"], hydrated["astring"]);
        }
Пример #19
0
 public UnsharedObject1(Flyweight flyweight)
 {
     this.flyweight = flyweight;
 }
Пример #20
0
 public HeroRole(Flyweight flyweight, string character)
 {
     _flyweight = flyweight;
     _character = character;
 }
Пример #21
0
 //constructor del Arbol
 public Arbol(string raiz, string tipo)
 {
     this.flyweight = ArbolFactory.GetFlyweight(raiz);
     this.tipo      = tipo;
 }
        public void FlyweightShouldPerformOperation()
        {
            IFlyweight flyweight = new Flyweight("F1");

            flyweight.Operation().Should().BeEquivalentTo("Operated by F1");
        }
        public void FlyweightShouldHaveStateFreeWhenCreated()
        {
            Flyweight flyweight = new Flyweight("F1");

            flyweight.State.Should().BeEquivalentTo("free");
        }
Пример #24
0
 public FlyweightContext(string repeatingState, int uniqueState)
 {
     _flyweight   = GetFlyweight(repeatingState);
     _uniqueState = uniqueState;
 }
Пример #25
0
        public void Serialization_Of_Scoped_Code_Is_Not_Lossy()
        {
            var obj1 = new GeneralDTO();
            obj1.Code = new ScopedCode();
            obj1.Code.CodeString = "function(){return 'hello world!'}";
            var scope = new Flyweight();
            scope["$ns"] = "root";
            obj1.Code.Scope = scope;

            var obj2 = BSONSerializer.Deserialize<GeneralDTO>(BSONSerializer.Serialize(obj1));

            Assert.AreEqual(obj1.Code.CodeString, obj2.Code.CodeString);
            Assert.AreEqual(((Flyweight)obj1.Code.Scope)["$ns"],((Flyweight)obj2.Code.Scope)["$ns"]);
        }
 public FlyweightWrapperA(Flyweight flyweight)
 {
     _flyweight = flyweight;
 }
Пример #27
0
 public void SetSharedFlyweight(Flyweight flyweight)
 {
     m_FlyweightDict = flyweight;
 }
Пример #28
0
 public IFlyweight this[string index]
 {
     get
     {
         if (!flyweights.ContainsKey(index))
             flyweights[index] = new Flyweight();
         return flyweights[index];
     }
 }
Пример #29
0
        public void FindCanQueryEmbeddedArray()
        {
            _collection.Delete(new { });
            var person1 = new Person
            {
                Name = "Joe Cool",
                Address =
                {
                    Street = "123 Main St",
                    City = "Anytown",
                    State = "CO",
                    Zip = "45123"
                }

            };
            var person2 = new Person
            {
                Name = "Sam Cool",
                Address =
                {
                    Street = "300 Main St",
                    City = "Anytown",
                    State = "CO",
                    Zip = "45123"
                },
                Relatives = new List<string>() { "Emma", "Bruce", "Charlie" }
            };
            _collection.Insert(person1);
            _collection.Insert(person2);

            var elem = new Flyweight();
            elem["Relatives"] = "Charlie";
            var a = _collection.Find(elem).ToArray();
            Assert.Equal(1, a.Length);
        }
Пример #30
0
        /// <summary>TODO::Description.</summary>
        public string Translate(Expression exp, bool useScopedQualifier)
        {
            UseScopedQualifier = useScopedQualifier;
            _sbWhere = new StringBuilder();
            _sbIndexed = new StringBuilder();
            FlyWeight = new Flyweight();
            SortFly = new Flyweight();

            Visit(exp);

            TransformToFlyWeightWhere();

            return WhereExpression;
        }
Пример #31
0
        public void UpdateMustSpecifyEverything()
        {
            //Note, when doing an update, MongoDB replaces everything in your document except the id. So, if you don't re-specify a property, it'll disappear.
            //In this example, the cheese is gone.

            var aPerson = new CheeseClubContact { Name = "Joe", FavoriteCheese = "Cheddar" };

            Assert.NotNull(aPerson.FavoriteCheese);

            _collection.Insert(aPerson);

            var matchDocument = new { Name = "Joe" };
            var updatesToApply = new { Name = "Joseph" };

            _collection.UpdateOne(matchDocument, updatesToApply);

            var query = new Flyweight();
            query["Name"] = Q.Equals<string>("Joseph");

            var retreivedPerson = _collection.FindOne(query);

            Assert.Null(retreivedPerson.FavoriteCheese);
        }
Пример #32
0
 public Context(string uniqueState, Flyweight flyweight)
 {
     _flyweight   = flyweight;
     _uniqueState = uniqueState;
 }
Пример #33
0
        public void SerializationOfScopedCodeIsNotLossy()
        {
            var obj1 = new GeneralDTO {Code = new ScopedCode {CodeString = "function(){return 'hello world!'}"}};
            var scope = new Flyweight();
            scope["$ns"] = "root";
            obj1.Code.Scope = scope;

            var obj2 = BsonDeserializer.Deserialize<GeneralDTO>(BsonSerializer.Serialize(obj1));

            Assert.Equal(obj1.Code.CodeString, obj2.Code.CodeString);
            Assert.Equal(((Flyweight)obj1.Code.Scope)["$ns"],((Flyweight)obj2.Code.Scope)["$ns"]);
        }
Пример #34
0
 public Context(FlyweightFactory factory, Car sharedState, Car uniqueState)
 {
     this.factory     = factory;
     flyweight        = factory.GetFlyweight(sharedState);
     this.uniqueState = uniqueState;
 }
Пример #35
0
 public RoleAustinPowers(Flyweight flyweight)
 {
     _flyweight = flyweight;
 }
Пример #36
0
 static void Main(string[] args)
 {
     Flyweight.TestDesign();
     Console.ReadKey();
 }