Пример #1
0
        /// <summary>
        /// obter todos os registros de tipo TType no banco de dados
        /// </summary>
        /// <param name="camposSelect"></param>
        /// <returns></returns>
        public async Task <JsonResult> GetAsync(string[] camposSelect)
        {
            //verifica parâmetros que são de preenchimento obrigatório.
            if (camposSelect == null || camposSelect.Length == 0)
            {
                throw new Exception("Parâmetros inválidos!");
            }

            //conectar no banco de dados.
            CouchClient   couchClient   = new CouchClient(connectionString);
            CouchDatabase couchDataBase = await couchClient.GetDatabaseAsync(dataBase);

            //É preciso informar rquais campos serão retornados na consulta ao CouchDB
            FindBuilder findBuilder = new FindBuilder().Fields(camposSelect);

            //obtem registros em banco de dados.
            CouchResponse couchResponse = await couchDataBase.SelectAsync(findBuilder);

            //valida o status do retorno a consulta ao CouchDB
            if (couchResponse.StatusCode == HttpStatusCode.OK)
            {
                //transforma o resultado em JsonTextReader
                JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(couchResponse.Docs.ToString()));

                //transforma o reader em objeto do tipo TType.
                TType[] result = new JsonSerializer().Deserialize(jsonTextReader, typeof(TType[])) as TType[];

                return(new JsonResult(result));
            }
            else
            {
                //retorna o erro ocorrido durante a pesquisa do CouchDB
                return(new JsonResult(couchResponse.Content));
            }
        }
Пример #2
0
        public static void ToCouchDb(RuntimeStorage intent)
        {
            CouchClient client = new CouchClient();

            if (!client.HasDatabase(DATABASE))
            {
                client.CreateDatabase(DATABASE);
            }

            CouchDatabase     db = client.GetDatabase(DATABASE);
            CouchDbIntentData dbIntent;

            try{
                Document doc = db.GetDocument(intent.filename);
                dbIntent      = new CouchDbIntentData();
                dbIntent.data = intent.data;

                Document <CouchDbIntentData> tosave = new Document <CouchDbIntentData>(dbIntent);
                tosave.Id  = doc.Id;
                tosave.Rev = doc.Rev;
                db.SaveDocument(tosave);
            }catch {
                dbIntent      = new CouchDbIntentData();
                dbIntent.data = intent.data;
                Document <CouchDbIntentData> tosave = new Document <CouchDbIntentData>(dbIntent);
                tosave.Id = intent.filename;

                db.CreateDocument(tosave);
            }
        }
Пример #3
0
 private void DatabaseLoaded(CouchDatabase aDatabase)
 {
     theDatabase = aDatabase;
     theContactsListBox.Database = theDatabase;
     theChangesListBox.Database  = theDatabase;
     theContactDetails.Database  = theDatabase;
 }
Пример #4
0
 private void DatabaseLoaded(CouchDatabase aDatabase)
 {
     theDatabase = aDatabase;
     theContactsListBox.Database = theDatabase;
     theChangesListBox.Database = theDatabase;
     theContactDetails.Database = theDatabase;
 }
Пример #5
0
        public static List <ImageAnnotation> GetAllAnnotationsForImage(string library, string imageId, IBoundingBox region)
        {
            CouchClient client = new CouchClient();

            CouchDatabase db      = GetDatabase(library);
            var           options = new ViewOptions();

            options.Key.Add(imageId);
            options.IncludeDocs = true;

            var cannotations = db.View <CouchDbAnnotation>("by_screenshot", options, "annotations");
            List <ImageAnnotation> annotations = new List <ImageAnnotation>();

            foreach (CouchDbAnnotation ca in cannotations.Items)
            {
                BoundingBox bb = new BoundingBox(ca.left, ca.top, ca.width, ca.height);
                if (BoundingBox.Equals(region, bb))
                {
                    ImageAnnotation ia = new ImageAnnotation(bb, ca.data, ca.screenshotId);
                    annotations.Add(ia);
                }
            }

            return(annotations);
        }
