Example #1
0
 public ApiException(HttpAction action, int code, string message, string rawError)
 {
     Action   = action.ToString();
     Code     = code;
     Message  = message;
     RawError = rawError;
 }
Example #2
0
 public static IHttpRequestModel CreateSimpleRequest(HttpAction method, Uri rootUri)
 {
     return(new HttpRequestModel(method, rootUri)
     {
         UseMultipart = false
     });
 }
Example #3
0
        public HttpRequest(HttpAction httpAction, HttpWebRequest request, IDispatcher dispatcher)
        {
            _request    = request;
            _dispatcher = dispatcher;

            SetMethod(httpAction);
        }
Example #4
0
 public OAuthConsumer()
 {
     AuthProperties = new OAuthProperties();
       AuthRequestMethod = RequestMethod.Header;
       HttpMethod = HttpAction.GET;
       _dispatcher = new Dispatcher();
 }
 public BasicAPIhandler(IHttpClient httpClient, ISerializer serializer, String uri, HttpAction method, TRequest request = default(TRequest))
 {
     this.httpClient = httpClient;
     this.serializer = serializer;
     this.uri        = uri;
     this.method     = method;
     this.request    = request;
 }
Example #6
0
 public static IHttpRequestModel CreateMultipartRequest(HttpAction method, Uri rootUri, string boundary = null)
 {
     return(new HttpRequestModel(method, rootUri)
     {
         UseMultipart = true,
         Body = string.IsNullOrWhiteSpace(boundary)
             ? new MultipartFormDataContent()
             : new MultipartFormDataContent(boundary)
     });
 }
        /// <summary>
        /// 获取服务行为的特性过滤器
        /// 并进行属性注入
        /// </summary>
        /// <param name="fastAction">服务行为</param>
        /// <returns></returns>
        public override IEnumerable <IFilter> GetActionFilters(HttpAction fastAction)
        {
            var filters       = base.GetActionFilters(fastAction);
            var lifetimeScope = this.dependencyResolver.CurrentLifetimeScope;

            if (lifetimeScope == null)
            {
                return(filters);
            }
            return(filters.Select(filter => lifetimeScope.InjectProperties(filter)));
        }
Example #8
0
        protected static HtmlTag HttpActionRender(TypedElement actionElement, RenderContext context)
        {
            HttpAction action = (HttpAction)actionElement;

            if (context.Config.SupportsInteractivity)
            {
                var uiButton = new LinkTag(action.Title, null, $"ac-{action.Type.Replace(".", "").ToLower()}", "ac-action");
                return(uiButton);
            }
            return(null);
        }
Example #9
0
        public void TestMethod1()
        {
            var action = new HttpAction()
            {
                Url    = "http://news.baidu.com/ent",
                Method = "GET"
            };

            var response = action.Run(null);

            Assert.IsNotNull(response);
        }
        /// <summary>
        /// Converts a HttpAction value to a corresponding string value
        /// </summary>
        /// <param name="enumValue">The HttpAction value to convert</param>
        /// <returns>The representative string value</returns>
        public static string ToValue(HttpAction enumValue)
        {
            switch (enumValue)
            {
            //only valid enum elements can be used
            //this is necessary to avoid errors
            case HttpAction.GET:
            case HttpAction.POST:
                return(stringValues[(int)enumValue]);

            //an invalid enum value was requested
            default:
                return(null);
            }
        }
Example #11
0
 private void QueueRequest(Uri uri, HttpAction httpAction, HttpCompletionOption httpCompletionOption, Action <HttpResponseMessage> responseCallback)
 {
     QueueWorkItem((t) =>
     {
         try
         {
             HttpWebRequest request = CreateRequest(uri);
             new HttpRequest(httpAction, request, _dispatcher).Execute(httpCompletionOption, responseCallback, DownloadBlockSize);
             RemoveRequest(request);
         }
         catch (Exception e)
         {
             RaiseErrorResponse(responseCallback, e);
         }
     });
 }
