public IncludeExcludeEngineFactory(IPlainEngine plainEngine, Engine.Minify.IMinifyEngine minifyEngine, Http.IHttp http, Configuration.JsMinifierConfiguration configuration)
 {
     _plainEngine = plainEngine;
     _minifyEngine = minifyEngine;
     _http = http;
     _configuration = configuration;
 }
Exemple #2
0
 public SlackApiClient(string token)
 {
     _jsonSettings = Default.JsonSettings(Default.SlackTypeResolver(Default.AssembliesContainingSlackTypes));
     _http         = Default.Http(_jsonSettings);
     _urlBuilder   = Default.UrlBuilder(_jsonSettings);
     _token        = token;
 }
 public void Dispose()
 {
     if (this._HttpHelper != null)
     {
         this._HttpHelper = null;
     }
 }
        internal static void AddBody(this IHttp http, string contentType, string name, object value)
        {
            // Only add the body if there aren't any files to make it a multipart form request
            // If there are files or AlwaysMultipartFormData = true, then add the body to the HTTP Parameters
            if (value == null)
            {
                return;
            }

            http.RequestContentType = name;

            if (!http.AlwaysMultipartFormData && !http.Files.Any())
            {
                var val = value;

                var bytes = val as byte[];
                if (bytes != null)
                {
                    http.RequestBodyBytes = bytes;
                }
                else
                {
                    http.RequestBody = value.ToString();
                }
            }
            else
            {
                http.Parameters.Add(new HttpParameter
                {
                    Name        = name,
                    Value       = value.ToString(),
                    ContentType = contentType
                });
            }
        }
Exemple #5
0
 private void ConfigureProxy(IHttp http)
 {
     if (Proxy != null)
     {
         http.Proxy = Proxy;
     }
 }
