コード例 #1
1
ファイル: CSharp595Tests.cs プロジェクト: RavenZZ/MDRelation
        public void TestDoesNotThrowStackOverflowExceptionWhenConvertingToSelfType()
        {
            var id1 = new BsonObjectId(ObjectId.GenerateNewId());
            var id2 = (BsonObjectId)((IConvertible)id1).ToType(typeof(BsonObjectId), null);

            Assert.Equal(id1, id2);
        }
コード例 #2
0
ファイル: Client.cs プロジェクト: travisrussi/KissCaller
        public static Client FindOneByClientId(MongoDatabase mongoDb, BsonObjectId clientId)
        {
            if (mongoDb == null ||
                clientId == null)
            {
                return null;
            }

            if (mongoDb.Server == null)
                mongoDb = Helper.MongoDb.GetDatabase();

            Client client = null;

            try
            {
                var clientCol = mongoDb.GetCollection<Client>("Client");
                var clientQuery = Query.EQ("_id", clientId);
                client = clientCol.FindOne(clientQuery);
            }
            catch (Exception ex)
            {
                if (log.IsDebugEnabled) { log.Error("FindOneByClientId.Client." + (client == null ? "null" : client.ToJsonString()), ex); }

                throw ex;
                return null; // "Error: unable to Client.FindOneByClientId for " + ClientId;
            }

            if (log.IsDebugEnabled) { log.Debug("FindOneByClientId.Client." + (client == null ? "null" : client.ToJsonString())); }

            return client;
        }
コード例 #3
0
            public void BsonObjectId()
            {
                const string id = "52ddb25d606fdc049c7aaf7e";
                BsonObjectId bsonId = new BsonObjectId(new ObjectId(id));
                string expected = string.Format("{0}", bsonId.Value.Increment);

                Assert.AreEqual(expected, MongoDataAccessExtensions.GenerateDisplayId(id));
            }
コード例 #4
0
        public void TestDoesNotThrowStackOverflowExceptionWhenConvertingToBsonString()
        {
            BsonObjectId id1 = new BsonObjectId(ObjectId.GenerateNewId());
            BsonString id2 = null;
            Assert.DoesNotThrow(() =>
            {
                id2 = (BsonString)((IConvertible)id1).ToType(typeof(BsonString), null);
            });

            Assert.AreEqual(id1.ToString(), id2.AsString);
        }
コード例 #5
0
 public void TestCompareLargerIncrement()
 {
     var objectId1 = new BsonObjectId("0102030405060708090a0b0d");
     var objectId2 = new BsonObjectId("0102030405060708090a0b0c");
     Assert.IsFalse(objectId1 < objectId2);
     Assert.IsFalse(objectId1 <= objectId2);
     Assert.IsTrue(objectId1 != objectId2);
     Assert.IsFalse(objectId1 == objectId2);
     Assert.IsTrue(objectId1 > objectId2);
     Assert.IsTrue(objectId1 >= objectId2);
 }
コード例 #6
0
 public void TestByteArrayConstructor()
 {
     byte[] bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
     var objectId = new BsonObjectId(bytes);
     Assert.AreEqual(0x01020304, objectId.Timestamp);
     Assert.AreEqual(0x050607, objectId.Machine);
     Assert.AreEqual(0x0809, objectId.Pid);
     Assert.AreEqual(0x0a0b0c, objectId.Increment);
     Assert.AreEqual(0x05060708090a0b0c, objectId.MachinePidIncrement);
     Assert.AreEqual(Bson.UnixEpoch.AddSeconds(0x01020304), objectId.CreationTime);
     Assert.AreEqual("0102030405060708090a0b0c", objectId.ToString());
     Assert.IsTrue(bytes.SequenceEqual(objectId.ToByteArray()));
 }
コード例 #7
0
        /// <summary>
        /// Generates a display ID for an application ID <paramref name="applicationId"/>.
        /// This is a human-readable, shortened version of the application ID,
        /// used for easy reference.
        /// </summary>
        /// <param name="applicationId">The application identifier.</param>
        /// <returns>A human-readable version of the application ID <paramref name="applicationId"/>.</returns>
        public static string GenerateDisplayId(string applicationId)
        {
            if (string.IsNullOrEmpty(applicationId))
            {
                return null;
            }

            if (applicationId.Length != 24)
            {
                return applicationId;
            }

            BsonObjectId bsonId = new BsonObjectId(new ObjectId(applicationId));
            return string.Format("{0}", bsonId.Value.Increment);
        }
コード例 #8
0
        public void TestIntIntShortIntConstructor()
        {
#pragma warning disable 618
            byte[] bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            var objectId = new BsonObjectId(0x01020304, 0x050607, 0x0809, 0x0a0b0c);
            Assert.AreEqual(0x01020304, objectId.Timestamp);
            Assert.AreEqual(0x050607, objectId.Machine);
            Assert.AreEqual(0x0809, objectId.Pid);
            Assert.AreEqual(0x0a0b0c, objectId.Increment);
            Assert.AreEqual(0x050607, objectId.Machine);
            Assert.AreEqual(0x0809, objectId.Pid);
            Assert.AreEqual(0x0a0b0c, objectId.Increment);
            Assert.AreEqual(BsonConstants.UnixEpoch.AddSeconds(0x01020304), objectId.CreationTime);
            Assert.AreEqual("0102030405060708090a0b0c", objectId.ToString());
            Assert.IsTrue(bytes.SequenceEqual(objectId.ToByteArray()));
#pragma warning restore
        }
コード例 #9
0
        public void TestConvertMultipleToObjectViaJson()
        {
            BsonDocument person1 = new BsonDocument();
            BsonDocument person2 = new BsonDocument();
            List<BsonDocument> people = new List<BsonDocument>();

            const string id1 = "51ca5da43d1b18cc15000000";
            const string name1 = "Luke Skywalker";
            const string gender1 = "Male";
            DateTime dateOfBirth1 = new DateTime(1977, 5, 25);

            person1["_id"] = new BsonObjectId(new ObjectId(id1));
            person1["Name"] = new BsonString(name1);
            person1["Gender"] = new BsonString(gender1);
            person1["DateOfBirth"] = new BsonDateTime(dateOfBirth1);
            people.Add(person1);

            const string id2 = "52cb5da43d1f17cc15000000";
            const string name2 = "Princess Leia";
            const string gender2 = "Female";
            DateTime dateOfBirth2 = new DateTime(1973, 5, 25);

            person2["_id"] = new BsonObjectId(new ObjectId(id2));
            person2["Name"] = new BsonString(name2);
            person2["Gender"] = new BsonString(gender2);
            person2["DateOfBirth"] = new BsonDateTime(dateOfBirth2);
            people.Add(person2);

            List<Person> personList = BsonConverter.ConvertToObjectViaJson<List<Person>>(people);
            for (var i = 0; i < personList.Count; i++)
            {
                var person = personList[i];
                var personToUse = i == 0 ? person1 : person2;
                Assert.AreEqual(person.Id, personToUse["_id"].ToString());
                Assert.AreEqual(person.Name, personToUse["Name"]);
                Assert.AreEqual(person.Gender, personToUse["Gender"]);
                Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), personToUse["DateOfBirth"].ToUniversalTime());
                Assert.IsNull(person.DateOfDeath);
            }
        }
