Exemplo n.º 1
0
 public HttpConnectionResponse(Uri url, IHttpConnection connection, IHttpReader reader, Stream stream, ILookup <string, string> headers, IHttpStatus status)
 {
     if ((Uri)null == url)
     {
         throw new ArgumentNullException("url");
     }
     if (null == stream)
     {
         throw new ArgumentNullException("stream");
     }
     if (null == headers)
     {
         throw new ArgumentNullException("headers");
     }
     if (null == status)
     {
         throw new ArgumentNullException("status");
     }
     this._url        = url;
     this._reader     = reader;
     this._stream     = stream;
     this._headers    = headers;
     this._status     = status;
     this._connection = connection;
 }
Exemplo n.º 2
0
        public void Dispose()
        {
            Stream stream = this._stream;

            if (null != stream)
            {
                this._stream = (Stream)null;
                stream.Dispose();
            }
            IHttpReader httpReader = this._reader;

            if (null != httpReader)
            {
                this._reader = (IHttpReader)null;
                httpReader.Dispose();
            }
            IHttpConnection httpConnection = this._connection;

            if (null == httpConnection)
            {
                return;
            }
            this._connection = httpConnection;
            httpConnection.Dispose();
        }
Exemplo n.º 3
0
 public HttpDataProvider(IHttpConnection connection, IHttpDataRequestFactory requestFactory, IStringDataConverter <T> stringConverter, string sessionToken)
 {
     this.connection     = connection;
     this.requestFactory = requestFactory;
     this.requestFactory.SetDefaultUrlParameters("sessionToken", sessionToken);
     this.stringConverter = stringConverter;
 }
