예제 #1
0
        public void MongoQueryExplainsExecutionPlansForFlyweightQueries()
        {
            using (var session = new Session())
            {
                session.Drop<TestProduct>();

                session.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 Expando();
                query["Supplier.Name"] = Q.Equals("Supplier");

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

                Assert.Equal("BtreeCursor TestIndex", result.Cursor);
            }
        }
예제 #2
0
        private long GetNextHi(string collectionName)
        {
            while (true)
            {
                try
                {
                    var update = new Expando();
                    update["$inc"] = new { ServerHi = 1 };

                    var hiLoKey = _db.GetCollection<NormHiLoKey>().FindAndModify(new { _id = collectionName }, update);
                    if (hiLoKey == null)
                    {
                        _db.GetCollection<NormHiLoKey>().Insert(new NormHiLoKey { CollectionName = collectionName, ServerHi = 2 });
                        return 1;
                    }

                    var newHi = hiLoKey.ServerHi;
                    return newHi;
                }
                catch (MongoException ex)
                {
                    if (!ex.Message.Contains("duplicate key"))
                        throw;
                }
            }
        }
예제 #3
0
 public void SerializationOfFlyweightIsNotLossy()
 {
     var testObj = new Expando();
     testObj["astring"] = "stringval";
     var testBytes = BsonSerializer.Serialize(testObj);
     var hydrated = BsonDeserializer.Deserialize<Expando>(testBytes);
     Assert.Equal(testObj["astring"], hydrated["astring"]);
 }
예제 #4
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 Expando();
            query["Address.City"] = Q.Equals<string>("Anytown");

            var results = _collection.Find(query);
            Assert.Equal(2, results.Count());
        }
예제 #5
0
        public void Expando_TryGet_Should_Not_Throw_Exception_When_Property_Doesnt_Exist()
        {
            var e = new Expando();
            e["hello"] = "world";
            var outval = "";
            Assert.True(e.TryGet<String>("hello",out outval));
            Assert.False(e.TryGet<String>("hello2", out outval));

            bool out2;
            Assert.False(e.TryGet<bool>("hello", out out2));
        }
        static Expando DeserializeAsValue(INode e)
        {
            if (e.childNodes.Length == 1)
            {
                if (e.childNodes[0].nodeType == INode.NodeTypeEnum.TextNode)
                {
                    return(Expando.Of(e.childNodes[0].nodeValue));
                }
            }

            return(DeserializeAsExpando(e));
        }
예제 #7
0
        public void Test1()
        {
            var foobar = new Expando();
            foobar.Add("foo", "$bar");
            Assert.AreEqual("foo = $bar", foobar.ToString());
            var quux = new Expando();
            quux.Add("qu", "ux");
            Assert.AreEqual("qu = ux", quux.ToString());

            // init
            dynamic map = new Expando();
            Assert.AreEqual("", map.ToString());

            // binaryoperation
            map += foobar;
            map += quux;
            Assert.AreEqual("foo = $bar, qu = ux", map.ToString());

            // fallback to csharpbinder
            map -= quux;
            Assert.AreEqual("foo = $bar", map.ToString());

            // convert
            var s = (String)map;
            Assert.AreEqual("foo = $bar", s);

            // getindex
            var bar = map["foo"];
            Assert.AreEqual("$bar", bar);

            // invoke, fallback to idynamicobject
            map = map(bar : "bar");
            Assert.AreEqual("foo = bar", map.ToString());

            // setindex
            map["two"] = 2;
            Assert.AreEqual("foo = bar, two = 2", map.ToString());
            map.Remove("two");

            //invokemember
            map["fn"] = ((Func<int, int, int>)((x, y) => x + y));
            var z = map.fn(1, 2);
            Assert.AreEqual(3, z);

            // setmember
            map.fn = "fn";
            map.two = "2";
            Assert.AreEqual("foo = bar, fn = fn, two = 2", map.ToString());

            // unaryoperation
            map = !map;
            Assert.AreEqual("oof = bar, nf = fn, owt = 2", map.ToString());
        }
예제 #8
0
        public IEnumerable <Z> Find <U, O, Z>(U template, O orderBy, int limit, int skip, String fullName, Expression <Func <T, Z> > fieldSelection)
        {
            #region Extract field names to request
            var exp = fieldSelection.Body as NewExpression;
            var fieldSelectionExpando = new Expando();
            if (exp != null)
            {
                foreach (var x in exp.Arguments.OfType <MemberExpression>())
                {
                    fieldSelectionExpando[x.GetPropertyAlias()] = 1;
                }
            }
            else if (fieldSelection.Body is MemberExpression)
            {
                var me = fieldSelection.Body as MemberExpression;
                fieldSelectionExpando[me.GetPropertyAlias()] = 1;
            }
            // Concrete typed expressions
            else if (fieldSelection.Body is MemberInitExpression)
            {
                var initExpression = (fieldSelection.Body as MemberInitExpression);
                foreach (var assignment in initExpression.Bindings.OfType <MemberAssignment>())
                {
                    if (assignment.Expression is MemberExpression)
                    {
                        var expression = assignment.Expression as MemberExpression;
                        fieldSelectionExpando[expression.GetPropertyAlias()] = 1;
                    }
                }
            }
            #endregion

            var qm = new QueryMessage <T, U>(_connection, fullName)
            {
                NumberToTake   = limit,
                NumberToSkip   = skip,
                Query          = template,
                OrderBy        = orderBy,
                FieldSelection = fieldSelectionExpando
            };

            object projection = null;
            if (!_compiledTransforms.TryGetValue(fieldSelection.GetHashCode(), out projection))
            {
                projection = fieldSelection.Compile();
                _compiledTransforms[fieldSelection.GetHashCode()] = projection;
            }
            return(new MongoQueryExecutor <T, U, Z>(qm, (Func <T, Z>)projection)
            {
                CollectionName = this._collectionName
            });
        }
