public void Test_Store_StoreMode_Set()
 {
     var client = new CouchbaseClient("memcached-config");
     var result = client.Store(StoreMode.Set, Key, "value");
     Assert.AreEqual(result, true);
     client.Remove(Key);
 }
예제 #2
1
 bool ICacheManager.Set(string key, object value, DateTime expiry)
 {
     bool bRet = false;
     using (var client = new CouchbaseClient(config))
     {
         bRet = client.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, expiry);
     }
     return bRet;
 }
예제 #3
0
 static void Main(string[] args)
 {
     var client = new CouchbaseClient();
     var returnValue = client.Get("");
     System.Console.WriteLine("OUTPUT: - {0}", returnValue);
     System.Console.ReadLine();
 }
예제 #4
0
        public override void Run()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools/"));
            config.Bucket = "default";

            var client = new CouchbaseClient(config);

            //add or replace a key
            client.Store(StoreMode.Set, "key_1", 1);
            Console.WriteLine(client.Get("key_1"));

            var success = client.Store(StoreMode.Add, "key_1", 2);
            Console.WriteLine(success); //will return false

            success = client.Store(StoreMode.Replace, "key_1", 2);
            Console.WriteLine(success); //will return true

            success = client.Store(StoreMode.Replace, "key_2", 2);
            Console.WriteLine(success); //will return false

            //add a new key
            client.Store(StoreMode.Set, "key_3", 1);
            Console.WriteLine(client.Get("key_3"));

            client.Remove("key_1");
            client.Remove("key_2");
        }
예제 #5
0
        private static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Connecting with Couchbase...");
                var couchbaseClient = new CouchbaseClient();

                var client = new StatsClient(couchbaseClient);

                Console.WriteLine("Obtaining statistics...");
                var stats = client.GetStats();

                Console.WriteLine("Storing...");
                var data = Serialize(stats);
                File.WriteAllText(ConfigurationManager.AppSettings["reportFilePath"], data);

                Console.WriteLine("Done!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.Write("Press enter to exit...");
                Console.ReadLine();
            }
        }
        static void AAAA()
        {
            //ITranscoder tr = new JsonTranscoder();

            //Dump(tr.Serialize("a").Data);
            //Dump(tr.Serialize(null).Data);
            //Dump(tr.Serialize(1.0f).Data);
            //Dump(tr.Serialize(2.4d).Data);
            //Dump(tr.Serialize(08976543).Data);
            //Dump(tr.Serialize(new { A = "a", B = 2, C = true, D = new[] { 1, 2, 3, 4 } }).Data);

            //var o = tr.Deserialize(tr.Serialize(new Tmp { A = "a" }));

            //Console.WriteLine(tr.Deserialize(tr.Serialize((Single)1)).GetType());
            //Console.WriteLine(tr.Deserialize(tr.Serialize((Double)1)).GetType());

            var mbc = new CouchbaseClientConfiguration();
            mbc.Urls.Add(new Uri("http://192.168.47.128:8091/pools/default"));

            var c = new CouchbaseClient(mbc);

            //	for (var i = 0; i < 10; i++) c.Store(StoreMode.Set, "json_" + i, i + 100);
            //for (var i = 0; i < 10; i++) c.Store(StoreMode.Set, "binary_" + i, i + 100);

            //for (var i = 0; i < 1000; i++)
            //    c.Store(StoreMode.Set, "key_" + i, i);

            var r = c.GetView("test", "all").Limit(20);
            var tmp = c.Get(r);

            //Console.WriteLine(r.Count);
        }
예제 #7
0
        static void ParallerInsert(CouchbaseClient client, int n)
        {
            var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };

            Parallel.For(0, n, options, i =>
            {
                var key = "key" + i;
                var value = "value" + i;

                var result = client.ExecuteStore(StoreMode.Set, key, value);
                if (result.Success)
                {
                    Console.WriteLine("Write Key: {0} - Value: {1}", key, value);
                    var result2 = client.ExecuteGet<string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                }
            });
        }
