예제 #1
0
            private bool IsMemberOfTheCurrentList(Couchbase.Lite.Document user)
            {
                IList <string> members = (IList <string>) this._enclosing.mCurrentList.GetProperty("members"
                                                                                                   );

                return(members != null?members.Contains(user.GetId()) : false);
            }
예제 #2
0
        /// <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);
        }
 protected internal UnsavedRevision(Document document, SavedRevision parentRevision
     ) : base(document)
 {
     if (parentRevision == null)
     {
         parentRevID = null;
     }
     else
     {
         parentRevID = parentRevision.GetId();
     }
     IDictionary<string, object> parentRevisionProperties;
     if (parentRevision == null)
     {
         parentRevisionProperties = null;
     }
     else
     {
         parentRevisionProperties = parentRevision.GetProperties();
     }
     if (parentRevisionProperties == null)
     {
         properties = new Dictionary<string, object>();
         properties.Put("_id", document.GetId());
         if (parentRevID != null)
         {
             properties.Put("_rev", parentRevID);
         }
     }
     else
     {
         properties = new Dictionary<string, object>(parentRevisionProperties);
     }
 }
예제 #4
0
 public static Image ImageFromAttachment(Document doc, string name)
 {
     if (!doc.CurrentRevision.AttachmentNames.Contains (name)) {
         return null;
     }
     Attachment att = doc.CurrentRevision.GetAttachment (name);
     return Image.Deserialize (att.Content.ToArray());
 }
예제 #5
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);
        }
예제 #6
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static void UpdateCheckedStatus(Couchbase.Lite.Document task, bool @checked
                                               )
        {
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties.PutAll(task.GetProperties());
            properties.Put("checked", @checked);
            task.PutProperties(properties);
        }
예제 #7
0
        private void DisplayListContent(string listDocId)
        {
            Couchbase.Lite.Document document = GetDatabase().GetDocument(listDocId);
            ActionBar.Subtitle = (string)document.GetProperty("title");
            FragmentManager fragmentManager = FragmentManager;

            fragmentManager.BeginTransaction().Replace(Resource.Id.container, MainActivity.TasksFragment
                                                       .NewInstance(listDocId)).Commit();
            Application application = (CouchbaseSample.Android.Application)Application;

            application.SetCurrentListId(listDocId);
        }
예제 #8
0
 private void DeleteTask(int position)
 {
     Couchbase.Lite.Document task = (Couchbase.Lite.Document)mAdapter.GetItem(position
                                                                              );
     try
     {
         Task.DeleteTask(task);
     }
     catch (CouchbaseLiteException e)
     {
         Log.E(Application.Tag, "Cannot delete a task", e);
     }
 }
            public override global::Android.Views.View GetView(int position, global::Android.Views.View convertView
                                                               , ViewGroup parent)
            {
                if (convertView == null)
                {
                    var inflater = (LayoutInflater)parent.Context.GetSystemService(Context.LayoutInflaterService);
                    convertView = inflater.Inflate(Resource.Layout.view_list_drawer, null);
                }
                Couchbase.Lite.Document document = (Couchbase.Lite.Document)GetItem(position);
                var textView = (TextView)convertView;

                textView.Text = document["title"];
                return(convertView);
            }
예제 #10
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static void RemoveMemberFromList(Couchbase.Lite.Document list, Couchbase.Lite.Document
                                                user)
        {
            IDictionary <string, object> newProperties = new Dictionary <string, object>();

            newProperties.PutAll(list.Properties);
            IList <string> members = (IList <string>)newProperties.Get("members");

            if (members != null)
            {
                members.Remove(user.Id);
            }
            newProperties.Put("members", members);
            list.PutProperties(newProperties);
        }
예제 #11
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static void AttachImage(Couchbase.Lite.Document task, Bitmap image)
        {
            if (task == null || image == null)
            {
                return;
            }
            UnsavedRevision       revision = task.CreateRevision();
            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();
        }
