/// <summary>
 /// 使用属性会发生一些MONO上的移植问题
 /// </summary>
 /// <returns></returns>
 public BsonValue getValue()
 {
     BsonValue mValue = null;
     switch (cmbDataType.SelectedIndex)
     {
         case 0:
             mValue = new BsonString(txtBsonValue.Text);
             break;
         case 1:
             mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value));
             break;
         case 2:
             mValue = new BsonDateTime(dateTimePicker.Value);
             break;
         case 3:
             if (radTrue.Checked)
             {
                 mValue = BsonBoolean.True;
             }
             else
             {
                 mValue = BsonBoolean.False;
             }
             break;
         case 4:
             mValue = mBsonArray;
             break;
         case 5:
             mValue = mBsonDocument;
             break;
     }
     return mValue;
 }
 public void TestSetDocumentIdBsonValue()
 {
     var document = new BsonDocument { { "x", "abc" } };
     var id = new BsonInt32(1);
     ((IBsonIdProvider)BsonDocumentSerializer.Instance).SetDocumentId(document, id);
     Assert.IsTrue(document["_id"].IsInt32);
     Assert.AreEqual(1, document["_id"].AsInt32);
 }
        public void CompareTo_BsonDouble_should_return_expected_result(int int32Value, double otherDoubleValue, int expectedResult)
        {
            var subject = new BsonInt32(int32Value);
            var other = new BsonDouble(otherDoubleValue);

            var result = subject.CompareTo(other);

            result.Should().Be(expectedResult);
        }
        public void CompareTo_BsonInt32_should_return_expected_result(long int64Value, int otherInt32Value, int expectedResult)
        {
            var subject = new BsonInt64(int64Value);
            var other = new BsonInt32(otherInt32Value);

            var result = subject.CompareTo(other);

            result.Should().Be(expectedResult);
        }
        public void CompareTo_BsonInt32_should_return_expected_result(int int32Value, int otherInt32Value, int expectedResult)
        {
            var subject = new BsonInt32(int32Value);
            var other = new BsonInt32(otherInt32Value);

            var result1 = subject.CompareTo((BsonInt32)other);
            var result2 = subject.CompareTo((BsonValue)other);

            result1.Should().Be(expectedResult);
            result2.Should().Be(expectedResult);
        }
 public void TestCompareOneAndTwo()
 {
     var n1 = new BsonInt32(1);
     var n2 = new BsonInt32(2);
     Assert.IsTrue(n1 < n2);
     Assert.IsTrue(n1 <= n2);
     Assert.IsTrue(n1 != n2);
     Assert.IsFalse(n1 == n2);
     Assert.IsFalse(n1 > n2);
     Assert.IsFalse(n1 >= n2);
 }
 public void TestCompareDifferentTypeOnes()
 {
     var n1 = new BsonInt32(1);
     var n2 = new BsonInt64(1);
     var n3 = new BsonDouble(1.0);
     Assert.IsTrue(n1 == n2);
     Assert.IsTrue(n1 == n3);
     Assert.IsTrue(n2 == n1);
     Assert.IsTrue(n2 == n3);
     Assert.IsTrue(n3 == n1);
     Assert.IsTrue(n3 == n2);
 }
        public void TestBsonInt32()
        {
            var value = new BsonInt32(1);

            Assert.AreEqual(true, Convert.ToBoolean(value));
            Assert.AreEqual(1, Convert.ToByte(value));
            Assert.AreEqual(1, Convert.ToChar(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value));
            Assert.AreEqual(1m, Convert.ToDecimal(value));
            Assert.AreEqual(1.0, Convert.ToDouble(value));
            Assert.AreEqual(1, Convert.ToInt16(value));
            Assert.AreEqual(1, Convert.ToInt32(value));
            Assert.AreEqual(1, Convert.ToInt64(value));
            Assert.AreEqual(1, Convert.ToSByte(value));
            Assert.AreEqual(1.0F, Convert.ToSingle(value));
            Assert.AreEqual("1", Convert.ToString(value));
            Assert.AreEqual(1, Convert.ToUInt16(value));
            Assert.AreEqual(1, Convert.ToUInt32(value));
            Assert.AreEqual(1, Convert.ToUInt64(value));
        }
        public void TestClassWithBsonInt32Id()
        {
            _collection.RemoveAll();

            var doc = new ClassWithBsonInt32Id {
                Id = null, X = 1
            };

            _collection.Insert(doc);

            doc = new ClassWithBsonInt32Id {
                Id = BsonInt32.Create(0), X = 1
            };
            _collection.Insert(doc);

            doc = new ClassWithBsonInt32Id {
                Id = BsonInt32.Create(1), X = 1
            };
            _collection.Insert(doc);
        }
Beispiel #10
0
        /// <summary>
        /// Really only for dev view - return a tuple for each StudentLessonActs
        /// instance defined as (LessonID, UserID, TurnCount)
        /// </summary>
        /// <returns>List of tuples</returns>
        public List <Tuple <string, string, int> > FindTurnSummary()
        {
            var collect = mongoDatabase.GetCollection(STUDENT_ACT_COLLECTION);
            var results = collect.FindAllAs <BsonDocument>()
                          .SetFields(Fields
                                     .Include("LessonID")
                                     .Include("UserID")
                                     .Include("TurnCount"));

            var ret = new List <Tuple <string, string, int> >();

            foreach (var one in results)
            {
                BsonValue lessonID;
                BsonValue userID;
                BsonValue turnCount;

                if (!one.TryGetValue("LessonID", out lessonID) || !lessonID.IsString)
                {
                    lessonID = new BsonString("???");
                }

                if (!one.TryGetValue("UserID", out userID) || !userID.IsString)
                {
                    userID = new BsonString("???");
                }

                if (!one.TryGetValue("TurnCount", out turnCount) || !turnCount.IsNumeric)
                {
                    turnCount = new BsonInt32(0);
                }

                ret.Add(new Tuple <string, string, int>(
                            lessonID.AsString,
                            userID.AsString,
                            turnCount.AsInt32));
            }

            ret.Sort();
            return(ret);
        }
        public void TestBsonInt32()
        {
            var value = new BsonInt32(1);

            Assert.Same(value, ((IConvertible)value).ToType(typeof(object), null));
            Assert.Equal(true, Convert.ToBoolean(value));
            Assert.Equal(1, Convert.ToByte(value));
            Assert.Equal(1, Convert.ToChar(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value));
            Assert.Equal(1m, Convert.ToDecimal(value));
            Assert.Equal(1.0, Convert.ToDouble(value));
            Assert.Equal(1, Convert.ToInt16(value));
            Assert.Equal(1, Convert.ToInt32(value));
            Assert.Equal(1, Convert.ToInt64(value));
            Assert.Equal(1, Convert.ToSByte(value));
            Assert.Equal(1.0F, Convert.ToSingle(value));
            Assert.Equal("1", Convert.ToString(value));
            Assert.Equal(1, Convert.ToUInt16(value));
            Assert.Equal(1U, Convert.ToUInt32(value));
            Assert.Equal(1UL, Convert.ToUInt64(value));
        }
Beispiel #12
0
        public void TestOpenCreateWithId()
        {
            gridFS.Files.RemoveAll();
            gridFS.Chunks.RemoveAll();
            gridFS.Chunks.ResetIndexCache();

            var createOptions = new MongoGridFSCreateOptions
            {
                Id = 1
            };

            using (var stream = gridFS.Create("test", createOptions))
            {
                var bytes = new byte[] { 1, 2, 3, 4 };
                stream.Write(bytes, 0, 4);
            }

            var fileInfo = gridFS.FindOne("test");

            Assert.AreEqual(BsonInt32.Create(1), fileInfo.Id);
        }
        public void TestCompareDifferentTypeOnes()
        {
            var n1 = new BsonInt32(1);
            var n2 = new BsonInt64(1);
            var n3 = new BsonDouble(1.0);
            Assert.IsTrue(n1 == n2);
            Assert.IsTrue(n1 == n3);
            Assert.IsTrue(n2 == n1);
            Assert.IsTrue(n2 == n3);
            Assert.IsTrue(n3 == n1);
            Assert.IsTrue(n3 == n2);

            var v1 = (BsonValue)new BsonInt32(1);
            var v2 = (BsonValue)new BsonInt64(1);
            var v3 = (BsonValue)new BsonDouble(1.0);
            Assert.IsTrue(v1 == v2);
            Assert.IsTrue(v1 == v3);
            Assert.IsTrue(v2 == v1);
            Assert.IsTrue(v2 == v3);
            Assert.IsTrue(v3 == v1);
            Assert.IsTrue(v3 == v2);
        }
        /// <summary>
        /// 使用属性会发生一些MONO上的移植问题
        /// </summary>
        /// <returns></returns>
        public BsonValue getValue()
        {
            BsonValue mValue = null;

            switch (cmbDataType.SelectedIndex)
            {
            case 0:
                mValue = new BsonString(txtBsonValue.Text);
                break;

            case 1:
                mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value));
                break;

            case 2:
                mValue = new BsonDateTime(dateTimePicker.Value);
                break;

            case 3:
                if (radTrue.Checked)
                {
                    mValue = BsonBoolean.True;
                }
                else
                {
                    mValue = BsonBoolean.False;
                }
                break;

            case 4:
                mValue = mBsonArray;
                break;

            case 5:
                mValue = mBsonDocument;
                break;
            }
            return(mValue);
        }