コード例 #10
0
 public void DeleteById(BsonObjectId objectId)
 {
     entities.Remove(entities.FirstOrDefault(w => w.Id == objectId));
 }
コード例 #11
0
 public void TestMapBsonObjectId()
 {
     var value = new BsonObjectId(ObjectId.GenerateNewId());
     var bsonValue = (BsonObjectId)BsonTypeMapper.MapToBsonValue(value);
     Assert.Same(value, bsonValue);
     var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(value, BsonType.ObjectId);
     Assert.Same(value, bsonObjectId);
 }
コード例 #12
0
ファイル: MongoObjectId.cs プロジェクト: Lietuva2/LT2
 public int CompareTo(MongoObjectId other)
 {
     return(BsonObjectId.CompareTo(other.BsonObjectId));
 }
コード例 #13
0
ファイル: MongoObjectId.cs プロジェクト: Lietuva2/LT2
 public override bool Equals(object obj)
 {
     return(BsonObjectId.Equals(obj));
 }
コード例 #14
0
ファイル: CRUDService.cs プロジェクト: okusnadi/RawCMS
        public JObject Get(string collection, string id)
        {
            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id));

            IFindFluent <BsonDocument, BsonDocument> results = _mongoService
                                                               .GetCollection <BsonDocument>(collection)
                                                               .Find <BsonDocument>(filter);

            List <BsonDocument> list = results.ToList();

            BsonDocument item = list.FirstOrDefault();
            string       json = "{}";

            //sanitize id format
            if (item != null)
            {
                item["_id"] = item["_id"].ToString();
                json        = item.ToJson(js);
            }

            return(JObject.Parse(json));
        }
コード例 #15
0
ファイル: ToDoComment.cs プロジェクト: Lietuva2/LT2
 public ToDoComment()
 {
     Id          = BsonObjectId.GenerateNewId();
     IsPrivate   = false;
     Attachments = new List <Website>();
 }
コード例 #16
0
 public DefaultSessionStateData()
 {
     Id = BsonObjectId.GenerateNewId();
 }
コード例 #17
0
ファイル: CompareResults.cs プロジェクト: joeynovak/webdiff
 public CompareResults(Session originalSession, Session newSession)
 {
     OriginalSessionId = originalSession._id;
     NewSessionId      = newSession._id;
 }
コード例 #18
0
        // 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);
            }
        }
コード例 #19
0
        public async Task <IEnumerable <PlayerProgress> > Lookup(PlayerProgressLookup lookup)
        {
            Game    game    = null;
            Profile profile = null;

            var searchRequest = new BsonDocument
            {
            };

            if (lookup.objectId != null)
            {
                searchRequest["_id"] = new BsonObjectId(new ObjectId(lookup.objectId));
            }
            else
            {
                profile = (await profileRepository.Lookup(lookup.profileLookup)).FirstOrDefault();
                game    = (await gameRepository.Lookup(lookup.gameLookup)).FirstOrDefault();
                searchRequest["gameid"]    = game.Id;
                searchRequest["profileid"] = profile.Id;

                if (lookup.pageKey != null)
                {
                    searchRequest["pageKey"] = lookup.pageKey;
                }
            }
            var return_value = new List <PlayerProgress>();
            var results      = (await collection.FindAsync(searchRequest)).ToList();

            foreach (var result in results)
            {
                var progress = new PlayerProgress();

                if (!result["profileid"].IsBsonNull && result["profileid"].AsInt32 != 0)
                {
                    var profileLookup = new ProfileLookup();
                    profileLookup.id = result["profileid"].AsInt32;
                    profile          = (await profileRepository.Lookup(profileLookup)).FirstOrDefault();
                }
                else
                {
                    profile = null;
                }

                if (!result["gameid"].IsBsonNull || result["gameid"].AsInt32 != 0)
                {
                    var gameLookup = new GameLookup();
                    gameLookup.id = result["gameid"].AsInt32;
                    game          = (await gameRepository.Lookup(gameLookup)).FirstOrDefault();
                }
                else
                {
                    game = null;
                }

                progress.game    = game;
                progress.profile = profile;
                progress.data    = Newtonsoft.Json.JsonConvert.DeserializeObject(result.GetValue("data").ToJson()); //stupid fix for weird bson deserialization

                if (result.Contains("modified"))
                {
                    progress.modified = (decimal)result["modified"].AsDouble;
                }
                return_value.Add(progress);
            }
            return(return_value);
        }
コード例 #20
0
ファイル: CRUDService.cs プロジェクト: zeppaman/RawCMS
        public JObject Get(string collection, string id, List <string> expando = null)
        {
            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id));

            JObject nullValue   = new JObject();
            var     dataContext = new Dictionary <string, object>();

            dataContext["expando"] = expando ?? new List <string>();

            InvokeProcess(collection, ref nullValue, PipelineStage.PreOperation, DataOperation.Read, dataContext);

            IFindFluent <BsonDocument, BsonDocument> results = _mongoService
                                                               .GetCollection <BsonDocument>(collection)
                                                               .Find <BsonDocument>(filter);

            List <BsonDocument> list = results.ToList();

            var    item = list.FirstOrDefault();
            string json = "{}";

            //sanitize id format
            if (item != null)
            {
                item["_id"] = item["_id"].ToString();
                json        = item.ToJson(js);
            }

            var output = JObject.Parse(json);

            InvokeProcess(collection, ref output, PipelineStage.PostOperation, DataOperation.Read, dataContext);
            return(output);
        }
コード例 #21
0
ファイル: CRUDService.cs プロジェクト: zeppaman/RawCMS
        public bool Delete(string collection, string id)
        {
            EnsureCollection(collection);

            var old         = Get(collection, id);
            var dataContext = new Dictionary <string, object>();

            InvokeProcess(collection, ref old, PipelineStage.PreOperation, DataOperation.Delete, dataContext);

            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id));

            DeleteResult result = _mongoService.GetCollection <BsonDocument>(collection).DeleteOne(filter);

            InvokeProcess(collection, ref old, PipelineStage.PostOperation, DataOperation.Delete, dataContext);

            return(result.DeletedCount == 1);
        }
