private async Task StartCursorAsync(CancellationToken token)
        {
            var collection = _collection.Value;

            var options = new FindOptions <ChangeRecord> {
                CursorType = CursorType.TailableAwait
            };


            while (!token.IsCancellationRequested)
            {
                _logger.Trace()
                .Message("Starting tailable cursor on oplog.")
                .Write();

                var timestamp = GetTimestamp();
                var filter    = Builders <ChangeRecord> .Filter.Gte(m => m.Timestamp, timestamp);

                // Start the cursor and wait for the initial response
                using (var cursor = await collection.FindAsync(filter, options, token).ConfigureAwait(false))
                {
                    await cursor.ForEachAsync(document =>
                    {
                        LastNotification = document.Timestamp;
                        Publish(document);
                    }, token).ConfigureAwait(false);
                }

                // cursor died, restart it
            }
        }
        public void ChangeStreamOperation_should_not_calculate_effective_options_for_non_resume_process()
        {
            var pipeline               = new BsonDocument[0];
            var resultSerializer       = new ChangeStreamDocumentSerializer <BsonDocument>(BsonDocumentSerializer.Instance);
            var messageEncoderSettings = new MessageEncoderSettings();

            var resumeAfter          = new BsonDocument("a", 1);
            var startAfter           = new BsonDocument("b", 2);
            var startAtOperationTime = BsonTimestamp.Create(3L);
            var documentResumeToken  = new BsonDocument("c", 3);

            ChangeStreamOperation <ChangeStreamDocument <BsonDocument> > subject = new ChangeStreamOperation <ChangeStreamDocument <BsonDocument> >(_collectionNamespace, pipeline, resultSerializer, messageEncoderSettings)
            {
                ResumeAfter          = resumeAfter,
                StartAfter           = startAfter,
                StartAtOperationTime = startAtOperationTime,
                DocumentResumeToken  = documentResumeToken
            };

            var result = subject.CreateChangeStreamStage(false);

            var changeStream = result.GetValue("$changeStream").AsBsonDocument;

            changeStream.GetValue("resumeAfter").Should().Be(resumeAfter);
            changeStream.GetValue("startAfter").Should().Be(startAfter);
            changeStream.GetValue("startAtOperationTime").Should().Be(startAtOperationTime);
        }
        public void CreateCommand_should_return_the_expected_result_when_using_causal_consistency(
            [Values(null, ReadConcernLevel.Linearizable, ReadConcernLevel.Local)]
            ReadConcernLevel?level)
        {
            var readConcern = level.HasValue ? new ReadConcern(level.Value) : ReadConcern.Default;
            var subject     = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
            {
                ReadConcern = readConcern
            };
            var session = OperationTestHelper.CreateSession(isCausallyConsistent: true, operationTime: new BsonTimestamp(100));
            var connectionDescription = OperationTestHelper.CreateConnectionDescription(serverVersion: Feature.ReadConcern.FirstSupportedVersion, supportsSessions: true);

            var result = subject.CreateCommand(session, connectionDescription);

            var expectedReadConcernDocument = readConcern.ToBsonDocument();

            expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100);

            var expectedResult = new BsonDocument
            {
                { "mapReduce", _collectionNamespace.CollectionName },
                { "map", _mapFunction },
                { "reduce", _reduceFunction },
                { "out", new BsonDocument("inline", 1) },
                { "readConcern", expectedReadConcernDocument }
            };

            result.Should().Be(expectedResult);
        }
        public void TestBsonTimestampEquals()
        {
            var a = new BsonTimestamp(1);
            var b = new BsonTimestamp(1);
            var c = new BsonTimestamp(2);
            var n = (BsonTimestamp)null;

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

            Assert.IsTrue(a == b);
            Assert.IsFalse(a == c);
            Assert.IsFalse(a == BsonNull.Value);
            Assert.IsFalse(a == null);
            Assert.IsFalse(null == a);
            Assert.IsTrue(n == null);
            Assert.IsTrue(null == n);

            Assert.IsFalse(a != b);
            Assert.IsTrue(a != c);
            Assert.IsTrue(a != BsonNull.Value);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
        /// <inheritdoc />
        public async Task <IAsyncCursor <TResult> > ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
        {
            var bindingHandle = binding as IReadBindingHandle;

            if (bindingHandle == null)
            {
                throw new ArgumentException("The binding value passed to ChangeStreamOperation.ExecuteAsync must implement IReadBindingHandle.", nameof(binding));
            }

            IAsyncCursor <RawBsonDocument> cursor;

            using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false))
                using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false))
                    using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork()))
                    {
                        cursor = await ResumeAsync(channelBinding, cancellationToken).ConfigureAwait(false);

                        if (_startAtOperationTime == null && _resumeAfter == null)
                        {
                            var maxWireVersion = channel.ConnectionDescription.IsMasterResult.MaxWireVersion;
                            if (maxWireVersion >= 7)
                            {
                                _startAtOperationTime = binding.Session.OperationTime;
                            }
                        }
                    }

            return(new ChangeStreamCursor <TResult>(cursor, _resultSerializer, bindingHandle.Fork(), this));
        }