Пример #6
0
		public NotificationManager(ISettingsController aSettingsController){
			theCouchClient = new CouchClient(aSettingsController.Host, aSettingsController.Port, aSettingsController.Username, aSettingsController.Password);
			theCouchDatabase = theCouchClient.GetDatabase(aSettingsController.DatabaseName);
			theOptions = new ChangeOptions();
			theOptions.Heartbeat = 10000;
			theOptions.Since = GetSequence();
		}
Пример #7
0
        public async Task <JsonResult> DeleteAsync(string id, string rev)
        {
            try
            {
                //se não houve campos para serem listados, deverá retornar a lista vazia.
                if (Guid.Equals(id, Guid.Empty))
                {
                    throw new Exception("Parâmetros inválidos!");
                }

                //conectar no banco de dados.
                CouchClient   couchClient   = new CouchClient(connectionString);
                CouchDatabase couchDataBase = await couchClient.GetDatabaseAsync(dataBase);

                //remove o documento.
                CouchResponse couchResponse = await couchDataBase.DeleteAsync(id, rev);

                //verifica se houve a exclusão
                if (couchResponse.StatusCode == HttpStatusCode.Accepted ||
                    couchResponse.StatusCode == HttpStatusCode.OK)
                {
                    return(new JsonResult("Ok"));
                }
                else
                {
                    //retorna o erro ocorrido durante a pesquisa do CouchDB
                    return(new JsonResult(couchResponse.Content));
                }
            }
            catch (Exception ex)
            {
                return(new JsonResult(ex.Message));
            }
        }
Пример #8
0
        public void Should_Trigger_Replication()
        {
            string dbname = "test-replicate-db-created";

            var obj = client.TriggerReplication(new ReplicationOptions(baseDatabase, String.Format("http://{0}:5984/{1}", couchdbHostName, replicateDatabase))
            {
                Continuous = true
            });

            Assert.IsTrue(obj != null);

            var obj2 = client.TriggerReplication(new ReplicationOptions(baseDatabase, dbname)
            {
                CreateTarget = true
            });

            Assert.IsTrue(obj2 != null);

            CouchDatabase db = client.GetDatabase(dbname, false);

            Assert.IsNotNull(db);

            client.DeleteDatabase(dbname);
            db = client.GetDatabase(dbname, false);
            Assert.IsNull(db);
        }
Пример #9
0
        public CouchRepository()
        {
            CouchClient client = new CouchClient("admin", "lnzldn");
            var         db     = client.GetDatabase(DB_NAME);

            _db = db;
        }
Пример #10
0
        public CouchDBService()
        {
            // connect to Cloudant
            client = new CouchClient("unieurocorn.cloudant.com", 443, "hermstaredgeshoreseembel", "36nDB1aax4CgOBgflrFgIpPU", true, AuthenticationType.Basic);

            database = client.GetDatabase("submissions");

            var settings   = new JsonSerializerSettings();
            var converters = new List <JsonConverter> {
                new IsoDateTimeConverter()
            };

            settings.Converters        = converters;
            settings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
            settings.NullValueHandling = NullValueHandling.Ignore;
            var doc = new
            {
                _id      = "_design/" + designDoc,
                Language = "javascript",
                Views    = new
                {
                    byDocType = new
                    {
                        Map = "function(doc) {\n  emit(doc.docType, doc);\n}"
                    }
                }
            };
            var res = database.CreateDocument(doc._id, JsonConvert.SerializeObject(doc, Formatting.Indented, settings));

            database.SetDefaultDesignDoc(designDoc);
        }
