Esempio n. 1
0
        static void Main(string[] args)
        {
            // sample XML, parsed into an XmlDocument
            // this might come from an XML file, another database, a REST API, etc
            // but for this example, it's just a hardcoded string
            // tag::xml[]
            var xml = @"
<Invoice>
    <Timestamp>1/1/2017 00:01</Timestamp>
    <CustNumber>12345</CustNumber>
    <AcctNumber>54321</AcctNumber>
</Invoice>";
            // end::xml[]
            // tag::xmldocument[]
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);
            // end::xmldocument[]

            // convert XML into JSON using Newtonsoft Json.net
            // tag::jsonconvert[]
            var json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);

            // end::jsonconvert[]

            // this is just an example of what the Json would look like if I DIDN'T omit root node
            // {"Invoice":{"Timestamp":"1/1/2017 00:01","CustNumber":"12345","AcctNumber":"54321"}}

            // connect to couchbase cluster
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("http://localhost:8091")
                }
            });
            var bucket = ClusterHelper.GetBucket("loadxml", "password");

            // insert directly (literal translation)
            // tag::insertobject[]
            object transactObject1 = JsonConvert.DeserializeObject(json);

            bucket.Insert(Guid.NewGuid().ToString(), transactObject1);
            // end::insertobject[]

            // insert via class (type information, naming conventions applied)
            // tag::insertobject2[]
            Invoice transactObject2 = JsonConvert.DeserializeObject <Invoice>(json);

            bucket.Insert(Guid.NewGuid().ToString(), transactObject2);
            // end::insertobject2[]
        }
Esempio n. 2
0
        private List <string> LogToCouchbase(List <string> lines)
        {
            try
            {
                if (firstRun)
                {
                    var config = new ClientConfiguration
                    {
                        Servers = new List <Uri> {
                            new Uri("http://10.0.0.4:8091")
                        }
                    };

                    ClusterHelper.Initialize(config);

                    firstRun = false;
                }

                // this will overwrite any old log lines!
                var result =
                    ClusterHelper
                    .GetBucket("default")
                    .Upsert <dynamic>(
                        "MyWindowsService.log.txt",
                        new
                {
                    id  = "MyWindowsService.log.txt",
                    log = string.Join("\n", lines)
                }
                        );

                lines.AddRange(
                    new[] {
                    "Couchbase result: ",
                    result.Success.ToString(),
                    "Document Key: ",
                    "MyWindowsService.log.txt"
                });
            }
            catch (Exception ex)
            {
                lines.AddRange(
                    new[] {
                    "Exception:",
                    ex.Message,
                    ex.StackTrace
                });
            }

            return(lines);
        }
        public void Test_GetBucket_Using_HttpStreamingProvider()
        {
            ClusterHelper.Initialize(TestConfiguration.GetCurrentConfiguration());
            var cluster = ClusterHelper.Get();

            cluster.SetupEnhancedAuth();

            const string expected = "default";

            using (var bucket = cluster.OpenBucket("default"))
            {
                Assert.AreEqual(expected, bucket.Name);
            }
        }
Esempio n. 4
0
        public void Test_GetBucket_Using_HttpStreamingProvider()
        {
            var clientConfig = new ClientConfiguration();

            ClusterHelper.Initialize(clientConfig);
            _cluster = ClusterHelper.Get();

            const string expected = "default";

            using (var bucket = _cluster.OpenBucket("default"))
            {
                Assert.AreEqual(expected, bucket.Name);
            }
        }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();
            //Couchbase Cluster Configuration
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            }, new PasswordAuthenticator("Test", "ritesh"));
        }
        public void When_Configuration_Is_Customized_Good_Things_Happens()
        {
            var config = new ClientConfiguration
            {
                Servers = new List <Uri>
                {
                    new Uri(ConfigurationManager.AppSettings["bootstrapUrl"])
                },
                PoolConfiguration = new PoolConfiguration(10, 10)
            };

            ClusterHelper.Initialize(config);
            _cluster = ClusterHelper.Get();
        }
