コード例 #1
0
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(BsonSymbol));

            var bsonType = bsonReader.GetCurrentBsonType();

            switch (bsonType)
            {
            case BsonType.Null:
                bsonReader.ReadNull();
                return(null);

            case BsonType.String:
                return(BsonSymbol.Create(bsonReader.ReadString()));

            case BsonType.Symbol:
                return(BsonSymbol.Create(bsonReader.ReadSymbol()));

            default:
                var message = string.Format("Cannot deserialize BsonSymbol from BsonType {0}.", bsonType);
                throw new FileFormatException(message);
            }
        }
コード例 #2
0
        public void TestBsonSymbolEquals()
        {
            var a = BsonSymbol.Create("symbol 1");
            var b = BsonSymbol.Create("symbol 1");
            var c = BsonSymbol.Create("symbol 2");
            var n = (BsonString)null;

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

            Assert.IsTrue(a == b);
            Assert.IsFalse(a == c);
            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.IsTrue(a != c);
            Assert.IsTrue(a != BsonNull.Value);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
コード例 #3
0
        public void TestTryMapToBsonValueWithBsonValues()
        {
            // test all the BsonValue subclasses because we removed them from the __fromMappings table
            var testValues = new BsonValue[]
            {
                new BsonArray(),
                new BsonBinaryData(new byte[0]),
                BsonBoolean.True,
                new BsonDateTime(DateTime.UtcNow),
                new BsonDocument("x", 1),
                new BsonDouble(1.0),
                new BsonInt32(1),
                new BsonInt64(1),
                new BsonJavaScript("code"),
                new BsonJavaScriptWithScope("code", new BsonDocument("x", 1)),
                BsonMaxKey.Value,
                BsonMinKey.Value,
                BsonNull.Value,
                new BsonObjectId(ObjectId.GenerateNewId()),
                new BsonRegularExpression("pattern"),
                new BsonString("abc"),
                BsonSymbol.Create("xyz"),
                new BsonTimestamp(0),
                BsonUndefined.Value
            };

            foreach (var testValue in testValues)
            {
                BsonValue bsonValue;
                var       ok = BsonTypeMapper.TryMapToBsonValue(testValue, out bsonValue);
                Assert.AreEqual(true, ok);
                Assert.AreSame(testValue, bsonValue);
            }
        }
コード例 #4
0
        public void TestToHashtableUnsupportedTypes()
        {
            var document = new BsonDocument
            {
                { "JavaScript", new BsonJavaScript("x = 1") },
                { "JavaScriptWithScope", new BsonJavaScriptWithScope("x = y", new BsonDocument("y", 1)) },
                { "MaxKey", BsonMaxKey.Value },
                { "MinKey", BsonMinKey.Value },
                { "Null", BsonNull.Value },
                { "RegularExpression", new BsonRegularExpression("abc") },
                { "Symbol", BsonSymbol.Create("name") },
                { "Timestamp", new BsonTimestamp(123L) },
                { "Undefined", BsonUndefined.Value },
            };
            var hashtable = document.ToHashtable();

            Assert.AreEqual(9, hashtable.Count);
            Assert.IsNull(hashtable["JavaScript"]);
            Assert.IsNull(hashtable["JavaScriptWithScope"]);
            Assert.IsNull(hashtable["MaxKey"]);
            Assert.IsNull(hashtable["MinKey"]);
            Assert.IsNull(hashtable["Null"]);
            Assert.IsNull(hashtable["RegularExpression"]);
            Assert.IsNull(hashtable["Symbol"]);
            Assert.IsNull(hashtable["Timestamp"]);
            Assert.IsNull(hashtable["Undefined"]);
        }
コード例 #5
0
        public void TestAsBsonSymbol()
        {
            BsonValue v   = BsonSymbol.Create("name");
            BsonValue s   = "";
            var       sym = v.AsBsonSymbol;

            Assert.AreEqual("name", sym.Name);
            Assert.Throws <InvalidCastException>(() => { var x = s.AsBsonSymbol; });
        }
コード例 #6
0
        public void TestBsonSymbolEquals()
        {
            BsonSymbol lhs = BsonSymbol.Create("name");
            BsonSymbol rhs = BsonSymbol.Create("name");

            Assert.AreSame(lhs, rhs);
            Assert.AreEqual(lhs, rhs);
            Assert.AreEqual(lhs.GetHashCode(), rhs.GetHashCode());
        }
コード例 #7
0
        public void TestBsonSymbolEquals()
        {
            BsonSymbol lhs = BsonSymbolTable.Lookup("name");
            BsonSymbol rhs = BsonSymbolTable.Lookup("name");

            Assert.Same(lhs, rhs);
            Assert.Equal(lhs, rhs);
            Assert.Equal(lhs.GetHashCode(), rhs.GetHashCode());
        }
コード例 #8
0
        public void TestMapBsonSymbol()
        {
            var value     = BsonSymbol.Create("symbol");
            var bsonValue = (BsonSymbol)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue);
            var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue(value, BsonType.Symbol);

            Assert.AreSame(value, bsonSymbol);
        }
