Configuration class
Наследование: ICouchbaseClientConfiguration
Пример #1
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());
            }
        }
 public DesignDocManager(CouchbaseClientConfiguration config)
 {
     if (_cluster == null)
     {
         _cluster = new CouchbaseCluster(config);
     }
 }
Пример #3
0
 public ViewRunner(CouchbaseClientConfiguration config)
 {
     if (_client == null)
     {
         _client = new CouchbaseClient(config);
     }
 }
Пример #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
        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");
        }
        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
 public static CouchbaseClientConfiguration CouchbaseConfiguration(string serverName)
 {
     var zone = Math.Max(ExecutionContext<RequestContext>.Current.Zone, 1);
     var couchbaseClientConfiguration = new CouchbaseClientConfiguration();
     var doc = XmlHelper.GetXmlDocCache(EndpointFile);
     if (Equals(doc, null)) return couchbaseClientConfiguration;
     var node = doc.SelectSingleNode("/configuration/couchbase[@zone='" + zone + "']/server[@name='" + serverName + "']");
     if (Equals(node, null)) return couchbaseClientConfiguration;
     couchbaseClientConfiguration.Bucket = XmlHelper.GetXmlAttributeValue(node, "bucket", "default");
     couchbaseClientConfiguration.BucketPassword = XmlHelper.GetXmlAttributeValue(node, "password", string.Empty);
     foreach (var item in node.ChildNodes.Cast<XmlNode>().Where(uri => uri.NodeType != XmlNodeType.Comment))
     {
         switch (item.Name)
         {
             case "urls":
                 foreach (var uri in item.ChildNodes.Cast<XmlNode>().Where(uri => uri.NodeType != XmlNodeType.Comment)) couchbaseClientConfiguration.Urls.Add(new Uri(XmlHelper.GetXmlAttributeValue(uri, "uri", string.Empty)));
                 break;
             case "socketPool":
                 couchbaseClientConfiguration.SocketPool.MinPoolSize = CoreParse.GetInt32((XmlHelper.GetXmlAttributeValue(item, "minPoolSize", string.Empty)), 10);
                 couchbaseClientConfiguration.SocketPool.MaxPoolSize = CoreParse.GetInt32((XmlHelper.GetXmlAttributeValue(item, "maxPoolSize", string.Empty)), 20);
                 couchbaseClientConfiguration.SocketPool.ConnectionTimeout = TimeSpan.Parse(XmlHelper.GetXmlAttributeValue(item, "connectionTimeout", "00:00:02"));
                 couchbaseClientConfiguration.SocketPool.DeadTimeout = TimeSpan.Parse(XmlHelper.GetXmlAttributeValue(item, "deadTimeout", "00:00:10"));
                 couchbaseClientConfiguration.SocketPool.ReceiveTimeout = TimeSpan.Parse(XmlHelper.GetXmlAttributeValue(item, "receiveTimeout", "00:00:10"));
                 couchbaseClientConfiguration.SocketPool.QueueTimeout = TimeSpan.Parse(XmlHelper.GetXmlAttributeValue(item, "queueTimeout", "00:00:00.1000000"));
                 break;
         }
     }
     return couchbaseClientConfiguration;
 }
Пример #8
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);
        }
        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>());
        }
        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);
        }
        /// <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);
        }
        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);
        }
        public void SetUp()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools"));
            config.DesignDocumentNameTransformer = new ProductionModeNameTransformer();
            config.HttpClientFactory = new HammockHttpClientFactory();
            config.Bucket = "default";

            _Client = new CouchbaseClient(config);
        }
 /// <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;
     config.DesignDocumentNameTransformer = new DevelopmentModeNameTransformer();
     config.HttpClientFactory = new HammockHttpClientFactory();
     return new CouchbaseClient(config);
 }
        protected Tuple<CouchbaseClient, CouchbaseClientConfiguration> GetClientWithConfig(INameTransformer nameTransformer = null)
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://10.0.0.79:8091/pools/default"));
            config.Bucket = "default";
            config.DesignDocumentNameTransformer = nameTransformer ?? new DevelopmentModeNameTransformer();
            config.HttpClientFactory = new MockHttpClientFactory();

            return Tuple.Create(new CouchbaseClient(config), config);
        }
Пример #16
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.");
                }
            }
        }
Пример #17
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);
 }
        /// <summary>
        /// Connects to couchbase client with given configuration details
        /// </summary>
        /// <param name="username">Name of bucket to be used</param>
        /// <param name="password">Password used to connect to bucket</param>
        /// <returns>Couchbase client object</returns>
        private CouchbaseClient getClient(string username, string password)
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools"));
            config.Bucket = username;
            config.BucketPassword = password;
            config.DesignDocumentNameTransformer = new DevelopmentModeNameTransformer();
            config.HttpClientFactory = new HammockHttpClientFactory();

            return new CouchbaseClient(config);
        }
        public void When_Using_Code_Config_And_Http_Client_Factory_Is_Not_Set_Hammock_Factory_Is_Default()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://10.0.0.79:8091/pools"));
            Assert.That(config.HttpClientFactory, Is.InstanceOf<HammockHttpClientFactory>());

            //HammockHttpClient is an internal class to the Couchbase assembly,
            //therefore the explicit type can't be checked for using Is.InstanceOf<T>
            var typeName = (config.HttpClientFactory.Create(config.Urls[0], "", "").GetType().Name);
            Assert.That(typeName, Is.StringContaining("HammockHttpClient"));
        }