Exemple #6
0
        public void CreateCommand_should_return_the_expected_result_when_using_causal_consistency(
            [Values(null, ReadConcernLevel.Linearizable, ReadConcernLevel.Local)]
            ReadConcernLevel?level)
        {
            var readConcern = level.HasValue ? new ReadConcern(level.Value) : ReadConcern.Default;
            var subject     = new FindCommandOperation <BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                ReadConcern = readConcern
            };

            var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.ReadConcern.FirstSupportedVersion, supportsSessions: true);
            var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100));

            var result = subject.CreateCommand(connectionDescription, session);

            var expectedReadConcernDocument = readConcern.ToBsonDocument();

            expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100);

            var expectedResult = new BsonDocument
            {
                { "find", _collectionNamespace.CollectionName },
                { "readConcern", expectedReadConcernDocument }
            };

            result.Should().Be(expectedResult);
        }
Exemple #7
0
 /// <inheritdoc />
 public void SetSnapshotTimeIfNeeded(BsonTimestamp snapshotTime)
 {
     if (IsSnapshot && _snapshotTime == null)
     {
         _snapshotTime = snapshotTime;
     }
 }
 private async Task SaveCheckpoint(Checkpoint checkpoint, BsonTimestamp position)
 {
     checkpoint.Position = position;
     await checkpoints.UpdateOneAsync(
         c => c.Id == checkpoint.Id,
         Builders <Checkpoint> .Update.Set(c => c.Position, checkpoint.Position));
 }
        public void CreateCommand_should_return_the_expected_result_when_using_causal_consistency(
            [Values(null, ReadConcernLevel.Linearizable, ReadConcernLevel.Local)]
            ReadConcernLevel?level)
        {
            var readConcern = level == null ? ReadConcern.Default : new ReadConcern(level);
            var subject     = new CountOperation(_collectionNamespace, _messageEncoderSettings)
            {
                ReadConcern = readConcern
            };

            var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true);
            var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100));

            var result = subject.CreateCommand(connectionDescription, session);

            var expectedReadConcernDocument = readConcern.ToBsonDocument();

            expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100);

            var expectedResult = new BsonDocument
            {
                { "count", _collectionNamespace.CollectionName },
                { "readConcern", expectedReadConcernDocument }
            };

            result.Should().Be(expectedResult);
        }
 public MongoMessage(string connectionId, string eventKey, object value)
 {
     Id = new BsonTimestamp(0);
     ConnectionId = connectionId;
     EventKey = eventKey;
     Value = value.ToString();
 }
Exemple #11
0
        public static BsonTimestamp DateTimeToStamp(this DateTime time)
        {
            TimeSpan ts = time - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var      s  = Convert.ToInt64(ts.TotalSeconds - 28800).ToString();

            return(BsonTimestamp.Create(s));
        }
Exemple #12
0
        public StreamPosition(BsonTimestamp timestamp, long commitOffset, long commitSize)
        {
            Timestamp = timestamp;

            CommitOffset = commitOffset;
            CommitSize   = commitSize;
        }