예제 #9
0
        /// <summary>
        /// Returns an Expando that contains the deserialized ExpandoSurrogate data
        /// </summary>
        /// <returns>An Expando that contains the deserialized ExpandoSurrogate data</returns>
        public Expando Save()
        {
            Expando expando = new Expando();

            ((ISupportInitialize)expando).BeginInit();
            expando.SuspendLayout();

            expando.Name     = this.Name;
            expando.Text     = this.Text;
            expando.Size     = this.Size;
            expando.Location = this.Location;

            expando.BackColor      = Tools.Drawing.ConvertStringToColor(this.BackColor);
            expando.ExpandedHeight = this.ExpandedHeight;

            expando.CustomSettings               = this.CustomSettings.Save();
            expando.CustomSettings.Expando       = expando;
            expando.CustomHeaderSettings         = this.CustomHeaderSettings.Save();
            expando.CustomHeaderSettings.Expando = expando;

            expando.TitleImage = this.TitleImage.ToImage();
            expando.Watermark  = this.Watermark.ToImage();

            expando.Animate       = this.Animate;
            expando.ShowFocusCues = this.ShowFocusCues;
            expando.Collapsed     = this.Collapsed;
            expando.CanCollapse   = this.CanCollapse;
            expando.SpecialGroup  = this.SpecialGroup;

            expando.Enabled    = this.Enabled;
            expando.Visible    = this.Visible;
            expando.AutoLayout = this.AutoLayout;

            expando.Anchor = this.Anchor;
            expando.Dock   = this.Dock;

            expando.Font = new Font(this.FontName, this.FontSize, this.FontDecoration);

            expando.Tag = this.Tag.SerializeToByteArray();

            foreach (Object o in this.Items)
            {
                TaskItem ti = ((TaskItemSurrogate)o).Save();

                expando.Items.Add(ti);
            }

            ((ISupportInitialize)expando).EndInit();
            expando.ResumeLayout(false);

            return(expando);
        }
예제 #10
0
        public static Task <IFunction> ByName(string name, object target = null)
        {
            // X:\jsc.svn\examples\javascript\test\TestChromeStackFrames\TestChromeStackFrames\Application.cs

            // X:\jsc.svn\examples\javascript\Test\TestHistoryForwardEvent\TestHistoryForwardEvent\Application.cs
            Console.WriteLine("enter IFunction.ByName " + new { name });

            // X:\jsc.svn\core\ScriptCoreLib.Async\ScriptCoreLib.Async\JavaScript\DOM\HistoryExtensions.cs

            // tested by
            // X:\jsc.svn\examples\javascript\WorkerInsideSecondaryApplication\WorkerInsideSecondaryApplicationWithStateReplaceTwice\Application.cs

            if (target == null)
            {
                target = Native.self;
            }

            var x = new TaskCompletionSource <IFunction>();

            Action y = delegate
            {
                if (Expando.InternalIsMember(target, name))
                {
                    // should wo typecheck that member?
                    var f = (IFunction)Expando.InternalGetMember(target, name);

                    x.SetResult(f);
                    return;
                }

                // ?
            };

            y();

            if (!x.Task.IsCompleted)
            {
                new Timer(
                    t =>
                {
                    y();

                    if (x.Task.IsCompleted)
                    {
                        t.Stop();
                    }
                }
                    ).StartInterval(15);
            }

            return(x.Task);
        }
예제 #11
0
 public TItem this[int i]
 {
     [Script(DefineAsStatic = true)]
     get
     {
         return((TItem)Expando.InternalGetMember(this, i));
     }
     [Script(DefineAsStatic = true)]
     set
     {
         Expando.InternalSetMember(this, i, value);
     }
 }
예제 #12
0
 public void SerializationOfFlyweightListsInsideFlyweightWorks()
 {
     var testObj = new Expando();
     testObj["astring"] = "stringval";
     var innerObj = new List<Expando>();
     var innerInnerObject = new Expando();
     innerInnerObject["innerInnerValue"] = "aStringOfDoom";
     innerObj.Add(innerInnerObject);
     testObj["InnerObject"] = innerObj;
     var testBytes = BsonSerializer.Serialize(testObj);
     var hydrated = BsonDeserializer.Deserialize<Expando>(testBytes);
     Assert.Equal(testObj["InnerObject"].GetType(),hydrated["InnerObject"].GetType());
 }
