Beispiel #1
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="convention">The convention.</param>
		/// <param name="credentials">The credentials.</param>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory)
		{
			this.url = url;
			this.jsonRequestFactory = jsonRequestFactory;
			this.convention = convention;
			this.credentials = credentials;
		}
Beispiel #2
0
		internal HttpJsonRequest(
			CreateHttpJsonRequestParams requestParams,
			HttpJsonRequestFactory factory)
		{
			_credentials = requestParams.Credentials;
			Url = requestParams.Url;
			this.factory = factory;
			owner = requestParams.Owner;
			conventions = requestParams.Convention;
			Method = requestParams.Method;
			webRequest = (HttpWebRequest)WebRequest.Create(requestParams.Url);
			webRequest.UseDefaultCredentials = true;
			webRequest.Credentials = requestParams.Credentials.Credentials;
			webRequest.Method = requestParams.Method;
			if (factory.DisableRequestCompression == false && requestParams.DisableRequestCompression == false)
			{
				if (requestParams.Method == "POST" || requestParams.Method == "PUT" ||
					requestParams.Method == "PATCH" || requestParams.Method == "EVAL")
					webRequest.Headers["Content-Encoding"] = "gzip";

				webRequest.Headers["Accept-Encoding"] = "gzip";
			}
			webRequest.ContentType = "application/json; charset=utf-8";
			webRequest.Headers.Add("Raven-Client-Version", ClientVersion);
			WriteMetadata(requestParams.Metadata);
			requestParams.UpdateHeaders(webRequest);
		}
Beispiel #3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="convention">The convention.</param>
		/// <param name="credentials">The credentials.</param>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid? sessionId)
		{
			profilingInformation = ProfilingInformation.CreateProfilingInformation(sessionId);
			this.url = url;
			this.jsonRequestFactory = jsonRequestFactory;
			this.sessionId = sessionId;
			this.convention = convention;
			this.credentials = credentials;
		}
Beispiel #4
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid? sessionId)
		{
			profilingInformation = ProfilingInformation.CreateProfilingInformation(sessionId);
			this.url = url;
			if (this.url.EndsWith("/"))
				this.url = this.url.Substring(0, this.url.Length-1);
			this.jsonRequestFactory = jsonRequestFactory;
			this.sessionId = sessionId;
			this.convention = convention;
			this.credentials = credentials;
		}
Beispiel #5
0
		public bool CanFullyCache(HttpJsonRequestFactory jsonRequestFactory, HttpJsonRequest httpJsonRequest, string postedData)
		{
			if (allRequestsCanBeServedFromAggressiveCache) // can be fully served from aggressive cache
			{
				jsonRequestFactory.InvokeLogRequest(holdProfilingInformation, () => new RequestResultArgs
				{
					DurationMilliseconds = httpJsonRequest.CalculateDuration(),
					Method = httpJsonRequest.Method,
					HttpResult = 0,
					Status = RequestStatus.AggressivelyCached,
					Result = "",
					Url = httpJsonRequest.Url.ToString(),
					//TODO: check that is the same as: Url = httpJsonRequest.webRequest.RequestUri.PathAndQuery,
					PostedData = postedData
				});
				return true;
			}
			return false;
		}
Beispiel #6
0
		internal HttpJsonRequest(string url, string method, RavenJObject metadata, DocumentConvention conventions, HttpJsonRequestFactory factory)
		{
			this.url = new Uri(url);
			this.conventions = conventions;
			this.factory = factory;
			this.method = new HttpMethod(method);

			var handler = new HttpClientHandler();
			httpClient = new HttpClient(handler);
			httpClient.DefaultRequestHeaders.Add("Raven-Client-Version", ClientVersion);

			WriteMetadata(metadata);
			if (method != "GET")
				httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json") {CharSet = "utf-8"});

			if (factory.DisableRequestCompression == false)
			if (method == "POST" || method == "PUT" || method == "PATCH" || method == "EVAL")
				httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Encoding", "gzip");
		}
Beispiel #7
0
		public GetRequest[] PreparingForCachingRequest(HttpJsonRequestFactory jsonRequestFactory)
		{
			cachedData = new CachedRequest[requests.Length];
			var requestsForServer = new GetRequest[requests.Length];
			Array.Copy(requests, 0, requestsForServer, 0, requests.Length);
			if (jsonRequestFactory.DisableHttpCaching == false && convention.ShouldCacheRequest(requestUri))
			{
				for (int i = 0; i < requests.Length; i++)
				{
					var request = requests[i];
					var cachingConfiguration = jsonRequestFactory.ConfigureCaching(url + request.UrlAndQuery,
																				   (key, val) => request.Headers[key] = val);
					cachedData[i] = cachingConfiguration.CachedRequest;
					if (cachingConfiguration.SkipServerCheck)
						requestsForServer[i] = null;
				}
			}
			allRequestsCanBeServedFromAggressiveCache = requestsForServer.All(x => x == null);
			return requestsForServer;
		}
Beispiel #8
0
		public BasicAuthenticator(ICredentials credentials, string apiKey, HttpJsonRequestFactory jsonRequestFactory)
		{
			this.credentials = credentials;
			this.apiKey = apiKey;
			this.jsonRequestFactory = jsonRequestFactory;
		}
		public BasicAuthenticator(string apiKey, HttpJsonRequestFactory jsonRequestFactory)
		{
			this.apiKey = apiKey;
			this.jsonRequestFactory = jsonRequestFactory;
		}