コード例 #22
0
ファイル: CRUDService.cs プロジェクト: zeppaman/RawCMS
        public JObject Update(string collection, JObject item, bool replace)
        {
            var dataContext = new Dictionary <string, object>();

            var id          = item["_id"].Value <string>();
            var itemToCheck = item;

            if (replace == false)
            {
                itemToCheck = Get(collection, id);
                itemToCheck.Merge(item, new JsonMergeSettings()
                {
                    MergeNullValueHandling = MergeNullValueHandling.Merge,
                    MergeArrayHandling     = MergeArrayHandling.Replace
                });
            }
            InvokeValidation(itemToCheck, collection);

            //TODO: create collection if not exists
            EnsureCollection(collection);

            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(item["_id"].Value <string>()));

            InvokeProcess(collection, ref item, PipelineStage.PreOperation, DataOperation.Write, dataContext);

            //insert id (mandatory)
            BsonDocument doc = BsonDocument.Parse(item.ToString());

            doc["_id"] = BsonObjectId.Create(id);
            doc.Remove("_metadata");

            UpdateOptions o = new UpdateOptions()
            {
                IsUpsert = true,
                BypassDocumentValidation = true
            };

            if (replace)
            {
                _mongoService.GetCollection <BsonDocument>(collection).ReplaceOne(filter, doc, o);
            }
            else
            {
                BsonDocument dbset = new BsonDocument("$set", doc);
                _mongoService.GetCollection <BsonDocument>(collection).UpdateOne(filter, dbset, o);
            }
            var fullSaved = Get(collection, id);

            InvokeProcess(collection, ref fullSaved, PipelineStage.PostOperation, DataOperation.Write, dataContext);
            return(fullSaved);
        }
コード例 #23
0
        public void TestBulkWriteCountsWithUpsert()
        {
            using (_server.RequestStart(null, ReadPreference.Primary))
            {
                var serverInstance = _server.RequestConnection.ServerInstance;

                _collection.Drop();
                var id = new BsonObjectId(ObjectId.GenerateNewId());
                var result = _collection.BulkWrite(
                    new BulkWriteArgs { IsOrdered = true, WriteConcern = WriteConcern.Acknowledged },
                    new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 2)) { IsUpsert = true },
                    new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 2)) { IsUpsert = true },
                    new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 3)));

                var expectedModifiedCount = 1;
                if (serverInstance.BuildInfo.Version < new Version(2, 5, 5))
                {
                    expectedModifiedCount = 2;
                }

                Assert.AreEqual(0, result.DeletedCount);
                Assert.AreEqual(0, result.InsertedCount);
                Assert.AreEqual(expectedModifiedCount, result.ModifiedCount);
                Assert.AreEqual(3, result.RequestCount);
                Assert.AreEqual(2, result.UpdatedCount);
                Assert.AreEqual(1, result.Upserts.Count);
                Assert.AreEqual(0, result.Upserts.First().Index);
                Assert.AreEqual(id, result.Upserts.First().Id);
            }
        }
コード例 #24
0
ファイル: Star.cs プロジェクト: Panza/JsonSandbox
 internal static Star Find(BsonObjectId id)
 {
     return Server.RunOperation<Star>((db) =>
     {
         MongoCollection<BsonDocument> table = db.GetCollection(TableName);
         return table.FindOneAs<Star>(Query.EQ("_id", id));
     });
 }
コード例 #25
0
        public void TestConvertToObjectViaJson()
        {
            const string id = "51ca5da43d1b18cc15000000";
            const string name = "Luke Skywalker";
            const string gender = "Male";
            DateTime dateOfBirth = new DateTime(1977, 5, 25);

            BsonDocument document = new BsonDocument();
            document["_id"] = new BsonObjectId(new ObjectId(id));
            document["Name"] = new BsonString(name);
            document["Gender"] = new BsonString(gender);
            document["DateOfBirth"] = new BsonDateTime(dateOfBirth);
            ////document["DateOfDeath"] = Deliberately excluded

            Person person = BsonConverter.ConvertToObjectViaJson<Person>(document);
            Assert.AreEqual(person.Id, id);
            Assert.AreEqual(person.Name, name);
            Assert.AreEqual(person.Gender, gender);
            Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), dateOfBirth.ToUniversalTime());
            Assert.IsNull(person.DateOfDeath);
        }
コード例 #26
0
 public MileStone()
 {
     Id    = BsonObjectId.GenerateNewId();
     ToDos = new List <ToDo>();
 }
コード例 #27
0
ファイル: CRUDService.cs プロジェクト: okusnadi/RawCMS
        public bool Delete(string collection, string id)
        {
            EnsureCollection(collection);

            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id));

            DeleteResult result = _mongoService.GetCollection <BsonDocument>(collection).DeleteOne(filter);

            return(result.DeletedCount == 1);
        }
コード例 #28
0
        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上
            viewFileData = viewFileData.Replace("<%SceneID%>", ID);        // 发布场景自动把`<%SceneID%>`替换成真实场景ID,不再需要加`SceneID`或`SceneFile`参数
            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"].IsBsonArray)
                    {
                        foreach (BsonDocument material in i["material"].AsBsonArray)
                        {
                            GetUrlInMaterial(material, urls);
                        }
                    }
                    else if (i["material"].IsBsonDocument)
                    {
                        GetUrlInMaterial(i["material"].AsBsonDocument, urls);
                    }
                }
                else if (generator == "AudioSerializer")
                {
                    urls.Add(i["userData"]["Url"].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}"
            }));
        }
コード例 #29
0
 public TestClass(
     BsonObjectId value
 )
 {
     this.B = value;
     this.V = value;
 }
コード例 #30
0
ファイル: Link.cs プロジェクト: Panza/JsonSandbox
 public Link(BsonObjectId a, BsonObjectId b)
 {
     this.a = a;
     this.b = b;
 }
コード例 #31
0
ファイル: MongoObjectId.cs プロジェクト: Lietuva2/LT2
 public MongoObjectId(BsonObjectId sb)
 {
     BsonObjectId = sb;
 }
コード例 #32
0
 public void RemoveById(BsonObjectId userId)
 {
     users.Remove(Query.EQ("_id", userId));
 }
コード例 #33
0
ファイル: MongoObjectId.cs プロジェクト: Lietuva2/LT2
 public bool Equals(MongoObjectId other)
 {
     return(BsonObjectId.Equals(other.BsonObjectId));
 }
