Esempio n. 1
0
 public ViewRunner(CouchbaseClientConfiguration config)
 {
     if (_client == null)
     {
         _client = new CouchbaseClient(config);
     }
 }
        public void When_Observe_Timeout_Is_Not_Set_And_Using_Code_Config_Default_Is_1_Minute()
        {
            var config = new CouchbaseClientConfiguration();

            Assert.That(config, Is.Not.Null, "Config was null");
            Assert.That(config.ObserveTimeout, Is.EqualTo(TimeSpan.FromMinutes(1)));
        }
Esempio n. 3
0
 public CouchbaseClient GetClient(CacheEndpoint endpoint, int connectTimeout)
 {
     lock (Clients)
     {
         try
         {
             var info = endpoint as CouchBaseEndpoint;
             Check.NotNull(info, "endpoint");
             var key = string.Format("{0}{1}{2}{3}{4}", info.Host, info.Port, info.BucketName, info.BucketPassword, info.Db);
             if (!Clients.ContainsKey(key))
             {
                 var clientConfiguration = new CouchbaseClientConfiguration();
                 var url = new Uri(string.Format("http://{0}:{1}/{2}", info.Host, info.Port, info.Db));
                 clientConfiguration.Bucket         = info.BucketName;
                 clientConfiguration.BucketPassword = info.BucketPassword;
                 clientConfiguration.Urls.Add(url);
                 clientConfiguration.HttpRequestTimeout     = TimeSpan.FromSeconds(connectTimeout);
                 clientConfiguration.SocketPool.MaxPoolSize = info.MaxSize;
                 clientConfiguration.SocketPool.MinPoolSize = info.MinSize;
                 var couchbaseClient = new CouchbaseClient(clientConfiguration);
                 Clients.GetOrAdd(key, couchbaseClient);
                 return(couchbaseClient);
             }
             else
             {
                 return(Clients[key]);
             }
         }
         catch (Exception)
         {
             return(null);
         }
     }
 }
        public void Test_That_Default_QueueTimeout_Is_2500ms()
        {
            var twoAndOneHalfSeconds = new TimeSpan(0, 0, 0, 0, 2500);
            var config = new CouchbaseClientConfiguration();

            Assert.AreEqual(twoAndOneHalfSeconds, config.SocketPool.QueueTimeout);
        }
 public DesignDocManager(CouchbaseClientConfiguration config)
 {
     if (_cluster == null)
     {
         _cluster = new CouchbaseCluster(config);
     }
 }
        public void When_Initialize_Connection_Is_Not_Set_In_Code_Default_Is_True()
        {
            var config = new CouchbaseClientConfiguration();

            Assert.That(config, Is.Not.Null, "Config was null");
            Assert.That(config.HttpClient.InitializeConnection, Is.True);
        }
Esempio n. 7
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);

            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);
            }

            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);
            }

            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);
            }
        }
Esempio n. 8
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");
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var config1 = new CouchbaseClientConfiguration {
                Bucket = "default"
            };

            config1.Urls.Add(new Uri("http://localhost:8091/pools"));

            var client1 = new CouchbaseClient(config1);

            Clients.Add(client1);

            Thread.Sleep(100);
            var config2 = new CouchbaseClientConfiguration {
                Bucket = "default"
            };

            config2.Urls.Add(new Uri("http://localhost:8091/pools"));

            var client2 = new CouchbaseClient(config2);

            Clients.Add(client2);

            const int itemsToProcess = 100000;

            foreach (var client in Clients)
            {
                //ProcessWithTap(client, itemsToProcess/Clients.Count);
                ProcessWithParallel(client, itemsToProcess / Clients.Count);
            }

            Console.Read();
        }
        public void When_HttpClient_Timeout_Is_Not_Set_In_Code_Default_Is_75_Seconds()
        {
            var config = new CouchbaseClientConfiguration();

            Assert.That(config, Is.Not.Null, "Config was null");
            Assert.That(config.HttpClient.Timeout, Is.EqualTo(TimeSpan.Parse("00:01:15")));
        }