예제 #12
0
 public static Couchbase.Lite.Document GetUserProfileById(Database database, string
                                                          userId)
 {
     Couchbase.Lite.Document profile = null;
     try
     {
         QueryEnumerator enumerator = Profile.GetQueryById(database, userId).Run();
         profile = enumerator != null && enumerator.GetCount() > 0 ? enumerator.GetRow(0).
                   GetDocument() : null;
     }
     catch (CouchbaseLiteException)
     {
     }
     return(profile);
 }
예제 #13
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);
        }
예제 #14
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static Couchbase.Lite.Document CreateProfile(Database database, string userId
                                                            , string name)
        {
            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("user_id", userId);
            properties.Put("name", name);
            Couchbase.Lite.Document document = database.GetDocument("profile:" + userId);
            document.PutProperties(properties);
            return(document);
        }
예제 #15
0
                public void OnItemClick <_T0>(AdapterView <_T0> adapter, global::Android.Views.View view, int
                                              position, long id) where _T0 : Adapter
                {
                    Couchbase.Lite.Document task = (Couchbase.Lite.Document)adapter.GetItemAtPosition
                                                       (position);
                    bool @checked = ((bool)task.GetProperty("checked"));

                    try
                    {
                        Task.UpdateCheckedStatus(task, @checked);
                    }
                    catch (CouchbaseLiteException e)
                    {
                        Log.E(Application.Tag, "Cannot update checked status", e);
                        Sharpen.Runtime.PrintStackTrace(e);
                    }
                }
예제 #16
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     SetContentView(R.Layout.activity_share);
     GetActionBar().SetDisplayHomeAsUpEnabled(true);
     if (savedInstanceState != null)
     {
         mCurrentListId = savedInstanceState.GetString(StateCurrentListId);
     }
     else
     {
         Intent intent = GetIntent();
         mCurrentListId = intent.GetStringExtra(ShareActivityCurrentListIdExtra);
     }
     mCurrentList = GetDatabase().GetDocument(mCurrentListId);
     Application application = (Application)GetApplication();
     Query query = Profile.GetQuery(GetDatabase(), application.GetCurrentUserId());
     mAdapter = new ShareActivity.UserAdapter(this, this, query.ToLiveQuery());
     ListView listView = (ListView)FindViewById(R.ID.listView);
     listView.SetAdapter(mAdapter);
 }
예제 #17
0
            public override global::Android.Views.View GetView(int position, global::Android.Views.View convertView
                                                               , ViewGroup parent)
            {
                if (convertView == null)
                {
                    LayoutInflater inflater = (LayoutInflater)parent.GetContext().GetSystemService(Context
                                                                                                   .LayoutInflaterService);
                    convertView = inflater.Inflate(R.Layout.view_user, null);
                }
                Couchbase.Lite.Document task = (Couchbase.Lite.Document) this.GetItem(position);
                TextView text = (TextView)convertView.FindViewById(R.ID.text);

                text.SetText((string)task.GetProperty("name"));
                Couchbase.Lite.Document user = (Couchbase.Lite.Document) this.GetItem(position);
                CheckBox checkBox            = (CheckBox)convertView.FindViewById(R.ID.@checked);
                bool     @checked            = this.IsMemberOfTheCurrentList(user);

                checkBox.SetChecked(@checked);
                checkBox.SetOnClickListener(new _OnClickListener_118(this, checkBox, user));
                return(convertView);
            }
예제 #18
0
            public void OnClick(IDialogInterface dialog, int whichButton)
            {
                string title = ((IEditable)input).Text.ToString();

                if (title.Length == 0)
                {
                    return;
                }
                try
                {
                    string currentUserId = ((Application)this._enclosing.GetApplication()).GetCurrentUserId
                                               ();
                    Couchbase.Lite.Document document = List.CreateNewList(this._enclosing.GetDatabase
                                                                              (), title, currentUserId);
                    this._enclosing.DisplayListContent(document.GetId());
                    this._enclosing.InvalidateOptionsMenu();
                }
                catch (CouchbaseLiteException e)
                {
                    Log.E(Application.Tag, "Cannot create a new list", e);
                }
            }