Exemple #13
0
        public void constructor_should_initialize_instance()
        {
            var cursor                = new Mock <IAsyncCursor <RawBsonDocument> >().Object;
            var documentSerializer    = new Mock <IBsonSerializer <BsonDocument> >().Object;
            var binding               = new Mock <IReadBinding>().Object;
            var initialOperationTime  = new BsonTimestamp(3L);
            var postBatchResumeToken  = new BsonDocument("c", 3);
            var changeStreamOperation = CreateChangeStreamOperation();
            var startAfter            = new BsonDocument("a", 1);
            var resumeAfter           = new BsonDocument("b", 2);
            var startAtOperationTime  = BsonTimestamp.Create(3L);

            var subject = new ChangeStreamCursor <BsonDocument>(cursor, documentSerializer, binding, changeStreamOperation, postBatchResumeToken, initialOperationTime, startAfter, resumeAfter, startAtOperationTime);

            subject._binding().Should().BeSameAs(binding);
            subject._changeStreamOperation().Should().BeSameAs(changeStreamOperation);
            subject._current().Should().BeNull();
            subject._cursor().Should().BeSameAs(cursor);
            subject._disposed().Should().BeFalse();
            subject._documentSerializer().Should().BeSameAs(documentSerializer);
            subject._postBatchResumeToken().Should().BeSameAs(postBatchResumeToken);
            subject._initialOperationTime().Should().BeSameAs(initialOperationTime);
            subject._initialStartAfter().Should().Be(startAfter);
            subject._initialResumeAfter().Should().Be(resumeAfter);
            subject._initialStartAtOperationTime().Should().Be(startAtOperationTime);
        }
        public void CreateCommand_should_return_the_expected_result_when_using_causal_consistency(
            [Values(null, ReadConcernLevel.Linearizable)]
            ReadConcernLevel?level)
        {
            var readConcern = new ReadConcern(level);
            var subject     = new AggregateOperation <BsonDocument>(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings)
            {
                ReadConcern = readConcern
            };

            var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.ReadConcern.FirstSupportedVersion, supportsSessions: true);
            var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100));

            var result = subject.CreateCommand(connectionDescription, session);

            var expectedReadConcernDocument = readConcern.ToBsonDocument();

            expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100);

            var expectedResult = new BsonDocument
            {
                { "aggregate", _collectionNamespace.CollectionName },
                { "pipeline", new BsonArray(__pipeline) },
                { "readConcern", expectedReadConcernDocument },
                { "cursor", new BsonDocument() }
            };

            result.Should().Be(expectedResult);
        }
Exemple #15
0
 public FakeClientSessionHandle(FakeMongoClient client)
 {
     this.client   = client ?? throw new ArgumentNullException(nameof(client));
     clusterTime   = new BsonDocument();
     operationTime = new BsonTimestamp(10);
     options       = new ClientSessionOptions();
 }
Exemple #16
0
        public static BsonTimestamp ConvertToTimeStamp(this string strTime)
        {
            TimeSpan ts = Convert.ToDateTime(strTime) - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var      s  = Convert.ToInt64(ts.TotalSeconds).ToString();

            return(BsonTimestamp.Create(s));
        }
Exemple #17
0
        public static DateTime ConvertToDateTime(this BsonTimestamp Id)
        {
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 8, 0, 0, 0), TimeZoneInfo.Local);
            long     lTime   = long.Parse(Id.ToString() + "0000000");
            TimeSpan toNow   = new TimeSpan(lTime);

            return(dtStart.Add(toNow));
        }
 public void UpdateOptime(BsonTimestamp timestamp)
 {
     _observer.OnNext(new OpLogEvent()
     {
         Type = "UpdateOptime",
         Timestamp = timestamp
     });
 }
        public void CompareTo_should_return_plus_one_when_other_type_compares_lower()
        {
            var subject = new BsonTimestamp(0);

            var result = subject.CompareTo(BsonMinKey.Value);

            result.Should().Be(1);
        }
        public void BsonType_get_should_return_expected_result()
        {
            var subject = new BsonTimestamp(0);

            var result = subject.BsonType;

            result.Should().Be(BsonType.Timestamp);
        }