예제 #8
0
        static void SynchronousInsert(CouchbaseClient client, int n)
        {
            for (int i = 0; i < n; i++)
            {
                var key = "key" + i;
                var value = "value" + i;

                var result = client.ExecuteStore(StoreMode.Set, key, value);

                if (result.Success)
                {
                    Console.WriteLine("Write Key: {0} - Value: {1}", key, value);
                    var result2 = client.ExecuteGet<string>(key);
                    if (result2.Success)
                    {
                        Console.WriteLine("Read Key: {0} - Value: {1}", key, result2.Value);
                    }
                    else
                    {
                        Console.WriteLine("Read Error: {0} - {1}", key, result.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Write Error: {0} - {1}", key, result.Message);
                }
            }
        }
 public void View_Operations_Succeed_When_Initialize_Connection_Is_True()
 {
     var config = ConfigSectionUtils.GetConfigSection<CouchbaseClientSection>("httpclient-config-initconn");
     var client = new CouchbaseClient(config);
     var view = client.GetView<City>("cities", "by_name", true).Stale(StaleMode.False);
     viewPass(view);
 }
        public void When_Using_App_Config_And_Design_Document_Name_Transformer_Is_Not_Set_Production_Mode_Is_Default()
        {
            var config = ConfigurationManager.GetSection("min-config") as CouchbaseClientSection;
            var client = new CouchbaseClient(config); //client sets up transformer

            Assert.That(config.DocumentNameTransformer.Type.Name, Is.StringMatching("ProductionModeNameTransformer"));
        }
예제 #11
0
        public override void Run()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools/"));
            config.Bucket = "beer-sample";

            var client = new CouchbaseClient(config);

            Console.WriteLine("Breweries by_name, limited to 10 records");
            var view = client.GetView("breweries", "by_name").Limit(10);

            Console.WriteLine("Breweries by_name, output the keys");
            view = client.GetView("breweries", "by_name").Limit(10);
            foreach (var item in view)
            {
                Console.WriteLine("Key: " + item.ViewKey.First());
            }

            Console.WriteLine("Breweries by_name, query by key range (y or Y)");
            view = client.GetView("breweries", "by_name").StartKey("y").EndKey("z");
            foreach (var item in view)
            {
                Console.WriteLine("Key: " + item.ViewKey.First());
            }

            Console.WriteLine("Breweries by_name, output the keys (y only)");
            view = client.GetView("breweries", "by_name").StartKey("y").EndKey("Y");
            foreach (var item in view)
            {
                Console.WriteLine("Key: " + item.ViewKey.First());
            }
        }
예제 #12
0
        public ActionResult Index(string setupKey)
        {
			try
			{
				if (setupKey != ConfigurationManager.AppSettings["TapMapSetupKey"])
				{
					throw new ApplicationException("Invalid TapMapSetupKey.  Please review the appSetting \"TapMapSetupKey\" in Web.config");
				}

				var client = new CouchbaseClient();				

				var root = Path.Combine(Environment.CurrentDirectory, Server.MapPath("~/App_Data"));
				import(client, "brewery", root, "breweries.zip");
				import(client, "beer", root, "beers.zip");
				import(client, "user", root, "users.zip");
				import(client, "tap", root, "taps.zip");
				
				createViewFromFile(Path.Combine(root, @"views\UserViews.json"), "users");
				createViewFromFile(Path.Combine(root, @"views\BreweryViews.json"), "breweries");
				createViewFromFile(Path.Combine(root, @"views\BeerViews.json"), "beers");
				createViewFromFile(Path.Combine(root, @"views\TapViews.json"), "taps");

				ViewBag.Message = "Successfully loaded views and data";
				ViewBag.MessageColor = "green";
			}
			catch (Exception ex)
			{
				ViewBag.Message = ex.Message;
				ViewBag.MessageColor = "red";
			}

			return View();
        }
        public void Test_That_Starved_SocketPool_Sends_StatusCode_SocketPoolTimeout()
        {
            try
            {
                s_cbClient = new CouchbaseClient("socket-timeout");

                List<Thread> workers = new List<Thread>();
                for (int i = 0; i < THREADS; i++)
                {
                    Thread t = new Thread(ThreadBody);
                    t.Priority = ThreadPriority.BelowNormal;
                    workers.Add(t);
                }
                foreach (Thread t in workers)
                {
                    t.Join();
                }
                Console.WriteLine();
                Console.WriteLine("done");
                Thread.Sleep(1000);
            }
            finally
            {
                s_cbClient.Dispose();
            }
        }
예제 #14
0
 public ViewRunner(CouchbaseClientConfiguration config)
 {
     if (_client == null)
     {
         _client = new CouchbaseClient(config);
     }
 }
예제 #15
0
        public override void Run()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools/"));
            config.Bucket = "default";

            var client = new CouchbaseClient(config);

            //Store a key, but don't return success until it is written
            //to disk on the master (or times out)
            var success = client.ExecuteStore(StoreMode.Set, "key_1", 2, PersistTo.One);
            Console.WriteLine(success.Success); //will return false

            //Store a key, but don't return success until it is
            //replicated to 2 nodes (or times out)
            //will fail on a single or two node cluster
            success = client.ExecuteStore(StoreMode.Set, "key_1", 2, ReplicateTo.Two);
            Console.WriteLine(success.Success); //will return false

            //Store a key, but don't return success until it is written
            //to disk on the master and replicated to 2 nodes (or times out)
            //will fail on a single or two node cluster
            success = client.ExecuteStore(StoreMode.Set, "key_1", 2, PersistTo.One, ReplicateTo.Two);
            Console.WriteLine(success.Success); //will return false

            client.Remove("key_1");
            client.Remove("key_2");
        }