Beispiel #15
0
        /// <summary>
        ///     还原BsonValue
        /// </summary>
        /// <returns></returns>
        public BsonValue GetBsonValue()
        {
            BsonValue value = new BsonString(string.Empty);

            switch (mBsonType)
            {
            case BasicType.BsonString:
                value = new BsonString(mBsonString);
                break;

            case BasicType.BsonInt32:
                value = new BsonInt32(mBsonInt32);
                break;

            case BasicType.BsonInt64:
                value = new BsonInt64(mBsonInt64);
                break;

            case BasicType.BsonDecimal128:
                value = new BsonDecimal128(mBSonDecimal128);
                break;

            case BasicType.BsonDouble:
                value = new BsonDouble(mBsonDouble);
                break;

            case BasicType.BsonDateTime:
                value = new BsonDateTime(mBsonDateTime);
                break;

            case BasicType.BsonBoolean:
                value = mBsonBoolean ? BsonBoolean.True : BsonBoolean.False;
                break;
            }
            return(value);
        }
        public void TestCompareDifferentTypeOnes()
        {
            var n1 = new BsonInt32(1);
            var n2 = new BsonInt64(1);
            var n3 = new BsonDouble(1.0);

            Assert.IsTrue(n1 == n2);
            Assert.IsTrue(n1 == n3);
            Assert.IsTrue(n2 == n1);
            Assert.IsTrue(n2 == n3);
            Assert.IsTrue(n3 == n1);
            Assert.IsTrue(n3 == n2);

            var v1 = (BsonValue) new BsonInt32(1);
            var v2 = (BsonValue) new BsonInt64(1);
            var v3 = (BsonValue) new BsonDouble(1.0);

            Assert.IsTrue(v1 == v2);
            Assert.IsTrue(v1 == v3);
            Assert.IsTrue(v2 == v1);
            Assert.IsTrue(v2 == v3);
            Assert.IsTrue(v3 == v1);
            Assert.IsTrue(v3 == v2);
        }
        private static BsonValue GetValueDifferenceAsBsonValue(IMemberDirtyTracker memberTracker)
        {
            BsonValue currentValue = memberTracker.CurrentValue, originalValue = memberTracker.OriginalValue;

            if (currentValue.BsonType != originalValue.BsonType)
            {
                throw new InvalidOperationException("BSON type of current value does not equal the original value");
            }

            BsonValue incrementBy;

            switch (currentValue.BsonType)
            {
            case BsonType.Double:
                incrementBy = new BsonDouble(currentValue.AsDouble - originalValue.AsDouble);
                break;

            case BsonType.Int32:
                incrementBy = new BsonInt32(currentValue.AsInt32 - originalValue.AsInt32);
                break;

            case BsonType.Int64:
                incrementBy = new BsonInt64(currentValue.AsInt64 - originalValue.AsInt64);
                break;

            case BsonType.Decimal128:
                incrementBy = new BsonDecimal128(currentValue.AsDecimal - originalValue.AsDecimal);
                break;

            default:
                throw new InvalidOperationException(
                          $"BSON type {memberTracker.CurrentValue.BsonType} cannot be incrementally updated");
            }

            return(incrementBy);
        }