コード例 #9
0
        public void TestSymbol()
        {
            var document = new BsonDocument {
                { "symbol", BsonSymbol.Create("name") }
            };
            string expected = "{ \"symbol\" : { \"$symbol\" : \"name\" } }";
            string actual   = document.ToJson();

            Assert.AreEqual(expected, actual);
        }
コード例 #10
0
        public void TestSymbol()
        {
            var document = new BsonDocument {
                { "symbol", BsonSymbol.Create("name") }
            };

            using (var bsonReader = BsonReader.Create(document)) {
                var rehydrated = BsonDocument.ReadFrom(bsonReader);
                Assert.IsTrue(document.Equals(rehydrated));
            }
        }
コード例 #11
0
 public static BsonSymbol Lookup(
     string name
 )
 {
     lock (staticLock) {
         BsonSymbol symbol;
         if (!symbolTable.TryGetValue(name, out symbol)) {
             symbol = new BsonSymbol(name);
             symbolTable[name] = symbol;
         }
         return symbol;
     }
 }
コード例 #12
0
        /// <summary>
        /// Writes a BSON Symbol to the writer.
        /// </summary>
        /// <param name="value">The symbol.</param>
        public override void WriteSymbol(string value)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("BsonDocumentWriter");
            }
            if (state != BsonWriterState.Value)
            {
                ThrowInvalidState("WriteSymbol", BsonWriterState.Value);
            }

            WriteValue(BsonSymbol.Create(value));
            state = GetNextState();
        }
コード例 #13
0
 // public static methods
 /// <summary>
 /// Looks up a symbol (and creates a new one if necessary).
 /// </summary>
 /// <param name="name">The name of the symbol.</param>
 /// <returns>The symbol.</returns>
 public static BsonSymbol Lookup(string name)
 {
     if (name == null)
     {
         throw new ArgumentNullException("name");
     }
     lock (__staticLock)
     {
         BsonSymbol symbol;
         if (!__symbolTable.TryGetValue(name, out symbol))
         {
             symbol = new BsonSymbol(name);
             __symbolTable[name] = symbol;
         }
         return symbol;
     }
 }
コード例 #14
0
        /// <summary>
        /// Writes a BSON Symbol to the writer.
        /// </summary>
        /// <param name="value">The symbol.</param>
        public override void WriteSymbol(
            string value
            )
        {
            if (disposed)
            {
                throw new ObjectDisposedException("BsonBinaryWriter");
            }
            if (state != BsonWriterState.Value)
            {
                var message = string.Format("WriteSymbol cannot be called when State is: {0}", state);
                throw new InvalidOperationException(message);
            }

            WriteValue(BsonSymbol.Create(value));
            state = GetNextState();
        }
コード例 #15
0
        public void TestMapString()
        {
            var value     = "hello";
            var bsonValue = (BsonString)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue("1", BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue("2010-01-02", BsonType.DateTime);

            Assert.AreEqual(new DateTime(2010, 1, 2), bsonDateTime.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Double);

            Assert.AreEqual(1.2, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue("1", BsonType.Int32);

            Assert.AreEqual(1, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue("1", BsonType.Int64);

            Assert.AreEqual(1L, bsonInt64.Value);
            var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScript);

            Assert.AreEqual("code", bsonJavaScript.Code);
            var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScriptWithScope);

            Assert.AreEqual("code", bsonJavaScriptWithScope.Code);
            Assert.AreEqual(0, bsonJavaScriptWithScope.Scope.ElementCount);
            var objectId     = ObjectId.GenerateNewId();
            var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(objectId.ToString(), BsonType.ObjectId);

            Assert.AreEqual(objectId, bsonObjectId.Value);
            var bsonRegularExpression = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(new Regex("pattern"), BsonType.RegularExpression);

            Assert.AreEqual("pattern", bsonRegularExpression.Pattern);
            Assert.AreEqual("", bsonRegularExpression.Options);
            var bsonString = (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String);

            Assert.AreEqual(value, bsonString.Value);
            var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue("symbol", BsonType.Symbol);

            Assert.AreSame(BsonSymbol.Create("symbol"), bsonSymbol);
        }
コード例 #16
0
        public void TestBsonSymbol()
        {
            var value = BsonSymbol.Create("name");

            Assert.Throws <InvalidCastException>(() => Convert.ToBoolean(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToByte(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToChar(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToDecimal(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToDouble(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToInt16(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToInt32(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToInt64(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToSByte(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToSingle(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToString(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToUInt16(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToUInt32(value));
            Assert.Throws <InvalidCastException>(() => Convert.ToUInt64(value));
        }
コード例 #17
0
 public TestClass(
     BsonSymbol value
 )
 {
     this.B = value;
     this.V = value;
     this.S = value;
 }
コード例 #18
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"]);
        }
コード例 #19
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);
        }