예제 #13
0
        /// <summary>
        /// Asynchronously creates an index on this collection.
        /// It is highly recommended that you use the overload of this method that accepts an expression unless you need the granularity that this method provides.
        /// </summary>
        /// <param retval="fieldSelectionExpando">The document properties that participate in this index. Each property of "fieldSelectionExpando" should be
        /// set to either "IndexOption.Ascending" or "IndexOption.Descending", the properties can be deep aliases, like "Suppiler.Name",
        /// but remember that this will make no effort to check that what you put in for values match the MongoConfiguration.</param>
        /// <param retval="indexName">The retval of the index as it should appear in the special "system.indexes" child collection.</param>
        /// <param retval="isUnique">True if MongoDB can expect that each document will have a unique combination for this fieldSelectionExpando.
        /// MongoDB will potentially optimize the index based on this being true.</param>
        public void CreateIndex(Expando key, String indexName, bool isUnique)
        {
            var collection = _db.GetCollection <MongoIndex>("system.indexes");

            collection.Insert(
                new MongoIndex
            {
                Key       = key,
                Namespace = FullyQualifiedName,
                Name      = indexName,
                Unique    = isUnique
            });
        }
예제 #14
0
        public void TestMongoInsert()
        {
            MongoEntity entity = new MongoEntity {
                备注 = "insert1"
            };

            manager.Insert(new MongoEntity[] { entity });
            var query = new Expando();

            query["_id"] = entity.Id;
            Assert.IsNotNull(manager.FindOne(query));
            manager.Delete(query);
        }
예제 #15
0
        public void TestLikeQuery()
        {
            var query     = new Expando();
            var querylike = new Expando();
            var subsub    = new Expando();

            query["备注"]     = Q.Matches("q");
            querylike["列表"] = Q.ElementMatch(new { 备注 = Q.Matches("hello") });
            subsub["列表"]    = Q.ElementMatch(new { 列表 = Q.ElementMatch(new { 备注 = Q.Matches("subsub1") }) });
            Assert.IsNotNull(manager.FindOne(query));
            Assert.IsNotNull(manager.FindOne(querylike));
            Assert.IsNotNull(manager.FindOne(subsub));
        }
        // Reveal() timer
        private void tmrReveal_Tick(object sender, EventArgs e)
        {
            Expando expEquipment = (Expando)this.Parent;

            if (expEquipment.Animating)
            {
                return; // wait until finished animating
            }
            if (expEquipment.TaskPane != null)
            {
                expEquipment.TaskPane.ScrollControlIntoView(expEquipment);
            }
            tmrReveal.Stop();
        }
예제 #17
0
        public void Expando_TryGet_Should_Not_Throw_Exception_When_Property_Doesnt_Exist()
        {
            var e = new Expando();

            e["hello"] = "world";
            var outval = "";

            Assert.True(e.TryGet <String>("hello", out outval));
            Assert.False(e.TryGet <String>("hello2", out outval));

            bool out2;

            Assert.False(e.TryGet <bool>("hello", out out2));
        }
예제 #18
0
        public IXMLSerializer(params object[] k)
        {
            if (k == null)
            {
                throw new Exception("IXMLSerializer: k is null");
            }

            foreach (object x in k)
            {
                Expando o = Expando.Of(x);

                KnownTypes.SetMember(o.TypeMetaName, o);
            }
        }
예제 #19
0
        /// <summary>
        /// Populates the ExpandoSurrogate with data that is to be
        /// serialized from the specified Expando
        /// </summary>
        /// <param name="expando">The Expando that contains the data
        /// to be serialized</param>
        public void Load(Expando expando)
        {
            this.Name     = expando.Name;
            this.Text     = expando.Text;
            this.Size     = expando.Size;
            this.Location = expando.Location;

            this.BackColor      = Tools.Drawing.ConvertColorToString(expando.BackColor);
            this.ExpandedHeight = expando.ExpandedHeight;

            this.CustomSettings = new ExpandoInfoSurrogate();
            this.CustomSettings.Load(expando.CustomSettings);
            this.CustomHeaderSettings = new HeaderInfoSurrogate();
            this.CustomHeaderSettings.Load(expando.CustomHeaderSettings);

            this.Animate       = expando.Animate;
            this.ShowFocusCues = expando.ShowFocusCues;
            this.Collapsed     = expando.Collapsed;
            this.CanCollapse   = expando.CanCollapse;
            this.SpecialGroup  = expando.SpecialGroup;

            this.TitleImage = expando.TitleImage.ToByteArray();
            this.Watermark  = expando.Watermark.ToByteArray();

            this.Enabled    = expando.Enabled;
            this.Visible    = expando.Visible;
            this.AutoLayout = expando.AutoLayout;

            this.Anchor = expando.Anchor;
            this.Dock   = expando.Dock;

            this.FontName       = expando.Font.FontFamily.Name;
            this.FontSize       = expando.Font.SizeInPoints;
            this.FontDecoration = expando.Font.Style;

            this.Tag = expando.Tag.SerializeToByteArray();

            for (int i = 0; i < expando.Items.Count; i++)
            {
                if (expando.Items[i] is TaskItem)
                {
                    TaskItemSurrogate tis = new TaskItemSurrogate();

                    tis.Load((TaskItem)expando.Items[i]);

                    this.Items.Add(tis);
                }
            }
        }