Example #12
0
        public async Task CreateProductAsyncRaw()
        {
            IntegrationsWebAppClient client = new IntegrationsWebAppClient("api.eovportal-softtek.com/api/V2", "AllPoints");
            var action = new PostProductRequest {
                Name = "Product Name", Identifier = "MyExternalId1234", ExternalIdentifier = "MyExternalId1234"
            };
            var revert = new DeleteProductRequest {
                ExternalIdentifier = action.Identifier
            };
            var test = new HttpAction <PostProductRequest, GetProductRequest, DeleteProductRequest, ProductResponse>(client.Products.GetByExternalIdentifier, client.Products.Create, client.Products.Remove);
            await test.BeginExecute(action, new GetProductRequest { ExternalIdentifier = action.Identifier });

            await test.BeginRevert(revert, new GetProductRequest { ExternalIdentifier = action.Identifier });

            var wasReverted = test.Confirm();
        }
Example #13
0
        protected IActionResult HandleException(Exception e, HttpAction action, string message)
        {
            ApiException error;

            //Object is already present in database, in a Post call. Use put instead
            if (e is ObjectExistsException)
            {
                error = new ApiException(action, ApiException.ERROR_CODE_OBJECT_EXISTS, e.Message + ApiException.ERROR_MSG_OBJECT_EXISTS);
                return(BadRequest(error));
            }
            /*Id and object.id in put mismatch*/
            else if (e is IdMismatchException)
            {
                error = new ApiException(action, ApiException.ERROR_CODE_ID_MISMATCH, e.Message + ApiException.ERROR_MSG_ID_MISMATCH);
                LogException(StatusCodes.Status400BadRequest, e, error);
                return(BadRequest(error));
            }
            else if (e is ObjectNotFoundException)
            {
                error = new ApiException(action, ApiException.ERROR_CODE_NOT_FOUND, e.Message + ApiException.ERROR_MSG_NHIBERNATE);
                if (action == HttpAction.Get)
                {
                    LogException(StatusCodes.Status404NotFound, e, error);
                    return(NotFound(error));
                }
                else
                {
                    LogException(StatusCodes.Status400BadRequest, e, error);
                    return(BadRequest(error));
                }
            }
            else
            {
                if (e.InnerException != null)
                {
                    error = new ApiException(action, ApiException.ERROR_CODE_NHIBERNATE, e.Message, new ApiException(action, ApiException.ERROR_CODE_NHIBERNATE_INNER, e.InnerException.Message, null), ToJson(e));
                    LogException(StatusCodes.Status500InternalServerError, e, error);
                }
                else
                {
                    error = new ApiException(action, ApiException.ERROR_CODE_NHIBERNATE, message, new ApiException(action, ApiException.ERROR_CODE_NHIBERNATE, e.Message, null), ToJson(e));
                    LogException(StatusCodes.Status500InternalServerError, e, error);
                }

                return(StatusCode(StatusCodes.Status500InternalServerError, error));
            }
        }
Example #14
0
        /// <summary>
        /// Method for tests logging and debugging
        /// </summary>
        private void WriteRequestIntoFile(HttpResponseMessage message, HttpAction action, string url, string contentObject)
        {
            var statusCode = (int)message.StatusCode;

            Log.Info();
            Log.Info("-----------------------Http request start!----------------------------");
            Log.Info($"Status code is {statusCode}, endpoing {action.ToString().ToUpper()} for {url}");
            Log.Info($"Request content: {contentObject}");
            Log.Info("Headers: key | value");
            foreach (var header in HttpClient.DefaultRequestHeaders)
            {
                Log.Info($"{header.Key} : {header.Value.FirstOrDefault()}");
            }
            Log.Info($"ReasonPhrase is: {message.ReasonPhrase}");
            Log.Info("-------------------------Http request end!----------------------------");
            Log.Info();
        }
