Exemplo n.º 1
0
		/// <summary>
		/// Creates the HTTP json request.
		/// </summary>
		/// <param name="self">The self.</param>
		/// <param name="url">The URL.</param>
		/// <param name="method">The method.</param>
		/// <param name="metadata">The metadata.</param>
		/// <param name="credentials">The credentials.</param>
		/// <param name="convention">The document conventions governing this request</param>
		/// <returns></returns>
		public HttpJsonRequest CreateHttpJsonRequest(object self, string url, string method, JObject metadata,
													 ICredentials credentials, DocumentConvention convention)
		{
			var request = new HttpJsonRequest(url, method, metadata, credentials, this);
			ConfigureCaching(url, method, convention, request);
			ConfigureRequest(self, new WebRequestEventArgs { Request = request.WebRequest });
			return request;
		}
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
 internal string GetCachedResponse(HttpJsonRequest httpJsonRequest)
 {
     if (httpJsonRequest.CachedRequestDetails == null)
     {
         throw new InvalidOperationException("Cannot get cached response from a request that has no cached infomration");
     }
     httpJsonRequest.ResponseStatusCode = HttpStatusCode.NotModified;
     httpJsonRequest.ResponseHeaders    = new NameValueCollection(httpJsonRequest.CachedRequestDetails.Headers);
     Interlocked.Increment(ref NumOfCachedRequests);
     return(httpJsonRequest.CachedRequestDetails.Data);
 }
Exemplo n.º 4
0
		private void ConfigureCaching(string url, string method, DocumentConvention convention, HttpJsonRequest request)
		{
			request.ShouldCacheRequest = convention.ShouldCacheRequest(url);
			if (!request.ShouldCacheRequest || method != "GET")
				return;

			var cachedRequest = (CachedRequest)cache.Get(url);
			if (cachedRequest == null)
				return;
			request.CachedRequestDetails = cachedRequest;
			request.WebRequest.Headers["If-None-Match"] = cachedRequest.Headers["ETag"];
		}
Exemplo n.º 5
0
 internal void CacheResponse(WebResponse response, string text, HttpJsonRequest httpJsonRequest)
 {
     if (httpJsonRequest.Method == "GET" && httpJsonRequest.ShouldCacheRequest &&
         string.IsNullOrEmpty(response.Headers["ETag"]) == false)
     {
         cache.Set(httpJsonRequest.Url, new CachedRequest
         {
             Data    = text,
             Headers = response.Headers
         }, new CacheItemPolicy());                 // cache as much as possible, for as long as possible, using the default cache limits
     }
 }
Exemplo n.º 6
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();
            }));
        }
Exemplo n.º 7
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());
        }
Exemplo n.º 8
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(),
            });
        }
Exemplo n.º 9
0
 public void Delete(string key, Guid? etag)
 {
     EnsureIsNotNullOrEmpty(key, "key");
     var metadata = new JObject();
     if (etag != null)
         metadata.Add("ETag", new JValue(etag.Value.ToString()));
     AddTransactionInformation(metadata);
     var httpJsonRequest = new HttpJsonRequest(url + "/docs/" + key, "DELETE", metadata);
     try
     {
         httpJsonRequest.ReadResponseString();
     }
     catch (WebException e)
     {
         var httpWebResponse = e.Response as HttpWebResponse;
         if (httpWebResponse == null ||
             httpWebResponse.StatusCode != HttpStatusCode.Conflict)
             throw;
          throw ThrowConcurrencyException(e);
     }
 }
Exemplo n.º 10
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())
            });
        }
Exemplo n.º 11
0
        public BatchResult[] Batch(ICommandData[] commandDatas)
        {
            var metadata = new JObject();
            AddTransactionInformation(metadata);
            var req = new HttpJsonRequest(url + "/bulk_docs", "POST",metadata);
            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);
        }
Exemplo n.º 12
0
        private void DirectRollback(Guid txId, string operationUrl)
        {
            var httpJsonRequest = HttpJsonRequest.CreateHttpJsonRequest(this, operationUrl + "/transaction/rollback?tx=" + txId, "POST", credentials);

            httpJsonRequest.ReadResponseString();
        }
Exemplo n.º 13
0
			public MultiStepAsyncResult(object state, HttpJsonRequest req)
			{
				this.state = state;
				this.req = req;
				manualResetEvent = new ManualResetEvent(false);
			}
Exemplo n.º 14
0
			public UserAsyncData(HttpJsonRequest request, IAsyncResult result)
			{
				Request = request;
				Result = result;
			}
Exemplo n.º 15
0
        public JsonDocument Get(string key)
        {
            EnsureIsNotNullOrEmpty(key, "key");

            var metadata = new JObject();
            AddTransactionInformation(metadata);
            var request = new HttpJsonRequest(url + "/docs/" + key, "GET", metadata);
            try
            {
                return new JsonDocument
                {
                    Data = Encoding.UTF8.GetBytes(request.ReadResponseString()),
                    Key = key,
                    Etag = new Guid(request.ResponseHeaders["ETag"]),
                    Metadata = request.ResponseHeaders.FilterHeaders()
                };
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null ||
                    httpWebResponse.StatusCode != HttpStatusCode.NotFound)
                    throw;
                return null;
            }
        }