Esempio n. 11
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");
        }
        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);
        }
Esempio n. 13
0
        public void When_Listing_Buckets_With_Invalid_Config_Argument_Exception_Is_Thrown()
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchbaseServerUrl"] + "/doesnotexist/"));
            config.Bucket = "default";
            var server  = new CouchbaseCluster(config);
            var buckets = server.ListBuckets();
        }
        /// <summary>
        /// Connects to couchbase client with given configuration details
        /// </summary>
        /// <param name="bucketName">Name of bucket to be used</param>
        /// <param name="bucketPassword">Password used to connect to bucket</param>
        /// <returns>Couchbase client object</returns>
        private CouchbaseClient GetClient(string bucketName, string bucketPassword)
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(_couchBasePools);
            config.Bucket         = bucketName;
            config.BucketPassword = bucketPassword;
            return(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://localhost:8091/pools"));
            var client = new CouchbaseClient(config);             //client sets up transformer

            Assert.That(config.DesignDocumentNameTransformer, Is.InstanceOf <ProductionModeNameTransformer>());
        }
Esempio n. 16
0
        private CouchbaseClientConfiguration GetConfig()
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri("http://localhost:8091/pools/"));
            config.Username = "******";
            config.Password = "******";
            return(config);
        }
Esempio n. 17
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_Listing_Buckets_With_Invalid_Config_Argument_Exception_Is_Thrown()
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri("http://localhost:8091/doesnotexist/"));
            config.Bucket = "default";
            var server  = new CouchbaseCluster(config);
            var buckets = server.ListBuckets();
        }
        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>());
        }
Esempio n. 20
0
        /// <summary>
        /// Connects to couchbase client with given configuration details
        /// </summary>
        /// <param name="bucketName">Name of bucket to be used</param>
        /// <param name="bucketPassword">Password used to connect to bucket</param>
        /// <returns>Couchbase client object</returns>
        private CouchbaseClient getClient(string bucketName, string bucketPassword)
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchbaseServerUrl"] + "/pools"));
            config.Bucket         = bucketName;
            config.BucketPassword = bucketPassword;

            return(new CouchbaseClient(config));
        }
Esempio n. 21
0
        /// <summary>
        /// Yeni bir CouchbaseDistributedCache instance ı oluşturur. Bu objenin oluşturulabilmesi için config dosyasında
        /// DistributedCache ayarları yapılmış olamlı. Bu ayarın içeriğinin
        /// { "ServerAddress": "http://sunucu.com", BucketName: "default", "SecondaryServerAdress": "http://sunucu2.com|bucket2" }
        /// gibi JSON formatında olması gerekli. ServerAddress ve BucketName alanları zorunludur. SecondaryServerAdress, varsa
        /// mirrorlama için kullanılacak ikincil bir sunucu (bu sunucuya sadece veri silme işlemleri mirror lanır) adresi
        /// "sunucu | bucket adı" formatında girilebilir.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Lutfen uygulama icin AppSettings -> DistributedCache ->
        /// ServerAddress ayarini yapiniz!</exception>
        public CouchbaseDistributedCache()
        {
            var setting = (ConfigurationManager.AppSettings["DistributedCache"] ?? "").Trim();

            if (setting.Length == 0)
            {
                setting = "{}";
            }

            this.configuration = JsonConvert.DeserializeObject <Configuration>(setting, JsonSettings.Tolerant);

            if (String.IsNullOrWhiteSpace(this.configuration.ServerAddress))
            {
                throw new InvalidOperationException(
                          "Lutfen uygulama icin AppSettings -> DistributedCache -> ServerAddress ayarini yapiniz!");
            }

            if (String.IsNullOrWhiteSpace(this.configuration.BucketName))
            {
                throw new InvalidOperationException(
                          "Lutfen uygulama icin AppSettings -> DistributedCache -> BucketName ayarini yapiniz!");
            }

            var config = new CouchbaseClientConfiguration
            {
                Bucket         = this.configuration.BucketName,
                BucketPassword = this.configuration.BucketPass
            };

            config.Urls.Add(new Uri(this.configuration.ServerAddress));

            this.cacheClient = new CouchbaseClient(config);

            foreach (var secondaryServerAddress in
                     (this.configuration.SecondaryServerAddress ?? "").Trim()
                     .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (!String.IsNullOrWhiteSpace(secondaryServerAddress))
                {
                    var secondaryConfig = new CouchbaseClientConfiguration();
                    secondaryConfig.Bucket         = config.Bucket;
                    secondaryConfig.BucketPassword = config.BucketPassword;
                    var secondaryServer = (secondaryServerAddress ?? "").Trim();
                    var pipeIndex       = secondaryServer.IndexOf('|');
                    if (pipeIndex > 0)
                    {
                        secondaryConfig.Bucket = secondaryServer.Substring(pipeIndex + 1);
                        secondaryServer        = secondaryServer.Substring(0, pipeIndex);
                    }
                    secondaryConfig.Urls.Add(new Uri(secondaryServer));
                    this.secondaryClients = this.secondaryClients ?? new List <ICouchbaseClient>();
                    this.secondaryClients.Add(new CouchbaseClient(secondaryConfig));
                }
            }
        }