Exemple #21
0
        public void BsonType_get_should_return_expected_result()
        {
            var subject = new BsonTimestamp(0);

            var result = subject.BsonType;

            result.Should().Be(BsonType.Timestamp);
        }
Exemple #22
0
        public void Value_get_should_return_expected_result(long value)
        {
            var subject = new BsonTimestamp(value);

            var result = subject.Value;

            result.Should().Be(value);
        }
        public static ICoreSession CreateSession(bool isCausallyConsistent = false, BsonTimestamp operationTime = null)
        {
            var mock = new Mock <ICoreSession>();

            mock.SetupGet(x => x.IsCausallyConsistent).Returns(isCausallyConsistent);
            mock.SetupGet(x => x.OperationTime).Returns(operationTime);
            return(mock.Object);
        }
Exemple #24
0
        public void ToString_should_return_expected_result(long value, string expectedResult)
        {
            var subject = new BsonTimestamp(value);

            var result = subject.ToString();

            result.Should().Be(expectedResult);
        }
Exemple #25
0
        public void Timestamp_get_should_return_expected_result(ulong value, int expectedResult)
        {
            var subject = new BsonTimestamp((long)value);

            var result = subject.Timestamp;

            result.Should().Be(expectedResult);
        }
Exemple #26
0
        public void CompareTo_should_return_plus_one_when_other_type_compares_lower()
        {
            var subject = new BsonTimestamp(0);

            var result = subject.CompareTo(BsonMinKey.Value);

            result.Should().Be(1);
        }
        public void TestBsonTimestampEquals()
        {
            BsonTimestamp lhs = new BsonTimestamp(1L);
            BsonTimestamp rhs = new BsonTimestamp(1L);

            Assert.NotSame(lhs, rhs);
            Assert.Equal(lhs, rhs);
            Assert.Equal(lhs.GetHashCode(), rhs.GetHashCode());
        }
Exemple #28
0
        public void AdvanceOperationTime_should_do_nothing()
        {
            var subject          = new NoOperationClock();
            var newOperationTime = new BsonTimestamp(1);

            subject.AdvanceOperationTime(newOperationTime);

            subject.OperationTime.Should().BeNull();
        }
        private static DateTime?GetDateTime(BsonTimestamp timestamp)
        {
            if (timestamp == null)
            {
                return(null);
            }

            return(new DateTime(1970, 1, 1).AddSeconds(timestamp.Timestamp));
        }
        public static DateTime?ToDateTime(this BsonTimestamp ts)
        {
            if (ts.Timestamp != 0)
            {
                return(new DateTime(1970, 1, 1).AddSeconds(ts.Timestamp));
            }

            return(null);
        }
        public void TestAsBsonTimestamp()
        {
            BsonValue v  = new BsonTimestamp(1234);
            BsonValue s  = "";
            var       ts = v.AsBsonTimestamp;

            Assert.AreEqual(1234, ts.Value);
            Assert.Throws <InvalidCastException>(() => { var x = s.AsBsonTimestamp; });
        }
Exemple #32
0
        public void AdvanceOperationTime_should_have_expected_result()
        {
            var subject          = CreateSubject();
            var newOperationTime = new BsonTimestamp(0);

            subject.AdvanceOperationTime(newOperationTime);

            subject.OperationTime.Should().BeSameAs(newOperationTime);
        }
Exemple #33
0
        public void TestMapBsonTimestamp()
        {
            var value     = new BsonTimestamp(1234L);
            var bsonValue = (BsonTimestamp)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue(value, BsonType.Timestamp);

            Assert.AreSame(value, bsonTimestamp);
        }
