. NET using CouchBase Basics

Source: Internet
Author: User
Tags couchbase

Here we will not introduce couchbase installation, but will only introduce the use of. NET Client Librarye. The SDK For CouchBase For Net can be downloaded through nuget, Install-Package CouchbaseNetClient on the official website. http://www.couchbase.com/communities/net To create a project on the CouchBase journey, we need to note that the project is used by default when we create a Console-like application in vs2010.. NET Framework Client Profile. We need to manually switch to full.. NET Framework. CouchBase is configured in the program. CouchBase provides encoding configuration and configuration file configuration. Of course, app is used. config is the most flexible. Here is our first choice. Add the following information to your configuration file. <? Xml version = "1.0"?> <Configuration> <configSections> <section name = "couchbase" type = "Couchbase. configuration. couchbaseClientSection, Couchbase "/> </configSections> <couchbase> <servers bucket =" default "bucketPassword =" "> <add uri =" "/> <Add uri =" "/> </Servers> </couchbase> </configuration> the url list configured by the cluster is used. Of course, you only need one address for local debugging, by default, CouchBase will create a default cache bucket without a password during installation. You can modify the information of this bucket as needed. (If you are not familiar with the bucket, google it yourself ). Add reference using Couchbase; using Couchbase. configuration; using Couchbase. extensions; using Enyim. caching; using Enyim. caching. configuration; using Enyim. caching. memcached; create an instance based on the actual reference and use var client = new CouchbaseClient (); // create an instance client. store (StoreMode. add, "somekey", "somevalue"); // store data var someValue = client. get ("somekey") as string; // Get the data var someValue = client. get <string> ("somekey"); // obtain data The above is the use of simple basic types. The following describes the complex types. Declare a class [Serializable] public class Beer {public Guid Id {get; set;} public string Name {get; set;} public string Brewery {get; set ;}} var key = Guid. newGuid (); var beer = new Beer {Id = key, Name = "Old Yankee Ale", Brewery = "Cottrell Brewing Company"}; client. store (StoreMode. add, "beer _" + key, beer); var beer = client. get <Beer> ("beer _" + key); json is supported in the official CouchBase2.0 version, which is exciting. Storage json data public static bool StoreJson <T> (this CouchbaseClient client, StoreMode storeMode, string key, T value) where T: class {var MS = new MemoryStream (); var serializer = new DataContractJsonSerializer (typeof (T); serializer. writeObject (MS, value); var json = Encoding. default. getString (ms. toArray (); ms. dispose (); return client. store (storeMode, key, json);} Get json data public static T GetJson <T> (This CouchbaseClient client, string key) where T: class {var json = client. get <string> (key); var MS = new MemoryStream (Encoding. default. getBytes (json); var serializer = new DataContractJsonSerializer (typeof (T); var obj = serializer. readObject (ms) as T; ms. dispose (); return obj;} Client usage var key = Guid. newGuid (); var beer = new Beer {Id = key, Name = "American Ale", Brewery = "Thomas Hook Er Brewing Company ", Type =" beer "}; client. storeJson <Beer> (StoreMode. add, "beer _" + key, beer); var beer = client. getJson <Beer> ("beer _" + key); For check and set operations, the return values are wrapped in a CasResult instance. the success of the operation is still determined by a Boolean and detailed failures still require logging. var result = client. getWithCas ("foo"); var bar = "ba R "; var result = client. cas (StoreMode. set, "foo", bar, result. cas); if (result. result) {Console. writeLine ("CAS operation was successful");} get detailed operation results. If you need to obtain detailed information about the runtime, you can use the IoperationResult API method, the following is an official description of the API attributes. Each of these methods shares its name with a method from the single-value return API, but prefixed with "Execute. "For example, Get () becomes ExecuteGet () and Store () becomes ExecuteStore (). property Interface Description Success IOperationResult Whether the operation succeeded Message IOperationResult Error, warning or informational message StatusCode IOperationResult Nullable status code from se Rver InnerResult IOperationResult Nested result. populated by low-level I/O failures. value INullableOperationResult Extended by IGetOperationResult, where Value is item for given key. hasValue INullableOperationResult failed cut for null Value check. cas ICasOperationResult Extended by IGetOperationResult, IMutateOperationResult, IConcatOperationResult and IStoreOperationResult. contains possible C AS value for operations. var getResult = client. executeGet <Beer> ("beer_heady_topper"); if (getResult. success & getResult. hasValue) {var beer = getResult. value; beer. brewery = "The Alchemist"; var casResult = client. executeCas (StoreMode. set, "beer_heady_topper", beer, getResult. cas); if (casResult. success) {Console. writeLine ("CAS operation was successful") ;}} else {Console. writeLine ("Get operat Ion failed with message {0} and exception {1} ", getResult. message, getResult. exception);} the configuration log CouchBase supports Log4Net and Nlog, which can be obtained by yourself or from the SDK provided by CouchBase. Log4Net configuration reference. <? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <sectionGroup name = "enyim.com"> <section name = "log" type = "Enyim. caching. configuration. loggerSection, Enyim. caching "/> </sectionGroup> <section name =" log4net "type =" log4net. config. log4NetConfigurationSectionHandler, log4net "/> </configSections> <enyim.com> <log factory =" Enyim. caching. log4NetFactory, Enyim. caching. log4NetAdapter "/> </enyim.com> <log4net debug =" fals E "> <appender name =" LogFileAppender "type =" log4net. appender. fileAppender, log4net "> <param name =" File "value =" c: \ temp \ error-log.txt "/> <param name =" AppendToFile "value =" true "/> <layout type =" log4net. layout. patternLayout, log4net "> <param name =" ConversionPattern "value =" % d [% t] %-5 p % c [% x] & lt; % X {auth} & gt; -% m % n "/> </layout> </appender> <root> <priority value =" ALL "/> <level value =" DEBUG "/> <Appender-ref = "LogFileAppender"/> </root> </log4net> </configuration> Nlog configuration reference <? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <sectionGroup name = "enyim.com"> <section name = "log" type = "Enyim. caching. configuration. loggerSection, Enyim. caching "/> </sectionGroup> <section name =" nlog "type =" NLog. config. configSectionHandler, NLog "/> </configSections> <enyim.com> <log factory =" Enyim. caching. NLogFactory, Enyim. caching. NLogAdapter "/> </enyim.com> <nlog> <targets> <target name =" logfile "type =" File "fileName =" c: \ temp \ error-log.txt "/> </targets> <rules> <logger name =" * "minlevel =" Info "writeTo =" logfile "/> </rules> </nlog> <startup> <supportedRuntime version = "v4.0" sku = ". NETFramework, Version = v4.0 "/> </startup> </configuration>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.