Esempio n. 7
0
        protected void InitializeCluster(IContractResolver contractResolver = null)
        {
            if (contractResolver != null)
            {
                _contractResolver = contractResolver;
            }
            var config = TestConfigurations.DefaultConfig();

            //var config = new ClientConfiguration();
            //config.Servers.Add(new Uri("http://127.0.0.1:8091"));
            config.DeserializationSettings.ContractResolver = _contractResolver;
            config.SerializationSettings.ContractResolver   = _contractResolver;
            ClusterHelper.Initialize(config);
        }
        public void Register(CouchbaseConfiguration configuration)
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri(configuration.Host)
                }
            });
            var username = configuration.Username;
            var password = configuration.Password;

            // provide authentication to cluster
            ClusterHelper.Get().Authenticate(new PasswordAuthenticator(username, password));
        }
Esempio n. 9
0
        private static void SetupConnections()
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            });
            _bucket = ClusterHelper.GetBucket("sqltocb");

            var db = new SqlConnection("data source=(local);initial catalog=sqltocb;integrated security=True;");

            _context = new SqlToCbContext(db);
        }
Esempio n. 10
0
        public void When_Bucket_Is_Opened_On_Two_Seperate_Threads_And_RemoveBucket_Is_Called_Count_Is_Zero()
        {
            ClusterHelper.Initialize();
            var t1 = new Thread(OpenBucket);
            var t2 = new Thread(OpenBucket);

            t1.Start();
            t2.Start();

            TwoThreadsCompleted.Wait();
            Assert.AreEqual(1, ClusterHelper.Count());
            ClusterHelper.RemoveBucket("default");
            Assert.AreEqual(0, ClusterHelper.Count());
        }
Esempio n. 11
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var config = new ClientConfiguration();

            config.Servers = new List <Uri>
            {
                new Uri("http://localhost:8091")
            };
            config.UseSsl = false;
            ClusterHelper.Initialize(config);
        }
Esempio n. 12
0
        public void Test_GetBucket_Using_CarrierPublicationProvider()
        {
            var config = new ClientConfiguration();

            ClusterHelper.Initialize(config);
            _cluster = ClusterHelper.Get();

            const string expected = "default";

            using (var bucket = _cluster.OpenBucket("default"))
            {
                Assert.IsNotNull(bucket);
                Assert.AreEqual(expected, bucket.Name);
            }
        }
Esempio n. 13
0
        public static void Main(string[] args)
        {
            ClusterHelper.Initialize(new ClientConfiguration {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            });
            var bucket = ClusterHelper.GetBucket("default");

            var doc = new Document <dynamic> {
                Id      = Guid.NewGuid().ToString(),
                Content = new {
                    invoiceNumber = Path.GetRandomFileName(),
                    amountDue     = new Random().Next(10, 1000),
                    type          = "electric_bill"
                }
            };

            bucket.Insert(doc);

            // --------

            var query = QueryRequest.Create("SELECT b.* FROM `default` b WHERE b.type = $1");

            query.AddPositionalParameter("electric_bill");
            query.ScanConsistency(ScanConsistency.RequestPlus);
            var result = bucket.Query <dynamic>(query);

            Console.WriteLine("Success: " + result.Success);

            if (!result.Success)
            {
                Console.WriteLine("Message: " + result.Message);
                Console.WriteLine("Exception: " + result.Exception?.GetType().Name);
                Console.WriteLine("Exception Message: " + result?.Exception?.Message);
                result.Errors.ForEach(e => Console.WriteLine("Error: " + e?.Message));
                return;
            }

            Console.WriteLine();

            Console.WriteLine("Bills:");
            Console.WriteLine("---------");
            foreach (var bill in result.Rows)
            {
                Console.WriteLine($"{bill.invoiceNumber} - {bill.amountDue.ToString("C")}");
            }
        }