예제 #19
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static void AddMemberToList(Couchbase.Lite.Document list, Couchbase.Lite.Document
                                           user)
        {
            IDictionary <string, object> newProperties = new Dictionary <string, object>();

            newProperties.PutAll(list.Properties);
            IList <string> members = (IList <string>)newProperties.Get("members");

            if (members == null)
            {
                members = new AList <string>();
            }
            members.AddItem(user.Id);
            newProperties.Put("members", members);
            try
            {
                list.PutProperties(newProperties);
            }
            catch (CouchbaseLiteException e)
            {
                Log.E(Application.Tag, "Cannot add member to the list", e);
            }
        }
예제 #20
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public static void AssignOwnerToListsIfNeeded(Database database, Couchbase.Lite.Document
                                                      user)
        {
            QueryEnumerator enumerator = GetQuery(database).Run();

            if (enumerator == null)
            {
                return;
            }
            foreach (var row in enumerator)
            {
                Couchbase.Lite.Document document = row.Document;
                string owner = (string)document.GetProperty("owner");
                if (owner != null)
                {
                    continue;
                }
                IDictionary <string, object> properties = new Dictionary <string, object>();
                properties.PutAll(document.Properties);
                properties.Put("owner", user.Id);
                document.PutProperties(properties);
            }
        }
예제 #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(R.Layout.activity_share);
            GetActionBar().SetDisplayHomeAsUpEnabled(true);
            if (savedInstanceState != null)
            {
                mCurrentListId = savedInstanceState.GetString(StateCurrentListId);
            }
            else
            {
                Intent intent = GetIntent();
                mCurrentListId = intent.GetStringExtra(ShareActivityCurrentListIdExtra);
            }
            mCurrentList = GetDatabase().GetDocument(mCurrentListId);
            Application application = (Application)GetApplication();
            Query       query       = Profile.GetQuery(GetDatabase(), application.GetCurrentUserId());

            mAdapter = new ShareActivity.UserAdapter(this, this, query.ToLiveQuery());
            ListView listView = (ListView)FindViewById(R.ID.listView);

            listView.SetAdapter(mAdapter);
        }
예제 #22
0
 private void SelectListItem(int position, bool closeDrawer)
 {
     mCurrentSelectedPosition = position;
     if (mDrawerListView != null)
     {
         mDrawerListView.SetItemChecked(position, true);
     }
     if (mDrawerLayout != null && closeDrawer)
     {
         mDrawerLayout.CloseDrawer(mFragmentContainerView);
     }
     if (mListsAdapter.GetCount() > position)
     {
         Couchbase.Lite.Document document = (Couchbase.Lite.Document)mListsAdapter.GetItem
                                                (position);
         Application application = (Application)Activity.Application;
         application.SetCurrentListId(document.Id);
         if (mCallbacks != null)
         {
             mCallbacks.OnListSelected(document.Id);
         }
     }
 }
예제 #23
0
            private void AttachImage(Couchbase.Lite.Document task)
            {
                CharSequence[] items;
                if (mImageToBeAttached != null)
                {
                    items = new CharSequence[] { "Take photo", "Choose photo", "Delete photo" };
                }
                else
                {
                    items = new CharSequence[] { "Take photo", "Choose photo" };
                }
                var builder = new AlertDialog.Builder(Activity);

                builder.SetTitle("Add picture");
                builder.SetItems(items, (sender, args) =>
                {
                    var item = args.Which;
                    if (item == 0)
                    {
                        mCurrentTaskToAttachImage = task;
                        DispatchTakePhotoIntent();
                    }
                    else
                    {
                        if (item == 1)
                        {
                            mCurrentTaskToAttachImage = task;
                            DispatchChoosePhotoIntent();
                        }
                        else
                        {
                            DeleteCurrentPhoto();
                        }
                    }
                });
                builder.Show();
            }
예제 #24
0
		public Document GetDocument(string documentId)
		{
			if (documentId == null || documentId.Length == 0)
			{
				return null;
			}
			Document doc = docCache.Get(documentId);
			if (doc == null)
			{
				doc = new Document(this, documentId);
				if (doc == null)
				{
					return null;
				}
				docCache.Put(documentId, doc);
			}
			return doc;
		}
예제 #25
0
		public void RemoveChangeListener(Document.ChangeListener changeListener)
		{
			changeListeners.Remove(changeListener);
		}
