CreateHttpJsonRequest() public static méthode

public static CreateHttpJsonRequest ( object self, string url, string method, ICredentials credentials ) : HttpJsonRequest
self object
url string
method string
credentials ICredentials
Résultat HttpJsonRequest
Exemple #1
0
        /// <summary>
        /// Perform a direct get for loading multiple ids in one request
        /// </summary>
        /// <param name="ids">The ids.</param>
        /// <param name="operationUrl">The operation URL.</param>
        /// <param name="includes">The includes.</param>
        /// <returns></returns>
        public MultiLoadResult DirectGet(string[] ids, string operationUrl, string[] includes)
        {
            var path = operationUrl + "/queries/?";

            if (includes != null && includes.Length > 0)
            {
                path += string.Join("&", includes.Select(x => "include=" + x).ToArray());
            }
            // if it is too big, we drop to POST (note that means that we can't use the HTTP cache any longer)
            // we are fine with that, requests to load > 128 items are going to be rare
            HttpJsonRequest request;

            if (ids.Length < 128)
            {
                path   += "&" + string.Join("&", ids.Select(x => "id=" + x).ToArray());
                request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "GET", credentials, convention);
            }
            else
            {
                request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "POST", credentials, convention);
                request.Write(new JArray(ids).ToString(Formatting.None));
            }

            request.AddOperationHeaders(OperationsHeaders);
            var result = JObject.Parse(request.ReadResponseString());

            return(new MultiLoadResult
            {
                Includes = result.Value <JArray>("Includes").Cast <JObject>().ToList(),
                Results = result.Value <JArray>("Results").Cast <JObject>().ToList()
            });
        }
        private IndexDefinition DirectGetIndex(string indexName, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/indexes/" + indexName + "?definition=yes", "GET", credentials);

            httpJsonRequest.AddOperationHeaders(OperationsHeaders);
            string indexDefAsString;

            try
            {
                indexDefAsString = httpJsonRequest.ReadResponseString();
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse != null &&
                    httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                throw;
            }
            var indexDefResultAsJson = JObject.Load(new JsonTextReader(new StringReader(indexDefAsString)));

            return(convention.CreateSerializer().Deserialize <IndexDefinition>(
                       new JTokenReader(indexDefResultAsJson["Index"])
                       ));
        }
Exemple #3
0
        ///<summary>
        /// Get the possible terms for the specified field in the index
        /// You can page through the results by use fromValue parameter as the
        /// starting point for the next query
        ///</summary>
        ///<returns></returns>
        public IEnumerable <string> GetTerms(string index, string field, string fromValue, int pageSize)
        {
            var requestUri = url + string.Format("/terms/{0}?field={1}&pageSize={2}&fromValue={3}",
                                                 Uri.EscapeUriString(index),
                                                 Uri.EscapeDataString(field),
                                                 pageSize,
                                                 Uri.EscapeDataString(fromValue ?? ""));

            var request = HttpJsonRequest.CreateHttpJsonRequest(this, requestUri, "GET", credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            var    serializer = convention.CreateSerializer();
            JToken json;

            try
            {
                using (var reader = new JsonTextReader(new StringReader(request.ReadResponseString())))
                    json = (JToken)serializer.Deserialize(reader);
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.InternalServerError)
                {
                    throw new InvalidOperationException("could not execute suggestions at this time");
                }
                throw;
            }

            return(json.Values <string>());
        }
        private QueryResult DirectQuery(string index, IndexQuery query, string operationUrl)
        {
            string path    = query.GetIndexQueryUrl(operationUrl, index, "indexes");
            var    request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "GET", credentials);

            request.AddOperationHeaders(OperationsHeaders);
            var    serializer = convention.CreateSerializer();
            JToken json;

            try
            {
                using (var reader = new JsonTextReader(new StringReader(request.ReadResponseString())))
                    json = (JToken)serializer.Deserialize(reader);
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new InvalidOperationException("There is no index named: " + index);
                }
                throw;
            }
            return(new QueryResult
            {
                IsStale = Convert.ToBoolean(json["IsStale"].ToString()),
                Results = json["Results"].Children().Cast <JObject>().ToArray(),
                TotalResults = Convert.ToInt32(json["TotalResults"].ToString())
            });
        }
        private void DirectDelete(string key, Guid?etag, string operationUrl)
        {
            var metadata = new JObject();

            if (etag != null)
            {
                metadata.Add("ETag", new JValue(etag.Value.ToString()));
            }
            AddTransactionInformation(metadata);
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/docs/" + key, "DELETE", metadata, credentials);

            httpJsonRequest.AddOperationHeaders(OperationsHeaders);
            try
            {
                httpJsonRequest.ReadResponseString();
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null ||
                    httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
                throw ThrowConcurrencyException(e);
            }
        }
        private BatchResult[] DirectBatch(IEnumerable <ICommandData> commandDatas, string operationUrl)
        {
            var metadata = new JObject();

            AddTransactionInformation(metadata);
            var req = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/bulk_docs", "POST", metadata, credentials);

            req.AddOperationHeaders(OperationsHeaders);
            var jArray = new JArray(commandDatas.Select(x => x.ToJson()));

            req.Write(jArray.ToString(Formatting.None));

            string response;

            try
            {
                response = req.ReadResponseString();
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null ||
                    httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
                throw ThrowConcurrencyException(e);
            }
            return(JsonConvert.DeserializeObject <BatchResult[]>(response));
        }