Esempio n. 14
0
 protected override void InitialiseInternal()
 {
     if (_clientConfig == null)
     {
         _clientConfig = _clientConfig ?? new ClientConfiguration((CouchbaseClientSection)ConfigurationManager.GetSection("couchbaseClients/couchbase"));
         BucketConfig  = _clientConfig.BucketConfigs.Values.FirstOrDefault();
     }
     try
     {
         ClusterHelper.Get();
     }
     catch (InitializationException)
     {
         ClusterHelper.Initialize(_clientConfig);
     }
 }
        public FhirRepository(Models.ICouchbaserServerConfiguration couchbaseConfig)
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri(couchbaseConfig.Host)
                },
                EnableTcpKeepAlives  = true,
                TcpKeepAliveInterval = 1000,
                TcpKeepAliveTime     = 300000
            }, new PasswordAuthenticator(couchbaseConfig.Username, couchbaseConfig.Password));



            _bucket = ClusterHelper.GetBucket(couchbaseConfig.Bucket);
        }
Esempio n. 16
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            var config = new ClientConfiguration();

            config.Servers = new List <Uri>
            {
                new Uri(ConfigurationManager.AppSettings["couchbaseServer1"])
            };
            config.UseSsl = false;
            ClusterHelper.Initialize(config);
        }
Esempio n. 17
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ClusterHelper.Initialize(new Couchbase.Configuration.Client.ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchebase://localhost")
                }
            }, new PasswordAuthenticator("Administrator", "niraj@1234")

                                     );
        }
        public static void OpenCouchbaseConnection()
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            }, new PasswordAuthenticator(User, Password));

            bucket = ClusterHelper.GetBucket(BucketName);

            if (bucket != null)
            {
                CreateIndexesOnCouchbase();
            }
        }
Esempio n. 19
0
        public DocumentExpiryUpdater(Options options, LogManager logManager)
        {
            Options    = options;
            LogManager = logManager;

            var config = options.BuildClientConfiguration();

            ServicePointManager.DefaultConnectionLimit = MaxActiveTasks;
            foreach (var bucketConfig in config.BucketConfigs)
            {
                bucketConfig.Value.PoolConfiguration.MaxSize = MaxActiveTasks;
                bucketConfig.Value.PoolConfiguration.MinSize = MaxActiveTasks;
            }

            ClusterHelper.Initialize(config);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            });
            var bucket = ClusterHelper.GetBucket("default");

            //ListDemo(bucket);

            //QueueDemo(bucket);

            DictionaryDemo(bucket);
        }
        public void When_Bucket_Is_Opened_On_Two_Seperate_Threads_And_RemoveBucket_Is_Called_Count_Is_Zero()
        {
            ClusterHelper.Initialize(TestConfiguration.GetCurrentConfiguration());
            ClusterHelper.Get().SetupEnhancedAuth();

            var t1 = new Thread(OpenBucket);
            var t2 = new Thread(OpenBucket);

            t1.Start();
            t2.Start();

            TwoThreadsCompleted.Wait();
            Assert.AreEqual(1, ClusterHelper.Count());
            ClusterHelper.RemoveBucket("default");
            Assert.AreEqual(0, ClusterHelper.Count());
        }
Esempio n. 22
0
        public static void Register()
        {
            var couchbaseServer = ConfigurationManager.AppSettings.Get("CouchbaseServer");

            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri(couchbaseServer)
                }
            });

            var bucketName = ConfigurationManager.AppSettings.Get("CouchbaseTravelBucket");
            var username   = ConfigurationManager.AppSettings.Get("CouchbaseUser");
            var password   = ConfigurationManager.AppSettings.Get("CouchbasePassword");

            EnsureIndexes(bucketName, username, password);
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri>
                {
                    new Uri("http://192.168.77.101/:8091/")
                }
            });

            UpsertWithTtl();

            UpsertWithDocumentTtl();

            Console.Read();
            ClusterHelper.Close();
        }