Esempio n. 22
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.");
                }
            }
        }
Esempio n. 23
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);
            }
        }
Esempio n. 24
0
        static CouchbaseManager()
        {
            CouchbaseClientConfiguration couchbaseClientConfiguration = new CouchbaseClientConfiguration()
            {
                Bucket         = "default",
                BucketPassword = string.Empty
            };

            couchbaseClientConfiguration.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchBaseServer"]));
            _instance = new CouchbaseClient(couchbaseClientConfiguration);
        }
    public CouchbaseClientExtended(string bucketName, string bucketPassword) : base(bucketName, bucketPassword)
    {
        var config = new CouchbaseClientConfiguration
        {
            Bucket         = bucketName,
            BucketPassword = bucketPassword
        };

        LoadBaseConfig(config);
        _bucket = bucketName;
    }
        protected Tuple <CouchbaseClient, CouchbaseClientConfiguration> GetClientWithConfig(INameTransformer nameTransformer = null)
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri("http://localhost:8091/pools/default"));
            config.Bucket = "default";
            config.DesignDocumentNameTransformer = nameTransformer ?? new DevelopmentModeNameTransformer();
            config.HttpClientFactory             = new MockHttpClientFactory();

            return(Tuple.Create(new CouchbaseClient(config), config));
        }
Esempio n. 27
0
        protected Tuple <CouchbaseClient, CouchbaseClientConfiguration> GetClientWithConfig(INameTransformer nameTransformer = null)
        {
            var config = new CouchbaseClientConfiguration();

            config.Urls.Add(new Uri(ConfigurationManager.AppSettings["CouchbaseServerUrl"] + "/pools"));
            config.Bucket = ConfigurationManager.AppSettings["CouchbaseServerUrl"];
            config.DesignDocumentNameTransformer = nameTransformer ?? new DevelopmentModeNameTransformer();
            config.HttpClientFactory             = new MockHttpClientFactory();

            return(Tuple.Create(new CouchbaseClient(config), config));
        }
Esempio n. 28
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);
        }
        private CouchbaseClient getClient(string username, string password)
        {
            var config = new CouchbaseClientConfiguration();

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

            return(new CouchbaseClient(config));
        }
Esempio n. 30
0
        // ---------- PROPERTIES ----------

        // ---------- CONSTRUCTORS ----------

        /// <summary>
        /// Creates a utility object that can be used to perform operations against a Couchbase server.
        /// </summary>
        /// <param name="config">A Couchbase configuration object initialized with information on how to connect to the server.</param>
        public CouchbaseUtility(CouchbaseClientConfiguration config)
        {
            if (config != null)
            {
                // Create a connection with the Couchbase bucket.
                client = new CouchbaseClient(config);
            }
            else
            {
                throw new ArgumentNullException("config", "A Couchbase Configuration object must be supplied.");
            }
        }