Exemplo n.º 4
0
 public UserService(
     IHttpConnection httpConnection,
     IAuthenticationServiceLS authenticationServiceLS)
     : base(httpConnection)
 {
     this.authenticationServiceLS = authenticationServiceLS;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Handles incoming requests.
        /// </summary>
        /// <param name="ctx">The HttpListenerContext returned by the HttpListener</param>
        public void HandleConnection(IHttpConnection con)
        {
            try {
                StreamReader msg = con.GetClientData();

                try{
                    RPCall   clientCall = Deserialize(msg);
                    ICommand requestedCommand;
                    if (!CommandDictionary.Instance.GetCommand(clientCall.procedureName, out requestedCommand))
                    {
                        // Wahrscheinlich besser eine eigene Exception zu schreiben und 404 zurückgeben.
                        throw new InvalidOperationException();
                    }
                    RPResult result = requestedCommand.Execute(clientCall);
                    byte[]   buffer = Encoding.UTF8.GetBytes(Serialize(result));
                    con.SendReponseData(buffer);
                } catch (Exception ex) {
                    // Deserialization did not work aborting.
                    if (ex is InvalidOperationException || ex is ArgumentNullException)
                    {
                        Console.WriteLine(ex.Message);
                        con.SendErrorCode(500);
                        return;
                    }
                    throw;
                }
            } catch (HttpListenerException ex) {
                // Can't really do anything at this point.
                Console.WriteLine(ex.Message);
                return;
            }
        }
Exemplo n.º 6
0
 public void TryPost(IHttpConnection conn, object content)
 {
     using (HttpClient client = new HttpClient())
     {
         HttpResponseMessage response = client.PostAsJsonAsync(conn.ConnectionUrl, content).Result;
         response.EnsureSuccessStatusCode();
     }
 }
Exemplo n.º 7
0
 public void TryGet(IHttpConnection conn)
 {
     using (HttpClient client = new HttpClient())
     {
         HttpResponseMessage response = client.GetAsync(conn.ConnectionUrl).Result;
         response.EnsureSuccessStatusCode();
     }
 }
Exemplo n.º 8
0
 private static OAuth2Client CreateClient(
     IHttpConnection conn         = null,
     IGogoKitConfiguration config = null)
 {
     return(new OAuth2Client(
                conn ?? new Mock <IHttpConnection>(MockBehavior.Loose).Object,
                config ?? new GogoKitConfiguration("c", "s")));
 }
Exemplo n.º 9
0
 private static HalClient CreateClient(IHttpConnection conn        = null,
                                       IHalKitConfiguration config = null,
                                       ILinkResolver resolver      = null)
 {
     return(new HalClient(
                config ?? new HalKitConfiguration(new Uri("http://foo.api.io")),
                conn ?? new FakeHttpConnection(),
                resolver ?? new Mock <ILinkResolver>(MockBehavior.Loose).Object));
 }
Exemplo n.º 10
0
        public OAuth2Client(IHttpConnection connection, IGogoKitConfiguration configuration)
        {
            Requires.ArgumentNotNull(connection, nameof(connection));
            Requires.ArgumentNotNull(configuration, nameof(configuration));

            _connection    = connection;
            _configuration = configuration;
            _linkResolver  = new LinkResolver();
        }
Exemplo n.º 11
0
 /// <summary>
 /// 关闭到客户端的连接而不发送响应。
 /// </summary>
 public void Abort()
 {
     if (_connection != null)
     {
         _connection.Close();
         _connection = null;
     }
     Dispose(true);
 }
Exemplo n.º 12
0
        public void Initialize(string username, string password)
        {
            //for BASIC auth
            HttpConnectionBasic con = new HttpConnectionBasic();

            con.Initialize(username, password);
            httpCon        = con;
            connectionType = AuthMethod.Basic;
        }
Exemplo n.º 13
0
        public void Initialize(string accessToken, string accessTokenSecret, string username)
        {
            //for OAuth
            HttpConnectionOAuth con = new HttpConnectionOAuth();

            con.Initialize(ConsumerKey, ConsumerSecret, accessToken, accessTokenSecret, username, "screen_name");
            httpCon        = con;
            connectionType = AuthMethod.OAuth;
        }
Exemplo n.º 14
0
        public void SetUp()
        {
            _solrUrl        = ConfigurationManager.AppSettings["SOLR_URL"];
            _httpConnection = new HttpConnection(_solrUrl);

            _httpConnection.Post("search/update", XElement.Parse("<delete><query>*:*</query></delete>")).Dispose();
            _httpConnection.Post("search/update", XElement.Parse("<commit/>")).Dispose();
            _httpConnection.Post("search/update", XElement.Parse("<add><doc><field name=\"Guid\">" + ResultOne + "</field></doc><doc><field name=\"Guid\">" + ResultTwo + "</field></doc><doc><field name=\"Guid\">" + ResultThree + "</field></doc></add>")).Dispose();
            _httpConnection.Post("search/update", XElement.Parse("<commit softCommit=\"true\"/>")).Dispose();
        }
Exemplo n.º 15
0
 private static void AddEmptyCall(IHttpConnection httpConnection, int startOffset)
 {
     httpConnection
     .SearchAsync(
         Arg.Any <Uri>(),
         Arg.Is <Dictionary <string, object> >(o => (int)o["offset"] > startOffset))
     .Returns(Task.FromResult(new SearchResult
     {
         Results = Array.Empty <TestModel>()
     }));
 }
Exemplo n.º 16
0
 public BatchClient(
     IHttpConnection connection,
     IApiResponseFactory responseFactory,
     IJsonSerializer jsonSerializer,
     ILinkResolver linkResolver)
 {
     _responseFactory = responseFactory;
     _httpConnection  = connection;
     _configuration   = connection.Configuration;
     _jsonSerializer  = jsonSerializer;
     _linkResolver    = linkResolver;
 }
Exemplo n.º 17
0
 /// <summary>
 /// 创建HttpListenerResponse实例。
 /// </summary>
 /// <param name="request"></param>
 /// <param name="outputStream"></param>
 /// <param name="connection"></param>
 public HttpListenerResponse(IHttpListenerRequest request, System.IO.Stream outputStream, IHttpConnection connection)
 {
     _cookies         = new HttpCookieCollection();
     _headers         = new System.Collections.Specialized.NameValueCollection();
     _connection      = connection;
     _protocolVersion = request.ProtocolVersion;
     _contentEncoding = request.ContentEncoding;
     _outputStream    = outputStream;
     _output          = new HtmlWriter(this);
     _buffer          = true;
     Clear();
 }
Exemplo n.º 18
0
        void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (_disposed)
            {
                return;
            }
            if (_output != null)
            {
                if (_connection != null)
                {
                    HtmlWriter writer = _output as HtmlWriter;
                    if (writer != null)
                    {
                        writer.Flush(true);
                    }
                    else
                    {
                        _output.Flush();
                    }
                }
                _output.Dispose();
                _output = null;
            }
            if (_outputStream != null)
            {
                if (_connection != null)
                {
                    _outputStream.Flush();
                }
                _outputStream.Dispose();
                _outputStream = null;
            }
            if (_connection != null)
            {
                _connection.Close();
                _connection = null;
            }
            _contentEncoding   = null;
            _cookies           = null;
            _headers           = null;
            _statusDescription = null;
            _protocolVersion   = null;

            _disposed = true;
        }
