public void Load(BulkLoad load) { var tasks = new Task[load.Collections.Count]; int i = 0; foreach (var pair in load.Collections) { var bulkCollection = pair.Value; var collectionName = pair.Key; var keys = bulkCollection.Documents.Keys; var bsonIdArray = new BsonArray(keys); var collection = _mongoDatabase.GetCollection(bulkCollection.CollectionType, collectionName); tasks[i] = Task.Factory.StartNew(() => { MongoCursor cursor = collection.FindAs(bulkCollection.CollectionType, Query.In("_id", bsonIdArray)); foreach (var doc in cursor) { var id = _metadata.GetDocumentId(doc); bulkCollection.Documents[id] = doc; } }); i++; } Task.WaitAll(tasks); }
/// <summary> /// /// </summary> /// <param name="newItem"></param> /// <param name="item"></param> public static void AddBSonArrayToTreeNode(TreeNode newItem, BsonArray item) { foreach (BsonValue SubItem in item) { if (SubItem.IsBsonDocument) { TreeNode newSubItem = new TreeNode(); AddBsonDocToTreeNode(newSubItem, SubItem.ToBsonDocument()); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } else { if (SubItem.IsBsonArray) { TreeNode newSubItem = new TreeNode(); AddBSonArrayToTreeNode(newSubItem, SubItem.AsBsonArray); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } else { TreeNode newSubItem = new TreeNode(); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } } } }
public BsonDocument Serialize(Scope scope) { var doc = new BsonDocument(); doc["_id"] = scope.Name; doc["_version"] = 1; doc.SetIfNotNull("displayName", scope.DisplayName); var claims = new BsonArray(); foreach (ScopeClaim scopeClaim in scope.Claims) { var claim = new BsonDocument(); claim["name"] = scopeClaim.Name; claim["alwaysIncludeInIdToken"] = scopeClaim.AlwaysIncludeInIdToken; claim.SetIfNotNull("description", scopeClaim.Description); claims.Add(claim); } doc["claims"] = claims; doc.SetIfNotNull("claimsRule", scope.ClaimsRule); doc.SetIfNotNull("description", scope.Description); doc["emphasize"] = scope.Emphasize; doc["enabled"] = scope.Enabled; doc["includeAllClaimsForUser"] = scope.IncludeAllClaimsForUser; doc["required"] = scope.Required; doc["showInDiscoveryDocument"] = scope.ShowInDiscoveryDocument; doc["type"] = scope.Type.ToString(); return doc; }
public void TestAllBsonArray() { var array = new BsonArray { 2, 4, null, 6 }; // null will be skipped due to functional construction semantics var query = Query.All("j", array); var expected = "{ \"j\" : { \"$all\" : [2, 4, 6] } }"; Assert.AreEqual(expected, query.ToJson()); }
public void TestMapBsonArray() { var value = new BsonArray(); var bsonValue = (BsonArray) BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonArray = (BsonArray) BsonTypeMapper.MapToBsonValue(value, BsonType.Array); Assert.AreSame(value, bsonArray); }
public static void AddField(this BsonDocument doc, string name, object value) { if (value == null) return; var unifiedName = name.ToLower(); switch (unifiedName) { case "exception": doc[name] = BuildExceptionBsonDocument((Exception)value); break; case "properties": var properties = (IDictionary<object, object>)value; if (properties.Count > 0) doc[name] = BuildPropertiesBsonDocument(properties); break; case "parameters": var parameters = (object[])value; BsonArray array = new BsonArray(); foreach (var param in parameters) { array.Add(SafeCreateBsonValue(param)); } doc[name] = array; break; default: doc[name] = SafeCreateBsonValue(value); break; } }
/// <summary> /// 将BsonArray放入树形控件 /// </summary> /// <param name="newItem"></param> /// <param name="item"></param> public static void AddBsonArrayToTreeNode(String ArrayName, TreeNode newItem, BsonArray item) { int Count = 1; foreach (BsonValue SubItem in item) { if (SubItem.IsBsonDocument) { TreeNode newSubItem = new TreeNode(ArrayName + "[" + Count + "]"); AddBsonDocToTreeNode(newSubItem, SubItem.ToBsonDocument()); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } else { if (SubItem.IsBsonArray) { TreeNode newSubItem = new TreeNode(Array_Mark); AddBsonArrayToTreeNode(ArrayName, newSubItem, SubItem.AsBsonArray); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } else { TreeNode newSubItem = new TreeNode(ArrayName + "[" + Count + "]"); newSubItem.Tag = SubItem; newItem.Nodes.Add(newSubItem); } } Count++; } }
public IEnumerable<Category> GetAllCategories(string[] categoryColors) { var colorArray = new BsonArray(categoryColors); var query = Query.In("Color", colorArray); return Categories.FindAs<Category>(query).ToList(); }
private BsonDocument CreateDoc() { // create same object, but using BsonDocument var doc = new BsonDocument(); doc["_id"] = 123; doc["FirstString"] = "BEGIN this string \" has \" \t and this \f \n\r END"; doc["CustomerId"] = Guid.NewGuid(); doc["Date"] = DateTime.Now; doc["MyNull"] = null; doc["EmptyObj"] = new BsonDocument(); doc["EmptyString"] = ""; doc["maxDate"] = DateTime.MaxValue; doc["minDate"] = DateTime.MinValue; doc.Set("Customer.Address.Street", "Av. Caçapava, Nº 122"); doc["Items"] = new BsonArray(); doc["Items"].AsArray.Add(new BsonDocument()); doc["Items"].AsArray[0].AsDocument["Qtd"] = 3; doc["Items"].AsArray[0].AsDocument["Description"] = "Big beer package"; doc["Items"].AsArray[0].AsDocument["Unit"] = (double)10 / (double)3; doc["Items"].AsArray.Add("string-one"); doc["Items"].AsArray.Add(null); doc["Items"].AsArray.Add(true); doc["Items"].AsArray.Add(DateTime.Now); return doc; }
public void add_doc_array_to_node(BsonArray array, ref TreeNode node_father) { for (int i = 0; i < array.Count; i++) { switch (array[i].BsonType) { case BsonType.Document: TreeNode node_doc = new TreeNode(); node_doc.Text = i.ToString(); add_doc_to_node(array[i].AsBsonDocument, ref node_doc); node_father.Nodes.Add(node_doc); break; case BsonType.Array: TreeNode node_array = new TreeNode(); node_array.Text = i.ToString(); add_doc_array_to_node(array[i].AsBsonArray, ref node_array); node_father.Nodes.Add(node_array); break; default: TreeNode node = new TreeNode(); node.Text = array[i].ToString(); node_father.Nodes.Add(node); break; } } }
/// <summary> /// </summary> /// <param name="SubNode"></param> /// <returns></returns> public static BsonDocument ConvertTreeNodeTozTreeBsonDoc(TreeNode SubNode) { var SingleNode = new BsonDocument(); SingleNode.Add("name", SubNode.Text + GetTagText(SubNode)); if (SubNode.Nodes.Count == 0) { SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png"); } else { var ChildrenList = new BsonArray(); foreach (TreeNode item in SubNode.Nodes) { ChildrenList.Add(ConvertTreeNodeTozTreeBsonDoc(item)); } SingleNode.Add("children", ChildrenList); SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png"); } if (SubNode.IsExpanded) { SingleNode.Add("open", "true"); } if (SubNode.Tag != null) { SingleNode.Add("click", "ShowData('" + SystemManager.GetTagType(SubNode.Tag.ToString()) + "','" + SystemManager.GetTagData(SubNode.Tag.ToString()) + "')"); } return SingleNode; }
private BsonDocument CreateDoc() { // create same object, but using BsonDocument var doc = new BsonDocument(); doc["_id"] = 123; doc["FirstString"] = "BEGIN this string \" has \" \t and this \f \n\r END"; doc["CustomerId"] = Guid.NewGuid(); doc["Date"] = new DateTime(2015, 1, 1); doc["MyNull"] = null; doc["Items"] = new BsonArray(); doc["MyObj"] = new BsonDocument(); doc["EmptyString"] = ""; var obj = new BsonDocument(); obj["Qtd"] = 3; obj["Description"] = "Big beer package"; obj["Unit"] = 1299.995; doc["Items"].AsArray.Add(obj); doc["Items"].AsArray.Add("string-one"); doc["Items"].AsArray.Add(null); doc["Items"].AsArray.Add(true); doc["Items"].AsArray.Add(DateTime.Now); doc.Set("MyObj.IsFirstId", true); return doc; }
/// <summary> /// Tests that the named array element contains all of the values (see $all). /// </summary> /// <param name="name">The name of the element to test.</param> /// <param name="values">The values to compare to.</param> /// <returns>The builder (so method calls can be chained).</returns> public static QueryConditionList All( string name, BsonArray values ) { return new QueryConditionList(name).All(values); }
public UserRole(ObjectId Id, String UserRoleName, BsonArray UserRolePowers, ObjectId PUserRole) { this.Id = Id; this.UserRoleName = UserRoleName; this.UserRolePowers = UserRolePowers; this.PUserRole = PUserRole; }
public static QueryConditionList All( string name, BsonArray array ) { return new QueryConditionList(name, "$all", array); }
public void TestBsonArrayEquals() { var a = new BsonArray { "a", 1 }; var b = new BsonArray { "a", 1 }; var c = new BsonArray { "b", 1 }; var n = (BsonArray)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsFalse(a == c); 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 != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
public void TestCapacity() { var array = new BsonArray(4); Assert.AreEqual(4, array.Capacity); array.Capacity = 8; Assert.AreEqual(8, array.Capacity); }
public void TestAddRangeBooleanNull() { var array = new BsonArray(); var values = (bool[])null; array.AddRange(values); Assert.AreEqual(0, array.Count); }
public void TestAddRangeInt32Null() { var array = new BsonArray(); var values = (int[])null; array.AddRange(values); Assert.AreEqual(0, array.Count); }
public void TestAddRangeDateTimeNull() { var array = new BsonArray(); var values = (DateTime[])null; array.AddRange(values); Assert.AreEqual(0, array.Count); }
/// <summary> /// 将BsonArray放入树形控件 /// </summary> /// <param name="arrayName"></param> /// <param name="newItem"></param> /// <param name="item"></param> public static void AddBsonArrayToTreeNode(string arrayName, TreeNode newItem, BsonArray item) { var count = 1; foreach (var subItem in item) { if (subItem.IsBsonDocument) { var newSubItem = new TreeNode(arrayName + "[" + count + "]"); AddBsonDocToTreeNode(newSubItem, subItem.ToBsonDocument()); newSubItem.Tag = subItem; newItem.Nodes.Add(newSubItem); } else { if (subItem.IsBsonArray) { var newSubItem = new TreeNode(ConstMgr.ArrayMark); AddBsonArrayToTreeNode(arrayName, newSubItem, subItem.AsBsonArray); newSubItem.Tag = subItem; newItem.Nodes.Add(newSubItem); } else { var newSubItem = new TreeNode(arrayName + "[" + count + "]") { Tag = subItem }; newItem.Nodes.Add(newSubItem); } } count++; } }
public void TestAddNull() { var array = new BsonArray(); var value = (BsonValue)null; array.Add(value); Assert.AreEqual(0, array.Count); }
/// <summary> /// 获得数据库角色 /// </summary> /// <param name="DatabaseName"></param> /// <returns></returns> public BsonArray GetRolesByDBName(String DatabaseName) { BsonArray roles = new BsonArray(); //当前DB的System.user的角色 if (UserList.ContainsKey(DatabaseName)) { roles = UserList[DatabaseName].roles; } ///Admin的OtherDBRoles和当前数据库角色合并 BsonArray adminRoles = GetOtherDBRoles(DatabaseName); foreach (String item in adminRoles) { if (!roles.Contains(item)) { roles.Add(item); } } ///ADMIN的ANY系角色的追加 if (UserList.ContainsKey(MongoDBHelper.DATABASE_NAME_ADMIN)) { if (UserList[MongoDBHelper.DATABASE_NAME_ADMIN].roles.Contains(MongoDBHelper.UserRole_dbAdminAnyDatabase)){ roles.Add(MongoDBHelper.UserRole_dbAdminAnyDatabase); } if (UserList[MongoDBHelper.DATABASE_NAME_ADMIN].roles.Contains(MongoDBHelper.UserRole_readAnyDatabase)) { roles.Add(MongoDBHelper.UserRole_readAnyDatabase); } if (UserList[MongoDBHelper.DATABASE_NAME_ADMIN].roles.Contains(MongoDBHelper.UserRole_readWriteAnyDatabase)) { roles.Add(MongoDBHelper.UserRole_readWriteAnyDatabase); } if (UserList[MongoDBHelper.DATABASE_NAME_ADMIN].roles.Contains(MongoDBHelper.UserRole_userAdminAnyDatabase)) { roles.Add(MongoDBHelper.UserRole_userAdminAnyDatabase); } } return roles; }
public void Post(UserModel model) { var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017"); var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks"); BsonArray arr = new BsonArray(); dynamic jobj = JsonConvert.DeserializeObject<dynamic>(model.Movies.ToString()); foreach (var item in jobj) { foreach(var subitem in item) { arr.Add(subitem.Title.ToString()); } } var document = new BsonDocument { { "Facebook_ID", model.Facebook_ID }, { "Ime", model.Ime }, { "Prezime", model.Prezime }, { "Email", model.Email }, { "DatumRodjenja", model.DatumRodjenja }, { "Hometown", model.Hometown}, { "ProfilePictureLink", model.ProfilePictureLink }, { "Movies", arr }, }; var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo"); collection.InsertOneAsync(document); }
// public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonArray)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Array: bsonReader.ReadStartArray(); var array = new BsonArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null); array.Add(value); } bsonReader.ReadEndArray(); return array; default: var message = string.Format("Cannot deserialize BsonArray from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
private void WriteArray(BsonArray arr) { var hasData = arr.Count > 0; this.WriteStartBlock("[", hasData); for (var i = 0; i < arr.Count; i++) { var item = arr[i]; // do not do this tests if is not pretty format - to better performance if (this.Pretty) { if (!((item.IsDocument && item.AsDocument.Keys.Any()) || (item.IsArray && item.AsArray.Count > 0))) { this.WriteIndent(); } } this.WriteValue(item ?? BsonValue.Null); if (i < arr.Count - 1) { _writer.Write(','); } this.WriteNewLine(); } this.WriteEndBlock("]", hasData); }
public static BsonDocument CreateReadPreferenceDocument(ServerType serverType, ReadPreference readPreference) { if (readPreference == null) { return null; } if (serverType != ServerType.ShardRouter) { return null; } BsonArray tagSets = null; if (readPreference.TagSets != null && readPreference.TagSets.Any()) { tagSets = new BsonArray(readPreference.TagSets.Select(ts => new BsonDocument(ts.Tags.Select(t => new BsonElement(t.Name, t.Value))))); } else if (readPreference.ReadPreferenceMode == ReadPreferenceMode.Primary || readPreference.ReadPreferenceMode == ReadPreferenceMode.SecondaryPreferred) { return null; } var readPreferenceString = readPreference.ReadPreferenceMode.ToString(); readPreferenceString = Char.ToLowerInvariant(readPreferenceString[0]) + readPreferenceString.Substring(1); return new BsonDocument { { "mode", readPreferenceString }, { "tags", tagSets, tagSets != null } }; }
public override void Build(MongoDB.Bson.BsonDocument bsonPanelSetOrder, int panelSetId) { base.Build(bsonPanelSetOrder, panelSetId); string reportNo = bsonPanelSetOrder.GetValue("ReportNo").ToString(); MongoCollection surgicalSpecimenTable = this.m_SQLTransferDatabase.GetCollection<BsonDocument>("tblSurgicalSpecimen"); MongoCursor mongoCursor = surgicalSpecimenTable.FindAs<BsonDocument>(Query.EQ("ReportNo", reportNo)); BsonArray bsonArray = new BsonArray(); foreach (BsonDocument bsonSurgicalSpecimen in mongoCursor) { string surgicalSpecimenId = bsonSurgicalSpecimen.GetValue("SurgicalSpecimenId").AsString; this.BuildIC(bsonSurgicalSpecimen, surgicalSpecimenId); this.BuildStainResult(bsonSurgicalSpecimen, surgicalSpecimenId); this.BuildICD9BillingCode(bsonSurgicalSpecimen, surgicalSpecimenId); bsonArray.Add(bsonSurgicalSpecimen); } bsonPanelSetOrder.Add("SurgicalSpecimenCollection", bsonArray); MongoCollection surgicalAuditTable = this.m_SQLTransferDatabase.GetCollection<BsonDocument>("tblSurgicalAudit"); MongoCursor surgicalAuditCursor = surgicalAuditTable.FindAs<BsonDocument>(Query.EQ("ReportNo", reportNo)); BsonArray surgicalAuditArray = new BsonArray(); foreach (BsonDocument bsonSurgicalAudit in surgicalAuditCursor) { string surgicalAuditId = bsonSurgicalAudit.GetValue("SurgicalAuditId").AsString; this.BuildSurgicalSpecimenAudit(bsonSurgicalAudit, surgicalAuditId); surgicalAuditArray.Add(bsonSurgicalAudit); } bsonPanelSetOrder.Add("SurgicalAuditCollection", surgicalAuditArray); }
public static BsonDocument CreateReadPreferenceDocument(ServerType serverType, ReadPreference readPreference) { if (serverType != ServerType.ShardRouter || readPreference == null) { return null; } BsonArray tagSets = null; if (readPreference.TagSets != null && readPreference.TagSets.Count > 0) { tagSets = new BsonArray(readPreference.TagSets.Select(ts => new BsonDocument(ts.Tags.Select(t => new BsonElement(t.Name, t.Value))))); } // simple ReadPreferences of Primary and SecondaryPreferred are encoded in the slaveOk bit if (readPreference.ReadPreferenceMode == ReadPreferenceMode.Primary || readPreference.ReadPreferenceMode == ReadPreferenceMode.SecondaryPreferred) { if (tagSets == null && !readPreference.MaxStaleness.HasValue) { return null; } } var modeString = readPreference.ReadPreferenceMode.ToString(); modeString = Char.ToLowerInvariant(modeString[0]) + modeString.Substring(1); return new BsonDocument { { "mode", modeString }, { "tags", tagSets, tagSets != null }, { "maxStalenessSeconds", () => (int)readPreference.MaxStaleness.Value.TotalSeconds, readPreference.MaxStaleness.HasValue } }; }
public void SaveObjectDefinitions(List <ObjectDefinition> items, TObjectState state) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("ObjectDefinition"); foreach (ObjectDefinition item in items) { if (item.ObjectDefinitionID == Guid.Empty) { item.ObjectDefinitionID = Guid.NewGuid(); } FilterDefinition <BsonDocument> query = Builders <BsonDocument> .Filter.Eq("_id", item.ObjectDefinitionID.ToByteArray()); if ((state == TObjectState.Add) || (state == TObjectState.Update)) { BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", item.ObjectDefinitionID); BsonHelper.SetValue(doc, "ObjectID", item.ObjectID); if (item.OrganisationID.HasValue && (item.OrganisationID.Value == 0)) { item.OrganisationID = null; } BsonHelper.SetValue(doc, "OrganisationID", item.OrganisationID); BsonHelper.SetValue(doc, "Name", item.Name); BsonHelper.SetValue(doc, "MIMEType", item.MIMEType); BsonHelper.SetValue(doc, "SerialisationName", item.SerialisationName); BsonHelper.SetValue(doc, "Description", item.Description); BsonHelper.SetValue(doc, "Singleton", item.Singleton); if ((item.Properties != null) && item.Properties.Count > 0) { BsonArray array = new BsonArray(); foreach (PropertyDefinition property in item.Properties) { if (property.PropertyDefinitionID == Guid.Empty) { property.PropertyDefinitionID = Guid.NewGuid(); } BsonDocument propertyDoc = new BsonDocument(); BsonHelper.SetValue(propertyDoc, "_id", property.PropertyDefinitionID); BsonHelper.SetValue(propertyDoc, "PropertyID", property.PropertyID); BsonHelper.SetValue(propertyDoc, "Name", property.Name); BsonHelper.SetValue(propertyDoc, "Description", property.Description); BsonHelper.SetValue(propertyDoc, "DataType", (int)property.DataType); BsonHelper.SetValue(propertyDoc, "DataTypeLength", property.DataTypeLength); BsonHelper.SetValue(propertyDoc, "MIMEType", property.MIMEType); BsonHelper.SetValue(propertyDoc, "MinValue", property.MinValue); BsonHelper.SetValue(propertyDoc, "MaxValue", property.MaxValue); BsonHelper.SetValue(propertyDoc, "Units", property.Units); BsonHelper.SetValue(propertyDoc, "IsCollection", property.IsCollection); BsonHelper.SetValue(propertyDoc, "IsMandatory", property.IsMandatory); BsonHelper.SetValue(propertyDoc, "Access", (int)property.Access); BsonHelper.SetValue(propertyDoc, "SortOrder", property.SortOrder); BsonHelper.SetValue(propertyDoc, "SerialisationName", property.SerialisationName); BsonHelper.SetValue(propertyDoc, "CollectionItemSerialisationName", property.CollectionItemSerialisationName); array.Add(propertyDoc); } doc.Add("Properties", array); } UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); } else if (state == TObjectState.Delete) { collection.DeleteOne(query); } } BroadcastTableChange("ObjectDefinition", string.Empty); }
/// <summary> /// 数据接收处理,失败后抛出NullReferenceException异常,主线程会进行捕获 /// </summary> /// <param name="args">url参数</param> public void DataReceive(DataReceivedEventArgs args) { if (UrlQueue.Instance.Count <= Settings.ThreadCount * 10 + 50) { if ((DateTime.Now - Settings.LastAvaiableTime).TotalSeconds >= 60) { Console.WriteLine("url剩余少于40"); Settings.LastAvaiableTime = DateTime.Now; Console.WriteLine("开始获取url"); InitialUrlQueue(); } } var hmtl = args.Html; HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(args.Html); var schoolId = GetSchoolKey(args.Url); var root = htmlDoc.DocumentNode; var doc = new BsonDocument(); //周边站点 var siteNode = root.SelectNodes("//div[@class='block']").Where(c => c.InnerText.Contains("周边站点")).FirstOrDefault(); if (siteNode != null) { var siteDetailNode = siteNode.SelectNodes("./div[@class='bd']/span"); if (siteDetailNode != null) { var docArr = new BsonArray(); foreach (var siteDetail in siteDetailNode) { docArr.Add(siteDetail.InnerText); } doc.Add("distinctDetail", docArr); } } //公交线路 var busNode = root.SelectNodes("//div[@class='block']").Where(c => c.InnerText.Contains("公交线路")).FirstOrDefault(); if (busNode != null) { var siteDetailNode = busNode.SelectNodes("./div[@class='bd']/span"); if (siteDetailNode != null) { var docArr = new BsonArray(); foreach (var siteDetail in siteDetailNode) { docArr.Add(siteDetail.InnerText); } doc.Add("busSiteDetail", docArr); } } ///2016.6.20添加更新xy轴 var xBenStr = "var poi_lat ="; var yBenStr = "var poi_lng ="; var xBeginIndex = args.Html.IndexOf(xBenStr); var yBeginIndex = args.Html.IndexOf(yBenStr); if (xBeginIndex != -1 && yBeginIndex != -1) { var xValue = Toolslib.Str.Sub(hmtl, xBenStr, ";"); var yValue = Toolslib.Str.Sub(hmtl, yBenStr, ";"); if (!string.IsNullOrEmpty(xValue) && !string.IsNullOrEmpty(yValue)) { doc.Add("x", xValue.Trim()); doc.Add("y", yValue.Trim()); } } if (!string.IsNullOrEmpty(schoolId)) { doc.Add("isUpdate", "1"); DBChangeQueue.Instance.EnQueue(new StorageData() { Name = DataTableName, Document = doc, Query = Query.EQ("schoolId", schoolId), Type = StorageType.Update }); } }
protected virtual void MaintenanceTask(object st) { if (_stop) { return; } var inm = Interlocked.CompareExchange(ref _inMaintenance, 1, 0); if (inm != 0) { return; } try { log.Debug("Maintenance task start"); var db = OpenDatabase(GetMongoConnectionStringForEndpoint(Endpoint)); var col = db.GetCollection(_collectionName); var cp = GetCurrentlyProcessed(); if (cp.Length > 0) { //touch currently locked messages col.Update(Query.And(Query.In("_id", BsonArray.Create(cp)), Query.EQ("Q", "P")), Update.Set("LT", DateTime.Now)); } //move from retry to the input queue var r = col.Update( Query.And(Query.EQ("Q", "R"), Query.LTE("RT", DateTime.Now)), Update.Set("Q", "I"), SafeMode.True); if (r != null && r.DocumentsAffected > 0) { log.Info("Moved {0} messages to input queue", r.DocumentsAffected); _waiter.Set(); } if ((DateTime.Now - _lastCleanup).TotalSeconds > 60) { _lastCleanup = DateTime.Now; //return abandonned messages to the queue r = col.Update( Query.And(Query.EQ("Q", "P"), Query.LT("LT", DateTime.Now.AddSeconds(-MessageLockTimeSec))), Update.Set("Q", "I"), SafeMode.True); if (r != null && r.DocumentsAffected > 0) { log.Info("Unlocked {0} messages", r.DocumentsAffected); _waiter.Set(); } if (MessageRetentionPeriod > TimeSpan.Zero) { col.Remove(Query.And(Query.EQ("Q", "X"), Query.LT("RT", DateTime.Now - MessageRetentionPeriod))); } } log.Debug("Maintenance task end"); } catch (ThreadInterruptedException) { } catch (Exception ex) { log.Error("Maintenance task error: {0}", ex); } finally { Interlocked.Decrement(ref _inMaintenance); } }
public BsonDocument LoggingEventToBSON(LoggingEvent loggingEvent) { if (loggingEvent == null) { return(null); } var toReturn = new BsonDocument(); toReturn[FieldNames.Timestamp] = loggingEvent.TimeStamp; toReturn[FieldNames.Level] = loggingEvent.Level.ToString(); toReturn[FieldNames.Thread] = loggingEvent.ThreadName ?? String.Empty; if (!LooseFix) { toReturn[FieldNames.Username] = loggingEvent.UserName ?? String.Empty; } toReturn[FieldNames.Message] = loggingEvent.RenderedMessage; toReturn[FieldNames.Loggername] = loggingEvent.LoggerName ?? String.Empty; toReturn[FieldNames.Domain] = loggingEvent.Domain ?? String.Empty; toReturn[FieldNames.Machinename] = MachineName ?? String.Empty; toReturn[FieldNames.ProgramName] = ProgramName ?? String.Empty; // location information, if available if (!LooseFix && loggingEvent.LocationInformation != null) { toReturn[FieldNames.Filename] = loggingEvent.LocationInformation.FileName ?? String.Empty; toReturn[FieldNames.Method] = loggingEvent.LocationInformation.MethodName ?? String.Empty; toReturn[FieldNames.Linenumber] = loggingEvent.LocationInformation.LineNumber ?? String.Empty; toReturn[FieldNames.Classname] = loggingEvent.LocationInformation.ClassName ?? String.Empty; } // exception information if (loggingEvent.ExceptionObject != null) { toReturn[FieldNames.Exception] = ExceptionToBSON(loggingEvent.ExceptionObject); if (loggingEvent.ExceptionObject.InnerException != null) { //Serialize all inner exception in a bson array var innerExceptionList = new BsonArray(); var actualEx = loggingEvent.ExceptionObject.InnerException; while (actualEx != null) { var ex = ExceptionToBSON(actualEx); innerExceptionList.Add(ex); if (actualEx.InnerException == null) { //this is the first exception toReturn[FieldNames.FirstException] = ExceptionToBSON(actualEx); } actualEx = actualEx.InnerException; } toReturn[FieldNames.Innerexception] = innerExceptionList; } } // properties PropertiesDictionary compositeProperties = loggingEvent.GetProperties(); if (compositeProperties != null && compositeProperties.Count > 0) { var properties = new BsonDocument(); foreach (DictionaryEntry entry in compositeProperties) { if (entry.Value == null) { continue; } //remember that no property can have a point in it because it cannot be saved. String key = entry.Key.ToString().Replace(".", "|"); BsonValue value; if (!BsonTypeMapper.TryMapToBsonValue(entry.Value, out value)) { properties[key] = entry.Value.ToBsonDocument(); } else { properties[key] = value; } } toReturn[FieldNames.Customproperties] = properties; } return(toReturn); }
private IEnumerable <ArrayFilterDefinition <BsonDocument> > ParseArrayFilters(BsonArray arrayFilters) { var arrayFilter = new List <ArrayFilterDefinition <BsonDocument> >(); foreach (var item in arrayFilters) { arrayFilter.Add(item.AsBsonDocument); } return(arrayFilter); }
private bool OrOperator(BsonArray comparisons, BsonDocument doc) => comparisons.Any(c => IsMatch(c.AsBsonDocument, doc));
public void SaveOrUpdate <TEntity>(TEntity entity) where TEntity : class, IEntity, new() { var id = entity.TryGetValue("Id"); if (GetById <TEntity>(id) == null) { Save(entity); return; } var update = new UpdateBuilder(); foreach (var property in typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(r => !r.Name.EqualsWithInvariant("Id"))) { var value = property.GetValue(entity, null); BsonValue bsonValue = BsonNull.Value; if (value != null) { var type = (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) ? property.PropertyType.GetGenericArguments()[0] : property.PropertyType; if (type == typeof(string)) { bsonValue = new BsonString(value.ToString()); } else if (type == typeof(bool)) { bsonValue = new BsonBoolean((bool)value); } else if (type == typeof(DateTime)) { bsonValue = new BsonDateTime((DateTime)value); } else if (type == typeof(long)) { bsonValue = new BsonInt64((long)value); } else if (type == typeof(int)) { bsonValue = new BsonInt32((int)value); } else if (type == typeof(byte[])) { bsonValue = new BsonBinaryData((byte[])value); } else if (type == typeof(Guid)) { bsonValue = new BsonBinaryData((Guid)value); } else if (type.IsEnum) { bsonValue = new BsonString(value.ToString()); } else if (type.IsImplement <IEnumerable>()) { bsonValue = new BsonArray((IEnumerable)value); } else if (type.IsClass && type.IsImplement <IEntity>()) { bsonValue = new BsonDocumentWrapper(value); } else { throw new ArgumentOutOfRangeException("propertyType {0} does not bson value".F(type)); } } update.Set(property.Name, bsonValue); } GetCollection <TEntity>().Update(MongoDB.Driver.Builders.Query <TEntity> .EQ(r => r.Id, id), update); }
/// <summary> /// Read all database pages from v7 structure into a flexible BsonDocument - only read what really needs /// </summary> private BsonDocument ReadPage(uint pageID) { if (pageID * V7_PAGE_SIZE > _stream.Length) { return(null); } _stream.Position = pageID * V7_PAGE_SIZE; // v7 uses 4k page size _stream.Read(_buffer, 0, V7_PAGE_SIZE); // decrypt encrypted page (except header page - header are plain data) if (_aes != null && pageID > 0) { _buffer = _aes.Decrypt(_buffer); } var reader = new ByteReader(_buffer); // reading page header var page = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["pageType"] = (int)reader.ReadByte(), ["prevPageID"] = (int)reader.ReadUInt32(), ["nextPageID"] = (int)reader.ReadUInt32(), ["itemCount"] = (int)reader.ReadUInt16() }; // skip freeByte + reserved reader.ReadBytes(2 + 8); #region Header (1) // read header if (page["pageType"] == 1) { var info = reader.ReadString(27); var ver = reader.ReadByte(); if (string.CompareOrdinal(info, HeaderPage.HEADER_INFO) != 0 || ver != 7) { throw LiteException.InvalidDatabase(); } // skip ChangeID + FreeEmptyPageID + LastPageID reader.ReadBytes(2 + 4 + 4); page["userVersion"] = (int)reader.ReadUInt16(); page["password"] = reader.ReadBytes(20); page["salt"] = reader.ReadBytes(16); page["collections"] = new BsonArray(); var cols = reader.ReadByte(); for (var i = 0; i < cols; i++) { page["collections"].AsArray.Add(new BsonDocument { ["name"] = reader.ReadString(), ["pageID"] = (int)reader.ReadUInt32() }); } } #endregion #region Collection (2) // collection page else if (page["pageType"] == 2) { page["collectionName"] = reader.ReadString(); page["indexes"] = new BsonArray(); reader.ReadBytes(12); for (var i = 0; i < 16; i++) { var index = new BsonDocument(); var field = reader.ReadString(); var eq = field.IndexOf('='); if (eq > 0) { index["name"] = field.Substring(0, eq); index["expression"] = field.Substring(eq + 1); } else { index["name"] = field; index["expression"] = "$." + field; } index["unique"] = reader.ReadBoolean(); index["headPageID"] = (int)reader.ReadUInt32(); // skip HeadNode (index) + TailNode + FreeIndexPageID reader.ReadBytes(2 + 6 + 4); if (field.Length > 0) { page["indexes"].AsArray.Add(index); } } } #endregion #region Index (3) else if (page["pageType"] == 3) { page["nodes"] = new BsonArray(); for (var i = 0; i < page["itemCount"].AsInt32; i++) { var node = new BsonDocument { ["index"] = (int)reader.ReadUInt16() }; var levels = reader.ReadByte(); // skip Slot + PrevNode + NextNode reader.ReadBytes(1 + 6 + 6); var length = reader.ReadUInt16(); // skip DataType + KeyValue reader.ReadBytes(1 + length); node["dataBlock"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // reading Prev[0] node["prev"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // reading Next[0] node["next"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // skip Prev/Next[1..N] reader.ReadBytes((levels - 1) * (6 + 6)); page["nodes"].AsArray.Add(node); } } #endregion #region Data (4) else if (page["pageType"] == 4) { page["blocks"] = new BsonArray(); for (var i = 0; i < page["itemCount"].AsInt32; i++) { var block = new BsonDocument { ["index"] = (int)reader.ReadUInt16(), ["extendPageID"] = (int)reader.ReadUInt32() }; var length = reader.ReadUInt16(); block["data"] = reader.ReadBytes(length); page["blocks"].AsArray.Add(block); } } #endregion #region Extend (5) else if (page["pageType"] == 5) { page["data"] = reader.ReadBytes(page["itemCount"].AsInt32); } #endregion return(page); }
internal BsonDocumentWriterContext(BsonDocumentWriterContext parentContext, ContextType contextType, BsonArray array) { this.parentContext = parentContext; this.contextType = contextType; this.array = array; }
private void AssertChangeStreamDocumentPropertyValuesAgainstBackingDocument(ChangeStreamDocument <BsonDocument> actualDocument) { var backingDocument = actualDocument.BackingDocument; backingDocument.Should().NotBeNull(); var clusterTime = actualDocument.ClusterTime; if (backingDocument.Contains("clusterTime")) { clusterTime.Should().Be(backingDocument["clusterTime"].AsBsonTimestamp); } else { clusterTime.Should().BeNull(); } var operationType = actualDocument.OperationType; operationType.ToString().ToLowerInvariant().Should().Be(backingDocument["operationType"].AsString); if (operationType == ChangeStreamOperationType.Invalidate) { return; } var collectionNamespace = actualDocument.CollectionNamespace; collectionNamespace.DatabaseNamespace.DatabaseName.Should().Be(backingDocument["ns"]["db"].AsString); collectionNamespace.CollectionName.Should().Be(backingDocument["ns"]["coll"].AsString); var documentKey = actualDocument.DocumentKey; if (operationType == ChangeStreamOperationType.Rename || operationType == ChangeStreamOperationType.Drop) { documentKey.Should().BeNull(); } else { documentKey.Should().Be(backingDocument["documentKey"].AsBsonDocument); } var fullDocument = actualDocument.FullDocument; if (backingDocument.Contains("fullDocument")) { fullDocument.Should().Be(backingDocument["fullDocument"].AsBsonDocument); } else { fullDocument.Should().BeNull(); } var resumeToken = actualDocument.ResumeToken; resumeToken.Should().Be(backingDocument["_id"].AsBsonDocument); var updateDescription = actualDocument.UpdateDescription; if (backingDocument.Contains("updateDescription")) { var removedFields = new BsonArray(updateDescription.RemovedFields); removedFields.Should().Be(backingDocument["updateDescription"]["removedFields"].AsBsonArray); updateDescription.UpdatedFields.Should().Be(backingDocument["updateDescription"]["updatedFields"].AsBsonDocument); } else { updateDescription.Should().BeNull(); } }
//private void UpdateSubDocument(BsonDocument parentDocument, string parentDocumentName, BsonDocument document, string parentId) //{ // foreach (BsonElement field in parentDocument) // { // if (field.Name == parentDocumentName) // { // var parentSubDocuments = field.Value as BsonArray; // foreach (BsonDocument parentSubDocument in parentSubDocuments) // { // var a = parentSubDocument["_id"].ToString(); // if (parentSubDocument["_id"].ToString() == parentId) // { // if (parentSubDocument[subDocumentName, null] == null) // { // var newSubDocument = new BsonArray(); // newSubDocument.Add(document); // parentSubDocument.Add(subDocumentName, document); // } // else // { // var subDoc2 = parentSubDocument[subDocumentName].AsBsonArray; // subDoc2.Add(document); // } // } // } // } // } //} public async Task Add(string data, string parentId, string subDocumentName, string parentDocumentName) { var document = BsonSerializer.Deserialize <BsonDocument>(data); document.Add("_id", ObjectId.GenerateNewId()); //var parentDocument = await Get(parentId); var parentDocument = string.IsNullOrEmpty(parentDocumentName) ? await Get(parentId) : await Get(parentId, parentDocumentName); if (string.IsNullOrEmpty(parentDocumentName)) { if (parentDocument[subDocumentName, null] == null) { var documents = new BsonArray(); documents.Add(document); parentDocument.Add(subDocumentName, documents); } else { var subDoc = parentDocument[subDocumentName].AsBsonArray; subDoc.Add(document); } } else { foreach (BsonElement field in parentDocument) { if (field.Name == parentDocumentName) { var parentSubDocuments = field.Value as BsonArray; foreach (BsonDocument parentSubDocument in parentSubDocuments) { var a = parentSubDocument["_id"].ToString(); if (parentSubDocument["_id"].ToString() == parentId) { if (parentSubDocument[subDocumentName, null] == null) { var newSubDocument = new BsonArray(); newSubDocument.Add(document); parentSubDocument.Add(subDocumentName, newSubDocument); } else { var subDoc2 = parentSubDocument[subDocumentName].AsBsonArray; subDoc2.Add(document); } } } } else { var type = field.GetType().ToString(); } } } //var rootId = ObjectId.Parse(parentId); var rootId = parentDocument["_id"].AsObjectId; var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("_id", rootId); var result = await MongoCollection.ReplaceOneAsync(filter, parentDocument); }
private void LoadObjectDefinition(IMongoDatabase database, ObjectDefinitionLookups lookups) { IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("ObjectDefinition"); IAsyncCursor <BsonDocument> mongoCursor = collection.FindSync(new BsonDocument()); while (mongoCursor.MoveNext()) { foreach (BsonDocument item in mongoCursor.Current) { ObjectDefinition objectDefinition = new ObjectDefinition(); objectDefinition.ObjectDefinitionID = BsonHelper.GetGuid(item, "_id"); objectDefinition.ObjectID = BsonHelper.GetString(item, "ObjectID"); objectDefinition.OrganisationID = BsonHelper.GetInteger(item, "OrganisationID"); if (objectDefinition.OrganisationID.HasValue && (objectDefinition.OrganisationID.Value == 0)) { objectDefinition.OrganisationID = null; } objectDefinition.Name = BsonHelper.GetString(item, "Name"); objectDefinition.MIMEType = BsonHelper.GetString(item, "MIMEType"); objectDefinition.Description = BsonHelper.GetString(item, "Description"); objectDefinition.SerialisationName = BsonHelper.GetString(item, "SerialisationName"); objectDefinition.Singleton = BsonHelper.GetBoolean(item, "Singleton"); if (item.Contains("Properties")) { BsonArray array = item["Properties"].AsBsonArray; foreach (BsonValue arrayItem in array) { BsonDocument propertyItem = arrayItem.AsBsonDocument; if (propertyItem != null) { if (objectDefinition.Properties == null) { objectDefinition.Properties = new List <PropertyDefinition>(); } PropertyDefinition property = new PropertyDefinition(); property.PropertyDefinitionID = BsonHelper.GetGuid(propertyItem, "_id"); property.PropertyID = BsonHelper.GetString(propertyItem, "PropertyID"); property.Name = BsonHelper.GetString(propertyItem, "Name"); property.Description = BsonHelper.GetString(propertyItem, "Description"); property.DataType = (TPropertyDataType)propertyItem["DataType"].AsInt32; if (propertyItem.Contains("DataTypeLength")) { property.DataTypeLength = propertyItem["DataTypeLength"].AsInt32; } property.MIMEType = BsonHelper.GetString(propertyItem, "MIMEType"); property.MinValue = BsonHelper.GetString(propertyItem, "MinValue"); property.MaxValue = BsonHelper.GetString(propertyItem, "MaxValue"); property.Units = BsonHelper.GetString(propertyItem, "Units"); property.IsCollection = BsonHelper.GetBoolean(propertyItem, "IsCollection"); property.IsMandatory = BsonHelper.GetBoolean(propertyItem, "IsMandatory"); property.Access = (TAccessRight)propertyItem["Access"].AsInt32; if (propertyItem.Contains("SortOrder")) { property.SortOrder = propertyItem["SortOrder"].AsInt32; } property.SerialisationName = BsonHelper.GetString(propertyItem, "SerialisationName"); property.CollectionItemSerialisationName = BsonHelper.GetString(propertyItem, "CollectionItemSerialisationName"); objectDefinition.Properties.Add(property); } } } lookups.AddObjectDefinition(objectDefinition); } } }
public static BsonDocument get_single_match_result(string str_win, string str_draw, string str_lose) { BsonDocument doc_result = new BsonDocument(); double win = Convert.ToDouble(str_win); double draw = Convert.ToDouble(str_draw); double lose = Convert.ToDouble(str_lose); double count_win = 0; double count_draw = 0; double count_lose = 0; double count_total = 0; double count_return = 0; double persent_win = 0; double persent_draw = 0; double persent_lose = 0; double persent_min = 0; BsonArray doc_array = new BsonArray(); //add ideal document BsonDocument doc_1 = new BsonDocument(); count_win = 1 / win; count_draw = 1 / draw; count_lose = 1 / lose; count_total = count_win + count_draw + count_lose; persent_win = (count_win * win - count_total) / count_total * 100; persent_draw = (count_draw * draw - count_total) / count_total * 100; persent_lose = (count_lose * lose - count_total) / count_total * 100; count_return = double.MaxValue; if ((count_win * win - count_total) < count_return) { count_return = count_win * win - count_total; } if ((count_draw * draw - count_total) < count_return) { count_return = count_draw * draw - count_total; } if ((count_lose * lose - count_total) < count_return) { count_return = count_lose * lose - count_total; } persent_min = double.MaxValue; if (persent_win < persent_min) { persent_min = persent_win; } if (persent_draw < persent_min) { persent_min = persent_draw; } if (persent_lose < persent_min) { persent_min = persent_lose; } doc_1.Add("count_return", Math.Round(count_return, 8).ToString("f8")); doc_1.Add("persent_min", Math.Round(persent_min, 6).ToString("f6")); doc_1.Add("count_ideal", "1"); doc_1.Add("count_actual", Math.Round(count_total, 8).ToString("f8")); doc_1.Add("count_win", Math.Round(count_win, 8).ToString("f8")); doc_1.Add("count_draw", Math.Round(count_draw, 8).ToString("f8")); doc_1.Add("count_lose", Math.Round(count_lose, 8).ToString("f8")); doc_1.Add("persent_win", Math.Round(persent_win, 6).ToString("f6")); doc_1.Add("persent_draw", Math.Round(persent_draw, 6).ToString("f6")); doc_1.Add("persent_lose", Math.Round(persent_lose, 6).ToString("f6")); //add some acture document double[] inputs = new double[] { 50, 100, 200, 500, 1000, 2000, 5000, 10000 }; foreach (double input in inputs) { BsonDocument doc_item = new BsonDocument(); count_win = Math.Round(input / win); count_draw = Math.Round(input / draw); count_lose = Math.Round(input / lose); count_total = count_win + count_draw + count_lose; persent_win = (count_win * win - count_total) / count_total * 100; persent_draw = (count_draw * draw - count_total) / count_total * 100; persent_lose = (count_lose * lose - count_total) / count_total * 100; count_return = double.MaxValue; if ((count_win * win - count_total) < count_return) { count_return = count_win * win - count_total; } if ((count_draw * draw - count_total) < count_return) { count_return = count_draw * draw - count_total; } if ((count_lose * lose - count_total) < count_return) { count_return = count_lose * lose - count_total; } persent_min = double.MaxValue; if (persent_win < persent_min) { persent_min = persent_win; } if (persent_draw < persent_min) { persent_min = persent_draw; } if (persent_lose < persent_min) { persent_min = persent_lose; } doc_item.Add("count_return", Math.Round(count_return, 2).ToString("f2")); doc_item.Add("persent_min", Math.Round(persent_min, 2).ToString("f2")); doc_item.Add("count_ideal", Math.Round(input)); doc_item.Add("count_actual", Math.Round(count_total)); doc_item.Add("count_win", Math.Round(count_win)); doc_item.Add("count_draw", Math.Round(count_draw)); doc_item.Add("count_lose", Math.Round(count_lose)); doc_item.Add("persent_win", Math.Round(persent_win, 2).ToString("f2")); doc_item.Add("persent_draw", Math.Round(persent_draw, 2).ToString("f2")); doc_item.Add("persent_lose", Math.Round(persent_lose, 2).ToString("f2")); doc_array.Add(doc_item); } doc_array.Add(doc_1); doc_result.Add("results", doc_array); doc_result.Add("count_return", doc_array[0]["count_return"].ToString()); doc_result.Add("persent_min", doc_array[0]["persent_min"].ToString()); return(doc_result); }
private bool NotOperator(BsonArray comparisons, BsonDocument doc) => !IsMatch(comparisons.AsBsonDocument, doc);
private void NewFieldMenuItem_Click(object sender, RoutedEventArgs e) { if (InputBoxWindow.ShowDialog("Enter name of new field.", "New field name:", "", out string fieldName) != true) { return; } if (currentDocument.Keys.Contains(fieldName)) { MessageBox.Show(string.Format("Field \"{0}\" already exists!", fieldName), "", MessageBoxButton.OK, MessageBoxImage.Error); return; } var menuItem = sender as MenuItem; BsonValue newValue; switch (menuItem.Header as string) { case "String": newValue = new BsonValue(string.Empty); break; case "Boolean": newValue = new BsonValue(false); break; case "Double": newValue = new BsonValue((double)0); break; case "Int32": newValue = new BsonValue((int)0); break; case "Int64": newValue = new BsonValue((long)0); break; case "DateTime": newValue = new BsonValue(DateTime.MinValue); break; case "Array": newValue = new BsonArray(); break; case "Document": newValue = new BsonDocument(); break; default: throw new Exception("Uknown value type."); } currentDocument.Add(fieldName, newValue); var newField = NewField(fieldName, false); customControls.Add(newField); newField.EditControl.Focus(); ItemsField_SizeChanged(ListItems, null); ListItems.ScrollIntoView(newField); }
/// <summary> /// Joins query clauses with a logical NOR returns all documents that fail to match both clauses. /// </summary> /// <param name="comparisons"></param> /// <param name="doc"></param> /// <returns></returns> private bool NorOperator(BsonArray comparisons, BsonDocument doc) => !comparisons.All(c => IsMatch(c.AsBsonDocument, doc));
/// <summary> /// 确定 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOK_Click(object sender, EventArgs e) { MBsonArray = ArrayPanel.GetBsonArray(); Close(); }
public static Requirement DecodeRequirement(BsonDocument requirementDocument) { string requirementType = requirementDocument.GetValue("type").AsString; if (requirementType == "set_flag") { string flagKey = requirementDocument.GetValue("flag").AsString; return(new SetRequirement(flagKey)); } else if (requirementType == "null_flag") { string flagKey = requirementDocument.GetValue("flag").AsString; return(new NullRequirement(flagKey)); } else if (requirementType == "equals") { string flagKey = requirementDocument.GetValue("flag").AsString; Flag flagValue = DecodeFlag(requirementDocument.GetValue("value")); return(new EqualsRequirement(flagKey, flagValue)); } else if (requirementType == "less_than") { string flagKey = requirementDocument.GetValue("flag").AsString; NumericalFlag flagValue = (NumericalFlag)DecodeFlag(requirementDocument.GetValue("value")); return(new LessThanRequirement(flagKey, flagValue)); } else if (requirementType == "more_than") { string flagKey = requirementDocument.GetValue("flag").AsString; NumericalFlag flagValue = (NumericalFlag)DecodeFlag(requirementDocument.GetValue("value")); return(new MoreThanRequirement(flagKey, flagValue)); } else if (requirementType == "not") { BsonDocument subRequirementDocument = requirementDocument.GetValue("requirement").AsBsonDocument; return(new NotRequirement(DecodeRequirement(subRequirementDocument))); } else if (requirementType == "and") { List <Requirement> requirements = new List <Requirement>(); BsonArray requirementArray = requirementDocument.GetValue("requirements").AsBsonArray; foreach (BsonValue requirementValue in requirementArray) { BsonDocument subRequirementDocument = requirementValue.AsBsonDocument; requirements.Add(DecodeRequirement(requirementDocument)); } return(new AndRequirement(requirements.ToArray())); } else if (requirementType == "or") { List <Requirement> requirements = new List <Requirement>(); BsonArray requirementArray = requirementDocument.GetValue("requirements").AsBsonArray; foreach (BsonValue requirementValue in requirementArray) { BsonDocument subRequirementDocument = requirementValue.AsBsonDocument; requirements.Add(DecodeRequirement(requirementDocument)); } return(new OrRequirement(requirements.ToArray())); } else if (requirementType == "true") { return(new TrueRequirement()); } else { return(new FalseRequirement()); } }
/// <summary> /// /// </summary> /// <param name="appCode">实际应用编码</param> /// <param name="businessModuleId">实际业务模块ID</param> /// <param name="sceneCode">实际场景编码</param> /// <param name="fields">支持用户定制的字段配置</param> /// <param name="sc">上下文</param> /// <returns></returns> public void InitUserMade(string appCode, string businessModuleId, string sceneCode, List <ModelFieldConfig> fields, IServerContext sc) { //var radiusFields = fields.Where(m => m.ControlType == "radiolist" || m.ControlType == "dropdownlist").ToList(); List <ModelFieldConfig> radiusFields = new List <ModelFieldConfig>(); foreach (var item in fields) { if (item.ControlType == "radiolist" || item.ControlType == "dropdownlist") { //BsonDocument config = BsonDocument.Parse(item.ControlConfig); //if (GetValueByBool(config, "IsCustomized")) //{ radiusFields.Add(item); //} } } if (radiusFields.Count > 0) { //从代码表中获取【代码表节点】 List <CodeTableNodeAPIModel> nodes = GetNodes(appCode, sceneCode, sc); if (nodes != null && nodes.Count > 0) { List <CodeTableItemAPIModel> list = GetItems(appCode, businessModuleId, sceneCode, sc); if (list != null) { var nodeItems = from node in nodes join item in list on node.Id equals item.CTId into newItem select new { Code = node.Code, Items = newItem }; foreach (var field in radiusFields) { BsonArray options = new BsonArray(); var tempNodes = nodeItems.Where(m => m.Code == field.FieldCode).ToList(); if (tempNodes != null) { var node = tempNodes.FirstOrDefault(); if (node != null) { var items = node.Items; foreach (var item in items) { options.Add(item.Text); } //替换原有的 BsonDocument controlConfig = BsonDocument.Parse(field.ControlConfig); if (options.Count > 0) { controlConfig.SetElement(new BsonElement("Options", options)); field.ControlConfig = controlConfig.ToJson(); } } } } } } } }
public JsonResult Run() { var meshPath = HttpContext.Current.Server.MapPath($"~/Upload/Model"); // 创建临时目录 var now = DateTime.Now; var path = HttpContext.Current.Server.MapPath($"~/Upload/Model{now.ToString("yyyyMMddHHmmss")}"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // 备份贴图数据表,并清空原数据表 var mongo = new MongoHelper(); var docs = mongo.FindAll(Constant.MeshCollectionName).ToList(); if (docs.Count > 0) { mongo.InsertMany($"{Constant.MeshCollectionName}{now.ToString("yyyyMMddHHmmss")}", docs); } mongo.DeleteAll(Constant.MeshCollectionName); // 读取模型数据表,将文件完美复制到临时目录 for (var i = 0; i < docs.Count; i++) { var doc = docs[i]; // 更新名称 var name = doc["Name"].ToString(); name = StringHelper.RemoveEndNumbersAnd_(name); var pinyin = PinYinHelper.GetTotalPinYin(name); doc["Name"] = name; doc["FirstPinYin"] = new BsonArray(pinyin.FirstPinYin); doc["TotalPinYin"] = new BsonArray(pinyin.TotalPinYin); // 处理Url,并复制文件 var urls = new List <string>(); foreach (var j in doc["Url"].ToString().Split(';')) { urls.Add(j); } HandleUrl(urls.ToArray(), path, ref doc); // 更新路径和时间 var addTime = doc["AddTime"].ToUniversalTime(); var savePath = $"/Upload/Model/{addTime.ToString("yyyyMMddHHmmss")}"; doc["SavePath"] = savePath.ToString(); doc["UpdateTime"] = DateTime.Now; // 添加到Mongo数据表 mongo.InsertOne(Constant.MeshCollectionName, doc); } // 交换正式目录和临时目录 Directory.Move(meshPath, path + "_temp"); Directory.Move(path, meshPath); Directory.Move(path + "_temp", path); // 移除模型目录空文件夹 DirectoryHelper.RemoveEmptyDir(meshPath); return(Json(new { Code = 200, Msg = "Execute sucessfully!" })); }
private void btn_90vs_read_leage_Click(object sender, EventArgs e) { string path = root_path_90vs + "leage.js"; FileStream stream = (FileStream)File.Open(path, FileMode.Open); StreamReader reader = new StreamReader(stream, Encoding.Default); string line = ""; BsonDocument doc_season_x = new BsonDocument(); BsonDocument doc_season = new BsonDocument(); BsonDocument doc_type = new BsonDocument(); BsonDocument doc_test = new BsonDocument(); while (line != null) { line = reader.ReadLine(); if (line != null) { string[] items = line.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); string name = items[0].Replace("var", "").Trim(); string value = items[1].Replace(";", ""); if (name == "test") { doc_test = MongoHelper.get_doc_from_str(get_js_json(value)); } if (name == "season_x") { doc_season_x = MongoHelper.get_doc_from_str(get_js_json(value)); } if (name == "season") { doc_season = MongoHelper.get_doc_from_str(get_js_json(value)); } if (name == "type") { doc_type = MongoHelper.get_doc_from_str(get_js_json(value)); } } } reader.Close(); stream.Close(); int count = 0; foreach (BsonElement element in doc_type.Elements) { BsonArray array_i = element.Value.AsBsonArray; for (int i = 0; i < array_i.Count; i++) { count = count + 1; BsonArray array_j = array_i[i].AsBsonArray; string lg_id = array_j[0].ToString(); string lg_name = array_j[1].ToString(); if (doc_season.Contains(lg_id)) { BsonArray array_k = doc_season[lg_id].AsBsonArray; for (int k = 0; k < array_k.Count; k++) { string season_id = array_k[k].ToString(); string season_name = doc_season_x[season_id].AsBsonArray[0].ToString(); count = count + 1; string url = "http://bf.90vs.com/db/all_season/{1}/{0}.js"; url = string.Format(url, season_id, lg_id); sb.AppendLine(url); } } } } this.txt_result.Text = sb.ToString(); Application.DoEvents(); }
private static Section GetSection(BsonDocument sectionBsonDocument) { Random rnd = new Random(); Section sectObj; string sectionType = sectionBsonDocument.GetValue("SectionType")?.ToString(); Debug.WriteLine("Section Type:" + sectionType); switch (sectionType?.ToLower()) { case "image": ImageSection imgSectObj = BsonSerializer.Deserialize <ImageSection>(sectionBsonDocument); Content imgContent = Contents.GetFor(imgSectObj); if (imgContent != null) { imgSectObj.Title = imgContent.Title; imgSectObj.Caption = imgContent.Caption; } sectObj = imgSectObj; break; case "text": TextSection textSectObj = BsonSerializer.Deserialize <TextSection>(sectionBsonDocument); Content textContent = Contents.GetFor(textSectObj); if (textContent != null) { textSectObj.Text = textContent.SectionText; } sectObj = textSectObj; break; case "graph": GraphSection gphObj = BsonSerializer.Deserialize <GraphSection>(sectionBsonDocument); Content docContent = Contents.GetFor(gphObj); if (docContent != null) { gphObj.Caption = docContent.Caption; gphObj.X.Label = docContent.XLabel; gphObj.Y.Label = docContent.YLabel; } gphObj.CoordinatesSet = new List <Coordinates>(); BsonArray coordinateSetBsonArray = sectionBsonDocument.GetValue("CoordinatesSet").AsBsonArray; if (coordinateSetBsonArray != null) { foreach (BsonDocument coordinateSetBsonDoc in coordinateSetBsonArray) { var coordinateListId = coordinateSetBsonDoc.GetValue("CoordinateListId")?.ToString(); if (!string.IsNullOrWhiteSpace(coordinateListId)) { continue; } var coordinatesObj = new Coordinates() { CoordinateListId = coordinateListId }; var coordinateContent = Contents.GetFor(coordinatesObj); coordinatesObj.LegendName = coordinateContent?.CoordinateListLegend; if (coordinateSetBsonDoc.TryGetValue("CoordinateList", out BsonValue tempCoordinateList)) { BsonArray coordinateListBsonArray = tempCoordinateList?.AsBsonArray; if (coordinateListBsonArray != null) { foreach (BsonDocument coordinateBsonDoc in coordinateListBsonArray) { string x = coordinateBsonDoc.GetValue("X")?.AsString; string y = coordinateBsonDoc.GetValue("Y")?.AsString; string coordinateText = coordinateContent?.CoordinateText; if (string.IsNullOrWhiteSpace(coordinateText)) { coordinatesObj.AddXYCoordinates(x, y); } else { coordinatesObj.AddXYCoordinates(x, y, coordinateText); } Debug.WriteLine(coordinatesObj.ToJson()); } } } gphObj.CoordinatesSet.Add(coordinatesObj); } } sectObj = gphObj; break; case "gif": GifSection gifObj = BsonSerializer.Deserialize <GifSection>(sectionBsonDocument); Content gifContent = Contents.GetFor(gifObj); if (gifContent != null) { gifObj.Title = gifContent.Title; gifObj.Caption = gifContent.Caption; } sectObj = gifObj; break; case "audio": AudioSection audioObj = BsonSerializer.Deserialize <AudioSection>(sectionBsonDocument); Content audioContent = Contents.GetFor(audioObj); if (audioContent != null) { audioObj.Title = audioContent.Title; audioObj.Caption = audioContent.Caption; } sectObj = audioObj; break; case "video": VideoSection videoObj = BsonSerializer.Deserialize <VideoSection>(sectionBsonDocument); Content videoContent = Contents.GetFor(videoObj); if (videoContent != null) { videoObj.Title = videoContent.Title; videoObj.Caption = videoContent.Caption; } sectObj = videoObj; break; case "link": UrlSection urlObj = BsonSerializer.Deserialize <UrlSection>(sectionBsonDocument); sectObj = urlObj; break; case "embeddedhtml": EmbeddedHtmlSection embeddedHtmlObj = BsonSerializer.Deserialize <EmbeddedHtmlSection>(sectionBsonDocument); Content embeddedHtmlContent = Contents.GetFor(embeddedHtmlObj); if (embeddedHtmlContent != null) { embeddedHtmlObj.Title = embeddedHtmlContent.Title; embeddedHtmlObj.Caption = embeddedHtmlContent.Caption; } sectObj = embeddedHtmlObj; break; default: sectObj = null; break; } return(sectObj); }
public static List <ChatNode> RetrieveRecordsFromChatNode() { try { var nodeTemplateCollection = ChatDB.GetCollection <BsonDocument>(Settings.TemplateCollectionName); // Creating Filter for Date Range Greater than Equal to Start Date and Less than End Date FilterDefinitionBuilder <BsonDocument> builder = Builders <BsonDocument> .Filter; var filter = new BsonDocument(); List <BsonDocument> nodeList; // Retrieving records, if no/invalid limit is specified then all records are retrieved otherwise records as per specified limit and offset are retrieved nodeList = nodeTemplateCollection.Find(filter).Project(Builders <BsonDocument> .Projection.Exclude("Sections._t").Exclude("Buttons._t")).ToList(); List <ChatNode> chatNodes = new List <ChatNode>(); foreach (BsonDocument node in nodeList) { try { var chatNode = BsonSerializer.Deserialize <ChatNode>(node); chatNode.Sections = new List <Section>(); chatNode.Buttons = new List <Button>(); //Adding Header Text Content nodeContent = Contents.GetFor(chatNode); if (nodeContent != null) { chatNode.HeaderText = nodeContent.NodeHeaderText; } BsonArray sectionBsonArray = node.GetValue("Sections").AsBsonArray; foreach (BsonDocument sectionBsonDocument in sectionBsonArray) { Section sectObj = GetSection(sectionBsonDocument); chatNode.Sections.Add(sectObj); } BsonArray buttonBsonArray = node.GetValue("Buttons").AsBsonArray; foreach (BsonDocument buttonBsonDocument in buttonBsonArray) { Button btn = BsonSerializer.Deserialize <Button>(buttonBsonDocument); Content buttonContent = Contents.GetFor(btn); btn.ButtonName = buttonContent?.ButtonName; btn.ButtonText = buttonContent?.ButtonText; chatNode.Buttons.Add(btn); } if (node.Contains("IsStartNode") && node["IsStartNode"] != null && (bool)node["IsStartNode"]) { chatNodes.Insert(0, chatNode); } else { chatNodes.Add(chatNode); } } catch (Exception e) { Debug.WriteLine(e); } } return(chatNodes); } catch (Exception e) { Debug.WriteLine(e.Message + "\n" + e.StackTrace); } return(null); }
public String GetRowsReportObjectsReal(List <string> profile = null, Dictionary <string, string> fields = null, Int64 start = 0, Int64 end = 0, string id = null) { var orderfield = "name"; try { string[] arrayprofile = profile.ToArray(); List <string> cols = new List <string>(); if (fields == null || fields.Count() == 0) { cols.Add("name"); cols.Add("location"); cols.Add("EPC"); cols.Add("serie"); cols.Add("CreatedTimeStamp"); } else { foreach (var x in fields) { cols.Add(x.Key); } if (!fields.Keys.Contains("location")) { cols.Add("location"); } cols.Add("CreatedTimeStamp"); } BsonArray bsonarray = new BsonArray(); for (int i = 0; i < arrayprofile.Length; i++) { bsonarray.Add(arrayprofile[i]); } string[] arrayfields = cols.ToArray(); List <BsonDocument> documents = new List <BsonDocument>(); var query = Query.And(Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); if (id != null) { BsonValue idbson = new BsonObjectId(id); query = Query.And(Query.EQ("_id", idbson)); } if (profile != null && profile.Count > 0) { if (id != null) { BsonValue idbson = new BsonObjectId(id); query = Query.And(Query.EQ("_id", idbson)); } else { query = Query.And(Query.In("location", bsonarray), Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); } /* var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); * * * foreach (BsonDocument document in cursor) * { * document.Set("_id", document.GetElement("_id").Value.ToString()); * try * { * document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); * } * catch (Exception ex) * { * * } * documents.Add(document); * }*/ } else { /* var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); * foreach (BsonDocument document in cursor) * { * document.Set("_id", document.GetElement("_id").Value.ToString()); * try * { * document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); * } * catch (Exception ex) * { * * } * documents.Add(document); * }*/ } JoinCollections Join = new JoinCollections(); Join.Select("ObjectReal") .Join("Locations", "location", "_id", "parent=>parent") .Join("ReferenceObjects", "objectReference", "_id", "name=>name,depreciacion=>depreciacion,parentCategory=>parentCategory,marca=>marca,modelo=>modelo,perfil=>perfil,department=>department,proveedor=>proveedor,object_id=>object_id_ref"); //.Join("Deparments", "department", "idDep", "name =>department"); return(Join.Find(query)); //return documents.ToJson(); } catch (Exception e) { // System.Windows.Forms.MessageBox.Show(e.ToString()); return(null); } }
internal static BsonDocument AddCompressorsToCommand(BsonDocument command, IEnumerable <CompressorConfiguration> compressors) { var compressorsArray = new BsonArray(compressors.Select(x => CompressorTypeMapper.ToServerName(x.Type))); return(command.Add("compression", compressorsArray)); }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public void SetValue(BsonValue value) { txtBsonValue.Visible = false; txtBsonValue.Text = string.Empty; txtBsonValue.ReadOnly = false; radTrue.Visible = false; radFalse.Visible = false; radFalse.Checked = true; dateTimePicker.Visible = false; NumberPick.Visible = false; if (value.IsString) { cmbDataType.SelectedIndex = 0; txtBsonValue.Visible = true; txtBsonValue.Text = value.ToString(); } if (value.IsInt32) { cmbDataType.SelectedIndex = 1; NumberPick.Visible = true; NumberPick.Value = value.AsInt32; } if (value.IsValidDateTime) { dateTimePicker.Visible = true; dateTimePicker.Value = value.ToUniversalTime(); cmbDataType.SelectedIndex = 2; } if (value.IsBoolean) { radTrue.Visible = true; radFalse.Visible = true; if (value.AsBoolean) { radTrue.Checked = true; } else { radFalse.Checked = true; } cmbDataType.SelectedIndex = 3; } if (value.IsBsonArray) { var t = GetArray(); if (t != null) { _mBsonArray = t; txtBsonValue.Visible = true; txtBsonValue.Text = _mBsonArray.ToString(); txtBsonValue.ReadOnly = true; cmbDataType.SelectedIndex = 4; } } if (value.IsBsonDocument) { var t = GetDocument(); if (t != null) { _mBsonDocument = t; txtBsonValue.Visible = true; txtBsonValue.Text = _mBsonDocument.ToString(); txtBsonValue.ReadOnly = true; cmbDataType.SelectedIndex = 5; } } }
public void Run( string schemaVersion, BsonArray testSetRunOnRequirements, BsonArray entities, BsonArray initialData, BsonArray runOnRequirements, string skipReason, BsonArray operations, BsonArray expectedEvents, BsonArray outcome, bool async) { if (_runHasBeenCalled) { throw new InvalidOperationException("The test suite has already been run."); } _runHasBeenCalled = true; var schemaSemanticVersion = SemanticVersion.Parse(schemaVersion); if (schemaSemanticVersion < new SemanticVersion(1, 0, 0) || schemaSemanticVersion > new SemanticVersion(1, 4, 0)) { throw new FormatException($"Schema version '{schemaVersion}' is not supported."); } if (testSetRunOnRequirements != null) { RequireServer.Check().RunOn(testSetRunOnRequirements); } if (runOnRequirements != null) { RequireServer.Check().RunOn(runOnRequirements); } if (skipReason != null) { throw new SkipException($"Test skipped because '{skipReason}'."); } KillOpenTransactions(DriverTestConfiguration.Client); _entityMap = new UnifiedEntityMapBuilder(_eventFormatters).Build(entities); if (initialData != null) { AddInitialData(DriverTestConfiguration.Client, initialData); } foreach (var operation in operations) { var cancellationToken = CancellationToken.None; CreateAndRunOperation(operation.AsBsonDocument, async, cancellationToken); } if (expectedEvents != null) { AssertEvents(expectedEvents, _entityMap); } if (outcome != null) { AssertOutcome(DriverTestConfiguration.Client, outcome); } }
private void AssertChangeStreamDocument(ChangeStreamDocument <BsonDocument> actualDocument, BsonDocument expectedDocument) { JsonDrivenHelper.EnsureAllFieldsAreValid(expectedDocument, "_id", "documentKey", "operationType", "ns", "fullDocument", "updateDescription", "to"); AssertChangeStreamDocumentPropertyValuesAgainstBackingDocument(actualDocument); if (expectedDocument.Contains("_id")) { actualDocument.ResumeToken.Should().NotBeNull(); } if (expectedDocument.Contains("documentKey")) { actualDocument.DocumentKey.Should().NotBeNull(); } if (expectedDocument.Contains("operationType")) { var expectedOperationType = (ChangeStreamOperationType)Enum.Parse(typeof(ChangeStreamOperationType), expectedDocument["operationType"].AsString, ignoreCase: true); actualDocument.OperationType.Should().Be(expectedOperationType); } if (expectedDocument.Contains("ns")) { var ns = expectedDocument["ns"].AsBsonDocument; JsonDrivenHelper.EnsureAllFieldsAreValid(ns, "db", "coll"); var expectedDatabaseName = ns["db"].AsString; var expectedCollectionName = ns["coll"].AsString; var expectedCollectionNamespace = new CollectionNamespace(new DatabaseNamespace(expectedDatabaseName), expectedCollectionName); actualDocument.CollectionNamespace.Should().Be(expectedCollectionNamespace); } if (expectedDocument.Contains("fullDocument")) { var actualFullDocument = actualDocument.FullDocument; actualFullDocument.Remove("_id"); var expectedFullDocument = expectedDocument["fullDocument"].AsBsonDocument; actualFullDocument.Should().Be(expectedFullDocument); } if (expectedDocument.Contains("updateDescription")) { var expectedUpdateDescription = expectedDocument["updateDescription"].AsBsonDocument; JsonDrivenHelper.EnsureAllFieldsAreValid(expectedUpdateDescription, "updatedFields", "removedFields"); var actualUpdateDescription = actualDocument.UpdateDescription; actualUpdateDescription.UpdatedFields.Should().Be(expectedUpdateDescription["updatedFields"].AsBsonDocument); if (expectedUpdateDescription.Contains("removedFields")) { var actualRemovedFields = new BsonArray(actualUpdateDescription.RemovedFields); actualRemovedFields.Should().Be(expectedUpdateDescription["removedFields"].AsBsonArray); } } if (expectedDocument.Contains("to")) { var to = expectedDocument["to"].AsBsonDocument; JsonDrivenHelper.EnsureAllFieldsAreValid(to, "db", "coll"); var expectedRenameToDatabaseName = to["db"].AsString; var expectedRenameToCollectionName = to["coll"].AsString; var expectedRenameToCollectionNamespace = new CollectionNamespace(new DatabaseNamespace(expectedRenameToDatabaseName), expectedRenameToCollectionName); actualDocument.RenameTo.Should().Be(expectedRenameToCollectionNamespace); } }
protected virtual List <BsonDocument> ParseExpectedContents(BsonArray data) { return(data.Cast <BsonDocument>().ToList()); }
public void addAlert2UserTest() { WellCastServerEngine mm = new WellCastServerEngine(); User user = new User(); user.ID = "542c53a302d6a4910db3fdd7"; BsonArray forecastIDs = new BsonArray(); string id1 = Guid.NewGuid().ToString(); string id2 = Guid.NewGuid().ToString(); forecastIDs.Add(id1); forecastIDs.Add(id2); MongoDatabase mdb; //Get a Reference to the Client Object var mongoClient = new MongoClient("mongodb://*****:*****@ds041140.mongolab.com:41140/wellcast"); var mongoServer = mongoClient.GetServer(); mdb = mongoServer.GetDatabase("wellcast"); var queryDoc2 = new QueryDocument { { "state", "unsent" } }; // Query the db for a document with the required ID var alertsUnSent0 = mdb.GetCollection("alerts").Find(queryDoc2); long alerts0 = alertsUnSent0.Count(); mm.addAlert2User(user, forecastIDs); var alertsUnSent1 = mdb.GetCollection("alerts").Find(queryDoc2); long alerts1 = alertsUnSent1.Count(); Assert.AreEqual(alerts1, alerts0 + 1); }