예제 #16
0
        public override void Run()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://*****:*****@cia.gov",
                Password = "******",
                Logins = 0
            };

            var user2 = new User
            {
                Username = "******",
                Name = "Nicholas Brody",
                Email = "*****@*****.**",
                Password = "******",
                Logins = 0
            };

            //store the user - ExecuteStore returns detailed error info, if any
            var result1 = client.ExecuteStore(StoreMode.Set, user1.Email, user1);
            if (!result1.Success)
            {
                Console.WriteLine("Store failed with message {0} and status code {1}", result1.Message, result1.StatusCode);

                if (result1.Exception != null)
                {
                    throw result1.Exception;
                }
            }

            var result2 = client.ExecuteStore(StoreMode.Set, user2.Email, user2);
            //same check as result1 would be useful

            var doc = client.Get<User>(user1.Email);
            Console.WriteLine(doc.Name);

            //get doc with extended info
            var result = client.ExecuteGet<User>(user1.Email);

            //update login count
            doc.Logins += 1;

            //update document (ignore errors for lab)
            client.ExecuteStore(StoreMode.Replace, user1.Email, doc);

            doc = client.Get<User>(user1.Email);
            Console.WriteLine("User {0} had {1} logins", doc.Name, doc.Logins);

            client.Remove(user1.Email);
            client.Remove(user2.Email);
        }
예제 #17
0
        public void When_Bucket_Is_Authenticated_View_Returns_Results()
        {
            Client = GetClient(_bucketName, _bucketPassword);
            var view = Client.GetView("cities", "by_name");

            //Whether or view has data is regardless, what matters is that a authenticated call returned succesfully
            Assert.IsNotNull(view);
        }
예제 #18
0
 /// <summary>
 /// Retrieve the brewery object by key
 /// </summary>
 /// <param name="breweryId"></param>
 /// <returns></returns>
 public Brewery GetBrewery(string breweryId)
 {
     using (CouchbaseClient client = new CouchbaseClient())
     {
         Brewery brewery = client.GetJson<Brewery>(breweryId);
         return brewery;
     }
 }
예제 #19
0
 public ViewRunner(string sectionName = "couchbase")
 {
     if (_client == null)
     {
         _config = ConfigurationManager.GetSection(sectionName) as CouchbaseClientSection;
         _client = new CouchbaseClient(_config);
     }
 }