예제 #20
0
        public bool Contains(T item)
        {
            bool j = false;

            for (int i = 0; i < Count; i++)
            {
                if (Expando.ReferenceEquals(this[i], item))
                {
                    j = true;
                    break;
                }
            }

            return(j);
        }
예제 #21
0
        public int IndexOf(T item)
        {
            var j = -1;

            for (int i = 0; i < Count; i++)
            {
                if (Expando.ReferenceEquals(this[i], item))
                {
                    j = i;
                    break;
                }
            }

            return(j);
        }
예제 #22
0
        /// <summary>
        /// Construct query and order by BSON.
        /// </summary>
        /// <returns></returns>
        private byte[] GetPayload()
        {
            if (Query != null && Query is ISystemQuery)
            {
                return(BsonSerializer.Serialize(Query));
            }
            var fly = new Expando();

            fly["query"] = Query;
            if (OrderBy != null)
            {
                fly["orderby"] = this.OrderBy;
            }
            return(BsonSerializer.Serialize(fly));
        }
예제 #23
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 Expando();
            query["$where"] = " function(){return this.ADouble > 1;} ";
            var results = _collection.Find(query);
            Assert.Equal(3, results.Count());
        }
예제 #24
0
        public int indexOf(TItem item)
        {
            var j = -1;

            for (int i = 0; i < length; i++)
            {
                if (Expando.ReferenceEquals(this[i], item))
                {
                    j = i;
                    break;
                }
            }

            return(j);
        }
예제 #25
0
 public void RemoveRule(int index)
 {
     if (Expando.InternalIsMember(this, "removeRule"))
     {
         this.removeRule(index);
     }
     else if (Expando.InternalIsMember(this, "deleteRule"))
     {
         this.deleteRule(index);
     }
     else
     {
         throw new System.NotSupportedException("RemoveRule");
     }
 }
        /// <summary>
        /// Adjust the height of the parent expando to fit the full tree in.
        /// </summary>
        private void ResizeWidget()
        {
            if (!tvwOrbat._suspendUpdate)
            {
                int tvwHeight = tvwOrbat.RowCount * tvwOrbat.RowHeight;
                this.Height = tvwHeight + 20;

                Expando expOrderOfBattle = (Expando)this.Parent;
                expOrderOfBattle.SuspendLayout();
                expOrderOfBattle.ExpandedHeight = tvwHeight + 46;
                expOrderOfBattle.Height        += 1; // workaround for bug in tskMain ScrollableControl:
                expOrderOfBattle.Height        -= 1; // force the correct scroll height
                expOrderOfBattle.ResumeLayout();
            }
        }
예제 #27
0
        public void SerializationOfFlyweightListsInsideFlyweightWorks()
        {
            var testObj = new Expando();

            testObj["astring"] = "stringval";
            var innerObj         = new List <Expando>();
            var innerInnerObject = new Expando();

            innerInnerObject["innerInnerValue"] = "aStringOfDoom";
            innerObj.Add(innerInnerObject);
            testObj["InnerObject"] = innerObj;
            var testBytes = BsonSerializer.Serialize(testObj);
            var hydrated  = BsonDeserializer.Deserialize <Expando>(testBytes);

            Assert.Equal(testObj["InnerObject"].GetType(), hydrated["InnerObject"].GetType());
        }
예제 #28
0
        public void CreatesExpandoWith2000Fields()
        {
            int           N           = 2000;
            StringBuilder codeBuilder = new StringBuilder();

            codeBuilder.Append("[b->'Hello'");
            for (int i = 0; i < N; i++)
            {
                codeBuilder.AppendFormat(", a{0}->{1}", i, i);
            }
            codeBuilder.Append("];");

            Expando resultVal = (Expando)Script.RunCode(codeBuilder.ToString());

            Assert.AreEqual(N + 1, resultVal.Fields.Count());
        }
        private void tvwOrbat_Collapsed(object sender, TreeViewAdvEventArgs e)
        {
            Expando expOrderOfBattle = (Expando)this.Parent;

            if (expOrderOfBattle.TaskPane != null)
            {
                expOrderOfBattle.TaskPane.PreventAutoScroll = true;
            }

            ResizeWidget();

            if (expOrderOfBattle.TaskPane != null)
            {
                expOrderOfBattle.TaskPane.PreventAutoScroll = false;
            }
        }