コード例 #34
0
 public void DeserializeProperty(
     BsonReader bsonReader,
     object obj,
     BsonPropertyMap propertyMap
 )
 {
     var bsonType = bsonReader.PeekBsonType();
     BsonObjectId value;
     if (bsonType == BsonType.Null) {
         bsonReader.ReadNull(propertyMap.ElementName);
         value = null;
     } else {
         int timestamp;
         long machinePidIncrement;
         bsonReader.ReadObjectId(propertyMap.ElementName, out timestamp, out machinePidIncrement);
         value = new BsonObjectId(timestamp, machinePidIncrement);
     }
     propertyMap.Setter(obj, value);
 }
コード例 #35
0
ファイル: PhoneNumber.cs プロジェクト: Lietuva2/LT2
 public PhoneNumber()
 {
     Id = BsonObjectId.GenerateNewId();
 }
コード例 #36
0
        public void SetDB(IOptions <MongoSettings> settings)
        {
            var          connectionUri    = settings.Value.connectionUri;
            var          connectionPort   = settings.Value.connectionPort;
            var          connectionString = "mongodb://" + connectionUri + ":" + connectionPort;
            IMongoClient client           = new MongoClient(connectionString);

            _database   = client.GetDatabase(settings.Value.mongoDataBase);
            _collection = _database.GetCollection <BsonDocument>("players");

            this.Client = client;
            var idForFindId     = new ObjectId("5a6f1b9b096a8a01c86f4c91");
            var idForFindIdBson = new BsonObjectId(idForFindId);

            _dummyPlayers = new List <BsonDocument>()
            {
                new BsonDocument {
                    { "_id", idForFindIdBson },
                    { "name", "Lorem Ipsum" },
                    { "wins", "100" },
                    { "losses", "12" }
                },

                new BsonDocument {
                    { "name", "Dolor Sit" },
                    { "wins", "99" },
                    { "losses", "1" },
                },
                new BsonDocument {
                    { "name", "consectetur adipiscing" },
                    { "wins", "68" },
                    { "losses", "1000" },
                },
                new BsonDocument {
                    { "name", "elit. Duis" },
                    { "wins", "56" },
                    { "losses", "10" },
                },

                new BsonDocument {
                    { "name", "sodales arcu" },
                    { "wins", "50" },
                    { "losses", "0" },
                },
                new BsonDocument {
                    { "name", "sed justo" },
                    { "wins", "48" },
                    { "losses", "20" },
                },
                new BsonDocument {
                    { "name", "porta, ut" },
                    { "wins", "45" },
                    { "losses", "90" },
                },
                new BsonDocument {
                    { "name", "bibendum augue" },
                    { "wins", "44" },
                    { "losses", "9" },
                },
                new BsonDocument {
                    { "name", "vestibulum. Nam" },
                    { "wins", "41" },
                    { "losses", "4" },
                },
                new BsonDocument {
                    { "name", "cursus convallis" },
                    { "wins", "40" },
                    { "losses", "40" },
                },
                new BsonDocument {
                    { "name", "lectus, id" },
                    { "wins", "32" },
                    { "losses", "1" },
                }
            };
        }
コード例 #37
0
 public User GetById(BsonObjectId id)
 {
     return users.FindOneById(id);
 }
コード例 #38
0
 // public methods
 /// <summary>
 /// Generates an Id for a document.
 /// </summary>
 /// <param name="container">The container of the document (will be a MongoCollection when called from the C# driver). </param>
 /// <param name="document">The document.</param>
 /// <returns>An Id.</returns>
 public object GenerateId(object container, object document)
 {
     return(BsonObjectId.GenerateNewId());
 }
コード例 #39
0
        public async Task Post(Comment comment)
        {
            try {
                BsonObjectId oldId = new BsonObjectId(new ObjectId(comment.id.ToString()));
                var temp = oldId.GetType();
                temp.GetType();
                var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
                var mongoDbServer = mongoDbClient.GetDatabase("nmbp");
                var collection = mongoDbServer.GetCollection<PostInfo>("post");

                var filter = Builders<PostInfo>.Filter.Eq("_id", oldId);
                var update = Builders<PostInfo>.Update.Push("post_comments", comment.comment);
                await collection.FindOneAndUpdateAsync(filter, update);
                var test = oldId.GetType();
            }
            catch
            {
                var yolo = "you only live once";
                yolo.GetType();
            }
        }
コード例 #40
0
 public void Write_Type_Name_Value(ReadOnlySpan <byte> name, BsonObjectId value)
 {
     WriteByte(7);
     WriteCString(name);
     WriteObjectId(value);
 }
コード例 #41
0
ファイル: DataModel.cs プロジェクト: IDWMaster/iDunno
 public async Task<UserInformation> GetUserById(BsonObjectId id)
 {
     return (await db.GetCollection<UserInformation>("users").Find(Builders<UserInformation>.Filter.Eq(m => m.Id, id)).ToListAsync()).First();
 }
コード例 #42
0
 public T Get(BsonObjectId id)
 {
     return(entities.Find(e => e.Id == id).FirstOrDefault());
 }
コード例 #43
0
        public void TestUpsertInsert()
        {
            _collection.Drop();
            var id = new BsonObjectId(ObjectId.GenerateNewId());
            var result = _collection.Update(Query.EQ("_id", id), Update.Set("x", 2), UpdateFlags.Upsert);

            Assert.AreEqual(true, result.Ok);
            Assert.AreEqual(null, result.Code);
            Assert.AreEqual(null, result.LastErrorMessage);
            Assert.AreEqual(1, result.DocumentsAffected);
            Assert.AreEqual(false, result.UpdatedExisting);
            Assert.AreEqual(id, result.Upserted);

            var document = _collection.FindOne();
            Assert.AreEqual(2, document["x"].AsInt32);
            Assert.AreEqual(1, _collection.Count());
        }
コード例 #44
0
 public void Update(BsonObjectId id, T entity)
 {
     entities.ReplaceOne(e => e.Id == id, entity);
 }
コード例 #45
0
 public User getUserById(string id)
 {
     // Get an Oid from the ID string
     var oid = new BsonObjectId( new ObjectId(id));
     // Create a document with the ID we want to find
     var queryDoc = new QueryDocument { { "_id", oid } };
     // Query the db for a document with the required ID
     var user2 = mdb.GetCollection("userDatas").FindOne(queryDoc);
     var profileDic = getAllProfilesDictionary();
     User wuser = mapMongoUser(user2, profileDic);
     return wuser;
 }
        // 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);
            }
        }