Exemple #6
0
        private IRestResponse Execute(IRestRequest request, string httpMethod,
                                      Func <IHttp, string, HttpResponse> getResponse)
        {
            this.AuthenticateIfNeeded(this, request);

            IRestResponse response = new RestResponse();

            try
            {
                IHttp http = this.HttpFactory.Create();

                this.ConfigureHttp(request, http);

                response         = ConvertToRestResponse(request, getResponse(http, httpMethod));
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
 public AzureResourceGroupClient(
     HttpClient client, IHttp http, IJson json, IOptions <AzureOptions> azureOptions,
     ILogger <AzureResourceGroupClient> log)
     : base(client, http, json, log)
 {
     _azureOptions = azureOptions.Value;
 }
Exemple #8
0
 public SlackApiClient(IHttp http, ISlackUrlBuilder urlBuilder, SlackJsonSettings jsonSettings, string token)
 {
     _http         = http;
     _urlBuilder   = urlBuilder;
     _jsonSettings = jsonSettings;
     _token        = token;
 }
Exemple #9
0
 public HandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
 {
     Http       = http;
     Response   = response;
     Engine     = engine;
     FileReader = fileReader;
 }
        internal static void AddBody(this IHttp http, RequestBody requestBody)
        {
            // Only add the body if there aren't any files to make it a multipart form request
            // If there are files or AlwaysMultipartFormData = true, then add the body to the HTTP Parameters
            if (requestBody.Value == null)
            {
                return;
            }

            http.RequestContentType = string.IsNullOrWhiteSpace(requestBody.Name)
                ? requestBody.ContentType
                : requestBody.Name;

            if (!http.AlwaysMultipartFormData && !http.Files.Any())
            {
                var val = requestBody.Value;

                if (val is byte[] bytes)
                {
                    http.RequestBodyBytes = bytes;
                }
                else
                {
                    http.RequestBody = requestBody.Value.ToString();
                }
            }
            else
            {
                http.Parameters.Add(new HttpParameter(requestBody.Name, requestBody.Value, requestBody.ContentType));
            }
        }
        internal static void AddBody(this IHttp http, IEnumerable <Parameter> parameters,
                                     IDictionary <DataFormat, IRestSerializer> serializers)
        {
            var body = parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);

            if (body == null)
            {
                return;
            }

            if (body.DataFormat == DataFormat.None)
            {
                http.AddBody(body.ContentType, body.Name, body.Value);
            }
            else
            {
                if (!serializers.TryGetValue(body.DataFormat, out var serializer))
                {
                    throw new InvalidDataContractException(
                              $"Can't find serializer for content type {body.DataFormat}");
                }

                http.AddBody(serializer.ContentType, serializer.ContentType, serializer.Serialize(body));
            }
        }
Exemple #12
0
 public LessHandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
 {
     Http = http;
     Response = response;
     Engine = engine;
     FileReader = fileReader;
 }
 private static void addTenantIdHeader(IHttp http)
 {
     if (LoginInfoCache.AuthenticateModel != null && !string.IsNullOrEmpty(LoginInfoCache.AuthenticateModel.TenantId))
     {
         http.Headers.Add(new HttpHeader(HttpHeaderConstants.MutitenancyTenantIdKeyName, LoginInfoCache.AuthenticateModel.TenantId));
     }
 }
 private static void addAuthorizationHeaders(IHttp http)
 {
     if (LoginInfoCache.AuthenticateResultModel != null && !string.IsNullOrEmpty(LoginInfoCache.AuthenticateResultModel.AccessToken))
     {
         http.Headers.Add(new HttpHeader("Authorization", "Bearer " + LoginInfoCache.AuthenticateResultModel.AccessToken));
     }
 }
        private async Task <IRestResponse> Execute(IRestRequest request, string httpMethod,
                                                   Func <IHttp, string, Task <HttpResponse> > getResponse)
        {
            this.AuthenticateIfNeeded(this, request);

            IRestResponse response = new RestResponse();

            try
            {
                IHttp http = this.HttpFactory.Create();

                this.ConfigureHttp(request, http);

                HttpResponse rawResponse = await getResponse(http, httpMethod);

                response         = ConvertToRestResponse(request, rawResponse);
                response.Request = request;
                response.Request.IncreaseNumAttempts();

                if (rawResponse.ContentType != null)
                {
                    response.ContentDeserializer = this.GetHandler(rawResponse.ContentType);
                }
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
 public virtual async Task<HttpContent> Update(Uri requestUri, HttpContent content, IHttp http)
 {
     http.OriginalRequest.RequestUri = requestUri;
     http.OriginalRequest.Content = content;
     HttpResponseMessage response = await http.SendOriginalAsync();
     return response.Content;
 }
 protected AzureClient(HttpClient client, IHttp http, IJson json, ILogger log)
 {
     Client = client;
     Http   = http;
     Json   = json;
     Log    = log;
 }
Exemple #18
0
 /// <summary>
 /// Constructor for DI, you must always call Init(...) afterwards
 /// </summary>
 public DnnEnvironment(IHttp http, ITenant tenant, IPagePublishing publishing, IZoneMapper zoneMapper) : base("DNN.Enviro")
 {
     _http          = http;
     _tenant        = tenant;
     PagePublishing = publishing.Init(Log);
     ZoneMapper     = zoneMapper.Init(Log);
 }
Exemple #19
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            IHttp http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);
            ConfigureHttp(request, http);
            RestRequestAsyncHandle asyncHandle = new RestRequestAsyncHandle();
            Action <HttpResponse>  action      = delegate(HttpResponse r)
            {
                ProcessResponse(request, r, asyncHandle, callback);
            };

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                SynchronizationContext ctx = SynchronizationContext.Current;
                Action <HttpResponse>  cb  = action;
                action = delegate(HttpResponse resp)
                {
                    ctx.Post(delegate
                    {
                        cb(resp);
                    }, null);
                };
            }
            asyncHandle.WebRequest = getWebRequest(http, action, httpMethod);
            return(asyncHandle);
        }
        private void Trace(IHttp http, IRestRequest request)
        {
            var tracer = Tracer;

            if (tracer != null)
            {
                // trace API method name
                var apiMethod = http.Headers.FirstOrDefault(h => StringComparer.OrdinalIgnoreCase.Equals(h.Name, ApiMethodNameHeaderName));
                if (apiMethod != null && !string.IsNullOrWhiteSpace(apiMethod.Value))
                {
                    tracer("// {0}", new[] { apiMethod.Value });
                }

                // trace HTTP request internals
                var method  = request.Method.ToString();
                var uri     = http.Url;
                var body    = FormatBody(request.Body);
                var headers = FormatHeaders(GetHeaders(http));

                tracer("-> {0} {1}{2}{3}{4}", new object[]
                {
                    method, uri, CR,
                    headers,
                    body,
                });
            }
        }
 public void OnExecuting(IHttp http, IRequest request)
 {
     foreach (var cookie in http.GetCookies())
     {
         request.Add(cookie);
     }
 }
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request,
                                                    Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod,
                                                    Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            IHttp http = this.HttpFactory.Create();

            this.AuthenticateIfNeeded(this, request);
            this.ConfigureHttp(request, http);

            RestRequestAsyncHandle asyncHandle = new RestRequestAsyncHandle();
            Action <HttpResponse>  responseCb  = r => ProcessResponse(request, r, asyncHandle, callback);