예제 #20
0
        static void ProcessWithParallel(CouchbaseClient client, int numberOfItems)
        {
            var options = new ParallelOptions {
                MaxDegreeOfParallelism = 4
            };

            Parallel.For(0, numberOfItems, options, i => PerformGetSet(client, i));
        }
예제 #21
0
 static void ProcessWithTap(CouchbaseClient client, int numberOfItems)
 {
     for (var i = 0; i < numberOfItems; i++)
     {
         var i1 = i;
         Task.Run(() => PerformGetSet(client, i1));
     }
 }
예제 #22
0
        public CommandBase(CouchbaseClient client,
			string key,
			CbcOptions options)
        {
            Key = key;
            this.client = client;
            this.options = options;
        }
예제 #23
0
 public ViewRunner(string sectionName = "couchbase")
 {
     if (_client == null)
     {
         _config = ConfigurationManager.GetSection(sectionName) as CouchbaseClientSection;
         _client = new CouchbaseClient(_config);
     }
 }
        public void When_Using_Code_Config_And_Design_Document_Name_Transformer_Is_Not_Set_Production_Mode_Is_Default()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://10.0.0.79:8091/pools"));
            var client = new CouchbaseClient(config); //client sets up transformer

            Assert.That(config.DesignDocumentNameTransformer, Is.InstanceOf<ProductionModeNameTransformer>());
        }
 public void When_FlushAll_Is_Called_On_BinaryNode_No_Exception_Is_Raised()
 {
     var config = ConfigurationManager.GetSection("memcached-config") as CouchbaseClientSection;
     using (var client = new CouchbaseClient(config))
     {
         client.FlushAll();
     }
 }
예제 #26
0
        public void View_Operations_Succeed_When_Initialize_Connection_Is_True()
        {
            var config = ConfigSectionUtils.GetConfigSection <CouchbaseClientSection>("httpclient-config-initconn");
            var client = new CouchbaseClient(config);
            var view   = client.GetView <City>("cities", "by_name", true).Stale(StaleMode.False);

            viewPass(view);
        }
예제 #27
0
 protected override void InitialiseInternal()
 {
     if (Client == null)
     {
         Log.Debug("CouchbaseCache.Initialise - initialising");
         Client = new CouchbaseClient();
     }
 }
예제 #28
0
 public CommandBase(CouchbaseClient client,
                    string key,
                    CbcOptions options)
 {
     Key          = key;
     this.client  = client;
     this.options = options;
 }
예제 #29
0
 /// <summary>
 /// Retrieve the beer object by name
 /// </summary>
 /// <param name="beerName"></param>
 /// <returns></returns>
 public Beer GetBeer(string beerName)
 {
     using (CouchbaseClient client = new CouchbaseClient())
     {
         Beer beer = client.GetJson<Beer>(beerName);
         return beer;
     }
 }
예제 #30
0
 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         Log.Debug("CouchbaseCache.Initialise - initialising");
         _cache = new CouchbaseClient();
     }
 }
예제 #31
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Creating client...");
            _client = new CouchbaseClient();

            Console.WriteLine("Importing Documents {0} through {1}...", _startId, _endId);
            Import();
        }
        static LeaderBoardController()
        {
            var config = new CouchbaseClientConfiguration();
            config.Bucket = "default";
            config.Urls.Add(new Uri("http://192.168.2.1:8091/pools/"));

            _client = new CouchbaseClient(config);
        }