コード例 #47
0
 public void TestCompareSmallerTimestamp()
 {
     var objectId1 = new BsonObjectId("0102030405060708090a0b0c");
     var objectId2 = new BsonObjectId("0102030505060708090a0b0c");
     Assert.IsTrue(objectId1 < objectId2);
     Assert.IsTrue(objectId1 <= objectId2);
     Assert.IsTrue(objectId1 != objectId2);
     Assert.IsFalse(objectId1 == objectId2);
     Assert.IsFalse(objectId1 > objectId2);
     Assert.IsFalse(objectId1 >= objectId2);
 }
コード例 #48
0
        public void TestUpsertInsert()
        {
            _collection.Drop();
            var id = new BsonObjectId(ObjectId.GenerateNewId());
            var result = _collection.Update(Query.EQ("_id", id), Update.Set("x", 2), UpdateFlags.Upsert);

            var expectedResult = new ExpectedWriteConcernResult
            {
                DocumentsAffected = 1,
                Upserted = id
            };
            CheckExpectedResult(expectedResult, result);

            var document = _collection.FindOne();
            Assert.AreEqual(2, document["x"].AsInt32);
            Assert.AreEqual(1, _collection.Count());
        }
コード例 #49
0
 public void Remove(BsonObjectId id)
 {
     entities.DeleteOne(e => e.Id == id);
 }
コード例 #50
0
ファイル: CRUDService.cs プロジェクト: okusnadi/RawCMS
        public JObject Update(string collection, JObject item, bool replace)
        {
            var dataContext = new Dictionary <string, object>();

            //TODO: why do not manage validation as a simple presave process?
            InvokeValidation(item, collection);

            //TODO: create collection if not exists
            EnsureCollection(collection);

            FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(item["_id"].Value <string>()));

            InvokeProcess(collection, ref item, SavePipelineStage.PreSave, dataContext);

            var id = item["_id"].Value <string>();
            //insert id (mandatory)
            BsonDocument doc = BsonDocument.Parse(item.ToString());

            doc["_id"] = BsonObjectId.Create(id);

            UpdateOptions o = new UpdateOptions()
            {
                IsUpsert = true,
                BypassDocumentValidation = true
            };

            if (replace)
            {
                _mongoService.GetCollection <BsonDocument>(collection).ReplaceOne(filter, doc, o);
            }
            else
            {
                BsonDocument dbset = new BsonDocument("$set", doc);
                _mongoService.GetCollection <BsonDocument>(collection).UpdateOne(filter, dbset, o);
            }
            var fullSaved = Get(collection, id);

            InvokeProcess(collection, ref fullSaved, SavePipelineStage.PostSave, dataContext);
            return(JObject.Parse(fullSaved.ToJson(js)));
        }
コード例 #51
0
        public void TestBulkWriteCountsWithUpsert()
        {
            _collection.Drop();
            var id = new BsonObjectId(ObjectId.GenerateNewId());

            var bulk = _collection.InitializeOrderedBulkOperation();
            bulk.Find(Query.EQ("_id", id)).Upsert().UpdateOne(Update.Set("x", 2));
            bulk.Find(Query.EQ("_id", id)).Upsert().UpdateOne(Update.Set("x", 2));
            bulk.Find(Query.EQ("_id", id)).UpdateOne(Update.Set("x", 3));
            var result = bulk.Execute();

            Assert.AreEqual(0, result.DeletedCount);
            Assert.AreEqual(0, result.InsertedCount);
            if (_primary.Supports(FeatureId.WriteCommands))
            {
                Assert.AreEqual(true, result.IsModifiedCountAvailable);
                Assert.AreEqual(1, result.ModifiedCount);
            }
            else
            {
                Assert.AreEqual(false, result.IsModifiedCountAvailable);
                Assert.Throws<NotSupportedException>(() => { var _ = result.ModifiedCount; });
            }
            Assert.AreEqual(3, result.RequestCount);
            Assert.AreEqual(2, result.MatchedCount);
            Assert.AreEqual(1, result.Upserts.Count);
            Assert.AreEqual(0, result.Upserts.First().Index);
            Assert.AreEqual(id, result.Upserts.First().Id);
        }
コード例 #52
0
 public void EquivalentToObjectIdNotMatch()
 {
     BsonValue val1 = new BsonObjectId(new ObjectId("5212e9f1d7eaf01e8c6b8b40"));
     BsonValue val2 = new BsonObjectId(new ObjectId("5212e9f1d7eaf01e8c6b8b41"));
     Assert.IsFalse(val1.EquivalentTo(val2));
 }
コード例 #53
0
 public void TestBsonObjectId()
 {
     var value = new BsonObjectId(ObjectId.Parse("0102030405060708090a0b0c"));
     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.AreEqual("0102030405060708090a0b0c", Convert.ToString(value));
     Assert.AreEqual("0102030405060708090a0b0c", ((IConvertible)value).ToType(typeof(string), null));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value));
     Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(value));
 }
コード例 #54
0
        public static void EnsureSeedData(this TrulliContext db)
        {
            BsonObjectId donAntonio = ObjectId.GenerateNewId();
            BsonObjectId cinquenoci = ObjectId.GenerateNewId();
            BsonObjectId carbonaio  = ObjectId.GenerateNewId();

            if (db.Properties.CountDocuments(new BsonDocument()) == 0 || db.Trulli.CountDocuments(new BsonDocument()) == 0)
            {
                var properties = new List <Property>
                {
                    new Property
                    {
                        _id          = donAntonio.ToString(),
                        Name         = "Trulli Don Antonio",
                        City         = "Locorotondo",
                        Street       = "S.C. 21 C.da Crocifisso n. 9",
                        Spa          = true,
                        SwimmingPool = false
                    },
                    new Property
                    {
                        _id          = cinquenoci.ToString(),
                        Name         = "Trulli Cinquenoci",
                        City         = "Locorotondo",
                        Street       = "S.C. 126 C.da Cinquenoci n. 6",
                        Spa          = false,
                        SwimmingPool = true
                    },
                    new Property
                    {
                        _id          = carbonaio.ToString(),
                        Name         = "Casa del Carbonaio",
                        City         = "Locorotondo",
                        Street       = "Via Garibaldi n. 17",
                        Spa          = false,
                        SwimmingPool = false
                    }
                };

                var trulli = new List <Trullo>
                {
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = donAntonio.ToString(),
                        Name        = "Trullo Panoramico",
                        Description = "Trullo con soppalco con 2 camere da letto e 2 bagni",
                        Capacity    = 4,
                        Price       = 100
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = donAntonio.ToString(),
                        Name        = "Trullo dell'Interprete",
                        Description = "Trullo in ambiente unico con 1 camera da letto e 1 bagno",
                        Capacity    = 3,
                        Price       = 80
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = donAntonio.ToString(),
                        Name        = "Trullo dell'Arco",
                        Description = "Trullo ampio con 2 camere da letto e 1 bagno",
                        Capacity    = 4,
                        Price       = 120
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = cinquenoci.ToString(),
                        Name        = "Trullo Mille Volte",
                        Description = "Trullo a volte in pietra con 3 camere da letto e 2 bagni",
                        Capacity    = 7,
                        Price       = 180
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = cinquenoci.ToString(),
                        Name        = "Trullo Romantico",
                        Description = "Trullo in ambiente unico con 1 camera da letto e 1 bagno",
                        Capacity    = 2,
                        Price       = 60
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = cinquenoci.ToString(),
                        Name        = "Trullo Nuovo",
                        Description = "Trullo di nuova costruzione con 2 camere da letto e 1 bagno",
                        Capacity    = 4,
                        Price       = 120
                    },
                    new Trullo
                    {
                        _id         = ObjectId.GenerateNewId().ToString(),
                        Property_id = carbonaio.ToString(),
                        Name        = "Trullo del Carbonaio",
                        Description = "Trullo a volte in pietra nel centro storico con 1 camera da letto e 2 bagni",
                        Capacity    = 7,
                        Price       = 110
                    },
                };

                db.Properties.InsertManyAsync(properties);
                db.Trulli.InsertManyAsync(trulli);
            }
        }