Beispiel #18
0
        /// <summary>
        ///     还原BsonValue
        /// </summary>
        /// <returns></returns>
        public BsonValue GetBsonValue()
        {
            BsonValue value = new BsonString(string.Empty);

            switch (MBsonType)
            {
            case "BsonString":
                value = new BsonString(MBsonString);
                break;

            case "BsonInt32":
                value = new BsonInt32(MBsonInt32);
                break;

            case "BsonDateTime":
                value = new BsonDateTime(MBsonDateTime);
                break;

            case "BsonBoolean":
                value = MBsonBoolean ? BsonBoolean.True : BsonBoolean.False;
                break;
            }
            return(value);
        }
        public JsonResult Run(string ID, int version = -1)
        {
            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID));

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            if (doc == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The scene is not existed!"
                }));
            }

            // 获取场景数据
            var collectionName = doc["CollectionName"].AsString;

            List <BsonDocument> docs;

            if (version == -1) // 最新版本
            {
                docs = mongo.FindAll(collectionName).ToList();
            }
            else // 特定版本
            {
                filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version));

                docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList();
            }

            // 创建临时目录
            var now = DateTime.Now;

            var path = HttpContext.Current.Server.MapPath($"~/temp/{now.ToString("yyyyMMddHHmmss")}");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // 拷贝静态资源
            var viewPath = HttpContext.Current.Server.MapPath("~/view.html");

            var viewFileData = File.ReadAllText(viewPath, Encoding.UTF8);

            viewFileData = viewFileData.Replace("location.origin", "'.'"); // 替换server地址,以便部署到Git Pages上
            File.WriteAllText($"{path}/view.html", viewFileData, Encoding.UTF8);

            var faviconPath = HttpContext.Current.Server.MapPath("~/favicon.ico");

            File.Copy(faviconPath, $"{path}/favicon.ico", true);

            var assetsPath = HttpContext.Current.Server.MapPath($"~/assets");

            DirectoryHelper.Copy(assetsPath, $"{path}/assets");

            var buildPath = HttpContext.Current.Server.MapPath($"~/build");

            DirectoryHelper.Copy(buildPath, $"{path}/build");

            // 分析场景,拷贝使用的资源
            var data = new JArray();

            var urls = new List <string>();

            foreach (var i in docs)
            {
                i["_id"] = i["_id"].ToString(); // ObjectId

                var generator = i["metadata"]["generator"].ToString();

                if (generator == "ServerObject")                            // 服务端模型
                {
                    urls.Add(i["userData"]["Url"].ToString());              // 模型文件

                    if (i["userData"].AsBsonDocument.Contains("Animation")) // MMD模型动画
                    {
                        urls.Add(i["userData"]["Animation"]["Url"].ToString());
                    }
                    if (i["userData"].AsBsonDocument.Contains("CameraAnimation")) // MMD相机动画
                    {
                        urls.Add(i["userData"]["CameraAnimation"]["Url"].ToString());
                    }
                    if (i["userData"].AsBsonDocument.Contains("Audio")) // MMD音频
                    {
                        urls.Add(i["userData"]["Audio"]["Url"].ToString());
                    }
                }
                else if (generator == "SceneSerializer")                                                    // 场景
                {
                    if (i["background"].IsBsonDocument)                                                     // 贴图或立方体纹理
                    {
                        if (i["background"]["metadata"]["generator"].ToString() == "CubeTextureSerializer") // 立方体纹理
                        {
                            var array = i["background"]["image"].AsBsonArray;
                            foreach (var j in array)
                            {
                                urls.Add(j["src"].ToString());
                            }
                        }
                        else // 普通纹理
                        {
                            urls.Add(i["background"]["image"]["src"].ToString());
                        }
                    }
                }
                else if (generator == "MeshSerializer" || generator == "SpriteSerializer") // 模型
                {
                    if (i["material"]["alphaMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["alphaMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["aoMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["aoMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["bumpMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["bumpMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["displacementMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["displacementMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["emissiveMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["emissiveMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["envMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["envMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["lightMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["lightMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["map"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["map"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["metalnessMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["metalnessMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["normalMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["normalMap"]["image"]["src"].ToString());
                    }
                    else if (i["material"]["roughnessMap"].IsBsonDocument)
                    {
                        urls.Add(i["material"]["roughnessMap"]["image"]["src"].ToString());
                    }
                }

                data.Add(JsonHelper.ToObject <JObject>(i.ToJson()));
            }

            // 将场景写入文件
            if (!Directory.Exists($"{path}/Scene"))
            {
                Directory.CreateDirectory($"{path}/Scene");
            }

            // 复制资源
            var file   = new FileStream($"{path}/Scene/{ID}.txt", FileMode.Create, FileAccess.Write);
            var writer = new StreamWriter(file);

            writer.Write(JsonHelper.ToJson(data));
            writer.Close();
            file.Close();

            foreach (var url in urls)
            {
                if (!url.StartsWith("/")) // 可能是base64地址
                {
                    continue;
                }

                // LOL模型存在多个url,两个url之间用分号分隔
                var _urls = url.Split(';');

                foreach (var _url in _urls)
                {
                    if (string.IsNullOrEmpty(_url))
                    {
                        continue;
                    }

                    var sourceDirName = Path.GetDirectoryName(HttpContext.Current.Server.MapPath($"~{_url}"));
                    var targetDirName = Path.GetDirectoryName($"{path}{_url}");

                    DirectoryHelper.Copy(sourceDirName, targetDirName);
                }
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Export successfully!",
                Url = $"/temp/{now.ToString("yyyyMMddHHmmss")}/view.html?sceneFile={ID}"
            }));
        }
Beispiel #20
0
        public void EqualTwoDifferentBsonValues()
        {
            // Arrange
            var a = new BsonInt32(100);
            var b = new BsonInt32(200);

            // Act
            var eq = a.Equal(b);

            // Assert
            Assert.False(eq);
        }
Beispiel #21
0
        public void TestExtraElementsOfAllTypes()
        {
            var json          = "{ '_id' : 1, 'A' : 2, 'B' : 3, #X }";
            var extraElements = new string[][]
            {
                new string[] { "XArray", "[1, 2.0]" },
                new string[] { "XBinary", "HexData(2, '1234')" },
                new string[] { "XBoolean", "true" },
                new string[] { "XByteArray", "HexData(0, '1234')" },
                new string[] { "XDateTime", "ISODate('2012-03-16T11:19:00Z')" },
                new string[] { "XDocument", "{ 'a' : 1 }" },
                new string[] { "XDouble", "1.0" },
                new string[] { "XGuidLegacy", "HexData(3, '33221100554477668899aabbccddeeff')" },
                new string[] { "XGuidStandard", "HexData(4, '00112233445566778899aabbccddeeff')" },
                new string[] { "XInt32", "1" },
                new string[] { "XInt64", "NumberLong(1)" },
                new string[] { "XJavaScript", "{ '$code' : 'abc' }" },
                new string[] { "XJavaScriptWithScope", "{ '$code' : 'abc', '$scope' : { 'x' : 1 } }" },
                new string[] { "XMaxKey", "{ '$maxkey' : 1 }" },
                new string[] { "XMinKey", "{ '$minkey' : 1 }" },
                new string[] { "XNull", "null" },
                new string[] { "XObjectId", "ObjectId('00112233445566778899aabb')" },
                new string[] { "XRegularExpression", "/abc/" },
                new string[] { "XString", "'abc'" },
                new string[] { "XSymbol", "{ '$symbol' : 'abc' }" },
                new string[] { "XTimestamp", "{ '$timestamp' : NumberLong(1234) }" },
                new string[] { "XUndefined", "undefined" },
            };
            var extraElementsRepresentation = string.Join(", ", extraElements.Select(e => string.Format("'{0}' : {1}", e[0], e[1])).ToArray());

            json = json.Replace("#X", extraElementsRepresentation).Replace("'", "\"");
            var c = BsonSerializer.Deserialize <C>(json);

            // round trip it both ways before checking individual values
            json = c.ToJson();
            c    = BsonSerializer.Deserialize <C>(json);

            Assert.IsInstanceOf <List <object> >(c.X["XArray"]);
            Assert.IsInstanceOf <BsonBinaryData>(c.X["XBinary"]);
            Assert.IsInstanceOf <bool>(c.X["XBoolean"]);
            Assert.IsInstanceOf <byte[]>(c.X["XByteArray"]);
            Assert.IsInstanceOf <DateTime>(c.X["XDateTime"]);
            Assert.IsInstanceOf <Dictionary <string, object> >(c.X["XDocument"]);
            Assert.IsInstanceOf <double>(c.X["XDouble"]);
            Assert.IsInstanceOf <Guid>(c.X["XGuidLegacy"]);
            Assert.IsInstanceOf <Guid>(c.X["XGuidStandard"]);
            Assert.IsInstanceOf <int>(c.X["XInt32"]);
            Assert.IsInstanceOf <long>(c.X["XInt64"]);
            Assert.IsInstanceOf <BsonJavaScript>(c.X["XJavaScript"]);
            Assert.IsInstanceOf <BsonJavaScriptWithScope>(c.X["XJavaScriptWithScope"]);
            Assert.IsInstanceOf <BsonMaxKey>(c.X["XMaxKey"]);
            Assert.IsInstanceOf <BsonMinKey>(c.X["XMinKey"]);
            Assert.IsNull(c.X["XNull"]);
            Assert.IsInstanceOf <ObjectId>(c.X["XObjectId"]);
            Assert.IsInstanceOf <BsonRegularExpression>(c.X["XRegularExpression"]);
            Assert.IsInstanceOf <string>(c.X["XString"]);
            Assert.IsInstanceOf <BsonSymbol>(c.X["XSymbol"]);
            Assert.IsInstanceOf <BsonTimestamp>(c.X["XTimestamp"]);
            Assert.IsInstanceOf <BsonUndefined>(c.X["XUndefined"]);

            Assert.AreEqual(22, c.X.Count);
            Assert.IsTrue(new object[] { 1, 2.0 }.SequenceEqual((List <object>)c.X["XArray"]));
#pragma warning disable 618 // OldBinary is obsolete
            Assert.AreEqual(BsonBinarySubType.OldBinary, ((BsonBinaryData)c.X["XBinary"]).SubType);
#pragma warning restore 618
            Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual(((BsonBinaryData)c.X["XBinary"]).Bytes));
            Assert.AreEqual(true, c.X["XBoolean"]);
            Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual((byte[])c.X["XByteArray"]));
            Assert.AreEqual(new DateTime(2012, 3, 16, 11, 19, 0, DateTimeKind.Utc), c.X["XDateTime"]);
            Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"]).Count);
            Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"])["a"]);
            Assert.AreEqual(1.0, c.X["XDouble"]);
            Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidLegacy"]);
            Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidStandard"]);
            Assert.AreEqual(1, c.X["XInt32"]);
            Assert.AreEqual(1L, c.X["XInt64"]);
            Assert.AreEqual("abc", ((BsonJavaScript)c.X["XJavaScript"]).Code);
            Assert.AreEqual("abc", ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Code);
            Assert.AreEqual(1, ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope.ElementCount);
            Assert.AreEqual(BsonInt32.Create(1), ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope["x"]);
            Assert.AreSame(BsonMaxKey.Value, c.X["XMaxKey"]);
            Assert.AreSame(BsonMinKey.Value, c.X["XMinKey"]);
            Assert.AreEqual(null, c.X["XNull"]);
            Assert.AreEqual(ObjectId.Parse("00112233445566778899aabb"), c.X["XObjectId"]);
            Assert.AreEqual(new BsonRegularExpression("abc"), c.X["XRegularExpression"]);
            Assert.AreEqual("abc", c.X["XString"]);
            Assert.AreSame(BsonSymbol.Create("abc"), c.X["XSymbol"]);
            Assert.AreEqual(BsonTimestamp.Create(1234), c.X["XTimestamp"]);
            Assert.AreSame(BsonUndefined.Value, c.X["XUndefined"]);
        }
Beispiel #22
0
 /// <summary>
 ///     使用属性会发生一些MONO上的移植问题
 /// </summary>
 /// <returns></returns>
 public BsonValue GetValue(BsonValueEx.BasicType DataType)
 {
     BsonValue mValue = null;
     switch (DataType)
     {
         case BsonValueEx.BasicType.BsonString:
             mValue = new BsonString(txtBsonValue.Text);
             break;
         case BsonValueEx.BasicType.BsonInt32:
             mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value));
             break;
         case BsonValueEx.BasicType.BsonInt64:
             mValue = new BsonInt64(Convert.ToInt64(NumberPick.Value));
             break;
         case BsonValueEx.BasicType.BsonDecimal128:
             mValue = new BsonDecimal128(Convert.ToDecimal(NumberPick.Value));
             break;
         case BsonValueEx.BasicType.BsonDouble:
             mValue = new BsonDouble(Convert.ToDouble(txtBsonValue.Text));
             break;
         case BsonValueEx.BasicType.BsonDateTime:
             mValue = new BsonDateTime(dateTimePicker.Value);
             break;
         case BsonValueEx.BasicType.BsonBoolean:
             mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False;
             break;
         case BsonValueEx.BasicType.BsonArray:
         case BsonValueEx.BasicType.BsonLegacyPoint:
             mValue = _mBsonArray;
             break;
         case BsonValueEx.BasicType.BsonGeoJSON:
         case BsonValueEx.BasicType.BsonDocument:
             mValue = _mBsonDocument;
             break;
         case BsonValueEx.BasicType.BsonMaxKey:
             mValue = BsonMaxKey.Value;
             break;
         case BsonValueEx.BasicType.BsonMinKey:
             mValue = BsonMinKey.Value;
             break;
         case BsonValueEx.BasicType.BsonBinary:
             mValue = new BsonBinaryData(Encoding.Default.GetBytes(txtBsonValue.Text));
             break;
     }
     return mValue;
 }
 /// <summary>
 ///     还原BsonValue
 /// </summary>
 /// <returns></returns>
 public BsonValue GetBsonValue()
 {
     BsonValue Value = new BsonString(String.Empty);
     switch (mBsonType)
     {
         case "BsonString":
             Value = new BsonString(mBsonString);
             break;
         case "BsonInt32":
             Value = new BsonInt32(mBsonInt32);
             break;
         case "BsonDateTime":
             Value = new BsonDateTime(mBsonDateTime);
             break;
         case "BsonBoolean":
             Value = mBsonBoolean ? BsonBoolean.True : BsonBoolean.False;
             break;
         default:
             break;
     }
     return Value;
 }
Beispiel #24
0
 /// <summary>
 ///     还原BsonValue
 /// </summary>
 /// <returns></returns>
 public BsonValue GetBsonValue()
 {
     BsonValue value = new BsonString(string.Empty);
     switch (MBsonType)
     {
         case "BsonString":
             value = new BsonString(MBsonString);
             break;
         case "BsonInt32":
             value = new BsonInt32(MBsonInt32);
             break;
         case "BsonDateTime":
             value = new BsonDateTime(MBsonDateTime);
             break;
         case "BsonBoolean":
             value = MBsonBoolean ? BsonBoolean.True : BsonBoolean.False;
             break;
         case "BsonDouble":
             value = new BsonDouble(MBsonDouble);
             break;
     }
     return value;
 }
 public void TestCompareTwoOnes()
 {
     var n1 = new BsonInt32(1);
     var n2 = new BsonInt32(1);
     Assert.False(n1 < n2);
     Assert.True(n1 <= n2);
     Assert.False(n1 != n2);
     Assert.True(n1 == n2);
     Assert.False(n1 > n2);
     Assert.True(n1 >= n2);
 }
        /// <summary>
        /// Gets the data for one custom field, and any relevant GUIDs.
        /// </summary>
        /// <param name="hvo">Hvo of object we're getting the field for.</param>
        /// <param name="flid">Flid for this field.</param>
        /// <param name="fieldSourceType">Either "entry", "senses" or "examples". Could also be "allomorphs", eventually.</param>
        /// <param name="bsonForThisField">Output of a BsonDocument with the following structure: <br />
        /// { fieldName: { "value": BsonValue, "guid": "some-guid-as-a-string" } } <br />
        /// -OR- <br />
        /// { fieldName: { "value": BsonValue, "guid": ["guid1", "guid2", "guid3"] } } <br />
        /// The format of the fieldName key will be "customField_FOO_field_name_with_underscores",
        /// where FOO is one of "entry", "senses", or "examples". <br />
        /// The type of the "guid" value (array or string) will determine whether there is a single GUID,
        /// or a list of GUIDs that happens to contain only one entry.
        /// If there is no "guid" key, that field has no need for a GUID. (E.g., a number).
        /// </param>
        /// <param name="listConverters">Dictionary of ConvertFdoToMongoOptionList instances, keyed by list code</param>
        /// <param name="customFieldType">output string of LF custom field type</param>
        private void GetCustomFieldData(int hvo, int flid, string fieldSourceType,
			IDictionary<string, ConvertFdoToMongoOptionList> listConverters,
			out BsonDocument bsonForThisField, out string customFieldType)
        {
            bsonForThisField = null;
            customFieldType = string.Empty;
            BsonValue fieldValue = null;
            BsonValue fieldGuid = null; // Might be a single value, might be a list (as a BsonArray)
            ISilDataAccessManaged data = (ISilDataAccessManaged)cache.DomainDataByFlid;
            CellarPropertyType fdoFieldType = (CellarPropertyType)fdoMetaData.GetFieldType(flid);
            var dataGuids = new List<Guid>();

            // Valid field types in FDO are GenDate, Integer, String, OwningAtomic, ReferenceAtomic, and ReferenceCollection, so that's all we implement.
            switch (fdoFieldType)
            {
            case CellarPropertyType.GenDate:
                GenDate genDate = data.get_GenDateProp(hvo, flid);
                string genDateStr = genDate.ToLongString();
                // LF wants single-string fields in the format { "ws": { "value": "contents" } }
                fieldValue = String.IsNullOrEmpty(genDateStr) ? null :
                    LfMultiText.FromSingleStringMapping(
                        MagicStrings.LanguageCodeForGenDateFields, genDateStr).AsBsonDocument();
                break;
                // When parsing, will use GenDate.TryParse(str, out genDate)

            case CellarPropertyType.Integer:
                fieldValue = new BsonInt32(data.get_IntProp(hvo, flid));
                if (fieldValue.AsInt32 == default(Int32))
                    fieldValue = null; // Suppress int fields with 0 in them, to save Mongo DB space
                else
                    // LF wants single-string fields in the format { "ws": { "value": "contents" } }
                    fieldValue = LfMultiText.FromSingleStringMapping(
                        MagicStrings.LanguageCodeForIntFields, fieldValue.AsInt32.ToString()).AsBsonDocument();
                break;

            case CellarPropertyType.OwningAtomic:
            case CellarPropertyType.ReferenceAtomic:
                int ownedHvo = data.get_ObjectProp(hvo, flid);
                fieldValue = GetCustomReferencedObject(ownedHvo, flid, listConverters, ref dataGuids);
                if (fieldValue != null && fdoFieldType == CellarPropertyType.ReferenceAtomic)
                {
                    // Single CmPossiblity reference - LF expects format like { "value": "key of possibility" }
                    fieldValue = new BsonDocument("value", fieldValue);
                }
                fieldGuid = new BsonString(dataGuids.FirstOrDefault().ToString());
                break;
            case CellarPropertyType.MultiUnicode:
                ITsMultiString tss = data.get_MultiStringProp(hvo, flid);
                if (tss != null && tss.StringCount > 0)
                    fieldValue = LfMultiText.FromMultiITsString(tss, cache.ServiceLocator.WritingSystemManager).AsBsonDocument();
                break;
            case CellarPropertyType.OwningCollection:
            case CellarPropertyType.OwningSequence:
            case CellarPropertyType.ReferenceCollection:
            case CellarPropertyType.ReferenceSequence:
                int[] listHvos = data.VecProp(hvo, flid);
                var innerValues = new BsonArray(listHvos.Select(listHvo => GetCustomReferencedObject(listHvo, flid, listConverters, ref dataGuids)).Where(x => x != null));
                if (innerValues.Count == 0)
                    fieldValue = null;
                else
                {
                    fieldValue = new BsonDocument("values", innerValues);
                    fieldGuid = new BsonArray(dataGuids.Select(guid => guid.ToString()));
                }
                break;

            case CellarPropertyType.String:
                ITsString iTsValue = data.get_StringProp(hvo, flid);
                if (iTsValue == null || String.IsNullOrEmpty(iTsValue.Text))
                    fieldValue = null;
                else
                    fieldValue = LfMultiText.FromSingleITsString(iTsValue, cache.ServiceLocator.WritingSystemManager).AsBsonDocument();
                break;
            default:
                fieldValue = null;
                if (logger != null)
                    logger.Warning("FDO CellarPropertyType.{0} not recognized for LF custom field", fdoFieldType.ToString());
                break;
            }

            CellarPropertyTypeToLfCustomFieldType.TryGetValue(fdoFieldType, out customFieldType);
            if (fieldValue == null)
                return;
            else
            {
                var result = new BsonDocument();
                result.Add("value", fieldValue ?? BsonNull.Value); // BsonValues aren't allowed to have C# nulls; they have their own null representation
                if (fieldGuid is BsonArray)
                    result.Add("guid", fieldGuid, ((BsonArray)fieldGuid).Count > 0);
                else
                    result.Add("guid", fieldGuid, fieldGuid != null);
                bsonForThisField = result;
            }
        }
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions)
        {
            using (_database.RequestStart(false)) // not slaveOk
            {
                EnsureIndexes();

                var files_id  = createOptions.Id ?? BsonObjectId.GenerateNewId();
                var chunkSize = createOptions.ChunkSize == 0 ? _settings.ChunkSize : createOptions.ChunkSize;
                var buffer    = new byte[chunkSize];

                var    length    = 0L;
                string md5Client = null;
                using (var md5Algorithm = _settings.VerifyMD5 ? MD5.Create() : null)
                {
                    for (var n = 0L; true; n++)
                    {
                        // might have to call Stream.Read several times to get a whole chunk
                        var bytesNeeded = chunkSize;
                        var bytesRead   = 0;
                        while (bytesNeeded > 0)
                        {
                            var partialRead = stream.Read(buffer, bytesRead, bytesNeeded);
                            if (partialRead == 0)
                            {
                                break; // EOF may or may not have a partial chunk
                            }
                            bytesNeeded -= partialRead;
                            bytesRead   += partialRead;
                        }
                        if (bytesRead == 0)
                        {
                            break; // EOF no partial chunk
                        }
                        length += bytesRead;

                        byte[] data = buffer;
                        if (bytesRead < chunkSize)
                        {
                            data = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                        }

                        var chunk = new BsonDocument
                        {
                            { "_id", BsonObjectId.GenerateNewId() },
                            { "files_id", files_id },
                            { "n", (n < int.MaxValue) ? (BsonValue)BsonInt32.Create((int)n) : BsonInt64.Create(n) },
                            { "data", new BsonBinaryData(data) }
                        };
                        _chunks.Insert(chunk, _settings.SafeMode);

                        if (_settings.VerifyMD5)
                        {
                            md5Algorithm.TransformBlock(data, 0, data.Length, null, 0);
                        }

                        if (bytesRead < chunkSize)
                        {
                            break; // EOF after partial chunk
                        }
                    }

                    if (_settings.VerifyMD5)
                    {
                        md5Algorithm.TransformFinalBlock(new byte[0], 0, 0);
                        md5Client = BsonUtils.ToHexString(md5Algorithm.Hash);
                    }
                }

                string md5Server = null;
                if (_settings.UpdateMD5 || _settings.VerifyMD5)
                {
                    var md5Command = new CommandDocument
                    {
                        { "filemd5", files_id },
                        { "root", _settings.Root }
                    };
                    var md5Result = _database.RunCommand(md5Command);
                    md5Server = md5Result.Response["md5"].AsString;
                }

                if (_settings.VerifyMD5 && !md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase))
                {
                    throw new MongoGridFSException("Upload client and server MD5 hashes are not equal.");
                }

                var          uploadDate = createOptions.UploadDate == DateTime.MinValue ? DateTime.UtcNow : createOptions.UploadDate;
                BsonDocument fileInfo   = new BsonDocument
                {
                    { "_id", files_id },
                    { "filename", remoteFileName },
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", (md5Server == null) ? (BsonValue)BsonNull.Value : new BsonString(md5Server) },
                    { "contentType", createOptions.ContentType },           // optional
                    { "aliases", BsonArray.Create(createOptions.Aliases) }, // optional
                    { "metadata", createOptions.Metadata } // optional
                };
                _files.Insert(fileInfo, _settings.SafeMode);

                return(FindOneById(files_id));
            }
        }
 public void TestCompareToBsonValue()
 {
     var other = new BsonInt32(1);
     var wrapper = new BsonDocumentWrapper(new BsonDocument("x", 1));
     Assert.AreEqual(false, wrapper.IsMaterialized);
     var result = wrapper.CompareTo(other);
     Assert.AreEqual(true, wrapper.IsMaterialized);
     Assert.AreEqual(1, result);
 }
Beispiel #29
0
        /// <summary>
        ///     各种基本类型的初始值
        /// </summary>
        /// <param name="DataType"></param>
        /// <returns></returns>
        public static BsonValue GetInitValue(BsonValueEx.BasicType DataType)
        {
            BsonValue InitValue = BsonNull.Value;

            switch (DataType)
            {
            case BasicType.BsonString:
                InitValue = new BsonString(string.Empty);
                break;

            case BasicType.BsonInt32:
                InitValue = new BsonInt32(0);
                break;

            case BasicType.BsonInt64:
                InitValue = new BsonInt64(0);
                break;

            case BasicType.BsonDecimal128:
                InitValue = new BsonDecimal128(0);
                break;

            case BasicType.BsonDouble:
                InitValue = new BsonDouble(0);
                break;

            case BasicType.BsonDateTime:
                InitValue = new BsonDateTime(DateTime.Now);
                break;

            case BasicType.BsonBoolean:
                InitValue = BsonBoolean.False;
                break;

            case BasicType.BsonArray:
                InitValue = new BsonArray();
                break;

            case BasicType.BsonDocument:
                InitValue = new BsonDocument();
                break;

            case BasicType.BsonLegacyPoint:
                InitValue = new BsonArray()
                {
                    0, 0
                };
                break;

            case BasicType.BsonGeoJSON:
                InitValue = new BsonDocument("type", "Point");
                InitValue.AsBsonDocument.Add("coordinates", new BsonArray()
                {
                    0, 0
                });
                break;

            case BasicType.BsonMaxKey:
                InitValue = BsonMaxKey.Value;
                break;

            case BasicType.BsonMinKey:
                InitValue = BsonMinKey.Value;
                break;

            case BasicType.BsonBinary:
                InitValue = new BsonBinaryData(new byte[0]);
                break;

            default:
                break;
            }
            return(InitValue);
        }
        public async Task <IEnumerable <Leaderboard> > Lookup(LeaderboardLookup lookup)
        {
            Game game = (await gameRepository.Lookup(lookup.gameLookup)).FirstOrDefault();

            var match = await getMatchFromLookupRequest(lookup);

            BsonValue dataFilter = null;

            if (lookup.data == null || lookup.data.Count == 0)
            {
                dataFilter = new BsonInt32(1);
            }
            else
            {
                dataFilter = getFilterFromLookupRequest(lookup);
            }
            var project = new BsonDocument
                          (
                "$project", new BsonDocument
            {
                new BsonElement("_id", new BsonInt32(1)),
                new BsonElement("baseKey", new BsonInt32(1)),
                new BsonElement("gameid", new BsonInt32(1)),
                new BsonElement("data", dataFilter)
            }
                          );

            BsonValue pageFilter = null;

            if (!lookup.pageOffset.HasValue || !lookup.pageSize.HasValue)
            {
                pageFilter = new BsonInt32(1);
            }
            else
            {
                pageFilter = getPaginationProjection(lookup);
            }

            var pagiantionProject = new BsonDocument
                                    (
                "$project", new BsonDocument
            {
                new BsonElement("_id", new BsonInt32(1)),
                new BsonElement("baseKey", new BsonInt32(1)),
                new BsonElement("gameid", new BsonInt32(1)),
                new BsonElement("total", new BsonDocument("$size", new BsonString("$data"))),
                new BsonElement("data", pageFilter)
            }
                                    );

            BsonDocument[] pipeline = new BsonDocument[] { match, project, pagiantionProject };

            var return_value = new List <Leaderboard>();
            var results      = (collection.Aggregate <BsonDocument>(pipeline).ToList <BsonDocument>());

            foreach (var result in results)
            {
                var leaderboard = new Leaderboard();
                leaderboard.game  = game;
                leaderboard.total = result.GetValue("total").AsInt32;
                leaderboard.data  = Newtonsoft.Json.JsonConvert.DeserializeObject(result.GetValue("data").ToJson()); //stupid fix for weird bson deserialization
                return_value.Add(leaderboard);
            }
            return(return_value);
        }
 public TestClass(
     BsonInt32 value
 )
 {
     this.B = value;
     this.V = value;
 }
 /// <summary>
 /// 还原BsonValue
 /// </summary>
 /// <returns></returns>
 public BsonValue GetBsonValue()
 {
     BsonValue Value = new BsonString("");
     switch (mBsonType)
     {
         case "BsonString":
             Value = new BsonString(mBsonString);
             break;
         case "BsonInt32":
             Value = new BsonInt32(mBsonInt32);
             break;
         case "BsonDateTime":
             Value = new BsonDateTime(mBsonDateTime);
             break;
         case "BsonBoolean":
             if (mBsonBoolean)
             {
                 Value = BsonBoolean.True;
             }
             else
             {
                 Value = BsonBoolean.False;
             }
             break;
         default:
             break;
     }
     return Value;
 }
Beispiel #33
0
        private void SetAncestors(ContentItem item)
        {
            var ids = item.AncestralTrail.Split('/').Where(id => !string.IsNullOrEmpty(id)).Select(id => BsonInt32.Create(int.Parse(id))).ToList();

            if (ids.Count == 0)
            {
                return;
            }

            var parents = database.GetCollection <ContentItem>().Find(Query.In("_id", ids)).OrderByDescending(p => p.AncestralTrail.Length).ToList();

            for (int i = 1; i < parents.Count; i++)
            {
                parents[i - 1].Parent = parents[i];
            }
            item.Parent = parents[0];
        }
        public void SaveOrUpdate <TEntity>(TEntity entity) where TEntity : class, IEntity, new()
        {
            var id = entity.TryGetValue("Id");

            if (GetById <TEntity>(id) == null)
            {
                Save(entity);
                return;
            }

            var update = new UpdateBuilder();

            foreach (var property in typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                     .Where(r => !r.Name.EqualsWithInvariant("Id")))
            {
                var value = property.GetValue(entity, null);

                BsonValue bsonValue = BsonNull.Value;
                if (value != null)
                {
                    var type = (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                                       ? property.PropertyType.GetGenericArguments()[0]
                                       : property.PropertyType;

                    if (type == typeof(string))
                    {
                        bsonValue = new BsonString(value.ToString());
                    }
                    else if (type == typeof(bool))
                    {
                        bsonValue = new BsonBoolean((bool)value);
                    }
                    else if (type == typeof(DateTime))
                    {
                        bsonValue = new BsonDateTime((DateTime)value);
                    }
                    else if (type == typeof(long))
                    {
                        bsonValue = new BsonInt64((long)value);
                    }
                    else if (type == typeof(int))
                    {
                        bsonValue = new BsonInt32((int)value);
                    }
                    else if (type == typeof(byte[]))
                    {
                        bsonValue = new BsonBinaryData((byte[])value);
                    }
                    else if (type == typeof(Guid))
                    {
                        bsonValue = new BsonBinaryData((Guid)value);
                    }
                    else if (type.IsEnum)
                    {
                        bsonValue = new BsonString(value.ToString());
                    }
                    else if (type.IsImplement <IEnumerable>())
                    {
                        bsonValue = new BsonArray((IEnumerable)value);
                    }
                    else if (type.IsClass && type.IsImplement <IEntity>())
                    {
                        bsonValue = new BsonDocumentWrapper(value);
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("propertyType {0} does not bson value".F(type));
                    }
                }

                update.Set(property.Name, bsonValue);
            }

            GetCollection <TEntity>().Update(MongoDB.Driver.Builders.Query <TEntity> .EQ(r => r.Id, id), update);
        }
Beispiel #35
0
        public void DiffTwoDifferentBsonValues()
        {
            // Arrange
            var a = new BsonInt32(1);
            var b = new BsonInt32(2);
            var expectedDiff = new BsonDocument("values differ", new BsonDocument {{"a", 1}, {"b", 2}});

            // Act
            var value = a.Diff(b);

            // Assert
            Assert.That(value, Is.EqualTo(expectedDiff));
        }
Beispiel #36
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public static BsonValue Int(object value)
 {
     return(BsonInt32.Create((int)value));
 }
        public void operator_equals_with_BsonInt32_should_return_expected_result(long lhsInt64Value, int rhsInt32Value, bool expectedResult)
        {
            var lhs = new BsonInt64(lhsInt64Value);
            var rhs = new BsonInt32(rhsInt32Value);

            var result = lhs == rhs;

            result.Should().Be(expectedResult);
        }
 public void TestBsonInt32()
 {
     var value = new BsonInt32(1);
     Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null));
     Assert.AreEqual(true, Convert.ToBoolean(value));
     Assert.AreEqual(1, Convert.ToByte(value));
     Assert.AreEqual(1, Convert.ToChar(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(value));
     Assert.AreEqual(1m, Convert.ToDecimal(value));
     Assert.AreEqual(1.0, Convert.ToDouble(value));
     Assert.AreEqual(1, Convert.ToInt16(value));
     Assert.AreEqual(1, Convert.ToInt32(value));
     Assert.AreEqual(1, Convert.ToInt64(value));
     Assert.AreEqual(1, Convert.ToSByte(value));
     Assert.AreEqual(1.0F, Convert.ToSingle(value));
     Assert.AreEqual("1", Convert.ToString(value));
     Assert.AreEqual(1, Convert.ToUInt16(value));
     Assert.AreEqual(1, Convert.ToUInt32(value));
     Assert.AreEqual(1, Convert.ToUInt64(value));
 }
 public void EquivalentToIntegerNotMatch()
 {
     BsonValue val1 = new BsonInt32(42);
     BsonValue val2 = new BsonInt32(-42);
     Assert.IsFalse(val1.EquivalentTo(val2));
 }
Beispiel #40
0
        /// <summary>
        /// Gets the data for one custom field, and any relevant GUIDs.
        /// </summary>
        /// <param name="hvo">Hvo of object we're getting the field for.</param>
        /// <param name="flid">Flid for this field.</param>
        /// <param name="fieldSourceType">Either "entry", "senses" or "examples". Could also be "allomorphs", eventually.</param>
        /// <param name="bsonForThisField">Output of a BsonDocument with the following structure: <br />
        /// { fieldName: { "value": BsonValue, "guid": "some-guid-as-a-string" } } <br />
        /// -OR- <br />
        /// { fieldName: { "value": BsonValue, "guid": ["guid1", "guid2", "guid3"] } } <br />
        /// The format of the fieldName key will be "customField_FOO_field_name_with_underscores",
        /// where FOO is one of "entry", "senses", or "examples". <br />
        /// The type of the "guid" value (array or string) will determine whether there is a single GUID,
        /// or a list of GUIDs that happens to contain only one entry.
        /// If there is no "guid" key, that field has no need for a GUID. (E.g., a number).
        /// </param>
        /// <param name="listConverters">Dictionary of ConvertLcmToMongoOptionList instances, keyed by list code</param>
        private BsonDocument GetCustomFieldData(int hvo, int flid, string fieldSourceType,
                                                IDictionary <string, ConvertLcmToMongoOptionList> listConverters)
        {
            BsonValue             fieldValue   = null;
            BsonValue             fieldGuid    = null; // Might be a single value, might be a list (as a BsonArray)
            ISilDataAccessManaged data         = (ISilDataAccessManaged)cache.DomainDataByFlid;
            CellarPropertyType    LcmFieldType = (CellarPropertyType)LcmMetaData.GetFieldType(flid);
            var dataGuids = new List <Guid>();

            // Valid field types in Lcm are GenDate, Integer, String, OwningAtomic, ReferenceAtomic, and ReferenceCollection, so that's all we implement.
            switch (LcmFieldType)
            {
            case CellarPropertyType.GenDate:
                GenDate genDate    = data.get_GenDateProp(hvo, flid);
                string  genDateStr = genDate.ToLongString();
                // LF wants single-string fields in the format { "ws": { "value": "contents" } }
                fieldValue = String.IsNullOrEmpty(genDateStr) ? null :
                             LfMultiText.FromSingleStringMapping(
                    MagicStrings.LanguageCodeForGenDateFields, genDateStr).AsBsonDocument();
                break;
            // When parsing, will use GenDate.TryParse(str, out genDate)

            case CellarPropertyType.Integer:
                fieldValue = new BsonInt32(data.get_IntProp(hvo, flid));
                if (fieldValue.AsInt32 == default(Int32))
                {
                    fieldValue = null;                     // Suppress int fields with 0 in them, to save Mongo DB space
                }
                else
                {
                    // LF wants single-string fields in the format { "ws": { "value": "contents" } }
                    fieldValue = LfMultiText.FromSingleStringMapping(
                        MagicStrings.LanguageCodeForIntFields, fieldValue.AsInt32.ToString()).AsBsonDocument();
                }
                break;

            case CellarPropertyType.OwningAtomic:
            case CellarPropertyType.ReferenceAtomic:
                int ownedHvo = data.get_ObjectProp(hvo, flid);
                fieldValue = GetCustomReferencedObject(ownedHvo, flid, listConverters, ref dataGuids);
                if (fieldValue != null && LcmFieldType == CellarPropertyType.ReferenceAtomic)
                {
                    // Single CmPossiblity reference - LF expects format like { "value": "key of possibility" }
                    fieldValue = new BsonDocument("value", fieldValue);
                }
                fieldGuid = new BsonString(dataGuids.FirstOrDefault().ToString());
                break;

            case CellarPropertyType.MultiUnicode:
                ITsMultiString tss = data.get_MultiStringProp(hvo, flid);
                if (tss != null && tss.StringCount > 0)
                {
                    fieldValue = LfMultiText.FromMultiITsString(tss, servLoc.WritingSystemManager).AsBsonDocument();
                }
                break;

            case CellarPropertyType.OwningCollection:
            case CellarPropertyType.OwningSequence:
            case CellarPropertyType.ReferenceCollection:
            case CellarPropertyType.ReferenceSequence:
                int[] listHvos    = data.VecProp(hvo, flid);
                var   innerValues = new BsonArray(listHvos.Select(listHvo => GetCustomReferencedObject(listHvo, flid, listConverters, ref dataGuids)).Where(x => x != null));
                if (innerValues.Count == 0)
                {
                    fieldValue = null;
                }
                else
                {
                    fieldValue = new BsonDocument("values", innerValues);
                    fieldGuid  = new BsonArray(dataGuids.Select(guid => guid.ToString()));
                }
                break;

            case CellarPropertyType.String:
                ITsString iTsValue = data.get_StringProp(hvo, flid);
                if (iTsValue == null || String.IsNullOrEmpty(iTsValue.Text))
                {
                    fieldValue = null;
                }
                else
                {
                    fieldValue = LfMultiText.FromSingleITsString(iTsValue, servLoc.WritingSystemManager).AsBsonDocument();
                }
                break;

            default:
                fieldValue = null;
                if (logger != null)
                {
                    logger.Warning("Lcm CellarPropertyType.{0} not recognized for LF custom field", LcmFieldType.ToString());
                }
                break;
            }

            if (fieldValue == null)
            {
                return(null);
            }
            else
            {
                var result = new BsonDocument();
                result.Add("value", fieldValue ?? BsonNull.Value);                 // BsonValues aren't allowed to have C# nulls; they have their own null representation
                if (fieldGuid is BsonArray)
                {
                    result.Add("guid", fieldGuid, ((BsonArray)fieldGuid).Count > 0);
                }
                else
                {
                    result.Add("guid", fieldGuid, fieldGuid != null);
                }
                return(result);
            }
        }
Beispiel #41
0
        private void okay_Click(object sender, EventArgs e)
        {
            BsonValue newValue;

            if (type == BsonType.Array)
            {
                switch (comboBox1.SelectedItem)
                {
                case "String":
                    newValue = new BsonString(inputValueForArrayElement.Text);
                    break;

                case "Int32":
                    int i = Convert.ToInt32(inputValueForArrayElement.Text);
                    newValue = new BsonInt32(i);
                    break;

                case "Document":
                    newValue = new BsonDocument();
                    break;

                case "Array":
                    newValue = new BsonArray();
                    break;

                default:
                    newValue = null;
                    break;
                }
                if (node.Tag is BsonElement)
                {
                    BsonElement tag = ((BsonElement)node.Tag).DeepClone();
                    BsonArray   arr = (BsonArray)tag.Value;

                    if (newValue != null)
                    {
                        arr.Add(newValue);
                        if (parent is MainForm)
                        {
                            ((MainForm)parent).addElement(node, tag);
                        }
                        else if (parent is ViewCollection)
                        {
                            ((ViewCollection)parent).addElement(node, tag);
                        }
                    }
                }
                else if (node.Tag is BsonValue)
                {
                    BsonValue tag = ((BsonValue)node.Tag).DeepClone();
                    BsonArray arr = (BsonArray)tag;

                    if (newValue != null)
                    {
                        arr.Add(newValue);
                        if (parent is MainForm)
                        {
                            ((MainForm)parent).addElement(node, tag);
                        }
                        else if (parent is ViewCollection)
                        {
                            ((ViewCollection)parent).addElement(node, tag);
                        }
                    }
                }
            }
            else if (type == BsonType.Document)
            {
                switch (comboBox1.SelectedItem)
                {
                case "String":
                    newValue = new BsonString(documentPropertyValue.Text);
                    break;

                case "Int32":
                    int i = Convert.ToInt32(documentPropertyValue.Text);
                    newValue = new BsonInt32(i);
                    break;

                case "Document":
                    newValue = new BsonDocument();
                    break;

                case "Array":
                    newValue = new BsonArray();
                    break;

                default:
                    newValue = null;
                    break;
                }

                if (node.Tag is BsonDocument)
                {
                    BsonElement  newEl = new BsonElement(documentPropertyName.Text, newValue);
                    BsonDocument tag   = (BsonDocument)node.Tag;
                    tag = tag.DeepClone() as BsonDocument;
                    tag.Add(newEl);
                    if (parent is MainForm)
                    {
                        ((MainForm)parent).addElement(node, tag);
                    }
                    else if (parent is ViewCollection)
                    {
                        ((ViewCollection)parent).addElement(node, tag);
                    }
                }
                else if (node.Tag is BsonElement)
                {
                    BsonElement tag   = ((BsonElement)node.Tag).DeepClone();
                    BsonElement newEl = new BsonElement(documentPropertyName.Text, newValue);
                    tag.Value.AsBsonDocument.Add(newEl);
                    if (parent is MainForm)
                    {
                        ((MainForm)parent).addElement(node, tag);
                    }
                    else if (parent is ViewCollection)
                    {
                        ((ViewCollection)parent).addElement(node, tag);
                    }
                }
            }

            Close();
        }
 // public methods
 /// <inheritdoc/>
 public override BsonValue ToBsonValue()
 {
     return(BsonInt32.Create(_w));
 }
 public void EquivalentToInteger()
 {
     BsonValue val1 = new BsonInt32(42);
     BsonValue val2 = new BsonInt32(42);
     Assert.IsTrue(val1.EquivalentTo(val2));
 }
Beispiel #44
0
        public void EqualTwoIdenticalBsonValues()
        {
            // Arrange
            var a = new BsonInt32(100);
            var b = new BsonInt32(100);

            // Act
            var eq = a.Equal(b);

            // Assert
            Assert.True(eq);
        }
 public void TestMapBsonInt32() {
     var value = new BsonInt32(1);
     var bsonValue = (BsonInt32) BsonTypeMapper.MapToBsonValue(value);
     Assert.AreSame(value, bsonValue);
     var bsonInt32 = (BsonInt32) BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);
     Assert.AreSame(value, bsonInt32);
 }
Beispiel #46
0
        public void TestClassWithBsonValueId()
        {
            // repeats all tee TestClassWithBsonXyzId tests using ClassWithBsonValueId
            {
                // same as TestClassWithBonArrayId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonArray(), X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });

                doc = new ClassWithBsonValueId {
                    Id = new BsonArray {
                        1, 2, 3
                    }, X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });
            }

            {
                // same as TestClastWithBsonBinaryDataId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBinaryData.Create(new byte[] { }), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBinaryData.Create(new byte[] { 1, 2, 3 }), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonBooleanId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBoolean.Create(false), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonBoolean.Create(true), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDocumentId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonDocument(), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = new BsonDocument {
                        { "A", 1 }, { "B", 2 }
                    }, X = 3
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDateTimeId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.MinValue), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.UtcNow), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDateTime.Create(DateTime.MaxValue), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonDoubleId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDouble.Create(0.0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonDouble.Create(1.0), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonInt32Id
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt32.Create(0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt32.Create(1), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonInt64Id
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt64.Create(0), X = 1
                };
                _collection.Insert(doc);

                doc = new ClassWithBsonValueId {
                    Id = BsonInt64.Create(1), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonMaxKeyId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonMaxKey.Value, X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonMinKeyId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonMinKey.Value, X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonNullId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(null, doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonNull.Value, X = 1
                };
                Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); });
            }

            {
                // same as TestClassWithBsonObjectId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue

                doc = new ClassWithBsonValueId {
                    Id = BsonObjectId.Empty, X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(ObjectId.Empty, doc.Id.AsObjectId); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue

                doc = new ClassWithBsonValueId {
                    Id = BsonObjectId.GenerateNewId(), X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonStringId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = "", X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual("", doc.Id.AsString);

                doc = new ClassWithBsonValueId {
                    Id = "123", X = 1
                };
                _collection.Insert(doc);
            }

            {
                // same as TestClassWithBsonTimestampId
                _collection.RemoveAll();

                var doc = new ClassWithBsonValueId {
                    Id = null, X = 1
                };
                _collection.Insert(doc);
                Assert.IsNull(doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonTimestamp.Create(0, 0), X = 1
                };
                _collection.Insert(doc);
                Assert.AreEqual(BsonTimestamp.Create(0, 0), doc.Id);

                doc = new ClassWithBsonValueId {
                    Id = BsonTimestamp.Create(1, 2), X = 1
                };
                _collection.Insert(doc);
            }
        }
        /// <summary>
        /// Gets the <see cref="WorkflowConfiguration"/> matching the
        /// <paramref name="workflowType"/> and <paramref name="externalId"/>.
        /// </summary>
        /// <param name="workflowType">The workflow type to retrieve.</param>
        /// <param name="externalId">The workflow type reference id of the workflow to retrieve.</param>
        /// <param name="externalVersion">The version number of the workflow configuration to retrieve.</param>
        /// <returns>The <see cref="WorkflowConfiguration"/> matching the
        /// <paramref name="workflowType"/> and <paramref name="externalId"/>.</returns>
        protected override WorkflowConfigurationContainer DoGetWorkflowConfiguration(WorkflowTargetType workflowType, string externalId, int externalVersion)
        {
            BsonString bsonWorkflowType = new BsonString(workflowType.ToString());
            BsonString bsonExternalId = new BsonString(externalId);
            BsonInt32 bsonExternalVersion = new BsonInt32(externalVersion);

            MongoCollection<BsonDocument> collection = this.Database.GetCollection(iApplyDb.WorkflowConfiguration._COLLECTION_NAME);
            IMongoQuery query =
                Query.And(
                    Query.EQ(iApplyDb.WorkflowConfiguration.TYPE, bsonWorkflowType),
                    Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_ID, bsonExternalId),
                    Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_VERSION, bsonExternalVersion));

            BsonDocument document = collection.FindOne(query);
            if (document == null)
            {
                return null;
            }

            return BsonConverter.ConvertToObjectViaJson<WorkflowConfigurationContainer>(document);
        }