예제 #33
0
        public void Test_Store_StoreMode_Set()
        {
            var client = new CouchbaseClient("memcached-config");
            var result = client.Store(StoreMode.Set, Key, "value");

            Assert.AreEqual(result, true);
            client.Remove(Key);
        }
        public void When_Bucket_Is_Authenticated_And_Bad_Credentials_Are_Provided_Exception_Is_Thrown()
        {
            Client = GetClient(_bucketName, "bad_credentials");
            var view = Client.GetView("cities", "by_name");

            var row = view.First();
            Assert.IsNotNull(row);
        }
 public void Stop()
 {
     lock (syncObject)
     {
         clientInstance.Dispose();
         clientInstance = null;
     }
 }
        public void When_Flushing_Bucket_Data_Are_Removed()
        {
            var storedConfig = ConfigurationManager.GetSection("couchbase") as ICouchbaseClientConfiguration;
            var config       = new CouchbaseClientConfiguration();

            config.Bucket   = "Bucket-" + DateTime.Now.Ticks;
            config.Username = storedConfig.Username;
            config.Password = storedConfig.Password;
            config.Urls.Add(storedConfig.Urls[0]);

            var cluster = new CouchbaseCluster(config);

            cluster.CreateBucket(new Bucket
            {
                Name       = config.Bucket,
                AuthType   = AuthTypes.Sasl,
                BucketType = BucketTypes.Membase,
                Quota      = new Quota {
                    RAM = 100
                },
                ReplicaNumber = ReplicaNumbers.Zero,
                FlushOption   = FlushOptions.Enabled
            }
                                 );

            Bucket bucket = null;

            for (int i = 0; i < 10; i++)             //wait for bucket to be ready to accept ops
            {
                bucket = waitForBucket(config.Bucket);
                if (bucket.Nodes.First().Status == "healthy")
                {
                    break;
                }
                Thread.Sleep(1000);
            }

            Assert.That(bucket, Is.Not.Null);

            var client = new CouchbaseClient(config);

            var storeResult = client.ExecuteStore(StoreMode.Set, "SomeKey", "SomeValue");

            Assert.That(storeResult.Success, Is.True, "Message: " + storeResult.Message);

            var getResult = client.ExecuteGet <string>("SomeKey");

            Assert.That(getResult.Success, Is.True);
            Assert.That(getResult.Value, Is.StringMatching("SomeValue"));

            cluster.FlushBucket(config.Bucket);

            getResult = client.ExecuteGet <string>("SomeKey");
            Assert.That(getResult.Success, Is.False);
            Assert.That(getResult.Value, Is.Null);

            _Cluster.DeleteBucket(config.Bucket);
        }
        public static CouchbaseClient CreateCouchbaseClient()
        {
            if (_client == null)
            {
                _client = new CouchbaseClient();
            }

            return _client;
        }
        public void When_Using_Code_Config_And_Design_Document_Name_Transformer_Is_Not_Set_Production_Mode_Is_Default()
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri("http://localhost:8091/pools"));
            var client = new CouchbaseClient(config);             //client sets up transformer

            Assert.That(config.DesignDocumentNameTransformer, Is.InstanceOf <ProductionModeNameTransformer>());
        }
        public static CouchbaseClient CreateCouchbaseClient()
        {
            if (_client == null)
            {
                _client = new CouchbaseClient();
            }

            return(_client);
        }
        public void When_Bucket_Is_Authenticated_And_Bad_Credentials_Are_Provided_Exception_Is_Thrown()
        {
            _client = GetClient(_bucketName, "bad_credentials");
            var view = _client.GetView("cities", "by_name");

            var row = view.First();

            Assert.IsNotNull(row);
        }
예제 #41
0
        /// <summary>
        /// Initializes static members of the <see cref="RepositoryBase{T}" /> class.
        /// </summary>
        public RepositoryBase()
        {
            _className = GetType().Namespace + "::" + GetType().Name;

            if (Client == null)
            {
                Client = CouchbaseManager.CouchbaseClient;
            }
        }
예제 #42
0
 bool ICacheManager.Delete(string key)
 {
     bool bRet = false;
     using (var client = new CouchbaseClient(config))
     {
         bRet = client.Remove(key);
     }
     return bRet;
 }