コード例 #55
0
        public void TestBulkWriteCountsWithUpsert()
        {
            using (_server.RequestStart(null, ReadPreference.Primary))
            {
                var serverInstance = _server.RequestConnection.ServerInstance;

                _collection.Drop();
                var id = new BsonObjectId(ObjectId.GenerateNewId());

                var result = _collection.BulkWrite(new BulkWriteArgs
                {
                    IsOrdered = true,
                    WriteConcern = WriteConcern.Acknowledged,
                    Requests = new WriteRequest[]
                    {
                        new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 2)) { IsUpsert = true },
                        new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 2)) { IsUpsert = true },
                        new UpdateRequest(Query.EQ("_id", id), Update.Set("x", 3))
                    }
                });

                Assert.AreEqual(0, result.DeletedCount);
                Assert.AreEqual(0, result.InsertedCount);
                if (serverInstance.Supports(FeatureId.WriteCommands))
                {
                    Assert.AreEqual(true, result.IsModifiedCountAvailable);
                    Assert.AreEqual(1, result.ModifiedCount);
                }
                else
                {
                    Assert.AreEqual(false, result.IsModifiedCountAvailable);
                    Assert.Throws<NotSupportedException>(() => { var _ = result.ModifiedCount; });
                }
                Assert.AreEqual(3, result.RequestCount);
                Assert.AreEqual(2, result.MatchedCount);
                Assert.AreEqual(1, result.Upserts.Count);
                Assert.AreEqual(0, result.Upserts.First().Index);
                Assert.AreEqual(id, result.Upserts.First().Id);
            }
        }