Exemple #34
0
        public void AdvanceOperationTime_should_call_coreSession(
            [Values(false, true)] bool value)
        {
            var subject          = CreateSubject();
            var newOperationTime = new BsonTimestamp(0);

            subject.AdvanceOperationTime(newOperationTime);

            Mock.Get(subject.WrappedCoreSession).Verify(m => m.AdvanceOperationTime(newOperationTime), Times.Once);
        }
        public void CompareTo_should_return_expected_result(long value1, long? value2, int expectedResult)
        {
            var subject = new BsonTimestamp(value1);
            var other = value2 == null ? null : new BsonTimestamp(value2.Value);

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

            result1.Should().Be(expectedResult);
            result2.Should().Be(expectedResult);
        }
        /// <summary>
        /// Get the most recent oplog.
        /// </summary>
        /// <param name="beforeTime">The timestamp to check at or before.</param>
        /// <returns>The most recent oplog at or before the given timestamp.</returns>
        public virtual async Task<Oplog> GetMostRecentOplog(BsonTimestamp beforeTime = null)
        {
            SortDefinition<Oplog> sort = Builders<Oplog>.Sort.Descending("$natural");

            FilterDefinition<Oplog> filter = new BsonDocument();
            if(beforeTime != null)
            {
                filter = Builders<Oplog>.Filter.Lte(o => o.Timestamp, beforeTime);
            }

            Oplog record = await m_oplogCollection.Find(filter).Sort(sort).FirstOrDefaultAsync();
            if(record != null)
            {
                return record;
            }

            return null;
        }
        public void Equals_should_return_true_when_values_are_equal(long value)
        {
            var subject = new BsonTimestamp(value);
            var other = new BsonTimestamp(value);
            other.Should().NotBeSameAs(subject);

            var result1 = subject.Equals(other);
            var result2 = subject.Equals((object)other);
            var subjectHashCode = subject.GetHashCode();
            var otherHashCode = other.GetHashCode();

            result1.Should().BeTrue();
            result2.Should().BeTrue();
            otherHashCode.Should().Be(subjectHashCode);
        }
        public void Value_get_should_return_expected_result(long value)
        {
            var subject = new BsonTimestamp(value);

            var result = subject.Value;

            result.Should().Be(value);
        }
        public void Equals_should_return_false_when_other_is_wrong_type()
        {
            var subject = new BsonTimestamp(0);
            var other = new object();

            var result1 = subject.Equals(other);
            var result2 = subject.Equals((object)other);

            result1.Should().BeFalse();
            result2.Should().BeFalse();
        }
 public IObservable<OpLogEvent> Create(BsonTimestamp startTime)
 {
     return CreateInternal((stream, _) => stream.RunForever(startTime));
 }
 public void TestBsonTimestamp()
 {
     var value = new BsonTimestamp(123);
     Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null));
     Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToByte(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToChar(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDecimal(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDouble(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt16(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt32(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt64(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToSByte(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToSingle(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToString(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(value));
 }
        // private methods
        private void ReadValue()
        {
            object jsonDotNetValue;
            switch (_wrappedReader.GetCurrentBsonType())
            {
                case BsonType.Array:
                    _wrappedReader.ReadStartArray();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.StartArray);
                    return;

                case BsonType.Binary:
                    var bsonBinaryData = _wrappedReader.ReadBinaryData();
                    switch (bsonBinaryData.SubType)
                    {
                        case BsonBinarySubType.UuidLegacy:
                            var guidRepresentation = GuidRepresentation.Unspecified;
                            var bsonReader = _wrappedReader as BsonReader;
                            if (bsonReader != null)
                            {
                                guidRepresentation = bsonReader.Settings.GuidRepresentation;
                            }
                            jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, guidRepresentation);
                            break;

                        case BsonBinarySubType.UuidStandard:
                            jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, GuidRepresentation.Standard);
                            break;

                        default:
                            jsonDotNetValue = bsonBinaryData.Bytes;
                            break;
                    }
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, jsonDotNetValue, bsonBinaryData);
                    return;

                case BsonType.Boolean:
                    var booleanValue = _wrappedReader.ReadBoolean();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Boolean, booleanValue, (BsonBoolean)booleanValue);
                    return;

                case BsonType.DateTime:
                    var bsonDateTime = new BsonDateTime(_wrappedReader.ReadDateTime());
                    if (bsonDateTime.IsValidDateTime)
                    {
                        jsonDotNetValue = bsonDateTime.ToUniversalTime();
                    }
                    else
                    {
                        jsonDotNetValue = bsonDateTime.MillisecondsSinceEpoch;
                    }
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Date, jsonDotNetValue, bsonDateTime);
                    return;

                case BsonType.Document:
                    _wrappedReader.ReadStartDocument();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.StartObject);
                    return;

                case BsonType.Double:
                    var bsonDouble = new BsonDouble(_wrappedReader.ReadDouble());
                    switch (FloatParseHandling)
                    {
                        case Newtonsoft.Json.FloatParseHandling.Decimal:
                            jsonDotNetValue = Convert.ToDecimal(bsonDouble);
                            break;

                        case Newtonsoft.Json.FloatParseHandling.Double:
                            jsonDotNetValue = bsonDouble.Value;
                            break;

                        default:
                            throw new NotSupportedException(string.Format("Unexpected FloatParseHandling value: {0}.", FloatParseHandling));
                    }
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Float, jsonDotNetValue, bsonDouble);
                    return;

                case BsonType.Int32:
                    var bsonInt32 = (BsonInt32)_wrappedReader.ReadInt32();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, (long)bsonInt32.Value, bsonInt32);
                    return;

                case BsonType.Int64:
                    var bsonInt64 = (BsonInt64)_wrappedReader.ReadInt64();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonInt64.Value, bsonInt64);
                    return;

                case BsonType.JavaScript:
                    {
                        var code = _wrappedReader.ReadJavaScript();
                        var bsonJavaScript = new BsonJavaScript(code);
                        SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScript);
                    }
                    return;

                case BsonType.JavaScriptWithScope:
                    {
                        var code = _wrappedReader.ReadJavaScriptWithScope();
                        var context = BsonDeserializationContext.CreateRoot(_wrappedReader);
                        var scope = BsonDocumentSerializer.Instance.Deserialize<BsonDocument>(context);
                        var bsonJavaScriptWithScope = new BsonJavaScriptWithScope(code, scope);
                        SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScriptWithScope);
                    }
                    return;

                case BsonType.MaxKey:
                    _wrappedReader.ReadMaxKey();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMaxKey.Value);
                    return;

                case BsonType.MinKey:
                    _wrappedReader.ReadMinKey();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMinKey.Value);
                    return;

                case BsonType.Null:
                    _wrappedReader.ReadNull();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Null, null, BsonNull.Value);
                    return;

                case BsonType.ObjectId:
                    var bsonObjectId = new BsonObjectId(_wrappedReader.ReadObjectId());
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, bsonObjectId.Value.ToByteArray(), bsonObjectId);
                    return;

                case BsonType.RegularExpression:
                    var bsonRegularExpression = _wrappedReader.ReadRegularExpression();
                    var pattern = bsonRegularExpression.Pattern;
                    var options = bsonRegularExpression.Options;
                    jsonDotNetValue = "/" + pattern.Replace("/", "\\/") + "/" + options;
                    SetCurrentToken(Newtonsoft.Json.JsonToken.String, jsonDotNetValue, bsonRegularExpression);
                    return;

                case BsonType.String:
                    var stringValue = _wrappedReader.ReadString();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.String, stringValue, (BsonString)stringValue);
                    return;

                case BsonType.Symbol:
                    var bsonSymbol = BsonSymbolTable.Lookup(_wrappedReader.ReadSymbol());
                    SetCurrentToken(Newtonsoft.Json.JsonToken.String, bsonSymbol.Name, bsonSymbol);
                    return;

                case BsonType.Timestamp:
                    var bsonTimestamp = new BsonTimestamp(_wrappedReader.ReadTimestamp());
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonTimestamp.Value, bsonTimestamp);
                    return;

                case BsonType.Undefined:
                    _wrappedReader.ReadUndefined();
                    SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonUndefined.Value);
                    return;

                default:
                    var message = string.Format("Unexpected BsonType: {0}.", _wrappedReader.GetCurrentBsonType());
                    throw new Newtonsoft.Json.JsonReaderException(message);
            }
        }