Exemplo n.º 19
0
 private static void AddCall(IHttpConnection httpConnection, int offset, int count)
 {
     httpConnection
     .SearchAsync(
         Arg.Any <Uri>(),
         Arg.Is <Dictionary <string, object> >(o => o["offset"].Equals(offset)))
     .Returns(Task.FromResult(new SearchResult
     {
         Results = Enumerable.Range(offset + 1, count)
                   .Select(i => new TestModel {
             Id = i
         })
                   .ToArray()
     }));
 }
        internal virtual async Task <IHttpConnectionResponse> GetAsync(HttpConnectionRequest request, CancellationToken cancellationToken)
        {
            IHttpConnection         connection = this._httpConnectionFactory.CreateHttpConnection();
            Uri                     requestUrl = request.Url;
            Uri                     url        = requestUrl;
            int                     retry      = 0;
            IHttpConnectionResponse response;
            string                  location;

            do
            {
                await connection.ConnectAsync(request.Proxy ?? url, cancellationToken).ConfigureAwait(false);

                request.Url = url;
                response    = await connection.GetAsync(request, true, cancellationToken).ConfigureAwait(false);

                request.Url = requestUrl;
                IHttpStatus status = response.Status;
                if (HttpStatusCode.Moved == status.StatusCode || HttpStatusCode.Found == status.StatusCode)
                {
                    if (++retry < 8)
                    {
                        connection.Close();
                        location = Enumerable.FirstOrDefault <string>(response.Headers["Location"]);
                    }
                    else
                    {
                        goto label_5;
                    }
                }
                else
                {
                    goto label_3;
                }
            }while (Uri.TryCreate(request.Url, location, out url));
            goto label_7;
label_3:
            IHttpConnectionResponse connectionResponse = response;

            goto label_9;
label_5:
            connectionResponse = response;
            goto label_9;
label_7:
            connectionResponse = response;
label_9:
            return(connectionResponse);
        }
Exemplo n.º 21
0
 public T Get <T>(IHttpConnection conn)
 {
     using (HttpClient client = new HttpClient())
     {
         HttpResponseMessage response = client.GetAsync(conn.ConnectionUrl).Result;
         try
         {
             response.EnsureSuccessStatusCode();
             return(response.Content.ReadAsAsync <T>().Result);
         }
         catch
         {
             return(default(T));
         }
     }
 }
Exemplo n.º 22
0
 public T Put <T>(IHttpConnection conn, object content)
 {
     using (HttpClient client = new HttpClient())
     {
         try
         {
             HttpResponseMessage response = client.PutAsJsonAsync(conn.ConnectionUrl, content).Result;
             response.EnsureSuccessStatusCode();
             return(response.Content.ReadAsAsync <T>().Result);
         }
         catch
         {
             return(default(T));
         }
     }
 }