예제 #26
0
 internal void RemoveDocumentFromCache(Document document)
 {
     DocumentCache.Remove(document.Id);
     var dummy = default(WeakReference);
     UnsavedRevisionDocumentCache.TryRemove(document.Id, out dummy);
 }
        public void Test08DocRevisions()
        {
            const string TEST_NAME = "test8";
            if (!PerformanceTestsEnabled) {
                return;
            }

            var docs = new Document[GetNumberOfDocuments(TEST_NAME)];
            var success = database.RunInTransaction(() =>
            {
                for(int i = 0; i < GetNumberOfDocuments(TEST_NAME); i++) {
                    var props = new Dictionary<string, object> {
                        { "toggle", true }
                    };
                    var doc = database.CreateDocument();
                    try {
                        doc.PutProperties(props);
                        docs[i] = doc;
                    } catch(CouchbaseLiteException e) {
                        Log.E(TAG, "Document creation failed");
                        return false;
                    }
                }

                return true;
            });

            Assert.IsTrue(success);
            TimeBlock(String.Format("{0}, {1}", GetNumberOfDocuments(TEST_NAME), GetNumberOfUpdates(TEST_NAME)), () =>
            {
                foreach(var doc in docs) {
                    for(int i = 0; i < GetNumberOfUpdates(TEST_NAME); i++) {
                        var contents = new Dictionary<string, object>(doc.Properties);
                        var wasChecked = contents.GetCast<bool>("toggle");
                        contents["toggle"] = !wasChecked;
                        doc.PutProperties(contents);
                    }
                 }
            });
        }
예제 #28
0
		//            assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet
		/// <exception cref="System.Exception"></exception>
		public virtual void TestViewWithLinkedDocs()
		{
			Database db = StartDatabase();
			int kNDocs = 50;
			Document[] docs = new Document[50];
			string lastDocID = string.Empty;
			for (int i = 0; i < kNDocs; i++)
			{
				IDictionary<string, object> properties = new Dictionary<string, object>();
				properties.Put("sequence", i);
				properties.Put("prev", lastDocID);
				Document doc = CreateDocumentWithProperties(db, properties);
				docs[i] = doc;
				lastDocID = doc.GetId();
			}
			Query query = db.SlowQuery(new _Mapper_691());
			query.SetStartKey(23);
			query.SetEndKey(33);
			query.SetPrefetch(true);
			QueryEnumerator rows = query.Run();
			NUnit.Framework.Assert.IsNotNull(rows);
			NUnit.Framework.Assert.AreEqual(rows.GetCount(), 11);
			int rowNumber = 23;
			for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
			{
				QueryRow row = it.Next();
				NUnit.Framework.Assert.AreEqual(row.GetKey(), rowNumber);
				Document prevDoc = docs[rowNumber];
				NUnit.Framework.Assert.AreEqual(row.GetDocumentId(), prevDoc.GetId());
				NUnit.Framework.Assert.AreEqual(row.GetDocument(), prevDoc);
				++rowNumber;
			}
		}
예제 #29
0
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static void DeleteTask(Couchbase.Lite.Document task)
 {
     task.Delete();
 }
예제 #30
0
 /// <summary>Constructor</summary>
 protected internal Revision(Document document)
 {
     this.Document = document;
 }
