private void RemoveMatchingElements(BsonValue value, Regex regex)
 {
     if (value.BsonType == BsonType.Document)
     {
         var document = value.AsBsonDocument;
         foreach (var name in document.Names.ToList())
         {
             if (regex.IsMatch(name))
             {
                 document.Remove(name);
             }
             else
             {
                 RemoveMatchingElements(document[name], regex);
             }
         }
     }
     else if (value.BsonType == BsonType.Array)
     {
         foreach (var item in value.AsBsonArray)
         {
             RemoveMatchingElements(item, regex);
         }
     }
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonDocumentReader class.
 /// </summary>
 /// <param name="document">A BsonDocument.</param>
 /// <param name="settings">The reader settings.</param>
 public BsonDocumentReader(BsonDocument document, BsonDocumentReaderSettings settings)
     : base(settings)
 {
     _context = new BsonDocumentReaderContext(null, ContextType.TopLevel, document);
     _currentValue = document;
     _documentReaderSettings = settings; // already frozen by base class
 }
 public IndexKeysDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
Example #4
1
        public static void Write(this BsonDocument document, string field, BsonValue value)
        {

            if (value == null) return;

            if (field.StartsWith("_")) field = "PREFIX" + field;
            // todo: make sure the search query builder also picks up this name change.

            bool forcearray = (value.BsonType == BsonType.Document);
            // anders kan er op zo'n document geen $elemMatch gedaan worden.

            BsonElement element;

            if (document.TryGetElement(field, out element))
            {
                if (element.Value.BsonType == BsonType.Array)
                {
                    element.Value.AsBsonArray.Add(value);
                }
                else
                {
                    document.Remove(field);
                    document.Append(field, new BsonArray() { element.Value, value ?? BsonNull.Value });
                }
            }
            else
            {
                if (forcearray)
                    document.Append(field, new BsonArray() { value ?? BsonNull.Value });
                else
                    document.Append(field, value);
            }
        }
 public GroupByDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 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"),
         BsonSymbolTable.Lookup("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);
     }
 }
 private MapReduceOutput(
     string option,
     BsonValue value
 ) {
     this.option = option;
     this.value = value;
 }
 public BsonDocumentReader(
     BsonDocument document
 )
 {
     context = new BsonDocumentReaderContext(null, ContextType.TopLevel, document);
     currentValue = document;
 }
            private BsonValue PreprocessHex(BsonValue value)
            {
                var array = value as BsonArray;
                if (array != null)
                {
                    for (var i = 0; i < array.Count; i++)
                    {
                        array[i] = PreprocessHex(array[i]);
                    }
                    return array;
                }

                var document = value as BsonDocument;
                if (document != null)
                {
                    if (document.ElementCount == 1 && document.GetElement(0).Name == "$hex" && document[0].IsString)
                    {
                        var hex = document[0].AsString;
                        var bytes = BsonUtils.ParseHexString(hex);
                        return new BsonBinaryData(bytes);
                    }

                    for (var i = 0; i < document.ElementCount; i++)
                    {
                        document[i] = PreprocessHex(document[i]);
                    }
                    return document;
                }

                return value;
            }
Example #10
0
        public void Serialize(BsonValue value)
        {
            _indent = 0;
            _spacer = this.Pretty ? " " : "";

            this.WriteValue(value ?? BsonValue.Null);
        }
 // constructors
 internal BulkWriteOperationUpsert(
     int index,
     BsonValue id)
 {
     _index = index;
     _id = id;
 }
        private List<TransitionEvent> DeserializeTransitionEvents(BsonValue bsonValue)
        {
            if (!bsonValue.IsBsonArray)
                throw new Exception("Events should always be an array.");

            var eventArray = bsonValue.AsBsonArray;

            var events = new List<TransitionEvent>();
            foreach (var eventValue in eventArray)
            {
                var eventDoc = eventValue.AsBsonDocument;

                var eventTypeId = eventDoc["TypeId"].AsString;

                var eventType = Type.GetType(eventTypeId);

                if (eventType == null)
                    throw new Exception(String.Format("Cannot load this type: {0}. Make sure that assembly containing this type is referenced by your project.", eventTypeId));

                var eventData = _dataSerializer.Deserialize(eventDoc["Data"].AsBsonDocument, eventType);

                events.Add(new TransitionEvent(eventTypeId, eventData));
            }

            return events;
        }
 public BsonValueMemberProvider(BsonValue value)
 {
     this.mValue = value;
     this.mPropsToWrite = mValue.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
         .Where(p => !IgnoredProperties.Contains(p.Name) && p.GetIndexParameters().Length == 0)
         .ToArray();
 }