Пример #11
0
        public static ImageAnnotation AddAnnotation(string library, Bitmap image, IBoundingBox region, JObject data)
        {
            CouchDatabase   db    = GetDatabase(library);
            string          imgid = AddImage(db, image);
            ImageAnnotation toAdd = new ImageAnnotation(region, data, imgid);

            if (HasDocument(db, toAdd.Id))
            {
                throw new InvalidOperationException("There already exists an annotation for this image with this location. Retreive that annotation and update its data accordingly.");
            }

            CouchDbAnnotation ca = new CouchDbAnnotation();

            ca.data         = toAdd.Data;
            ca.top          = toAdd.Region.Top;
            ca.left         = toAdd.Region.Left;
            ca.width        = toAdd.Region.Width;
            ca.height       = toAdd.Region.Height;
            ca.screenshotId = toAdd.ImageId;
            ca.type         = "annotation";
            Document <CouchDbAnnotation> document = new Document <CouchDbAnnotation>(ca);

            document.Id = toAdd.Id;
            db.CreateDocument(document);


            return(toAdd);
        }
Пример #12
0
        public void BeforeEach()
        {
            couch = new Couch("localhost", 5984);

            // use my own routines -- even though I would be using my own code as a testing predicate,
            // bugs would still cause obvious failures, and I would only have to use a small slice of my code

            SallyFixture = new Person {Name = "Sally Acorn", Id = "sally", DocumentType = "Person"};
            HayekFixture = new Person {Name = "Frederich Hayek", DocumentType = "Person"}; // hayek gets a generated Id

            PersonFixtures = new List<Person>() {
                SallyFixture,
                HayekFixture
            };
            couch.EnsureDatabaseDeleted(TEST_DATABASE).Wait();
            couch.EnsureDatabaseDeleted(CREATION_TEST_DATABASE).Wait();
            couch.CreateDatabase(TEST_DATABASE).Wait();

            var dbOpenTask = couch.OpenDatabase(TEST_DATABASE);
            dbOpenTask.Wait();
            TestDatabase = dbOpenTask.Result;

            foreach (var personFixture in PersonFixtures) {
                TestDatabase.CreateDocument<Person>(personFixture).Wait();
            }
        }
Пример #13
0
        public static Guid?SignUp(string email, string password)
        {
            CouchDatabase db  = couchClient.GetDatabase("dokuku");
            Account       acc = db.GetDocument <Account>(email);

            if (acc != null)
            {
                throw new ApplicationException(String.Format("{0} sudah terdaftar", acc._id));
            }

            Document <Account> account = new Document <Account>(new Account
            {
                _id      = email,
                Guid     = Guid.NewGuid(),
                Email    = email,
                Password = password,
                Roles    = new string[2] {
                    OWNER_ROLE, ADMIN_ROLE
                },
                Type = ACCOUNT_TYPE
            });

            db.CreateDocument(account);

            return(ValidateUser(email, password));
        }
Пример #14
0
        public static void Delete(string library, string id)
        {
            CouchDatabase db = GetDatabase(library);
            Document      ca = db.GetDocument(id);

            db.DeleteDocument(ca.Id, ca.Rev);
        }
Пример #15
0
        public async Task Changes()
        {
            using (var client = new CouchClient("http://localhost:5984"))
            {
                IEnumerable <string> dbs = await client.GetDatabasesNamesAsync().ConfigureAwait(false);

                CouchDatabase <Rebel> rebels = client.GetDatabase <Rebel>();

                if (dbs.Contains(rebels.Database))
                {
                    await client.DeleteDatabaseAsync <Rebel>().ConfigureAwait(false);
                }

                rebels = await client.CreateDatabaseAsync <Rebel>().ConfigureAwait(false);

                Rebel luke = await rebels.CreateAsync(new Rebel { Name = "Luke", Age = 19 }).ConfigureAwait(false);

                Assert.Equal("Luke", luke.Name);

                var options = new ChangesFeedOptions
                {
                    IncludeDocs = true
                };
                var filter        = ChangesFeedFilter.Selector <Rebel>(r => r.Name == "Luke" && r.Age == 19);
                var changesResult = await rebels.GetChangesAsync(options, filter);

                Assert.NotEmpty(changesResult.Results);
                Assert.Equal(changesResult.Results[0].Id, luke.Id);

                await client.DeleteDatabaseAsync <Rebel>().ConfigureAwait(false);
            }
        }