예제 #30
0
        public int Compare(object ka, object kb)
        {
            if (ka == kb)
            {
                return(0);
            }
            if (ka == null)
            {
                return(-1);
            }
            if (kb == null)
            {
                return(1);
            }

            var r = -2;

            if (Expando.Of(ka).IsString)
            {
                r = Expando.Compare(ka, kb);
            }

            if (Expando.Of(ka).IsNumber)
            {
                r = Expando.Compare(ka, kb);
            }

            if (Expando.Of(ka).IsBoolean)
            {
                r = Expando.Compare(ka, kb);
            }


            if (r == -2)
            {
                if (ka == kb)
                {
                    return(0);
                }

                // how do we compare two objects?
                // X:\jsc.svn\core\ScriptCoreLib\ActionScript\BCLImplementation\System\Collections\Comparer.cs
                return(1);
            }

            return(r);
        }
예제 #31
0
        // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Runtime\Serialization\FormatterServices.cs

        // use by?
        public static object CreateInstance(Type type, params object[] args)
        {
            if ((object)type == null)
            {
                throw new NotSupportedException();
            }


            //  var ctor$dRwABhEmij_awUY_aNs2ypYA = pcI2XBEmij_awUY_aNs2ypYA.ctor = $ctor$(null, 'dRwABhEmij_awUY_aNs2ypYA', type$pcI2XBEmij_awUY_aNs2ypYA);
            //  var ctor$rwAABqwhHjSCn60Jy_bMQpA = $ctor$(null, 'rwAABqwhHjSCn60Jy_bMQpA', type$fAZ65awhHjSCn60Jy_bMQpA);

            // X:\jsc.svn\examples\javascript\test\TestActivatorWithArgs\TestActivatorWithArgs\Application.cs

            // can we get the default ctor with args?
            var ctor = (IFunction)Expando.InternalGetMember(
                ((__Type)type).AsExpando().constructor, "ctor");

            // 0:31ms { type = <Namespace>.Foo, ctor = function (b)


            //Console.WriteLine(new { type, ctor });
            //[Script(OptimizedCode = @"return new f();")]

            // how to apply ctor args correctly?

            if (args.Length == 0)
            {
                return(new IFunction("f",
                                     "return new f();").apply(null, ctor));
            }

            if (args.Length == 1)
            {
                return(new IFunction("f", "a",
                                     "return new f(a);").apply(null, ctor, args[0]));
            }

            if (args.Length == 2)
            {
                return(new IFunction("f", "a", "b",
                                     "return new f(a, b);").apply(null, ctor, args[0], args[1]));
            }

            // manually add more or make it more elegant?
            throw new NotImplementedException();
            //return ctor.CreateType();
        }
예제 #32
0
        public CSSStyleRule AddRule(string selectorText, string declaration, int index)
        {
            //34ms __get_item IStyleSheet { selectorText = @media print } view-source:35342
            //35ms AddRule { selectorText = @media print, Length = 0 } view-source:35342
            //38ms AddRule { selectorText = 0, Length = 1 } view-source:35342
            //39ms IStyleSheetRule.AddRule error { text = 0{/**/} }

            // https://developer.mozilla.org/en-US/docs/Web/CSS/@media
            // http://davidwalsh.name/add-rules-stylesheets

            if (Expando.InternalIsMember(this, "insertRule"))
            {
                // I/Web Console(32117): IStyleSheetRule.AddRule error { text = @media print{/**/} }


                var text = selectorText + "{" + declaration + "}";



                try
                {
                    this.insertRule(text, index);
                }
                catch
                {
                    // tested by
                    // X:\jsc.svn\examples\javascript\Test\TestCSSPrint\TestCSSPrint\Application.cs


                    Console.WriteLine("IStyleSheetRule.AddRule error " + new { text });
                    throw;
                }

                return(this.Rules[index]);
            }

            if (Expando.InternalIsMember(this, "addRule"))
            {
                this.addRule(selectorText, declaration, index);
                return(this.Rules[index]);
            }



            throw new System.Exception("fault at IStyleSheetRule.AddRule");
        }
예제 #33
0
        public void SerializationOfScopedCodeIsNotLossy()
        {
            var obj1 = new GeneralDTO {
                Code = new ScopedCode {
                    CodeString = "function(){return 'hello world!'}"
                }
            };
            var scope = new Expando();

            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(((Expando)obj1.Code.Scope)["$ns"], ((Expando)obj2.Code.Scope)["$ns"]);
        }
예제 #34
0
파일: QueryTests.cs 프로젝트: zulkamal/NoRM
        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 Expando();

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

            var results = _collection.Find(query);

            Assert.Equal(2, results.Count());
        }
예제 #35
0
        /// <summary>
        /// Convert a string to an IExpando.
        /// </summary>
        /// <exception cref="">Throws an exception when the string passed in cannot be parsed.</exception>
        /// <param name="jsonToParse"></param>
        /// <returns></returns>
        public Expando ParseJSON(String jsonToParse)
        {
            Expando retval = new Expando();
            var memberstring = _rxObject.Match(jsonToParse).Groups["obj"].Value;
            Match m;
            do
            {
                m = _rxPair.Match(memberstring);
                if(m.Success)
                {
                    retval[m.Groups["key"].Value] = this.ParseMember(m.Groups["value"].Value);
                    memberstring = memberstring.Remove(0, m.Length);
                }

            } while (m.Success && memberstring.Length > 0);
            return retval;
        }