Beispiel #48
0
        public static BsonValue Create(this BsonType bsonType, object o)
        {
            BsonValue value = BsonNull.Value;

            try
            {
                switch (bsonType)
                {
                case BsonType.EndOfDocument:
                    break;

                case BsonType.Double:
                    value = BsonDouble.Create(o);
                    break;

                case BsonType.String:
                    value = BsonString.Create(o);
                    break;

                case BsonType.Document:
                    value = BsonDocument.Create(o);
                    break;

                case BsonType.Array:
                    value = BsonArray.Create(o);
                    break;

                case BsonType.Binary:
                    value = BsonBinaryData.Create(o);
                    break;

                case BsonType.Undefined:
                    break;

                case BsonType.ObjectId:
                    value = BsonObjectId.Create(o);
                    break;

                case BsonType.Boolean:
                    value = BsonBoolean.Create(o);
                    break;

                case BsonType.DateTime:
                    value = BsonDateTime.Create(o);
                    break;

                case BsonType.Null:
                    value = BsonNull.Value;
                    break;

                case BsonType.RegularExpression:
                    value = BsonRegularExpression.Create(o);
                    break;

                case BsonType.JavaScript:
                    value = BsonJavaScript.Create(o);
                    break;

                case BsonType.Symbol:
                    value = BsonSymbol.Create(o);
                    break;

                case BsonType.JavaScriptWithScope:
                    value = BsonJavaScriptWithScope.Create(o);
                    break;

                case BsonType.Int32:
                    value = BsonInt32.Create(o);
                    break;

                case BsonType.Timestamp:
                    value = BsonTimestamp.Create(o);
                    break;

                case BsonType.Int64:
                    value = BsonInt64.Create(o);
                    break;

                case BsonType.MaxKey:
                    value = BsonValue.Create(o);
                    break;

                case BsonType.MinKey:
                    value = BsonValue.Create(o);
                    break;
                }
            }
            catch
            {
            }

            return(value);
        }
 public void TestIsNumeric()
 {
     BsonValue d128 = new BsonDecimal128(1.0M);
     BsonValue d = new BsonDouble(1.0);
     BsonValue i32 = new BsonInt32(1);
     BsonValue i64 = new BsonInt64(1L);
     BsonValue s = new BsonString("");
     Assert.True(d128.IsNumeric);
     Assert.True(d.IsNumeric);
     Assert.True(i32.IsNumeric);
     Assert.True(i64.IsNumeric);
     Assert.False(s.IsDecimal128);
 }