コード例 #56
0
ファイル: MongoDB.cs プロジェクト: bbai/TestResultUI
        /// <summary>
        /// Analyze the data in the Mongodb, and put associated data in to different tables
        /// </summary>
        /// <returns>Returns true when finshed analyzing data</returns>
        public bool AnalyzeData(int dropDownIndex, int days)
        {
            DateTime      date = DateTime.Now.Subtract(TimeSpan.FromDays(days));
            SortByBuilder sbb  = new SortByBuilder();

            sbb.Descending("_id");
            var       lastDocs       = collection.FindAllAs <BsonDocument>().SetSortOrder(sbb).SetLimit(15);
            Hashtable idRunNameTable = new Hashtable();
            ArrayList keyList        = new ArrayList();

            foreach (BsonDocument lastDoc in lastDocs)
            {
                BsonObjectId id           = lastDoc["_id"].AsObjectId;
                BsonDocument testRun      = lastDoc["TestRun"].AsBsonDocument;
                string       testRunName  = testRun["@testRunName"].AsString;
                string       userName     = testRun["@userName"].AsString;
                string       timeStamp    = testRun["@timeStamp"].AsString;
                string       hashtableKey = @"""" + testRunName + @""" """ + userName + @""" """ + timeStamp + @"""";
                idRunNameTable.Add(hashtableKey, id);
                //Track the order of each test run
                keyList.Add(hashtableKey);
            }
            BsonObjectId objectId = null;

            if (dropDownIndex >= 0)
            {
                objectId = (BsonObjectId)idRunNameTable[keyList[dropDownIndex]];
            }
            bool ret = false;

            successAllConfigTable = new Hashtable();
            failAllConfigTable    = new Hashtable();
            successConfigTable    = new Hashtable();
            failConfigTable       = new Hashtable();
            //var projectNames = collection.Distinct("TestRun.Configuration.test-results.@project-name").ToList();
            Hashtable projectAutomationTable = this.GetProjectAutomationTable(objectId, days);
            var       filteredTable          = projectAutomationTable.Cast <DictionaryEntry>().Where(x => ((ArrayList)x.Value).Count != 0).ToDictionary(x => (string)x.Key, x => (ArrayList)x.Value);
            var       projectNames           = filteredTable.Keys;
            int       progress        = 0;
            int       totalNumProject = projectNames.Count;

            foreach (string project in projectNames)
            {
                ArrayList automationNameList = (ArrayList)filteredTable[project];
                int       report             = progress * 100 / totalNumProject;
                OnProgressUpdate(report);
                foreach (string automation in automationNameList)
                {
                    MongoCursor <BsonDocument> testSuccess = null;
                    if (dropDownIndex == -1)
                    {
                        var queryResults1 = Query.And(Query.GT("Date", date),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.And(
                                                                                              Query.EQ("@name", automation),
                                                                                              Query.EQ("@success", "True"))))));
                        testSuccess = collection.Find(queryResults1);
                    }
                    else
                    {
                        var queryResults1 = Query.And(Query.EQ("_id", objectId),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.And(
                                                                                              Query.EQ("@name", automation),
                                                                                              Query.EQ("@success", "True"))))));

                        testSuccess = collection.Find(queryResults1);
                    }
                    MongoCursor <BsonDocument> testAll;
                    if (dropDownIndex == -1)
                    {
                        var queryResults2 = Query.And(Query.GT("Date", date),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.EQ("@name", automation)))));
                        testAll = collection.Find(queryResults2);
                    }
                    else
                    {
                        var queryResults2 = Query.And(Query.EQ("_id", objectId),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.EQ("@name", automation)))));
                        testAll = collection.Find(queryResults2);
                    }
                    MongoCursor <BsonDocument> testFail;
                    if (dropDownIndex == -1)
                    {
                        var queryResults3 = Query.And(Query.GT("Date", date),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.And(
                                                                                              Query.EQ("@name", automation),
                                                                                              Query.EQ("@success", "False"))))));
                        testFail = collection.Find(queryResults3);
                    }
                    else
                    {
                        var queryResults3 = Query.And(Query.EQ("_id", objectId),
                                                      Query.ElemMatch("TestRun.Configuration.test-results",
                                                                      Query.And(
                                                                          Query.EQ("@project-name", project),
                                                                          Query.ElemMatch("test-suite.results.test-case",
                                                                                          Query.And(
                                                                                              Query.EQ("@name", automation),
                                                                                              Query.EQ("@success", "False"))))));
                        testFail = collection.Find(queryResults3);
                    }
                    if (testSuccess.Count() != testAll.Count() && testSuccess.Count() != 0)
                    {
                        IEnumerable <BsonDocument> diffs = testAll.Except(testSuccess);
                        foreach (BsonDocument diffBson in diffs)
                        {
                            BsonDocument testRun   = diffBson["TestRun"].AsBsonDocument;
                            string       version   = testRun["@runtimeVersion"].AsString;
                            var          failQuery = Query.And(
                                Query.EQ("@project-name", project), Query.EQ("@runtime-version", version),
                                Query.ElemMatch("failures.automation",
                                                Query.And(
                                                    Query.EQ("@name", automation), Query.EQ("@success", "False"))));
                            MongoCursor <BsonDocument> failCursor            = failCollection.Find(failQuery);
                            List <Automation>          failureAutomationList = new List <Automation>();
                            BsonArray failAutomation = new BsonArray();
                            if (failCursor.Count() != 0)
                            {
                                BsonDocument failTypeDoc  = failCursor.First();
                                BsonDocument failures     = failTypeDoc["failures"].AsBsonDocument;
                                var          failAutoJson = failures.ToJson();
                                failureAutomationList = JsonConvert.DeserializeObject <Failures>(failAutoJson).automation;
                            }
                            string failureType = string.Empty;
                            string failureMsg  = string.Empty;
                            if (failureAutomationList.Count != 0)
                            {
                                var failAutomationWithName = failureAutomationList.Find(x => x.name.Equals(automation));
                                var failStatus             = failAutomationWithName.status;
                                failureType = failStatus.failureType;
                                failureMsg  = failStatus.message;
                            }

                            BsonArray configs = testRun["Configuration"].AsBsonArray;
                            foreach (BsonDocument config in configs)
                            {
                                var    configJson          = config.ToJson();
                                var    configDeserial      = JsonConvert.DeserializeObject <Configuration>(configJson);
                                string templateName        = configDeserial.templateName;
                                var    testResultsDeserial = configDeserial.testResults;
                                var    testResultOnProject = testResultsDeserial.Find(x => x.projectName.Equals(project));
                                var    testSuite           = testResultOnProject.testSuite;
                                var    testResults         = testSuite.results;
                                var    testCase            = testResults.TestCases;
                                var    unitTestResult      = testCase.Find(x => x.name.Equals(automation));
                                //To be done
                                string errorMsg = string.Empty;

                                if (failCursor.Count() == 0)
                                {
                                    failureType = "Failure";
                                }
                                if (failConfigTable.ContainsKey(templateName) == false)
                                {
                                    Hashtable projectTable = new Hashtable();
                                    ArrayList list         = new ArrayList();
                                    Hashtable detailTable  = new Hashtable();
                                    list.Add(failureType);
                                    list.Add(version);
                                    list.Add(errorMsg);
                                    detailTable.Add(automation, list);
                                    projectTable.Add(project, detailTable);
                                    failConfigTable.Add(templateName, projectTable);
                                }
                                else
                                {
                                    Hashtable table = (Hashtable)failConfigTable[templateName];
                                    if (table == null)
                                    {
                                        table = new Hashtable();
                                    }
                                    if (table.ContainsKey(project))
                                    {
                                        Hashtable errorTable = (Hashtable)table[project];
                                        if (errorTable.ContainsKey(automation) == false)
                                        {
                                            ArrayList list = new ArrayList();
                                            list.Add(failureType);
                                            list.Add(version);
                                            list.Add(errorMsg);
                                            errorTable.Add(automation, list);
                                            table[project] = errorTable;
                                        }
                                    }
                                    else
                                    {
                                        Hashtable errorTable = new Hashtable();
                                        ArrayList list       = new ArrayList();
                                        list.Add(failureType);
                                        list.Add(version);
                                        list.Add(errorMsg);
                                        errorTable.Add(automation, list);
                                        table.Add(project, errorTable);
                                    }
                                    failConfigTable[templateName] = table;
                                }
                            }
                        }
                    }
                    if (testAll.Count() != testFail.Count() && testFail.Count() != 0)
                    {
                        IEnumerable <BsonDocument> diff = testAll.Except(testFail);
                        foreach (BsonDocument diffBson in diff)
                        {
                            BsonDocument testRun = diffBson["TestRun"].AsBsonDocument;
                            string       version = testRun["@runtimeVersion"].AsString;
                            BsonArray    configs = testRun["Configuration"].AsBsonArray;
                            foreach (BsonDocument config in configs)
                            {
                                var    configJson          = config.ToJson();
                                var    configDeserial      = JsonConvert.DeserializeObject <Configuration>(configJson);
                                string templateName        = configDeserial.templateName;
                                var    testResultsDeserial = configDeserial.testResults;
                                var    testResultOnProject = testResultsDeserial.Find(x => x.projectName.Equals(project));
                                var    testSuite           = testResultOnProject.testSuite;
                                var    testResults         = testSuite.results;
                                var    testCase            = testResults.TestCases;
                                var    unitTestResult      = testCase.Find(x => x.name.Equals(automation));
                                if (successConfigTable.ContainsKey(templateName) == false)
                                {
                                    Hashtable projectTable = new Hashtable();
                                    Hashtable detailTable  = new Hashtable();
                                    ArrayList list         = new ArrayList();
                                    list.Add(version);
                                    detailTable.Add(automation, list);
                                    projectTable.Add(project, detailTable);
                                    successConfigTable.Add(templateName, projectTable);
                                }
                                else
                                {
                                    Hashtable table = (Hashtable)successConfigTable[templateName];
                                    if (table == null)
                                    {
                                        table = new Hashtable();
                                    }
                                    if (table.ContainsKey(project) == true)
                                    {
                                        Hashtable detailTable = (Hashtable)table[project];
                                        ArrayList list        = new ArrayList();
                                        if (detailTable.ContainsKey(automation) == false)
                                        {
                                            list.Add(version);
                                            detailTable.Add(automation, list);
                                        }
                                        else
                                        {
                                            list = (ArrayList)detailTable[automation];
                                            list.Add(version);
                                            detailTable[automation] = list;
                                        }
                                        table[project] = detailTable;
                                    }
                                    else
                                    {
                                        Hashtable detailTable = new Hashtable();

                                        ArrayList list = new ArrayList();
                                        if (detailTable.ContainsKey(automation) == false)
                                        {
                                            list.Add(version);
                                            detailTable.Add(automation, list);
                                        }
                                        table.Add(project, detailTable);
                                    }
                                    successConfigTable[templateName] = table;
                                }
                            }
                        }
                    }
                    if (testFail.Count() == 0)
                    {
                        BsonDocument first   = testSuccess.First();
                        string       version = this.GetRuntimeVersion(first);
                        if (successAllConfigTable.ContainsKey(project) == false)
                        {
                            ArrayList list = new ArrayList();
                            list.Add(version);
                            Hashtable table = new Hashtable();
                            table.Add(automation, list);
                            successAllConfigTable.Add(project, table);
                        }
                        else
                        {
                            Hashtable table = (Hashtable)successAllConfigTable[project];
                            ArrayList list  = (ArrayList)table[automation];
                            if (list == null)
                            {
                                list = new ArrayList();
                            }
                            list.Add(version);
                            table[automation] = list;
                            successAllConfigTable[project] = table;
                        }
                    }

                    if (testSuccess.Count() == 0)
                    {
                        BsonDocument first     = testFail.First();
                        string       version   = this.GetRuntimeVersion(first);
                        var          failQuery = Query.And(
                            Query.EQ("@project-name", project), Query.EQ("@runtime-version", version),
                            Query.ElemMatch("failures.automation",
                                            Query.And(
                                                Query.EQ("@name", automation), Query.EQ("@success", "False"))));
                        MongoCursor <BsonDocument> failCursor            = failCollection.Find(failQuery);
                        List <Automation>          failureAutomationList = new List <Automation>();
                        BsonArray failAutomation = new BsonArray();
                        if (failCursor.Count() != 0)
                        {
                            BsonDocument failTypeDoc  = failCursor.First();
                            BsonDocument failures     = failTypeDoc["failures"].AsBsonDocument;
                            var          failAutoJson = failures.ToJson();
                            failureAutomationList = JsonConvert.DeserializeObject <Failures>(failAutoJson).automation;
                        }
                        string failureType = string.Empty;
                        string failureMsg  = string.Empty;
                        if (failureAutomationList.Count != 0)
                        {
                            var failAutomationWithName = failureAutomationList.Find(x => x.name.Equals(automation));
                            var failStatus             = failAutomationWithName.status;
                            failureType = failStatus.failureType;
                            failureMsg  = failStatus.message;
                        }
                        if (failCursor.Count() == 0)
                        {
                            failureType = "Failure";
                        }
                        string errorMsg = string.Empty;
                        foreach (BsonDocument fail in testFail)
                        {
                            BsonDocument testRun = fail["TestRun"].AsBsonDocument;
                            BsonArray    configs = testRun["Configuration"].AsBsonArray;
                            foreach (BsonDocument config in configs)
                            {
                                var    configJson          = config.ToJson();
                                var    configDeserial      = JsonConvert.DeserializeObject <Configuration>(configJson);
                                string templateName        = configDeserial.templateName;
                                var    testResultsDeserial = configDeserial.testResults;
                                var    testResultOnProject = testResultsDeserial.Find(x => x.projectName.Equals(project));
                                var    testSuite           = testResultOnProject.testSuite;
                                var    testResults         = testSuite.results;
                                var    testCase            = testResults.TestCases;
                                var    unitTestResult      = testCase.Find(x => x.name.Equals(automation));
                                //To be done
                                errorMsg = string.Empty;
                            }
                        }
                        if (failAllConfigTable.ContainsKey(project) == false)
                        {
                            ArrayList list = new ArrayList();
                            list.Add(failureType);
                            list.Add(version);
                            list.Add(errorMsg);
                            Hashtable table = new Hashtable();
                            table.Add(automation, list);
                            failAllConfigTable.Add(project, table);
                        }
                        else
                        {
                            Hashtable table = (Hashtable)failAllConfigTable[project];
                            ArrayList list  = (ArrayList)table[automation];
                            if (list == null)
                            {
                                list = new ArrayList();
                            }
                            list.Add(failureType);
                            list.Add(version);
                            list.Add(errorMsg);
                            table[automation]           = list;
                            failAllConfigTable[project] = table;
                        }
                    }
                }
                progress++;
            }
            OnProgressUpdate(100);
            ret = true;
            return(ret);
        }