예제 #36
0
        /// <summary>
        /// Generates a new identity value
        /// </summary>
        /// <param name="collectionName">Collection Name</param>
        /// <param name="database"></param>
        /// <returns></returns>
        public long GenerateId(string collectionName, IMongoDatabase database)
        {
            while (true)
            {
                try
                {
                    var update = new Expando();
                    update["$inc"] = new { Next = 1 };

                    var counter = database.GetCollection <SequenceIdCounters>().FindAndModify(new { _id = collectionName }, update);

                    if (counter == null)
                    {
                        // account for starting seed
                        if (Seed != null)
                        {
                            database.GetCollection <SequenceIdCounters>()
                            .Insert(new SequenceIdCounters
                            {
                                CollectionName = collectionName,
                                Next           = Seed.Value + 1
                            });
                            return(Seed.Value);
                        }

                        database.GetCollection <SequenceIdCounters>()
                        .Insert(new SequenceIdCounters
                        {
                            CollectionName = collectionName,
                            Next           = 2
                        });
                        return(1);
                    }

                    var id = counter.Next;
                    return(id);
                }
                catch (MongoException ex)
                {
                    if (!ex.Message.Contains("duplicate key"))
                    {
                        throw;
                    }
                }
            }
        }
예제 #37
0
파일: QueryTests.cs 프로젝트: zulkamal/NoRM
        public void FindAndModify()
        {
            _collection.Insert(new Person {
                Name = "Joe Cool", Age = 10
            });

            var update = new Expando();

            update["$inc"] = new { Age = 1 };

            var result = _collection.FindAndModify(new { Name = "Joe Cool" }, update);

            Assert.Equal(10, result.Age);

            var result2 = _collection.Find(new { Name = "Joe Cool" }).FirstOrDefault();

            Assert.Equal(11, result2.Age);
        }
예제 #38
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 Expando();
         if (where.StartsWith("function"))
         {
             FlyWeight["$where"] = where;
         }
         else
         {
             FlyWeight["$where"] = " function(){return " + where + ";}";
         }
     }
 }
예제 #39
0
        /// <summary>
        /// Generates a new identity value
        /// </summary>
        /// <param name="collectionName">Collection Name</param>
        /// <param name="database"></param>
        /// <returns></returns>
        public long GenerateId(string collectionName, IMongoDatabase database)
        {
            while (true)
            {
                try
                {
                    var update = new Expando();
                    update["$inc"] = new { Next = 1 };

                    var counter = database.GetCollection<SequenceIdCounters>().FindAndModify(new { _id = collectionName }, update);

                    if (counter == null)
                    {
                        // account for starting seed
                        if (Seed != null)
                        {
                            database.GetCollection<SequenceIdCounters>()
                            .Insert(new SequenceIdCounters
                            {
                                CollectionName = collectionName,
                                Next = Seed.Value + 1
                            });
                            return Seed.Value;
                        }

                        database.GetCollection<SequenceIdCounters>()
                            .Insert(new SequenceIdCounters
                            {
                                CollectionName = collectionName,
                                Next = 2
                            });
                        return 1;
                    }

                    var id = counter.Next;
                    return id;
                }
                catch (MongoException ex)
                {
                    if (!ex.Message.Contains("duplicate key"))
                        throw;
                }
            }
        }
예제 #40
0
        Expando DeserializeTo(IXMLElement r, string name)
        {
            if (KnownTypes[name] == null)
            {
                return(null);
            }

            Expando z = KnownTypes[name].CreateType();


            foreach (IXMLElement x in r.childNodes)
            {
                if (x.nodeType == INode.NodeTypeEnum.ElementNode)
                {
                    if (z.Metadata[x.nodeName] == null)
                    {
                        z.SetMember(x.nodeName, x.innerXML);
                    }
                    else
                    {
                        if (z.Metadata[x.nodeName].IsArray)
                        {
                            IArray <object> a = new IArray <object>();

                            foreach (IXMLElement xx in x.childNodes)
                            {
                                if (xx.nodeType == INode.NodeTypeEnum.ElementNode)
                                {
                                    a += DeserializeTo(xx, xx.nodeName);
                                }
                            }

                            z.SetMember(x.nodeName, a);
                        }
                        else
                        {
                            z.SetMember(x.nodeName, DeserializeTo(x, z.Metadata[x.nodeName].GetValue()));
                        }
                    }
                }
            }

            return(z);
        }
예제 #41
0
파일: UpdateTests.cs 프로젝트: ashmind/NoRM
        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 Expando();
            query["_id"] = Q.Equals<ObjectId>(aPerson.Id);

            var retreivedPerson = _collection.FindOne(query);

            Assert.Equal("Velveeta", retreivedPerson.FavoriteCheese);
        }
예제 #42
0
파일: UpdateTests.cs 프로젝트: ashmind/NoRM
        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 Expando();
            query["Name"] = Q.Equals<string>("Joe");

            var retreivedPerson = _collection.FindOne(query);

            Assert.Equal("Gouda", retreivedPerson.FavoriteCheese);
        }