예제 #43
0
        public void When_Creating_New_Bucket_Item_Counts_Are_Set_On_Basic_Stats()
        {
            var bucketName = "Bucket-" + DateTime.Now.Ticks;

            _bucket = new Bucket
            {
                Name       = bucketName,
                AuthType   = AuthTypes.Sasl,
                BucketType = BucketTypes.Membase,
                Quota      = new Quota {
                    RAM = 100
                },
                ReplicaNumber = ReplicaNumbers.Zero
            };
            Cluster.CreateBucket(_bucket);

            _bucket = waitForListedBucket(bucketName);
            Assert.That(_bucket, Is.Not.Null, "New bucket was null");

            var count = _bucket.BasicStats.ItemCount;

            Assert.That(count, Is.EqualTo(0), "Item count was not 0");

            var client = new CouchbaseClient(bucketName, "");

            var result = false;

            for (var i = 0; i < 10; i++)
            {
                var aResult = client.ExecuteStore(StoreMode.Set, "a", "a");
                var bResult = client.ExecuteStore(StoreMode.Set, "b", "b");
                var cResult = client.ExecuteStore(StoreMode.Set, "c", "c");
                result = aResult.Success & bResult.Success & cResult.Success;
                if (result)
                {
                    break;
                }
                Thread.Sleep(2000);                 //wait for the bucket to be ready for writing
            }
            Assert.That(result, Is.True, "Store operations failed");

            for (var i = 0; i < 10; i++)
            {
                _bucket = Cluster.ListBuckets().Where(b => b.Name == bucketName).FirstOrDefault();
                count   = _bucket.BasicStats.ItemCount;
                if (count == 3)
                {
                    break;
                }
                Thread.Sleep(2000);                 //wait for the bucket to compute writes into basic stats
            }
            Assert.That(count, Is.EqualTo(3), "Item count was not 3");

            Cluster.DeleteBucket(bucketName);
            _bucket = waitForListedBucket(bucketName);
            Assert.That(_bucket, Is.Null, "Deleted bucket still exists");
        }
예제 #44
0
            public Worker()
            {
                var config = new CouchbaseClientConfiguration {
                    Bucket = "default"
                };

                config.Urls.Add(new Uri("http://localhost:8091/pools"));
                _client = new CouchbaseClient(config);
            }
        public void When_Using_Code_Config_And_Design_Document_Name_Transformer_Is_Not_Set_Production_Mode_Is_Default()
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchbaseServerUrl"] + "/pools"));
            var client = new CouchbaseClient(config);             //client sets up transformer

            Assert.That(config.DesignDocumentNameTransformer, Is.InstanceOf <ProductionModeNameTransformer>());
        }
예제 #46
0
        public void Test_Store_StoreMode_Add_Will_Fail_If_Key_Exists()
        {
            var client = new CouchbaseClient("memcached-config");
            var result = client.Store(StoreMode.Set, Key, "value");
            var resultWhenKeyExists = client.Store(StoreMode.Add, Key, "value");

            Assert.AreEqual(resultWhenKeyExists, false);
            client.Remove(Key);
        }
예제 #47
0
        public void When_FlushAll_Is_Called_On_BinaryNode_No_Exception_Is_Raised()
        {
            var config = ConfigurationManager.GetSection("memcached-config") as CouchbaseClientSection;

            using (var client = new CouchbaseClient(config))
            {
                client.FlushAll();
            }
        }
예제 #48
0
        bool ICacheManager.Replace(string key, object value, DateTime expiry)
        {
            bool bRet = false;

            using (var client = new CouchbaseClient(config))
            {
                bRet = client.Store(Enyim.Caching.Memcached.StoreMode.Replace, key, value, expiry);
            }
            return(bRet);
        }
예제 #49
0
 public CbcSet(CouchbaseClient cli,
               string key, CbcOptions options)
     : base(cli, key, options)
 {
     Value = options.Value;
     if (Value == null)
     {
         throw new ArgumentException("Set command needs value");
     }
 }
예제 #50
0
 /// <summary>
 /// set up our client to talk to the cache
 /// </summary>
 static void InitializeClient()
 {
     var section = (ICouchbaseClientConfiguration)ConfigurationManager.GetSection(ConfigSectionName);
     if (section == null || section.Urls.Count <= 0)
     throw new ConfigurationErrorsException(
     "Cannot create CouchbaseClient. Got a default section with 0 URLs when trying the .config file");
     Console.WriteLine("{0} Couchbase REST URLs are: {1}", section.Urls.Count, String.Join(", ", section.Urls));
     _couchbaseClient = new CouchbaseClient(section);
     Console.WriteLine("Connected {0}", _couchbaseClient);
 }
