/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue NullableInt(object value) { int?val = (int?)value; if (val == null) { return(BsonNull.Value); } return(BsonInt32.Create(val)); }
private static void WriteInt(SqlDataReader dr, int index, BsonDocument document) { if (dr.GetValue(index) != DBNull.Value) { BsonInt32 bsonInt32 = BsonInt32.Create(dr.GetValue(index)); document.Add(dr.GetName(index), bsonInt32); } else { document.Add(dr.GetName(index), BsonNull.Value); } }
private static void WriteInt(PropertyInfo property, object o, BsonDocument document) { if (property.GetValue(o, null) != null) { BsonInt32 bsonInt = BsonInt32.Create(property.GetValue(o, null)); document.Add(property.Name, bsonInt); } else { document.Add(property.Name, BsonNull.Value); } }
/// <summary> /// 将数据放入TreeNode里进行展示 /// </summary> /// <param name="treeNode"></param> /// <param name="doc"></param> public static void AddBsonDocToTreeNode(TreeNode treeNode, BsonDocument doc) { foreach (var item in doc.Elements) { if (item.Value.IsBsonDocument) { var newItem = new TreeNode(item.Name); AddBsonDocToTreeNode(newItem, item.Value.ToBsonDocument()); newItem.Tag = item; treeNode.Nodes.Add(newItem); } else { if (item.Value.IsBsonArray) { //虽然TreeNode的Text属性带有Array_Mark,表示的时候则会屏蔽掉, //必须要加上,不然FullPath会出现错误 var newItem = new TreeNode(item.Name + ConstMgr.ArrayMark); AddBsonArrayToTreeNode(item.Name, newItem, item.Value.AsBsonArray); newItem.Tag = item; treeNode.Nodes.Add(newItem); } else { var elementNode = new TreeNode(item.Name); elementNode.Tag = item; treeNode.Nodes.Add(elementNode); if (item.Value.IsObjectId) { //objId的展开 ObjectId oid = item.Value.AsObjectId; var oidCreateTime = new TreeNode("CreationTime"); oidCreateTime.Tag = BsonDateTime.Create(oid.CreationTime); var oidMachine = new TreeNode("Machine"); oidMachine.Tag = BsonInt32.Create(oid.Machine); var oidPid = new TreeNode("Pid"); oidPid.Tag = BsonInt32.Create(oid.Pid); var oidIncrement = new TreeNode("Increment"); oidIncrement.Tag = BsonInt32.Create(oid.Increment); var oidTimestamp = new TreeNode("Timestamp"); oidTimestamp.Tag = BsonInt32.Create(oid.Timestamp); elementNode.Nodes.Add(oidCreateTime); elementNode.Nodes.Add(oidMachine); elementNode.Nodes.Add(oidPid); elementNode.Nodes.Add(oidIncrement); elementNode.Nodes.Add(oidTimestamp); } } } } }
public void TestSetDocumentIdBsonValue() { var document = new BsonDocument { { "x", "abc" } }; var id = BsonInt32.Create(1); #pragma warning disable 618 // SetDocumentId is obsolete document.SetDocumentId(id); #pragma warning restore Assert.IsTrue(document["_id"].IsInt32); Assert.AreEqual(1, document["_id"].AsInt32); }
public void unesiVijest(Result newArticle) { var collection = _database.GetCollection <BsonDocument>("articles"); var id = (int)collection.Count(new BsonDocument()); var vijest = new BsonDocument { { "_id", BsonInt32.Create(id + 1) }, { "headline", BsonString.Create(newArticle.headline) }, { "text", BsonString.Create(newArticle.text) }, { "author", BsonString.Create(newArticle.author) }, { "comment", new BsonArray() }, { "picture", new BsonBinaryData(newArticle.picture) } }; collection.InsertOneAsync(vijest); }
public void TestBsonDocumentWithBsonInt32Id() { _collection.RemoveAll(); var doc = new BsonDocument { { "_id", BsonInt32.Create(0) }, { "X", 1 } }; _collection.Insert(doc); doc = new BsonDocument { { "_id", BsonInt32.Create(1) }, { "X", 1 } }; _collection.Insert(doc); }
private BsonValue GetValue(object value) { if (value is DBNull || value == null) { return(BsonNull.Value); } else if (value is string) { return(BsonString.Create(value)); } else if (value is bool) { return(BsonBoolean.Create(value)); } else if (value is int || value is short || value is byte) { return(BsonInt32.Create(value)); } else if (value is long) { return(BsonInt64.Create(value)); } else if (value is decimal) { return(BsonDecimal128.Create(value)); } else if (value is double || value is float) { return(BsonDouble.Create(value)); } else if (value is DateTime) { return(BsonDateTime.Create(value)); } else if (value is char c) { return(BsonString.Create("" + c)); } else if (value is byte[]) { return(BsonBinaryData.Create(value)); } else { return(BsonString.Create(value.ToString())); } }
public JsonResult Load(string ID, int version = -1) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The scene is not existed!" })); } var collectionName = doc["CollectionName"].AsString; List <BsonDocument> docs; if (version == -1) // 最新版本 { docs = mongo.FindAll(collectionName).ToList(); } else // 特定版本 { filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version)); docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList(); } var data = new JArray(); foreach (var i in docs) { i["_id"] = i["_id"].ToString(); // ObjectId data.Add(JsonHelper.ToObject <JObject>(i.ToJson())); } return(Json(new { Code = 200, Msg = "Get Successfully!", Data = data })); }
public void Add(QueryResult article) { var collection = database.GetCollection <BsonDocument>("articles"); var Id = (int)collection.Count(new BsonDocument()); var news = new BsonDocument { { "_id", BsonInt32.Create(Id + 1) }, { "headline", BsonString.Create(article.Headline) }, { "body", BsonString.Create(article.Body) }, { "author", BsonString.Create(article.Author) }, { "comments", new BsonArray() }, { "image", new BsonBinaryData(article.Image) } }; collection.InsertOne(news); }
// 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); } } }
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 TestOpenCreateWithId() { gridFS.Files.RemoveAll(); gridFS.Chunks.RemoveAll(); gridFS.Chunks.ResetIndexCache(); var createOptions = new MongoGridFSCreateOptions { Id = 1 }; using (var stream = gridFS.Create("test", createOptions)) { var bytes = new byte[] { 1, 2, 3, 4 }; stream.Write(bytes, 0, 4); } var fileInfo = gridFS.FindOne("test"); Assert.AreEqual(BsonInt32.Create(1), fileInfo.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; }
public void TestClassWithBsonInt32Id() { _collection.RemoveAll(); var doc = new ClassWithBsonInt32Id { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonInt32Id { Id = BsonInt32.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonInt32Id { Id = BsonInt32.Create(1), X = 1 }; _collection.Insert(doc); }
// 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(BsonInt32)); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { return(BsonInt32.Create((int)Int32Serializer.Instance.Deserialize(bsonReader, typeof(int), options))); } }
public void TestBsonInt32() { var value = BsonInt32.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 void TestExtraElementsOfAllTypes() { var json = "{ '_id' : 1, 'A' : 2, 'B' : 3, #X }"; var extraElements = new string[][] { new string[] { "XArray", "[1, 2.0]" }, new string[] { "XBinary", "HexData(2, '1234')" }, new string[] { "XBoolean", "true" }, new string[] { "XByteArray", "HexData(0, '1234')" }, new string[] { "XDateTime", "ISODate('2012-03-16T11:19:00Z')" }, new string[] { "XDocument", "{ 'a' : 1 }" }, new string[] { "XDouble", "1.0" }, new string[] { "XGuidLegacy", "HexData(3, '33221100554477668899aabbccddeeff')" }, new string[] { "XGuidStandard", "HexData(4, '00112233445566778899aabbccddeeff')" }, new string[] { "XInt32", "1" }, new string[] { "XInt64", "NumberLong(1)" }, new string[] { "XJavaScript", "{ '$code' : 'abc' }" }, new string[] { "XJavaScriptWithScope", "{ '$code' : 'abc', '$scope' : { 'x' : 1 } }" }, new string[] { "XMaxKey", "{ '$maxkey' : 1 }" }, new string[] { "XMinKey", "{ '$minkey' : 1 }" }, new string[] { "XNull", "null" }, new string[] { "XObjectId", "ObjectId('00112233445566778899aabb')" }, new string[] { "XRegularExpression", "/abc/" }, new string[] { "XString", "'abc'" }, new string[] { "XSymbol", "{ '$symbol' : 'abc' }" }, new string[] { "XTimestamp", "{ '$timestamp' : NumberLong(1234) }" }, new string[] { "XUndefined", "undefined" }, }; var extraElementsRepresentation = string.Join(", ", extraElements.Select(e => string.Format("'{0}' : {1}", e[0], e[1])).ToArray()); json = json.Replace("#X", extraElementsRepresentation).Replace("'", "\""); var c = BsonSerializer.Deserialize <C>(json); // round trip it both ways before checking individual values json = c.ToJson(); c = BsonSerializer.Deserialize <C>(json); Assert.IsInstanceOf <List <object> >(c.X["XArray"]); Assert.IsInstanceOf <BsonBinaryData>(c.X["XBinary"]); Assert.IsInstanceOf <bool>(c.X["XBoolean"]); Assert.IsInstanceOf <byte[]>(c.X["XByteArray"]); Assert.IsInstanceOf <DateTime>(c.X["XDateTime"]); Assert.IsInstanceOf <Dictionary <string, object> >(c.X["XDocument"]); Assert.IsInstanceOf <double>(c.X["XDouble"]); Assert.IsInstanceOf <Guid>(c.X["XGuidLegacy"]); Assert.IsInstanceOf <Guid>(c.X["XGuidStandard"]); Assert.IsInstanceOf <int>(c.X["XInt32"]); Assert.IsInstanceOf <long>(c.X["XInt64"]); Assert.IsInstanceOf <BsonJavaScript>(c.X["XJavaScript"]); Assert.IsInstanceOf <BsonJavaScriptWithScope>(c.X["XJavaScriptWithScope"]); Assert.IsInstanceOf <BsonMaxKey>(c.X["XMaxKey"]); Assert.IsInstanceOf <BsonMinKey>(c.X["XMinKey"]); Assert.IsNull(c.X["XNull"]); Assert.IsInstanceOf <ObjectId>(c.X["XObjectId"]); Assert.IsInstanceOf <BsonRegularExpression>(c.X["XRegularExpression"]); Assert.IsInstanceOf <string>(c.X["XString"]); Assert.IsInstanceOf <BsonSymbol>(c.X["XSymbol"]); Assert.IsInstanceOf <BsonTimestamp>(c.X["XTimestamp"]); Assert.IsInstanceOf <BsonUndefined>(c.X["XUndefined"]); Assert.AreEqual(22, c.X.Count); Assert.IsTrue(new object[] { 1, 2.0 }.SequenceEqual((List <object>)c.X["XArray"])); #pragma warning disable 618 // OldBinary is obsolete Assert.AreEqual(BsonBinarySubType.OldBinary, ((BsonBinaryData)c.X["XBinary"]).SubType); #pragma warning restore 618 Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual(((BsonBinaryData)c.X["XBinary"]).Bytes)); Assert.AreEqual(true, c.X["XBoolean"]); Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual((byte[])c.X["XByteArray"])); Assert.AreEqual(new DateTime(2012, 3, 16, 11, 19, 0, DateTimeKind.Utc), c.X["XDateTime"]); Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"]).Count); Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"])["a"]); Assert.AreEqual(1.0, c.X["XDouble"]); Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidLegacy"]); Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidStandard"]); Assert.AreEqual(1, c.X["XInt32"]); Assert.AreEqual(1L, c.X["XInt64"]); Assert.AreEqual("abc", ((BsonJavaScript)c.X["XJavaScript"]).Code); Assert.AreEqual("abc", ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Code); Assert.AreEqual(1, ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope.ElementCount); Assert.AreEqual(BsonInt32.Create(1), ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope["x"]); Assert.AreSame(BsonMaxKey.Value, c.X["XMaxKey"]); Assert.AreSame(BsonMinKey.Value, c.X["XMinKey"]); Assert.AreEqual(null, c.X["XNull"]); Assert.AreEqual(ObjectId.Parse("00112233445566778899aabb"), c.X["XObjectId"]); Assert.AreEqual(new BsonRegularExpression("abc"), c.X["XRegularExpression"]); Assert.AreEqual("abc", c.X["XString"]); Assert.AreSame(BsonSymbol.Create("abc"), c.X["XSymbol"]); Assert.AreEqual(BsonTimestamp.Create(1234), c.X["XTimestamp"]); Assert.AreSame(BsonUndefined.Value, c.X["XUndefined"]); }
/// <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)); } }
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); }
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 JsonResult Run(string ID, int version = -1) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The scene is not existed!" })); } // 获取场景数据 var collectionName = doc["CollectionName"].AsString; List <BsonDocument> docs; if (version == -1) // 最新版本 { docs = mongo.FindAll(collectionName).ToList(); } else // 特定版本 { filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version)); docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList(); } // 创建临时目录 var now = DateTime.Now; var path = HttpContext.Current.Server.MapPath($"~/temp/{now.ToString("yyyyMMddHHmmss")}"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // 拷贝静态资源 var viewPath = HttpContext.Current.Server.MapPath("~/view.html"); var viewFileData = File.ReadAllText(viewPath, Encoding.UTF8); viewFileData = viewFileData.Replace("location.origin", "'.'"); // 替换server地址,以便部署到Git Pages上 File.WriteAllText($"{path}/view.html", viewFileData, Encoding.UTF8); var faviconPath = HttpContext.Current.Server.MapPath("~/favicon.ico"); File.Copy(faviconPath, $"{path}/favicon.ico", true); var assetsPath = HttpContext.Current.Server.MapPath($"~/assets"); DirectoryHelper.Copy(assetsPath, $"{path}/assets"); var buildPath = HttpContext.Current.Server.MapPath($"~/build"); DirectoryHelper.Copy(buildPath, $"{path}/build"); // 分析场景,拷贝使用的资源 var data = new JArray(); var urls = new List <string>(); foreach (var i in docs) { i["_id"] = i["_id"].ToString(); // ObjectId var generator = i["metadata"]["generator"].ToString(); if (generator == "ServerObject") // 服务端模型 { urls.Add(i["userData"]["Url"].ToString()); // 模型文件 if (i["userData"].AsBsonDocument.Contains("Animation")) // MMD模型动画 { urls.Add(i["userData"]["Animation"]["Url"].ToString()); } if (i["userData"].AsBsonDocument.Contains("CameraAnimation")) // MMD相机动画 { urls.Add(i["userData"]["CameraAnimation"]["Url"].ToString()); } if (i["userData"].AsBsonDocument.Contains("Audio")) // MMD音频 { urls.Add(i["userData"]["Audio"]["Url"].ToString()); } } else if (generator == "SceneSerializer") // 场景 { if (i["background"].IsBsonDocument) // 贴图或立方体纹理 { if (i["background"]["metadata"]["generator"].ToString() == "CubeTextureSerializer") // 立方体纹理 { var array = i["background"]["image"].AsBsonArray; foreach (var j in array) { urls.Add(j["src"].ToString()); } } else // 普通纹理 { urls.Add(i["background"]["image"]["src"].ToString()); } } } else if (generator == "MeshSerializer" || generator == "SpriteSerializer") // 模型 { if (i["material"]["alphaMap"].IsBsonDocument) { urls.Add(i["material"]["alphaMap"]["image"]["src"].ToString()); } else if (i["material"]["aoMap"].IsBsonDocument) { urls.Add(i["material"]["aoMap"]["image"]["src"].ToString()); } else if (i["material"]["bumpMap"].IsBsonDocument) { urls.Add(i["material"]["bumpMap"]["image"]["src"].ToString()); } else if (i["material"]["displacementMap"].IsBsonDocument) { urls.Add(i["material"]["displacementMap"]["image"]["src"].ToString()); } else if (i["material"]["emissiveMap"].IsBsonDocument) { urls.Add(i["material"]["emissiveMap"]["image"]["src"].ToString()); } else if (i["material"]["envMap"].IsBsonDocument) { urls.Add(i["material"]["envMap"]["image"]["src"].ToString()); } else if (i["material"]["lightMap"].IsBsonDocument) { urls.Add(i["material"]["lightMap"]["image"]["src"].ToString()); } else if (i["material"]["map"].IsBsonDocument) { urls.Add(i["material"]["map"]["image"]["src"].ToString()); } else if (i["material"]["metalnessMap"].IsBsonDocument) { urls.Add(i["material"]["metalnessMap"]["image"]["src"].ToString()); } else if (i["material"]["normalMap"].IsBsonDocument) { urls.Add(i["material"]["normalMap"]["image"]["src"].ToString()); } else if (i["material"]["roughnessMap"].IsBsonDocument) { urls.Add(i["material"]["roughnessMap"]["image"]["src"].ToString()); } } data.Add(JsonHelper.ToObject <JObject>(i.ToJson())); } // 将场景写入文件 if (!Directory.Exists($"{path}/Scene")) { Directory.CreateDirectory($"{path}/Scene"); } // 复制资源 var file = new FileStream($"{path}/Scene/{ID}.txt", FileMode.Create, FileAccess.Write); var writer = new StreamWriter(file); writer.Write(JsonHelper.ToJson(data)); writer.Close(); file.Close(); foreach (var url in urls) { if (!url.StartsWith("/")) // 可能是base64地址 { continue; } // LOL模型存在多个url,两个url之间用分号分隔 var _urls = url.Split(';'); foreach (var _url in _urls) { if (string.IsNullOrEmpty(_url)) { continue; } var sourceDirName = Path.GetDirectoryName(HttpContext.Current.Server.MapPath($"~{_url}")); var targetDirName = Path.GetDirectoryName($"{path}{_url}"); DirectoryHelper.Copy(sourceDirName, targetDirName); } } return(Json(new { Code = 200, Msg = "Export successfully!", Url = $"/temp/{now.ToString("yyyyMMddHHmmss")}/view.html?sceneFile={ID}" })); }
/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue Int(object value) { return(BsonInt32.Create((int)value)); }
// public methods /// <inheritdoc/> public override BsonValue ToBsonValue() { return(BsonInt32.Create(_w)); }
private void SetAncestors(ContentItem item) { var ids = item.AncestralTrail.Split('/').Where(id => !string.IsNullOrEmpty(id)).Select(id => BsonInt32.Create(int.Parse(id))).ToList(); if (ids.Count == 0) { return; } var parents = database.GetCollection <ContentItem>().Find(Query.In("_id", ids)).OrderByDescending(p => p.AncestralTrail.Length).ToList(); for (int i = 1; i < parents.Count; i++) { parents[i - 1].Parent = parents[i]; } item.Parent = parents[0]; }