Exemple #7
0
        public void DeleteIndex(string name)
        {
            EnsureIsNotNullOrEmpty(name, "name");
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, url + "/indexes/" + name, "DELETE", credentials);

            request.ReadResponseString();
        }
        private void DirectRollback(Guid txId, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/transaction/rollback?tx=" + txId, "POST", credentials);

            httpJsonRequest.AddOperationHeaders(OperationsHeaders);
            httpJsonRequest.ReadResponseString();
        }
Exemple #9
0
        public string PutIndex(string name, IndexDefinition definition, bool overwrite)
        {
            EnsureIsNotNullOrEmpty(name, "name");

            string requestUri = url + "/indexes/" + name;

            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                webRequest.Method = "HEAD";
                webRequest.GetResponse().Close();
                if (overwrite == false)
                {
                    throw new InvalidOperationException("Cannot put index: " + name + ", index already exists");
                }
            }
            catch (WebException e)
            {
                var response = e.Response as HttpWebResponse;
                if (response == null || response.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            var request = HttpJsonRequest.CreateHttpJsonRequest(this, requestUri, "PUT", credentials);

            request.Write(JsonConvert.SerializeObject(definition, new JsonEnumConverter()));

            var obj = new { index = "" };

            obj = JsonConvert.DeserializeAnonymousType(request.ReadResponseString(), obj);
            return(obj.index);
        }
Exemple #10
0
        private PutResult DirectPut(JObject metadata, string key, Guid?etag, JObject document, string operationUrl)
        {
            if (metadata == null)
            {
                metadata = new JObject();
            }
            var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";

            AddTransactionInformation(metadata);
            if (etag != null)
            {
                metadata["ETag"] = new JValue(etag.Value.ToString());
            }
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/docs/" + key, method, metadata, credentials);

            request.Write(document.ToString());

            string readResponseString;

            try
            {
                readResponseString = request.ReadResponseString();
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null ||
                    httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
                throw ThrowConcurrencyException(e);
            }
            return(JsonConvert.DeserializeObject <PutResult>(readResponseString, new JsonEnumConverter()));
        }
Exemple #11
0
        private object DirectResetIndex(string name, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/indexes/" + name, "RESET", credentials, convention);

            httpJsonRequest.AddOperationHeaders(OperationsHeaders);
            httpJsonRequest.ReadResponseString();
            return(null);
        }
Exemple #12
0
        private string[] DirectGetIndexNames(int start, int pageSize, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/indexes/?namesOnly=true&start=" + start + "&pageSize=" + pageSize, "GET", credentials, convention);

            httpJsonRequest.AddOperationHeaders(OperationsHeaders);
            var responseString = httpJsonRequest.ReadResponseString();

            return(JArray.Parse(responseString).Select(x => x.Value <string>()).ToArray());
        }
Exemple #13
0
        /// <summary>
        /// Execute a GET request against the provided url
        /// and return the result as a string
        /// </summary>
        /// <param name="requestUrl">The relative url to the server</param>
        /// <remarks>
        /// This method respects the replication semantics against the database.
        /// </remarks>
        public string ExecuteGetRequest(string requestUrl)
        {
            EnsureIsNotNullOrEmpty(requestUrl, "url");
            return(ExecuteWithReplication("GET", serverUrl =>
            {
                var metadata = new JObject();
                AddTransactionInformation(metadata);
                var request = HttpJsonRequest.CreateHttpJsonRequest(this, serverUrl + requestUrl, "GET", metadata, credentials, convention);
                request.AddOperationHeaders(OperationsHeaders);

                return request.ReadResponseString();
            }));
        }
Exemple #14
0
        /// <summary>
        /// Puts the index.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="definition">The definition.</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        /// <returns></returns>
        public string PutIndex(string name, IndexDefinition definition, bool overwrite)
        {
            EnsureIsNotNullOrEmpty(name, "name");

            string requestUri = url + "/indexes/" + name;

            var request = HttpJsonRequest.CreateHttpJsonRequest(this, requestUri, "PUT", credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            request.Write(JsonConvert.SerializeObject(definition, new JsonEnumConverter()));

            var obj = new { index = "" };

            obj = JsonConvert.DeserializeAnonymousType(request.ReadResponseString(), obj);
            return(obj.index);
        }
Exemple #15
0
        private JsonDocument DirectGet(string serverUrl, string key)
        {
            var metadata = new JObject();

            AddTransactionInformation(metadata);
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, serverUrl + "/docs/" + key, "GET", metadata, credentials);

            request.AddOperationHeaders(OperationsHeaders);
            try
            {
                return(new JsonDocument
                {
                    DataAsJson = JObject.Parse(request.ReadResponseString()),
                    NonAuthoritiveInformation = request.ResponseStatusCode == HttpStatusCode.NonAuthoritativeInformation,
                    Key = key,
                    Etag = new Guid(request.ResponseHeaders["ETag"]),
                    Metadata = request.ResponseHeaders.FilterHeaders(isServerDocument: false)
                });
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw;
                }
                if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                {
                    var conflicts    = new StreamReader(httpWebResponse.GetResponseStream());
                    var conflictsDoc = JObject.Load(new JsonTextReader(conflicts));
                    var conflictIds  = conflictsDoc.Value <JArray>("Conflicts").Select(x => x.Value <string>()).ToArray();

                    throw new ConflictException("Conflict detected on " + key +
                                                ", conflict must be resolved before the document will be accessible")
                          {
                              ConflictedVersionIds = conflictIds
                          };
                }
                throw;
            }
        }
