public async Task log_has_expected_bson_datatypes() { MockClock clockMock = new MockClock(); (IBank <TestUser> bank, IMongoCollection <TestUser> usersCollection) = CreateDbObjects(clockMock); TestUser user = new TestUser { Money = 10 }; await usersCollection.InsertOneAsync(user); List <int> list = new List <int> { 1, 2, 3 }; Dictionary <string, bool> dictionary = new Dictionary <string, bool> { ["yes"] = true, ["no"] = false }; await bank.PerformTransaction(new Transaction <TestUser>(user, 1, "test", new Dictionary <string, object?> { ["null_field"] = null, ["int_field"] = 42, ["string_field"] = "foo", ["list_field"] = list, ["dictionary_field"] = dictionary })); IMongoCollection <BsonDocument> transactionLogCollection = usersCollection.Database.GetCollection <BsonDocument>("transactionLog"); BsonDocument log = await transactionLogCollection.Find(FilterDefinition <BsonDocument> .Empty).FirstAsync(); Assert.IsInstanceOf <BsonObjectId>(log["_id"]); Assert.AreEqual(BsonString.Create(user.Id), log["user"]); Assert.AreEqual(BsonInt64.Create(1), log["change"]); Assert.AreEqual(BsonInt64.Create(10), log["old_balance"]); Assert.AreEqual(BsonInt64.Create(11), log["new_balance"]); Assert.AreEqual(clockMock.FixedCurrentInstant, log["timestamp"].ToUniversalTime().ToInstant()); Assert.AreEqual(BsonString.Create("test"), log["type"]); Assert.AreEqual(BsonNull.Value, log["null_field"]); Assert.AreEqual(BsonInt32.Create(42), log["int_field"]); Assert.AreEqual(BsonString.Create("foo"), log["string_field"]); Assert.AreEqual(BsonArray.Create(list), log["list_field"]); Assert.AreEqual(BsonDocument.Create(dictionary), log["dictionary_field"]); }
public void TestClassWithBsonInt64Id() { _collection.RemoveAll(); var doc = new ClassWithBsonInt64Id { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonInt64Id { Id = BsonInt64.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonInt64Id { Id = BsonInt64.Create(1), X = 1 }; _collection.Insert(doc); }
public void TestBsonInt64() { var value = BsonInt64.Create(1); Assert.AreEqual(true, Convert.ToBoolean(value)); Assert.AreEqual(1, Convert.ToByte(value)); Assert.AreEqual(1, Convert.ToChar(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value)); Assert.AreEqual(1m, Convert.ToDecimal(value)); Assert.AreEqual(1.0, Convert.ToDouble(value)); Assert.AreEqual(1, Convert.ToInt16(value)); Assert.AreEqual(1, Convert.ToInt32(value)); Assert.AreEqual(1, Convert.ToInt64(value)); Assert.AreEqual(1, Convert.ToSByte(value)); Assert.AreEqual(1.0F, Convert.ToSingle(value)); Assert.AreEqual("1", Convert.ToString(value)); Assert.AreEqual(1, Convert.ToUInt16(value)); Assert.AreEqual(1, Convert.ToUInt32(value)); Assert.AreEqual(1, Convert.ToUInt64(value)); }
// public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonInt64)); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { return(BsonInt64.Create((long)Int64Serializer.Instance.Deserialize(bsonReader, typeof(long), options))); } }
private BsonValue ParseNumberLong() { VerifyToken("("); var valueToken = PopToken(); long value; if (valueToken.Type == JsonTokenType.Int32 || valueToken.Type == JsonTokenType.Int64) { value = valueToken.Int64Value; } else if (valueToken.Type == JsonTokenType.String) { value = long.Parse(valueToken.StringValue); } else { var message = string.Format("JSON reader expected an integer or a string but found: '{0}'", valueToken.Lexeme); throw new FileFormatException(message); } VerifyToken(")"); return(BsonInt64.Create(value)); }
public void TestClassWithBsonValueId() { // repeats all tee TestClassWithBsonXyzId tests using ClassWithBsonValueId { // same as TestClassWithBonArrayId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonArray(), X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); doc = new ClassWithBsonValueId { Id = new BsonArray { 1, 2, 3 }, X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); } { // same as TestClastWithBsonBinaryDataId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBinaryData.Create(new byte[] { }), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBinaryData.Create(new byte[] { 1, 2, 3 }), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonBooleanId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBoolean.Create(false), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBoolean.Create(true), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonDocumentId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonDocument(), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonDocument { { "A", 1 }, { "B", 2 } }, X = 3 }; _collection.Insert(doc); } { // same as TestClassWithBsonDateTimeId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.MinValue), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.UtcNow), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.MaxValue), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonDoubleId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDouble.Create(0.0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDouble.Create(1.0), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonInt32Id _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt32.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt32.Create(1), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonInt64Id _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt64.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt64.Create(1), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonMaxKeyId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonMaxKey.Value, X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonMinKeyId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonMinKey.Value, X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonNullId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonNull.Value, X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); } { // same as TestClassWithBsonObjectId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue doc = new ClassWithBsonValueId { Id = BsonObjectId.Empty, X = 1 }; _collection.Insert(doc); Assert.AreEqual(ObjectId.Empty, doc.Id.AsObjectId); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue doc = new ClassWithBsonValueId { Id = BsonObjectId.GenerateNewId(), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonStringId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); doc = new ClassWithBsonValueId { Id = "", X = 1 }; _collection.Insert(doc); Assert.AreEqual("", doc.Id.AsString); doc = new ClassWithBsonValueId { Id = "123", X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonTimestampId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); doc = new ClassWithBsonValueId { Id = BsonTimestamp.Create(0, 0), X = 1 }; _collection.Insert(doc); Assert.AreEqual(BsonTimestamp.Create(0, 0), doc.Id); doc = new ClassWithBsonValueId { Id = BsonTimestamp.Create(1, 2), X = 1 }; _collection.Insert(doc); } }
public static BsonValue Create(this BsonType bsonType, object o) { BsonValue value = BsonNull.Value; try { switch (bsonType) { case BsonType.EndOfDocument: break; case BsonType.Double: value = BsonDouble.Create(o); break; case BsonType.String: value = BsonString.Create(o); break; case BsonType.Document: value = BsonDocument.Create(o); break; case BsonType.Array: value = BsonArray.Create(o); break; case BsonType.Binary: value = BsonBinaryData.Create(o); break; case BsonType.Undefined: break; case BsonType.ObjectId: value = BsonObjectId.Create(o); break; case BsonType.Boolean: value = BsonBoolean.Create(o); break; case BsonType.DateTime: value = BsonDateTime.Create(o); break; case BsonType.Null: value = BsonNull.Value; break; case BsonType.RegularExpression: value = BsonRegularExpression.Create(o); break; case BsonType.JavaScript: value = BsonJavaScript.Create(o); break; case BsonType.Symbol: value = BsonSymbol.Create(o); break; case BsonType.JavaScriptWithScope: value = BsonJavaScriptWithScope.Create(o); break; case BsonType.Int32: value = BsonInt32.Create(o); break; case BsonType.Timestamp: value = BsonTimestamp.Create(o); break; case BsonType.Int64: value = BsonInt64.Create(o); break; case BsonType.MaxKey: value = BsonValue.Create(o); break; case BsonType.MinKey: value = BsonValue.Create(o); break; } } catch { } return(value); }
/// <summary> /// Uploads a GridFS file. /// </summary> /// <param name="stream">The source stream.</param> /// <param name="remoteFileName">The remote file name.</param> /// <param name="createOptions">The create options.</param> /// <returns>The file info of the new GridFS file.</returns> public MongoGridFSFileInfo Upload( Stream stream, string remoteFileName, MongoGridFSCreateOptions createOptions) { using (_database.RequestStart(false)) // not slaveOk { EnsureIndexes(); var files_id = createOptions.Id ?? BsonObjectId.GenerateNewId(); var chunkSize = createOptions.ChunkSize == 0 ? _settings.ChunkSize : createOptions.ChunkSize; var buffer = new byte[chunkSize]; var length = 0L; string md5Client = null; using (var md5Algorithm = _settings.VerifyMD5 ? MD5.Create() : null) { for (var n = 0L; true; n++) { // might have to call Stream.Read several times to get a whole chunk var bytesNeeded = chunkSize; var bytesRead = 0; while (bytesNeeded > 0) { var partialRead = stream.Read(buffer, bytesRead, bytesNeeded); if (partialRead == 0) { break; // EOF may or may not have a partial chunk } bytesNeeded -= partialRead; bytesRead += partialRead; } if (bytesRead == 0) { break; // EOF no partial chunk } length += bytesRead; byte[] data = buffer; if (bytesRead < chunkSize) { data = new byte[bytesRead]; Buffer.BlockCopy(buffer, 0, data, 0, bytesRead); } var chunk = new BsonDocument { { "_id", BsonObjectId.GenerateNewId() }, { "files_id", files_id }, { "n", (n < int.MaxValue) ? (BsonValue)BsonInt32.Create((int)n) : BsonInt64.Create(n) }, { "data", new BsonBinaryData(data) } }; _chunks.Insert(chunk, _settings.SafeMode); if (_settings.VerifyMD5) { md5Algorithm.TransformBlock(data, 0, data.Length, null, 0); } if (bytesRead < chunkSize) { break; // EOF after partial chunk } } if (_settings.VerifyMD5) { md5Algorithm.TransformFinalBlock(new byte[0], 0, 0); md5Client = BsonUtils.ToHexString(md5Algorithm.Hash); } } string md5Server = null; if (_settings.UpdateMD5 || _settings.VerifyMD5) { var md5Command = new CommandDocument { { "filemd5", files_id }, { "root", _settings.Root } }; var md5Result = _database.RunCommand(md5Command); md5Server = md5Result.Response["md5"].AsString; } if (_settings.VerifyMD5 && !md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase)) { throw new MongoGridFSException("Upload client and server MD5 hashes are not equal."); } var uploadDate = createOptions.UploadDate == DateTime.MinValue ? DateTime.UtcNow : createOptions.UploadDate; BsonDocument fileInfo = new BsonDocument { { "_id", files_id }, { "filename", remoteFileName }, { "length", length }, { "chunkSize", chunkSize }, { "uploadDate", uploadDate }, { "md5", (md5Server == null) ? (BsonValue)BsonNull.Value : new BsonString(md5Server) }, { "contentType", createOptions.ContentType }, // optional { "aliases", BsonArray.Create(createOptions.Aliases) }, // optional { "metadata", createOptions.Metadata } // optional }; _files.Insert(fileInfo, _settings.SafeMode); return(FindOneById(files_id)); } }
private void SaveChunk() { var lastChunkIndex = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize - 1; if (_chunkIndex == -1 || _chunkIndex > lastChunkIndex) { var message = string.Format("Invalid chunk index {0}.", _chunkIndex); throw new MongoGridFSException(message); } var lastChunkSize = (int)(_length % _fileInfo.ChunkSize); if (lastChunkSize == 0) { lastChunkSize = _fileInfo.ChunkSize; } BsonBinaryData data; if (_chunkIndex < lastChunkIndex || lastChunkSize == _fileInfo.ChunkSize) { data = new BsonBinaryData(_chunk); } else { var lastChunk = new byte[lastChunkSize]; Buffer.BlockCopy(_chunk, 0, lastChunk, 0, lastChunkSize); data = new BsonBinaryData(lastChunk); } var query = Query.EQ("_id", _chunkId); var update = new UpdateDocument { { "_id", _chunkId }, { "files_id", _fileInfo.Id }, { "n", (_chunkIndex < int.MaxValue) ? (BsonValue)BsonInt32.Create((int)_chunkIndex) : BsonInt64.Create(_chunkIndex) }, { "data", data } }; _gridFS.Chunks.Update(query, update, UpdateFlags.Upsert); _chunkIsDirty = false; }
// private methods private void AddMissingChunks() { var query = Query.EQ("files_id", _fileInfo.Id); var fields = Fields.Include("n"); var chunkCount = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize; var chunksFound = new HashSet <long>(); var foundExtraChunks = false; foreach (var chunk in _gridFS.Chunks.Find(query).SetFields(fields)) { var n = chunk["n"].ToInt64(); chunksFound.Add(n); if (n >= chunkCount) { foundExtraChunks = true; } } if (foundExtraChunks) { var extraChunksQuery = Query.And(Query.EQ("files_id", _fileInfo.Id), Query.GTE("n", chunkCount)); _gridFS.Chunks.Remove(extraChunksQuery); } BsonBinaryData zeros = null; // delay creating it until it's actually needed for (var n = 0L; n < chunkCount; n++) { if (!chunksFound.Contains(n)) { if (zeros == null) { zeros = new BsonBinaryData(new byte[_fileInfo.ChunkSize]); } var missingChunk = new BsonDocument { { "_id", ObjectId.GenerateNewId() }, { "files_id", _fileInfo.Id }, { "n", (n < int.MaxValue) ? (BsonValue)BsonInt32.Create((int)n) : BsonInt64.Create(n) }, { "data", zeros } }; _gridFS.Chunks.Insert(missingChunk); } } }
/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue DateTime(object value) { return(BsonInt64.Create(((DateTime)value).Ticks)); }
/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue Long(object value) { return(BsonInt64.Create((long)value)); }