public void TestInsertDotNotatedRoot() { BsonDocument doc = (BsonDocument)_testDoc.DeepClone(); DestinationColumnInfo ci = new DestinationColumnInfo(); ci.ColumnName = "dbl"; doc.InsertDotNotated(ci, 5.66); Assert.AreEqual(5.66, doc["dbl"]); }
/// <summary> /// The write workload writes a set of documents /// </summary> private static async Task ExecuteWriteWorkloadAsync(MongoClient mongoClient, Guid runGuid) { IMongoDatabase mongoDatabase = mongoClient.GetDatabase(ConfigurationManager.AppSettings["database"]); IMongoCollection <BsonDocument> mongoCollection = mongoDatabase.GetCollection <BsonDocument>(ConfigurationManager.AppSettings["collection"]); ServerDescription primaryServerDescription = mongoClient.Cluster.Description.Servers.First(x => x.Type == ServerType.ReplicaSetPrimary); string region = Helpers.TryGetRegionFromTags(primaryServerDescription.Tags) ?? string.Empty; BsonDocument template = new BsonDocument(new BsonElement("writtenFrom", new BsonString(region))); const int NumToWrite = 100; Console.WriteLine($"Writing {NumToWrite} documents to {region}..."); Stopwatch stopWatch = Stopwatch.StartNew(); for (int i = 0; i < NumToWrite; ++i) { BsonDocument toInsert = (BsonDocument)template.DeepClone(); toInsert["_id"] = new BsonString($"{runGuid}:{i}"); await mongoCollection.InsertOneAsync(toInsert); } Console.WriteLine($"Complete ({stopWatch.ElapsedMilliseconds} milliseconds)."); Console.WriteLine(); }
private BsonDocument PostEntry(BsonDocument source) { var clone = source.DeepClone().AsBsonDocument; if (clone.Contains("_id")) { clone.Remove("_id"); } var client = new RestClient(); client.BaseUrl = new Uri(apiWebsiteURL); var request = new RestRequest($"api/entries", Method.POST); request.AddBody(clone.ToJson(jsonWriterSettings)); var response = client.Execute(request); Assert.IsTrue(response.IsSuccessful); Assert.IsFalse(string.IsNullOrWhiteSpace(response.Content)); var bson = BsonDocument.Parse(response.Content); return(bson); }
private BsonDocument MassageCommand(string commandName, BsonDocument command) { var massagedCommand = (BsonDocument)command.DeepClone(); switch (commandName) { case "delete": massagedCommand["ordered"] = massagedCommand.GetValue("ordered", true); break; case "getMore": massagedCommand["getMore"] = 42L; break; case "insert": massagedCommand["ordered"] = massagedCommand.GetValue("ordered", true); break; case "killCursors": massagedCommand["cursors"][0] = 42L; break; case "update": massagedCommand["ordered"] = massagedCommand.GetValue("ordered", true); break; } massagedCommand.Remove("$clusterTime"); massagedCommand.Remove("lsid"); return(massagedCommand); }
public void InsertMany(int _times) { Stopwatch stopWatch = new Stopwatch(); BsonDocument template = new BsonDocument( new BsonElement("_myid", new BsonString(Guid.NewGuid().ToString())), new BsonElement("writtenTime", new BsonDateTime(DateTime.UtcNow)), new BsonElement("mypartition", new BsonString(Guid.NewGuid().ToString().Substring(0, 2))), #region document payload new BsonElement("writtenText01", new BsonString(Guid.NewGuid().ToString())), new BsonElement("writtenText02", new BsonString(Guid.NewGuid().ToString())) #endregion ); var listWrites = new List <BsonDocument>(); try { stopWatch.Start(); for (int i = 0; i < _times; ++i) { BsonDocument toInsert = (BsonDocument)template.DeepClone(); toInsert.Set("_myid", Guid.NewGuid().ToString()); toInsert.Set("mypartition", Guid.NewGuid().ToString().Substring(0, 2)); listWrites.Add(new BsonDocument(toInsert)); } Console.WriteLine("each thread starting to insert " + listWrites.Count.ToString() + " documents"); mongoCollection.InsertMany(listWrites); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff") + $", thread completed in {stopWatch.ElapsedMilliseconds} milliseconds."); }
protected override IEnumerable <JsonDrivenTestCase> CreateTestCases(BsonDocument document) { var name = GetTestCaseName(document, document, 0); foreach (var async in new[] { false, true }) { var testDecorated = document.DeepClone().AsBsonDocument.Add("async", async); yield return(new JsonDrivenTestCase($"{name}:async={async}", testDecorated, testDecorated)); } }
protected override IEnumerable <JsonDrivenTestCase> CreateTestCases(BsonDocument document) { var index = 0; foreach (var async in new[] { false, true }) { var name = GetTestCaseName(document, document, index); name = $"{name}:async={async}"; var test = document.DeepClone().AsBsonDocument.Add("async", async); yield return(new JsonDrivenTestCase(name, test, test)); } }
protected override void UpdateDocument(BsonDocument document, Func<BsonDocument, UpdateCompiler> update) { var copy = document.DeepClone(); try { update(document); } catch { document.Clear(); document.AddRange(copy.AsBsonDocument); throw; } }
protected override void UpdateDocument(BsonDocument document, Func <BsonDocument, UpdateCompiler> update) { var copy = document.DeepClone(); try { update(document); } catch { document.Clear(); document.AddRange(copy.AsBsonDocument); throw; } }
protected override void RunTest(BsonDocument shared, BsonDocument test, EventCapturer eventCapturer) { Console.WriteLine("dotnet astrolabetestrunner> creating disposable client..."); using (var client = CreateDisposableMongoClient(eventCapturer)) { Console.WriteLine("dotnet astrolabetestrunner> looping until cancellation is requested..."); while (!_cancellationToken.IsCancellationRequested) { // Clone because inserts will auto assign an id to the test case document ExecuteOperations( client: client, objectMap: new Dictionary <string, object>(), test: test.DeepClone().AsBsonDocument); } } }
private void importTxTestData(ExcelWorksheet ws, BsonDocument bson) { if (ws == null || bson == null) { return; } BsonDocument[] bsons = new BsonDocument[4]; // Loop through all cells in 3. row to determine channels for (int c = 1; c <= 12; c++) { if (ws.Rows[2].Cells[c].Value != null && ws.Rows[3].Cells[c].Value != null) { string varname = ws.Rows[2].Cells[c].Value.ToString().Replace(".", "").Trim() + " " + ws.Rows[3].Cells[c].Value.ToString().Replace(".", "").Trim(); BsonArray barray = new BsonArray(); for (int r = 4; r <= 7; r++) { if (bsons[r - 4] == null) { bsons[r - 4] = (BsonDocument)bson.DeepClone(); bsons[r - 4].Add(new BsonElement("_id", Guid.NewGuid().ToString())); bsons[r - 4]["meta"]["Channel"] = r - 4; } if (ws.Rows[r].Cells[c].Value != null && ws.Rows[r].Cells[c].Value.ToString() != "#N/A") { decimal d; if (decimal.TryParse(ws.Rows[r].Cells[c].Value.ToString(), out d)) { if (txmap.Contains(varname)) { varname = txmap[varname].ToString(); } bsons[r - 4]["data"][varname] = decimal.ToDouble(d); } } } } } for (int i = 0; i < 4; i++) { // Console.WriteLine(bsons[i].ToJson(new JsonWriterSettings { Indent = true })); saveDoc(bsons[i]); } }
protected override void UpdateDocument(BsonDocument document, Func <BsonDocument, UpdateCompiler> update) { var oldId = document[MyValue.Id]; var copy = document.DeepClone(); try { update(document); BsonValue newId; if (!document.TryGetValue(MyValue.Id, out newId) || !oldId.Equals(newId)) { throw new InvalidOperationException("Modification of _id is not allowed."); } } catch { document.Clear(); document.AddRange(copy.AsBsonDocument); throw; } }
private BsonDocument MassageReply(string commandName, BsonDocument reply, BsonDocument expectedReply) { var massagedReply = (BsonDocument)reply.DeepClone(); switch (commandName) { case "find": case "getMore": if (massagedReply.Contains("cursor") && massagedReply["cursor"]["id"] != 0L) { massagedReply["cursor"]["id"] = 42L; } break; case "killCursors": massagedReply["cursorsUnknown"][0] = 42L; break; case "delete": case "insert": case "update": if (massagedReply.Contains("writeErrors")) { foreach (BsonDocument writeError in (BsonArray)massagedReply["writeErrors"]) { writeError["code"] = 42; writeError["errmsg"] = ""; writeError.Remove("codeName"); } } break; } // add any fields in the actual reply into the expected reply that don't already exist expectedReply.Merge(reply, false); return(massagedReply); }
private void okay_Click(object sender, EventArgs e) { BsonValue newValue; if (type == BsonType.Array) { switch (comboBox1.SelectedItem) { case "String": newValue = new BsonString(inputValueForArrayElement.Text); break; case "Int32": int i = Convert.ToInt32(inputValueForArrayElement.Text); newValue = new BsonInt32(i); break; case "Document": newValue = new BsonDocument(); break; case "Array": newValue = new BsonArray(); break; default: newValue = null; break; } if (node.Tag is BsonElement) { BsonElement tag = ((BsonElement)node.Tag).DeepClone(); BsonArray arr = (BsonArray)tag.Value; if (newValue != null) { arr.Add(newValue); if (parent is MainForm) { ((MainForm)parent).addElement(node, tag); } else if (parent is ViewCollection) { ((ViewCollection)parent).addElement(node, tag); } } } else if (node.Tag is BsonValue) { BsonValue tag = ((BsonValue)node.Tag).DeepClone(); BsonArray arr = (BsonArray)tag; if (newValue != null) { arr.Add(newValue); if (parent is MainForm) { ((MainForm)parent).addElement(node, tag); } else if (parent is ViewCollection) { ((ViewCollection)parent).addElement(node, tag); } } } } else if (type == BsonType.Document) { switch (comboBox1.SelectedItem) { case "String": newValue = new BsonString(documentPropertyValue.Text); break; case "Int32": int i = Convert.ToInt32(documentPropertyValue.Text); newValue = new BsonInt32(i); break; case "Document": newValue = new BsonDocument(); break; case "Array": newValue = new BsonArray(); break; default: newValue = null; break; } if (node.Tag is BsonDocument) { BsonElement newEl = new BsonElement(documentPropertyName.Text, newValue); BsonDocument tag = (BsonDocument)node.Tag; tag = tag.DeepClone() as BsonDocument; tag.Add(newEl); if (parent is MainForm) { ((MainForm)parent).addElement(node, tag); } else if (parent is ViewCollection) { ((ViewCollection)parent).addElement(node, tag); } } else if (node.Tag is BsonElement) { BsonElement tag = ((BsonElement)node.Tag).DeepClone(); BsonElement newEl = new BsonElement(documentPropertyName.Text, newValue); tag.Value.AsBsonDocument.Add(newEl); if (parent is MainForm) { ((MainForm)parent).addElement(node, tag); } else if (parent is ViewCollection) { ((ViewCollection)parent).addElement(node, tag); } } } Close(); }
public void TestDeepClone() { var document = new BsonDocument("d", new BsonDocument("x", 1)); var clone = (BsonDocument)document.DeepClone(); Assert.AreEqual(clone, document); Assert.AreNotSame(clone["d"], document["d"]); }
private void importRxTestData(ExcelWorksheet ws, BsonDocument bson) { if (ws == null || bson == null) { return; } BsonDocument[] bsons = new BsonDocument[4]; // Loop through all cells in 3. row to determine channels Console.WriteLine(bson["mid"]); for (int c = 1; c < 30; c++) { if (ws.Rows[2].Cells[c].Value != null && ws.Rows[3].Cells[c].Value != null) { int channel = int.Parse(ws.Rows[2].Cells[c].Value.ToString().Replace("Ch", "")); if (bsons[channel] == null) { bsons[channel] = (BsonDocument)bson.DeepClone(); bsons[channel].Add(new BsonElement("_id", Guid.NewGuid().ToString())); bsons[channel]["meta"]["Channel"] = channel; } string varname = ws.Rows[3].Cells[c].Value.ToString().Replace(".", "").Trim(); if (varname == "Q0" || varname == "Q1" || varname == "Q2" || varname == "Q3") { varname = "Q"; } BsonArray barray = new BsonArray(); for (int r = 4; r < 20; r++) { if (ws.Rows[r].Cells[c].Value != null && ws.Rows[r].Cells[c].Value.ToString() != "#N/A") { Console.WriteLine(ws.Rows[r].Cells[c].Value); decimal d; if (decimal.TryParse(ws.Rows[r].Cells[c].Value.ToString(), NumberStyles.AllowExponent | NumberStyles.Float, CultureInfo.InvariantCulture, out d)) { Console.WriteLine(d); barray.Add(decimal.ToDouble(d)); } else { barray.Add(0); } } else { barray.Add(0); } } bsons[channel]["data"][varname] = barray; } } for (int i = 0; i < 4; i++) { if (ws.Rows[26 + i].Cells[2].Value != null) { decimal d; if (decimal.TryParse(ws.Rows[26 + i].Cells[2].Value.ToString(), out d)) { bsons[i]["data"]["CWDM4 sensitivity dBm"] = decimal.ToDouble(d); } } if (ws.Rows[26 + i].Cells[6].Value != null) { decimal d; if (decimal.TryParse(ws.Rows[26 + i].Cells[6].Value.ToString(), out d)) { bsons[i]["data"]["CLR4 sensitivity dBm"] = decimal.ToDouble(d); } } //Console.WriteLine(bsons[i].ToJson(new JsonWriterSettings { Indent = true })); saveDoc(bsons[i]); } }
private void importDcTestData(ExcelWorksheet ws, BsonDocument bson) { if (ws == null || bson == null) { return; } int lastIndex = 0; float f = 0; var list = new ArrayList(); String pattern = @"[-+]?[0-9]*\.?[0-9]*"; // Loop through all cells in 1. and 2. column to determine channels int r = 1; do { Console.WriteLine(bson["mid"]); if (ws.Rows != null && ws.Rows[r].Cells[0].Value != null) { string val0 = ws.Rows[r].Cells[0].Value.ToString().Trim(); object val1 = ws.Rows[r].Cells[1].Value; if (val0.IndexOf("Condition:") >= 0) { var dict = new Dictionary <string, BsonDocument[]> { { "c", new BsonDocument[4] }, { "m", new BsonDocument[1] } }; list.Add(dict); lastIndex = list.Count - 1; for (int i = 0; i < 4; i++) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i] = (BsonDocument)bson.DeepClone(); } ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0] = (BsonDocument)bson.DeepClone(); for (int i = 0; i < 4; i++) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i].Add(new BsonElement("_id", Guid.NewGuid().ToString())); ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["subtype"] = "channel"; ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["meta"]["Channel"] = i; } ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0].Add(new BsonElement("_id", Guid.NewGuid().ToString())); ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["subtype"] = "module"; MatchCollection m = Regex.Matches(val0, pattern); if (m[11].Value != "") { for (int i = 0; i < 4; i++) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["meta"]["SetTemperature_C"] = long.Parse(m[11].Value); } ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["meta"]["SetTemperature_C"] = long.Parse(m[11].Value); } if (m[14].Value != "") { for (int i = 0; i < 4; i++) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["meta"]["SetVoltage"] = float.Parse(m[14].Value); } ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["meta"]["SetVoltage"] = float.Parse(m[14].Value); } } else if (val0 == "Supply current(A)" && val1 != null) { for (int i = 0; i < 4; i++) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["data"]["Current (A)"] = float.Parse(val1.ToString()); } ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["data"]["Current (A)"] = float.Parse(val1.ToString()); } else if (val0 == "Supply voltage(V)" && val1 != null) { } else if (val0.IndexOf("ch.") >= 0 && val1 != null) { MatchCollection m = Regex.Matches(val0, pattern); long i = long.Parse(m[9].Value.Replace(".", "")); if (float.TryParse(val1.ToString(), out f)) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["data"][val0.Replace(" ch." + i.ToString(), "")] = f; } else { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["c"][i]["data"][val0.Replace(" ch." + i.ToString(), "")] = val1.ToString(); } } else if (val1 != null) { if (float.TryParse(val1.ToString(), out f)) { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["data"][val0] = f; } else { ((Dictionary <string, BsonDocument[]>)list[lastIndex])["m"][0]["data"][val0] = val1.ToString(); } } r++; } } while (ws.Rows[r].Cells[0].Value != null); foreach (var item in list) { var dict = (Dictionary <string, BsonDocument[]>)item; foreach (var bc in dict["c"]) { //Console.WriteLine(bc.ToJson(new JsonWriterSettings { Indent = true })); saveDoc(bc); } foreach (var bm in dict["m"]) { //Console.WriteLine(bm.ToJson(new JsonWriterSettings { Indent = true })); saveDoc(bm); } } }
protected override void UpdateDocument(BsonDocument document, Func<BsonDocument, UpdateCompiler> update) { var oldId = document[MyValue.Id]; var copy = document.DeepClone(); try { update(document); BsonValue newId; if (!document.TryGetValue(MyValue.Id, out newId) || !oldId.Equals(newId)) throw new InvalidOperationException("Modification of _id is not allowed."); } catch { document.Clear(); document.AddRange(copy.AsBsonDocument); throw; } }
public BsonDocument DeepClone() { return(_root.DeepClone().AsBsonDocument); }