Example #1
0
        public bool AddItem(NewTodoItem item, string userId)
        {
            var userDocument = bucket.GetDocument <User>(userId);
            var user         = userDocument.Content;
            var todoItem     = new TodoItem()
            {
                Id         = Guid.NewGuid(),
                IsDone     = false,
                Title      = item.Title,
                CreatedUtc = DateTime.UtcNow
            };

            if (userDocument.Content.TodoList == null)
            {
                userDocument.Content.TodoList = new List <TodoItem> {
                    todoItem
                };
            }
            else
            {
                userDocument.Content.TodoList.Add(todoItem);
            }

            var result = bucket.Replace(userId, userDocument.Content);

            return(result.Success);
        }
Example #2
0
        public Patient GetById(Guid id)
        {
            var document = _bucket.GetDocument <PatientDb>(id.ToString());

            var mapper  = PatientDbMapper.Create();
            var patient = mapper.Map <Patient>(document.Content);

            return(patient);
        }
        public void When_Id_Field_Exists_It_Is_Removed_From_Document()
        {
            _bucket.Remove("25892e17-80f6-415f-9c65-7395632f0223");
            var json = File.ReadAllText("Data\\doc-with-embedded-id.json");

            string id;
            var    insert = _bucket.ExtractKeyAndInsert <dynamic>(json, "_id", out id);

            Assert.IsTrue(insert.Success);

            var get = _bucket.GetDocument <dynamic>(id);

            Assert.IsTrue(get.Success);
            Assert.IsNull(get.Content._id);
        }
        public IActionResult SearchAddress(string address = "")
        {
            if (!string.IsNullOrEmpty(address))
            {
                var query = new SearchQuery
                {
                    Index = "fts_index",
                    Query = new MatchQuery(address)
                }
                .Limit(10);
                var             result    = bucket.Query(query);
                List <Landmark> landmarks = new List <Landmark>();

                ISearchQueryResult searchQueryRows = result;
                foreach (var item in searchQueryRows)
                {
                    var landmark = bucket.GetDocument <Landmark>(item.Id).Document.Content;

                    landmarks.Add(landmark);
                }

                return(View(landmarks));
            }
            else
            {
                List <Landmark> landmarks = new List <Landmark>();
                return(View(landmarks));
            }
        }
        public static Customer GetDocument(string id)
        {
            _bucket = ClusterHelper.GetBucket("beer-sample");
            var result = _bucket.GetDocument <Customer>(id);

            return(result.Content);
        }
Example #6
0
        public WebOptions Resolve()
        {
            if (_options != null)
            {
                // Already cached in this request
                return(_options);
            }

            var key = GetKey();

            var documentResult = _bucket.GetDocument <WebOptions>(key);

            if (documentResult.Success && documentResult.Content != null)
            {
                // Loaded from Couchbase cache
                _options = documentResult.Content;
            }
            else
            {
                // Need to load from database, then store in Couchbase cache
                _options = LoadFromDatabase();

                _bucket.Upsert(new Document <WebOptions>()
                {
                    Id      = key,
                    Content = _options,
                    Expiry  = (uint)CacheInterval.TotalMilliseconds
                });
            }

            return(_options);
        }
Example #7
0
        public T Retrieve <T>(string key)
        {
            T   cachedData = default(T);
            var data       = _ibucket.GetDocument <T>(key);

            cachedData = data.Document.Content;
            return(cachedData);
        }
Example #8
0
        static void GetDocument(IBucket bucket, string id)
        {
            var result = bucket.GetDocument <Person>("P1");

            if (result.Success)
            {
                var person = result.Content;
                Console.WriteLine("Retrieved document '{0}': {1} {2}", id, person.FirstName, person.LastName);
            }
        }
Example #9
0
        public void GetDocument_IdIsInOperationResult()
        {
            var key   = "thekey";
            var value = "thevalue";

            _bucket.Remove(key);
            _bucket.Insert(key, value);
            var result = _bucket.GetDocument <string>(key);

            Assert.AreEqual(key, result.Id);
        }
Example #10
0
        public TDocument GetDocument<TDocument>(string collectionName, string id)
        {
            Initialize();

            var documentId = GetDocumentId(collectionName, id);

            var doc = bucket.GetDocument<TDocument>(documentId);
            if (doc == null)
            {
                return default(TDocument);
            }

            return doc.Content;
        }