Example #15
0
        public void SetUp()
        {
            _accounts = new Accounts();

            _httpAccount                       = new HttpAccount();
            _httpAccount.AccountId             = "1";
            _httpAccount.Url                   = "http://http_URL";
            _httpAccount.IsBasicAuthentication = true;
            _httpAccount.UserName              = "******";
            _httpAccount.Password              = "******";

            _accounts.HttpAccounts.Add(_httpAccount);

            _profile = new ConversionProfile();
            _profile.HttpSettings.AccountId = _httpAccount.AccountId;
            _profile.HttpSettings.Enabled   = true;

            _httpAction = new HttpAction();
        }
Example #16
0
        /// <summary>
        /// Catch and write the http request with error
        /// </summary>
        private void CatchTheError(HttpResponseMessage message, HttpAction action, string url, string contentObject)
        {
            var statusCode = (int)message.StatusCode;

            if (statusCode.ToString().StartsWith("4") || statusCode.ToString().StartsWith("5"))
            {
                WriteLine();
                WriteLine("----------------Negative, status code is received!-------------------");
                WriteLine($"Status code is {statusCode}, endpoing {action.ToString().ToUpper()} for {url}");
                WriteLine($"Request content: {contentObject}");
                WriteLine("Headers: key | value");
                foreach (var header in HttpClient.DefaultRequestHeaders)
                {
                    WriteLine($"{header.Key} : {header.Value.FirstOrDefault()}");
                }
                WriteLine($"Error message is: {message.Content.ReadAsStringAsync().Result}");
                WriteLine("------------------------Error message end!---------------------------");
                WriteLine();
            }
        }
Example #17
0
        internal static HttpMethod GetHttpMethodFromAction(HttpAction action)
        {
            switch (action)
            {
            case HttpAction.GET:
                return(HttpMethod.Get);

            case HttpAction.PUT:
                return(HttpMethod.Put);

            case HttpAction.POST:
                return(HttpMethod.Post);

            case HttpAction.DELETE:
                return(HttpMethod.Delete);

            default:
                throw new NotImplementedException("This HTTP action has not been implemented");
            }
        }
Example #18
0
        public static FrameworkElement Render(TypedElement element, RenderContext context)
        {
            HttpAction action = (HttpAction)element;

            if (context.Config.SupportsInteractivity)
            {
                Button uiButton = XamlUtilities.CreateActionButton(action, context);
                uiButton.Click += (sender, e) =>
                {
                    dynamic data = new JObject();
                    try
                    {
                        data = context.MergeInputData(data);

                        string body = (string)action.Body?.ToString() ?? String.Empty;

                        context.Action(uiButton, new ActionEventArgs()
                        {
                            Action = new HttpAction()
                            {
                                Title   = action.Title,
                                Method  = action.Method,
                                Url     = RendererUtilities.BindData(data, action.Url, url: true),
                                Headers = action.Headers,
                                Body    = RendererUtilities.BindData(data, body),
                            },
                            Data = data
                        });
                    }
                    catch (MissingInputException err)
                    {
                        context.MissingInput(action, new MissingInputEventArgs(err.Input, err.FrameworkElement));
                    }
                };
                return(uiButton);
            }
            return(null);
        }