예제 #43
0
        public void TestExpando2()
        {
            dynamic NewD = new DynamicObjects.Builder<ExpandoObject>();

            var tExpandoNamedTest = NewD.Robot(
                LeftArm: "Rise",
                RightArm: "Clamp"
                );

            dynamic NewE = new Expando();

            var tExpandoNamedTestShortcut = NewE.Robot(
               LeftArm: "Rise",
               RightArm: "Clamp"
               );

            Assert.AreEqual("Rise", tExpandoNamedTestShortcut.LeftArm);
            Assert.AreEqual("Clamp", tExpandoNamedTestShortcut.RightArm);

            Assert.AreEqual(tExpandoNamedTest.LeftArm, tExpandoNamedTestShortcut.LeftArm);
            Assert.AreEqual(tExpandoNamedTest.RightArm, tExpandoNamedTestShortcut.RightArm);
            Assert.AreEqual(tExpandoNamedTest.GetType(), tExpandoNamedTestShortcut.GetType());
        }
예제 #44
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 Expando();
                query["Supplier.Name"] = Q.Equals("Supplier");

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

                Assert.Equal(1, result.Count());
            }
        }
예제 #45
0
        public void SerializesSharedReferencesInExpando()
        {
            Expression child = new Expression() { Title = "Child" };
            Expando top = new Expando();
            top["Title"] = "Top";
            top["Left"] = child;
            top["Right"] = child;

            var bytes = BsonSerializer.Serialize(top);
            var top2 = BsonDeserializer.Deserialize<Expando>(bytes);

            Assert.Equal(top["Title"], top2["Title"]);
            Assert.Equal(child.Title, ((Expression)top2["Left"]).Title);
            Assert.Equal(child.Title, ((Expression)top2["Right"]).Title);

            // Modify Left and verify that Right is modified too
            ((Expression)top2["Left"]).Title = "Changed";
            Assert.Equal(((Expression)top2["Left"]).Title, ((Expression)top2["Right"]).Title);
        }
예제 #46
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 Expando();
            query["Name"] = Q.Equals<string>("Joseph");

            var retreivedPerson = _collection.FindOne(query);

            Assert.Null(retreivedPerson.FavoriteCheese);
        }
예제 #47
0
        public void SerializesSharedExpandoInExpando()
        {
            Expando child = new Expando();
            child["Title"] = "Child";

            Expando top = new Expando();
            top["Title"] = "Top";
            top["Left"] = child;
            top["Right"] = child;

            var bytes = BsonSerializer.Serialize(top);
            var top2 = BsonDeserializer.Deserialize<Expando>(bytes);

            Assert.Equal(top["Title"], top2["Title"]);
            Assert.Equal(child["Title"], ((Expando)top2["Left"])["Title"]);
            Assert.Equal(child["Title"], ((Expando)top2["Right"])["Title"]);

            // Modify Left and verify that Right is modified too
            ((Expando)top2["Left"])["Title"] = "Changed";
            Assert.Equal(((Expando)top2["Left"])["Title"], ((Expando)top2["Right"])["Title"]);
        }
예제 #48
0
파일: Expando.cs 프로젝트: Exclr8/CloudCore
        public void ExpandoObjectXmlTest()
        {
            dynamic ex = new Expando();
            ex.Name = "Alex";
            ex.Entered = DateTime.Now;

            string address = "64 Atlantic Beach Drive";

            ex.Address = address;
            ex.Contacted = true;

            ex.Count = 10;
            ex.Completed = DateTime.Now.AddHours(2);

            string xml = null;
            Assert.IsTrue(Core.Utilities.Serialization.SerializeObject(ex as Expando, out xml, true));


            Console.WriteLine(xml);
        }
예제 #49
0
        /// <summary>TODO::Description.</summary>
        public string Translate(Expression exp, bool useScopedQualifier)
        {
            UseScopedQualifier = useScopedQualifier;
            _sbWhere = new StringBuilder();
            _sbIndexed = new StringBuilder();
            FlyWeight = new Expando();
            SortFly = new Expando();

            Visit(exp);

            TransformToFlyWeightWhere();

            return WhereExpression;
        }
예제 #50
0
        public void FindAndModifyReturnsNullWhenQueryNotFound()
        {
            _collection.Insert(new Person { Name = "Joe Cool", Age = 10 });
            _collection.Insert(new Person { Name = "Joe Cool", Age = 15 });

            var update = new Expando();
            update["$inc"] = new { Age = 1 };

            var result = _collection.FindAndModify(new { Name = "Joe Cool1" }, update, new { Age = Norm.OrderBy.Descending });
            Assert.Null(result);

            var result2 = _collection.Find(new { Age = 15 }).ToList();
            Assert.Equal(1, result2.Count);
        }
