Exemplo n.º 1
0
        public User ProjectAddUser(string username, string projectId)
        {
            var userDocument = _bucket.Get <User>(username);

            if (!userDocument.Success)
            {
                throw new ArgumentException("The user does not exists");
            }
            var projectDocument = _bucket.Get <Project>(projectId);

            if (!projectDocument.Success)
            {
                throw new ArgumentException("The project does not exist");
            }

            var project = projectDocument.Value;

            if (!project.Users.Contains(username))
            {
                project.Users.Add(username);
            }

            _bucket.Upsert(new Document <Project>
            {
                Id      = projectDocument.Id,
                Content = project
            });

            return(userDocument.Value);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Function to add a new item to the output cache. If there is already a value in the cache for the
        /// specified key, the provider must return that value and must not store the data passed by using the Add method
        /// parameters. The Add method stores the data if it is not already in the cache and returns the value
        /// read from the cache if it already exists.
        /// </summary>
        /// <param name="key">A unique identifier for entry</param>
        /// <param name="entry">The content to add to the output cache</param>
        /// <param name="utcExpiry">The time and date on which the cached entry expires</param>
        /// <returns>
        /// The value that identifies what was in the cache, or the value that was just added if it was not
        /// </returns>
        public override object Add(
            string key,
            object entry,
            DateTime utcExpiry)
        {
            // Fix the key
            key = SanitizeKey(key);

            // We should only store the item if it's not in the cache. So try to add it and if it
            // succeeds, return the value we just stored
            var expiration = ToExpiration(utcExpiry);

            if (_bucket.Insert(key, Serialize(entry), expiration).Success)
            {
                return(entry);
            }

            // If it's in the cache we should return it
            var retval = DeSerialize(_bucket.Get <byte[]>(key).Value);

            // If the item got evicted between the Add and the Get (very rare) we store it anyway,
            // but this time with Set to make sure it always gets into the cache
            if (retval == null)
            {
                _bucket.Insert(key, entry, expiration);
                retval = entry;
            }

            // Return the value read from the cache if it was present
            return(retval);
        }
Exemplo n.º 3
0
        public void Test_Dequeue()
        {
            var key = "CouchbaseQueueTests.Test_Dequeue";

            _bucket.Remove(key);

            var queue = new CouchbaseQueue <Poco>(_bucket, key);

            queue.Enqueue(new Poco {
                Name = "pcoco1"
            });
            queue.Enqueue(new Poco {
                Name = "pcoco2"
            });
            queue.Enqueue(new Poco {
                Name = "pcoco3"
            });

            var item = queue.Dequeue();

            Assert.AreEqual("pcoco1", item.Name);

            var items = _bucket.Get <List <Poco> >(key).Value;

            Assert.AreEqual(2, items.Count);
        }
        public void Test_Get()
        {
            var key   = "thekey";
            var value = "thevalue";

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

            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public T Update <T>(long id, T data) where T : BaseModel
        {
            var result = _bucket.Get <T>(id.ToString()).Value;

            result = data;
            var doc = new Document <T> {
                Id = data.Id.ToString(), Content = data
            };

            _bucket.Insert(doc);
            return(data);
        }
        private void Rollback(IOperationResult <Barn> source, IOperationResult <Barn> destination, int amountToTransfer, IDocumentResult <TransactionRecord> transaction, Exception ex)
        {
            Console.WriteLine("Handling a rollback");
            Console.ReadLine();
            var transactionRecord = _bucket.Get <TransactionRecord>(transaction.Id);

            switch (transactionRecord.Value.State)
            {
            case TransactionStates.Committed:
            case TransactionStates.Pending:
                // #1 -> switch to 'cancelling' state
                // tag::cancelling[]
                UpdateWithCas <TransactionRecord>(transaction.Id, x => x.State = TransactionStates.Cancelling, transactionRecord.Cas);
                // end::cancelling[]
                Console.WriteLine($"Switch transaction to {TransactionStates.Cancelling}");
                Console.ReadLine();

                // #2 -> revent changes if they were applied
                // tag::reventbarn1[]
                UpdateWithCas <Barn>(source.Id, x =>
                {
                    if (x.Transaction != null)
                    {
                        x.Chickens   += transactionRecord.Value.Amount;
                        x.Transaction = null;
                    }
                });
                // end::reventbarn1[]
                Console.WriteLine($"If necessary: Add {amountToTransfer} to {source.Value.Name} (and remove transaction {transaction.Id})");
                Console.ReadLine();

                // tag::reventbarn2[]
                UpdateWithCas <Barn>(destination.Id, x =>
                {
                    if (x.Transaction != null)
                    {
                        x.Chickens   -= transactionRecord.Value.Amount;
                        x.Transaction = null;
                    }
                });
                // end::reventbarn2[]
                Console.WriteLine($"If necessary: Remove {amountToTransfer} from {destination.Value.Name} (and remove transaction {transaction.Id})");
                Console.ReadLine();

                // #3 -> switch to cancelled state
                // tag::cancelled[]
                UpdateWithCas <TransactionRecord>(transaction.Id, x => x.State = TransactionStates.Cancelled);
                // end::cancelled[]
                Console.WriteLine($"Switch transaction to {TransactionStates.Cancelled}");
                Console.ReadLine();
                break;
            }
        }
Exemplo n.º 7
0
        public void RetrieveAndUpdate()
        {
            var key  = "SampleApp-" + DateTime.Now.Ticks;
            var data = new Data
            {
                Number = 42,
                Text   = "Life, the Universe, and Everything",
                Date   = DateTime.UtcNow
            };

            // Get non-existent document.
            // Note that it's enough to check the Status property,
            // We're only checking all three to show they exist.
            var notFound = _bucket.Get <dynamic>(key);

            if (!notFound.Success &&
                notFound.Status == ResponseStatus.KeyNotFound)
            {
                Console.WriteLine("Document doesn't exist!");
            }

            // Prepare a JSON document value
            _bucket.Upsert(key, data);

            // Get a JSON document string value
            var docResult = _bucket.Get <Data>(key);

            Console.WriteLine("Found: " + docResult.Value);

            // Change the data
            data.Number++;
            data.Text = "What's 7 * 6 + 1?";
            data.Date = DateTime.UtcNow;

            // Try to insert under the same key should fail
            var insertResult = _bucket.Insert(key, data);

            if (!insertResult.Success)
            {
                Console.WriteLine("Inserting under an existing key fails as expected.");
            }

            // Replace existing document
            // Note this only works if the key already exists
            var replaceResult = _bucket.Replace(key, data);

            // Check that the data was updated
            var res = _bucket.Remove(key);

            Console.WriteLine("Got: " + res.Status);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Loads a session state item from the bucket. This function is publicly accessible
        /// so that you have direct access to session data from another application if necesssary.
        /// We use this so our front end code can determine if an employee is logged into our back
        /// end application to give them special permissions, without the session data being actually common
        /// between the two applications.
        /// </summary>
        /// <param name="headerPrefix">Prefix for the header data</param>
        /// <param name="dataPrefix">Prefix for the real data</param>
        /// <param name="bucket">Couchbase bucket to load from</param>
        /// <param name="id">Session ID</param>
        /// <param name="metaOnly">True to load only meta data</param>
        /// <returns>Session store item read, null on failure</returns>
        public static SessionStateItem Load(
            string headerPrefix,
            string dataPrefix,
            IBucket bucket,
            string id,
            bool metaOnly)
        {
            // Read the header value from Couchbase
            var header = bucket.Get <byte[]>(CouchbaseSessionStateProvider.HeaderPrefix + id);

            if (header.Status != ResponseStatus.Success)
            {
                return(null);
            }

            // Deserialize the header values
            SessionStateItem entry;

            using (var ms = new MemoryStream(header.Value))
            {
                entry = LoadHeader(ms);
            }
            entry.HeadCas = header.Cas;

            // Bail early if we are only loading the meta data
            if (metaOnly)
            {
                return(entry);
            }

            // Read the data for the item from Couchbase
            var data = bucket.Get <byte[]>(CouchbaseSessionStateProvider.DataPrefix + id);

            if (data.Value == null)
            {
                return(null);
            }
            entry.DataCas = data.Cas;

            // Deserialize the data
            using (var ms = new MemoryStream(data.Value))
            {
                using (var br = new BinaryReader(ms))
                {
                    entry.Data = SessionStateItemCollection.Deserialize(br);
                }
            }

            // Return the session entry
            return(entry);
        }
        /// <summary>
        /// Gets the set.
        /// </summary>
        /// <returns></returns>
        protected HashSet <TValue> GetSet()
        {
            var get = Bucket.Get <HashSet <TValue> >(Key);

            if (!get.Success)
            {
                if (get.Exception != null)
                {
                    throw get.Exception;
                }
                throw new InvalidOperationException(get.Status.ToString());
            }
            return(get.Value);
        }
Exemplo n.º 10
0
        public IActionResult GetCategories(string userId)
        {
            var  u    = _bucket.Get <User>(userId);
            User user = u.Value;

            if (user != null)
            {
                var             q            = _bucket.Get <User>(user.UserId);
                List <Category> categorylist = new List <Category>();
                categorylist = q.Value.Categories;
                return(Ok(categorylist));
            }
            return(BadRequest());
        }
Exemplo n.º 11
0
        public static Dictionary <string, T> GetMultiJson <T>(this IBucket client, IList <string> keys) where T : class
        {
            Dictionary <string, T> result = new Dictionary <string, T>();

            if (keys.Count > 0)
            {
                // TODO: Use the async overloads that take a list of keys for multi-operations.
                var dicObj = client.Get <dynamic>(keys);

                foreach (var item in dicObj)
                {
                    if (item.Value.Success && !string.IsNullOrEmpty(item.Value.Value))
                    {
                        var json = item.Value.Value.ToString();

                        if (!string.IsNullOrEmpty(json))
                        {
                            var obj = JsonConvert.DeserializeObject <T>(json);

                            if (!result.ContainsKey(item.Key))
                            {
                                result.Add(item.Key, obj);
                            }
                        }
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Gets a <c>CacheItem</c> for the specified key.
        /// </summary>
        /// <param name="key">The key being used to identify the item within the cache.</param>
        /// <param name="region">The cache region.</param>
        /// <returns>The <c>CacheItem</c>.</returns>
        protected override CacheItem <TCacheValue> GetCacheItemInternal(string key, string region)
        {
            var fullkey = GetKey(key, region);
            var result  = _bucket.Get <CacheItem <TCacheValue> >(fullkey);

            if (result.Success)
            {
                var cacheItem = result.Value;
                if (cacheItem.Value is JToken)
                {
                    var value = cacheItem.Value as JToken;
                    cacheItem = cacheItem.WithValue((TCacheValue)value.ToObject(cacheItem.ValueType));
                }

                // TODO: test sliding
                // extend sliding expiration
                if (cacheItem.ExpirationMode == ExpirationMode.Sliding)
                {
                    _bucket.Touch(fullkey, cacheItem.ExpirationTimeout);
                }

                return(cacheItem);
            }

            return(null);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// An enumerator that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator <T> GetEnumerator()
        {
            // ReSharper disable once InconsistentlySynchronizedField
            var get = Bucket.Get <List <T> >(Key);

            if (!get.Success)
            {
                if (get.Exception != null)
                {
                    throw get.Exception;
                }
                throw new InvalidOperationException(get.Status.ToString());
            }

            return(get.Value.GetEnumerator());
        }
Exemplo n.º 14
0
        public T Get(string id)
        {
            var key    = CreateKey(id);
            var result = _bucket.Get <T>(key);

            return(!result.Success ? null : result.Value);
        }
Exemplo n.º 15
0
        public Dictionary <string, MagicDoc> GetMagicTen()
        {
            var dict = new Dictionary <string, MagicDoc>();

            for (int i = 0; i < 10; i++)
            {
                var key      = "doc" + i;
                var magicDoc = new MagicDoc
                {
                    Active  = _bucket.Get <dynamic>(key),
                    Replica = _bucket.GetFromReplica <dynamic>(key)
                };
                dict.Add(key, magicDoc);
            }
            return(dict);
        }
Exemplo n.º 16
0
        public Profile GetProfileByKey(string key)
        {
            var profile = _bucket.Get <Profile>(key).Value;

            profile.Id = key;
            return(profile);
        }
        protected override Task <WorkloadOperationResult> OnExecuteStep(IBucket bucket, int workloadIndex, int docIndex, Func <TimeSpan> getTiming)
        {
            var key       = DocKeyGenerator.Generate(workloadIndex, docIndex);
            var randomKey = DocKeyGenerator.Generate(workloadIndex, docIndex);

            if (UseSync)
            {
                var upsertResult = bucket.Upsert(key, SampleDocument);
                var getResult    = bucket.Get <string>(randomKey);

                return(Task.FromResult(
                           new WorkloadOperationResult(upsertResult.Success && getResult.Success, GetMessage(upsertResult, getResult), getTiming())
                           ));
            }

            return(Task.WhenAll(
                       bucket.UpsertAsync(key, SampleDocument), bucket.GetAsync <string>(randomKey)
                       )
                   .ContinueWith(tasks => new WorkloadOperationResult(tasks.Result[0].Success && tasks.Result[1].Success,
                                                                      GetMessage(tasks.Result[0], tasks.Result[1]),
                                                                      getTiming())
            {
                DocSize = GetDocSize(tasks.Result[1]) + SampleDocument.Length
            }));
        }
Exemplo n.º 18
0
        static void ThreadPoolInsert(IBucket bucket, int n)
        {
            for (int i = 0; i < n; i++)
            {
                int i1 = i;
                Task.Factory.StartNew(() =>
                {
                    var key = "key" + i1;
                    var value = "value" + i1;

                    /*var result = bucket.Upsert(key, value);

                    if (result.Success)
                    {
                        Console.WriteLine("Write Key: {0} - Value: {1}", key, value);*/
                    var result2 = bucket.Get<string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result2.Message);
                    }
                    /*}
                    else
                    {
                        Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                    }*/
                });
            }
        }
Exemplo n.º 19
0
        static void SynchronousInsert(IBucket bucket, int n)
        {
            for (int i = 0; i < n; i++)
            {
                var key   = "key" + i;
                var value = "value" + i;

                var result = bucket.Upsert(key, value);
                if (result.Success)
                {
                    Console.WriteLine("Write Key: {0} - Value: {1}", key, value);
                    var result2 = bucket.Get <string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result2.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                }
            }
        }
Exemplo n.º 20
0
        static void SynchronousInsert(IBucket bucket, int n)
        {
            for (int i = 0; i < n; i++)
            {
                var key = "key" + i;
                var value = "value" + i;

                var result = bucket.Upsert(key, value);
                if (result.Success)
                {
                    Console.WriteLine("Write Key: {0} - Value: {1}", key, value);
                    var result2 = bucket.Get<string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result2.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                }
            }
        }
Exemplo n.º 21
0
        public void Test_Dispose_On_Many_Threads()
        {
            Random random  = new Random(100);
            int    n       = 100;
            var    options = new ParallelOptions {
                MaxDegreeOfParallelism = 4
            };

            Parallel.For(0, n, options, i =>
            {
                try
                {
                    using (IBucket bucket = _cluster.OpenBucket())
                    {
                        var key = "key_" + i;
                        var set = bucket.Upsert(key, i);
                        Console.WriteLine("Inserted {0}: {1} Thread: {2}", key, set.Success, Thread.CurrentThread.ManagedThreadId);
                        var get = bucket.Get <int>(key);
                        Console.WriteLine("Getting {0} - {1}: {2} Thread: {3}", key, get.Value, get.Success, Thread.CurrentThread.ManagedThreadId);
                    }
                    Thread.Sleep(random.Next(0, 100));
                }
                catch (AggregateException ae)
                {
                    ae.Flatten().Handle(e =>
                    {
                        Console.WriteLine(e);
                        return(true);
                    });
                }
            });
        }
Exemplo n.º 22
0
        static void ThreadPoolInsert(IBucket bucket, int n)
        {
            for (int i = 0; i < n; i++)
            {
                int i1 = i;
                Task.Factory.StartNew(() =>
                {
                    var key   = "key" + i1;
                    var value = "value" + i1;

                    /*var result = bucket.Upsert(key, value);
                     *
                     * if (result.Success)
                     * {
                     *  Console.WriteLine("Write Key: {0} - Value: {1}", key, value);*/
                    var result2 = bucket.Get <string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result2.Message);
                    }

                    /*}
                     * else
                     * {
                     *  Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                     * }*/
                });
            }
        }
Exemplo n.º 23
0
        private static string[] MergeSchema(string[] newHeaders)
        {
            List <string> headers = new List <string>();

            var res = _bucket.Get <string>("schema");

            if (res.Success && res.Value != null)
            {
                var schema = JsonConvert.DeserializeObject <List <string> >(res.Value);
                schema.ForEach(s =>
                {
                    if (!headers.Contains(s))
                    {
                        headers.Add(s);
                    }
                });
            }

            newHeaders.ToList().ForEach(h =>
            {
                if (!headers.Contains(h))
                {
                    headers.Add(h);
                }
            });

            headers.Sort();
            return(headers.Where(h => !string.IsNullOrEmpty(h)).ToArray());
        }
Exemplo n.º 24
0
        public User FindById(string id)
        {
            var result = _bucket.Get <User>(id);
            var user   = result.Value;

            user.Id = id;
            return(user);
        }
Exemplo n.º 25
0
        private static void PessimisticLockingExample1(IBucket bucket)
        {
            // tag::PessimisticLockingExample1[]
            // create initial document
            bucket.Upsert("myshield", new { defenseLevel = 1, name = "Mirror Shield" });

            // document is retrieved and locked by A
            var shieldAResult = bucket.GetAndLock <dynamic>("myshield", TimeSpan.FromMilliseconds(30000));
            var shieldA       = shieldAResult.Value;
            // B attempts to get and lock it as well
            var shieldBResult = bucket.GetAndLock <dynamic>("myshield", TimeSpan.FromMilliseconds(30000));

            if (!shieldBResult.Success)
            {
                Console.WriteLine("B couldn't establish a lock, trying a plain Get");
                shieldBResult = bucket.Get <dynamic>("myshield");
            }

            // B tries to make a change, despite not having a lock
            Console.WriteLine("'B' is updating the document");
            var shieldB = shieldBResult.Value;

            shieldB.defenseLevel = 3;
            IOperationResult bResult = bucket.Replace("myshield", shieldB);

            if (!bResult.Success)
            {
                Console.WriteLine($"B was unable to make a change: {bResult.Message}");
                Console.WriteLine();
            }

            // A can make the change, but MUST use the CAS value
            shieldA.defenseLevel = 2;
            IOperationResult aResult = bucket.Replace("myshield", shieldA);

            if (!aResult.Success)
            {
                Console.WriteLine($"A tried to make a change, but forgot to use a CAS value: {aResult.Message}");
                Console.WriteLine();
                Console.WriteLine("Trying again with CAS this time");
                aResult = bucket.Replace("myshield", shieldA, shieldAResult.Cas);
                if (aResult.Success)
                {
                    Console.WriteLine("Success!");
                }
            }

            // now, the document is unlocked
            // so B can try again
            bResult = bucket.Replace("myshield", shieldB);
            if (bResult.Success)
            {
                Console.WriteLine($"B was able to make a change.");
            }
            // end::PessimisticLockingExample1[]
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            // tag::cluster[]
            var clientConfig = new ClientConfiguration
            {
                Servers = new List <Uri>
                {
                    new Uri("http://172.17.0.2"),
                    new Uri("http://172.17.0.3"),
                    new Uri("http://172.17.0.4")
                }
            };
            var cluster = new Cluster(clientConfig);

            var credentials = new PasswordAuthenticator("myuser", "password");

            cluster.Authenticate(credentials);

            _bucket = cluster.OpenBucket("mybucket");
            // end::cluster[]

            // tag::createdocs[]
            var docKeys = new List <string>();

            for (var i = 0; i < numDocuments; i++)
            {
                var key = "documentKey" + i;
                docKeys.Add(key);
                _bucket.Upsert(key, new { name = "Document" + i });
            }
            // end::createdocs[]

            // tag::mainloop[]
            var iteration = 0;

            while (true)
            {
                Console.WriteLine($"Getting {numDocuments} documents [{iteration++}]");
                foreach (var docKey in docKeys)
                {
                    var result = _bucket.Get <dynamic>(docKey);
                    if (terse)
                    {
                        ShowResultTerse(result, docKey);
                    }
                    else
                    {
                        ShowResult(result, docKey);
                    }
                }
                Console.WriteLine();

                Thread.Sleep(2000);
            }
            // end::mainloop[]
        }
Exemplo n.º 27
0
        public ActionResult KeyValueExample()
        {
            var key = Guid.NewGuid().ToString();

            _bucket.Insert(key, FooBar.Generate());
            var foobar = _bucket.Get <FooBar>(key).Value;

            ViewBag.Key = key;
            return(View(foobar));
        }
Exemplo n.º 28
0
        // just to show that the bucket is being injected properly
        // tag::About[]
        public IActionResult About()
        {
            // get the route document for Columbus to Chicago (United)
            var route = _bucket.Get <dynamic>("route_56027").Value;

            // display the equipment number of the route
            ViewData["Message"] = "CMH to ORD - " + route.equipment;

            return(View());
        }
        public IActionResult Point([FromBody] PointSearch point)
        {
            var query = new GeoDistanceQuery();

            query.Latitude(point.Latitude);
            query.Longitude(point.Longitude);
            query.Distance(point.DistanceWithUnits);
            var searchParams = new SearchParams()
                               // .Fields("geo", "name") // omitting because of bug NCBC-1651
                               .Limit(10)
                               .Timeout(TimeSpan.FromMilliseconds(10000));
            var searchQuery = new SearchQuery
            {
                Query        = query,
                Index        = "mygeoindex",
                SearchParams = searchParams
            };
            var results = _bucket.Query(searchQuery);

            var list = new List <GeoSearchResult>();

            foreach (var hit in results.Hits)
            {
                // *** this part shouldn't be necessary
                // the geo and name should come with the search results
                // but there's an SDK bug NCBC-1651
                var doc = _bucket.Get <dynamic>(hit.Id).Value;
                // ****************
                list.Add(new GeoSearchResult
                {
                    Latitude   = doc.geo.lat,
                    Longitude  = doc.geo.lon,
                    InfoWindow = new InfoWindow
                    {
                        Content = doc.name + "<br />" +
                                  doc.city + ", " +
                                  doc.state + " " +
                                  doc.country
                    }
                });
            }
            return(Ok(list));
        }
        /// <summary>
        /// Gets the dictionary document.
        /// </summary>
        /// <returns></returns>
        protected virtual IDictionary <TKey, TValue> GetDictionary()
        {
            var get = Bucket.Get <IDictionary <TKey, TValue> >(Key);

            if (!get.Success && get.Exception != null)
            {
                throw get.Exception;
            }
            return(get.Value);
        }
Exemplo n.º 31
0
        protected T Get(Guid id)
        {
            var result = _bucket.Get <T>(CreateKey(id));

            if (!result.Success)
            {
                throw result.Exception;
            }

            return(result.Value);
        }
Exemplo n.º 32
0
 private void LoadSchema()
 {
     Task.Run(() =>
     {
         var schema = _bucket.Get <string>("schema");
         if (schema != null && schema.Success)
         {
             Fields = new List <string>(JsonConvert.DeserializeObject <string[]>(schema.Value));
         }
     });
 }
        /// <summary>
        /// Loads a session state item from the bucket. This function is publicly accessible
        /// so that you have direct access to session data from another application if necesssary.
        /// We use this so our front end code can determine if an employee is logged into our back
        /// end application to give them special permissions, without the session data being actually common
        /// between the two applications.
        /// </summary>
        /// <param name="headerPrefix">Prefix for the header data</param>
        /// <param name="dataPrefix">Prefix for the real data</param>
        /// <param name="bucket">Couchbase bucket to load from</param>
        /// <param name="id">Session ID</param>
        /// <param name="metaOnly">True to load only meta data</param>
        /// <returns>Session store item read, null on failure</returns>
        public static SessionStateItem Load(
            string headerPrefix,
            string dataPrefix,
            IBucket bucket,
            string id,
            bool metaOnly)
        {
            // Read the header value from Couchbase
            var header = bucket.Get<byte[]>(CouchbaseSessionStateProvider.HeaderPrefix + id);
            if (header.Status != ResponseStatus.Success)
            {
                return null;
            }

            // Deserialize the header values
            SessionStateItem entry;
            using (var ms = new MemoryStream(header.Value))
            {
                entry = LoadHeader(ms);
            }
            entry.HeadCas = header.Cas;

            // Bail early if we are only loading the meta data
            if (metaOnly)
            {
                return entry;
            }

            // Read the data for the item from Couchbase
            var data = bucket.Get<byte[]>(CouchbaseSessionStateProvider.DataPrefix + id);
            if (data.Value == null)
            {
                return null;
            }
            entry.DataCas = data.Cas;

            // Deserialize the data
            using (var ms = new MemoryStream(data.Value))
            {
                using (var br = new BinaryReader(ms))
                {
                    entry.Data = SessionStateItemCollection.Deserialize(br);
                }
            }

            // Return the session entry
            return entry;
        }
Exemplo n.º 34
0
        static void ParallerInsert(IBucket bucket, int n)
        {
            var options = new ParallelOptions {MaxDegreeOfParallelism = 4};
            Parallel.For(0, n, options, i =>
            {
                var key = "key" + i;
                int value =  i;

              var result = bucket.Upsert(key, value);

                if (result.Success)
                {
                    Console.WriteLine("Write Key: {0} - Value: {1}", key, value);
                   
                    var result2 = bucket.Get<int>(key);
                    if (result2.Success)
                    {
                        if (result2.Value != value)
                        {
                            throw new Exception();
                        }
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result2.Message);
                    }
               }
                else
                {
                    Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                }
               
            });
        }