Pregunta

Using the Couchbase .NET client, how does one determine if a bucket exists?

It seems that if you specify a bucket that doesn't exist, there's no good indication, all the Get() calls just return null. This can be pretty confusing.

I'd like to detect this situation and generate a more helpful error.

¿Fue útil?

Solución

At this time, there's no way to do this directly in the client. I'm currently (as in starting soon) working on some changes to allow for better exception detection. In the mean time, you have 2 options:

  1. You could enable logging (which obviously won't help you at runtime). See the section titled "Configuring Logging" at http://www.couchbase.com/develop/net/current for information on how to do so.

  2. You could query the server for information on configured buckets. This query is already in the codebase, but in an internal class which does not expose its API calls. You could create an extension method that will compare the configured bucket to the actual buckets configured on the server. I wouldn't recommend calling the BucketExists extension often, but it should work as a validation method that you call once at app startup.

    public static class CouchbaseClientExtensions {
    
        public static bool BucketExists(this CouchbaseClient client, CouchbaseClientSection section = null) {
    
            section = section ?? (CouchbaseClientSection)ConfigurationManager.GetSection("couchbase");
    
            var webClient = new WebClient();            
            var bucketUri = section.Servers.Urls.ToUriCollection().First().AbsoluteUri;
    
            var response = webClient.DownloadString(bucketUri + "/buckets");               
            var jss = new JavaScriptSerializer();
            var jArray = jss.DeserializeObject(response) as object[];
    
            foreach (var item in jArray) {
                var jDict = item as Dictionary<string, object>;
                var bucket = jDict.Single(kv => kv.Key == "name").Value as string;
                if (bucket == section.Servers.Bucket) {
                    return true;
                }                               
            }
            return false;
        }
    }
    

Hope that helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top