Example #1
0
        /// <summary>
        /// Create or update a list of ICouchDocuments in CouchDB. Uses POST and CouchDB will
        /// allocate new ids if the documents lack them.
        /// </summary>
        /// <param name="documents">List of documents to store.</param>
        /// <param name="allOrNothing">if set to <c>true</c> [all or nothing].</param>
        /// <remarks>POST may be problematic in some environments.</remarks>
        public void SaveDocuments(IEnumerable <IBigDbDocument> documents, bool allOrNothing)
        {
            var bulk = new BigDBulkDocuments(documents);

            try
            {
                var json = BigDDocument.WriteJson(bulk, false);

                var result = Request("_bulk_docs")
                             .Data(json)
                             .Query("?all_or_nothing=" + allOrNothing.ToString().ToLower())
                             .PostJson()
                             .Parse <JArray>();

                int index = 0;
                foreach (var document in documents)
                {
                    document.Id  = (result[index])["id"].Value <string>();
                    document.Rev = (result[index])["rev"].Value <string>();
                    ++index;
                }
            }
            catch (WebException e)
            {
                throw BigDException.Create("Failed to create bulk documents", e);
            }
        }
Example #2
0
        private HttpWebRequest GetRequest()
        {
            var requestUri = new UriBuilder(ConfigurationHelper.CouchDbProtocol, server.Host, server.Port, ((db != null) ? db.Name + "/" : "") + path, query).Uri;
            var request    = WebRequest.Create(requestUri) as HttpWebRequest;

            if (request == null)
            {
                throw BigDException.Create("Failed to create request");
            }
            request.Timeout = 3600000; // 1 hour. May use System.Threading.Timeout.Infinite;
            request.Method  = method;

            if (mimeType != null)
            {
                request.ContentType = mimeType;
            }

            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }

            if (!string.IsNullOrEmpty(server.EncodedCredentials))
            {
                request.Headers.Add("Authorization", server.EncodedCredentials);
            }

            if (postStream != null)
            {
                WriteData(request);
            }

            Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Request: {0} Method: {1}", requestUri, method));
            return(request);
        }
Example #3
0
        /// <summary>
        /// Delete documents in bulk fashion.
        /// </summary>
        /// <param name="bulk">The bulk.</param>
        public void DeleteDocuments(ICanJson bulk)
        {
            try
            {
                var json = BigDDocument.WriteJson(bulk, false);

                var result = Request("_bulk_docs")
                             .Data(json)
                             .PostJson()
                             .Parse <JArray>();
                for (var i = 0; i < result.Count(); i++)
                {
                    //documents[i]._id= (result[i])["id"].Value<string>();
                    //documents[i]._rev = (result[i])["rev"].Value<string>();
                    if ((result[i])["error"] == null)
                    {
                        continue;
                    }
                    throw BigDException.Create(string.Format(CultureInfo.InvariantCulture,
                                                             "Document with id {0} was not deleted: {1}: {2}",
                                                             (result[i])["id"].Value <string>(), (result[i])["error"], (result[i])["reason"]));
                }
            }
            catch (WebException e)
            {
                throw BigDException.Create("Failed to bulk delete documents", e);
            }
        }
Example #4
0
 /// <summary>
 /// Typically only used from CouchServer.
 /// </summary>
 public void CreateDatabase(string name)
 {
     try
     {
         Request().Path(name).Put().Check("Failed to create database");
     }
     catch (WebException e)
     {
         throw BigDException.Create("Failed to create database", e);
     }
 }
Example #5
0
 public BigDLuceneViewResult GetResult()
 {
     try
     {
         return(GetResult <BigDLuceneViewResult>());
     }
     catch (WebException e)
     {
         throw BigDException.Create("Query failed", e);
     }
 }
Example #6
0
 /// <summary>
 /// Read a couch attachment given a document id, this method does not have enough information to do caching.
 /// </summary>
 /// <param name="documentId">Document identifier</param>
 /// <param name="attachmentName">Name of the attachment.</param>
 /// <returns>Document attachment</returns>
 public WebResponse ReadAttachment(string documentId, string attachmentName)
 {
     try
     {
         return(Request(documentId + "/" + attachmentName).Response());
     }
     catch (WebException e)
     {
         throw BigDException.Create("Failed to read document: " + e.Message, e);
     }
 }
Example #7
0
 /// <summary>
 /// Read a couch document given an id, this method does not have enough information to do caching.
 /// </summary>
 /// <param name="documentId">Document identifier</param>
 /// <returns>Document Json as string</returns>
 public string ReadDocumentString(string documentId)
 {
     try
     {
         return(Request(documentId).String());
     }
     catch (WebException e)
     {
         throw BigDException.Create("Failed to read document: " + e.Message, e);
     }
 }