#if !PocketPC
            if (this.UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                SynchronizationContext ctx = SynchronizationContext.Current;
                Action <HttpResponse>  cb  = responseCb;

                responseCb = resp => ctx.Post(s => cb(resp), null);
            }
#endif

            asyncHandle.WebRequest = getWebRequest(http, responseCb, httpMethod);

            return(asyncHandle);
        }
Exemple #23
0
        public EavDiModel(ITenant tenant, IHttpContextAccessor httpC, IHttp http)
        {
            // itenant should exist
            var x = tenant.Id;
            var y = httpC.HttpContext.Request.Body;

            Http = http;
        }
Exemple #24
0
 public HttpResponse DoReturnMockResponse(IHttp http, string method)
 {
     MockResponse.ContentType     = "application/json";
     MockResponse.ContentEncoding = "UTF-8";
     MockResponse.StatusCode      = MockResponse.StatusCode == 0 ? System.Net.HttpStatusCode.OK : MockResponse.StatusCode;
     MockResponse.ResponseStatus  = ResponseStatus.Completed;
     return(MockResponse);
 }
        public ExternalContentService(IHttp http, ICacheManager cacheManager)
        {
            Check.Argument.IsNotNull(http, "http");
            Check.Argument.IsNotNull(cacheManager, "cacheManager");

            this.http         = http;
            this.cacheManager = cacheManager;
        }
        public TwitterNotificationService(Settings settings, IEventAggregator eventAggregator, IHttp http) : base(eventAggregator)
        {
            Check.Argument.IsNotNull(settings, "settings");
            Check.Argument.IsNotNull(http, "http");

            this.settings = settings;
            this.http     = http;
        }
Exemple #27
0
 public WithingsAuthentication(ILoggerFactory log, IHttp http, ISecrets secrets, ISettings settings)
 {
     this.log          = log.CreateLogger <WithingsAuthentication>();
     this.http         = http;
     this.secrets      = secrets;
     this.clientId     = settings.GetSetting("WITHINGS_CLIENT_ID");
     this.clientSecret = settings.GetSetting("WITHINGS_CLIENT_SECRET");
 }
Exemple #28
0
 public LicencePlateApi(
     IHttp http,
     IEndpointGetter endpointGetter)
 {
     this.http           = http;
     this.endpointGetter = endpointGetter;
     this.endpoint       = endpointGetter.Get(MicroserviceType.ResourceServer).Result;
 }
 public WithingsClient(ILoggerFactory log, IHttp http, ISettings settings, ICache cache, IWithingsAuthentication authentication)
 {
     this.log            = log.CreateLogger <WithingsClient>();
     this.http           = http;
     this.authentication = authentication;
     this.cache          = cache;
     this.notificationCallbackEndpoint = new Uri($"{settings.GetSetting("API_PREFIX")}/{Apis.CallbackUrl}");
 }
Exemple #30
0
 public JsMinifier(ILogger logger, IHttp http,Reader.IReader reader, Response.IResponse response, Func<IEngineFactory> engineFactory)
 {
     _logger = logger;
     _http = http;
     _reader = reader;
     _response = response;
     _engineFactory = engineFactory;
 }
        public PageGlimpseThumbnail(Settings settings, IHttp http)
        {
            Check.Argument.IsNotNull(settings, "settings");
            Check.Argument.IsNotNull(http, "http");

            this.settings = settings;
            this.http     = http;
        }
 public void OnExecuted(IHttp http, IRequest request, IResponse response)
 {
     foreach (var header in response.Headers.Where(x => x.Name == Slumber.HttpHeaders.SetCookie))
     {
         var cookie = new HttpCookie(header.Value);
         http.Add(cookie);
     }
 }