예제 #31
0
 public override void OnActivityResult(int requestCode, int resultCode, Intent data
                                       )
 {
     base.OnActivityResult(requestCode, resultCode, data);
     if (resultCode != ResultOk)
     {
         if (mCurrentTaskToAttachImage != null)
         {
             mCurrentTaskToAttachImage = null;
         }
         return;
     }
     if (requestCode == RequestTakePhoto)
     {
         mImageToBeAttached = BitmapFactory.DecodeFile(mImagePathToBeAttached);
         // Delete the temporary image file
         FilePath file = new FilePath(mImagePathToBeAttached);
         file.Delete();
         mImagePathToBeAttached = null;
     }
     else
     {
         if (requestCode == RequestChoosePhoto)
         {
             try
             {
                 Uri uri = data.GetData();
                 mImageToBeAttached = MediaStore.Images.Media.GetBitmap(Activity.GetContentResolver
                                                                            (), uri);
             }
             catch (IOException e)
             {
                 Log.E(Application.Tag, "Cannot get a selected photo from the gallery.", e);
             }
         }
     }
     if (mImageToBeAttached != null)
     {
         if (mCurrentTaskToAttachImage != null)
         {
             try
             {
                 Task.AttachImage(mCurrentTaskToAttachImage, mImageToBeAttached);
             }
             catch (CouchbaseLiteException e)
             {
                 Log.E(Application.Tag, "Cannot attach an image to a task.", e);
             }
         }
         else
         {
             // Attach an image for a new task
             Bitmap thumbnail = ThumbnailUtils.ExtractThumbnail(mImageToBeAttached, ThumbnailSizePx
                                                                , ThumbnailSizePx);
             ImageView imageView = (ImageView)Activity.FindViewById(Resource.Id.image);
             imageView.SetImageBitmap(thumbnail);
         }
     }
     // Ensure resetting the task to attach an image
     if (mCurrentTaskToAttachImage != null)
     {
         mCurrentTaskToAttachImage = null;
     }
 }
예제 #32
0
        private Document GetDocument(string docId, bool mustExist)
        {
            if (StringEx.IsNullOrWhiteSpace (docId)) {
                return null;
            }

            var unsavedDoc = UnsavedRevisionDocumentCache.Get(docId);
            var doc = unsavedDoc != null 
                ? (Document)unsavedDoc.Target 
                : DocumentCache.Get(docId);

            if (doc != null) {
                if (mustExist && doc.CurrentRevision == null) {
                    return null;
                }

                return doc;
            }

            doc = new Document(this, docId);
            if (mustExist && doc.CurrentRevision == null) {
                return null;
            }

            if (DocumentCache == null) {
                DocumentCache = new LruCache<string, Document>(MAX_DOC_CACHE_SIZE);
            }

            DocumentCache[docId] = doc;
            UnsavedRevisionDocumentCache[docId] = new WeakReference(doc);
            return doc;
        }
 /// <summary>
 /// Checks if the specified document is pending replication
 /// </summary>
 /// <returns><c>true</c> if this document is pending, otherwise, <c>false</c>.</returns>
 /// <param name="doc">The document to check.</param>
 public bool IsDocumentPending(Document doc)
 {
     return doc != null && GetPendingDocumentIDs().Contains(doc.Id);
 }
예제 #34
0
			public ChangeEvent(Document source, DocumentChange documentChange)
			{
				this.source = source;
				this.change = documentChange;
			}
예제 #35
0
		protected internal void RemoveDocumentFromCache(Document document)
		{
			docCache.Remove(document.GetId());
		}
        internal UnsavedRevision(Document document, SavedRevision parentRevision): base(document)
        {
            if (parentRevision == null)
                ParentRevisionID = null;
            else
                ParentRevisionID = parentRevision.Id;

            IDictionary<String, Object> parentRevisionProperties;
            if (parentRevision == null)
            {
                parentRevisionProperties = null;
            }

            else
            {
                parentRevisionProperties = parentRevision.Properties;
            }
            if (parentRevisionProperties == null)
            {
                properties = new Dictionary<String, Object>();
                properties["_id"] = document.Id;
                if (ParentRevisionID != null)
                {
                    properties["_rev"] = ParentRevisionID;
                }
            }
            else
            {
                properties = new Dictionary<string, object>(parentRevisionProperties);
            }
        }
예제 #37
0
 public void Changed(Document.ChangeEvent @event)
 {
     DocumentChange docChange = @event.GetChange();
     string msg = "New revision added: %s.  Conflict: %s";
     msg = string.Format(msg, docChange.GetAddedRevision(), docChange.IsConflict());
     Log.D(LiteTestCase.Tag, msg);
     documentChanged.CountDown();
 }
예제 #38
0
		public SavedRevision Update(Document.DocumentUpdater updater)
		{
			int lastErrorCode = Status.Unknown;
			do
			{
				UnsavedRevision newRev = CreateRevision();
				if (updater.Update(newRev) == false)
				{
					break;
				}
				try
				{
					SavedRevision savedRev = newRev.Save();
					if (savedRev != null)
					{
						return savedRev;
					}
				}
				catch (CouchbaseLiteException e)
				{
					lastErrorCode = e.GetCBLStatus().GetCode();
				}
			}
			while (lastErrorCode == Status.Conflict);
			return null;
		}