Exemple #43
0
 public void TestBsonTimestampEquals()
 {
     BsonTimestamp lhs = new BsonTimestamp(1L);
     BsonTimestamp rhs = new BsonTimestamp(1L);
     Assert.NotSame(lhs, rhs);
     Assert.Equal(lhs, rhs);
     Assert.Equal(lhs.GetHashCode(), rhs.GetHashCode());
 }
        public void constructor_with_value_should_initialize_instance(long value)
        {
            var result = new BsonTimestamp(value);

            result.Value.Should().Be(value);
        }
        public void ToString_should_return_expected_result(long value, string expectedResult)
        {
            var subject = new BsonTimestamp(value);

            var result = subject.ToString();

            result.Should().Be(expectedResult);
        }
 public void TestBsonTimestamp()
 {
     var value = new BsonTimestamp(123);
     Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToByte(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToChar(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDecimal(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToDouble(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt16(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt32(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToInt64(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToSByte(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToSingle(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToString(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(value));
 }
 public void TestMapBsonTimestamp() {
     var value = new BsonTimestamp(1234L);
     var bsonValue = (BsonTimestamp) BsonTypeMapper.MapToBsonValue(value);
     Assert.AreSame(value, bsonValue);
     var bsonTimestamp = (BsonTimestamp) BsonTypeMapper.MapToBsonValue(value, BsonType.Timestamp);
     Assert.AreSame(value, bsonTimestamp);
 }
 public void TestAsBsonTimestamp()
 {
     BsonValue v = new BsonTimestamp(1234);
     BsonValue s = "";
     var ts = v.AsBsonTimestamp;
     Assert.AreEqual(1234, ts.Value);
     Assert.Throws<InvalidCastException>(() => { var x = s.AsBsonTimestamp; });
 }
 /// <summary>
 /// Start streaming the oplog tailer forever.
 /// </summary>
 /// <param name="startTime">The oplog timestamp to start at.</param>
 /// <returns>A never-ending task.</returns>
 public async Task RunForever(BsonTimestamp startTime)
 {
     var startOplog = await m_tailer.GetMostRecentOplog(startTime);
     await RunForever(startOplog);
 }
        public void Timestamp_get_should_return_expected_result(ulong value, int expectedResult)
        {
            var subject = new BsonTimestamp((long)value);

            var result = subject.Timestamp;

            result.Should().Be(expectedResult);
        }
 public TestClass(
     BsonTimestamp value
 )
 {
     this.B = value;
     this.V = value;
 }
        public void Equals_should_return_false_when_values_are_not_equal(long value1, long value2)
        {
            var subject = new BsonTimestamp(value1);
            var other = new BsonTimestamp(value2);

            var result1 = subject.Equals(other);
            var result2 = subject.Equals((object)other);
            var subjectHashCode = subject.GetHashCode();
            var otherHashCode = other.GetHashCode();

            result1.Should().BeFalse();
            result2.Should().BeFalse();
            otherHashCode.Should().NotBe(subjectHashCode);
        }
        public void TestBsonTimestampEquals()
        {
            var a = new BsonTimestamp(1);
            var b = new BsonTimestamp(1);
            var c = new BsonTimestamp(2);
            var n = (BsonTimestamp)null;

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

            Assert.IsTrue(a == b);
            Assert.IsFalse(a == c);
            Assert.IsFalse(a == BsonNull.Value);
            Assert.IsFalse(a == null);
            Assert.IsFalse(null == a);
            Assert.IsTrue(n == null);
            Assert.IsTrue(null == n);

            Assert.IsFalse(a != b);
            Assert.IsTrue(a != c);
            Assert.IsTrue(a != BsonNull.Value);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
        public void constructor_with_timestamp_increment_should_initialize_instance(int timestamp, int increment, ulong expectedValue)
        {
            var result = new BsonTimestamp(timestamp, increment);

            result.Value.Should().Be((long)expectedValue);
        }