Esempio n. 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "User Behavior Statistics API", Version = "V1"
                });
            });

            ClusterHelper.Initialize(new ClientConfiguration {
                Servers = new List <Uri> {
                    new Uri(Configuration.GetSlnConfig("CouchbaseEndpoint"))
                }
            }, new PasswordAuthenticator(Configuration.GetSlnConfig("CouchbaseUserName"), Configuration.GetSlnConfig("CouchbasePassword")));
        }
Esempio n. 25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // setup Couchbase
            var servers = new List <Uri> {
                // couchcase
                //new Uri("couchbase://192.168.1.10"),
                //new Uri("couchbase://192.168.1.20"),
                //new Uri("couchbase://192.168.1.30"),

                // local
                //new Uri("couchbase://localhost"),

                // docker
                new Uri("couchbase://172.17.0.2"),
                new Uri("couchbase://172.17.0.3"),
                new Uri("couchbase://172.17.0.4")
            };

            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = servers
            });

            lifetime.ApplicationStopping.Register(Cleanup);
        }
Esempio n. 26
0
        private static void CreateCluster()
        {
            var cbConfig = new CouchbaseConfiguration();
            var port     = cbConfig.GetPort();

            var hosts  = cbConfig.GetHosts().Select(x => new Uri(string.Format("{0}:{1}/pools", x, port))).ToList();
            var config = new ClientConfiguration()
            {
                Servers = hosts,
            };

            ClusterHelper.Initialize(config);

            cluster = ClusterHelper.Get(); // Single connection, do not use using (do not dispose a recreate)

            //var cm = cluster.CreateManager("Administrator", "123456");
        }
Esempio n. 27
0
        public void UsingAppConfigWithAuthentication()
        {
            // see couchbaseClients/couchbase section in app.config of this project
            // Note: even though we pass in "cb", CacheManager will fall back to the
            // default couchbase section at couchbaseClients/couchbase!
            // We could also pass in the section name explicitly instead of "cb".

            ClusterHelper.Initialize("couchbaseClients/couchbase");
            ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password"));

            var cacheConfig = new ConfigurationBuilder()
                              .WithCouchbaseCacheHandle("keydoesnotmatter")
                              .Build();

            var cache = new BaseCacheManager <int>(cacheConfig);

            cache.AddOrUpdate("test", 1, (v) => v + 1);
        }
Esempio n. 28
0
        public CouchbaseCacheTests()
        {
            if (!ClusterHelper.Initialized)
            {
                var config = TestConfiguration.GetCurrentConfiguration();

                var settings = TestConfiguration.Settings;
                if (settings.EnhancedAuth)
                {
                    ClusterHelper.Initialize(config,
                                             new PasswordAuthenticator(settings.AdminUsername, settings.AdminPassword));
                }
                else
                {
                    ClusterHelper.Initialize(config);
                }
            }
        }
Esempio n. 29
0
        static ServiceProvider SetupServices()
        {
            var path = $"db-files/itunes.db";

            ClusterHelper.Initialize(new ClientConfiguration {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            }, new PasswordAuthenticator("jayScrill", "password"));
            var serviceProvider = new ServiceCollection()
                                  .AddLogging()
                                  .AddSingleton <IDbService, CouchbaseService>()
                                  .AddScoped <ISQLiteService, SQLiteService>()
                                  .AddDbContext <MyContext>(opt => opt.UseSqlite("Data Source=" + path))
                                  .BuildServiceProvider();

            return(serviceProvider);
        }
Esempio n. 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "Gift WishList API", Version = "v1"
                });
            });

            ClusterHelper.Initialize(new Couchbase.Configuration.Client.ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("couchbase://localhost")
                }
            }, new PasswordAuthenticator("Administrator", "123456"));
        }