Example #11
0
        public async Task <GetGroupByIdQueryResult> GetGroupByUrlKey(GetGroupByUrlKeyQuery getGroupByUrlKeyQuery)
        {
            var documentResult = _groupsBucket.GetDocument <GroupUrlKeyDocument>($"urlkey::{getGroupByUrlKeyQuery.UrlKey}");

            if (!documentResult.Success && documentResult.Status == Couchbase.IO.ResponseStatus.KeyNotFound)
            {
                throw new GroupNotFoundException();
            }
            else if (!documentResult.Success)
            {
                throw documentResult.Exception;
            }

            return(await GetGroupById(new GetGroupByIdQuery(documentResult.Document.Content.GroupId)));
        }
Example #12
0
        private static void ReplaceDocument(IBucket bucket, Document <Person> document)
        {
            var person = document.Content;

            person.FirstName = "Tom";
            person.LastName  = "Finnigan";

            if (bucket.Replace(document).Success)
            {
                var result = bucket.GetDocument <Person>("P1");
                if (result.Success)
                {
                    person = result.Content;
                    Console.WriteLine("Replaced document '{0}': {1} {2}",
                                      document.Id, person.FirstName, person.LastName);
                }
            }
        }
Example #13
0
        public static IObservable <IDocument <T> > GetDocumentObservable <T>(this IBucket bucket, IList <string> ids)
        {
            if (bucket == null)
            {
                throw new ArgumentNullException("bucket");
            }

            // Create an IObservable to get the IOperationResult for all keys
            IObservable <KeyValuePair <string, IDocumentResult <T> > > operationObserver =
                new MultiGetObservable <string, KeyValuePair <string, IDocumentResult <T> > >(
                    ids, id => new KeyValuePair <string, IDocumentResult <T> >(id, bucket.GetDocument <T>(id)));

            // Filter out KeyNotFound results
            operationObserver = operationObserver.Where(p => p.Value.Status != ResponseStatus.KeyNotFound);

            return(operationObserver.Select(p =>
            {
                CheckResultForError(p.Value);

                return p.Value.Document;
            }));
        }
        public override JobData GetJobData(string jobId)
        {
            if (jobId == null)
            {
                throw new ArgumentNullException(nameof(jobId));
            }

            IDocumentResult <Documents.Job> result = bucket.GetDocument <Documents.Job>(jobId);

            if (result.Success && result.Content != null)
            {
                Documents.Job  data           = result.Content;
                InvocationData invocationData = data.InvocationData;
                invocationData.Arguments = data.Arguments;

                Common.Job       job           = null;
                JobLoadException loadException = null;

                try
                {
                    job = invocationData.Deserialize();
                }
                catch (JobLoadException ex)
                {
                    loadException = ex;
                }

                return(new JobData
                {
                    Job = job,
                    State = data.StateName,
                    CreatedAt = data.CreatedOn,
                    LoadException = loadException
                });
            }

            return(null);
        }
Example #15
0
        public void When_Document_Has_Expiry_It_Is_Evicted_After_It_Expires_Upsert()
        {
            var document = new Document <dynamic>
            {
                Id      = "When_Document_Has_Expiry_It_Is_Evicted_After_It_Expires_Upsert",
                Expiry  = 1000,
                Content = new { name = "I expire in 2000 milliseconds." }
            };

            var upsert = _bucket.Upsert(document);

            Assert.IsTrue(upsert.Success);

            var get = _bucket.GetDocument <dynamic>(document.Id);

            Assert.AreEqual(ResponseStatus.Success, get.Status);

            Thread.Sleep(2000);
            get = _bucket.GetDocument <dynamic>(document.Id);
            Assert.AreEqual(ResponseStatus.KeyNotFound, get.Status);
        }
