Пример #1
0
        public static Document CreateDocumentWithProperties(Database db, IDictionary<String, Object> properties)
		{
            var doc = db.CreateDocument();

			Assert.IsNotNull(doc);
			Assert.IsNull(doc.CurrentRevisionId);
			Assert.IsNull(doc.CurrentRevision);
			Assert.IsNotNull("Document has no ID", doc.Id);

			// 'untitled' docs are no longer untitled (8/10/12)
			try
			{
				doc.PutProperties(properties);
			}
			catch (Exception e)
			{
				Log.E(Tag, "Error creating document", e);
                Assert.IsTrue( false, "can't create new document in db:" + db.Name +
                    " with properties:" + properties.Aggregate(new StringBuilder(" >>> "), (str, kvp)=> { str.AppendFormat("'{0}:{1}' ", kvp.Key, kvp.Value); return str; }, str=>str.ToString()));
			}

			Assert.IsNotNull(doc.Id);
			Assert.IsNotNull(doc.CurrentRevisionId);
			Assert.IsNotNull(doc.UserProperties);
			Assert.AreEqual(db.GetDocument(doc.Id), doc);

			return doc;
		}
Пример #2
0
		internal ValidationContextImpl(Database database, RevisionInternal currentRevision
			, RevisionInternal newRev)
		{
			this.database = database;
			this.currentRevision = currentRevision;
			this.newRev = newRev;
		}
 public static Query GetQuery(Database database, string listDocId)
 {
     View view = database.GetView(ViewName);
     if (view.Map == null)
     {
         view.Map += (IDictionary<string, object> document, EmitDelegate emitter)=> 
         {
             if (Task.DocType.Equals(document.Get("type")))
             {
                 var keys = new AList<object>();
                 keys.AddItem(document.Get("list_id"));
                 keys.AddItem(document.Get("created_at"));
                 emitter(keys, document);
             }
         };
     }
     Query query = view.CreateQuery();
     query.Descending = true;
     IList<object> startKeys = new AList<object>();
     startKeys.AddItem(listDocId);
     startKeys.AddItem(new Dictionary<string, object>());
     IList<object> endKeys = new AList<object>();
     endKeys.AddItem(listDocId);
     query.StartKey = startKeys;
     query.EndKey = endKeys;
     return query;
 }
Пример #4
0
		/// <summary>Constructor</summary>
        public Pusher(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory
            , TaskFactory workExecutor) : base(db, remote, continuous, clientFactory
			, workExecutor)
		{
			CreateTarget = false;
			observing = false;
		}
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static Couchbase.Lite.Document CreateTask(Database database, string title, 
     Bitmap image, string listId)
 {
     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
         );
     Calendar calendar = GregorianCalendar.GetInstance();
     string currentTimeString = dateFormatter.Format(calendar.GetTime());
     IDictionary<string, object> properties = new Dictionary<string, object>();
     properties.Put("type", DocType);
     properties.Put("title", title);
     properties.Put("checked", false);
     properties.Put("created_at", currentTimeString);
     properties.Put("list_id", listId);
     Couchbase.Lite.Document document = database.CreateDocument();
     UnsavedRevision revision = document.CreateRevision();
     revision.SetUserProperties(properties);
     if (image != null)
     {
         ByteArrayOutputStream @out = new ByteArrayOutputStream();
         image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
         ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
         revision.SetAttachment("image", "image/jpg", @in);
     }
     revision.Save();
     return document;
 }
 public RevisionInternal(Body body, Database database) : this((string)body.GetPropertyForKey
     ("_id"), (string)body.GetPropertyForKey("_rev"), (((bool)body.GetPropertyForKey(
     "_deleted") != null) && ((bool)body.GetPropertyForKey("_deleted") == true)), database
     )
 {
     this.body = body;
 }
Пример #7
0
 internal View(Database database, String name)
 {
     Database = database;
     Name = name;
     _id = -1;
     // means 'unknown'
     Collation = ViewCollation.Unicode;
 }
Пример #8
0
        static ConversationDatabase()
        {
            conversations = new List<Conversation> ();

            database = Manager.SharedInstance.GetDatabase ("conversations");

            LoadConversations ();
        }
Пример #9
0
        /// <summary>
        /// Deserializes a <c>Document</c>
        /// </summary>
        /// <returns>A new object deserialized.</returns>
        /// <param name="db">The <c>Database</c> where the Document is stored.</param>
        /// <param name="doc">The document to deserialize.</param>
        /// <param name = "serializer">The serializer to use when deserializing the object</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        internal static object DeserializeObject(Type type, Document doc, Database db,
		                                          IDReferenceResolver resolver = null)
        {
            JObject jo = JObject.FromObject (doc.Properties);
            JsonSerializer serializer = GetSerializer (type, doc.CurrentRevision, db,
                                            resolver, GetLocalTypes (type));
            return jo.ToObject (type, serializer);
        }