Exemple #16
0
        private JsonDocument[] DirectGet(string[] ids, string operationUrl)
        {
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/queries/", "POST", credentials);

            request.Write(new JArray(ids).ToString(Formatting.None));
            var responses = JArray.Parse(request.ReadResponseString());

            return((from doc in responses.Cast <JObject>()
                    let metadata = (JObject)doc["@metadata"]
                                   let _ = doc.Remove("@metadata")
                                           select new JsonDocument
            {
                Key = metadata["@id"].Value <string>(),
                Etag = new Guid(metadata["@etag"].Value <string>()),
                Metadata = metadata,
                DataAsJson = doc,
            })
                   .ToArray());
        }
Exemple #17
0
        /// <summary>
        /// Returns a list of suggestions based on the specified suggestion query.
        /// </summary>
        /// <param name="index">The index to query for suggestions</param>
        /// <param name="suggestionQuery">The suggestion query.</param>
        /// <returns></returns>
        public SuggestionQueryResult Suggest(string index, SuggestionQuery suggestionQuery)
        {
            if (suggestionQuery == null)
            {
                throw new ArgumentNullException("suggestionQuery");
            }

            var requestUri = url + string.Format("/suggest/{0}?term={1}&field={2}&max={3}&distance={4}&accuracy={5}",
                                                 Uri.EscapeUriString(index),
                                                 Uri.EscapeDataString(suggestionQuery.Term),
                                                 Uri.EscapeDataString(suggestionQuery.Field),
                                                 Uri.EscapeDataString(suggestionQuery.MaxSuggestions.ToString()),
                                                 Uri.EscapeDataString(suggestionQuery.Distance.ToString()),
                                                 Uri.EscapeDataString(suggestionQuery.Accuracy.ToString()));

            var request = HttpJsonRequest.CreateHttpJsonRequest(this, requestUri, "GET", credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            var    serializer = convention.CreateSerializer();
            JToken json;

            try
            {
                using (var reader = new JsonTextReader(new StringReader(request.ReadResponseString())))
                    json = (JToken)serializer.Deserialize(reader);
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.InternalServerError)
                {
                    throw new InvalidOperationException("could not execute suggestions at this time");
                }
                throw;
            }

            return(new SuggestionQueryResult
            {
                Suggestions = json["Suggestions"].Children().Select(x => x.Value <string>()).ToArray(),
            });
        }