Example #19
0
        public void SetUp()
        {
            _account = new HttpAccount();

            _account.Url = GetUrl();
            _account.IsBasicAuthentication = false;
            _account.AccountId             = "1";

            var bootstrapper = new IntegrationTestBootstrapper();
            var container    = bootstrapper.ConfigureContainer();

            _th = container.GetInstance <TestHelper>();
            _th.InitTempFolder("HttpRequestTest");

            _th.GenerateGsJob_WithSetOutput(TestFile.PDFCreatorTestpage_GS9_19_PDF);

            _th.Job.Accounts.HttpAccounts.Add(_account);

            _th.Job.Profile.HttpSettings.Enabled   = true;
            _th.Job.Profile.HttpSettings.AccountId = _account.AccountId;

            _httpAction = new HttpAction();
        }
        protected static HtmlTag HttpActionRender(TypedElement actionElement, RenderContext context)
        {
            HttpAction action = (HttpAction)actionElement;

            if (!context.Config.SupportsInteractivity)
            {
                return(null);
            }

            var buttonElement = new HtmlTag("button")
            {
                Text = action.Title
            }
            .Attr("type", "button")
            .Attr("url", action.Url)
            .Attr("method", action.Method)
            .Style("overflow", "hidden")
            .Style("white-space", "nowrap")
            .Style("text-overflow", "ellipsis")
            .Style("flex",
                   context.Config.Actions.ActionAlignment == HorizontalAlignment.Stretch ? "0 1 100%" : "0 1 auto")
            .AddClass("ac-pushButton")
            .AddClass("ac-httpAction");

            if (string.IsNullOrEmpty(action.Body))
            {
                buttonElement.Attr("body", action.Body);
            }

            if (!string.IsNullOrEmpty(action.HeadersJson))
            {
                buttonElement.Attr("header", action.HeadersJson);
            }

            return(buttonElement);
        }
Example #21
0
 public ExecuteCommand(HttpAction action, string requestUri, object data)
 {
     Action     = action;
     RequestUri = requestUri;
     Data       = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");;
 }
Example #22
0
        public async Task <(int httpCode, string responseString)> ExecuteAPI(string uri, HttpAction method, Dictionary <string, string> headers = null, string requestBody = null)
        {
            var client = new HttpClient();

            if (headers != null && headers.Count > 0)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var header in headers)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            Logger.Log($"{method.ToString()}: {uri} \nHeaders: {JSONSerializer.LogObject(headers)} \nRequest: {JSONSerializer.PrettyPrint(requestBody)}");

            try
            {
                switch (method)
                {
                case HttpAction.GET: return(await GetResponse(await client.GetAsync(uri), requestBody));

                case HttpAction.POST: return(await GetResponse(await client.PostAsync(uri, new StringContent(requestBody, Encoding.UTF8, "application/json")), requestBody));

                case HttpAction.PUT: return(await GetResponse(await client.PutAsync(uri, new StringContent(requestBody, Encoding.UTF8, "application/json")), requestBody));

                case HttpAction.DELETE: return(await GetResponse(await client.DeleteAsync(uri), requestBody));

                default: return(999, null);
                }
            }
            catch (TaskCanceledException ex)
            {
                string path = uri;
                if (Uri.TryCreate(uri, UriKind.Absolute, out var url))
                {
                    path = String.Format($"{url.Scheme}://{url.Authority}{url.AbsolutePath}");
                }
                EventTracker.TrackError(ex, new Dictionary <String, String>
                {
                    { "URL", path },
                    { "Response", "Request Timeout" }
                });
                return(APIConstant.HTTPTimeout, String.Empty);
            }
            catch (Exception ex)
            {
                string path = uri;
                if (Uri.TryCreate(uri, UriKind.Absolute, out var url))
                {
                    path = String.Format($"{url.Scheme}://{url.Authority}{url.AbsolutePath}");
                }
                EventTracker.TrackError(ex, new Dictionary <String, String>
                {
                    { "URL", path },
                    { "Response", "General Exception" }
                });
                return(999, String.Empty);
            }
        }
Example #23
0
 public RESTClient(string endpoint, HttpAction method, Context context, string username = null, string password = null)
     : this(endpoint, context, username, password)
 {
     Method = method;
 }
Example #24
0
 public RESTClient(string endpoint, HttpAction method, string postData, Context context, string username = null, string password = null)
     : this(endpoint, method, context, username, password)
 {
     PostData = postData;
 }
Example #25
0
        /// <summary>
        /// Outputs the QueryString object to a string
        /// </summary>
        /// <param name="type">The type of HTTP action the query will be used in</param>
        /// <returns>The encoded QueryString as it would appear in a browser</returns>
        public string ToString(HttpAction type)
        {
            StringBuilder sb = new StringBuilder();
            if (type == HttpAction.Get)
            {
                sb.Append("?");
            }

            foreach (string key in Keys)
            {
                if (sb.Length > 1)
                    sb.Append("&");
                sb.AppendFormat("{0}={1}", HttpUtility.UrlEncodeUnicode(key), HttpUtility.UrlEncodeUnicode(this[key]));
            }

            return sb.ToString();
        }