Beispiel #10
0
		public GetResponse[] HandleCachingResponse(GetResponse[] responses, HttpJsonRequestFactory jsonRequestFactory)
		{
			var hasCachedRequests = false;
			var requestStatuses = new RequestStatus[responses.Length];
			for (int i = 0; i < responses.Length; i++)
			{
				if (responses[i] == null || responses[i].Status == 304)
				{
					hasCachedRequests = true;

					requestStatuses[i] = responses[i] == null ? RequestStatus.AggressivelyCached : RequestStatus.Cached;
					responses[i] = responses[i] ?? new GetResponse { Status = 0 };

					foreach (string header in cachedData[i].Headers)
					{
						responses[i].Headers[header] = cachedData[i].Headers[header];
					}
					responses[i].Result = cachedData[i].Data.CloneToken();
					jsonRequestFactory.IncrementCachedRequests();
				}
				else
				{
					requestStatuses[i] = responses[i].RequestHasErrors() ? RequestStatus.ErrorOnServer : RequestStatus.SentToServer;

					var nameValueCollection = new NameValueCollection();
					foreach (var header in responses[i].Headers)
					{
						nameValueCollection[header.Key] = header.Value;
					}
					jsonRequestFactory.CacheResponse(url + requests[i].UrlAndQuery, responses[i].Result, nameValueCollection);
				}
			}

			if (hasCachedRequests == false || convention.DisableProfiling)
				return responses;

			var lastRequest = holdProfilingInformation.ProfilingInformation.Requests.Last();
			for (int i = 0; i < requestStatuses.Length; i++)
			{
				lastRequest.AdditionalInformation["NestedRequestStatus-" + i] = requestStatuses[i].ToString();
			}
			lastRequest.Result = JsonConvert.SerializeObject(responses);

			return responses;
		}
Beispiel #11
0
        protected AsyncServerClientBase(string serverUrl, TConvention convention, OperationCredentials credentials, HttpJsonRequestFactory jsonRequestFactory,
                                        Guid?sessionId, NameValueCollection operationsHeaders, Func <string, TReplicationInformer> replicationInformerGetter, string resourceName)
        {
            WasDisposed = false;

            ServerUrl   = serverUrl.TrimEnd('/');
            Conventions = convention ?? new TConvention();
            CredentialsThatShouldBeUsedOnlyInOperationsWithoutReplication = credentials;
            RequestFactory    = jsonRequestFactory ?? new HttpJsonRequestFactory(DefaultNumberOfCachedRequests);
            SessionId         = sessionId;
            OperationsHeaders = operationsHeaders ?? DefaultNameValueCollection;

            ReplicationInformerGetter = replicationInformerGetter ?? DefaultReplicationInformerGetter();
            replicationInformer       = new Lazy <TReplicationInformer>(() => ReplicationInformerGetter(resourceName), true);
            readStrippingBase         = new Lazy <int>(() => ReplicationInformer.GetReadStripingBase(true), true);

            MaxQuerySizeForGetRequest = 8 * 1024;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
        /// </summary>
        public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid?sessionId, Task veryFirstRequest)
        {
            profilingInformation    = ProfilingInformation.CreateProfilingInformation(sessionId);
            this.url                = url.EndsWith("/") ? url.Substring(0, url.Length - 1) : url;
            this.convention         = convention;
            this.credentials        = credentials;
            this.jsonRequestFactory = jsonRequestFactory;
            this.sessionId          = sessionId;
            this.veryFirstRequest   = veryFirstRequest;

            jsonRequestFactory.ConfigureRequest += (sender, args) =>
            {
                args.JsonRequest.WaitForTask = veryFirstRequest;
            };
        }
        internal static async Task <Stream> DownloadAsyncImpl(IHoldProfilingInformation self, HttpJsonRequestFactory requestFactory, FilesConvention conventions,
                                                              NameValueCollection operationsHeaders, string path, string filename, Reference <RavenJObject> metadataRef, long? @from, long?to, string baseUrl, OperationCredentials credentials)
        {
            var request = requestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(self, baseUrl + path + Uri.EscapeDataString(filename), "GET", credentials, conventions)).AddOperationHeaders(operationsHeaders);

            if (@from != null)
            {
                if (to != null)
                {
                    request.AddRange(@from.Value, to.Value);
                }
                else
                {
                    request.AddRange(@from.Value);
                }
            }

            try
            {
                var response = await request.ExecuteRawResponseAsync().ConfigureAwait(false);

                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new FileNotFoundException("The file requested does not exists on the file system.", baseUrl + path + filename);
                }

                await response.AssertNotFailingResponse().ConfigureAwait(false);

                if (metadataRef != null)
                {
                    metadataRef.Value = response.HeadersToObject();
                }

                return(new DisposableStream(await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false), request.Dispose));
            }
            catch (Exception e)
            {
                throw e.SimplifyException();
            }
        }
        internal static async Task <RavenJObject> GetMetadataForAsyncImpl(IHoldProfilingInformation self, HttpJsonRequestFactory requestFactory, FilesConvention conventions,
                                                                          NameValueCollection operationsHeaders, string filename, string baseUrl, OperationCredentials credentials)
        {
            using (var request = requestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(self, baseUrl + "/files?name=" + Uri.EscapeDataString(filename), "HEAD", credentials, conventions)).AddOperationHeaders(operationsHeaders))
            {
                try
                {
                    await request.ExecuteRequestAsync().ConfigureAwait(false);

                    var response = request.Response;

                    var metadata = response.HeadersToObject();
                    metadata[Constants.MetadataEtagField] = metadata[Constants.MetadataEtagField].Value <string>().Trim('\"');
                    return(metadata);
                }
                catch (Exception e)
                {
                    try
                    {
                        throw e.SimplifyException();
                    }
                    catch (FileNotFoundException)
                    {
                        return(null);
                    }
                }
            }
        }