/// <summary>
 /// Initializes a new instance of the DateTimeSerializationOptions class.
 /// </summary>
 /// <param name="kind">The DateTimeKind (Local, Unspecified or Utc).</param>
 /// <param name="representation">The external representation.</param>
 public DateTimeSerializationOptions(
     DateTimeKind kind,
     BsonType representation
 ) {
     this.kind = kind;
     this.representation = representation;
 }
 public CollectionProperty(string name, BsonType type, string fullName)
 {
     _name = name;
     _type = type;
     _fullName = fullName;
     Children = new Dictionary<string, CollectionProperty>();
 }
 /// <summary>
 /// Initializes a new instance of the DateTimeSerializationOptions class.
 /// </summary>
 /// <param name="dateOnly">Whether this DateTime consists of a Date only.</param>
 /// <param name="representation">The external representation.</param>
 public DateTimeSerializationOptions(
     bool dateOnly,
     BsonType representation
 ) {
     this.dateOnly = dateOnly;
     this.representation = representation;
 }
        public int CalculateSize(BsonType t_Type, List<object> value)
        {
            switch (t_Type)
            {
                case BsonType.Object:
                    {
                        foreach (var p in value)
                        {
                            //Console.WriteLine(new { p });

                            Native.document.body += new IHTMLPre { new { p } };

                        }
                        return -1;
                    }

                case BsonType.Integer:
                    return 4;
                case BsonType.Long:
                    return 8;
                case BsonType.Number:
                    return 8;
                case BsonType.Boolean:
                    return 1;
                case BsonType.Null:
                case BsonType.Undefined:
                    return 0;
                case BsonType.Date:
                    return 8;
                default:
                    return 12;
            }
        }
示例#5
0
        public static IBehavior Find(BsonType bsonType)
        {
            IBehavior behavior;

            return DsonBehaviors.TryGetValue(bsonType, out behavior)
                ? behavior
                : null;
        }
 // constructors
 internal JsonReaderBookmark(BsonReaderState state, BsonType currentBsonType, string currentName, JsonReaderContext context, JsonToken currentToken, BsonValue currentValue, JsonToken pushedToken, int position)
     : base(state, currentBsonType, currentName)
 {
     _context = context.Clone();
     _currentToken = currentToken;
     _currentValue = currentValue;
     _pushedToken = pushedToken;
     _position = position;
 }
 /// <summary>
 /// Initializes a new instance of the RepresentationSerializationOptions class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 /// <param name="allowOverflow">Whether to allow overflow.</param>
 /// <param name="allowTruncation">Whether to allow truncation.</param>
 public RepresentationSerializationOptions(
     BsonType representation,
     bool allowOverflow,
     bool allowTruncation
 ) {
     this.representation = representation;
     this.allowOverflow = allowOverflow;
     this.allowTruncation = allowTruncation;
 }
 internal BsonDocumentReaderBookmark(
     BsonDocumentReaderContext context,
     BsonReadState state,
     BsonType currentBsonType
 )
 {
     this.context = context.Clone();
     this.state = state;
     this.currentBsonType = currentBsonType;
 }
 protected BsonReaderBookmark(
     BsonReadState state,
     BsonType currentBsonType,
     string currentName
 )
 {
     this.state = state;
     this.currentBsonType = currentBsonType;
     this.currentName = currentName;
 }
示例#10
0
 public void ReturnToBookmark(PBBsonReaderBookmark bookmark)
 {
     _reader.ReturnToBookmark(bookmark.Bookmark);
     _type = bookmark.Type;
     _name = bookmark.Name;
     _bsonType = bookmark.BsonType;
     _value = bookmark.Value;
     _indent = bookmark.Indent;
     _indentString = bookmark.IndentString;
 }