コード例 #57
0
        public void TestCreateNull()
        {
            object obj = null;

            Assert.Throws <ArgumentNullException>(() => { BsonObjectId.Create(obj); });
        }
コード例 #58
0
        /// <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()) {
                EnsureIndexes();

                var files_id  = createOptions.Id ?? BsonObjectId.GenerateNewId();
                var chunkSize = createOptions.ChunkSize == 0 ? settings.ChunkSize : createOptions.ChunkSize;
                var buffer    = new byte[chunkSize];

                var    length = 0;
                string md5Client;
                using (var md5Algorithm = MD5.Create()) {
                    for (int n = 0; 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 },
                            { "data", new BsonBinaryData(data) }
                        };
                        chunks.Insert(chunk, settings.SafeMode);

                        md5Algorithm.TransformBlock(data, 0, data.Length, null, 0);

                        if (bytesRead < chunkSize)
                        {
                            break; // EOF after partial chunk
                        }
                    }

                    md5Algorithm.TransformFinalBlock(new byte[0], 0, 0);
                    md5Client = BsonUtils.ToHexString(md5Algorithm.Hash);
                }

                var md5Command = new CommandDocument {
                    { "filemd5", files_id },
                    { "root", settings.Root }
                };
                var md5Result = database.RunCommand(md5Command);
                var md5Server = md5Result.Response["md5"].AsString;

                if (!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 },
                    { "contentType", createOptions.ContentType },                                 // optional
                    { "aliases", BsonArray.Create((IEnumerable <string>)createOptions.Aliases) }, // optional
                    { "metadata", createOptions.Metadata } // optional
                };
                files.Insert(fileInfo, settings.SafeMode);

                return(FindOneById(files_id));
            }
        }
コード例 #59
0
        public void TestBsonObjectIdEquals()
        {
            var a = new BsonObjectId(ObjectId.GenerateNewId());
            var b = new BsonObjectId(a.Value);
            var c = new BsonObjectId(ObjectId.GenerateNewId());
            var n = (BsonObjectId)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);
        }
コード例 #60
0
        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);
            }
        }