Пример #20
0
 public static CouchbaseClientConfiguration GetCouchbaseClientConfiguration()
 {
     CouchbaseClientConfiguration cf = new CouchbaseClientConfiguration();
     cf.Username = DatabaseSettings.Instance.Username;
     cf.Password = DatabaseSettings.Instance.Password;
     DatabaseSettings.Instance.Urls.ForEach((url, index) =>
     {
         cf.Urls.Add(url);
     });
     return cf;
 }
Пример #21
0
        public SourcePropertyChanges(string username, string password, params Uri[] couchbaseServers)
        {
            var config = new CouchbaseClientConfiguration
            {
                Bucket = username,
                BucketPassword = password,
            };

            Array.ForEach(couchbaseServers, uri => config.Urls.Add(uri));
            _couch = new CouchbaseClient(config);
            _couch.NodeFailed += node => Console.WriteLine(node.ToString());
        }
Пример #22
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.");
     }
 }
        public void When_Removing_A_Key_From_A_Down_Node_No_Exception_Is_Thrown_And_Success_Is_False()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://doesnotexist:8091/pools/"));
            config.Bucket = "default";

            var client = new CouchbaseClient(config);
            var removeResult = client.ExecuteRemove("foo");

            Assert.That(removeResult.Success, Is.False);
            Assert.That(removeResult.Message, Is.StringContaining(ClientErrors.FAILURE_NODE_NOT_FOUND));
        }
Пример #24
0
        static void Main(string[] args)
        {
            CbcOptions options = new CbcOptions();
            CommandLineParserSettings settings = new CommandLineParserSettings();
            settings.CaseSensitive = true;
            CommandLineParser parser = new CommandLineParser(settings);
            if (!parser.ParseArguments(args, options, System.Console.Error))
            {
                return;
            }

            options.Process();

            var config = new CouchbaseClientConfiguration();
            config.Bucket = options.Bucket;
            config.Username = options.Username;
            config.Password = options.Password;
            config.BucketPassword = options.BucketPassword;
            string uriString = "http://" + options.Hostname + "/pools";
            System.Console.WriteLine("URI: " + uriString);
            config.Urls.Add(new UriBuilder(uriString).Uri);

            DateTime begin = DateTime.Now;
            CouchbaseClient cli = new CouchbaseClient(config);
            System.Console.WriteLine("Created new client..");

            if (!commandMap.ContainsKey(options.Command))
            {
                throw new ArgumentException("Unknown command!");
            }

            Type t = commandMap[options.Command];
            Type[] proto = {
                               typeof(CouchbaseClient),
                               typeof(string),
                               typeof(CbcOptions)
                           };
            object[] cargs = {
                                cli,
                                options.Key,
                                options
                            };

            CommandBase cmd = (CommandBase) t.GetConstructor(proto).Invoke(cargs);
            cmd.Execute();

            var duration = DateTime.Now - begin;
            Console.WriteLine(
                String.Format("Duration was {0:F} Sec.", duration.TotalMilliseconds/1000));
        }
Пример #25
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);
            }
        }
 public override void Load()
 {
     Bind<CouchbaseClient>().ToMethod(context =>
         {
             var config = new CouchbaseClientConfiguration
                 {
                     Bucket = "<bucket name to store object",
                     BucketPassword = "******"
                 };
             config.Urls.Add(new Uri("http://localhost:8091/pools"));
             return new CouchbaseClient(config);
         });
     Bind<IRepository>().To<CouchbaseRepository>();
 }
        public void Client_Operations_Succeed_When_Bootstrapping_To_Pools_Root_Uri()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools"));
            config.Bucket = "default";

            var client = new CouchbaseClient(config);

            string key = GetUniqueKey(), value = GetRandomString();
            var storeResult = client.ExecuteStore(StoreMode.Add, key, value);
            StoreAssertPass(storeResult);

            var getResult = client.ExecuteGet(key);
            GetAssertPass(getResult, value);
        }
        public void Client_Operations_Succeed_When_Bootstrapping_To_Pools_Default_Root_Uri()
        {
            var config = new CouchbaseClientConfiguration();
            config.Urls.Add(new Uri("http://localhost:8091/pools/default"));
            config.Bucket = "default";

            var client = new CouchbaseClient(config);

            string key = GetUniqueKey(), value = GetRandomString();
            var storeResult = client.ExecuteStore(StoreMode.Add, key, value);
            Assert.That(storeResult.Success, Is.True, "Success was false");
            Assert.That(storeResult.Message, Is.Null.Or.Empty, "Message was not empty");

            var getResult = client.ExecuteGet(key);
            GetAssertPass(getResult, value);
        }
Пример #29
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 JSON
            client.StoreJson(StoreMode.Set, "CT_Hartford", new City { Name = "Hartford", State = "CT" });

            //Get City instance back from JSON
            var city = client.GetJson<City>("CT_Hartford");
            Console.WriteLine(city.Name);

            client.Remove("CT_Hartford");
        }
Пример #30
0
 public static CouchbaseClient GetWriteInstance()
 {
     if (_instance1 == null)
     {
         lock (Lock1)
         {
             if (_instance1 == null)
             {
                 var uri = new Uri("http://10.4.18.26:8091/pools");
                 var config = new CouchbaseClientConfiguration();
                 config.Urls.Add(uri);
                 config.Bucket = BucketName;
                 config.BucketPassword = BucketPassword;
                 _instance1 = new CouchbaseClient(config);
             }
         }
     }
     return _instance1;
 }