示例#11
0
 public int Read(BsonReader reader)
 {
     sbyte typeNum = (sbyte)reader.ReadByte();
     int bytesRead;
     this.Name = reader.ReadString();
     this.Val = BsonConvert.Create((BsonDataType)typeNum);
     bytesRead = this.Val.Read(reader);
     bytesRead += (1 + this.Name.Length + 1); //type byte & name + term
     return bytesRead;
 }
 public BsonBinaryReader(
     BsonBuffer buffer,
     BsonBinaryReaderSettings settings
 ) {
     this.buffer = buffer ?? new BsonBuffer();
     this.disposeBuffer = buffer == null; // only call Dispose if we allocated the buffer
     this.settings = settings;
     context = null;
     state = BsonReadState.Initial;
     currentBsonType = BsonType.Document;
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="EnumRepresentationConvention" /> class.
 /// </summary>  
 /// <param name="representation">The serialization representation. 0 is used to detect representation
 /// from the enum itself.</param>
 public EnumRepresentationConvention(BsonType representation)
 {
     if (!((representation == 0) ||
         (representation == BsonType.String) ||
         (representation == BsonType.Int32) ||
         (representation == BsonType.Int64)))
     {
         throw new ArgumentException("Enums can only be represented as String, Int32, Int64 or the type of the enum");
     }
     _representation = representation;
 }
 // constructors
 internal BsonBinaryReaderBookmark(
     BsonReaderState state,
     BsonType currentBsonType,
     string currentName,
     BsonBinaryReaderContext context,
     int position)
     : base(state, currentBsonType, currentName)
 {
     _context = context.Clone();
     _position = position;
 }
 public void TestConvention(BsonType value)
 {
     var convention = new EnumRepresentationConvention(value);
     var classMap = new BsonClassMap<TestClass>();
     var nonEnumMemberMap = classMap.MapMember(x => x.NonEnum);
     var defaultEnumMemberMap = classMap.MapMember(x => x.DefaultEnum);
     var changedEnumMemberMap = classMap.MapMember(x => x.ChangedRepresentationEnum);
     convention.Apply(nonEnumMemberMap);
     convention.Apply(changedEnumMemberMap);
     Assert.AreEqual(value, ((IRepresentationConfigurable)(changedEnumMemberMap.GetSerializer())).Representation);
 }
 // constructors
 internal BsonDocumentReaderBookmark(
     BsonReaderState state,
     BsonType currentBsonType,
     string currentName,
     BsonDocumentReaderContext context,
     BsonValue currentValue)
     : base(state, currentBsonType, currentName)
 {
     _context = context.Clone();
     _currentValue = currentValue;
 }
 internal BsonBinaryReaderBookmark(
     BsonBinaryReaderContext context,
     BsonReadState state,
     BsonType currentBsonType,
     int position
 )
 {
     this.context = context;
     this.state = state;
     this.currentBsonType = currentBsonType;
     this.position = position;
 }
 public void TestConvention(BsonType value)
 {
     var convention = new EnumRepresentationConvention(value);
     var classMap = new BsonClassMap<TestClass>();
     var nonEnumMemberMap = classMap.MapMember(x => x.NonEnum);
     var defaultEnumMemberMap = classMap.MapMember(x => x.DefaultEnum);
     var changedEnumMemberMap = classMap.MapMember(x => x.ChangedRepresentationEnum);
     convention.Apply(nonEnumMemberMap);
     convention.Apply(changedEnumMemberMap);
     Assert.IsNull(nonEnumMemberMap.SerializationOptions);
     Assert.IsNull(defaultEnumMemberMap.SerializationOptions);
     Assert.AreEqual(value, ((RepresentationSerializationOptions)changedEnumMemberMap.SerializationOptions).Representation);
 }
示例#19
0
        public int CalculateSize(BsonType t_Type, List<object> value)
        {
            //TestSwitchForEach.BsonBinaryWriter <0000> nop
            //TestSwitchForEach.BsonBinaryWriter <004a> nop
            //TestSwitchForEach.BsonBinaryWriter <0053> br.s, to be optimized away
            //enter finally { mname = <0053> br.s, to be optimized away.try }
            //TestSwitchForEach.BsonBinaryWriter <006b> ldloca.s
            //enter finally { mname = <006b> ldloca.s.try }
            //TestSwitchForEach.BsonBinaryWriter <0055> ldloca.s
            //{ p = { x = 1 } }
            //enter finally { mname = <0055> ldloca.s.try }
            //TestSwitchForEach.BsonBinaryWriter <006b> ldloca.s
            //enter finally { mname = <006b> ldloca.s.try }
            //TestSwitchForEach.BsonBinaryWriter <0055> ldloca.s
            //{ p = { x = 2 } }
            //enter finally { mname = <0055> ldloca.s.try }
            //TestSwitchForEach.BsonBinaryWriter <006b> ldloca.s
            //enter finally { mname = <006b> ldloca.s.try }
            //TestSwitchForEach.BsonBinaryWriter <0078> leave.s, to be optimized away
            //enter finally { mname = <0078> leave.s, to be optimized away.try }
            //TestSwitchForEach.BsonBinaryWriter <0089> nop
            //TestSwitchForEach.BsonBinaryWriter <00ab> ldloc.1

            switch (t_Type)
            {
                case BsonType.Object:
                    {
                        foreach (var p in value)
                        {
                            Console.WriteLine(new { p });
                        }
                        return -1;
                    }

                case BsonType.Integer:
                    return 4;
                case BsonType.Long:
                    return 8;
                case BsonType.Number:
                    return 8;
                case BsonType.Boolean:
                    return 1;
                case BsonType.Null:
                case BsonType.Undefined:
                    return 0;
                case BsonType.Date:
                    return 8;
                default:
                    return 12;
            }
        }
示例#20
0
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140524

        //public static int WriteEscapedJavaScriptString(BsonType t_Type, ref  char[] writeBuffer)
        //public static int WriteEscapedJavaScriptString(BsonType t_Type, char[] writeBuffer)



        public int WriteEscapedJavaScriptString(
            BsonType t_Type,
            char[] writeBuffer,
            // why is this not made byref?
            foo foo)
        {
            foo foocopy = foo;

            // X:\jsc.svn\examples\rewrite\Test\TestSwitchForEach\TestSwitchForEach\Program.cs

            switch (t_Type)
            {
                case BsonType.Object:
                    {
                        //foreach (var p in writeBuffer)
                        foreach (var p in foo.writeBuffer)
                        {
                            Console.WriteLine(new { p });
                        }
                        return -1;
                    }

                case BsonType.Integer:
                    return 4;
                case BsonType.Long:
                    return 8;
                case BsonType.Number:
                    return 8;
                case BsonType.Boolean:
                    return 1;
                case BsonType.Null:
                case BsonType.Undefined:
                    return 0;
                case BsonType.Date:
                    return 8;
                default:
                    return 12;
            }
        }
示例#21
0
        private void ReadType(BsonType type)
        {
            switch (type)
            {
            case BsonType.Number:
                var d = ReadDouble();

                if (_floatParseHandling == FloatParseHandling.Decimal)
                {
                    SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
                }
                else
                {
                    SetToken(JsonToken.Float, d);
                }
                break;

            case BsonType.String:
            case BsonType.Symbol:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.Object:
            {
                SetToken(JsonToken.StartObject);

                var newContext = new ContainerContext(BsonType.Object);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Array:
            {
                SetToken(JsonToken.StartArray);

                var newContext = new ContainerContext(BsonType.Array);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Binary:
                BsonBinaryType binaryType;
                var            data = ReadBinary(out binaryType);

                var value = binaryType != BsonBinaryType.Uuid
                                                ? data
                                                : (object)new Guid(data);

                SetToken(JsonToken.Bytes, value);
                break;

            case BsonType.Undefined:
                SetToken(JsonToken.Undefined);
                break;

            case BsonType.Oid:
                var oid = ReadBytes(12);
                SetToken(JsonToken.Bytes, oid);
                break;

            case BsonType.Boolean:
                var b = Convert.ToBoolean(ReadByte());
                SetToken(JsonToken.Boolean, b);
                break;

            case BsonType.Date:
                var ticks       = ReadInt64();
                var utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);

                DateTime dateTime;
                switch (DateTimeKindHandling)
                {
                case DateTimeKind.Unspecified:
                    dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
                    break;

                case DateTimeKind.Local:
                    dateTime = utcDateTime.ToLocalTime();
                    break;

                default:
                    dateTime = utcDateTime;
                    break;
                }

                SetToken(JsonToken.Date, dateTime);
                break;

            case BsonType.Null:
                SetToken(JsonToken.Null);
                break;

            case BsonType.Regex:
                var expression = ReadString();
                var modifiers  = ReadString();

                var regex = @"/" + expression + @"/" + modifiers;
                SetToken(JsonToken.String, regex);
                break;

            case BsonType.Reference:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.ReferenceStart;
                break;

            case BsonType.Code:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.CodeWScope:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.CodeWScopeStart;
                break;

            case BsonType.Integer:
                SetToken(JsonToken.Integer, (long)ReadInt32());
                break;

            case BsonType.TimeStamp:
            case BsonType.Long:
                SetToken(JsonToken.Integer, ReadInt64());
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
            }
        }
示例#22
0
 private void AddValue(object value, BsonType type)
 {
     AddToken(new BsonValue(value, type));
 }
示例#23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DoubleSerializer"/> class.
 /// </summary>
 /// <param name="representation">The representation.</param>
 public DoubleSerializer(BsonType representation)
     : this(representation, new RepresentationConverter(false, false))
 {
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonReaderBookmark class.
 /// </summary>
 /// <param name="state">The state of the reader.</param>
 /// <param name="currentBsonType">The current BSON type.</param>
 /// <param name="currentName">The name of the current element.</param>
 protected BsonReaderBookmark(BsonReaderState state, BsonType currentBsonType, string currentName)
 {
     _state           = state;
     _currentBsonType = currentBsonType;
     _currentName     = currentName;
 }
示例#25
0
        private void ReadType(BsonType type)
        {
            switch (type)
            {
            case BsonType.Number:
                SetToken(JsonToken.Float, ReadDouble());
                break;

            case BsonType.String:
            case BsonType.Symbol:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.Object:
            {
                SetToken(JsonToken.StartObject);

                ContainerContext newContext = new ContainerContext(BsonType.Object);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Array:
            {
                SetToken(JsonToken.StartArray);

                ContainerContext newContext = new ContainerContext(BsonType.Array);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Binary:
                SetToken(JsonToken.Bytes, ReadBinary());
                break;

            case BsonType.Undefined:
                SetToken(JsonToken.Undefined);
                break;

            case BsonType.Oid:
                byte[] oid = ReadBytes(12);
                SetToken(JsonToken.Bytes, oid);
                break;

            case BsonType.Boolean:
                bool b = Convert.ToBoolean(ReadByte());
                SetToken(JsonToken.Boolean, b);
                break;

            case BsonType.Date:
                long     ticks       = ReadInt64();
                DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);

                DateTime dateTime;
                switch (DateTimeKindHandling)
                {
                case DateTimeKind.Unspecified:
                    dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
                    break;

                case DateTimeKind.Local:
                    dateTime = utcDateTime.ToLocalTime();
                    break;

                default:
                    dateTime = utcDateTime;
                    break;
                }

                SetToken(JsonToken.Date, dateTime);
                break;

            case BsonType.Null:
                SetToken(JsonToken.Null);
                break;

            case BsonType.Regex:
                string expression = ReadString();
                string modifiers  = ReadString();

                string regex = @"/" + expression + @"/" + modifiers;
                SetToken(JsonToken.String, regex);
                break;

            case BsonType.Reference:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.ReferenceStart;
                break;

            case BsonType.Code:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.CodeWScope:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.CodeWScopeStart;
                break;

            case BsonType.Integer:
                SetToken(JsonToken.Integer, (long)ReadInt32());
                break;

            case BsonType.TimeStamp:
            case BsonType.Long:
                SetToken(JsonToken.Integer, ReadInt64());
                break;

            default:
                throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
            }
        }
示例#26
0
 private BsonEmpty(BsonType type)
 {
     Type = type;
 }
示例#27
0
        /***************************************************/

        private object DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            // First try to recover the object type
            IBsonReader        reader   = context.Reader;
            BsonReaderBookmark bookmark = reader.GetBookmark();
            Type actualType             = typeof(CustomObject);

            try
            {
                actualType = _discriminatorConvention.GetActualType(reader, typeof(object));
            }
            catch
            {
                // This is were we can call the Version_Engine to return the new type string from the old one if exists
                string recordedType = GetCurrentTypeValue(reader);

                // If failed, return Custom object
                context.Reader.ReturnToBookmark(bookmark);
                Engine.Reflection.Compute.RecordWarning("The type " + recordedType + " is unknown -> data returned as custom objects.");
                IBsonSerializer customSerializer = BsonSerializer.LookupSerializer(typeof(CustomObject));
                return(customSerializer.Deserialize(context, args));
            }

            // Handle the special case where the type is object
            if (actualType == typeof(object))
            {
                BsonType currentBsonType = reader.GetCurrentBsonType();
                if (currentBsonType == BsonType.Document && context.DynamicDocumentSerializer != null)
                {
                    return(context.DynamicDocumentSerializer.Deserialize(context, args));
                }
                reader.ReadStartDocument();
                reader.ReadEndDocument();
                return(new object());
            }

            // Handle the genral case of finding the correct deserialiser and calling it
            IBsonSerializer            bsonSerializer            = BsonSerializer.LookupSerializer(actualType);
            IBsonPolymorphicSerializer bsonPolymorphicSerializer = bsonSerializer as IBsonPolymorphicSerializer;

            if (bsonPolymorphicSerializer != null && bsonPolymorphicSerializer.IsDiscriminatorCompatibleWithObjectSerializer)
            {
                bookmark = context.Reader.GetBookmark();
                try
                {
                    return(bsonSerializer.Deserialize(context, args));
                }
                catch
                {
                    context.Reader.ReturnToBookmark(bookmark);
                    Engine.Reflection.Compute.RecordWarning("Cannot find a definition of type " + actualType.FullName + " that matches the object to deserialise -> data returned as custom objects.");
                    IBsonSerializer customSerializer = BsonSerializer.LookupSerializer(typeof(CustomObject));
                    CustomObject    fallback         = customSerializer.Deserialize(context, args) as CustomObject;

                    //This is where we will try to get the correct object type from the custom object using the versionning engine

                    // If failed, just return the custom object
                    return(fallback);
                }
            }

            object result = null;
            bool   flag   = false;

            reader.ReadStartDocument();
            while (reader.ReadBsonType() != 0)
            {
                string text = reader.ReadName();
                if (text == _discriminatorConvention.ElementName)
                {
                    reader.SkipValue();
                }
                else
                {
                    if (!(text == "_v"))
                    {
                        throw new FormatException($"Unexpected element name: '{text}'.");
                    }
                    result = bsonSerializer.Deserialize(context);
                    flag   = true;
                }
            }
            reader.ReadEndDocument();
            if (!flag)
            {
                throw new FormatException("_v element missing.");
            }
            return(result);
        }
示例#28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeRepresentationSerializationOptionsConvention"/> class.
 /// </summary>
 /// <param name="type">The type of the member.</param>
 /// <param name="representation">The BSON representation to use for this type.</param>
 public TypeRepresentationSerializationOptionsConvention(Type type, BsonType representation)
 {
     _type           = type;
     _representation = representation;
 }
示例#29
0
 /// <summary>
 /// Initializes a new instance of the RepresentationSerializationOptions class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 public RepresentationSerializationOptions(
     BsonType representation
     )
 {
     this.representation = representation;
 }
示例#30
0
        public void RemoveFilesFromUserAccounts(File file, string username)
        {
            UserAccount account = GetUser(username);
            IMongoCollection <BsonDocument> userCollection = GetCollection(USER_COLLECTION);
            FilterDefinition <BsonDocument> getUserFilter  = Builders <BsonDocument> .Filter.Eq("_id", username);

            BsonDocument user = userCollection.Find(getUserFilter).First();

            BsonType    typeOfFiles = user["ListOfFiles"].BsonType;
            List <File> listOfFiles = new List <File>();

            if (typeOfFiles != BsonType.Null)
            {
                var userFilesList = user["ListOfFiles"].AsBsonArray;

                foreach (var element in userFilesList)
                {
                    File f = null;
                    f = BsonSerializer.Deserialize <File>(element.ToJson());
                    if (f.GUID != file.GUID)
                    {
                        listOfFiles.Add(f);
                    }
                }
            }

            UserAccount updatedAccount = GetUser(username);

            userCollection.DeleteOne(updatedAccount.ToBsonDocument());
            updatedAccount.ListOfFiles = listOfFiles;
            userCollection.InsertOne(updatedAccount.ToBsonDocument());

            Dictionary <string, Permission> users            = new Dictionary <string, Permission>();
            IMongoCollection <BsonDocument> fileCollection   = GetCollection(FILE_COLLECTION);
            FilterDefinition <BsonDocument> deleteFileFilter = Builders <BsonDocument> .Filter.Eq("GUID", file.GUID);

            BsonDocument fileToUpdateUsers = fileCollection.Find(deleteFileFilter).First();
            File         sharingFile       = BsonSerializer.Deserialize <File>(file.ToJson());

            file.Users = sharingFile.Users;
            Dictionary <string, Permission> remainingUsers = new Dictionary <string, Permission>();

            String toBeRemovedUsername = null;

            foreach (KeyValuePair <string, Permission> entry in sharingFile.Users)
            {
                string     currentAccount    = entry.Key;
                Permission currentPermission = entry.Value;

                if (currentAccount.Equals(username))
                {
                    toBeRemovedUsername = currentAccount;
                }
                else
                {
                    remainingUsers.Add(currentAccount, currentPermission);
                }
            }
            RemoveUserFromAccountFileUsers(toBeRemovedUsername, file.GUID, remainingUsers);
            DeleteFileFromFileCollection(sharingFile.GUID);
            sharingFile.Users = remainingUsers;
            fileCollection.InsertOne(sharingFile.ToBsonDocument());
        }
示例#31
0
 public BsonValue(object value, BsonType type)
 {
     this._value = value;
     this._type  = type;
 }
示例#32
0
        /// <summary>
        /// Internal implementation of insert a document
        /// </summary>
        private void InsertDocument(CollectionPage col, BsonDocument doc, BsonType autoId)
        {
            BsonValue id;

            // collection Sequence was created after release current datafile version.
            // In this case, Sequence will be 0 but already has documents. Let's fix this
            // ** this code can be removed when datafile change from 7 (HeaderPage.FILE_VERSION) **
            if (col.Sequence == 0 && col.DocumentCount > 0)
            {
                var max = this.Max(col.CollectionName, "_id");

                // if max value is a number, convert to Sequence last value
                // if not, just set sequence as document count
                col.Sequence = (max.IsInt32 || max.IsInt64 || max.IsDouble || max.IsDecimal) ?
                               Convert.ToInt64(max.RawValue) :
                               Convert.ToInt64(col.DocumentCount);
            }

            // increase collection sequence _id
            col.Sequence++;

            _pager.SetDirty(col);

            // if no _id, add one
            if (!doc.RawValue.TryGetValue("_id", out id))
            {
                doc["_id"] = id =
                    autoId == BsonType.ObjectId ? new BsonValue(ObjectId.NewObjectId()) :
                    autoId == BsonType.Guid ? new BsonValue(Guid.NewGuid()) :
                    autoId == BsonType.DateTime ? new BsonValue(DateTime.Now) :
                    autoId == BsonType.Int32 ? new BsonValue((Int32)col.Sequence) :
                    autoId == BsonType.Int64 ? new BsonValue(col.Sequence) : BsonValue.Null;
            }
            // create bubble in sequence number if _id is bigger than current sequence
            else if (autoId == BsonType.Int32 || autoId == BsonType.Int64)
            {
                var current = id.AsInt64;

                // if current id is bigger than sequence, jump sequence to this number. Other was, do not increse sequnce
                col.Sequence = current >= col.Sequence ? current : col.Sequence - 1;
            }

            // test if _id is a valid type
            if (id.IsNull || id.IsMinValue || id.IsMaxValue)
            {
                throw LiteException.InvalidDataType("_id", id);
            }

            _log.Write(Logger.COMMAND, "insert document on '{0}' :: _id = {1}", col.CollectionName, id.RawValue);

            // serialize object
            var bytes = BsonSerializer.Serialize(doc);

            // storage in data pages - returns dataBlock address
            var dataBlock = _data.Insert(col, bytes);

            // store id in a PK index [0 array]
            var pk = _indexer.AddNode(col.PK, id, null);

            // do link between index <-> data block
            pk.DataBlock = dataBlock.Position;

            // for each index, insert new IndexNode
            foreach (var index in col.GetIndexes(false))
            {
                // for each index, get all keys (support now multi-key) - gets distinct values only
                // if index are unique, get single key only
                var expr = new BsonExpression(index.Expression);
                var keys = expr.Execute(doc, true);

                // do a loop with all keys (multi-key supported)
                foreach (var key in keys)
                {
                    // insert node
                    var node = _indexer.AddNode(index, key, pk);

                    // link my index node to data block address
                    node.DataBlock = dataBlock.Position;
                }
            }
        }
示例#33
0
        /// <summary>
        /// Bulk documents to a collection - use data chunks for most efficient insert
        /// </summary>
        public int InsertBulk(string collection, IEnumerable <BsonDocument> docs, int batchSize = 5000, BsonType autoId = BsonType.ObjectId)
        {
            if (collection.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("collection");
            }
            if (docs == null)
            {
                throw new ArgumentNullException("docs");
            }
            if (batchSize < 100 || batchSize > 100000)
            {
                throw new ArgumentException("batchSize must be a value between 100 and 100000");
            }

            var count = 0;

            foreach (var batch in docs.Batch(batchSize))
            {
                count += this.Insert(collection, batch, autoId);
            }

            return(count);
        }
示例#34
0
 public ContainerContext(BsonType type) => Type = type;
示例#35
0
 public BsonValue(object value, BsonType type)
 {
     _value = value;
     _type  = type;
 }
 public Mapping(Type netType, BsonType bsonType)
 {
     this.netType  = netType;
     this.bsonType = bsonType;
 }
示例#37
0
 // explicit interface implementations
 IBsonSerializer IRepresentationConfigurable.WithRepresentation(BsonType representation)
 {
     return(WithRepresentation(representation));
 }
示例#38
0
        public void constructor_should_initialize_instance_when_representation_is_valid(BsonType representation)
        {
            var subject = new EnumRepresentationConvention(representation);

            subject.Representation.Should().Be(representation);
        }
示例#39
0
 public AstTypeFilterOperation(BsonType type)
 {
     _types = new List <BsonType> {
         type
     }.AsReadOnly();
 }
        /// <summary>
        /// Maps an object to a specific BsonValue type.
        /// </summary>
        /// <param name="value">An object.</param>
        /// <param name="bsonType">The BsonType to map to.</param>
        /// <returns>A BsonValue.</returns>
        public static BsonValue MapToBsonValue(object value, BsonType bsonType)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            var valueType = value.GetType();

            if (valueType.IsEnum)
            {
                valueType = Enum.GetUnderlyingType(valueType);
                switch (Type.GetTypeCode(valueType))
                {
                case TypeCode.Byte: value = (int)(byte)value; break;

                case TypeCode.Int16: value = (int)(short)value; break;

                case TypeCode.Int32: value = (int)value; break;

                case TypeCode.Int64: value = (long)value; break;

                case TypeCode.SByte: value = (int)(sbyte)value; break;

                case TypeCode.UInt16: value = (int)(ushort)value; break;

                case TypeCode.UInt32: value = (long)(uint)value; break;

                case TypeCode.UInt64: value = (long)(ulong)value; break;
                }
                valueType = value.GetType();
            }

            Conversion conversion; // the conversion (if it exists) that will convert value to bsonType

            if (fromToMappings.TryGetValue(Mapping.FromTo(valueType, bsonType), out conversion))
            {
                return(Convert(value, conversion));
            }

            // these coercions can't be handled by the conversions table (because of the interfaces)
            switch (bsonType)
            {
            case BsonType.Array:
                if (value is IEnumerable)
                {
                    return(new BsonArray((IEnumerable)value));
                }
                break;

            case BsonType.Document:
                if (value is IDictionary <string, object> )
                {
                    return(new BsonDocument((IDictionary <string, object>)value));
                }
                if (value is IDictionary)
                {
                    return(new BsonDocument((IDictionary)value));
                }
                break;
            }

            string message = string.Format(".NET type {0} cannot be mapped to BsonType.{1}.", value.GetType().FullName, bsonType);

            throw new ArgumentException(message, "value");
        }
示例#41
0
文件: BsonEmpty.cs 项目: cs130-w21/13
 private BsonEmpty(BsonType type)
 {
     this.Type = type;
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the TimeSpanSerializationOptions class.
 /// </summary>
 /// <param name="representation">The representation for serialized TimeSpans.</param>
 public TimeSpanSerializationOptions(BsonType representation)
     : this(representation, TimeSpanUnits.Ticks)
 {
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the RepresentationSerializationOptions class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 public RepresentationSerializationOptions(BsonType representation)
 {
     _representation = representation;
 }
示例#44
0
 private void AddValue(object value, BsonType type)
 {
     AddToken(new BsonValue(value, type));
 }
示例#45
0
        /***************************************************/

        private object DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            // First try to recover the object type
            IBsonReader        reader   = context.Reader;
            BsonReaderBookmark bookmark = reader.GetBookmark();
            Type actualType             = typeof(CustomObject);

            try
            {
                actualType = _discriminatorConvention.GetActualType(reader, typeof(object));
            }
            catch
            {
                try
                {
                    context.Reader.ReturnToBookmark(bookmark);
                    DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer();
                    return(deprecatedSerialiser.Deserialize(context, args));
                }
                catch { }
            }
            context.Reader.ReturnToBookmark(bookmark);

            if (actualType == null)
            {
                return(null);
            }

            // Handle the special case where the type is object
            if (actualType == typeof(object))
            {
                BsonType currentBsonType = reader.GetCurrentBsonType();
                if (currentBsonType == BsonType.Document && context.DynamicDocumentSerializer != null)
                {
                    return(context.DynamicDocumentSerializer.Deserialize(context, args));
                }
                reader.ReadStartDocument();
                reader.ReadEndDocument();
                return(new object());
            }

            // Handle the general case of finding the correct deserialiser and calling it
            try
            {
                if (!BsonClassMap.IsClassMapRegistered(actualType))
                {
                    Compute.RegisterClassMap(actualType); // LookupSerializer creates the classMap if it doesn't exist so important to do it through our own method
                }
                IBsonSerializer bsonSerializer = BsonSerializer.LookupSerializer(actualType);

                if (bsonSerializer.GetType().Name == "EnumerableInterfaceImplementerSerializer`2" && context.Reader.CurrentBsonType == BsonType.Document)
                {
                    if (!m_FallbackSerialisers.ContainsKey(actualType))
                    {
                        CreateFallbackSerialiser(actualType);
                    }
                    bsonSerializer = m_FallbackSerialisers[actualType];
                }
                else if (actualType.Name == "Dictionary`2" && context.Reader.CurrentBsonType == BsonType.Document)
                {
                    DictionarySerializer dicSerialiser = new DictionarySerializer();
                    return(dicSerialiser.Deserialize(context, args));
                }

                return(bsonSerializer.Deserialize(context, args));
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Could not load file or assembly"))
                {
                    Engine.Reflection.Compute.RecordError(e.Message);
                }

                context.Reader.ReturnToBookmark(bookmark);
                DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer();
                return(deprecatedSerialiser.Deserialize(context, args));
            }
        }
示例#46
0
 private static bool IsValidBsonType(
     BsonType bsonType
     )
 {
     return(validBsonTypes[(byte)bsonType]);
 }
示例#47
0
        private bool ReadNormal()
        {
            switch (CurrentState)
            {
            case State.Start:
            {
                JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
                BsonType  type  = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;

                SetToken(token);
                ContainerContext newContext = new ContainerContext(type);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                return(true);
            }

            case State.Complete:
            case State.Closed:
                return(false);

            case State.Property:
            {
                ReadType(_currentElementType);
                return(true);
            }

            case State.ObjectStart:
            case State.ArrayStart:
            case State.PostValue:
                ContainerContext context = _currentContext;
                if (context == null)
                {
                    return(false);
                }

                int lengthMinusEnd = context.Length - 1;

                if (context.Position < lengthMinusEnd)
                {
                    if (context.Type == BsonType.Array)
                    {
                        ReadElement();
                        ReadType(_currentElementType);
                        return(true);
                    }
                    else
                    {
                        SetToken(JsonToken.PropertyName, ReadElement());
                        return(true);
                    }
                }
                else if (context.Position == lengthMinusEnd)
                {
                    if (ReadByte() != 0)
                    {
                        throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
                    }

                    PopContext();
                    if (_currentContext != null)
                    {
                        MovePosition(context.Length);
                    }

                    JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
                    SetToken(endToken);
                    return(true);
                }
                else
                {
                    throw JsonReaderException.Create(this, "Read past end of current container context.");
                }

            case State.ConstructorStart:
                break;

            case State.Constructor:
                break;

            case State.Error:
                break;

            case State.Finished:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(false);
        }
 /// <summary>
 /// Verifies the current state and BsonType of the reader.
 /// </summary>
 /// <param name="methodName">The name of the method calling this one.</param>
 /// <param name="requiredBsonType">The required BSON type.</param>
 protected void VerifyBsonType(string methodName, BsonType requiredBsonType)
 {
     if (_state == BsonReaderState.Initial || _state == BsonReaderState.ScopeDocument || _state == BsonReaderState.Type)
     {
         ReadBsonType();
     }
     if (_state == BsonReaderState.Name)
     {
         // ignore name
         SkipName();
     }
     if (_state != BsonReaderState.Value)
     {
         ThrowInvalidState(methodName, BsonReaderState.Value);
     }
     if (_currentBsonType != requiredBsonType)
     {
         var message = string.Format(
             "{0} can only be called when CurrentBsonType is {1}, not when CurrentBsonType is {2}.",
             methodName, requiredBsonType, _currentBsonType);
         throw new InvalidOperationException(message);
     }
 }
 /// <summary>
 /// Writes a BsonType to the stream.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="value">The value.</param>
 public static void WriteBsonType(this BsonStream stream, BsonType value)
 {
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     
     stream.WriteByte((byte)value);
 }
示例#50
0
        private void ReadType(BsonType type)
        {
            switch (type)
            {
                case BsonType.Number:
                    double d = ReadDouble();

                    if (_floatParseHandling == FloatParseHandling.Decimal)
                        SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
                    else
                        SetToken(JsonToken.Float, d);
                    break;
                case BsonType.String:
                case BsonType.Symbol:
                    SetToken(JsonToken.String, ReadLengthString());
                    break;
                case BsonType.Object:
                {
                    SetToken(JsonToken.StartObject);

                    ContainerContext newContext = new ContainerContext(BsonType.Object);
                    PushContext(newContext);
                    newContext.Length = ReadInt32();
                    break;
                }
                case BsonType.Array:
                {
                    SetToken(JsonToken.StartArray);

                    ContainerContext newContext = new ContainerContext(BsonType.Array);
                    PushContext(newContext);
                    newContext.Length = ReadInt32();
                    break;
                }
                case BsonType.Binary:
                    SetToken(JsonToken.Bytes, ReadBinary());
                    break;
                case BsonType.Undefined:
                    SetToken(JsonToken.Undefined);
                    break;
                case BsonType.Oid:
                    byte[] oid = ReadBytes(12);
                    SetToken(JsonToken.Bytes, oid);
                    break;
                case BsonType.Boolean:
                    bool b = Convert.ToBoolean(ReadByte());
                    SetToken(JsonToken.Boolean, b);
                    break;
                case BsonType.Date:
                    long ticks = ReadInt64();
                    DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);

                    DateTime dateTime;
                    switch (DateTimeKindHandling)
                    {
                        case DateTimeKind.Unspecified:
                            dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
                            break;
                        case DateTimeKind.Local:
                            dateTime = utcDateTime.ToLocalTime();
                            break;
                        default:
                            dateTime = utcDateTime;
                            break;
                    }

                    SetToken(JsonToken.Date, dateTime);
                    break;
                case BsonType.Null:
                    SetToken(JsonToken.Null);
                    break;
                case BsonType.Regex:
                    string expression = ReadString();
                    string modifiers = ReadString();

                    string regex = @"/" + expression + @"/" + modifiers;
                    SetToken(JsonToken.String, regex);
                    break;
                case BsonType.Reference:
                    SetToken(JsonToken.StartObject);
                    _bsonReaderState = BsonReaderState.ReferenceStart;
                    break;
                case BsonType.Code:
                    SetToken(JsonToken.String, ReadLengthString());
                    break;
                case BsonType.CodeWScope:
                    SetToken(JsonToken.StartObject);
                    _bsonReaderState = BsonReaderState.CodeWScopeStart;
                    break;
                case BsonType.Integer:
                    SetToken(JsonToken.Integer, (long)ReadInt32());
                    break;
                case BsonType.TimeStamp:
                case BsonType.Long:
                    SetToken(JsonToken.Integer, ReadInt64());
                    break;
                default:
                    throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
            }
        }
 /// <summary>
 /// Initializes a new instance of the TimeSpanSerializationOptions class.
 /// </summary>
 /// <param name="representation">The representation for serialized TimeSpans.</param>
 /// <param name="units">The units for serialized TimeSpans.</param>
 public TimeSpanSerializationOptions(BsonType representation, TimeSpanUnits units)
 {
     _representation = representation;
     _units = units;
 }
示例#52
0
 /// <summary>
 /// Initializes a new instance of the KeyValuePairSerializationOptions class.
 /// </summary>
 /// <param name="representation">The representation to use for the KeyValuePair.</param>
 /// <param name="keySerializationOptions">The serialization options for the key.</param>
 /// <param name="valueSerializationOptions">The serialization options for the value.</param>
 public KeyValuePairSerializationOptions(BsonType representation, IBsonSerializationOptions keySerializationOptions, IBsonSerializationOptions valueSerializationOptions)
 {
     _representation            = representation;
     _keySerializationOptions   = keySerializationOptions;
     _valueSerializationOptions = valueSerializationOptions;
 }
        // public methods
        /// <summary>
        /// Apply an attribute to these serialization options and modify the options accordingly.
        /// </summary>
        /// <param name="serializer">The serializer that these serialization options are for.</param>
        /// <param name="attribute">The serialization options attribute.</param>
        public override void ApplyAttribute(IBsonSerializer serializer, Attribute attribute)
        {
            EnsureNotFrozen();
            var representationAttribute = attribute as BsonRepresentationAttribute;
            if (representationAttribute != null)
            {
                _allowOverflow = representationAttribute.AllowOverflow;
                _allowTruncation = representationAttribute.AllowTruncation;
                _representation = representationAttribute.Representation;
                return;
            }

            var message = string.Format("A serialization options attribute of type {0} cannot be applied to serialization options of type {1}.",
                BsonUtils.GetFriendlyTypeName(attribute.GetType()), BsonUtils.GetFriendlyTypeName(GetType()));
            throw new NotSupportedException(message);
        }
示例#54
0
 protected BsonValue(BsonType type, object rawValue)
 {
     this.Type     = type;
     this.RawValue = rawValue;
 }
示例#55
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonTimeSpanOptionsAttribute class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 public BsonTimeSpanOptionsAttribute(BsonType representation)
 {
     _representation = representation;
 }
 public static Mapping FromTo(Type netType, BsonType bsonType)
 {
     return(new Mapping(netType, bsonType));
 }
示例#57
0
 private string ReadElement()
 {
     _currentElementType = ReadType();
     string elementName = ReadString();
     return elementName;
 }
示例#58
0
 /// <summary>
 /// Initializes a new instance of the BsonTimeSpanOptionsAttribute class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 /// <param name="units">The TimeSpanUnits.</param>
 public BsonTimeSpanOptionsAttribute(BsonType representation, TimeSpanUnits units)
 {
     _representation = representation;
     _units          = units;
 }
示例#59
0
 public ContainerContext(BsonType type)
 {
     Type = type;
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonRepresentationAttribute class.
 /// </summary>
 /// <param name="representation">The external representation.</param>
 public BsonRepresentationAttribute(BsonType representation)
 {
     _representation = representation;
 }