예제 #51
0
파일: Expando.cs 프로젝트: Exclr8/CloudCore
        public void Class2ExpandoTest()
        {
            NonExpandoClass myNonExandoClass = new NonExpandoClass() { Name = "Mannetjie", Age = 86 };
            dynamic myExandoClass = new Expando(myNonExandoClass);
            myExandoClass.Snoop = "Snoopy";
            Assert.IsTrue(myExandoClass.Name == "Mannetjie");
            Assert.IsTrue(myExandoClass.Snoop == "Snoopy");


        }
예제 #52
0
        public void FindAndModify()
        {
            _collection.Insert(new Person { Name = "Joe Cool", Age = 10 });

            var update = new Expando();
            update["$inc"] = new { Age = 1 };

            var result = _collection.FindAndModify(new { Name = "Joe Cool" }, update);
            Assert.Equal(10, result.Age);

            var result2 = _collection.Find(new { Name = "Joe Cool" }).FirstOrDefault();
            Assert.Equal(11, result2.Age);
        }
예제 #53
0
        public void FindAndModifyWithSort()
        {
            _collection.Insert(new Person { Name = "Joe Cool", Age = 10 });
            _collection.Insert(new Person { Name = "Joe Cool", Age = 15 });

            var update = new Expando();
            update["$inc"] = new { Age = 1 };

            var result = _collection.FindAndModify(new { Name = "Joe Cool" }, update, new { Age = Norm.OrderBy.Descending });
            Assert.Equal(15, result.Age);

            var result2 = _collection.Find(new { Name = "Joe Cool" }).OrderByDescending(x => x.Age).ToList();
            Assert.Equal(16, result2[0].Age);
            Assert.Equal(10, result2[1].Age);

        }
예제 #54
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 Expando();
            elem["Relatives"] = "Charlie";
            var a = _collection.Find(elem).ToArray();
            Assert.Equal(1, a.Length);
        }
예제 #55
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 Expando();
         if (where.StartsWith("function"))
         {
             FlyWeight["$where"] = where;
         }
         else
         {
             FlyWeight["$where"] = " function(){return " + where + ";}";
         }
     }
 }
예제 #56
0
 public ActionResult Undefined(string displayText)
 {
     dynamic displayItem = new Expando();
     displayItem.Text = displayText;
     return View(displayItem);
 }
예제 #57
0
 public void Expando_Get_Should_Throw_Exception_When_Property_Doesnt_Exist()
 {
     Assert.Throws<InvalidOperationException>(() => { var a = new Expando(); a.Get<bool>("doesn't exist"); });
 }
예제 #58
0
        public void SerializationOfScopedCodeIsNotLossy()
        {
            var obj1 = new GeneralDTO {Code = new ScopedCode {CodeString = "function(){return 'hello world!'}"}};
            var scope = new Expando();
            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(((Expando)obj1.Code.Scope)["$ns"],((Expando)obj2.Code.Scope)["$ns"]);
        }
예제 #59
0
        /// <summary>
        /// Translates LINQ to MongoDB.
        /// </summary>
        /// <param retval="exp">The expression.</param>
        /// <param retval="useScopedQualifier">Whether to use the "this" qualifier</param>
        /// <returns>The translated string</returns>
        public QueryTranslationResults Translate(Expression exp, bool useScopedQualifier)
        {
            UseScopedQualifier = useScopedQualifier;
            _sbWhere = new StringBuilder();
            FlyWeight = new Expando();
            SortFly = new Expando();

            Visit(exp);

            ProcessGuards();
            TransformToFlyWeightWhere();

            return new QueryTranslationResults
                       {
                           Where = FlyWeight,
                           Sort = SortFly,
                           Skip = Skip,
                           Take = Take,
                           CollectionName = CollectionName,
                           MethodCall = MethodCall,
                           AggregatePropName = AggregatePropName,
                           IsComplex = IsComplex,
                           TypeName = TypeName,
                           Query = WhereExpression,
                           Select = SelectLambda,
                           OriginalSelectType = OriginalSelectType
                       };
        }
예제 #60
0
        public IEnumerable<INativeElement> GetElementsWithQuerySelector(ICssSelector selector, DomContainer domContainer)
        {
            var container = "document";
            if (_element != null)
            {
                var elementTag = new ElementTag(_element.TagName);
                if (elementTag.Equals(new ElementTag("frame")) || elementTag.Equals(new ElementTag("iframe")))
                {
                    var frameHierarchy = _element.GetAttributeValue("data-watinFrameHierarchy");
                    container = frameHierarchy + ".document";
                }
                else
                {
                    var document = _element.AsHtmlElement.document;
                    var result = new Expando(document).GetValue<string>("___WATINFRAMEHIERARCHY");

                    container = "";
                    if (result != null)
                        container = result;

                    if (!string.IsNullOrEmpty(container))
                        container += ".";

                    container += _element.GetJavaScriptElementReference();
                }
            }
            else
            {
                //container = CreateArray();
            }

            domContainer.RunScript(new ScriptLoader().GetSizzleInstallScript());

            var code = string.Format("document.___WATINRESULT = Sizzle('{0}', {1});", selector.Selector(true), container);
            domContainer.RunScript(code);

            return new JScriptElementArrayEnumerator((IEDocument) domContainer.NativeDocument, "___WATINRESULT");
        }