Example #26
0
 public MockHttpResponseMatcher(HttpAction methodToMatch, Regex UrlPatternToMatch, Mock <IHttpResponseModel> mockResponse)
 {
     _methodToMatch     = methodToMatch;
     _urlPatternToMatch = UrlPatternToMatch;
     _mockResponse      = mockResponse;
 }
        public void CheckThatJsonObjectsSuchAsFromCurrencyAndToCurrencyShouldMatchToCodeAndNameValues()
        {
            // JPath выражения
            string jsonFromCurPath = "$...fromCurrency";
            string jsonToCurPath   = "$...toCurrency";

            var datapattern = new DataPattern();
            var testdata    = new TestData();
            var http        = new HttpAction();

            var response = http.GETRequest(testdata.BaseUrl, testdata.GetResourcePath()["currencyRatesPath"]);
            var content  = response.Content;

            JObject jsonObj = JObject.Parse(content);
            IEnumerable <JToken> jsonArrayFromCur = jsonObj.SelectTokens(jsonFromCurPath, true);
            IEnumerable <JToken> jsonArrayToCur   = jsonObj.SelectTokens(jsonToCurPath, true);

            var rubcode = datapattern.GetCurrencyStuff()["rubcode"];
            var rubname = datapattern.GetCurrencyStuff()["rubname"];
            var usdcode = datapattern.GetCurrencyStuff()["usdcode"];
            var usdname = datapattern.GetCurrencyStuff()["usdname"];
            var eurcode = datapattern.GetCurrencyStuff()["eurcode"];
            var eurname = datapattern.GetCurrencyStuff()["eurname"];
            var gbpcode = datapattern.GetCurrencyStuff()["gbpcode"];
            var gbpname = datapattern.GetCurrencyStuff()["gbpname"];

            foreach (JToken fromCur in jsonArrayFromCur)
            {
                string cutFromCur = fromCur.ToString().
                                    Trim(new char[] { '{', '}' }).Replace(" ", string.Empty);
                Debug.WriteLine(cutFromCur);
                if (cutFromCur.Contains(rubcode))
                {
                    Assert.That(cutFromCur.Contains(rubcode));
                    Debug.WriteLine("RUB TRUE");
                }
                else if (cutFromCur.Contains(usdcode))
                {
                    Assert.That(cutFromCur.Contains(usdcode));
                    Debug.WriteLine("USD TRUE");
                }
                else if (cutFromCur.Contains(eurcode))
                {
                    Assert.That(cutFromCur.Contains(eurcode));
                    Debug.WriteLine("EUR TRUE");
                }
                else if (cutFromCur.Contains(gbpcode))
                {
                    Assert.That(cutFromCur.Contains(gbpcode));
                    Debug.WriteLine("GBP TRUE");
                }
                else
                {
                    throw new Exception(
                              $"Matching CurrencyCode did not happen.");
                }
            }


            foreach (JToken toCur in jsonArrayToCur)
            {
                var cutToCur = toCur.ToString().
                               Trim(new char[] { '{', '}' }).Replace(" ", string.Empty);
                Debug.WriteLine(cutToCur);
                if (cutToCur.Contains(rubname))
                {
                    Assert.That(cutToCur.Contains(rubname));
                    Debug.WriteLine("RUB TRUE");
                }
                else if (cutToCur.Contains(usdname))
                {
                    Assert.That(cutToCur.Contains(usdname));
                    Debug.WriteLine("USD TRUE");
                }
                else if (cutToCur.Contains(eurname))
                {
                    Assert.That(cutToCur.Contains(eurname));
                    Debug.WriteLine("EUR TRUE");
                }
                else if (cutToCur.Contains(gbpname))
                {
                    Assert.That(cutToCur.Contains(gbpname));
                    Debug.WriteLine("GBP TRUE");
                }
                else
                {
                    throw new Exception(
                              $"Matching CurrencyName did not happen.");
                }
            }
        }