Beispiel #50
0
        public void DiffTwoDifferentBsonTypes()
        {
            // Arrange
            var a = new BsonInt32(100);
            var b = new BsonInt64(100);
            var expected = new BsonDocument("types differ", new BsonDocument {{"a", "Int32"}, {"b", "Int64"}});

            // Act
            var doc = a.Diff(b);

            // Assert
            Assert.That(doc, Is.EqualTo(expected));
        }
Beispiel #51
0
 /// <summary>
 ///     将数据放入TreeNode里进行展示
 /// </summary>
 /// <param name="treeNode"></param>
 /// <param name="doc"></param>
 public static void AddBsonDocToTreeNode(TreeNode treeNode, BsonDocument doc)
 {
     foreach (var item in doc.Elements)
     {
         if (item.Value.IsBsonDocument)
         {
             var newItem = new TreeNode(item.Name);
             AddBsonDocToTreeNode(newItem, item.Value.ToBsonDocument());
             newItem.Tag = item;
             treeNode.Nodes.Add(newItem);
         }
         else
         {
             if (item.Value.IsBsonArray)
             {
                 //虽然TreeNode的Text属性带有Array_Mark,表示的时候则会屏蔽掉,
                 //必须要加上,不然FullPath会出现错误
                 var newItem = new TreeNode(item.Name + ConstMgr.ArrayMark);
                 AddBsonArrayToTreeNode(item.Name, newItem, item.Value.AsBsonArray);
                 newItem.Tag = item;
                 treeNode.Nodes.Add(newItem);
             }
             else
             {
                 var elementNode = new TreeNode(item.Name)
                 {
                     Tag = item
                 };
                 treeNode.Nodes.Add(elementNode);
                 if (item.Value.IsObjectId)
                 {
                     //objId的展开
                     ObjectId oid           = item.Value.AsObjectId;
                     var      oidCreateTime = new TreeNode("CreationTime")
                     {
                         Tag = BsonDateTime.Create(oid.CreationTime)
                     };
                     var oidMachine = new TreeNode("Machine")
                     {
                         Tag = BsonInt32.Create(oid.Machine)
                     };
                     var oidPid = new TreeNode("Pid")
                     {
                         Tag = BsonInt32.Create(oid.Pid)
                     };
                     var oidIncrement = new TreeNode("Increment")
                     {
                         Tag = BsonInt32.Create(oid.Increment)
                     };
                     var oidTimestamp = new TreeNode("Timestamp")
                     {
                         Tag = BsonInt32.Create(oid.Timestamp)
                     };
                     elementNode.Nodes.Add(oidCreateTime);
                     elementNode.Nodes.Add(oidMachine);
                     elementNode.Nodes.Add(oidPid);
                     elementNode.Nodes.Add(oidIncrement);
                     elementNode.Nodes.Add(oidTimestamp);
                 }
             }
         }
     }
 }