Пример #16
0
        public async Task Users()
        {
            using (var client = new CouchClient("http://localhost:5984"))
            {
                IEnumerable <string> dbs = await client.GetDatabasesNamesAsync().ConfigureAwait(false);

                CouchDatabase <CouchUser> users = client.GetUsersDatabase();

                if (!dbs.Contains(users.Database))
                {
                    users = await client.CreateDatabaseAsync <CouchUser>().ConfigureAwait(false);
                }

                CouchUser luke = await users.CreateAsync(new CouchUser(name : "luke", password : "******")).ConfigureAwait(false);

                Assert.Equal("luke", luke.Name);

                luke = await users.FindAsync(luke.Id).ConfigureAwait(false);

                Assert.Equal("luke", luke.Name);

                await users.DeleteAsync(luke).ConfigureAwait(false);

                luke = await users.FindAsync(luke.Id).ConfigureAwait(false);

                Assert.Null(luke);

                await client.DeleteDatabaseAsync <CouchUser>().ConfigureAwait(false);
            }
        }
Пример #17
0
        protected void UpdateWithMergeConflicts(JToken offer, CouchDatabase dbOffers)
        {
            var result = dbOffers.UpdateAsync(offer).Result;

            if (result.StatusCode == System.Net.HttpStatusCode.Conflict)
            {
                var offerNewer = dbOffers.GetAsync(offer.GetString("_id")).Result.Json;

                var offerObje     = offer.ToObject <Offer>();
                var offerNewerObj = offer.ToObject <Offer>();

                offerObje.ListProduct.ToList().ForEach(x => {
                    if (offerNewerObj.ListProduct.FirstOrDefault(y => y.Guid == x.Guid) != null)
                    {
                        x.ListUserCoupon = x.ListUserCoupon.Concat(offerNewerObj.ListProduct.FirstOrDefault(y => y.Guid == x.Guid).ListUserCoupon)
                                           .GroupBy(y => y.UserEmail)
                                           .Select(y => y
                                                   .OrderBy(z => z.IsDelivered)
                                                   .ThenByDescending(z => z.DateChange)
                                                   .First()).ToList();
                    }
                });
                offerObje.ListProduct.Union(offerNewerObj.ListProduct).GroupBy(x => x.Guid).Select(x => x.First()).ToList();

                offer         = JToken.FromObject(offerObje);
                offer["_rev"] = offerNewer["_rev"];

                UpdateWithMergeConflicts(offer, dbOffers);
            }
        }
Пример #18
0
 public void SetUp()
 {
     var host = ConfigurationManager.AppSettings["CouchHost"] ?? "localhost";
     var port = Convert.ToInt32(ConfigurationManager.AppSettings["CouchPort"] ?? "5984");
     server = new CouchServer(host, port);
     db = server.GetNewDatabase(DbName);
 }
Пример #19
0
        public void RunUpdate()
        {
            var db      = new CouchDatabase(new Uri("http://localhost:5984/tmp"));
            var updater = new DesignDocUpdater(db, "couch_views");

            updater.UpdateIfNecessary();
        }
Пример #20
0
        public static Guid?SignUp(string email, string password)
        {
            CouchDatabase        db    = couchClient.GetDatabase("dokuku");
            ViewResult <Account> users = db.View <Account>("all_accounts", "view_accounts");
            var userRecord             = users.Items.Where(usr => usr.Email == email).FirstOrDefault();

            if (userRecord != null)
            {
                throw new ApplicationException(String.Format("{0} sudah terdaftar", userRecord.Email));
            }

            Document <Account> account = new Document <Account>(new Account
            {
                _id      = Guid.NewGuid(),
                Email    = email,
                Password = password,
                Roles    = new string[2] {
                    OWNER_ROLE, ADMIN_ROLE
                },
                Type = ACCOUNT_TYPE
            });

            db.CreateDocument(account);

            return(ValidateUser(email, password));
        }