Пример #10
0
		internal View(Database database, string name)
		{
			this.database = database;
			this.name = name;
			this.viewId = -1;
			// means 'unknown'
			this.collation = View.TDViewCollation.TDViewCollationUnicode;
		}
 public RemoteMultipartRequest(ScheduledExecutorService workExecutor, HttpClientFactory
      clientFactory, string method, Uri url, MultipartEntity multiPart, Database db, 
     IDictionary<string, object> requestHeaders, RemoteRequestCompletionBlock onCompletion
     ) : base(workExecutor, clientFactory, method, url, null, db, requestHeaders, onCompletion
     )
 {
     this.multiPart = multiPart;
 }
Пример #12
0
		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		private RevisionInternal PutDoc(Database db, IDictionary<string, object> props)
		{
			RevisionInternal rev = new RevisionInternal(props, db);
			Status status = new Status();
			rev = db.PutRevision(rev, null, false, status);
			NUnit.Framework.Assert.IsTrue(status.IsSuccessful());
			return rev;
		}
Пример #13
0
 static Conversation()
 {
     database = Manager.SharedInstance.GetDatabase ("conversations");
     defaultView = database.GetView ("conversation-messages");
     defaultView.SetMap ((document, emit) => {
         //
     }, "1");
 }
 public RevisionInternal(String docId, String revId, Boolean deleted, Database database)
 {
     // TODO: get rid of this field!
     this.docId = docId;
     this.revId = revId;
     this.deleted = deleted;
     this.database = database;
 }
Пример #15
0
        static Database()
        {
            // Suppress Couchbase logging.
            var tmp = Console.Out;

            Console.SetOut(TextWriter.Null);
            Db = Manager.SharedInstance.GetDatabase(DATABASE_NAME);
            Console.SetOut(tmp);
        }
Пример #16
0
        public static Task CreateDocumentsAsync(Database db, int n)
		{
            return db.RunAsync((database)=>
                {
                    database.BeginTransaction();
                    ApiTest.CreateDocuments(database, n);
                    database.EndTransaction(true);
                });
		}
Пример #17
0
 internal Query(Database database, View view)
 {
     // null for _all_docs query
     Database = database;
     View = view;
     Limit = Int32.MaxValue;
     MapOnly = (view != null && view.Reduce == null);
     IndexUpdateMode = IndexUpdateMode.Before;
     AllDocsMode = AllDocsMode.AllDocs;
 }
Пример #18
0
 public static Query GetQuery(Database database, string ignoreUserId)
 {
     View view = database.GetView(ViewName);
     if (view.GetMap() == null)
     {
         Mapper map = new _Mapper_30(ignoreUserId);
         view.SetMap(map, null);
     }
     Query query = view.CreateQuery();
     return query;
 }
Пример #19
0
  		public static void CreateDocuments(Database db, int numberOfDocsToCreate)
		{
			//TODO should be changed to use db.runInTransaction
			for (int i = 0; i < numberOfDocsToCreate; i++)
			{
                var properties = new Dictionary<String, Object>();
                properties["testName"] = "testDatabase";
                properties["sequence"] = i;
				CreateDocumentWithProperties(db, properties);
			}
		}
Пример #20
0
 public static Query GetQueryById(Database database, string userId)
 {
     View view = database.GetView(ByIdViewName);
     if (view.GetMap() == null)
     {
         Mapper map = new _Mapper_52();
         view.SetMap(map, null);
     }
     Query query = view.CreateQuery();
     IList<object> keys = new AList<object>();
     keys.AddItem(userId);
     query.SetKeys(keys);
     return query;
 }
Пример #21
0
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static Couchbase.Lite.Document CreateNewList(Database database, string title, string userId)
 {
     var dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
     var calendar = Calendar.CurrentEra;
     string currentTimeString = dateFormatter.Format(calendar.GetTime());
     IDictionary<string, object> properties = new Dictionary<string, object>();
     properties.Put("type", "list");
     properties.Put("title", title);
     properties.Put("created_at", currentTimeString);
     properties.Put("owner", "profile:" + userId);
     properties.Put("members", new AList<string>());
     Couchbase.Lite.Document document = database.CreateDocument();
     document.PutProperties(properties);
     return document;
 }
Пример #22
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     SetContentView(Resource.Layout.Main);
     db2          = Manager.SharedInstance.GetDatabase("dbase");///test code
     messagesList = new List <MessageModel>();
     db           = new DbStorage();
     FindViews();
     HandleEvents();
     messagesList.Clear();
     // messagesList= db.GetItems();
     GetItems();
     mListView.Adapter = new MessagesAdapter(this, messagesList);
     StartSync();
 }