Exemplo n.º 23
0
        public HalClient(IHalKitConfiguration configuration,
                         IHttpConnection httpConnection,
                         ILinkResolver linkResolver)
        {
            Requires.ArgumentNotNull(httpConnection, nameof(httpConnection));
            Requires.ArgumentNotNull(configuration, nameof(configuration));
            Requires.ArgumentNotNull(linkResolver, nameof(linkResolver));
            if (configuration.RootEndpoint == null)
            {
                throw new ArgumentException($"{nameof(configuration)} must have a RootEndpoint");
            }

            HttpConnection = httpConnection;
            Configuration  = configuration;
            _linkResolver  = linkResolver;
        }
Exemplo n.º 24
0
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <param name="accessToken"> The access token. </param>
        /// <param name="accessTokenSecret"> The access token secret. </param>
        /// <param name="username"> The username. </param>
        /// <param name="userId"> The user id. </param>
        public void Initialize(string accessToken, string accessTokenSecret, string username, long userId)
        {
            var con = new HttpOAuthApiProxy();

            if (_tk != accessToken || _tks != accessTokenSecret || _un != username)
            {
                // 以前の認証状態よりひとつでも変化があったらhttpヘッダより読み取ったカウントは初期化
                _tk  = accessToken;
                _tks = accessTokenSecret;
                _un  = username;
            }

            con.Initialize(ConsumerKey, ConsumerSecret, accessToken, accessTokenSecret, username, userId, "screen_name", "user_id");
            _httpCon      = con;
            _requestToken = string.Empty;
        }
Exemplo n.º 25
0
        public ViagogoClient(
            ProductHeaderValue product,
            IGogoKitConfiguration configuration,
            IOAuth2TokenStore tokenStore,
            IJsonSerializer serializer,
            IHttpConnection oauthConnection,
            IHttpConnection apiConnection)
        {
            Requires.ArgumentNotNull(product, nameof(product));
            Requires.ArgumentNotNull(configuration, nameof(configuration));
            Requires.ArgumentNotNull(tokenStore, nameof(tokenStore));
            Requires.ArgumentNotNull(serializer, nameof(serializer));
            Requires.ArgumentNotNull(oauthConnection, nameof(oauthConnection));
            Requires.ArgumentNotNull(apiConnection, nameof(apiConnection));

            var halKitConfiguration = new HalKitConfiguration(configuration.ViagogoApiRootEndpoint)
            {
                CaptureSynchronizationContext = configuration.CaptureSynchronizationContext
            };

            Configuration = configuration;
            TokenStore    = tokenStore;
            Hypermedia    = new HalClient(halKitConfiguration, apiConnection);
            var linkFactory = new LinkFactory(configuration);

            OAuth2         = new OAuth2Client(oauthConnection, configuration);
            User           = new UserClient(Hypermedia);
            Search         = new SearchClient(Hypermedia);
            Addresses      = new AddressesClient(User, Hypermedia, linkFactory);
            Purchases      = new PurchasesClient(User, Hypermedia, linkFactory);
            Sales          = new SalesClient(Hypermedia, linkFactory);
            Shipments      = new ShipmentsClient(Hypermedia, linkFactory);
            PaymentMethods = new PaymentMethodsClient(User, Hypermedia, linkFactory);
            Countries      = new CountriesClient(Hypermedia, linkFactory);
            Currencies     = new CurrenciesClient(Hypermedia, linkFactory);
            Categories     = new CategoriesClient(Hypermedia, linkFactory);
            Events         = new EventsClient(Hypermedia);
            Listings       = new ListingsClient(Hypermedia);
            Venues         = new VenuesClient(Hypermedia);
            SellerListings = new SellerListingsClient(Hypermedia, linkFactory);
            Webhooks       = new WebhooksClient(Hypermedia, linkFactory);

            BatchClient = new BatchClient(apiConnection,
                                          new ApiResponseFactory(serializer, halKitConfiguration),
                                          serializer,
                                          new LinkResolver());
        }
