public void TestFromDocument() { Document doc = new Document(); doc.Add("string", "test"); doc.Add("int", 1); BsonDocument bdoc = BsonConvert.From(doc); Assert.AreEqual(2,bdoc.Count); /*doc.Add("date", DateTime.MinValue); Assert.Throws<ArgumentOutOfRangeException>( delegate {BsonConvert.From(doc);});*/ //Not in nUnit 2.4. }
/// <summary> /// Converts the dictionary to document. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="document">The document.</param> public static Document ToDocument(this IDictionary<string, object> dictionary) { var document = new Document(); foreach (var kvp in dictionary) { if (kvp.Value is IDictionary<string, object>) { var subDocument = ((IDictionary<string, object>)kvp.Value).ToDocument(); document.Add(kvp.Key, subDocument); } else document.Add(kvp.Key, kvp.Value); } return document; }
public void TestKeyOrderPreservedOnRemove() { Document d = new Document(); d["one"] = 1; d["onepointfive"] = 1.5; d.Add("two", 2); d.Add("two.5", 2.5); d.Remove("two.5"); d["three"] = 3; d.Remove("onepointfive"); int cnt = 1; foreach(String key in d.Keys){ Assert.AreEqual(cnt, d[key]); cnt++; } }
/// <summary> /// Create a Nut for a specific application account and in a specific configuration container. /// </summary> /// <param name="account">The application account we are creating the nut for.</param> /// <param name="container">The container we are inserting the nut into (e.g. connectionstrings, endpoints, appconfig, etc).</param> /// <param name="nut">Busta nut.</param> /// <returns>True if the nut was added and false if it already exists, and therefore was not added/updated.</returns> public static bool CreateNut(string account, string container, Nut nut) { bool nutAdded = false; Mongo mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase(WellKnownDb.AppConfiguration); var collection = db.GetCollection(container); var doc = new Document(); doc["account"] = account; doc["name"] = nut.Key; doc["value"] = nut.Value; if (nut.Properties != null) { foreach (var k in nut.Properties.Keys) { doc.Add(k, nut.Properties[k]); } } if (collection.FindOne(doc) == null) { collection.Insert(doc); nutAdded = true; } return nutAdded; }
public void ReadElement(Document doc) { sbyte typeNum = (sbyte)reader.ReadByte (); position++; String key = ReadString (); Object element = ReadElementType(typeNum); doc.Add (key, element); }
protected QueryMessage generateQueryMessage() { Document qdoc = new Document(); qdoc.Add("listDatabases", 1.0); //QueryMessage qmsg = new QueryMessage(qdoc,"system.namespaces"); QueryMessage qmsg = new QueryMessage(qdoc,"admin.$cmd"); qmsg.NumberToReturn = -1; return qmsg; }
/// <summary> /// Deletes a post from the data store. /// </summary> public override void DeletePost(Post post) { using (var mongo = new MongoDbWr()) { var coll = mongo.BlogDB.GetCollection("posts"); Document spec = new Document(); spec.Add("id", post.Id); coll.Delete(spec); } }
public void TestCopyToCopiesAndOverwritesKeys() { Document d = new Document(); Document dest = new Document(); dest["two"] = 200; d["one"] = 1; d.Add("two", 2); d["three"] = 3; d.CopyTo(dest); Assert.AreEqual(2, dest["two"]); }
public void TestKeyOrderIsPreserved() { Document d = new Document(); d["one"] = 1; d.Add("two", 2); d["three"] = 3; int cnt = 1; foreach(String key in d.Keys){ Assert.AreEqual(cnt, d[key]); cnt++; } }
public void TestClearRemovesAll() { Document d = new Document(); d["one"] = 1; d.Add("two", 2); d["three"] = 3; Assert.AreEqual(3,d.Count); d.Clear(); Assert.AreEqual(0, d.Count); Assert.IsNull(d["one"]); Assert.IsFalse(d.Contains("one")); }
public bool Authenticate(string username, string password) { Document nonceResult = this.SendCommand("getnonce"); String nonce = (String)nonceResult["nonce"]; if (nonce == null){ throw new MongoException("Error retrieving nonce", null); } else { string pwd = Database.Hash(username + ":mongo:" + password); Document auth = new Document(); auth.Add("authenticate", 1.0); auth.Add("user", username); auth.Add("nonce", nonce); auth.Add("key", Database.Hash(nonce + username + pwd)); try{ this.SendCommand(auth); return true; }catch(MongoCommandException){ return false; } } }
public void TestCopyToCopiesAndPreservesKeyOrderToEmptyDoc() { Document d = new Document(); Document dest = new Document(); d["one"] = 1; d.Add("two", 2); d["three"] = 3; d.CopyTo(dest); int cnt = 1; foreach(String key in dest.Keys){ Assert.AreEqual(cnt, d[key]); cnt++; } }
public void TestRoundTrip() { Document idoc = new Document(); idoc.Add("b",new Binary(new byte[]{(byte)1,(byte)2})); MemoryStream stream = new MemoryStream(); BsonWriter writer = new BsonWriter(stream); writer.Write(idoc); stream.Seek(0,SeekOrigin.Begin); BsonReader reader = new BsonReader(stream); Document odoc = reader.Read(); Assert.AreEqual(idoc.ToString(), odoc.ToString()); }
public static Document BuildFromObject(object spec) { Document result = new Document(); if (spec != null) { foreach (var property in spec.GetType().GetProperties()) { if (property.CanRead) { object value = property.GetValue(spec, null); result.Add(property.Name, value ?? MongoDBNull.Value); } } } return result; }
public static void Set(string key, string val) { var doc = new Document { { "key", key } }; var res = AdminParametersCollection.FindOne(doc); if (res == null) { doc.Add("value", val); AdminParametersCollection.Insert(doc); } else { res["value"] = val; AdminParametersCollection.Update(res); } }
/// <summary> /// Retrieves a post based on the specified Id. /// </summary> public override Post SelectPost(Guid id) { Post post; using (var mongo = new MongoDbWr()) { var coll = mongo.BlogDB.GetCollection("settings"); Document spec = new Document(); spec.Add("id", id); Document docPost = coll.FindOne(spec); post = docPost.ToPost(); } return post; }
public void TestRoundTrip() { Document idoc = new Document(); idoc.Add("b",new Binary(new byte[]{(byte)1,(byte)2})); BsonDocument bidoc = BsonConvert.From(idoc); MemoryStream stream = new MemoryStream(); BsonWriter writer = new BsonWriter(stream); bidoc.Write(writer); stream.Seek(0,SeekOrigin.Begin); BsonReader reader = new BsonReader(stream); BsonDocument bodoc = new BsonDocument(); bodoc.Read(reader); Document odoc = (Document) bodoc.ToNative(); Assert.AreEqual(idoc.ToString(), odoc.ToString()); }
private byte[] GetFile(string mongoFilename) { if (!this.Exists) { return null; } byte[] retBuffer = null; System.Security.Cryptography.MD5 sscMD5 = System.Security.Cryptography.MD5.Create(); if (_chunksDocument.Count == 0) { bool closeConnection = false; try { if (this.mongo.Connection.State != ConnectionState.Opened) { this.mongo.Connection.Open(); closeConnection = true; } List<Chunk> chunksList = new List<Chunk>(); Document searcher = new Document(); searcher.Add("files_id", this.Oid); foreach (Document d in chunks.Find(searcher).Documents) { Chunk c = Chunk.CreateFromDocument(d); _chunksDocument.Add(c); } chunksList.Sort(delegate(Chunk a, Chunk b) { if (a == null && b == null) return 0; else if (a == null) return -1; else if (b == null) return 1; else { return a.Number - b.Number; } }); } catch (Exception) { throw; } finally { if (closeConnection) { this.mongo.Connection.Close(); } } } retBuffer = new byte[this.Length]; int destIndex = 0; foreach (Chunk c in _chunksDocument) { byte[] chunkBuffer = c.Data; Array.Copy(chunkBuffer, 0, retBuffer, destIndex, chunkBuffer.Length); destIndex += chunkBuffer.Length; } byte[] mHash = sscMD5.ComputeHash(retBuffer); if (this.MD5 != Convert.ToBase64String(mHash)) { throw new InvalidDataException("Hash MD5 errato per il file '" + mongoFilename + "' dalla collection '" + this.files.FullName + "'"); } return retBuffer; }
private void CreateIndex() { Document d = new Document(); d.Add("name", "file_id_1_n_1"); Document result = mongo.CurrentDB["system.indexes"].FindOne(d); if (result == null) { d.Add("ns", this.chunks.FullName); Document subd = new Document(); subd.Add("file_id", 1); subd.Add("n", 1); d.Add("key", subd); mongo.CurrentDB["system.indexes"].Insert(d); } }
private void ChunkFile(byte[] data, string mongoname, bool overwrite, string contentType) { if (string.IsNullOrEmpty(contentType)) { contentType = "file/undef"; if (mongoname.LastIndexOf('.') > 0) { contentType = "file/" + mongoname.Substring(mongoname.LastIndexOf('.') + 1); } } _chunksDocument.Clear(); System.Security.Cryptography.MD5 sscMD5 = System.Security.Cryptography.MD5.Create(); Document file = null; bool closeConnection = false; try { if (this.mongo.Connection.State != ConnectionState.Opened) { this.mongo.Connection.Open(); closeConnection = true; } file = files.FindOne(this.FileDocument); if (file != null) { if (overwrite) { file["length"] = data.Length; file["contentType"] = contentType; file["uploadDate"] = DateTime.Now; file["chunkSize"] = this.ChunkSize; byte[] mHash = sscMD5.ComputeHash(data); file["md5"] = Convert.ToBase64String(mHash); files.Update(file); Document eraser = new Document(); eraser.Add("files_id", file["_id"]); foreach (Document erased in chunks.Find(eraser).Documents) { chunks.Delete(erased); } if (data.Length <= this.ChunkSize) { Chunk chunk = new Chunk(); chunk.FileID = this.Oid; chunk.Number = 0; chunk.Data = data; _chunksDocument.Add(chunk); } else { int chucksNumbers = data.Length / this.ChunkSize + (data.Length % this.ChunkSize > 0 ? 1 : 0); for (int i = 0; i < chucksNumbers; i++) { byte[] buffer = new byte[i < chucksNumbers - 1 ? this.ChunkSize : data.Length % this.ChunkSize]; Array.Copy(data, i * this.ChunkSize, buffer, 0, buffer.Length); Chunk chunk = new Chunk(); chunk.FileID = this.Oid; chunk.Number = i; chunk.Data = buffer; _chunksDocument.Add(chunk); } } } else { throw new Exception("Il file '" + file["filename"] + " esiste nella collection '" + this.files.FullName + "'"); } } else { file = new Document(); OidGenerator oidg = new OidGenerator(); file.Add("_id", oidg.Generate()); file.Add("contentType", contentType); file.Add("length", data.Length); file.Add("chunkSize", DEFAULT_CHUNKSIZE); file.Add("uploadDate", DateTime.Now); byte[] mHash = sscMD5.ComputeHash(data); file.Add("md5", Convert.ToBase64String(mHash)); files.Insert(file); if (data.Length <= this.ChunkSize) { Chunk chunk = new Chunk(); chunk.FileID = this.Oid; chunk.Number = 0; chunk.Data = data; _chunksDocument.Add(chunk); } else { int chucksNumbers = data.Length / this.ChunkSize + (data.Length % this.ChunkSize > 0 ? 1 : 0); for (int i = 0; i < chucksNumbers; i++) { byte[] buffer = new byte[i < chucksNumbers - 1 ? this.ChunkSize : data.Length % this.ChunkSize]; Array.Copy(data, i * this.ChunkSize, buffer, 0, buffer.Length); Chunk chunk = new Chunk(); chunk.FileID = this.Oid; chunk.Number = i; chunk.Data = buffer; _chunksDocument.Add(chunk); } } } this.CreateIndex(); foreach (Chunk c in _chunksDocument) { chunks.Insert(c.Document); } this.FileDocument = file; } catch (Exception) { throw; } finally { if (closeConnection) { this.mongo.Connection.Close(); } } }
public virtual object DoCheck() { Document commandResults = null; Mongo mongo = null; try { mongo = new Mongo(_connectionString); mongo.Connect(); // In the Linux agent, we get all database names and use the first // one found, but no such functionality exists with this .NET // MongoDB library. Database database = mongo.GetDatabase(DatabaseName); commandResults = database.SendCommand("serverStatus"); } catch (Exception ex) { Log.Error(ex); return null; } finally { if (mongo != null) { mongo.Disconnect(); } } if (commandResults == null) { Log.Warn("MongoDB returned no results for serverStatus command."); Log.Warn("This is possible on older versions of MongoDB."); return null; } Document indexCounters = (Document)commandResults["indexCounters"]; Document btree = null; // Index counters are currently not supported on Windows. if (indexCounters["note"] == null) { btree = (Document)indexCounters["btree"]; } else { // We add a blank document, since the server is expecting // these btree index values to be present. btree = new Document(); indexCounters.Add("btree", btree); btree.Add("accesses", 0); btree.Add("accessesPS", 0); btree.Add("hits", 0); btree.Add("hitsPS", 0); btree.Add("misses", 0); btree.Add("missesPS", 0); btree.Add("missRatio", 0D); btree.Add("missRatioPS", 0); } Document opCounters = (Document)commandResults["opcounters"]; Document asserts = (Document)commandResults["asserts"]; if (_mongoDBStore == null) { Log.Debug("No cached data, so storing for the first time."); btree["accessesPS"] = 0; btree["hitsPS"] = 0; btree["missesPS"] = 0; btree["missRatioPS"] = 0; opCounters.Add("insertPS", 0); opCounters.Add("queryPS", 0); opCounters.Add("updatePS", 0); opCounters.Add("deletePS", 0); opCounters.Add("getmorePS", 0); opCounters.Add("commandPS", 0); asserts.Add("regularPS", 0); asserts.Add("warningPS", 0); asserts.Add("msgPS", 0); asserts.Add("userPS", 0); asserts.Add("rolloversPS", 0); } else { Log.Debug("Cached data exists, so calculating per sec metrics."); Document cachedBtree = (Document)((Document)_mongoDBStore["indexCounters"])["btree"]; Document cachedOpCounters = (Document)_mongoDBStore["opcounters"]; Document cachedAsserts = (Document)commandResults["asserts"]; btree["accessesPS"] = (float)(((int)btree["accesses"] - (int)cachedBtree["accesses"]) / 60); btree["hitsPS"] = (float)(((int)btree["hits"] - (int)cachedBtree["hits"]) / 60); btree["missesPS"] = (float)(((int)btree["misses"] - (int)cachedBtree["misses"]) / 60); btree["missRatioPS"] = (float)(((double)btree["missRatio"] - (double)cachedBtree["missRatio"]) / 60); opCounters.Add("insertPS", (float)(((int)opCounters["insert"] - (int)cachedOpCounters["insert"]) / 60)); opCounters.Add("queryPS", (float)(((int)opCounters["query"] - (int)cachedOpCounters["query"]) / 60)); opCounters.Add("updatePS", (float)(((int)opCounters["update"] - (int)cachedOpCounters["update"]) / 60)); opCounters.Add("deletePS", (float)(((int)opCounters["delete"] - (int)cachedOpCounters["delete"]) / 60)); opCounters.Add("getmorePS", (float)(((int)opCounters["getmore"] - (int)cachedOpCounters["getmore"]) / 60)); opCounters.Add("commandPS", (float)(((int)opCounters["command"] - (int)cachedOpCounters["command"]) / 60)); asserts.Add("regularPS", (float)(((int)asserts["regular"] - (int)cachedAsserts["regular"]) / 60)); asserts.Add("warningPS", (float)(((int)asserts["warning"] - (int)cachedAsserts["warning"]) / 60)); asserts.Add("msgPS", (float)(((int)asserts["msg"] - (int)cachedAsserts["msg"]) / 60)); asserts.Add("userPS", (float)(((int)asserts["user"] - (int)cachedAsserts["user"]) / 60)); asserts.Add("rolloversPS", (float)(((int)asserts["rollovers"] - (int)cachedAsserts["rollovers"]) / 60)); } _mongoDBStore = commandResults; return _mongoDBStore; }
/// <summary> /// Creates the indexes. /// </summary> private void CreateIndexes(Database database) { foreach (var rootClassMap in this.mappingStore.RootClassMaps) { //getting a collection is more expensive than counting indexes, so let's make this as fast as possible... if (rootClassMap.Indexes.Count() == 0) continue; var collectionMetaData = database.GetCollection(rootClassMap.CollectionName).MetaData; foreach (var index in rootClassMap.Indexes) { Document fieldsAndDirections = new Document(); foreach (var part in index.Parts) { fieldsAndDirections.Add( part.Key, part.Value == IndexDirection.Ascending ? 1 : -1); } collectionMetaData.CreateIndex(index.Name, fieldsAndDirections, index.IsUnique); } } }
private static object SerializeMember(object obj) { Type objType = obj.GetType(); switch (Type.GetTypeCode(objType)) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.Char: return obj; case TypeCode.DBNull: return null; case TypeCode.DateTime: case TypeCode.Decimal: case TypeCode.Double: return obj; case TypeCode.Empty: return null; case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return obj; case TypeCode.Object: IEnumerable enumerable = obj as IEnumerable; if (enumerable != null) { List<object> docs = new List<object>(); foreach (var item in enumerable) { docs.Add(SerializeMember(item)); } return docs.ToArray(); } else if (objType.IsEnum) { return obj; } else { var publicProperties = objType.GetProperties(); Document doc = new Document(); for (int i = 0; i < publicProperties.Length; i++) { var property = publicProperties[i]; if (property.GetGetMethod().GetParameters().Length != 0) { continue; } object propertyValue = property.GetValue(obj, null); if (propertyValue == null) { continue; } doc.Add(property.Name, SerializeMember(propertyValue)); } return doc; } case TypeCode.SByte: case TypeCode.Single: case TypeCode.String: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return obj; default: return obj; } }
public void TestValues() { Document d = new Document(); d["one"] = 1; d.Add("two", 2); d["three"] = 3; ICollection vals = d.Values; Assert.AreEqual(3, vals.Count); }
private QueryMessage BuildQueryMessage() { Document query = spec; if (_Special) { query = new Document(); query.Add("query", spec); query.Add("orderby", _OrderBy); } _QueryMessage.Query = BsonConvert.From(query); if (fields != null) _QueryMessage.ReturnFieldSelector = BsonConvert.From(fields); return _QueryMessage; }
protected Document ParseObject(char[] json, ref int index) { Document doc = new Document(); int token; // { NextToken(json, ref index); bool done = false; while(!done) { token = LookAhead(json, index); // if (token == TOKEN_NONE) { // return null; // } else if(token == TOKEN_COMMA) { NextToken(json, ref index); } else if(token == TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return doc; } else { // name string name = ParseString(json, ref index, true); if(name == null) { return null; } // : token = NextToken(json, ref index); if(token != TOKEN_COLON) { return null; } // value bool success = true; object value = ParseValue(json, ref index, ref success); if(!success) { return null; } doc.Add(name, value); } } return doc; }