Example #8
0
 /// <summary>
 /// Read a couch document given an id, this method does not have enough information to do caching.
 /// </summary>
 /// <param name="documentId">Document identifier</param>
 /// <returns>Document Json as JObject</returns>
 public JObject ReadDocumentJObject(string documentId)
 {
     try
     {
         return(Request(documentId).Parse());
     }
     catch (WebException e)
     {
         throw BigDException.Create("Failed to read document", e);
     }
 }
Example #9
0
        /// <summary>
        /// Writes the attachment.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="attachmentName">Name of the attachment.</param>
        /// <param name="attachmentData">The attachment data.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <returns>The document.</returns>
        /// <remarks>This relies on the document to already have an id.</remarks>
        public IBigDbDocument WriteAttachment(IBigDbDocument document, string attachmentName, Stream attachmentData, string mimeType)
        {
            if (document.Id == null)
            {
                throw BigDException.Create(
                          "Failed to add attachment to document using PUT because it lacks an id");
            }

            JObject result =
                Request(document.Id + "/" + attachmentName).Query("?rev=" + document.Rev).Data(attachmentData).MimeType(mimeType).Put().Check("Failed to write attachment")
                .Result();

            document.Id  = result["id"].Value <string>();          // Not really neeed
            document.Rev = result["rev"].Value <string>();

            return(document);
        }
Example #10
0
 /// <summary>
 /// Gets the document.
 /// </summary>
 /// <param name="documentId">The document identifier.</param>
 /// <returns>CouchJsonDocument.</returns>
 public BigDJsonDocument GetDocument(string documentId)
 {
     try
     {
         try
         {
             return(new BigDJsonDocument(Request(documentId).Parse()));
         }
         catch (WebException e)
         {
             throw BigDException.Create("Failed to get document", e);
         }
     }
     catch (BigDNotFoundException)
     {
         return(null);
     }
 }
Example #11
0
        /// <summary>
        /// Create a given ICouchDocument in CouchDB. Uses POST and CouchDB will allocate a new id and overwrite any existing id.
        /// </summary>
        /// <param name="document">Document to store.</param>
        /// <returns>Document with Id and Rev set.</returns>
        /// <remarks>POST which may be problematic in some environments.</remarks>
        public IBigDbDocument CreateDocument(IBigDbDocument document)
        {
            try
            {
                // Wulka mods
                var json = BigDDocument.WriteJson(document, false);
                // end Wulka mods

                JObject result = Request().Data(json).PostJson().Check("Failed to create document").Result();
                document.Id  = result["id"].Value <string>();
                document.Rev = result["rev"].Value <string>();
                return(document);
            }
            catch (WebException e)
            {
                throw BigDException.Create("Failed to create document", e);
            }
        }
Example #12
0
 public IBigDRequest Check(string message)
 {
     try
     {
         if (result == null)
         {
             Parse();
         }
         if (!result["ok"].Value <bool>())
         {
             throw BigDException.Create(string.Format(CultureInfo.InvariantCulture, message + ": {0}", result));
         }
         return(this);
     }
     catch (WebException e)
     {
         throw BigDException.Create(message, e);
     }
 }
Example #13
0
        /// <summary>
        /// Write a CouchDocument or ICouchDocument, it may already exist in db and will then be overwritten.
        /// </summary>
        /// <param name="document">Couch document</param>
        /// <param name="batch">True if we don't want to wait for flush (commit).</param>
        /// <returns>Couch Document with new Rev set.</returns>
        /// <remarks>This relies on the document to already have an id.</remarks>
        public IBigDbDocument WriteDocument(IBigDbDocument document, bool batch)
        {
            if (document.Id == null)
            {
                throw BigDException.Create(
                          "Failed to write document using PUT because it lacks an id, use CreateDocument instead to let CouchDB generate an id");
            }

            // Wulka additions

            var json = BigDDocument.WriteJson(document, false);

            // End Wulka additions


            JObject result =
                Request(document.Id).Query(batch ? "?batch=ok" : null).Data(json).Put().Check("Failed to write document").Result();

            document.Id  = result["id"].Value <string>();           // Not really needed
            document.Rev = result["rev"].Value <string>();

            return(document);
        }
Example #14
0
        public T GetResult <T>() where T : BigDLuceneViewResult, new()
        {
            if (Options["q"] == null)
            {
                throw BigDException.Create("Lucene query failed, you need to specify Q(<Lucene-query-string>).");
            }
            var req = Request();

            if (Result == null)
            {
                Result = new T();
            }
            else
            {
                // Tell the request what we already have
                req.Etag(Result.etag);
                if (checkETagUsingHead)
                {
                    // Make a HEAD request to avoid transfer of data
                    if (req.Head().Send().IsETagValid())
                    {
                        return((T)Result);
                    }
                    // Set back to GET before proceeding below
                    req.Get();
                }
            }

            JObject json = req.Parse();

            if (json != null) // ETag did not match, view has changed
            {
                Result.Result(json, View);
                Result.etag = req.Etag();
            }
            return((T)Result);
        }