Exemplo n.º 26
0
        public HttpConnectionResponse(Uri url, IHttpConnection connection, IHttpReader reader, Stream stream, ILookup<string, string> headers, IHttpStatus status)
        {
            if (null == url)
                throw new ArgumentNullException(nameof(url));
            if (null == stream)
                throw new ArgumentNullException(nameof(stream));
            if (null == headers)
                throw new ArgumentNullException(nameof(headers));
            if (null == status)
                throw new ArgumentNullException(nameof(status));

            ResponseUri = url;
            _reader = reader;
            ContentReadStream = stream;
            Headers = headers;
            Status = status;
            _connection = connection;
        }
Exemplo n.º 27
0
 public void Initialize(string accessToken,
                                 string accessTokenSecret,
                                 string username,
                                 long userId)
 {
     //for OAuth
     HttpOAuthApiProxy con = new HttpOAuthApiProxy();
     if (tk != accessToken || tks != accessTokenSecret ||
             un != username || connectionType != AuthMethod.OAuth)
     {
         // 以前の認証状態よりひとつでも変化があったらhttpヘッダより読み取ったカウントは初期化
         tk = accessToken;
         tks = accessTokenSecret;
         un = username;
     }
     con.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret, accessToken, accessTokenSecret, username, userId, "screen_name", "user_id");
     httpCon = con;
     connectionType = AuthMethod.OAuth;
     requestToken = "";
 }
Exemplo n.º 28
0
        public PaynovaClient(IHttpConnection connection)
        {
            Ensure.That(connection, "connection").IsNotNull();

            Connection = connection;
            Serializer = new DefaultJsonSerializer();

            CreateOrderHttpRequestFactory               = new CreateOrderHttpRequestFactory(Runtime.Instance, Serializer);
            AuthorizeInvoiceHttpRequestFactory          = new AuthorizeInvoiceHttpRequestFactory(Runtime.Instance, Serializer);
            InitializePaymentHttpRequestFactory         = new InitializePaymentHttpRequestFactory(Runtime.Instance, Serializer);
            RefundPaymentHttpRequestFactory             = new RefundPaymentHttpRequestFactory(Runtime.Instance, Serializer);
            FinalizeAuthorizationHttpRequestFactory     = new FinalizeAuthorizationHttpRequestFactory(Runtime.Instance, Serializer);
            AnnulAuthorizationHttpRequestFactory        = new AnnulAuthorizationHttpRequestFactory(Runtime.Instance, Serializer);
            GetAddressesHttpRequestFactory              = new GetAddressesHttpRequestFactory(Runtime.Instance, Serializer);
            GetCustomerProfileHttpRequestFactory        = new GetCustomerProfileHttpRequestFactory(Runtime.Instance, Serializer);
            GetPaymentOptionsHttpRequestFactory         = new GetPaymentOptionsHttpRequestFactory(Runtime.Instance, Serializer);
            RemoveCustomerProfileCardHttpRequestFactory = new RemoveCustomerProfileCardHttpRequestFactory(Runtime.Instance, Serializer);
            RemoveCustomerProfileHttpRequestFactory     = new RemoveCustomerProfileHttpRequestFactory(Runtime.Instance, Serializer);

            ResponseFactory = new GenericResponseFactory(Serializer);
        }
Exemplo n.º 29
0
        public void Initialize(string accessToken,
                               string accessTokenSecret,
                               string username,
                               long userId)
        {
            //for OAuth
            HttpOAuthApiProxy con = new HttpOAuthApiProxy();

            if (tk != accessToken || tks != accessTokenSecret ||
                un != username || connectionType != AuthMethod.OAuth)
            {
                // 以前の認証状態よりひとつでも変化があったらhttpヘッダより読み取ったカウントは初期化
                tk  = accessToken;
                tks = accessTokenSecret;
                un  = username;
            }
            con.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret, accessToken, accessTokenSecret, username, userId, "screen_name", "user_id");
            httpCon        = con;
            connectionType = AuthMethod.OAuth;
            requestToken   = "";
        }