예제 #51
0
        public static CasResult <bool> CasJson(this CouchbaseClient client, StoreMode storeMode, string key, object value)
        {
            var json = JsonConvert.SerializeObject(value,
                                                   Formatting.None,
                                                   new JsonSerializerSettings {
                ContractResolver = new DocumentIdContractResolver()
            });

            return(client.Cas(storeMode, key, json));
        }
예제 #52
0
        bool ICacheManager.Delete(string key)
        {
            bool bRet = false;

            using (var client = new CouchbaseClient(config))
            {
                bRet = client.Remove(key);
            }
            return(bRet);
        }
        public void When_Bucket_Is_Authenticated_And_No_Credentials_Are_Provided_Exception_Is_Thrown()
        {
            Client = GetClient(_bucketName, "");
            var view = Client.GetView("cities", "by_name");

            var row = view.First();

            //Test will end on previous line
            Assert.IsNotNull(row);
        }
        public void When_Bucket_Is_Authenticated_And_No_Credentials_Are_Provided_Exception_Is_Thrown()
        {
            _client = GetClient(_bucketName, "");
            var view = _client.GetView("cities", "by_name");

            var row = view.First();

            //Test will end on previous line
            Assert.IsNotNull(row);
        }
예제 #55
0
        /// <summary>
        /// Creates a utility object that can be used to perform operations against a Couchbase server.
        /// Note:
        /// Uses the authentication and bucket information from the supplied configuration item.
        /// </summary>
        /// <param name="configurationFolderPath">The path to the folder containing the encrypted configuration file containing information required to establish the connection to the server.</param>
        /// <param name="configurationItemName">The name of configuration item containing the information required to connect to the server. (Typically it's filename without the extension.)</param>
        public CouchbaseUtility(string configurationFolderPath, string configurationItemName)
        {
            if (!string.IsNullOrWhiteSpace(configurationFolderPath) && !string.IsNullOrWhiteSpace(configurationItemName))
            {
                ConfigurationItem configItem = new ConfigurationItem(configurationFolderPath, configurationItemName, true);

                try
                {
                    // Read the values required from the configuration file.
                    StringReader reader   = new StringReader(configItem.Value);
                    string       urlsLine = reader.ReadLine();
                    string[]     urls     = new string[] { };
                    if (!string.IsNullOrWhiteSpace(urlsLine))
                    {
                        urls = urlsLine.Split(',');
                    }
                    string bucket         = reader.ReadLine();
                    string bucketPassword = reader.ReadLine();

                    if (urls.Length > 0 && !string.IsNullOrWhiteSpace(bucket) && !string.IsNullOrWhiteSpace(bucketPassword))
                    {
                        // Configure the client.
                        CouchbaseClientConfiguration config = new CouchbaseClientConfiguration();
                        foreach (string url in urls)
                        {
                            config.Urls.Add(new Uri(url));
                        }
                        config.Bucket         = bucket;
                        config.BucketPassword = bucketPassword;

                        // Create a connection with the Couchbase bucket.
                        client = new CouchbaseClient(config);
                    }
                    else
                    {
                        throw new FormatException("Could not load configuration data from file. File is not of the correct format.");
                    }
                }
                catch
                {
                    throw new FormatException("Could not load configuration data from file. File is not of the correct format.");
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(configurationFolderPath))
                {
                    throw new ArgumentNullException("configurationFolderPath", "A path to a configuration items folder must be supplied.");
                }
                else
                {
                    throw new ArgumentNullException("configurationItemName", "The name of the configuration item to load must be supplied.");
                }
            }
        }