Beispiel #52
0
        public void DiffTwoIdenticalBsonValues()
        {
            // Arrange
            var a = new BsonInt32(1);
            var b = new BsonInt32(1);
            var expectedDiff = new BsonDocument();

            // Act
            var value = a.Diff(b);

            // Assert
            Assert.That(value, Is.EqualTo(expectedDiff));
        }
Beispiel #53
0
        /// <summary>Try to convert the string to a <see cref="BsonInt32"/>.</summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="bsonValue">The BsonValue result.</param>
        /// <returns><c>true</c> if the value was converted; otherwise <c>false</c>.</returns>
        public static bool TryInt32(this string value, out BsonValue bsonValue)
        {
            bsonValue = null;
            if (value == null)
                return false;

            int result;
            var r = int.TryParse(value, out result);
            if (r) bsonValue = new BsonInt32(result);

            return r;
        }
        public void TestBsonInt64Equals()
        {
            var a = new BsonInt64(1L);
            var b = new BsonInt64(1L);
            var c = new BsonInt32(1);
            var d = new BsonDouble(1.0);
            var e = new BsonInt64(2L);
            var f = new BsonInt32(2);
            var g = new BsonDouble(2.0);
            var n = (BsonInt64)null;

            Assert.IsTrue(object.Equals(a, b));
            Assert.IsFalse(object.Equals(a, c));
            Assert.IsFalse(object.Equals(a, d));
            Assert.IsFalse(object.Equals(a, e));
            Assert.IsFalse(object.Equals(a, f));
            Assert.IsFalse(object.Equals(a, g));
            Assert.IsFalse(object.Equals(a, BsonNull.Value));
            Assert.IsFalse(a.Equals(n));
            Assert.IsFalse(a.Equals(null));

            Assert.IsTrue(a == b);
            Assert.IsTrue(a == c);
            Assert.IsTrue(a == d);
            Assert.IsFalse(a == e);
            Assert.IsFalse(a == f);
            Assert.IsFalse(a == g);
            Assert.IsFalse(a == BsonNull.Value);
            Assert.IsFalse(a == null);
            Assert.IsFalse(null == a);
            Assert.IsTrue(n == null);
            Assert.IsTrue(null == n);

            Assert.IsFalse(a != b);
            Assert.IsFalse(a != c);
            Assert.IsFalse(a != d);
            Assert.IsTrue(a != e);
            Assert.IsTrue(a != f);
            Assert.IsTrue(a != g);
            Assert.IsTrue(a != BsonNull.Value);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
Beispiel #55
0
        public async Task <IEnumerable <Snapshot> > Lookup(SnapshotLookup lookup)
        {
            var searchRequest = new BsonDocument
            {
            };

            if (lookup._id != null)
            {
                searchRequest["_id"] = new BsonObjectId(lookup._id);
            }
            else
            {
                Game game = (await gameRepository.Lookup(lookup.gameLookup)).FirstOrDefault();
                if (game != null)
                {
                    searchRequest["gameid"] = new BsonInt32(game.Id);
                }
            }

            if (lookup.processed.HasValue)
            {
                searchRequest["processed"] = new BsonBoolean(lookup.processed.Value);
            }

            var results = (await collection.FindAsync(searchRequest)).ToList();
            var output  = new List <Snapshot>();

            foreach (var result in results)
            {
                var snapshot = new Snapshot();
                snapshot._id    = result["_id"].AsObjectId;
                snapshot.gameid = result["gameid"].AsInt32;
                if (result.Contains("processed"))
                {
                    snapshot.processed = result["processed"].AsBoolean;
                }
                else
                {
                    snapshot.processed = false;
                }
                if (result.Contains("profileid"))
                {
                    snapshot.profileid = result["profileid"].AsInt32;
                }

                snapshot.ip = result["ip"].AsString;
                if (result["created"].IsDateTime)
                {
                    snapshot.created = result["created"].AsDateTime;
                }
                snapshot.updates = new List <SnapshotUpdate>();
                var updates = result["updates"].AsBsonArray;

                foreach (var update in updates)
                {
                    var sub_update = new SnapshotUpdate();
                    if (update["created"].IsDateTime)
                    {
                        sub_update.created = update["created"].AsDateTime;
                    }
                    if (update.AsBsonDocument.Contains("profileid"))
                    {
                        sub_update.profileid = update["profileid"].AsInt32;
                    }
                    else
                    {
                        sub_update.profileid = snapshot.profileid;
                    }
                    if (update.AsBsonDocument.Contains("gameid"))
                    {
                        sub_update.gameid = update["gameid"].AsInt32;
                    }
                    else
                    {
                        sub_update.gameid = snapshot.gameid;
                    }
                    if (update.AsBsonDocument.Contains("complete"))
                    {
                        sub_update.completed = update["complete"].AsBoolean;
                    }

                    sub_update.data = new Dictionary <string, string>();
                    var data     = update["data"].AsBsonDocument;
                    var elements = data.Elements;
                    foreach (var element in elements)
                    {
                        sub_update.data[element.Name] = element.Value.AsString;
                    }
                    snapshot.updates.Add(sub_update);
                }
                output.Add(snapshot);
            }
            return(output);
        }