public void Literal_Name() { Assert.Throws <ArgumentNullException>(() => CouchbaseHelper.LiteralName(null)); Assert.Throws <ArgumentNullException>(() => CouchbaseHelper.LiteralName(string.Empty)); Assert.Equal("`test`", CouchbaseHelper.LiteralName("test")); Assert.Equal("`test\\\\foo`", CouchbaseHelper.LiteralName("test\\foo")); }
public Entity.ExceptionLog GetExceptionLog(string logId) { CouchbaseHelper helper = new CouchbaseHelper("default"); ExceptionLog log = helper.GetDocument <ExceptionLog>(logId); return(log); }
public List <CoreProfile> GetProfileList() { string n1ql = "select enable,exceptionConsumerNum,modifyTime,mqServer,normalConsumerNum,operateConsumerNum,profileKey,projectKey,systemConsumerNum,description from TrackInfo where profileKey is not null"; CouchbaseHelper helper = new CouchbaseHelper("TrackInfo"); return(helper.Query <CoreProfile>(n1ql)); }
public void GetClientTest() { //new CouchbaseHelper().GetClient("couchbase1"); //var bb = CouchbaseHelper.Store(CouchbaseHelper.GetClient("couchbase1"), StoreMode.Add, "test_1", "中国人民"); //var ss = CouchbaseHelper.Get<string>(CouchbaseHelper.GetClient("couchbase1"), "test_1"); var ss = CouchbaseHelper.Get <string>(CouchbaseHelper.GetClient("127.0.0.1", ""), "test_1"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Swagger Registration - BEGIN //services.AddSwaggerGen(c => //{ // c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info() // { // Title = "Nandalala.RoyalCottage.Api", // Version = "v1", // Description = "Platform's Product API", // TermsOfService = "None" // }); //}); ////Swagger Registration - END services.AddCors(options => { options.AddPolicy("CORS", corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddOptions(); //services.Configure<RoyalCottageConfiguration>(Configuration.GetSection("RoyalCottageConfiguration")); var RoyalCottageConfig = Configuration.GetSection("RoyalCottageConfiguration").Get <RoyalCottageConfiguration>(); SecurityContext securityContext = new SecurityContext( Guid.Parse("4a096a88-69ea-46b5-8909-442078fb3a16"), Guid.Parse("fe5d2b85-b5f4-4f2b-8f59-f8623ab92a4e") ); ICouchbaseClient _client; ICouchbaseBucket _bucket; CouchbaseHelper.TryGet(RoyalCottageConfig.ServerUri, RoyalCottageConfig.UserName, RoyalCottageConfig.Password, out _client); _bucket = _client.GetBucket(RoyalCottageConfig.Bucket); services.AddTransient <IBroker, Broker>(); Container container = new Container(); container.RegisterSingleton(securityContext); container.Register <IDocumentRepository, DocumentRepository>(); container.RegisterSingleton(_bucket); ContainerConfig.Configure(container); container.Verify(); services.AddSingleton(container); }
/// <summary> /// Removes all data and indexes from the database bucket and then recreates the /// primary index if an index was specified when the fixture was started. /// </summary> public void Clear() { CheckDisposed(); // Remove any full-text indexes. var fullTextIndexes = jsonClient.GetAsync <dynamic>("/api/index").Result.indexDefs; if (fullTextIndexes != null) { foreach (var _index in fullTextIndexes.indexDefs) { jsonClient.DeleteAsync($"/api/index/{_index.Name}").Wait(); } } // Remove all bucket indexes except for the primary index (if present). var existingIndexes = Bucket.ListIndexesAsync().Result; foreach (var index in existingIndexes.Where(i => i.Name != "#primary")) { Bucket.QuerySafeAsync <dynamic>($"drop index {CouchbaseHelper.LiteralName(Bucket.Name)}.{CouchbaseHelper.LiteralName(index.Name)} using {index.Type}").Wait(); } // Flush the bucket data. using (var bucketManager = Bucket.CreateManager()) { NeonBucket.ReadyRetry.InvokeAsync( async() => { bucketManager.Flush(); await Bucket.WaitUntilReadyAsync(); }).Wait(); } // Wait until all of the indexes are actually deleted as well // as all of the bucket items. NeonHelper.WaitFor( () => { var indexes = Bucket.ListIndexesAsync().Result; var expectedCount = createPrimaryIndex ? 1 : 0; var countResult = Bucket.QuerySafeAsync <JObject>($"select count(*) from `{Bucket.Name}`;").Result.First(); var docCount = (long)countResult["$1"]; return(indexes.Count == expectedCount && docCount == 0); }, timeout: NeonBucket.ReadyTimeout, pollTime: retryDelay); }
public void Literal_String() { Assert.Equal("NULL", CouchbaseHelper.Literal(null)); Assert.Equal("\"Hello World!\"", CouchbaseHelper.Literal("Hello World!")); Assert.Equal("\"'\"", CouchbaseHelper.Literal("'")); Assert.Equal("\"\\\"\"", CouchbaseHelper.Literal("\"")); Assert.Equal("\"\\\\\"", CouchbaseHelper.Literal("\\")); Assert.Equal("\"\\b\"", CouchbaseHelper.Literal("\b")); Assert.Equal("\"\\f\"", CouchbaseHelper.Literal("\f")); Assert.Equal("\"\\n\"", CouchbaseHelper.Literal("\n")); Assert.Equal("\"\\r\"", CouchbaseHelper.Literal("\r")); Assert.Equal("\"\\t\"", CouchbaseHelper.Literal("\t")); }
public List <TotalDTO> GetNormalTotalByDate(DateTime currentDate, string projectKey) { CouchbaseHelper helper = new CouchbaseHelper("default"); string n1ql = @"select DATE_PART_STR(createTime,'day') day , count(*) total from default where createTime like '2016-12%' and type = '4' and subKey = 'IIS' group by DATE_PART_STR(createTime,'day') order by DATE_PART_STR(createTime,'day')"; List <TotalDTO> result = helper.Query <TotalDTO>(n1ql); return(result); }
public List <TotalDTO> GetExceptionTotalByDate(DateTime currentDate, string projectKey) { CouchbaseHelper helper = new CouchbaseHelper("default"); string n1ql = @"select DATE_PART_STR(createTime,'day') day , count(*) total from default where createTime like $createTime and type = '1' and projectKey =$projectKey group by DATE_PART_STR(createTime,'day') order by DATE_PART_STR(createTime,'day')"; Dictionary <string, object> args = new Dictionary <string, object>(); args["$projectKey"] = projectKey; args["$createTime"] = currentDate.ToString("yyyy-MM") + "%"; List <TotalDTO> result = helper.Query <TotalDTO>(n1ql, args); return(result); }
public List <TotalDTO> GetTotalWithAllTypeMonth(DateTime currentDate, string projectKey) { CouchbaseHelper helper = new CouchbaseHelper("default"); string n1ql = @"select type LogType, count(*) total from default where createTime like $createTime and projectKey = $projectKey group by type order by type"; Dictionary <string, object> args = new Dictionary <string, object>(); args["$projectKey"] = projectKey; args["$createTime"] = currentDate.ToString("yyyy-MM") + "%"; List <TotalDTO> result = helper.Query <TotalDTO>(n1ql, args); return(result); }
private static void ClearCacheProvider(CachingProviderType cachingProvider) { #if NETFULL if (cachingProvider == CachingProviderType.Memcached) { MemcachedHelper.ClearDatabase("127.0.0.1", 11211); } #endif if (cachingProvider == CachingProviderType.Redis) { RedisHelper.ClearDatabase("localhost", 0); } if (cachingProvider == CachingProviderType.Couchbase) { CouchbaseHelper.ClearDatabase("http://localhost:8091", "default", "password", "default"); } }
/// <summary> /// Establishes the bucket connection and waits until the Couchbase container is ready /// to start handling requests. /// </summary> private void ConnectBucket() { // Dispose any existing underlying cluster and bucket. if (Bucket != null) { var existingBucket = Bucket.GetInternalBucket(); if (existingBucket != null) { existingBucket.Cluster.CloseBucket(existingBucket); existingBucket.Cluster.Dispose(); Bucket.SetInternalBucket(null); } } // It appears that it may take a bit of time for the Couchbase query // service to start in the new container we started above. We're going // to retry creating the primary index (or a dummy index) until it works. var bucket = (NeonBucket)null; var indexCreated = false; var indexReady = false; var queryReady = false; var doRetry = false; NeonBucket.ReadyRetry.InvokeAsync( async() => { if (doRetry) { Thread.Sleep(retryDelay); } else { doRetry = true; } if (bucket == null) { bucket = Settings.OpenBucket(Username, Password); } try { if (createPrimaryIndex) { // Create the primary index if requested. if (!indexCreated) { await bucket.QuerySafeAsync <dynamic>($"create primary index on {CouchbaseHelper.LiteralName(bucket.Name)} using gsi"); indexCreated = true; } if (!indexReady) { await bucket.WaitForIndexAsync("#primary"); indexReady = true; } // Ensure that the query service is running too. if (!queryReady) { var query = new QueryRequest($"select meta({bucket.Name}).id, {bucket.Name}.* from {bucket.Name}"); await bucket.QuerySafeAsync <dynamic>(query); await bucket.ListIndexesAsync(); queryReady = true; } } else { // List the indexes to ensure the index service is ready when we didn't create a primary index. if (!queryReady) { await bucket.ListIndexesAsync(); queryReady = true; } } } catch { // $hack(jefflill): // // It looks like we need to create a new bucket if the query service // wasn't ready. I'm guessing that this is due to the Couchbase index // service not being ready at the time the bucket was connected and // the bucket isn't smart enough to retry looking for the index service // afterwards. This won't be a problem for most real-world scenarios // because for those, Couchbase will have been started long ago and // will continue running indefinitely. // // We'll dispose the old bucket and set it to NULL here and then // open a fresh bucket above when the retry policy tries again. bucket.Dispose(); bucket = null; throw; } }).Wait(); // Use the new bucket if this is the first Couchbase container initialization // or else substitute the new underlying bucket into the existing bucket so // that unit tests don't need to be aware of the change. if (this.Bucket == null) { this.Bucket = bucket; } else { this.Bucket.SetInternalBucket(bucket.GetInternalBucket()); } }
public async Task Clear() { var indexQuery = $"select * from system:indexes where keyspace_id={CouchbaseHelper.Literal(bucket.Name)}"; // Flush and verify that the primary index was created by default. couchbase.Clear(); var indexes = await bucket.QuerySafeAsync <JObject>(indexQuery); Assert.Single(indexes); var index = (JObject)indexes.First().GetValue("indexes"); Assert.True((bool)index.GetValue("is_primary")); Assert.Equal("#primary", (string)index.GetValue("name")); // Write some data, verify that it was written then flush // the bucket and verify that the data is gone. await bucket.UpsertSafeAsync("hello", "world!"); Assert.Equal("world!", await bucket.GetSafeAsync <string>("hello")); couchbase.Clear(); Assert.Null(await bucket.FindSafeAsync <string>("hello")); // Create a secondary index and verify. await bucket.QuerySafeAsync <dynamic>($"create index idx_foo on {CouchbaseHelper.LiteralName(bucket.Name)} ( {CouchbaseHelper.LiteralName("Test")} )"); indexes = await bucket.QuerySafeAsync <JObject>(indexQuery); Assert.Equal(2, indexes.Count); // Expecting the primary and new secondary index // Clear the database and then verify that only the // recreated primary index exists. couchbase.Clear(); indexes = await bucket.QuerySafeAsync <JObject>(indexQuery); Assert.Single(indexes); index = (JObject)indexes.First().GetValue("indexes"); Assert.True((bool)index.GetValue("is_primary")); Assert.Equal("#primary", (string)index.GetValue("name")); // Create a fts index and verify. var ftsIndex = new Dictionary <string, object>(); ftsIndex.Add("type", "fulltext-index"); ftsIndex.Add("name", "test"); ftsIndex.Add("sourceType", "couchbase"); ftsIndex.Add("sourceName", "test"); await jsonClient.PutAsync("/api/index/test", JsonConvert.SerializeObject(ftsIndex)); ftsIndex = new Dictionary <string, object>(); ftsIndex.Add("type", "fulltext-index"); ftsIndex.Add("name", "test123"); ftsIndex.Add("sourceType", "couchbase"); ftsIndex.Add("sourceName", "test"); await jsonClient.PutAsync("/api/index/test123", JsonConvert.SerializeObject(ftsIndex)); var ftsIndexes = jsonClient.GetAsync <dynamic>("/api/index").Result.indexDefs; Assert.True(((JObject)ftsIndexes.indexDefs).Count == 2); // Clear the database and then verify that only the // recreated primary index exists. couchbase.Clear(); ftsIndexes = jsonClient.GetAsync <dynamic>("/api/index").Result.indexDefs; Assert.True(((JObject)ftsIndexes.indexDefs).Count == 0); }