Пример #21
0
 public void Connect()
 {
     _client = new CouchClient(ConfigurationManager.AppSettings["DbIpAddress"], 5984, "user", "password", false, AuthenticationType.Basic);
     FlushDb();
     _client.CreateDatabase("test");
     _db = _client.GetDatabase("test");
     _db.SetDefaultDesignDoc("docs");
 }
Пример #22
0
        public Item GetItem(string name)
        {
            CouchClient couchClient = new CouchClient("192.168.1.100", 5984, null, null);

            CouchDatabase db  = couchClient.GetDatabase(itemsDB);
            JDocument     doc = db.GetDocument <JDocument>(name);

            return(Item.FromJson(doc.ToString()));
        }
Пример #23
0
        public Account GetAccount(string email)
        {
            CouchClient couchClient = new CouchClient("192.168.1.100", 5984, null, null);

            CouchDatabase db  = couchClient.GetDatabase(accountsDB);
            JDocument     doc = db.GetDocument <JDocument>(email);

            return(Account.FromJson(doc.ToString()));
        }
Пример #24
0
        public async Task Attachment()
        {
            using (var client = new CouchClient("http://*****:*****@"{runningPath}\Assets\luke.txt", MediaTypeNames.Text.Plain);
                luke = await rebels.CreateAsync(luke).ConfigureAwait(false);

                Assert.Equal("Luke", luke.Name);
                Assert.NotEmpty(luke.Attachments);

                CouchAttachment attachment = luke.Attachments.First();
                Assert.NotNull(attachment);
                Assert.NotNull(attachment.Uri);

                // Download
                var downloadFilePath = await rebels.DownloadAttachment(attachment, $@"{runningPath}\Assets", "luke-downloaded.txt");

                Assert.True(File.Exists(downloadFilePath));
                File.Delete(downloadFilePath);

                // Find
                luke = await rebels.FindAsync(luke.Id).ConfigureAwait(false);

                Assert.Equal(19, luke.Age);
                attachment = luke.Attachments.First();
                Assert.NotNull(attachment);
                Assert.NotNull(attachment.Uri);
                Assert.NotNull(attachment.Digest);
                Assert.NotNull(attachment.Length);

                // Update
                luke.Surname = "Skywalker";
                luke         = await rebels.CreateOrUpdateAsync(luke).ConfigureAwait(false);

                Assert.Equal("Skywalker", luke.Surname);

                await client.DeleteDatabaseAsync <Rebel>().ConfigureAwait(false);
            }
        }
Пример #25
0
        public void WriteSale(Sale sale)
        {
            CouchClient couchClient = new CouchClient("192.168.1.100", 5984, null, null);

            CouchDatabase db = couchClient.GetDatabase(salesDB);

            db.CreateDocument(Serialize.ToJson(sale));

            couchClient = null;
        }
Пример #26
0
        public static IUserIdentity GetUserFromUsername(string username)
        {
            CouchDatabase db  = couchClient.GetDatabase("dokuku");
            Account       acc = db.GetDocument <Account>(username);

            return(acc == null
                       ? null
                       : new UserIdentity {
                UserName = acc._id, Claims = acc.Roles
            });
        }
Пример #27
0
        public static Guid?ValidateUser(string email, string password)
        {
            CouchDatabase db  = couchClient.GetDatabase("dokuku");
            Account       acc = db.GetDocument <Account>(email);

            if (acc == null)
            {
                return(null);
            }
            return(acc.Guid);
        }
Пример #28
0
        public static AccountUser GetAccountByUsername(string username)
        {
            CouchDatabase db      = couchClient.GetDatabase("dokuku");
            AccountUser   accUser = db.GetDocument <AccountUser>(username);

            if (accUser == null)
            {
                accUser.CompanyId = username;
            }
            return(accUser);
        }
Пример #29
0
        /// <summary>
        /// Get's the user.
        /// </summary>
        /// <param name="aUserId"></param>
        /// <returns></returns>
        public JDocument GetUser(string aUserId)
        {
            if (String.IsNullOrEmpty(aUserId))
            {
                throw new ArgumentException("aUser cannot be null nor empty");
            }

            var db = new CouchDatabase(BasePlug.At("_users"));

            aUserId = "org.couchdb.user:" + HttpUtility.UrlEncode(aUserId);
            return(db.GetDocument(aUserId, new Result <JDocument>()).Wait());
        }
Пример #30
0
        public void Setup()
        {
            client = new CouchClient(host, port, username, password, false, AuthenticationType.Cookie);
            if (!client.HasDatabase(baseDatabase))
            {
                client.CreateDatabase(baseDatabase);
            }

            var uriBuilder = new UriBuilder("http", host, port, baseDatabase);

            db = new CouchDatabase(uriBuilder.Uri);
        }
Пример #31
0
        public IUserIdentity GetUserFromIdentifier(Guid identifier)
        {
            CouchDatabase        db    = couchClient.GetDatabase("dokuku");
            ViewResult <Account> users = db.View <Account>("all_accounts", "view_accounts");
            var userRecord             = users.Items.Where(acc => acc.Guid == identifier).FirstOrDefault();

            return(userRecord == null
                       ? null
                       : new UserIdentity {
                UserName = userRecord.Email, Claims = userRecord.Roles
            });
        }
Пример #32
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            NSError error;

            window = new UIWindow(UIScreen.MainScreen.Bounds);
            window.MakeKeyAndVisible();
            dvc = new DialogViewController(new RootElement("CouchDemo")
            {
                new Section("Welcome")
            });
            window.RootViewController = new UINavigationController(dvc);

            server = new CouchTouchDBServer();
            if (server.Error != null)
            {
                Console.WriteLine("Error with the code: {0}", server.Error);
            }
            database = server.GetDatabase("grocery-sync");
            database.EnsureCreated(out error);
            database.TracksChanges = true;

            //
            // Create a view with documents sorted by date
            //
            design = database.DesignDocumentWithName("grocery");
            design.DefineView("byDate", (doc, emit) => {
                var date = doc ["created_at"];
                if (date != null)
                {
                    emit(date, doc);
                }
            }, "1.0");

            // Validation function requiring parseable dates
            design.SetValidationBlock((newRevision, context) => {
                if (newRevision.Deleted)
                {
                    return(true);
                }
                var date = newRevision.Properties ["created_at"];
                if (date != null && RestBody.DateWithJSONObject(date) == null)
                {
                    context.ErrorMessage = "Invalid date";
                    return(false);
                }
                return(true);
            });

            AddNewItem();

            return(true);
        }