예제 #39
0
        public void TestViewWithLinkedDocs()
        {
            var db = database;

            const int numberOfDocs = 50;
            var docs = new Document[50];
            var lastDocID = String.Empty;

            for (var i = 0; i < numberOfDocs; i++)
            {
                var properties = new Dictionary<String, Object>();
                properties["sequence"] = i;
                properties["prev"] = lastDocID;

                var doc = CreateDocumentWithProperties(db, properties);
                docs[i] = doc;
                lastDocID = doc.Id;
            }

            var query = db.SlowQuery((document, emitter)=> emitter (document ["sequence"], new Dictionary<string, object> { { "_id", document ["prev"] } }));
            query.StartKey = 23;
            query.EndKey = 33;
            query.Prefetch = true;

            var rows = query.Run();
            Assert.IsNotNull(rows);
            Assert.AreEqual(rows.Count, 11);

            var rowNumber = 23;
            foreach (var row in rows)
            {
                Assert.AreEqual(row.Key, rowNumber);

                var prevDoc = docs[rowNumber - 1];
                Assert.AreEqual(row.DocumentId, prevDoc.Id);
                Assert.AreEqual(row.Document, prevDoc);

                ++rowNumber;
            }
        }
        public void Test05ReadAttachments()
        {
            const string TEST_NAME = "test5";
            if (!PerformanceTestsEnabled) {
                return;
            }

            var bytes = Encoding.UTF8.GetBytes(CreateContent(GetSizeOfAttachment(TEST_NAME)));
            var docs = new Document[GetNumberOfDocuments(TEST_NAME)];
            var success = database.RunInTransaction(() =>
            {
                try {
                    for(int i = 0; i < GetNumberOfDocuments(TEST_NAME); i++) {
                        var properties = new Dictionary<string, object> {
                            { "foo", "bar" }
                        };
                        var doc = database.CreateDocument();
                        var unsaved = doc.CreateRevision();
                        unsaved.SetProperties(properties);
                        unsaved.SetAttachment("attach", "text/plain", bytes);
                        unsaved.Save();

                        docs[i] = doc;
                    }
                } catch(Exception e) {
                    Log.E(TAG, "Document create with attachment failed", e);
                    return false;
                }

                return true;
            });

            Assert.IsTrue(success);

            TimeBlock(String.Format("{0}, {1}", GetNumberOfDocuments(TEST_NAME), GetSizeOfAttachment(TEST_NAME)), () =>
            {
                foreach(var doc in docs) {
                    var att = doc.CurrentRevision.GetAttachment("attach");
                    Assert.IsNotNull(att);

                    var gotBytes = att.Content.ToArray();
                    Assert.AreEqual(GetSizeOfAttachment(TEST_NAME), gotBytes.Length);
                    LogPerformanceStats(bytes.Length, "Size");
                }
            });
        }
        public void TestJsFilterFunctionWithParameters()
        {
            var c = new JSFilterCompiler();
            var filterBlock = c.CompileFilter("function(doc,req){return doc.name == req.name;}", "javascript");
            Assert.IsNotNull(filterBlock);
            var filterParams = new Dictionary<string, object> { { "name", "jim" } };
            var document = new Document(null, "doc1");
            var rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "foo", 666 }
            });
            var savedRev = new SavedRevision(document, rev);
            Assert.IsFalse(filterBlock(savedRev, filterParams));

            rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "name", "bob" }
            });
            savedRev = new SavedRevision(document, rev);
            Assert.IsFalse(filterBlock(savedRev, filterParams));

            rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "name", "jim" }
            });
            savedRev = new SavedRevision(document, rev);
            Assert.IsTrue(filterBlock(savedRev, filterParams));
        }
        public void Test11DeleteDocs()
        {
            const string TEST_NAME = "test11";
            if (!PerformanceTestsEnabled) {
                return;
            }

            var docs = new Document[GetNumberOfDocuments(TEST_NAME)];
            var success = database.RunInTransaction(() =>
            {
                for(int i = 0; i < GetNumberOfDocuments(TEST_NAME); i++) {
                    var props = new Dictionary<string, object> {
                        { "toggle", true }
                    };
                    var doc = database.CreateDocument();
                    try {
                        doc.PutProperties(props);
                        docs[i] = doc;
                    } catch(CouchbaseLiteException e) {
                        Log.E(TAG, "Document creation failed", e);
                        return false;
                    }
                }

                return true;
            });

            Assert.IsTrue(success);
            TimeBlock(String.Format("{0}, {1}", GetNumberOfDocuments(TEST_NAME), GetSizeOfDocument(TEST_NAME)), () =>
            {
                success = database.RunInTransaction(() =>
                {
                    foreach(var doc in docs) {
                        try {
                            doc.Delete();
                        } catch(Exception e) {
                            Log.E(TAG, "Document delete failed", e);
                            return false;
                        }
                    }

                    return true;
                });

                Assert.IsTrue(success);
            });
        }