Example #16
0
        public User Get(string userKey)
        {
            var userDocument = bucket.GetDocument <User>(userKey);

            return(userDocument.Content);
        }
        public IHttpActionResult RegisterSawariBooking(SawariBookingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter()));
                }

                // Commented By Arvind acccording vinay on 21/08/2018

                //var userKey = "SawariBooking_" + model.PassengerID;
                //if (await _bucket.ExistsAsync(userKey))
                //{
                //    //return Content(HttpStatusCode.Conflict, new Error($"SawariBooking '{model.PassengerID}' already exists"));
                //    return Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "169-Passenger ID already exists."), new JsonMediaTypeFormatter());
                //}
                //AuditInfo auditInfo = new AuditInfo();
                //if (model.AuditInfo != null)
                //{
                //    auditInfo.Version = model.AuditInfo.Version;
                //    auditInfo.Status = model.AuditInfo.Status;
                //    auditInfo.Remarks = model.AuditInfo.Remarks;
                //    auditInfo.LastChangeDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                //    auditInfo.LastChangeBy = model.AuditInfo.LastChangeBy;
                //    auditInfo.DateCreated = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                //    auditInfo.CreatedBy = model.AuditInfo.CreatedBy;
                //}
                //var sawariBookingModelMessageDoc = new Document<SawariBookingModel>()
                //{
                //    Id = userKey,
                //    Content = new SawariBookingModel
                //    {
                //        PassengerID = model.PassengerID,
                //        MobileNumber = model.MobileNumber,
                //        FromLocation = model.FromLocation,
                //        ToLocation = model.ToLocation,
                //        DateTimeRequired = model.DateTimeRequired,
                //        Comments = model.Comments,
                //        AuditInfo= auditInfo
                //    }
                //};
                //var result = await _bucket.InsertAsync(sawariBookingModelMessageDoc);

                //if (!result.Success)
                //{
                //    return Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter());
                //}

                Booking booking = new Booking();
                booking.FromLocation     = model.FromLocation;
                booking.ToLocation       = model.ToLocation;
                booking.DateTimeRequired = model.DateTimeRequired;
                booking.Comments         = model.Comments;

                var PassengerMessage = _bucket.GetDocument <object>("PassengerMessage_" + model.PassengerID);
                if (PassengerMessage.Content != null)
                {
                    string query  = @"UPDATE APTCCRM SET booking = ARRAY_APPEND( booking, " + Newtonsoft.Json.JsonConvert.SerializeObject(booking).ToString() + ") where meta().id = 'PassengerMessage_" + model.PassengerID + "'";
                    var    result = _bucket.Query <object>(query);
                }
                else
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "169-Passenger ID does not exists."), new JsonMediaTypeFormatter()));
                }

                SawariBookingResponse sawariBookingResponse = new SawariBookingResponse();
                sawariBookingResponse.RequestRefID = model.PassengerID;
                sawariBookingResponse.Message      = "messge by CT";
                sawariBookingResponse.Telephone    = "1800-6000-123456";

                var jsonSBR = JSONHelper.ToJSON(sawariBookingResponse);
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), jsonSBR), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Example #18
0
        public List <Location> GetLocations()
        {
            IDocumentResult <Locations> result = bucket.GetDocument <Locations>("attendance::locations");

            return(result.Content.locations);
        }
        private void Acquire(TimeSpan timeout)
        {
            logger.Trace($"Trying to acquire lock for {resource} within {timeout.TotalSeconds} seconds");

            System.Diagnostics.Stopwatch acquireStart = new System.Diagnostics.Stopwatch();
            acquireStart.Start();

            string id = $"{resource}:{DocumentTypes.Lock}".GenerateHash();

            while (string.IsNullOrEmpty(resourceId))
            {
                // default ttl for lock document
                TimeSpan ttl = DateTime.UtcNow.Add(timeout).AddMinutes(1).TimeOfDay;

                // read the document
                IDocumentResult <Lock> document = bucket.GetDocument <Lock>(id);

                // false means the document does not exists got ahead and create
                if (document.Success == false)
                {
                    Lock @lock = new Lock
                    {
                        Id       = id,
                        Name     = resource,
                        ExpireOn = DateTime.UtcNow.Add(timeout).ToEpoch()
                    };

                    IOperationResult <Lock> result = bucket.Insert(@lock.Id, @lock, ttl);
                    if (result.Success)
                    {
                        resourceId = id;
                        break;
                    }
                }
                else if (document.Content != null)
                {
                    if (document.Content.ExpireOn < DateTime.UtcNow.ToEpoch())
                    {
                        IDocumentFragment <Lock> result = bucket.MutateIn <Lock>(id)
                                                          .WithCas(document.Document.Cas)
                                                          .WithExpiry(ttl)
                                                          .Upsert(l => l.ExpireOn, DateTime.UtcNow.Add(timeout).ToEpoch(), false)
                                                          .Execute();

                        if (result.Success)
                        {
                            resourceId = id;
                            break;
                        }
                    }
                }

                // check the timeout
                if (acquireStart.ElapsedMilliseconds > timeout.TotalMilliseconds)
                {
                    throw new CouchbaseDistributedLockException($"Could not place a lock on the resource '{resource}': Lock timeout.");
                }

                // sleep for 2000 millisecond
                logger.Trace($"Unable to acquire lock for {resource}. Will check try after 2 seconds");
                System.Threading.Thread.Sleep(2000);
            }

            logger.Trace($"Acquired lock for {resource} in {acquireStart.Elapsed.TotalSeconds} seconds");
        }
Example #20
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 public T Get <T>(string key) where T : class
 {
     return(_bucket.GetDocument <T>(key).Document?.Content);
 }