Example #14
0
 public static QueryComplete EQ(
     string name,
     BsonValue value
 )
 {
     return new QueryComplete(new BsonDocument(name, value));
 }
Example #15
0
 /// <summary>
 ///     初始化
 /// </summary>
 /// <param name="value"></param>
 public BsonValueEx(BsonValue value)
 {
     if (value.IsString)
     {
         MBsonType = "BsonString";
         MBsonString = value.ToString();
     }
     if (value.IsInt32)
     {
         MBsonType = "BsonInt32";
         MBsonInt32 = value.AsInt32;
     }
     if (value.IsValidDateTime)
     {
         MBsonType = "BsonDateTime";
         MBsonDateTime = value.ToUniversalTime();
     }
     if (value.IsBoolean)
     {
         MBsonType = "BsonBoolean";
         MBsonBoolean = value.AsBoolean;
     }
     if (value.IsDouble)
     {
         MBsonType = "BsonDouble";
         MBsonDouble = value.AsDouble;
     }
 }
 public QueryDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 public CommandDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
Example #18
0
        /// <summary>Try to convert the string to a <see cref="BsonBoolean"/>.</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 TryBoolean(this string value, out BsonValue bsonValue)
        {
            bsonValue = new BsonBoolean(false);

            if (value == null)
                return false;

            bool result;
            if (bool.TryParse(value, out result))
            {
                bsonValue = new BsonBoolean(true);
                return true;
            }

            string v = value.Trim();

            if (string.Equals(v, "t", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "true", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "y", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "yes", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "1", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "x", StringComparison.OrdinalIgnoreCase)
                || string.Equals(v, "on", StringComparison.OrdinalIgnoreCase))
                bsonValue = new BsonBoolean(true);

            return true;
        }
 public GeoNearOptionsDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 private static string FormatMessage(BsonValue id, long n, string reason)
 {
     Ensure.IsNotNull(id, nameof(id));
     Ensure.IsGreaterThanOrEqualToZero(n, nameof(n));
     Ensure.IsNotNull(reason, nameof(reason));
     return string.Format("GridFS chunk {0} of file id {1} is {2}.", n, id, reason);
 }
 public SortByDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 public static UpdateBuilder AddToSet(
     string name,
     BsonValue value
 )
 {
     return new UpdateBuilder().AddToSet(name, value);
 }
        public static IMongoQuery ExpressionQuery(string name, Operator optor, BsonValue value)
        {
            switch (optor)
            {
                case Operator.EQ:
                    return M.Query.EQ(name, value);

                case Operator.GT:
                    return M.Query.GT(name, value);

                case Operator.GTE:
                    return M.Query.GTE(name, value);

                case Operator.ISNULL:
                    return M.Query.EQ(name, null);

                case Operator.LT:
                    return M.Query.LT(name, value);

                case Operator.LTE:
                    return M.Query.LTE(name, value);

                case Operator.NOTNULL:
                    return M.Query.NE(name, null);

                default:
                    throw new ArgumentException(String.Format("Invalid operator {0} on token parameter {1}", optor.ToString(), name));
            }
        }
Example #24
0
        protected override bool TrySetArgument(string name, BsonValue value)
        {
            switch (name)
            {
                case "filter":
                    _filter = (BsonDocument)value;
                    return true;
                case "sort":
                    _options.Sort = value.ToBsonDocument();
                    return true;
                case "limit":
                    _options.Limit = value.ToInt32();
                    return true;
                case "skip":
                    _options.Skip = value.ToInt32();
                    return true;
                case "batchSize":
                    _options.BatchSize = value.ToInt32();
                    return true;
                case "modifiers":
                    _options.Modifiers = (BsonDocument)value;
                    return true;
            }

            return false;
        }
        private static object ConvertValue(string elementName, BsonValue value, IDictionary<string, string> aliases)
        {
            if (value.IsBsonDocument)
            {
                aliases = aliases.Where(x => x.Key.StartsWith(elementName + ".")).ToDictionary(x => x.Key.Remove(0, elementName.Length + 1), x => x.Value);
                return value.AsBsonDocument.ToSimpleDictionary(aliases);
            }
            else if (value.IsBsonArray)
                return value.AsBsonArray.Select(v => ConvertValue(elementName, v, aliases)).ToList();
            else if (value.IsBoolean)
                return value.AsBoolean;
            else if (value.IsDateTime)
                return value.AsDateTime;
            else if (value.IsDouble)
                return value.AsDouble;
            else if (value.IsGuid)
                return value.AsGuid;
            else if (value.IsInt32)
                return value.AsInt32;
            else if (value.IsInt64)
                return value.AsInt64;
            else if (value.IsObjectId)
                return value.AsObjectId;
            else if (value.IsString)
                return value.AsString;
            else if (value.BsonType == BsonType.Binary)
                 return value.AsByteArray;
 
            return value.RawValue;
        }
 public ScopeDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 private static void _assertRequired(Property property, BsonValue value)
 {
     if (property.Options.Required && value == BsonNull.Value)
     {
         throw new ArgumentException("the property \"" + property.Name + "\" is required and connot be null");
     }
 }
 public UpdateDocument(
     string name,
     BsonValue value
 )
     : base(name, value)
 {
 }
 /// <summary>
 /// Json serialize a BsonValue into a TextWriter
 /// </summary>
 public static void Serialize(BsonValue value, TextWriter writer, bool pretty = false, bool writeBinary = true)
 {
     var w = new JsonWriter(writer);
     w.Pretty = pretty;
     w.WriteBinary = writeBinary;
     w.Serialize(value ?? BsonValue.Null);
 }