Exemplo n.º 30
0
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <param name="accessToken"> The access token. </param>
        /// <param name="accessTokenSecret"> The access token secret. </param>
        /// <param name="username"> The username. </param>
        /// <param name="userId"> The user id. </param>
        public void Initialize(string accessToken, string accessTokenSecret, string username, long userId)
        {
            var con = new HttpOAuthApiProxy();
            if (_tk != accessToken || _tks != accessTokenSecret || _un != username)
            {
                // 以前の認証状態よりひとつでも変化があったらhttpヘッダより読み取ったカウントは初期化
                _tk = accessToken;
                _tks = accessTokenSecret;
                _un = username;
            }

            con.Initialize(ConsumerKey, ConsumerSecret, accessToken, accessTokenSecret, username, userId, "screen_name", "user_id");
            _httpCon = con;
            _requestToken = string.Empty;
        }
Exemplo n.º 31
0
 public void Initialize(string accessToken, string accessTokenSecret, string username)
 {
     //for OAuth
     HttpConnectionOAuth con = new HttpConnectionOAuth();
     con.Initialize(ConsumerKey, ConsumerSecret, accessToken, accessTokenSecret, username, "screen_name");
     httpCon = con;
     connectionType = AuthMethod.OAuth;
 }
Exemplo n.º 32
0
 public BasketsClient(IHttpConnection httpConnection)
     : base(httpConnection.BaseAddress, httpConnection)
 {
 }
Exemplo n.º 33
0
        /**
         *
         */
        private void SetAuthInfo(string access_token, string access_token_secret, string user_name, long user_id)
        {
            OAuthHttpConnection connection = null;

            //static string _cache_key = string.Empty;
            //static string _cache_key_secret = string.Empty;
            //static string _cache_user_name = string.Empty;

            //if ( _cache_key != access_token || _cache_key_secret != access_token_secret || _cache_user_name == user_name ) {
            //    _cache_key = access_token;
            //    _cache_key_secret = access_token_secret;
            //    _cache_user_name = user_name;
            //}
            connection = this.CreateHttpConnection( access_token, access_token_secret, user_name, user_id );

            this.http_connection_ = connection;
            this.connection_type_ = AuthMethod.OAuth;
            this.request_token_ = string.Empty;
        }
Exemplo n.º 34
0
 public LocationWeatherService(IHttpConnection connection, IJsonConverter jsonConverter)
 {
     _connection    = connection;
     _jsonConverter = jsonConverter;
 }
Exemplo n.º 35
0
        public void Dispose()
        {
            var stream = ContentReadStream;

            if (null != stream)
            {
                ContentReadStream = null;

                stream.Dispose();
            }

            var reader = _reader;

            if (null != reader)
            {
                _reader = null;

                reader.Dispose();
            }

            var connection = _connection;

            if (null != connection)
            {
                _connection = connection;

                connection.Dispose();
            }
        }
 public LocationWeatherServiceTest()
 {
     _httpConnectionMock = Substitute.For <IHttpConnection>();
     _sut = new LocationWeatherService(_httpConnectionMock);
 }
Exemplo n.º 37
0
 public SolrCore(IHttpConnection httpConnection, string core)
 {
     _httpConnection = httpConnection;
     Core = core;
 }
Exemplo n.º 38
0
 public ApiConnection(IHttpConnection connection)
 {
     Connection = connection;
 }
Exemplo n.º 39
0
 public void Initialize(string username, string password)
 {
     //for BASIC auth
     HttpConnectionBasic con = new HttpConnectionBasic();
     con.Initialize(username, password);
     httpCon = con;
     connectionType = AuthMethod.Basic;
 }