Пример #33
0
        public void Should_Return_View_Results()
        {
            CouchDatabase db = client.GetDatabase(baseDatabase);

            db.CreateDocument(new JDocument());
            db.CreateDocument(new JDocument());
            db.CreateDocument(new JDocument());

            ViewResult <string, JObject> result = db.GetView("testviewitem", "testview", new Result <ViewResult <string, JObject> >()).Wait();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.TotalRows > 0);
        }
Пример #34
0
        public void Should_Return_View_Results_As_JObject()
        {
            CouchDatabase db = client.GetDatabase(baseDatabase);

            db.CreateDocument(new JDocument());
            db.CreateDocument(new JDocument());
            db.CreateDocument(new JDocument());

            JObject result = db.GetView("testviewitem", "testview", new Result <JObject>()).Wait();

            Assert.IsNotNull(result);
            Assert.IsNotNull(result["rows"]);
        }
Пример #35
0
        public static void UpdateDesignDocuments(CouchDatabase db)
        {
            var view = new CouchDesignDocument("explosionview");
            foreach (var pair in views)
            {
                var processed = pair.Value.Replace("$MODEL_NAME", typeof(Note).Name);
                view.Views.Add(pair.Key, new CouchView(processed));
            }

            db.CreateDocument(view, new Result<CouchDesignDocument>()).WhenDone((designDocument) => {
                Console.Out.WriteLine("Successfully written design doc!");
            }, (designDocumentError) => {
                Console.Out.WriteLine("Hah, couldn't write design doc: " + designDocumentError.Message);
            });
        }