Exemple #33
0
        public CoffeeHandlerImpl(IHttp http, IResponse response,
                                 ICoffeeEngine engine, IPathResolver resolver)
        {
            Http     = http;
            Response = response;

            mEngine   = engine;
            mResolver = resolver;
        }
Exemple #34
0
        public CoffeeHandlerImpl(IHttp http, IResponse response,
            ICoffeeEngine engine, IPathResolver resolver)
        {
            Http = http;
            Response = response;

            mEngine = engine;
            mResolver = resolver;
        }
        public AccountApi(
            IHttp http,
            IEndpointGetter endpointGetter)
        {
            this.http           = http;
            this.endpointGetter = endpointGetter;

            endpoint = endpointGetter.Get(MicroserviceType.IdentityServer).Result;
        }
Exemple #36
0
            /// <summary>
            /// Intercepts the request just before going over the wire in order to calculate and insert hmacauth validation.
            /// </summary>
            /// <param name="http"></param>
            internal void ApplyHmac(IHttp http)
            {
                var secretBytes    = http.Encoding.GetBytes(ApiSecret ?? string.Empty);
                var apiKey         = ApiKey ?? string.Empty;
                var installationId = ApiInstallationId ?? string.Empty;

                var bodyBytes = http.RequestBodyBytes ?? http.Encoding.GetBytes(http.RequestBody ?? string.Empty);

                var    httpverb  = Request.Method.ToString();
                var    entireUrl = (http.Host ?? http.Url.Host) + http.Url.PathAndQuery;
                string bodyHashString;

                using (var bodyHmac = new HMACSHA256(secretBytes))
                {
                    bodyHashString = Convert.ToBase64String(bodyHmac.ComputeHash(bodyBytes));
                }

                var nonce              = Guid.NewGuid().ToString();
                var unixTimeStamp      = Convert.ToInt32((DateTime.UtcNow - Epoch).TotalSeconds).ToStringConfigStyle();
                var headersInSignature = string.Empty;

                // Intend to use SHA256 both for body and signature hashes
                var hashMethods = "SHA256/SHA256";

                /// Creating the signature
                var signaturePlainText = new StringBuilder();

                signaturePlainText.Append(apiKey);
                signaturePlainText.Append(installationId);
                signaturePlainText.Append(httpverb);
                signaturePlainText.Append(entireUrl);
                signaturePlainText.Append(bodyHashString);
                signaturePlainText.Append(nonce);
                signaturePlainText.Append(unixTimeStamp);
                signaturePlainText.Append(headersInSignature);

                string signature;

                using (var signatureHmac = new HMACSHA256(secretBytes))
                {
                    signature = Convert.ToBase64String(
                        signatureHmac.ComputeHash(
                            http.Encoding.GetBytes(
                                signaturePlainText.ToString()
                                )
                            )
                        );
                }

                http.Headers.Add(
                    new HttpHeader(
                        "Authorization",
                        $"hmacauth {hashMethods}:{apiKey}:{installationId}:{signature}:{nonce}:{unixTimeStamp}"
                        )
                    );
            }