Пример #23
0
 public static void SaveObject(IStorable obj, Database db, IDReferenceResolver resolver = null)
 {
     Document doc = db.GetDocument (obj.ID.ToString ());
     doc.Update ((UnsavedRevision rev) => {
         JObject jo = SerializeObject (obj, rev, db, resolver);
         IDictionary<string, object> props = jo.ToObject<IDictionary<string, object>> ();
         /* SetProperties sets a new properties dictionary, removing the attachments we
              * added in the serialization */
         if (rev.Properties.ContainsKey ("_attachments")) {
             props ["_attachments"] = rev.Properties ["_attachments"];
         }
         rev.SetProperties (props);
         return true;
     });
 }
		void CreateDatabase ()
		{
			_db = Manager.SharedInstance.GetExistingDatabase (DATABASE_NAME);

			if (_db == null)
			{
				var assembly = Assembly.GetCallingAssembly ();
				var resourceName = assembly.GetManifestResourceNames ().Where (x => x.EndsWith ("couchbase-connect.cblite", StringComparison.CurrentCultureIgnoreCase)).Single ();
				Console.WriteLine ("resourceName: {0}", resourceName);
				var stream = assembly.GetManifestResourceStream (resourceName);
				Console.WriteLine ("Stream length: {0}", stream.Length);
				Manager.SharedInstance.ReplaceDatabase (DATABASE_NAME, stream, null);
				_db = Manager.SharedInstance.GetExistingDatabase (DATABASE_NAME);
			}	
		}
        public static IDictionary<string, object> ReadToDatabase(IEnumerable<byte> data, IDictionary<string, string> headers, 
            Database db)
        {
            var realized = data.ToArray();
            if (realized.Length == 0) {
                throw new CouchbaseLiteException(StatusCode.BadJson);
            }

            var reader = new MultipartDocumentReader(db);
            reader.SetHeaders(headers);
            reader.AppendData(data);
            reader.Finish();

            return reader.document;
        }
Пример #26
0
 public static Query GetQuery(Database database)
 {
     View view = database.GetView(ViewName);
     if (view.Map == null)
     {
         view.Map += (IDictionary<string, object> document, EmitDelegate emitter) =>
         {
             string type = (string)document.Get("type");
             if (List.DocType.Equals(type))
             {
                 emitter(document.Get("title"), document);
             }
         };
     }
     Query query = view.CreateQuery();
     return query;
 }
Пример #27
0
        public static Query GetQuery(Database database)
        {
            var view = database.GetView(ViewName);
            if (view.Map == null)
            {
                view.SetMap((document, emitter) => 
                   {
                    object deleted;
                    document.TryGetValue(DeletedKey, out deleted);

                    if(deleted == null)
                        emitter (document["text"], document["check"]);
                    }, "2");
            }
            var query = view.CreateQuery();
            return query;
        }
Пример #28
0
        public static Query GetQuery(Database database)
        {
            var view = database.GetView(ViewName);
            if (view.Map == null)
            {
                view.SetMap((document, emitter) => 
                    {
                        object type;
                        document.TryGetValue("type", out type);

                        if (List.DocType.Equals ((string)type)) {
                            emitter (document["text"], document);
                        }
                    }, "1");
            }
            var query = view.CreateQuery();
            return query;
        }
Пример #29
0
        static ContactDatabase()
        {
            database = Manager.SharedInstance.GetDatabase ("contacts");
            emailLookup = new Dictionary<string, string> ();

            lookupView = database.GetView ("addresses");
            lookupView.SetMap ((document, emit) => {
                var val = document["contact.address.address"];
                emit(document["_id"], val);
            }, "1");

            Query lookupQuery = lookupView.CreateQuery ();

            BuildLookup(lookupQuery.Run ());

            lookupViewLiveQuery = lookupQuery.ToLiveQuery();
            lookupViewLiveQuery.Changed += (object sender, QueryChangeEventArgs e) => { BuildLookup(e.Rows); };
            lookupViewLiveQuery.Start ();
        }
        private void InitializeCouchbase()
        {
            _db = Manager.SharedInstance.GetDatabase("wpf-lite");
            
            var view = _db.GetView("todos");

            if (view.Map == null)
            {
                view.SetMap((props, emit) =>
                {
                    Console.WriteLine("Mapper mapping");
                    emit(DateTime.UtcNow.ToString(), props["text"]);
                }, "1");
            }

            _query = view.CreateQuery().ToLiveQuery();
            _query.Changed += QueryChanged;
            _query.Completed += QueryCompleted;
            _query.Start();
        }
Пример #31
0
        internal Task RunAsync(RunAsyncDelegate action, Database database)
        {
            var task = workExecutor.StartNew(() => { action(database); });

            return(task);
        }
 public DbStorage()
 {
     db = Manager.SharedInstance.GetDatabase("testdb");
 }
Пример #33
-1
		public Pusher(Database db, Uri remote, bool continuous, HttpClientFactory clientFactory
			, ScheduledExecutorService workExecutor) : base(db, remote, continuous, clientFactory
			, workExecutor)
		{
			createTarget = false;
			observing = false;
		}
 public RemoteMultipartDownloaderRequest(ScheduledExecutorService workExecutor, HttpClientFactory
      clientFactory, string method, Uri url, object body, Database db, IDictionary<string
     , object> requestHeaders, RemoteRequestCompletionBlock onCompletion) : base(workExecutor
     , clientFactory, method, url, body, db, requestHeaders, onCompletion)
 {
     this.db = db;
 }