Exemple #18
0
        private QueryResult DirectQuery(string index, IndexQuery query, string operationUrl)
        {
            var path = string.Format("{0}/indexes/{1}?query={2}&start={3}&pageSize={4}", operationUrl, index, query.Query, query.Start, query.PageSize);

            if (query.FieldsToFetch != null && query.FieldsToFetch.Length > 0)
            {
                path = query.FieldsToFetch.Aggregate(
                    new StringBuilder(path),
                    (sb, field) => sb.Append("&fetch=").Append(Uri.EscapeDataString(field))
                    ).ToString();
            }
            if (query.SortedFields != null && query.SortedFields.Length > 0)
            {
                path = query.SortedFields.Aggregate(
                    new StringBuilder(path),
                    (sb, field) => sb.Append("&sort=").Append(field.Descending ? "-" : "").Append(Uri.EscapeDataString(field.Field))
                    ).ToString();
            }
            if (query.Cutoff != null)
            {
                path = path + "&cutOff=" + Uri.EscapeDataString(query.Cutoff.Value.ToString("o", CultureInfo.InvariantCulture));
            }
            var request    = HttpJsonRequest.CreateHttpJsonRequest(this, Uri.EscapeUriString(path), "GET", credentials);
            var serializer = new JsonSerializer
            {
                ContractResolver    = convention.JsonContractResolver,
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            };
            JToken json;

            using (var reader = new JsonTextReader(new StringReader(request.ReadResponseString())))
                json = (JToken)serializer.Deserialize(reader);

            return(new QueryResult
            {
                IsStale = Convert.ToBoolean(json["IsStale"].ToString()),
                Results = json["Results"].Children().Cast <JObject>().ToArray(),
                TotalResults = Convert.ToInt32(json["TotalResults"].ToString())
            });
        }
Exemple #19
0
        private QueryResult DirectQuery(string index, IndexQuery query, string operationUrl, string[] includes)
        {
            string path = query.GetIndexQueryUrl(operationUrl, index, "indexes");

            if (includes != null && includes.Length > 0)
            {
                path += "&" + string.Join("&", includes.Select(x => "include=" + x).ToArray());
            }
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "GET", credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            var    serializer = convention.CreateSerializer();
            JToken json;

            try
            {
                using (var reader = new JsonTextReader(new StringReader(request.ReadResponseString())))
                    json = (JToken)serializer.Deserialize(reader);
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new InvalidOperationException("There is no index named: " + index);
                }
                throw;
            }
            return(new QueryResult
            {
                IsStale = Convert.ToBoolean(json["IsStale"].ToString()),
                IndexTimestamp = json.Value <DateTime>("IndexTimestamp"),
                IndexEtag = new Guid(request.ResponseHeaders["ETag"]),
                Results = json["Results"].Children().Cast <JObject>().ToList(),
                Includes = json["Includes"].Children().Cast <JObject>().ToList(),
                TotalResults = Convert.ToInt32(json["TotalResults"].ToString()),
                IndexName = json.Value <string>("IndexName"),
                SkippedResults = Convert.ToInt32(json["SkippedResults"].ToString()),
            });
        }