Exemple #37
0
        public BinanceDexApi(IHttp http, string baseUrl, string hrp, IRateLimiter rateLimiter)
        {
            Throw.IfNull(http, nameof(http));
            Throw.IfNullOrWhiteSpace(baseUrl, nameof(baseUrl));

            this.http    = http;
            this.baseUrl = baseUrl;
            this.Hrp     = hrp;
            this.rateLimiterImplementation = rateLimiter;
        }
        public void OnExecuting(IHttp http, IRequest request)
        {
            foreach (var header in http.GetHeaders(request.Method))
            {
                if (request.Contains(header))
                {
                    continue;
                }

                request.Add(header);
            }
        }
        /// <summary>
        /// Cache reads in a dictionary.
        /// </summary>
        /// <param name="requestUri">The Uri of the request.</param>
        /// <param name="getResponse">A function to actually call the server.</param>
        /// <returns>A response possibly cached.</returns>
        public override async Task<HttpContent> Read(Uri requestUri, IHttp http)
        {
            Tuple<DateTime, HttpContent> cachedValue;
            //look for existing item and check if not expired
            if (memCache.TryGetValue(requestUri, out cachedValue))
            {
                if (DateTime.UtcNow < cachedValue.Item1 + this.expirationTime)
                {
                    return cachedValue.Item2;
                }
            }

            //return and cache a fresh response
            HttpContent content = await base.Read(requestUri, http);
            memCache[requestUri] = new Tuple<DateTime, HttpContent>(DateTime.UtcNow, content);
            return content;
        }
        public async Task<JObject> DownloadChanges(Uri requestUri, IHttp http)
        {
            //get latest known timestamp for a reqeust
            string timestamp = await GetLastTimestampForRequest(requestUri);
            Uri stampedRequestUri;
            if (timestamp != null)
            {
                stampedRequestUri = new Uri(string.Format("{0}&version={1}", requestUri.OriginalString, Uri.EscapeDataString(timestamp)));
            }
            else
            {
                stampedRequestUri = requestUri;
            }

            //send the timestamped request
            http.OriginalRequest.RequestUri = stampedRequestUri;
            HttpResponseMessage response = await http.SendOriginalAsync();
            JObject json = await ResponseHelper.GetResponseAsJObject(response.Content);
            
            // get the tablename out of the uri
            string tableName = UriHelper.GetTableNameFromUri(requestUri);

            using (await this.storage.Open())
            {
                JToken newtimestamp;
                if (json.TryGetValue("__version", out newtimestamp))
                {
                    await this.SetLastTimestampForRequest(requestUri, newtimestamp.ToString());
                }

                await this.storage.StoreData(tableName, ResponseHelper.GetResultsJArrayFromJson(json));
                await this.storage.RemoveStoredData(tableName, ResponseHelper.GetDeletedJArrayFromJson(json));
            }

            return json;
        }
Exemple #41
0
 public CssResponse(IHttp http, bool isCompressionHandledByResponse)
 {
     Http = http;
     IsCompressionHandledByResponse = isCompressionHandledByResponse;
 }
Exemple #42
0
 public CssResponse(IHttp http)
     : base(http)
 {
 }
 public CachedCssResponse(IHttp http, bool isCompressionHandledByResponse, int httpExpiryInMinutes, IClock clock) 
     : base(http, isCompressionHandledByResponse)
 {
     _httpExpiryInMinutes = httpExpiryInMinutes;
     _clock = clock;
 }
 public AzureManagementLowLevelApi(IHttp http)
 {
     _http = http;
 }
        public override async Task<HttpContent> Delete(Uri requestUri, IHttp http)
        {
            Contract.Requires<ArgumentNullException>(requestUri != null, "requestUri");

            string id = UriHelper.GetIdFromUri(requestUri);
            if (string.IsNullOrEmpty(id))
            {
                throw new InvalidOperationException("Can't retrieve id from Uri.");
            }

            string tableName = UriHelper.GetTableNameFromUri(requestUri);
            IDictionary<string, string> parameters = UriHelper.GetQueryParameters(requestUri);

            if (await network.IsConnectedToInternet())
            {
                Uri tableUri = UriHelper.GetCleanTableUri(requestUri);
                //make sure we synchronize
                await this.synchronizer.UploadChanges(tableUri, http);
                JArray arr = new JArray();
                using (await this.storage.Open())
                {
                    arr = await this.storage.GetStoredData(tableName, new StaticQueryOptions() { Filter = new FilterQuery(string.Format("id eq '{0}'", Uri.EscapeDataString(id.Replace("'", "''")))) });
                }
                if (arr.Count > 0)
                {
                    JObject json = await this.synchronizer.UploadDelete(arr.First as JObject, tableUri, http, parameters);
                }
            }
            else
            {
                this.synchronizer.NotifyOfUnsynchronizedChange();

                //TODO: if local item is not known by server
                // we can just remove it locally and the server will never know about its existence
                using (await this.storage.Open())
                {
                    JArray arr = await this.storage.GetStoredData(tableName, new StaticQueryOptions() { Filter = new FilterQuery(string.Format("id eq '{0}'", Uri.EscapeDataString(id.Replace("'", "''")))) });
                    if (arr.Count > 0 && arr.First.Value<int>("status") != (int)ItemStatus.Inserted)
                    {
                        //update status of current item 
                        JArray deleted = new JArray();
                        deleted.Add(new JObject() { { "id", new JValue(id) }, { "status", new JValue((int)ItemStatus.Deleted) } });

                        await this.storage.UpdateData(tableName, deleted);
                    }
                    else
                    {
                        await this.storage.RemoveStoredData(tableName, new string[] { id });
                    }                    
                }
            }            

            Debug.WriteLine("Returning response:    {0}", string.Empty);

            return new StringContent(string.Empty);
        }
 public HttpContextLogger(IHttp http,LogLevel level)
     : base(level)
 {
     Http = http;
 }