예제 #43
0
 public _OnClickListener_118(UserAdapter _enclosing, CheckBox checkBox, Couchbase.Lite.Document
                             user)
 {
     this._enclosing = _enclosing;
     this.checkBox   = checkBox;
     this.user       = user;
 }
예제 #44
0
        public void TestMultiDocumentUpdate()
        {
            const Int32 numDocs = 10;
            const Int32 numUpdates = 10;
            var docs = new Document[numDocs];

            for (var i = 0; i < numDocs; i++)
            {
                var props = new Dictionary<string, object>() 
                {
                    { "foo", "bar" },
                    { "toggle", true }
                };

                var doc = CreateDocumentWithProperties(database, props);
                docs[i] = doc;
            }

            for (var i = 0; i < numDocs; i++)
            {
                var doc = docs[i];
                for (var j = 0; j < numUpdates; j++)
                {
                    var contents = new Dictionary<string, object>(doc.Properties);
                    contents["toggle"] = !(Boolean)contents["toggle"];
                    var rev = doc.PutProperties(contents);
                    Assert.IsNotNull(rev);
                }
            }
        }
예제 #45
0
		public void AddChangeListener(Document.ChangeListener changeListener)
		{
			changeListeners.AddItem(changeListener);
		}
 /// <summary>Constructor</summary>
 internal SavedRevision(Document document, RevisionInternal revision)
     : base(document) { RevisionInternal = revision; }
        public void TestJsFilterFunction()
        {
            var c = new JSFilterCompiler();
            var filterBlock = c.CompileFilter("function(doc,req){return doc.ok;}", "javascript");
            Assert.IsNotNull(filterBlock);

            var document = new Document(null, "doc1");
            var rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "foo", 666 }
            });
            var savedRev = new SavedRevision(document, rev);
            Assert.IsFalse(filterBlock(savedRev, null));

            rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "ok", false }
            });
            savedRev = new SavedRevision(document, rev);
            Assert.IsFalse(filterBlock(savedRev, null));

            rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "ok", true }
            });
            savedRev = new SavedRevision(document, rev);
            Assert.IsTrue(filterBlock(savedRev, null));

            rev = new RevisionInternal(new Dictionary<string, object> {
                { "_id", "doc1" },
                { "_rev", "1-aa" },
                { "ok", "mais oui" }
            });
            savedRev = new SavedRevision(document, rev);
            Assert.IsTrue(filterBlock(savedRev, null));
        }
예제 #48
0
 internal void RemoveDocumentFromCache(Document document)
 {
     DocumentCache.Remove(document.Id);
 }
예제 #49
0
 private SavedRevision CreateTestRevisionNoConflicts(Document doc, string val) {
     var unsavedRev = doc.CreateRevision();
     var props = new Dictionary<string, object>() 
     {
         {"key", val}
     };
     unsavedRev.SetUserProperties(props);
     return unsavedRev.Save();
 }
