/// <summary> /// 返回指定ID的对象 /// </summary> /// <param name="objId"></param> /// <returns></returns> public override object GetObject(string objId) { if (objId == null || objId.Length == 0) { return(null); } lock (lockObject) { object returnObject = null; //处理本地缓存 if (localCache != null) { returnObject = localCache.GetObject(objId); if (returnObject != null) { return(returnObject); } } returnObject = dataCache.Get(GetInputKey(objId)); //添加到本地缓存 if (returnObject != null && localCache != null) { localCache.AddObject(objId, returnObject, localTimeSpan); } return(returnObject); } }
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"); }
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 virtual T Get(Request request) { var key = GetKey(request); var obj = _client.Get <T>(key); return(obj); }
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); }
static void Main(string[] args) { var client = new CouchbaseClient(); var returnValue = client.Get(""); System.Console.WriteLine("OUTPUT: - {0}", returnValue); System.Console.ReadLine(); }
public object Get(object key) { if (key == null) { return(null); } if (log.IsDebugEnabled) { log.DebugFormat("fetching object {0} from the cache", key); } object maybeObj = client.Get(KeyAsString(key)); if (maybeObj == null) { return(null); } //we need to check here that the key that we stored is really the key that we got //the reason is that for long keys, we hash the value, and this mean that we may get //hash collisions. The chance is very low, but it is better to be safe var de = (DictionaryEntry)maybeObj; string checkKeyHash = GetAlternateKeyHash(key); if (checkKeyHash.Equals(de.Key)) { return(de.Value); } return(null); }
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); } }
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 Run() { var config = new CouchbaseClientConfiguration(); config.Urls.Add(new Uri("http://localhost:8091/pools/")); config.Bucket = "default"; var client = new CouchbaseClient(config); Console.WriteLine("Set the counter to 0"); client.Increment("counter", 0, 0); Console.WriteLine("Increment by 1, set initial value to 0"); client.Increment("counter", 0, 1); Console.WriteLine(client.Get("counter")); Console.WriteLine("Increment by 10, initial value is ignored since it exists"); client.Increment("counter", 0, 10); Console.WriteLine(client.Get("counter")); client.Remove("counter"); Console.WriteLine("Set the counter to 1000"); client.Decrement("counter", 1000, 0); Console.WriteLine("Decrement by 1"); client.Decrement("counter", 0, 1); Console.WriteLine(client.Get("counter")); Console.WriteLine("Decrement by 10, initial value is ignored since it exists"); client.Decrement("counter", 0, 10); Console.WriteLine(client.Get("counter")); }
public void When_Using_App_Config_And_Http_Client_Factory_Is_Not_Set_Operations_Succeed() { var config = ConfigurationManager.GetSection("min-config") as CouchbaseClientSection; Assert.That(config, Is.Not.Null, "min-config section missing from app.config"); Assert.That(config.HttpClientFactory, Is.InstanceOf<ProviderElement<IHttpClientFactory>>()); var client = new CouchbaseClient(config); var kv = KeyValueUtils.GenerateKeyAndValue("default_config"); var result = client.Store(StoreMode.Add, kv.Item1, kv.Item2); Assert.That(result, Is.True, "Store failed"); var value = client.Get(kv.Item1); Assert.That(value, Is.StringMatching(kv.Item2)); }
public static void Main() { var clientA = new CouchbaseClient("couchbase"); var clientB = new CouchbaseClient(); clientA.Remove("fooA"); IStoreOperationResult result = clientA.ExecuteStore(StoreMode.Set, "fooA", "barA"); var itemA = clientA.Get<string>("fooA"); Console.WriteLine(itemA); clientB.ExecuteStore(StoreMode.Set, "fooB", "barB"); var itemB = clientB.Get<string>("fooB"); Console.WriteLine(itemB); Console.ReadLine(); }
public void When_Using_App_Config_And_HttpClient_Factory_Is_Not_Set_Operations_Succeed() { var config = ConfigurationManager.GetSection("min-config") as CouchbaseClientSection; Assert.That(config, Is.Not.Null, "min-config section missing from app.config"); Assert.That(config.HttpClientFactory, Is.InstanceOf <ProviderElement <IHttpClientFactory> >()); var client = new CouchbaseClient(config); var kv = KeyValueUtils.GenerateKeyAndValue("default_config"); var result = client.ExecuteStore(StoreMode.Add, kv.Item1, kv.Item2); Assert.That(result.Success, Is.True, "Store failed: " + result.Message); var value = client.Get(kv.Item1); Assert.That(value, Is.StringMatching(kv.Item2)); }
private void PopulateData(long index, BlockingCollection <KafkaRecord> data) { try { //load the large documet set from couchbase Console.WriteLine("Polling for couchbase changes..."); var changes = _couch.GetView("Kafka", "by_versiontick", false) .StartKey(index) .Select(x => new KafkaRecord { Key = x.ItemId, Offset = (long)x.ViewKey[0], Topic = ApiTopic, }); //as fast as we can, pull the documents from CB and push to our output collection Parallel.ForEach(changes.Batch(100), new ParallelOptions { MaxDegreeOfParallelism = 20 }, (batch) => { var temp = batch.ToList(); var records = _couch.Get(temp.Select(x => x.Key)); foreach (var change in temp) { if (records.ContainsKey(change.Key)) { change.AddDocument(records[change.Key].ToString()); data.Add(change); } } }); } catch (Exception ex) { Console.WriteLine("Failed to populate _dataQueue: {0}", ex); } finally { data.CompleteAdding(); } }
public void When_Using_Code_Config_And_HttpClient_Factory_Is_Not_Set_Operations_Succeed() { var config = new CouchbaseClientConfiguration(); config.Urls.Add(new Uri("http://localhost:8091/pools")); Assert.That(config.HttpClientFactory, Is.InstanceOf <DefaultHttpClientFactory>()); Assert.That(config, Is.Not.Null, "min-config section missing from app.config"); Assert.That(config.HttpClientFactory, Is.InstanceOf <DefaultHttpClientFactory>()); var client = new CouchbaseClient(config); var kv = KeyValueUtils.GenerateKeyAndValue("default_config"); var result = client.ExecuteStore(StoreMode.Add, kv.Item1, kv.Item2); Assert.That(result.Success, Is.True, "Store failed: " + result.Message); var value = client.Get(kv.Item1); Assert.That(value, Is.StringMatching(kv.Item2)); }
public async Task ReadStateAsync(string grainType, Orleans.Runtime.GrainReference grainReference, IGrainState grainState) { var GrainKey = GetGrainKey(grainType, grainReference); try { var Client = new CouchbaseClient(); if (Client.KeyExists(GrainKey)) { var json = ""; await Task.Run(() => { json = Client.Get(GrainKey).ToString(); }); var data = JsonConvert.DeserializeObject <Dictionary <String, Object> >(json); grainState.SetAll(data); } } catch (Exception ex) { Log.Error(0, "Error in ReadStateAsync", ex); } }
static void Main(string[] args) { CouchbaseClientConfiguration cbcc = new CouchbaseClientConfiguration(); //设置各种超时时间 cbcc.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 2); cbcc.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 4); cbcc.SocketPool.DeadTimeout = new TimeSpan(0, 0, 10); //使用默认的数据库 cbcc.Urls.Add(new Uri("http://127.0.0.1:8091/pools/default")); //建立一个Client,装入Client的配置 CouchbaseClient client = new CouchbaseClient(cbcc); //添加一条数据 CasResult<bool> casResult = client.Cas(StoreMode.Add, "Test", "Hello World!"); //获取刚添加的数据 Console.WriteLine(client.Get("Test")); Console.WriteLine("完成!"); Console.ReadLine(); }
/// <summary> /// Get error log entry by id /// </summary> public override ErrorLogEntry GetError(string id) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id"); } Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } var errorJson = _client.Get <string>(id); var error = JsonConvert.DeserializeObject <Error>(errorJson); return(new ErrorLogEntry(this, id, error)); }
/// <summary> /// Try a get data from the cache /// </summary> static string PerformGet(string cacheKey) { return(_couchbaseClient.Get <string>(cacheKey)); }
public T Retrieve <T>(string key) { return(client.Get <T>(key)); }
public void When_Using_Code_Config_And_HttpClient_Factory_Is_Not_Set_Operations_Succeed() { var config = new CouchbaseClientConfiguration(); config.Urls.Add(new Uri("http://localhost:8091/pools")); Assert.That(config.HttpClientFactory, Is.InstanceOf<DefaultHttpClientFactory>()); Assert.That(config, Is.Not.Null, "min-config section missing from app.config"); Assert.That(config.HttpClientFactory, Is.InstanceOf<DefaultHttpClientFactory>()); var client = new CouchbaseClient(config); var kv = KeyValueUtils.GenerateKeyAndValue("default_config"); var result = client.ExecuteStore(StoreMode.Add, kv.Item1, kv.Item2); Assert.That(result.Success, Is.True, "Store failed: " + result.Message); var value = client.Get(kv.Item1); Assert.That(value, Is.StringMatching(kv.Item2)); }
public object Get(string key) { return(_memcachedClient.Get(key)); }
/// <summary> /// Given an array of keys, gets all the objects associated with those keys in a single call. /// This method is more efficient then making multiple calls for a group of documents /// </summary> /// <param name="keysToGet">The keys to get.</param> /// <returns>Dictionary{System.StringSystem.Object}.</returns> public virtual IDictionary <string, object> GetMultipleDocuments(IEnumerable <string> keysToGet) { IDictionary <string, object> docs = Client.Get(keysToGet); return(docs ?? new Dictionary <string, object>()); }
static void Main(string[] args) { var cbCacheService = CouchbaseCacheFactory.GetCurrentCache(); var Plist = new List<Person>() { new Person() { Gid = new Guid(), Name = "1", Age = 12, Sex = SexEnum.男 }, new Person() { Gid = new Guid(), Name = "2", Age = 11, Sex = SexEnum.女 }, new Person() { Gid = new Guid(), Name = "4", Age = 41, Sex = SexEnum.人妖 }, }; cbCacheService.AddCache("key_1", Plist); var d = cbCacheService.GetAllCache<Person>("key_1"); Console.WriteLine(cbCacheService.GetAllCache<Person>("key_1")); //配置服务器 CouchbaseClientConfiguration cbcc = new CouchbaseClientConfiguration(); //设置各种超时时间 cbcc.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 2); cbcc.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 4); cbcc.SocketPool.DeadTimeout = new TimeSpan(0, 0, 10); //使用默认的数据库 cbcc.Urls.Add(new Uri("http://127.0.0.1:8091/pools/default")); //建立一个Client,装入Client的配置 CouchbaseClient client = new CouchbaseClient(cbcc); //添加一条数据 //CasResult<bool> casResult = client.Cas(StoreMode.Add, "Test", "Hello World!"); //获取刚添加的数据 Console.WriteLine(client.Get("key_1")); Console.WriteLine("完成!"); Console.ReadLine(); //InitTaskList(); //TestMethod(); //InstanceContext instanceContext = new InstanceContext(new CalculateCallback()); //using ( // DuplexChannelFactory<ICalculator> channelFactory = new DuplexChannelFactory<ICalculator>( // instanceContext, "CalculatorService")) //{ // ICalculator proxy = channelFactory.CreateChannel(); // using (proxy as IDisposable) // { // proxy.Add1(1, 2); // Console.Read(); // } //} }
public string Get(string key) { return((string)Client.Get(key)); }
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 T Get <T>(string key) { return(client.Get <T>(key)); }
protected void Page_Load(object sender, EventArgs e) { string id = ""; string format = "html"; if (Request.QueryString["format"] as string != null ) { format = (Request.QueryString["format"] as string).ToLower(); } if (Request.QueryString["id"] as string != null) { id = Request.QueryString["id"]; } /* if(Page.RouteData.Values["id"] as string != null){ id = Page.RouteData.Values["id"] as string; }*/ var Couchbase = new CouchbaseClient(); var temp = Couchbase.Get(id); QRResume.Classes.Resume theresume = Classes.Resume.ParseJSON(temp.ToString()); if(theresume !=null && (theresume.Expires > DateTime.Now || theresume.Expires <= Global.DateCutoff)){ //TODO view PASSWORD REQUIRED. if(theresume.ViewPassword!= null && ViewPassword.Value == theresume.ViewPassword){ ViewPassword.Visible=false; switch(format){ case "json": Response.Clear(); Response.ContentType = "application/json"; Response.Write(theresume.toJSON()); //Causes errors i think Response.End(); break; case "vcf": StringBuilder PhonesAddressesEmail = new StringBuilder(); foreach(Classes.PhoneNumber p in theresume.Phones){ PhonesAddressesEmail.AppendLine(String.Format("TEL;{0};VOICE:{1}", p.Type,p.Number)); } /** * Addresses are busted. * ADR;WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America LABEL;WORK;ENCODING=QUOTED-PRINTABLE:100 Waters Edge=0D=0ABaytown, LA 30314=0D=0AUnited States of America ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America LABEL;HOME;ENCODING=QUOTED-PRINTABLE:42 Plantation St.=0D=0ABaytown, LA 30314=0D=0AUnited States of America **/ foreach(Classes.Email email in theresume.Emails) { PhonesAddressesEmail.AppendLine(String.Format("EMAIL;PREF;INTERNET:{0}", email.Text)); } Response.Clear(); Response.ContentType = "text/vcard"; Response.Write(String.Format(@"BEGIN:VCARD VERSION:2.1 N:{0} FN:{0} ORG:{2} TITLE:{1} {3} REV:{4:yyyyMMddThhmmssZ} END:VCARD", theresume.Name, theresume.WorkExperience.Count > 0? theresume.WorkExperience[0].Title: "", theresume.WorkExperience.Count > 0? theresume.WorkExperience[0].Company: "", PhonesAddressesEmail, theresume.Updated)); //Causes errors i think Response.End(); break; case "html": default: resume.InnerHtml = theresume.toHTML(); Title = "Resume: "+ theresume.Name; break; } } else{ resume.InnerHtml = "<h1>Password Required</h1><p>Sorry, this resume is a password protected, enter the password below to view it.</p>"; ViewPassword.Visible= true; } } else{ resume.InnerHtml = "<h1> Can't find that resume</h1><p>Sorry, it might have expired or simply never existed.</p>"; } }
//并发读缓存 public static void ParallelReadCache() { var bag = new ConcurrentBag <string>(); var now = DateTime.Now; var watch = new Stopwatch(); watch.Start(); var count = Mapper.QueryForObject("GetPostCount", null); var pageCount = PageCount; Console.WriteLine("当前共{0}条数据,可分页{1}", count, pageCount); var param = new QueryParams(); int page = 0; Parallel.ForEach(_postList, item => { if (page++ % 100 == 0) { Console.Title = string.Format("当前执行第{0}页,共{2}页,已执行时间{1}秒", (page / 100) + 1, (DateTime.Now - now).TotalSeconds, pageCount); } var tmp = Client.Get(item.PostId.ToString()); if (tmp == null) { bag.Add(item.ToString()); Console.WriteLine("{0}:{1}", "Fail", item.PostId); } else { Console.WriteLine("{0}:{1}", "OK", item.PostId); } }); #region //Parallel.For(PageIndex, pageCount, i => //{ // int page = i; // ++page; // Console.Title = string.Format("当前执行第{0}页,共{2}页,已执行时间{1}秒", page, (DateTime.Now - now).TotalSeconds, pageCount); // param.index = i * 100; // param.count = 100; // var result = Mapper.QueryForList<Post>("SelectProductByPager", param); // foreach (var item in result) // { // var tmp= Client.Get(item.PostId.ToString()); // if (tmp == null) // { // bag.Add(item.ToString()); // Console.WriteLine("{0}:{1}","Fail",item.PostId); // } // else // { // Console.WriteLine("{0}:{1}","OK",item.PostId); // } // } //}); #endregion watch.Stop(); Console.WriteLine("共执行{0},失败个数{1}", watch.Elapsed, bag.Count); }
public void TestRemoveNode(string bucketType) { ClearCluster(); Assert.True(CreateBucket(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword, "default", 256, bucketType), "Could not ctreate bucket"); Thread.Sleep(10000); var config = new CouchbaseClientConfiguration { SocketPool = { ReceiveTimeout = new TimeSpan(0, 0, 2), DeadTimeout = new TimeSpan(0, 0, 10) } }; string node1 = _servers[1].Ip + ":" + _servers[1].Port; string node2 = _servers[2].Ip + ":" + _servers[2].Port; Assert.True(AddNode(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword, node1), "Could not add node"); Assert.True(StartRebalance(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword), "Could not start rebalancing"); while (CheckStillRebalancing(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword)) { Thread.Sleep(1000); } config.Urls.Add(new Uri("http://" + _servers[0].Ip + ":" + _servers[0].Port + "/pools/default")); var couchbase = new CouchbaseClient(config); for (int i = 0; i < ItemsToLoad; i++) { couchbase.Store(StoreMode.Set, "TEST_KEY" + i, "Hello World" + i); } for (int i = 0; i < ItemsToLoad; i++) { Assert.AreEqual("Hello World" + i, couchbase.Get("TEST_KEY" + i), "Missing data"); } Assert.True(RemoveNode(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword, node2), "Could not remove node"); Assert.True(StartRebalance(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword), "Could not start rebalancing"); for (int i = 0; i < ItemsToLoad; i++) { Assert.AreEqual("Hello World" + i, couchbase.Get("TEST_KEY" + i), "Missing data"); } var rand = new Random(); while (CheckStillRebalancing(_servers[0].Ip, _servers[0].Port, _membaseUserName, _membasePassword)) { for (int i = 0; i < ItemsToLoad; i++) { int value = rand.Next(1000); couchbase.Store(StoreMode.Set, "RAND_KEY", value); Assert.AreEqual(value, couchbase.Get("RAND_KEY"), "Missing data"); } } for (int i = 0; i < ItemsToLoad; i++) { Assert.AreEqual("Hello World" + i, couchbase.Get("TEST_KEY" + i)); } }
public static T GetJson <T>(this CouchbaseClient client, string key) where T : class { var json = client.Get <string>(key); return(json == null ? null : JsonConvert.DeserializeObject <T>(json)); }
protected void Page_Load(object sender, EventArgs e) { string id = ""; Resume theresume=new Resume(); var Couchbase = new CouchbaseClient(); if (Request.QueryString["id"] as string != null) { id = Request.QueryString["id"]; } if(Page.RouteData.Values["id"] as string != null){ id = Page.RouteData.Values["id"] as string; } if(id!= ""){ theresume = Resume.ParseJSON(Couchbase.Get<String>(id)); initalobject.InnerHtml = String.Format("<script>var resume = {0};</script>", theresume.toJSON()); if(theresume.EditPassword == null ||theresume.EditPassword == EditPassword.Value){ //Check for password }else{ ;//Prompt for password. } } if(Request.HttpMethod =="POST" && json.Value.Length>0 && (theresume.EditPassword == null || theresume.EditPassword == EditPassword.Value)){ bool okay =false; string reason =""; Resume newResume = Resume.ParseJSON(json.Value); if(newResume.Id == null || newResume.Id ==""){ newResume.Id= Guid.NewGuid().ToString(); okay = Couchbase.Store(Enyim.Caching.Memcached.StoreMode.Add, newResume.Id, newResume.toJSON(false)); if(!okay){ reason = " Could not save resume, likley due to a server failure, "; } } else{ if (theresume.EditPassword == newResume.EditPassword){ okay = Couchbase.Store(Enyim.Caching.Memcached.StoreMode.Replace, newResume.Id, newResume.toJSON(false)); if (!okay) { reason = " Could not save resume, likley due to a server failure, "; } } else{ reason = "Incorrect Edit Password"; } } Response.Clear(); Response.ContentType = @"application\json"; if(okay){ Response.Write(String.Format("{{\"Response\":\"okay\",\"id\":\"{0}\"}}", newResume.Id)); } else{ Response.Write(String.Format("{{\"Response\":\"error\",\"id\":\"{0}\",\"reason\":\"{1}\"}}", newResume.Id, reason)); } } //TODO Populate forms fields }