Exemplo n.º 16
0
        public QueryResult Query(string index, IndexQuery query)
        {
            EnsureIsNotNullOrEmpty(index, "index");
            var path = string.Format("{0}/indexes/{1}?query={2}&start={3}&pageSize={4}", url, 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(field)
                    ).ToString();
            }
            if(query.SortedFields!=null && query.SortedFields.Length>0)
            {
                path = query.SortedFields.Aggregate(
                        new StringBuilder(path),
                        (sb, field) => sb.Append("&sort=").Append(HttpUtility.UrlEncode(field.Descending ? "-" : "+")).Append(field.Field)
                    ).ToString();
            }
            var request = new HttpJsonRequest(path, "GET");
            var serializer = new JsonSerializer();
            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(),
            };
        }
Exemplo n.º 17
0
		/// <summary>
		/// Creates the HTTP json request.
		/// </summary>
		/// <param name="self">The self.</param>
		/// <param name="url">The URL.</param>
		/// <param name="method">The method.</param>
		/// <param name="credentials">The credentials.</param>
		/// <param name="convention">The document conventions governing this request</param>
		/// <returns></returns>
		public static HttpJsonRequest CreateHttpJsonRequest(object self, string url, string method, ICredentials credentials, DocumentConvention convention)
		{
			var request = new HttpJsonRequest(url, method, new JObject());
			ConfigureRequest(self, new WebRequestEventArgs { Request = request.webRequest });
			return request;
		}
Exemplo n.º 18
0
        public PutResult Put(string key, Guid? etag, JObject document, JObject metadata)
        {
            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 = new HttpJsonRequest(url + "/docs/" + key, method, metadata);
            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());
        }
Exemplo n.º 19
0
 public void DeleteIndex(string name)
 {
     EnsureIsNotNullOrEmpty(name, "name");
     var request = new HttpJsonRequest(url + "/indexes/" + name, "DELETE");
     request.ReadResponseString();
 }
Exemplo n.º 20
0
        private void ConfigureCaching(string url, string method, DocumentConvention convention, HttpJsonRequest request)
        {
            request.ShouldCacheRequest = convention.ShouldCacheRequest(url);
            if (!request.ShouldCacheRequest || method != "GET")
            {
                return;
            }

            var cachedRequest = (CachedRequest)cache.Get(url);

            if (cachedRequest == null)
            {
                return;
            }
            request.CachedRequestDetails = cachedRequest;
            request.WebRequest.Headers["If-None-Match"] = cachedRequest.Headers["ETag"];
        }
Exemplo n.º 21
0
 public void Commit(Guid txId)
 {
     var httpJsonRequest = new HttpJsonRequest("/transaction/commit?tx=" + txId, "POST");
     httpJsonRequest.ReadResponseString();
 }
Exemplo n.º 22
0
 public void Rollback(Guid txId)
 {
     var httpJsonRequest = new HttpJsonRequest("/transaction/rollback?tx=" + txId, "POST");
     httpJsonRequest.ReadResponseString();
 }
Exemplo n.º 23
0
		internal string GetCachedResponse(HttpJsonRequest httpJsonRequest)
		{
			if (httpJsonRequest.CachedRequestDetails == null)
				throw new InvalidOperationException("Cannot get cached response from a request that has no cached infomration");
			httpJsonRequest.ResponseStatusCode = HttpStatusCode.NotModified;
			httpJsonRequest.ResponseHeaders = new NameValueCollection(httpJsonRequest.CachedRequestDetails.Headers);
			Interlocked.Increment(ref NumOfCachedRequests);
			return httpJsonRequest.CachedRequestDetails.Data;
		}
Exemplo n.º 24
0
        public JsonDocument[] Get(string[] ids)
        {
            var request = new HttpJsonRequest(url + "/queries/", "POST");
            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,
                        Data = Encoding.UTF8.GetBytes(doc.ToString(Formatting.None)),
                    })
                .ToArray();
        }
Exemplo n.º 25
0
		internal void CacheResponse(WebResponse response, string text, HttpJsonRequest httpJsonRequest)
		{
			if (httpJsonRequest.Method == "GET" && httpJsonRequest.ShouldCacheRequest &&
				string.IsNullOrEmpty(response.Headers["ETag"]) == false)
			{
				cache.Set(httpJsonRequest.Url, new CachedRequest
				{
					Data = text,
					Headers = response.Headers
				}, new CacheItemPolicy()); // cache as much as possible, for as long as possible, using the default cache limits
			}
		}
Exemplo n.º 26
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;
            }
        }
Exemplo n.º 27
0
 public static HttpJsonRequest CreateHttpJsonRequest(object self, string url, string method, JObject metadata, ICredentials credentials)
 {
     var request = new HttpJsonRequest(url, method, metadata, credentials);
     ConfigureRequest(self, new WebRequestEventArgs { Request = request.webRequest });
     return request;
 }
Exemplo n.º 28
0
        public string PutIndex(string name, IndexDefinition definition)
        {
            EnsureIsNotNullOrEmpty(name, "name");
            var request = new HttpJsonRequest(url + "/indexes/" + name, "PUT");
            request.Write(JsonConvert.SerializeObject(definition, new JsonEnumConverter()));

            var obj = new {index = ""};
            obj = JsonConvert.DeserializeAnonymousType(request.ReadResponseString(), obj);
            return obj.index;
        }