Exemple #47
0
 public HttpCache(IHttp http, IPathResolver pathResolver)
 {
     _http = http;
     PathResolver = pathResolver;
 }
Exemple #48
0
		private void ConfigureHttp(IRestRequest request, IHttp http)
		{
            //TODO: Add support for Cookies
			//http.CookieContainer = CookieContainer;

			// move RestClient.DefaultParameters into Request.Parameters
			foreach(var p in DefaultParameters)
			{
				if(request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type))
				{
					continue;
				}

				request.AddParameter(p);
			}

			http.Url = BuildUri(request);

			var userAgent = UserAgent ?? http.UserAgent;
			http.UserAgent = userAgent.HasValue() ? userAgent : "RestSharp " + version.ToString();

			var timeout = request.Timeout > 0 ? request.Timeout : Timeout;
			if (timeout > 0)
			{
				http.Timeout = timeout;
			}

            //TODO: Ad support for Credentials
            //if(request.Credentials != null)
            //{
            //    http.Credentials = request.Credentials;
            //}

			var headers = from p in request.Parameters
						  where p.Type == ParameterType.HttpHeader
						  select new HttpHeader
						  {
							  Name = p.Name,
							  Value = p.Value.ToString()
						  };

			foreach(var header in headers)
			{
				http.Headers.Add(header);
			}

			var cookies = from p in request.Parameters
						  where p.Type == ParameterType.Cookie
						  select new HttpCookie
						  {
							  Name = p.Name,
							  Value = p.Value.ToString()
						  };

			foreach(var cookie in cookies)
			{
				http.Cookies.Add(cookie);
			}

			var @params = from p in request.Parameters
						  where p.Type == ParameterType.GetOrPost
								&& p.Value != null
						  select new HttpParameter
						  {
							  Name = p.Name,
							  Value = p.Value.ToString()
						  };

			foreach(var parameter in @params)
			{
				http.Parameters.Add(parameter);
			}

            foreach (var file in request.Files)
            {
                http.Files.Add(new HttpFile { Name = file.Name, ContentType = file.ContentType, Content = file.Content, FileName = file.FileName, ContentLength = file.ContentLength });
            }

			var body = (from p in request.Parameters
						where p.Type == ParameterType.RequestBody
						select p).FirstOrDefault();

			if(body != null)
			{
				http.RequestBody = body.Value.ToString();
				http.RequestContentType = body.Name;
			}
		}