예제 #50
0
        /// <summary>
        /// Gets or creates the <see cref="Couchbase.Lite.Document" /> with the given id.
        /// </summary>
        /// <returns>The <see cref="Couchbase.Lite.Document" />.</returns>
        /// <param name="id">The id of the Document to get or create.</param>
        public Document GetDocument(String id) 
        { 
            if (String.IsNullOrWhiteSpace (id)) {
                return null;
            }

            var unsavedDoc = UnsavedRevisionDocumentCache.Get(id);
            var doc = unsavedDoc != null 
                ? (Document)unsavedDoc.Target 
                : DocumentCache.Get(id);

            if (doc == null)
            {
                doc = new Document(this, id);
                DocumentCache[id] = doc;
                UnsavedRevisionDocumentCache[id] = new WeakReference(doc);
            }

            return doc;
        }
예제 #51
0
        /// <summary>
        /// Gets or creates the %Document% with the given id.
        /// </summary>
        /// <returns>The %Document%.</returns>
        /// <param name="id">Identifier.</param>
        public Document GetDocument(String id) 
        { 
            if (String.IsNullOrWhiteSpace (id)) {
                return null;
            }

            var doc = DocumentCache.Get(id);
            if (doc == null)
            {
                doc = new Document(this, id);
                if (doc == null)
                {
                    return null;
                }
                DocumentCache[id] = doc;
            }

            return doc;
        }
예제 #52
0
 internal void RemoveDocumentFromCache(Document document)
 {
     DocumentCache.Remove(document.Id);
     UnsavedRevisionDocumentCache.Remove(document.Id);
 }
예제 #53
0
                public override global::Android.Views.View GetView(int position, global::Android.Views.View convertView
                                                                   , ViewGroup parent)
                {
                    if (convertView == null)
                    {
                        LayoutInflater inflater = (LayoutInflater)parent.GetContext().GetSystemService(Context
                                                                                                       .LayoutInflaterService);
                        convertView = inflater.Inflate(Resource.Layout.view_task, null);
                    }
                    Couchbase.Lite.Document task   = (Couchbase.Lite.Document) this.GetItem(position);
                    Bitmap             image       = null;
                    Bitmap             thumbnail   = null;
                    IList <Attachment> attachments = task.GetCurrentRevision().GetAttachments();

                    if (attachments != null && attachments.Count > 0)
                    {
                        Attachment attachment = attachments[0];
                        try
                        {
                            image     = BitmapFactory.DecodeStream(attachment.GetContent());
                            thumbnail = ThumbnailUtils.ExtractThumbnail(image, MainActivity.TasksFragment.ThumbnailSizePx
                                                                        , MainActivity.TasksFragment.ThumbnailSizePx);
                        }
                        catch (Exception e)
                        {
                            Log.E(Application.Tag, "Cannot decode the attached image", e);
                        }
                    }
                    Bitmap    displayImage = image;
                    ImageView imageView    = (ImageView)convertView.FindViewById(Resource.Id.image);

                    if (thumbnail != null)
                    {
                        imageView.SetImageBitmap(thumbnail);
                    }
                    else
                    {
                        imageView.SetImageDrawable(this._enclosing.GetResources().GetDrawable(Resource.Drawable.
                                                                                              ic_camera_light));
                    }
                    imageView.Click += async(sender, e) => {
                        if (displayImage != null)
                        {
                            DispatchImageViewIntent(displayImage);
                        }
                        else
                        {
                            AttachImage(task);
                        }
                    };
                    TextView text = (TextView)convertView.FindViewById(Resource.Id.text);

                    text.SetText((string)task.GetProperty("title"));
                    CheckBox checkBox        = (CheckBox)convertView.FindViewById(Resource.Id.@checked);
                    bool     checkedProperty = (bool)task.GetProperty("checked");
                    bool     @checked        = checkedProperty != null ? checkedProperty : false;

                    checkBox.SetChecked(@checked);
                    checkBox.Click += async(sender, e) => {
                        try
                        {
                            Task.UpdateCheckedStatus(task, checkBox.IsChecked());
                        }
                        catch (CouchbaseLiteException ex)
                        {
                            Log.E(((CouchbaseSample.Android.Application)Application).Tag, "Cannot update checked status", e);
                        }
                    };
                    return(convertView);
                }