Example #30
0
        public static void WriteBsonValue(this BinaryWriter writer, BsonValue value, ushort length)
        {
            writer.Write((byte)value.Type);

            switch(value.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    break;

                case BsonType.Int32: writer.Write((Int32)value.RawValue); break;
                case BsonType.Int64: writer.Write((Int64)value.RawValue); break;
                case BsonType.Double: writer.Write((Double)value.RawValue); break;

                case BsonType.String: writer.Write((String)value.RawValue, length); break;

                case BsonType.Document: new BsonWriter().WriteDocument(writer, value.AsDocument); break;
                case BsonType.Array: new BsonWriter().WriteArray(writer, value.AsArray); break;

                case BsonType.Binary: writer.Write((Byte[])value.RawValue); break;
                case BsonType.ObjectId: writer.Write((ObjectId)value.RawValue); break;
                case BsonType.Guid: writer.Write((Guid)value.RawValue); break;

                case BsonType.Boolean: writer.Write((Boolean)value.RawValue); break;
                case BsonType.DateTime: writer.Write((DateTime)value.RawValue); break;

                default: throw new NotImplementedException();
            }
        }
Example #31
0
 private void AssertEnum <T>(T?value, BsonValue expectedValue) where T : struct
 {
     value.Should().Be(expectedValue.IsBsonNull ? null : (T?)Enum.Parse(typeof(T), expectedValue.AsString, true));
 }