Exemple #49
0
 public AspCache(IHttp http, IFileResolver fileResolver)
 {
     _http = http;
     _fileResolver = fileResolver;
 }
 public QueryStringParameterSource(IHttp http)
 {
     this.http = http;
 }
 public CachedCssResponse(IHttp http, bool isCompressionHandledByResponse, int httpExpiryInMinutes) :
     this(http, isCompressionHandledByResponse, httpExpiryInMinutes, new Clock())
 {
 }
        private const int CacheAgeMinutes = 10080; //7 days

        #endregion Fields

        #region Constructors

        public CachedCssResponse(IHttp http, bool isCompressionHandledByResponse)
            : base(http, isCompressionHandledByResponse)
        {
        }
        public async Task<JObject> UploadInsert(JObject item, Uri tableUri, IHttp http, IDictionary<string, string> parameters = null)
        {
            //remove systemproperties
            JObject insertItem = item.Remove(prop => prop.Name.StartsWith("__"));

            string paramString = TimestampSynchronizer.GetQueryString(parameters);

            Uri insertUri = new Uri(string.Format("{0}{1}",
                tableUri.OriginalString,
                paramString != null ? "?" + paramString : string.Empty));

            HttpRequestMessage req = http.CreateRequest(HttpMethod.Post, insertUri);
            req.Content = new StringContent(insertItem.ToString(Formatting.None), Encoding.UTF8, "application/json");

            JObject response = await http.GetJsonAsync(req);
            JArray results = ResponseHelper.GetResultsJArrayFromJson(response);
            IEnumerable<string> deleted = ResponseHelper.GetDeletedJArrayFromJson(response);

            string tableName = UriHelper.GetTableNameFromUri(tableUri);

            using (await this.storage.Open())
            {
                await this.storage.StoreData(tableName, results);
                await this.storage.RemoveStoredData(tableName, deleted);
            }

            return response;
        }
 public AspServerPathResolver(IHttp http)
 {
     _http = http;
 }
        public async Task<JObject> UploadUpdate(JObject item, Uri tableUri, IHttp http, IDictionary<string, string> parameters = null)
        {
            string version = null;
            JToken versionToken = item["__version"];
            if(versionToken != null)
            {
                version = versionToken.ToString();
            }
            else if(http.OriginalRequest != null)
            {
                EntityTagHeaderValue tag = http.OriginalRequest.Headers.IfMatch.FirstOrDefault();
                if (tag != null)
                {
                    //trim "
                    version = tag.Tag.Trim(new char[] { '"' });
                }
            }

            if(version == null)
            {
                throw new InvalidOperationException("Cannot update value without __version.");
            }

            //remove systemproperties
            JObject insertItem = item.Remove(prop => prop.Name.StartsWith("__"));

            string paramString = TimestampSynchronizer.GetQueryString(parameters);

            Uri updateUri = new Uri(string.Format("{0}/{1}{2}",
                tableUri.OriginalString,
                Uri.EscapeDataString(item["id"].ToString()),
                paramString != null ? "?" + paramString : string.Empty));

            HttpRequestMessage req = http.CreateRequest(new HttpMethod("PATCH"), updateUri, new Dictionary<string, string>() { { "If-Match", string.Format("\"{0}\"", version) } });
            req.Content = new StringContent(insertItem.ToString(Formatting.None), Encoding.UTF8, "application/json");

            try
            {
                JObject response = await http.GetJsonAsync(req);
                JArray results = ResponseHelper.GetResultsJArrayFromJson(response);
                IEnumerable<string> deleted = ResponseHelper.GetDeletedJArrayFromJson(response);

                string tableName = UriHelper.GetTableNameFromUri(tableUri);

                using (await this.storage.Open())
                {
                    await this.storage.StoreData(tableName, results);
                    await this.storage.RemoveStoredData(tableName, deleted);
                }

                return response;
            }
            catch(HttpStatusCodeException e)
            {
                if(e.StatusCode == HttpStatusCode.Conflict)
                {
                    Conflict c = JsonConvert.DeserializeObject<Conflict>(e.Message);
                    if(c != null)
                    {
                        this.OnConflict(c);
                        return ResponseHelper.CreateSyncResponseWithItems(c.CurrentItem, null);
                    }
                }
                return ResponseHelper.CreateSyncResponseWithItems(null, null);
            }
        }
        public override async Task<HttpContent> Read(Uri requestUri, IHttp http)
        {
            Contract.Requires<ArgumentNullException>(requestUri != null, "requestUri");

            //this will be our return object
            JObject json = new JObject();

            // get the tablename out of the uri
            string tableName = UriHelper.GetTableNameFromUri(requestUri);
            //LookupAsync adds id
            string id = UriHelper.GetIdFromUri(requestUri);
            if (string.IsNullOrEmpty(id))
            {
                //TODO
            }

            if (await network.IsConnectedToInternet())
            {
                //upload changes
                await this.synchronizer.UploadChanges(UriHelper.GetCleanTableUri(requestUri), http);
                //download changes
                JToken count;
                JObject obj = await this.synchronizer.DownloadChanges(requestUri, http);
                if(obj.TryGetValue("count", out count))
                {
                    json["count"] = count;
                }
                else
                {
                    json["count"] = -1;
                }
            }
            else
            {
                json["count"] = -1;
            }

            using (await this.storage.Open())
            {
                //parse uri into separate query options
                IQueryOptions uriQueryOptions = new UriQueryOptions(requestUri);
                IQueryOptions queryOptions = new StaticQueryOptions()
                {
                    Filter = uriQueryOptions.Filter != null ?
                        new FilterQuery(string.Format("{0} and status ne {1}", uriQueryOptions.Filter.RawValue, (int)ItemStatus.Deleted))
                        : new FilterQuery(string.Format("status ne {0}", (int)ItemStatus.Deleted)),
                    InlineCount = uriQueryOptions.InlineCount,
                    OrderBy = uriQueryOptions.OrderBy,
                    Skip = uriQueryOptions.Skip,
                    Top = uriQueryOptions.Top,
                };

                //send same query to local data store with the addition of
                JArray data = null;
                try
                {
                    data = await this.storage.GetStoredData(tableName, queryOptions);
                }
                // catch error because we don't want to throw on missing columns when read
                catch (Exception)
                {
                    data = new JArray();
                }

                //set the results
                json["results"] = data;
            }

            //remove time stamp values
            json.Remove("__version");
            //remove deleted values
            json.Remove("deleted");

            Debug.WriteLine("Returning response:    {0}", json.ToString());

            //this json should be in the format that the MobileServiceClient expects
            return new StringContent(json.ToString());
        }
 public void Setup()
 {
     this.http = new Http(req => Task.FromResult(response));
     this.http.OriginalRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");
     this.http.OriginalRequest.Headers.Add("X-ZUMO", "TEST");
 }
        private const int CacheAgeMinutes = 10080; //7 days

        #endregion Fields

        #region Constructors

        public CachedCssResponse(IHttp http)
        {
            Http = http;
        }
        /// <summary>
        /// Uploads changes using the specified table URI. This Uri should end with /table/tablename
        /// </summary>
        /// <param name="tableUri">The table URI.</param>
        /// <param name="getResponse">The get response.</param>
        /// <returns></returns>
        public async Task UploadChanges(Uri tableUri, IHttp http)
        {
            Contract.Requires<ArgumentNullException>(tableUri != null, "tableUri");
            Contract.Requires<ArgumentNullException>(http != null, "http");

            // return is there is nothing to sync
            if (!hasLocalChanges)
            {
                return;
            }

            string tableName = UriHelper.GetTableNameFromUri(tableUri);

            JArray localChanges = new JArray();
            // all communication with the database should be on the same thread
            using (await this.storage.Open())
            {
                //sent all local changes 
                localChanges = await this.storage.GetStoredData(tableName, new StaticQueryOptions() { Filter = new FilterQuery("status ne 0") });
            }
            foreach (JObject item in localChanges)
            {
                try
                {
                    JToken status;
                    if (item.TryGetValue("status", out status))
                    {
                        ItemStatus itemStatus = (ItemStatus)(int)status;
                        item.Remove("status");
                        //preform calls based on status: insert, change, delete 
                        switch (itemStatus)
                        {
                            case ItemStatus.Inserted:
                                await this.UploadInsert(item, tableUri, http);
                                break;
                            case ItemStatus.Changed:
                                await this.UploadUpdate(item, tableUri, http);
                                break;
                            case ItemStatus.Deleted:
                                await this.UploadDelete(item, tableUri, http);
                                break;
                        };
                    }
                }
                catch { }
            }

            //we have synchronized everything
            this.hasLocalChanges = false;
        }
        public async Task<JObject> UploadDelete(JObject item, Uri tableUri, IHttp http, IDictionary<string, string> parameters = null)
        {
            string paramString = TimestampSynchronizer.GetQueryString(parameters);
            Uri deleteUri = new Uri(string.Format("{0}/{1}?version={2}{3}", 
                tableUri.OriginalString, 
                Uri.EscapeDataString(item["id"].ToString()), 
                Uri.EscapeDataString(item["__version"].ToString()),
                paramString != null ? "&" + paramString : string.Empty));

            HttpRequestMessage req = http.CreateRequest(HttpMethod.Delete, deleteUri);

            try
            {
                JObject response = await http.GetJsonAsync(req);
                JArray results = ResponseHelper.GetResultsJArrayFromJson(response);
                IEnumerable<string> deleted = ResponseHelper.GetDeletedJArrayFromJson(response);

                string tableName = UriHelper.GetTableNameFromUri(tableUri);

                using (await this.storage.Open())
                {
                    await this.storage.StoreData(tableName, results);
                    await this.storage.RemoveStoredData(tableName, deleted);
                }

                return response;
            }
            catch (HttpStatusCodeException e)
            {
                if (e.StatusCode == HttpStatusCode.Conflict)
                {
                    Conflict c = JsonConvert.DeserializeObject<Conflict>(e.Message);
                    if (c != null)
                    {
                        this.OnConflict(c);
                        return ResponseHelper.CreateSyncResponseWithItems(null, c.CurrentItem["id"]);
                    }
                }
                return ResponseHelper.CreateSyncResponseWithItems(null, null);
            }
        }