예제 #56
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            //Manually configure CouchbaseClient
            //May also use app/web.config section
            var config = new CouchbaseClientConfiguration();

            config.Bucket         = "default";
            config.BucketPassword = "";
            config.Urls.Add(new Uri("http://10.0.0.79:8091/pools"));
            config.DesignDocumentNameTransformer = new ProductionModeNameTransformer();
            config.HttpClientFactory             = new HammockHttpClientFactory();

            //Quick test of Store/Get operations
            var client = new CouchbaseClient(config);
            var result = client.Store(StoreMode.Set, "foo", "bar");

            Debug.Assert(result, "Store failed");
            Console.WriteLine("Item saved successfully");

            var value = client.Get <string>("foo");

            Debug.Assert(value == "bar", "Get failed");
            Console.WriteLine("Item retrieved succesfully");

            processJson(client);

            Console.WriteLine("\r\n\r\n***  SAMPLE VIEWS MUST BE CREATED - SEE SampleViews.js in Data directory ***");

            Console.WriteLine("\r\n\r\nRequesting view all_breweries");
            var allBreweries = client.GetView <Brewery>("breweries", "all_breweries");

            foreach (var item in allBreweries)
            {
                Console.WriteLine(item.Name);
            }

            Console.WriteLine("\r\n\r\nRequesting view beers_by_name");
            var beersByName = client.GetView <Beer>("beers", "beers_by_name").StartKey("T");

            foreach (var item in beersByName)
            {
                Console.WriteLine(item.Name);
            }

            Console.WriteLine("\r\n\r\nRequesting view beers_by_name_and_abv");
            var beersByNameAndABV = client.GetView <Beer>("beers", "beers_by_name_and_abv")
                                    .StartKey(new object[] { "T", 6 });

            foreach (var item in beersByNameAndABV)
            {
                Console.WriteLine(item.Name);
            }
        }
예제 #57
0
        static CouchbaseManager()
        {
            CouchbaseClientConfiguration couchbaseClientConfiguration = new CouchbaseClientConfiguration()
            {
                Bucket         = "default",
                BucketPassword = string.Empty
            };

            couchbaseClientConfiguration.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchBaseServer"]));
            _instance = new CouchbaseClient(couchbaseClientConfiguration);
        }
예제 #58
0
        static void Main(string[] args)
        {
            try
            {
                var client = new CouchbaseClient();
                foreach (var file in Directory.GetFiles(Environment.CurrentDirectory, "*.txt"))
                {
                    var type = InflectorNet.Singularize(new FileInfo(file).Name.Replace(".txt", "").ToLower());
                    using (var sr = new StreamReader(file))
                    {
                        var keys = sr.ReadLine().Split('|');
                        var dict = new Dictionary <string, object>()
                        {
                            { "type", type }
                        };

                        string line = null;
                        while ((line = sr.ReadLine()) != null)
                        {
                            var values = line.Split('|');
                            for (var i = 0; i < values.Length; i++)
                            {
                                var    keyData = keys[i].Split(':');
                                object value   = null;
                                switch (keyData[0])
                                {
                                case "i":
                                    value = int.Parse(values[i]);
                                    break;

                                case "d":
                                    value = double.Parse(values[i]);
                                    break;

                                default:
                                    value = values[i];
                                    break;
                                }

                                dict[keyData[1]] = value;
                                var json = JsonConvert.SerializeObject(dict);
                                Console.WriteLine(json);
                                var key = string.Concat(type, "_", dict["name"].ToString().ToLower().Replace(" ", "_"));
                                client.Store(StoreMode.Set, key, json);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #59
0
        public StoreHandler(IEnumerable <Uri> uris, string bucketName, string bucketPassword)
        {
            var config = new CouchbaseClientConfiguration();

            foreach (var uri in uris)
            {
                config.Urls.Add(uri);
            }
            config.Bucket         = bucketName;
            config.BucketPassword = bucketPassword;
            _client = new CouchbaseClient(config);
        }
 public void Test_Store_StoreMode_Add_Will_Fail_If_Key_Exists()
 {
     var client = new CouchbaseClient("memcached-config");
     var result = client.Store(StoreMode.Set, Key, "value");
     var resultWhenKeyExists = client.Store(StoreMode.Add, Key, "value");
     Assert.AreEqual(resultWhenKeyExists, false);
     client.Remove(Key);
 }