Пример #36
0
        public void SetUp()
        {
            var host = ConfigurationManager.AppSettings["CouchHost"] ?? "localhost";
            var port = Convert.ToInt32(ConfigurationManager.AppSettings["CouchPort"] ?? "5984");
            server = new CouchServer(host, port);
            db = server.GetNewDatabase(DbName);
            Car car = null;

            for (int i = 0; i < 10; i++)
            {
                car = new Car("Saab", "93", 170 + i);
                db.SaveDocument(car);
            }
            tempView = db.NewTempView("test", "test", "if (doc.docType && doc.docType == 'car') emit(doc.Hps, doc);");
        }
Пример #37
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            NSError error;

            window = new UIWindow (UIScreen.MainScreen.Bounds);
            window.MakeKeyAndVisible ();
            dvc = new DialogViewController (new RootElement ("CouchDemo") {
                new Section ("Welcome")
            });
            window.RootViewController = new UINavigationController (dvc);

            server = new CouchTouchDBServer ();
            if (server.Error != null){
                Console.WriteLine ("Error with the code: {0}", server.Error);
            }
            database = server.GetDatabase ("grocery-sync");
            database.EnsureCreated (out error);
            database.TracksChanges = true;

            //
            // Create a view with documents sorted by date
            //
            design = database.DesignDocumentWithName ("grocery");
            design.DefineView ("byDate", (doc,emit) => {
                var date = doc ["created_at"];
                if (date != null)
                    emit (date, doc);
            }, "1.0");

            // Validation function requiring parseable dates
            design.SetValidationBlock ((newRevision,context)=>{
                if (newRevision.Deleted)
                    return true;
                var date = newRevision.Properties ["created_at"];
                if (date != null && RestBody.DateWithJSONObject (date) == null){
                    context.ErrorMessage = "Invalid date";
                    return false;
                }
                return true;
            });

            AddNewItem ();

            return true;
        }
Пример #38
0
        /// <summary>
        /// Processes the expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="db">The db.</param>
        /// <param name="definition">The view definition.</param>
        /// <returns></returns>
        public ExpressionVisitor ProcessExpression(Expression expression, CouchDatabase db, CouchViewDefinition definition)
        {
            Query = db.Query(definition);
            VisitExpression(expression);

            switch (keys.Count)
            {
                case 0: // 0 keys means it's a range query. do nothing.
                    break;
                case 1: // 1 key means it's a single Equals or a Contains on a single.
                    Query.Key(keys[0]);
                    break;
                default: // neither 0 nor 1 means that we've got a set of keys to test.
                    Query.Keys(keys);
                    break;
            }

            return this;
        }
Пример #39
0
 public override IReconcilingDocument GetDatabaseCopy(CouchDatabase db)
 {
     return db.GetDocument<Car>(Id);
 }
Пример #40
0
 /// <summary>
 /// Processes the expression.
 /// </summary>
 /// <param name="expression">The expression.</param>
 /// <param name="db">The db.</param>
 /// <param name="design">The name of the design document.</param>
 /// <param name="view">The name of the view.</param>
 /// <returns></returns>
 public ExpressionVisitor ProcessExpression(Expression expression, CouchDatabase db, string design, string view)
 {
     Query = db.Query(design, view);
     VisitExpression(expression);
     return this;
 }
Пример #41
0
 public virtual IReconcilingDocument GetDatabaseCopy(CouchDatabase db)
 {
     return db.GetDocument<CouchDocument>(Id);
 }
Пример #42
0
 /// <summary>
 /// Get's the user.  
 /// </summary>
 /// <param name="userId"></param>
 /// <returns></returns>
 public Document GetUser(string userId)
 {
     var db = new CouchDatabase(baseUri, "_users", username, password, this.authType);
     userId = "org.couchdb.user:" + HttpUtility.UrlEncode(userId);
     return db.GetDocument(userId);
 }