Example #28
0
 private HttpRequestModel(HttpAction method, Uri rootUri)
 {
     Method  = method;
     RootUri = rootUri;
 }
Example #29
0
 public ApiException(HttpAction action, int code, ApiException innerException)
 {
     Action     = action.ToString();
     Code       = code;
     InnerError = innerException;
 }
Example #30
0
 public ApiException(HttpAction action, int code, string message)
 {
     Action  = action.ToString();
     Code    = code;
     Message = message;
 }
Example #31
0
 public ApiException(HttpAction action, int code, string message, ApiException innerError, string rawError) : this(action, code, message, rawError)
 {
     InnerError = innerError;
 }
 public virtual void Visit(HttpAction action)
 {
 }
Example #33
0
 public void SetMethod(HttpAction httpAction)
 {
     _request.Method = httpAction.ToString().ToUpper();
 }
Example #34
0
        private static void ConfigureRESTfulApi(RestMethodInfo methodInfo, HttpClientRequest client)
        {
            //add headers
            if (methodInfo.Headers.Count > 0)
            {
                foreach (var keyValuePair in methodInfo.Headers)
                {
                    client.Request.Headers.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }
            if (methodInfo.HeaderParameterMap.Count > 0)
            {
                foreach (var keyValuePair in methodInfo.HeaderParameterMap)
                {
                    client.Request.Headers.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }
            HttpAction httpAction = (HttpAction)Enum.Parse(typeof(HttpAction), methodInfo.Method.ToString());

            client.SetMethod(httpAction);
            switch (httpAction)
            {
            case HttpAction.Delete:
                break;

            case HttpAction.Get:
                break;

            case HttpAction.Patch:
            case HttpAction.Post:
            case HttpAction.Put:
                MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent();
                FormUrlEncodedContent    formUrlEncodedContent    = null;
                ByteArrayContent         byteArrayContent         = null;
                if (methodInfo.IsMultipart && methodInfo.GotPart && methodInfo.Part != null)
                {
                    //multipart bytes
                    byteArrayContent = new ByteArrayContent(methodInfo.Part.GetBinaryData(), methodInfo.Part.Mimetype);
                }
                if (methodInfo.FieldParameterMap.Count > 0)
                {
                    //field
                    var fields = new Dictionary <string, string>();
                    foreach (var keyValuePair in methodInfo.FieldParameterMap)
                    {
                        fields.Add(keyValuePair.Key, keyValuePair.Value.ToString());
                    }
                    formUrlEncodedContent = new FormUrlEncodedContent(fields);
                }

                if (byteArrayContent != null)
                {
                    //multipart/form-data; boundary=***
                    multipartFormDataContent.Add(byteArrayContent, methodInfo.Part.Field, methodInfo.Part.FileName);
                    if (formUrlEncodedContent != null)
                    {
                        foreach (var keyValuePair in methodInfo.FieldParameterMap)
                        {
                            StringContent stringContent = new StringContent(keyValuePair.Value.ToString());
                            multipartFormDataContent.Add(stringContent, keyValuePair.Key);
                        }
                        client.SetHttpContent(multipartFormDataContent);
                    }
                }
                else if (formUrlEncodedContent != null)
                {
                    client.SetHttpContent(formUrlEncodedContent);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            if (!string.IsNullOrEmpty(methodInfo.bodyString))
            {
                //raw body application/json
                StringContent content = new StringContent(methodInfo.bodyString, Encoding.UTF8, "application/json");
                client.SetHttpContent(content);
            }
//          client.SetProxy(new WebProxy(new Uri("http://127.0.0.1:8888")));
        }
 public TokenAuthorizeAttribute(HttpAction action)
 {
     _action = action.ToString();
 }