Description of Document.
Inheritance: System.Collections.DictionaryBase
Esempio n. 1
1
 public static DBRef FromDocument(Document doc)
 {
     if(IsDocumentDBRef(doc) == false) throw new ArgumentException("Document is not a DBRef");
     DBRef ret = new DBRef();
     ret.CollectionName = (String)doc["$ref"];
     ret.Id = (String)doc["$id"];
     return ret;
 }
        public void ShouldReturnAllDataFromCollection()
        {
            //Given
            Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017"));
            db.Connect();
            IMongoCollection collection = db["test"]["folks"];
            Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } };
            Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            collection.Insert(doc1);
            collection.Insert(doc2);
            collection.Insert(doc3);
            var queryProvider = new MongoDbCSharpQuery();

            try
            {
                //When
                IEnumerable data = queryProvider.RunQuery("localhost", "test", "27017", "folks");

                int numberOfRows = 0;
                foreach (var row in data) numberOfRows++;

                //Then
                Assert.AreEqual(3, numberOfRows);
            }
            finally
            {
                //Clean Up
                collection.Delete(doc1);
                collection.Delete(doc2);
                collection.Delete(doc3);
                queryProvider.Dispose();
            }
        }
Esempio n. 3
0
 public GridChunk(Document doc)
 {
     this.id = (Oid)doc["_id"];
     this.filesId = (Object)doc["files_id"];
     this.n = Convert.ToInt32(doc["n"]);
     this.data = (Binary)doc["data"];
 }
        public void ShouldCopyDataToClipboard()
        {
            //Given
            DictionaryBase doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            DictionaryBase doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            IList<DictionaryBase> documents = new List<DictionaryBase>() { doc1, doc3 };
            IMongoQuery query = MockRepository.GenerateStub<IMongoQuery>();
            query.Stub(q => q.RunQuery("localhost", "test", "27017", "folks:this.middle_initial == 'Q'")).Return(documents);
            IMongoQueryFactory queryFactory = MockRepository.GenerateStub<IMongoQueryFactory>();
            queryFactory.Stub(factory => factory.BuildQuery()).Return(query);
            IClipboardService clipboardService = MockRepository.GenerateMock<IClipboardService>();
            IUserMessageService messageService = MockRepository.GenerateMock<IUserMessageService>();

            MainViewModel viewModel = new MainViewModel(queryFactory)
                                          {
                                              Server = "localhost",
                                              Database = "test",
                                              Port = "27017",
                                              Query = "folks:this.middle_initial == 'Q'",
                                              ClipboardService = clipboardService,
                                              UserMessageService = messageService
                                          };

            //When
            viewModel.RunQueryCommand.Execute(null);
            viewModel.CopyToClipboardCommand.Execute(null);

            //Then
            clipboardService.AssertWasCalled(clipboard => clipboard.SetText(
                                                              "last_name\tfirst_name\tmiddle_initial\taddress\tcity\t\r\nJackson\tBill\tQ\t744 Nottingham St.\t\t\r\nWeasly\tRonald\tQ\t\tSanta Rosa\t\r\n"));
            messageService.AssertWasCalled(service => service.ShowMessage("Results copied to clipboard"));
        }
        public async Task<Document> Post(Document document)
        {
            document.Key = ObjectId.GenerateNewId().ToString();
            await _documents.InsertOneAsync(document);

            return document;
        }
        /// <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;
        }