Example #32
0
        private BsonDocument GetReference()
        {
            BsonDocument reference = null;

            if (!_dontSetDocumentReference)
            {
                if (_documentReferenceElements1 != null || _documentReferenceElements2 != null)
                {
                    reference = new BsonDocument();
                    if (_documentReferenceElements1 != null)
                    {
                        BsonDocument documentReference1 = new BsonDocument();
                        reference.Add("document1", documentReference1);
                        if (_twoBsonDocuments.Document1 != null)
                        {
                            foreach (string element in _documentReferenceElements1)
                            {
                                BsonValue value = _twoBsonDocuments.Document1.zGet(element);
                                if (value != null)
                                {
                                    documentReference1.zSet(element, value);
                                }
                            }
                        }
                        else
                        {
                            documentReference1.Add("error", "document 1 is null");
                        }
                    }
                    if (_documentReferenceElements2 != null)
                    {
                        BsonDocument documentReference2 = new BsonDocument();
                        reference.Add("document2", documentReference2);
                        if (_twoBsonDocuments.Document2 != null)
                        {
                            foreach (string element in _documentReferenceElements2)
                            {
                                BsonValue value = _twoBsonDocuments.Document2.zGet(element);
                                if (value != null)
                                {
                                    documentReference2.zSet(element, value);
                                }
                            }
                        }
                        else
                        {
                            documentReference2.Add("error", "document 2 is null");
                        }
                    }
                }
                else
                {
                    reference = new BsonDocument();
                    if (_twoBsonDocuments.Document1 != null)
                    {
                        bool first = true;
                        foreach (BsonElement element in _twoBsonDocuments.Document1)
                        {
                            if (element.Value.IsBsonDocument)
                            {
                                if (first)
                                {
                                    //reference.Add(element);
                                    reference = element.Value.AsBsonDocument;
                                }
                                break;
                            }
                            reference.Add(element);
                            first = false;
                        }
                    }
                    else if (_twoBsonDocuments.Document2 != null)
                    {
                        bool first = true;
                        foreach (BsonElement element in _twoBsonDocuments.Document2)
                        {
                            if (element.Value.IsBsonDocument)
                            {
                                if (first)
                                {
                                    //reference.Add(element);
                                    reference = element.Value.AsBsonDocument;
                                }
                                break;
                            }
                            reference.Add(element);
                            first = false;
                        }
                    }
                    else
                    {
                        reference.Add("error", "document 1 and document 2 are null");
                    }
                }
            }
            return(reference);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="BsonValueAggregateExpressionDefinition{TSource, TResult}"/> class.
 /// </summary>
 /// <param name="expression">The expression.</param>
 public BsonValueAggregateExpressionDefinition(BsonValue expression)
 {
     _expression = Ensure.IsNotNull(expression, nameof(expression));
 }
        public void TestLookupActualType()
        {
            var actualType = BsonSerializer.LookupActualType(typeof(A), BsonValue.Create("C"));

            Assert.AreEqual(typeof(C), actualType);
        }
Example #35
0
        /// <summary>
        /// Looks up the actual type of an object to be deserialized.
        /// </summary>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="discriminator">The discriminator.</param>
        /// <returns>The actual type of the object.</returns>
        public static Type LookupActualType(Type nominalType, BsonValue discriminator)
        {
            if (discriminator == null)
            {
                return(nominalType);
            }

            // note: EnsureKnownTypesAreRegistered handles its own locking so call from outside any lock
            EnsureKnownTypesAreRegistered(nominalType);

            __configLock.EnterReadLock();
            try
            {
                Type actualType = null;

                HashSet <Type> hashSet;
                if (__discriminators.TryGetValue(discriminator, out hashSet))
                {
                    foreach (var type in hashSet)
                    {
                        if (nominalType.IsAssignableFrom(type))
                        {
                            if (actualType == null)
                            {
                                actualType = type;
                            }
                            else
                            {
                                string message = string.Format("Ambiguous discriminator '{0}'.", discriminator);
                                throw new BsonSerializationException(message);
                            }
                        }
                    }
                }

                if (actualType == null && discriminator.IsString)
                {
                    actualType = TypeNameDiscriminator.GetActualType(discriminator.AsString); // see if it's a Type name
                }

                if (actualType == null)
                {
                    string message = string.Format("Unknown discriminator value '{0}'.", discriminator);
                    throw new BsonSerializationException(message);
                }

                if (!nominalType.IsAssignableFrom(actualType))
                {
                    string message = string.Format(
                        "Actual type {0} is not assignable to expected type {1}.",
                        actualType.FullName, nominalType.FullName);
                    throw new BsonSerializationException(message);
                }

                return(actualType);
            }
            finally
            {
                __configLock.ExitReadLock();
            }
        }
Example #36
0
        public void TestDeserializeDouble()
        {
            // test with valid values
            _collection.RemoveAll();
            var values = new object[]
            {
                0,
                0L,
                0.0,
                -1,
                -1L,
                -1.0,
                1,
                1L,
                1.0,
                Int32.MinValue,
                Int32.MaxValue
            };

            for (int i = 0; i < values.Length; i++)
            {
                var document = new BsonDocument
                {
                    { "_id", i + 1 },
                    { "N", BsonValue.Create(values[i]) }
                };
                _collection.Insert(document);
            }

            for (int i = 0; i < values.Length; i++)
            {
                var query    = Query.EQ("_id", i + 1);
                var document = _collection.FindOneAs <D>(query);
                Assert.Equal(BsonValue.Create(values[i]).ToDouble(), document.N);
            }

            // test with values that cause data loss
            _collection.RemoveAll();
            values = new object[]
            {
                0x7eeeeeeeeeeeeeee,
                0xfeeeeeeeeeeeeeee,
                Int64.MinValue + 1, // need some low order bits to see data loss
                Int64.MaxValue
            };
            for (int i = 0; i < values.Length; i++)
            {
                var document = new BsonDocument
                {
                    { "_id", i + 1 },
                    { "N", BsonValue.Create(values[i]) }
                };
                _collection.Insert(document);
            }

            for (int i = 0; i < values.Length; i++)
            {
                var query = Query.EQ("_id", i + 1);
                try
                {
                    _collection.FindOneAs <D>(query);
                    Assert.True(false, "Expected an exception to be thrown.");
                }
                catch (Exception ex)
                {
                    var expectedMessage = "An error occurred while deserializing the N field of class MongoDB.Driver.Tests.Jira.CSharp112.CSharp112Tests+D: Truncation resulted in data loss.";
                    Assert.IsType <FormatException>(ex);
                    Assert.IsType <TruncationException>(ex.InnerException);
                    Assert.Equal(expectedMessage, ex.Message);
                }
            }
        }
Example #37
0
        public void TestDeserializeInt64()
        {
            // test with valid values
            _collection.RemoveAll();
            var values = new object[]
            {
                0,
                0L,
                0.0,
                -1,
                -1L,
                -1.0,
                1,
                1L,
                1.0,
                (double)Int32.MinValue,
                (double)Int32.MaxValue,
                (long)Int32.MinValue,
                (long)Int32.MaxValue,
                Int64.MinValue,
                Int64.MaxValue
            };

            for (int i = 0; i < values.Length; i++)
            {
                var document = new BsonDocument
                {
                    { "_id", i + 1 },
                    { "N", BsonValue.Create(values[i]) }
                };
                _collection.Insert(document);
            }

            for (int i = 0; i < values.Length; i++)
            {
                var query    = Query.EQ("_id", i + 1);
                var document = _collection.FindOneAs <L>(query);
                Assert.Equal(BsonValue.Create(values[i]).ToInt64(), document.N);
            }

            // test with values that cause overflow
            _collection.RemoveAll();
            values = new object[]
            {
                double.MaxValue,
                double.MinValue
            };
            for (int i = 0; i < values.Length; i++)
            {
                var document = new BsonDocument
                {
                    { "_id", i + 1 },
                    { "N", BsonValue.Create(values[i]) }
                };
                _collection.Insert(document);
            }

            for (int i = 0; i < values.Length; i++)
            {
                var query = Query.EQ("_id", i + 1);
                try
                {
                    _collection.FindOneAs <L>(query);
                    Assert.True(false, "Expected an exception to be thrown.");
                }
                catch (Exception ex)
                {
                    var expectedMessage = "An error occurred while deserializing the N field of class MongoDB.Driver.Tests.Jira.CSharp112.CSharp112Tests+L";
                    Assert.IsType <FormatException>(ex);
                    Assert.IsType <OverflowException>(ex.InnerException);
                    Assert.Equal(expectedMessage, ex.Message.Substring(0, ex.Message.IndexOf(':')));
                }
            }

            // test with values that cause data truncation
            _collection.RemoveAll();
            values = new object[]
            {
                -1.5,
                1.5
            };
            for (int i = 0; i < values.Length; i++)
            {
                var document = new BsonDocument
                {
                    { "_id", i + 1 },
                    { "N", BsonValue.Create(values[i]) }
                };
                _collection.Insert(document);
            }

            for (int i = 0; i < values.Length; i++)
            {
                var query = Query.EQ("_id", i + 1);
                try
                {
                    _collection.FindOneAs <L>(query);
                    Assert.True(false, "Expected an exception to be thrown.");
                }
                catch (Exception ex)
                {
                    var expectedMessage = "An error occurred while deserializing the N field of class MongoDB.Driver.Tests.Jira.CSharp112.CSharp112Tests+L: Truncation resulted in data loss.";
                    Assert.IsType <FormatException>(ex);
                    Assert.IsType <TruncationException>(ex.InnerException);
                    Assert.Equal(expectedMessage, ex.Message);
                }
            }
        }
Example #38
0
        /// <summary>
        /// Insert a new node index inside an collection index.
        /// </summary>
        private async Task <IndexNode> AddNode(CollectionIndex index, BsonValue key, PageAddress dataBlock, byte level, IndexNode last)
        {
            // get a free index page for head note
            var bytesLength = IndexNode.GetNodeLength(level, key, out var keyLength);

            // test for index key maxlength
            if (keyLength > MAX_INDEX_KEY_LENGTH)
            {
                throw LiteException.InvalidIndexKey($"Index key must be less than {MAX_INDEX_KEY_LENGTH} bytes.");
            }

            var freePage = await _snapshot.GetFreeIndexPage(bytesLength, index.FreeIndexPageList);

            // update free index page
            index.FreeIndexPageList = freePage.freeIndexPageList;

            // create node in buffer
            var node = freePage.indexPage.InsertIndexNode(index.Slot, level, key, dataBlock, bytesLength);

            // now, let's link my index node on right place
            var cur = await this.GetNode(index.Head);

            // using as cache last
            IndexNode cache = null;

            // scan from top left
            for (int i = index.MaxLevel - 1; i >= 0; i--)
            {
                // get cache for last node
                cache = cache != null && cache.Position == cur.Next[i] ? cache : await this.GetNode(cur.Next[i]);

                // for(; <while_not_this>; <do_this>) { ... }
                for (; cur.Next[i].IsEmpty == false; cur = cache)
                {
                    // get cache for last node
                    cache = cache != null && cache.Position == cur.Next[i] ? cache : await this.GetNode(cur.Next[i]);

                    // read next node to compare
                    var diff = cache.Key.CompareTo(key, _collation);

                    // if unique and diff = 0, throw index exception (must rollback transaction - others nodes can be dirty)
                    if (diff == 0 && index.Unique)
                    {
                        throw LiteException.IndexDuplicateKey(index.Name, key);
                    }

                    if (diff == 1)
                    {
                        break;
                    }
                }

                if (i <= (level - 1)) // level == length
                {
                    // cur = current (immediately before - prev)
                    // node = new inserted node
                    // next = next node (where cur is pointing)

                    node.SetNext((byte)i, cur.Next[i]);
                    node.SetPrev((byte)i, cur.Position);
                    cur.SetNext((byte)i, node.Position);

                    var next = await this.GetNode(node.Next[i]);

                    if (next != null)
                    {
                        next.SetPrev((byte)i, node.Position);
                    }
                }
            }

            // if last node exists, create a double link list
            if (last != null)
            {
                ENSURE(last.NextNode == PageAddress.Empty, "last index node must point to null");

                last.SetNextNode(node.Position);
            }

            // fix page position in free list slot
            index.FreeIndexPageList = await _snapshot.AddOrRemoveFreeIndexList(node.Page, index.FreeIndexPageList);

            return(node);
        }
        BsonDocument WhereExpress(string key, object obj)
        {
            var rtn    = new BsonDocument(true);
            var filter = Builders <BsonDocument> .Filter;

            if (key.StartsWith("$"))
            {
                if (key.ToLower() == "$or")
                {
                    BsonDocument q = new BsonDocument(true);
                    if (obj is object[])
                    {
                        var aobj = (object[])obj;
                        foreach (var item in aobj)
                        {
                            if (item is FrameDLRObject)
                            {
                                var ditem = (FrameDLRObject)item;
                                foreach (var itemkey in ditem.Keys)
                                {
                                    q.AddRange(filter.And(WhereExpress(itemkey, ditem.GetValue(itemkey))).ToBsonDocument());
                                }
                            }
                        }
                    }
                    //else if (obj is FrameDLRObject)
                    //{
                    //    var ditem = (FrameDLRObject)obj;
                    //    foreach (var itemkey in ditem.Keys)
                    //    {
                    //        l.AddRange(WhereExpress(itemkey, ditem.GetValue(itemkey)));
                    //    }
                    //}

                    if (q.Count() > 0)
                    {
                        rtn.AddRange(filter.Or(q).ToBsonDocument());
                    }
                }
                else if (key.ToLower() == "$and")
                {
                    BsonDocument q = new BsonDocument(true);
                    if (obj is object[])
                    {
                        var aobj = (object[])obj;
                        foreach (var item in aobj)
                        {
                            if (item is FrameDLRObject)
                            {
                                var ditem = (FrameDLRObject)item;
                                foreach (var itemkey in ditem.Keys)
                                {
                                    q.AddRange(filter.And(WhereExpress(itemkey, ditem.GetValue(itemkey))).ToBsonDocument());
                                }
                            }
                        }
                    }
                    if (q.Count() > 0)
                    {
                        rtn.AddRange(filter.And(q).ToBsonDocument());
                    }
                }
            }
            else
            {
                if (obj is FrameDLRObject)
                {
                    var dobj = (FrameDLRObject)obj;
                    foreach (var k in dobj.Keys)
                    {
                        var vobj = dobj.GetValue(k);
                        switch (k.ToLower())
                        {
                        case "$eq":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime || obj is bool)
                            {
                                rtn.AddRange(filter.Eq(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$neq":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime || obj is bool)
                            {
                                rtn.AddRange(filter.Ne(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$lt":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime)
                            {
                                rtn.AddRange(filter.Lt(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$gt":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime)
                            {
                                rtn.AddRange(filter.Gt(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$lte":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime)
                            {
                                rtn.AddRange(filter.Lte(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$gte":
                            if (vobj is string || vobj is double || vobj is int || vobj is DateTime)
                            {
                                rtn.AddRange(filter.Gte(key, BsonValue.Create(dobj.GetValue(k))).ToBsonDocument());
                            }
                            break;

                        case "$like":
                            if (vobj is string)
                            {
                                rtn.AddRange(filter.Regex(key, "/" + vobj + "/").ToBsonDocument());
                            }
                            break;

                        case "$likel":
                            if (vobj is string)
                            {
                                rtn.AddRange(filter.Regex(key, "/^" + vobj + "/").ToBsonDocument());
                            }
                            break;

                        case "$liker":
                            if (vobj is string)
                            {
                                rtn.AddRange(filter.Regex(key, "/" + vobj + "$/").ToBsonDocument());
                            }
                            break;

                        case "$in":
                            List <BsonValue> inl = new List <BsonValue>();
                            if (vobj is object[])
                            {
                                var array = (object[])vobj;
                                foreach (var item in array)
                                {
                                    if (item is string || item is int || item is double)
                                    {
                                        inl.Add(BsonValue.Create(item));
                                    }
                                }
                            }
                            rtn.AddRange(filter.In(key, inl.ToArray()).ToBsonDocument());
                            break;

                        case "$nin":
                            List <BsonValue> ninl = new List <BsonValue>();
                            if (vobj is object[])
                            {
                                var array = (object[])vobj;
                                foreach (var item in array)
                                {
                                    if (item is string || item is int || item is double)
                                    {
                                        ninl.Add(BsonValue.Create(item));
                                    }
                                }
                            }
                            rtn.AddRange(filter.Not(filter.In(key, ninl.ToArray())).ToBsonDocument());
                            break;

                        default:
                            break;
                        }
                    }
                }
                else if (obj is string || obj is int || obj is double || obj is DateTime || obj is bool)
                {
                    rtn.AddRange(new BsonDocument(key, BsonValue.Create(obj)));
                }
            }
            return(rtn);
        }
Example #40
0
 public IFilter Parse(BsonValue filter)
 {
     return(new NotEqualFilter(filter));
 }
 public AstBitsAnySetFilterOperation(BsonValue bitmask)
 {
     _bitmask = Ensure.IsNotNull(bitmask, nameof(bitmask));
 }
        protected override FrameDLRObject ParseExpress(FrameDLRObject obj)
        {
            var            rtn            = FrameDLRObject.CreateInstance();
            var            query          = new BsonDocument(true);
            var            update         = new BsonDocument(true);
            FrameDLRObject insert         = FrameDLRObject.CreateInstance(FrameDLRFlags.SensitiveCase);
            var            fields         = new BsonDocument(true);
            var            collectionname = "";

            foreach (var k in obj.Keys)
            {
                if (k.StartsWith("$"))
                {
                    if (k.ToLower() == "$where")
                    {
                        WhereExpress((FrameDLRObject)obj.GetValue(k), query, fields);
                    }
                    else if (k.ToLower() == "$table")
                    {
                        if (obj.GetValue(k) is string)
                        {
                            collectionname = ComFunc.nvl(obj.GetValue(k));
                        }
                    }
                }
                else
                {
                    var v = obj.GetValue(k);
                    if (this.CurrentAct == ActType.Query)
                    {
                        if (v is bool)
                        {
                            var bisinclude = (bool)v;
                            if (bisinclude)
                            {
                                fields.AddRange(Builders <BsonDocument> .Projection.Include(k).ToBsonDocument());
                            }
                            else
                            {
                                fields.AddRange(Builders <BsonDocument> .Projection.Exclude(k).ToBsonDocument());
                            }
                        }
                    }
                    else if (this.CurrentAct == ActType.Insert)
                    {
                        insert.SetValue(k, v);
                    }
                    else
                    {
                        if (!(v is FrameDLRObject))
                        {
                            update.Add(k, BsonValue.Create(v));
                        }
                    }
                }
            }
            rtn.query  = query;
            rtn.update = update;
            rtn.insert = insert;
            rtn.fields = fields;
            rtn.table  = collectionname;
            return(rtn);
        }
Example #43
0
 private void AssertBoolean(bool?value, BsonValue expectedValue)
 {
     value.Should().Be(expectedValue.IsBsonNull ? (bool?)null : expectedValue.ToBoolean());
 }
 /// <summary>
 /// Inserts a new value into the array.
 /// </summary>
 /// <param name="index">The zero based index at which to insert the new value.</param>
 /// <param name="value">The new value.</param>
 public override void Insert(int index, BsonValue value)
 {
     throw new NotSupportedException("RawBsonArray instances are immutable.");
 }
Example #45
0
        private void AssertTimeSpan(TimeSpan?value, BsonValue expectedValue, bool ms = true)
        {
            var expectedResult = ms ? TimeSpan.FromMilliseconds(expectedValue.AsInt32) : TimeSpan.FromSeconds(expectedValue.AsInt32);

            value.Should().Be(expectedValue.IsBsonNull ? (TimeSpan?)null : expectedResult);
        }
 /// <summary>
 /// Removes the first occurrence of a value from the array.
 /// </summary>
 /// <param name="value">The value to remove.</param>
 /// <returns>True if the value was removed.</returns>
 public override bool Remove(BsonValue value)
 {
     throw new NotSupportedException("RawBsonArray instances are immutable.");
 }
Example #47
0
 /// <summary>
 /// Sets the value of an element (an element will be added if no element with this name is found).
 /// </summary>
 /// <param name="name">The name of the element whose value is to be set.</param>
 /// <param name="value">The new value.</param>
 /// <returns>
 /// The document (so method calls can be chained).
 /// </returns>
 public override BsonDocument Set(string name, BsonValue value)
 {
     throw new NotSupportedException("RawBsonDocument instances are immutable.");
 }
 /// <summary>
 /// Gets the index of a value in the array.
 /// </summary>
 /// <param name="value">The value to search for.</param>
 /// <param name="index">The zero based index at which to start the search.</param>
 /// <returns>The zero based index of the value (or -1 if not found).</returns>
 public override int IndexOf(BsonValue value, int index)
 {
     return(IndexOf(value, index, int.MaxValue));
 }
 protected override List <BsonDocument> ConvertExpectedResult(BsonValue expectedResult)
 {
     return(((BsonArray)expectedResult).Select(x => (BsonDocument)x).ToList());
 }
Example #50
0
 public override BsonValue this[string name, BsonValue defaultValue]
 {
     get { return(GetValue(name, defaultValue)); }
 }
Example #51
0
 // explicit interface implementations
 // our version of Add returns BsonArray
 void ICollection <BsonValue> .Add(BsonValue value)
 {
     Add(value);
 }
Example #52
0
        /// <summary>
        /// 根据条件获取实体
        /// </summary>
        /// <param name="filterExp">查询条件表达式</param>
        /// <param name="includeFieldExp">查询字段表达式</param>
        /// <param name="sortExp">排序表达式</param>
        /// <param name="sortType">排序方式</param>
        /// <param name="hint">hint索引</param>
        /// <param name="readPreference">访问设置</param>
        /// <returns></returns>
        public TEntity Get(Expression <Func <TEntity, bool> > filterExp, Expression <Func <TEntity, object> > includeFieldExp = null
                           , Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, BsonValue hint = null
                           , ReadPreference readPreference = null)
        {
            FilterDefinition <TEntity> filter = null;
            ProjectionDefinition <TEntity, TEntity> projection = null;

            if (filterExp != null)
            {
                filter = Builders <TEntity> .Filter.Where(filterExp);
            }
            else
            {
                filter = Builders <TEntity> .Filter.Empty;
            }

            if (includeFieldExp != null)
            {
                projection = base.IncludeFields(includeFieldExp);
            }
            var option = base.CreateFindOptions(projection, sortExp, sortType, limit: 1, hint: hint);
            var result = base.GetCollection(readPreference).FindSync(filter, option);

            return(result.FirstOrDefault());
        }
Example #53
0
 /// <summary>
 /// Remove o elemento do respositório
 /// </summary>
 public void Delete(object key)
 {
     _collection.Remove(new QueryDocument("_id",
                                          BsonValue.Create(key)));
 }
Example #54
0
 /// <summary>
 /// Tests whether the array contains a value.
 /// </summary>
 /// <param name="value">The value to test for.</param>
 /// <returns>True if the array contains the value.</returns>
 public bool Contains(BsonValue value)
 {
     // don't throw ArgumentNullException if value is null
     // just let _values.Contains return false
     return(_values.Contains(value));
 }
Example #55
0
 protected override DeleteResult ConvertExpectedResult(BsonValue expectedResult)
 {
     return(new DeleteResult.Acknowledged(expectedResult["deletedCount"].ToInt64()));
 }
Example #56
0
 public void AddElement(string name, CompareElementResult compareResult, BsonValue value1 = null, BsonValue value2 = null)
 {
     _elements.Add(new ElementResult {
         Name = name, CompareResult = compareResult, Value1 = value1, Value2 = value2
     });
     if (compareResult != CompareElementResult.Equal)
     {
         _allElementsEqual = false;
     }
 }