Пример #43
0
 private static string AddImage(CouchDatabase db, Bitmap image)
 {
     string imgid = ImageAnnotation.GetImageId(image);
     if (!HasDocument(db, imgid))
     {
         JObject imgJson = new JObject();
         imgJson["_id"] = imgid;
         imgJson["type"] = "screenshot";
         Document doc = new Document(imgJson);
         db.CreateDocument(doc);
         System.Drawing.Bitmap bmp = Bitmap.ToSystemDrawingBitmap(image);
         ImageConverter converter = new ImageConverter();
         byte[] imgbytes = (byte[])converter.ConvertTo(bmp, typeof(byte[]));
         
         db.AddAttachment(imgid, imgbytes, "image", "image/png");
     }
     return imgid;
 }
        public void CreateDatabase()
        {
            _client = new CouchClient(
            host: ConfigurationManager.AppSettings["Host"],
            port: Int32.Parse(ConfigurationManager.AppSettings["Port"]),
            username: ConfigurationManager.AppSettings["Username"],
            password: ConfigurationManager.AppSettings["Password"]
              );

              DeleteDatabase();
              _db = _client.GetDatabase(BASE_DB);
        }
Пример #45
0
 private bool Exists(CouchDatabase database)
 {
     return database != null && Exists(database.Name);
 }
Пример #46
0
        public ICouchServerResponse BeginDatabaseCompact(CouchDatabase database)
        {
            if(database == null)
            {
                throw new ArgumentNullException("database");
            }

            if (EnableValidation)
            {
                if (!Exists(database))
                {
                    throw new CouchDatabaseNotFoundException(database.Name);
                }
            }

            var path = string.Format("{0}/_compact", database.Name);
            var response = Connection.Post(path, null);

            return new CouchServerResponse(response);
        }
Пример #47
0
 public CouchDbConnection(CouchDatabase couchDatabase)
 {
     _couchDatabase = couchDatabase;
     ConnectionString = couchDatabase.ServerUrl;
 }
Пример #48
0
 public void RunUpdate()
 {
     var db = new CouchDatabase(new Uri("http://localhost:5984/tmp"));
     var updater = new DesignDocUpdater(db, "couch_views");
     updater.UpdateIfNecessary();
 }
Пример #49
0
 /// <summary>
 /// Get's the user.  
 /// </summary>
 /// <param name="userId"></param>
 /// <returns></returns>
 public Document GetUser(string userId)
 {
     var db = new CouchDatabase(couchConnection);
     userId = "org.couchdb.user:" + HttpUtility.UrlEncode(userId);
     return db.GetDocument(userId);
 }
Пример #50
0
 public SummonerProducer(CouchClient db)
 {
     _summoners = db.GetDatabase(DatabaseName);
     _summoners.SetDefaultDesignDoc(IndexName);
 }
Пример #51
0
        private static bool HasDocument(CouchDatabase db, string id)
        {
            Document d = null;
            try
            {
                d = db.GetDocument(id);
            }
            catch { }

            if (d == null)
                return false;

            return true;
        }
Пример #52
0
 public DesignDocUpdater(CouchDatabase db, string filePath)
 {
     this.db = db;
     this.filePath = filePath;
 }
Пример #53
0
        /// <summary>
        /// Get's the user.
        /// </summary>
        /// <param name="aUserId"></param>
        /// <returns></returns>
        public JDocument GetUser(string aUserId)
        {
            if (String.IsNullOrEmpty(aUserId))
                throw new ArgumentException("aUser cannot be null nor empty");

            var db = new CouchDatabase(BasePlug.At("_users"));
            aUserId = "org.couchdb.user:" + HttpUtility.UrlEncode(aUserId);
            return db.GetDocument(aUserId, new Result<JDocument>()).Wait();
        }