Esempio n. 7
0
 public void TestEvalWithScope()
 {
     int val = 3;
     Document scope = new Document().Append("x",val);
     Document result = db.Eval("function(){return x;}", scope);
     Assert.AreEqual(val, result["retval"]);
 }
        public void ShouldReturnCollectionsFromDatabase()
        {
            //Given
            Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017"));
            db.Connect();
            IMongoCollection collection = db["test"]["folks"];
            Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } };
            Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            collection.Insert(doc1);
            collection.Insert(doc2);
            collection.Insert(doc3);
            var queryProvider = new MongoDbCSharpQuery();

            try
            {
                //When
                IList<string> collections = queryProvider.GetCollections("localhost", "test", "27017");

                //Then
                Assert.IsNotNull(collections.Where(c => c == "folks").SingleOrDefault());
            }
            finally
            {
                //Clean Up
                collection.Delete(doc1);
                collection.Delete(doc2);
                collection.Delete(doc3);
                queryProvider.Dispose();
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoWhereClauseExpressionTreeVisitor"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 private ProjectionBuilder(IMappingStore mappingStore, ParameterExpression documentParameter)
 {
     this.mappingStore = mappingStore;
     this.resultObjectMappingParameter = documentParameter;
     this.fields = new Document();
     this.memberNames = new Stack<string>();
 }
        public void ShouldPullInDataFromQueryProvider()
        {
            //Given
            DictionaryBase doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            DictionaryBase doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            IList<DictionaryBase> documents = new List<DictionaryBase>() {doc1, doc3};
            IMongoQuery query = MockRepository.GenerateStub<IMongoQuery>();
            query.Stub(q => q.RunQuery("localhost", "test", "27017", "folks:this.middle_initial == 'Q'")).Return(documents);
            IMongoQueryFactory queryFactory = MockRepository.GenerateStub<IMongoQueryFactory>();
            queryFactory.Stub(factory => factory.BuildQuery()).Return(query);

            MainViewModel viewModel = new MainViewModel()
            {
                Server = "localhost", Database = "test", Port = "27017",
                Query = "folks:this.middle_initial == 'Q'",
                MongoQueryFactory = queryFactory
            };

            //When
            viewModel.RunQueryCommand.Execute(null);

            //Then
            Assert.AreEqual(2, viewModel.Items.Count);
            Assert.AreEqual(5, viewModel.Headers.Count);
        }
Esempio n. 11
0
 public void TestRemove()
 {
     Document d = new Document();
     d["one"] = 1;
     d.Remove("one");
     Assert.IsFalse(d.Contains("one"));
 }
Esempio n. 12
0
        /// <summary>
        /// Copies one file to another.  The destination file must not exist or an IOException will be thrown.
        /// </summary>
        /// <exception cref="FileNotFoundException">Source file not found.</exception>
        /// <exception cref="IOException">Destination file already exists.</exception>
        /// <exception cref="MongoCommandException">A database error occurred executing the copy function.</exception>
        public void Copy(String src, String dest)
        {
            if(Exists(src) == false) throw new FileNotFoundException("Not found in the database.", src);
            if(Exists(dest) == true) throw new IOException("Destination file already exists.");

            Document scope = new Document().Append("bucket", this.name).Append("srcfile", src).Append("destfile",dest);
            String func ="function(){\n" +
                            //"   print(\"copying \" + srcfile);\n" +
                            "   var files = db[bucket + \".files\"];\n" +
                            "   var chunks = db[bucket + \".chunks\"];\n" +
                            "   var srcdoc = files.findOne({filename:srcfile});\n" +
                            //"   return srcdoc; \n" +
                            "   if(srcdoc != undefined){\n" +
                            "       var srcid = srcdoc._id;\n" +
                            "       var newid = ObjectId();\n" +
                            "       srcdoc._id = newid\n" +
                            "       srcdoc.filename = destfile;\n" +
                            "       files.insert(srcdoc);\n" +
                            "       chunks.find({files_id:srcid}).forEach(function(chunk){\n" +
                            //"           print(\"copying chunk...\");\n" +
                            "           chunk._id = ObjectId();\n" +
                            "           chunk.files_id = newid;\n" +
                            "           chunks.insert(chunk);\n" +
                            "       });\n" +
                            "       return true;\n" +
                            "   }\n" +
                            "   return false;\n" +
                            "}";
            Document result = db.Eval(func,scope);
        }
        public override void SaveToDataStore(BlogEngine.Core.DataStore.ExtensionType exType, string exId, object settings)
        {
            XmlSerializer xs = new XmlSerializer(settings.GetType());
            string objectXML = string.Empty;
            using (StringWriter sw = new StringWriter())
            {
                xs.Serialize(sw, settings);
                objectXML = sw.ToString();
            }

            using (var mongo = new MongoDbWr())
            {
                var coll = mongo.BlogDB.GetCollection("DataStoreSettings");

                Document spec = new Document();
                spec["ExtensionType"] = exType;
                spec["ExtensionId"] = exId;

                var res = new Document();
                res["Settings"] = objectXML;
                res["ExtensionType"] = exType;
                res["ExtensionId"] = exId;

                coll.Update(res, spec, UpdateFlags.Upsert);
            }
        }
Esempio n. 14
0
 public DBRef(Document doc)
 {
     if(IsDocumentDBRef(doc) == false) throw new ArgumentException("Document is not a valid DBRef");
     collectionName = (String)doc[DBRef.RefName];
     id = doc[DBRef.IdName];
     this.doc = doc;
 }
        public void TestBuilderSetsAllProperties()
        {
            Document query = new Document().Append("x",1);
            Document scope = new Document().Append("y",2);
            Document sort = new Document().Append("z",3);
            MapReduceBuilder mrb = mrcol.MapReduceBuilder();
            mrb.Map(mapfunction)
                    .Reduce(reducefunction)
                    .KeepTemp(true)
                    .Limit(5)
                    .Out("outtest")
                    .Query(query)
                    .Scope(scope)
                    .Sort(sort)
                    .Verbose(false);

            MapReduce mr = mrb.MapReduce;
            Assert.AreEqual(query.ToString(), mr.Query.ToString());
            Assert.AreEqual(scope.ToString(), mr.Scope.ToString());
            Assert.AreEqual(sort.ToString(), mr.Sort.ToString());
            Assert.AreEqual(true, mr.KeepTemp);
            Assert.AreEqual(5, mr.Limit);
            Assert.AreEqual("outtest", mr.Out);
            Assert.AreEqual(false, mr.Verbose);
        }
Esempio n. 16
0
 public void DocumentConstructorTest()
 {
     string key = string.Empty; // TODO: Initialize to an appropriate value
     object value = null; // TODO: Initialize to an appropriate value
     Document target = new Document(key, value);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Esempio n. 17
0
 public Collection CreateCollection(String name, Document options)
 {
     Document cmd = new Document();
     cmd.Append("create", name).Update(options);
     db.SendCommand(cmd);
     return new Collection(name, connection, this.name);
 }
Esempio n. 18
0
 public void TestCanAddAFunctionDoc()
 {
     string name = "fadddoc";
     Code func = new Code("function(x, y){return x + y;}");
     Document doc = new Document().Append("_id", name).Append("value", func);
     js.Add(doc);
     Assert.IsNotNull(js[name]);
 }
Esempio n. 19
0
 /// <summary>
 /// Удаляем статус с заданным Id
 /// </summary>
 /// <param name="Id">Id статуса</param>
 public static void DeleteStatus(string Id)
 {
     ConnectToMongo();
     var docstatus = new Document();
     docstatus["_id"] = Id;
     db["test"]["statuses"].Delete(docstatus);
     DisconnectWithMongo();
 }
        public void TestCreateCollectionWithInvalidOptions()
        {
            Document options = new Document().Append("invalidoption",true);
            DB.MetaData.CreateCollection("createdinvalid",options);

            List<String> names = DB.GetCollectionNames();
            Assert.IsTrue(names.Contains("tests.createdinvalid"));
        }
Esempio n. 21
0
 public void TestCanAddFunctionByAssignment()
 {
     string name = "fassignadd";
     Code func = new Code("function(x,y){return x + y;}");
     Document doc = new Document().Append("_id", name).Append("value", func);
     js[name] = doc;
     Assert.IsNotNull(js[name]);
 }
Esempio n. 22
0
 public void ReadElement(Document doc)
 {
     sbyte typeNum = (sbyte)reader.ReadByte ();
     position++;
     String key = ReadString ();
     Object element = ReadElementType(typeNum);
     doc.Add (key, element);
 }
        public void TestCreateCollectionWithOptions()
        {
            Document options = new Document().Append("capped",true).Append("size",10000);
            DB.MetaData.CreateCollection("createdcapped",options);

            List<String> names = DB.GetCollectionNames();
            Assert.IsTrue(names.Contains("tests.createdcapped"));
        }
Esempio n. 24
0
        public void TestCalculateSizeOfEmptyDoc()
        {
            Document doc = new Document();
            MemoryStream ms = new MemoryStream();
            BsonWriter writer = new BsonWriter(ms);

            Assert.AreEqual(5,writer.CalculateSize(doc));
        }
Esempio n. 25
0
 /// <summary>
 /// Constructs a DBRef from a document that matches the DBref specification.
 /// </summary>
 public DBRef(Document document)
 {
     if(IsDocumentDBRef(document) == false) throw new ArgumentException("Document is not a valid DBRef");
     collectionName = (String)document[RefName];
     id = document[IdName];
     this.document = document;
     if(document.Contains("metadata")) this.MetaData = (Document)document["metadata"];
 }
Esempio n. 26
0
 /// <summary>
 /// TODO Fix any accidental reordering issues.
 /// </summary>
 /// <param name="dest"></param>
 public void CopyTo(Document dest)
 {
     foreach (String key in orderedKeys) {
         if (dest.Contains (key))
             dest.Remove (key);
         dest[key] = this[key];
     }
 }
 public MongoQuerySpec(Document query, int limit, int skip, Document fields, Document sortOrder, bool isFirstCall)
 {
     Query = query;
     Limit = limit;
     Skip = skip;
     Fields = fields;
     SortOrder = sortOrder;
     IsFirstCall = isFirstCall;
 }
Esempio n. 28
0
 /// <summary>
 /// Удаляем информацию о пользователе
 /// </summary>
 /// <param name="Id">
 /// в качестве параметра передаем Id юзера
 /// </param>
 public static void DeleteUser(string Id)
 {
     ConnectToMongo();
     var docuser = new Document();
     ///заполняем _id и удаляем запись
     docuser["_id"] = Id;
     db["test"]["users"].Delete(docuser);
     DisconnectWithMongo();
 }
Esempio n. 29
0
        public void TestFromDocument()
        {
            String colname = "tests";
            String id = "32312312";
            Document doc = new Document().Append(DBRef.RefName,colname).Append(DBRef.IdName,id);

            DBRef expected = new DBRef(colname, id);
            Assert.AreEqual(expected, DBRef.FromDocument(doc));
        }
Esempio n. 30
0
 public Cursor(Connection conn, String fullCollectionName, Document spec, int limit, int skip, Document fields)
     : this(conn,fullCollectionName)
 {
     if(spec == null)spec = new Document();
     this.spec = spec;
     this.limit = limit;
     this.skip = skip;
     this.fields = fields;
 }