Exemple #20
0
 public void DeleteByIndex(string indexName, IndexQuery queryToDelete, bool allowStale)
 {
     ExecuteWithReplication <object>(operationUrl =>
     {
         string path = queryToDelete.GetIndexQueryUrl(operationUrl, indexName, "bulk_docs") + "&allowStale=" + allowStale;
         var request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "DELETE", credentials);
         request.AddOperationHeaders(OperationsHeaders);
         try
         {
             request.ReadResponseString();
         }
         catch (WebException e)
         {
             var httpWebResponse = e.Response as HttpWebResponse;
             if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
             {
                 throw new InvalidOperationException("There is no index named: " + indexName);
             }
             throw;
         }
         return(null);
     });
 }
Exemple #21
0
 public void UpdateByIndex(string indexName, IndexQuery queryToUpdate, PatchRequest[] patchRequests, bool allowStale)
 {
     ExecuteWithReplication <object>(operationUrl =>
     {
         string path = queryToUpdate.GetIndexQueryUrl(operationUrl, indexName, "bulk_docs") + "&allowStale=" + allowStale;
         var request = HttpJsonRequest.CreateHttpJsonRequest(this, path, "PATCH", credentials);
         request.AddOperationHeaders(OperationsHeaders);
         request.Write(new JArray(patchRequests.Select(x => x.ToJson())).ToString(Formatting.Indented));
         try
         {
             request.ReadResponseString();
         }
         catch (WebException e)
         {
             var httpWebResponse = e.Response as HttpWebResponse;
             if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
             {
                 throw new InvalidOperationException("There is no index named: " + indexName);
             }
             throw;
         }
         return(null);
     });
 }
Exemple #22
0
        private void DirectCommit(Guid txId, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/transaction/commit?tx=" + txId, "POST", credentials);

            httpJsonRequest.ReadResponseString();
        }
Exemple #23
0
        /// <summary>
        /// Perform a direct get for a document with the specified key on the specified server URL.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public JsonDocument DirectGet(string serverUrl, string key)
        {
            var metadata = new JObject();

            AddTransactionInformation(metadata);
            var request = HttpJsonRequest.CreateHttpJsonRequest(this, serverUrl + "/docs/" + key, "GET", metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            try
            {
                var     requestString = request.ReadResponseString();
                JObject meta          = null;
                JObject jsonData      = null;
                try
                {
                    jsonData = JObject.Parse(requestString);
                    meta     = request.ResponseHeaders.FilterHeaders(isServerDocument: false);
                }
                catch (JsonReaderException jre)
                {
                    var headers = "";
                    foreach (string header in request.ResponseHeaders)
                    {
                        headers = headers + string.Format("\n\r{0}:{1}", header, request.ResponseHeaders[header]);
                    }
                    throw new JsonReaderException("Invalid Json Response: \n\rHeaders:\n\r" + headers + "\n\rBody:" + requestString, jre);
                }
                return(new JsonDocument
                {
                    DataAsJson = jsonData,
                    NonAuthoritiveInformation = request.ResponseStatusCode == HttpStatusCode.NonAuthoritativeInformation,
                    Key = key,
                    Etag = new Guid(request.ResponseHeaders["ETag"]),
                    LastModified = DateTime.ParseExact(request.ResponseHeaders["Last-Modified"], "r", CultureInfo.InvariantCulture),
                    Metadata = meta
                });
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw;
                }
                if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                {
                    var conflicts    = new StreamReader(httpWebResponse.GetResponseStreamWithHttpDecompression());
                    var conflictsDoc = JObject.Load(new JsonTextReader(conflicts));
                    var conflictIds  = conflictsDoc.Value <JArray>("Conflicts").Select(x => x.Value <string>()).ToArray();

                    throw new ConflictException("Conflict detected on " + key +
                                                ", conflict must be resolved before the document will be accessible")
                          {
                              ConflictedVersionIds = conflictIds
                          };
                }
                throw;
            }
        }