Exemplo n.º 1
0
        private RestResult CallMethod(ArraySegment <byte> content, RestMethod method, IAccount account, IUsers users)
        {
            switch (method.Method)
            {
            case RestMethods.GetServerVersion:
                return(GetServerVersion());

            case RestMethods.GetRole:
                return(GetRole());

            case RestMethods.GetServerOptions:
                return(GetServerOptions());

            case RestMethods.PutServerOptions:
                return(PutServerOptions(content));

            case RestMethods.ValidateServerOptions:
                return(ValidateServerOptions(content));

            case RestMethods.GetAccountsForSuper:
                return(GetAccounts());

            case RestMethods.PostAccount:
                return(PostAccount(content));

            case RestMethods.GetAccount:
                return(GetAccount());

            case RestMethods.PutAccount:
                return(PutAccount(content));

            case RestMethods.DeleteAccount:
                return(DeleteAccount());
            }

            if (account == null)
            {
                throw new Exception(@"Account not found");
            }

            switch (method.Method)
            {
            case RestMethods.GetUserz:
                return(GetUserz(account));

            case RestMethods.GetUsers:
                return(GetUsers(account, users));

            case RestMethods.PostUser:
                return(PostUser(account, users, content));

            case RestMethods.PutUser:
                return(PutUser(account, users, content));

            case RestMethods.DeleteUser:
                return(DeleteUser(account, users));
            }

            throw new NotImplementedException(@"Restapi.CallMethod for " + method.Method.ToString() + " is not implemeted");
        }
Exemplo n.º 2
0
        public static async Task <string> CallRestServiceAsync(Format restType, RestMethod restConstant, string authorizationHeader, Uri requestUri, Guid identityWorkID,
                                                               Guid instanceID, params object[] parameters)
        {
            var jsonObject = GetParameters(parameters);

            return(await CallServiceAsync(restType, restConstant, authorizationHeader, requestUri, jsonObject.ToString(), "", identityWorkID, instanceID));
        }
Exemplo n.º 3
0
            public IRouteTreeBranch AddBranch(string endpoint, RestMethod logic)
            {
                IRouteTreeBranch branch = new Branch(this)
                {
                    Logic = logic
                };

                if (endpoint.Equals("*"))
                {
                    _wildcardBranch = branch;
                }
                else if (endpoint.Equals("**"))
                {
                    _greedyBranch = new GreedyBranch(this)
                    {
                        Logic = logic
                    };
                    branch = _greedyBranch;
                }
                else if (endpoint.StartsWith("{"))
                {
                    endpoint = String.Format("^{0}$", endpoint.Trim('{', '}'));
                    _regexBranches[new Regex(endpoint)] = branch;
                }
                else
                {
                    _literalBranches[endpoint] = branch;
                }

                return(branch);
            }
Exemplo n.º 4
0
 public static RestServiceException Unavailable(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException($"Currently unavailable: {baseUrl}",
         HttpStatusCode.ServiceUnavailable,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Add a stream handler for the designated HTTP method and path prefix.
        /// If the handler is not enabled, the request is ignored. If the path
        /// does not start with the REST prefix, it is added. If method-qualified
        /// path has not already been registered, the method is added to the active
        /// handler table.
        /// </summary>

        public void AddStreamHandler(string httpMethod, string path, RestMethod method)
        {
            if (!IsEnabled)
            {
                return;
            }

            if (!path.StartsWith(Rest.Prefix))
            {
                path = String.Format("{0}{1}", Rest.Prefix, path);
            }

            path = String.Format("{0}{1}{2}", httpMethod, Rest.UrlMethodSeparator, path);

            // Conditionally add to the list

            if (!streamHandlers.ContainsKey(path))
            {
                streamHandlers.Add(path, new RestStreamHandler(httpMethod, path, method));
                Rest.Log.DebugFormat("{0} Added handler for {1}", MsgId, path);
            }
            else
            {
                Rest.Log.WarnFormat("{0} Ignoring duplicate handler for {1}", MsgId, path);
            }
        }
Exemplo n.º 6
0
        public void RegisterCaps(IRegionClientCapsService service)
        {
            m_service     = service;
            m_gridService = service.Registry.RequestModuleInterface <IGridService>();
            IConfig config =
                service.ClientCaps.Registry.RequestModuleInterface <ISimulationBase>().ConfigSource.Configs["MapCaps"];

            if (config != null)
            {
                m_allowCapsMessage = config.GetBoolean("AllowCapsMessage", m_allowCapsMessage);
            }

#if (!ISWIN)
            RestMethod method = delegate(string request, string path, string param,
                                         OSHttpRequest httpRequest, OSHttpResponse httpResponse)
            {
                return(MapLayerRequest(request, path, param, httpRequest, httpResponse, m_service.AgentID));
            };
#else
            RestMethod method =
                (request, path, param, httpRequest, httpResponse) =>
                MapLayerRequest(request, path, param, httpRequest, httpResponse,
                                m_service.AgentID);
#endif
            m_service.AddStreamHandler("MapLayer",
                                       new RestStreamHandler("POST", m_service.CreateCAPS("MapLayer", m_mapLayerPath),
                                                             method));
            m_service.AddStreamHandler("MapLayerGod",
                                       new RestStreamHandler("POST", m_service.CreateCAPS("MapLayerGod", m_mapLayerPath),
                                                             method));
        }
Exemplo n.º 7
0
        public async Task <RestResponse <T> > SendAsync <T>(RestMethod method, string url, string value = null)
        {
            RestResponse <T> response = new RestResponse <T>(await SendAsync(method, url, value));

            response.Data = JsonConvert.DeserializeObject <T>(response.Body);
            return(response);
        }
Exemplo n.º 8
0
        private RestResponse DoRequest(RestMethod method, string resource, object requestData = null, bool json = true)
        {
            var request = new RestRequest
            {
                IsJson = json,
                Method = Enum.GetName(typeof(RestMethod), method),
                Url    = string.Format("{0}{1}", _endpointUri, resource)
            };

            request.Headers = new Dictionary <string, string>
            {
                { "api-expires", Expires.ToString() },
                { "api-key", ApiKey },
                { "api-signature", HttpHelper.CalculateSignature(_endpointUri, Expires, ApiSecret, request.Method, resource, requestData) }
            };
            if (method != RestMethod.GET)
            {
                if (requestData != null)
                {
                    var queryDataString = request.IsJson ? JsonConvert.SerializeObject(requestData) : BuildQueryData(requestData.ToStringDicrionary());
                    var queryDataBytes  = Encoding.UTF8.GetBytes(queryDataString);
                    request.Data = queryDataBytes;
                }
            }
            return(HttpHelper.RawHttpRestQuery(request));
        }
Exemplo n.º 9
0
 public static RestServiceException Unauthorized(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException("Attempted to authenticate, but failed.",
         HttpStatusCode.Unauthorized,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 10
0
        public RestRequestHandler GetRestRequestHandler(RestDigestibleUri uri, RestMethod method, RestRequestParameters parameters)
        {
            HandleParameters(uri, parameters);

            if (uri.IsLastNode || this is WildCardUriRequestHandlerNode)
            {
                switch (method)
                {
                case RestMethod.GET:
                    return(HttpGetRequestHandler);

                case RestMethod.POST:
                    return(HttpPostRequestHandler);

                default:
                    throw new ApplicationException("Unknown REST method.");
                }
            }

            uri.NextNode();

            foreach (var childNode in ChildNodes)
            {
                if (childNode.MatchesUriPattern(uri))
                {
                    return(childNode.GetRestRequestHandler(uri, method, parameters));
                }
            }

            return(null);
        }
Exemplo n.º 11
0
 public static RestServiceException BadRequest(
     string specificMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException(specificMsg,
                                     HttpStatusCode.BadRequest,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 12
0
 public static RestServiceException Unresolvable(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException($"Unresolvable: “{baseUrl}”",
         HttpStatusCode.ServiceUnavailable, //this should be WebExceptionStatus.NameResolutionFailure
         method, baseUrl, resource, ex);
 }
Exemplo n.º 13
0
 public static RestServiceException Unavailable(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException($"Currently unavailable: {baseUrl}",
                                     HttpStatusCode.ServiceUnavailable,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 14
0
 public static RestServiceException Unauthorized(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException("Attempted to authenticate, but failed.",
                                     HttpStatusCode.Unauthorized,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 15
0
 public static RestServiceException Unresolvable(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException($"Unresolvable: “{baseUrl}”",
                                     HttpStatusCode.ServiceUnavailable, //this should be WebExceptionStatus.NameResolutionFailure
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 16
0
 public static InvalidSslRestException InvalidSsl(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new InvalidSslRestException("SSL certificate is invalid.",
                                        HttpStatusCode.Forbidden,
                                        method, baseUrl, resource, ex));
 }
Exemplo n.º 17
0
 public static RestServiceException InternalServer(
     string shortMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException(shortMsg,
                                     HttpStatusCode.InternalServerError,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 18
0
 public static RestServiceException NotFound(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException("Requested resource does not exist on the server.",
                                     HttpStatusCode.NotFound,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 19
0
 public RequestShim(string resource, RestMethod method)
 {
     this.Method     = method;
     this.Resource   = resource;
     this.Cookies    = new Dictionary <string, string>();
     this.Parameters = new Dictionary <string, object>();
 }
Exemplo n.º 20
0
 public static InvalidSslRestException InvalidSsl(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new InvalidSslRestException("SSL certificate is invalid.",
         HttpStatusCode.Forbidden,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 21
0
 public RequestShim(string resource, RestMethod method)
 {
     this.Method = method;
     this.Resource = resource;
     this.Cookies = new Dictionary<string, string>();
     this.Parameters = new Dictionary<string, object>();
 }
Exemplo n.º 22
0
        public static async Task <InvokeResult <T> > Invoke <T>(RestMethod method, string uri, string data)
        {
            SetXAPIKey();

            switch (method)
            {
            case RestMethod.GET:
                string content = await InvokeGet(uri);

                InvokeResult <T> res = null;
                try
                {
                    res = JsonConvert.DeserializeObject <InvokeResult <T> >(content);
                    return(res);
                }
                catch (Exception e)
                {
                    SubsystemUtils.Instance.Err("Json deserialization is failed, " + e.Message);
                    SubsystemUtils.Instance.Err("------------------------------------------------------------------");
                    SubsystemUtils.Instance.Err(content);
                    SubsystemUtils.Instance.Err("------------------------------------------------------------------");
                    res = null;
                }
                return(res);
            }

            return(null);
        }
Exemplo n.º 23
0
        public async Task <Concert> GetConcertsDetailsAsync(RestMethod restMethod)
        {
            string result = await HttpRequestWithToken(restMethod.Route,
                                                       restMethod.MethodType.ToHttpMethod());

            return(JsonConvert.DeserializeObject <Concert>(result));
        }
        private static Method TranslateRestMethod(RestMethod method)
        {
            switch (method)
            {
            case RestMethod.POST:
                return(Method.POST);

            case RestMethod.PUT:
                return(Method.PUT);

            case RestMethod.DELETE:
                return(Method.DELETE);

            case RestMethod.GET:
                return(Method.GET);

            case RestMethod.HEAD:
                return(Method.HEAD);

            case RestMethod.OPTIONS:
                return(Method.OPTIONS);

            default:
                throw new Exception("Unrecognized REST method");
            }
        }
        public ParameterUriRequestHandlerNode(RestDigestibleUri uri, RestMethod method, RestRequestHandler handler)
        {
            m_parameterPattern = uri.GetCurrentNode();
            m_parameterName    = m_parameterPattern.Replace("]", string.Empty).Replace("[", string.Empty);

            AddRestRequestHandler(uri, method, handler);
        }
Exemplo n.º 26
0
        public byte[] RestCallRaw(string urlBase, string url, RestMethod method, IEnumerable <RestParam> parameters = null, object body = null)
        {
            var response = GetRestResponse(urlBase, url, method, parameters, body);

            CheckStatusCode(response);
            return(response.RawBytes);
        }
Exemplo n.º 27
0
        public IRestResponse GetRestResponse(string urlBase, string url, RestMethod method, IEnumerable <RestParam> parameters = null, object body = null)
        {
            var client  = new RestClient(urlBase);
            var request = BuildRestRequest(url, method, parameters, body);

            return(client.Execute(request));
        }
Exemplo n.º 28
0
 public static RestServiceException Conflict(
     string conflictMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return(new RestServiceException(conflictMsg,
                                     HttpStatusCode.Conflict,
                                     method, baseUrl, resource, ex));
 }
Exemplo n.º 29
0
        protected virtual string ParseREST(string request, string path, string method)
        {
            string response;

            string requestKey = String.Format("{0}: {1}", method, path);

            string bestMatch = String.Empty;

            foreach (string currentKey in m_restHandlers.Keys)
            {
                if (requestKey.StartsWith(currentKey))
                {
                    if (currentKey.Length > bestMatch.Length)
                    {
                        bestMatch = currentKey;
                    }
                }
            }

            RestMethodEntry restMethodEntry;

            if (m_restHandlers.TryGetValue(bestMatch, out restMethodEntry))
            {
                RestMethod restMethod = restMethodEntry.RestMethod;

                string param = path.Substring(restMethodEntry.Path.Length);
                response = restMethod(request, path, param);
            }
            else
            {
                response = String.Empty;
            }

            return(response);
        }
Exemplo n.º 30
0
 public static RestServiceException Forbidden(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     var msg = $"Forbidden [{method}] {resource}";
     return new RestServiceException(msg,
         HttpStatusCode.Forbidden,
         method, baseUrl, resource, ex);
 }
 public RestRequest(RestMethod method, string path, string requestBody, ContentType contentType, Dictionary <string, string> additionalHeaders)
 {
     _method            = method;
     _path              = path;
     _requestBody       = requestBody;
     _contentType       = contentType;
     _additionalHeaders = additionalHeaders;
 }
Exemplo n.º 32
0
 public VerbNotSupportedProtocolException(RestMethod calledMethod, ReadOnlyCollection <RestMethod> allowedMethods, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "The method {0} is not supported for the specified resource. Refer to 'Allow' response header for the list of supported methods.", new object[] { calledMethod }), innerException)
 {
     NephosAssertionException.Assert(calledMethod != RestMethod.Unknown);
     NephosAssertionException.Assert(allowedMethods != null);
     NephosAssertionException.Assert(allowedMethods.Count > 0);
     this.calledMethod   = calledMethod;
     this.allowedMethods = allowedMethods;
 }
Exemplo n.º 33
0
        public void Register(RestMethod method, string uri, Action <Request, Response> handler)
        {
            //check if running
            //   if (IsListening)
            //       throw new ApplicationException("RestService is listening, cannot register new methods");

            this.server.m_requestTree.AddRequestHandler(uri, method, handler);
        }
Exemplo n.º 34
0
 /// <summary>
 /// Constructor for HttpCall
 /// </summary>
 /// <param name="method"></param>
 /// <param name="headers"></param>
 /// <param name="url"></param>
 /// <param name="requestBody"></param>
 /// <param name="contentType"></param>
 public HttpCall(RestMethod method, Dictionary <string, string> headers, string url, string requestBody, ContentType contentType)
 {
     _method      = method;
     _headers     = headers;
     _url         = url;
     _requestBody = requestBody;
     _contentType = contentType;
 }
Exemplo n.º 35
0
 /// <summary>
 /// On View loaded event of caliburn
 /// </summary>
 /// <param name="view"></param>
 protected override void OnViewLoaded(object view)
 {
     base.OnViewLoaded(view);
     //Load rest API table
     SelectedRestMethod  = new RestMethod();
     SelectedContentItem = SelectedRestMethod.ContentType;
     RestMethodList      = Test.TestPackage.RestMethods;
 }
Exemplo n.º 36
0
        private static async Task <string> CallServiceAsync(Format restType, RestMethod restConstant, string authorizationHeader, Uri requestUri, string serializedParameters, string TransactionKey = "",
                                                            Guid?identityWorkID = null, Guid?instanceID = null)
        {
            HttpClient client = new HttpClient();

            client.Timeout = TimeSpan.FromMinutes(40);
            string result = string.Empty;

            ConfigureEndPoints(requestUri);
            HttpRequestMessage reqmsg = new HttpRequestMessage();

            reqmsg.RequestUri = requestUri;
            reqmsg.Method     = new HttpMethod(restConstant.ToString("g"));
            reqmsg.Headers.TryAddWithoutValidation(ServiceHelperConstants.authorizationHeaderTitle, authorizationHeader);
            reqmsg.Headers.TryAddWithoutValidation(ServiceHelperConstants.transactionHeaderTitle, TransactionKey);

            if (identityWorkID != null)
            {
                reqmsg.Headers.TryAddWithoutValidation("companyid", identityWorkID.ToString());
            }
            if (instanceID != null)
            {
                reqmsg.Headers.TryAddWithoutValidation("instanceid", instanceID.ToString());
            }

            if (reqmsg.Method == HttpMethod.Post || reqmsg.Method == HttpMethod.Put)
            {
                reqmsg.Content = new StringContent(serializedParameters, Encoding.UTF8, resolveContentType(restType));
            }
            var response = await client.SendAsync(reqmsg, HttpCompletionOption.ResponseContentRead);

            result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                if (!String.IsNullOrEmpty(result))
                {
                    try
                    {
                        var contentHelper = Newtonsoft.Json.JsonConvert.DeserializeObject <ContentHelper>(result);
                        manageWebException(contentHelper);
                    }
                    catch (Newtonsoft.Json.JsonReaderException ex)
                    {
                        throw new CallRestException().getDefault(ex.TargetSite, result, (int)response.StatusCode);
                    }
                }
                else
                {
                    throw new CallRestException().getDefault(MethodBase.GetCurrentMethod(), "No se pudo conectar al servicio.", (int)response.StatusCode);
                }
            }
            else
            {
                result = await response.Content.ReadAsStringAsync();
            }
            return(result);
        }
Exemplo n.º 37
0
 internal static IRequestShim Make(string resource, RestMethod method, D7UserSession sess, string usr, string pwd)
 {
     var req = new RequestShim(resource, method);
     req.UserName = usr;
     req.Password = pwd;
     req.CsrfToken = sess.token;
     req.Cookies.Add(sess.session_name, sess.sessid);
     return req;
 }
        /// <summary>
        /// Registers the given method for the given endpoint
        /// </summary>
        /// <param name="endpoint">The endpoint to register with the logic</param>
        /// <param name="logic">The logic to use for the endpoint</param>
        public void AddRoute(string endpoint, RestMethod logic)
        {
            var branch = _routeTree.Trunk;
            var components = endpoint.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var component in components) {
                branch = branch.GetChild(component, true);
            }

            branch.Logic = logic;
        }
Exemplo n.º 39
0
        public static RestServiceException Unknown(string clue,
            RestMethod method, string baseUrl, string resource, Exception inr)
        {
            var msg = "Unknown REST Service exception."
                    + L.f + "clue :" + clue
                    + L.f + "type :" + inr.GetType().Name;

            return new RestServiceException(msg,
                HttpStatusCode.InternalServerError,
                method, baseUrl, resource, inr);
        }
Exemplo n.º 40
0
 private RestSharp.Portable.Method Unshim(RestMethod restMethod)
 {
     switch (restMethod)
     {
         case RestMethod.Get    : return RestSharp.Portable.Method.GET;
         case RestMethod.Post   : return RestSharp.Portable.Method.POST;
         case RestMethod.Put    : return RestSharp.Portable.Method.PUT;
         case RestMethod.Delete : return RestSharp.Portable.Method.DELETE;
         default:
             throw Error.Unsupported(restMethod, "RestMethod");
     }
 }
Exemplo n.º 41
0
        public bool AddRestHandler(string method, string path, RestMethod handler)
        {
            string methodKey = String.Format("{0}: {1}", method, path);

            if (!this.m_restHandlers.ContainsKey(methodKey))
            {
                this.m_restHandlers.Add(methodKey, new RestMethodEntry( path, handler ));
                return true;
            }

            //must already have a handler for that path so return false
            return false;
        }
Exemplo n.º 42
0
 public RestServiceException(string msg,
                             HttpStatusCode code,
                             RestMethod method,
                             string baseUrl,
                             string resource,
                             Exception inr = null)
 : base(msg, inr)
 {
     this.Code = code;
     this.Method = method;
     this.BaseUrl = baseUrl;
     this.Resource = resource;
 }
		private RestRequest CreateRequest(RestMethod method, string endpoint, object data = null, QueryParamList parameters = null, string factoryId = null)
		{
			var access = _apiAccess;

			var request = new RestRequest();
			request.Method = method;
			request.Endpoint = endpoint;
			request.TimeStamp = DateTime.Now;
			request.FactoryId = factoryId;
			request.Data = data;
			request.Params = parameters;
			request.ApiHost = access.Host;
			request.ApiVersion = access.Version;
			request.ApiPort = access.Port;
			request.AccessKey = access.AccessKey;
			request.SecretKey = access.SecretKey;

			return request;
		}
Exemplo n.º 44
0
 /// <summary>
 /// On View loaded event of caliburn
 /// </summary>
 /// <param name="view"></param>
 protected override void OnViewLoaded(object view)
 {
     base.OnViewLoaded(view);
     //Load rest API table
     SelectedRestMethod = new RestMethod();
     SelectedContentItem = SelectedRestMethod.ContentType;
     RestMethodList = Test.TestPackage.RestMethods;
 }
Exemplo n.º 45
0
 private void ResetView()
 {
     IsExisting = false;
     //_isExisting = false;
     _existingGuid = string.Empty;
     SelectedRestMethod = new RestMethod();
     SelectedContentItem = SelectedRestMethod.ContentType;
     NotifyOfPropertyChange(() => RestMethodList);
 }
Exemplo n.º 46
0
        /// <summary>
        /// Add a stream handler for the designated HTTP method and path prefix.
        /// If the handler is not enabled, the request is ignored. If the path
        /// does not start with the REST prefix, it is added. If method-qualified
        /// path has not already been registered, the method is added to the active
        /// handler table.
        /// </summary>
        public void AddStreamHandler(string httpMethod, string path, RestMethod method)
        {
            if (!IsEnabled)
            {
                return;
            }

            if (!path.StartsWith(Rest.Prefix))
            {
                path = String.Format("{0}{1}", Rest.Prefix, path);
            }

            path = String.Format("{0}{1}{2}", httpMethod, Rest.UrlMethodSeparator, path);

            // Conditionally add to the list

            if (!streamHandlers.ContainsKey(path))
            {
                streamHandlers.Add(path, new RestStreamHandler(httpMethod, path, method));
                Rest.Log.DebugFormat("{0} Added handler for {1}", MsgId, path);
            }
            else
            {
                Rest.Log.WarnFormat("{0} Ignoring duplicate handler for {1}", MsgId, path);
            }
        }
 public IRouteTreeBranch AddBranch(string endpoint, RestMethod logic)
 {
     throw new NotSupportedException(); // It doesn't make sense to add a child to a greedy branch
 }
            public IRouteTreeBranch AddBranch(string endpoint, RestMethod logic)
            {
                IRouteTreeBranch branch = new Branch(this) { Logic = logic };
                if (endpoint.Equals("*")) {
                    _wildcardBranch = branch;
                } else if (endpoint.Equals("**")) {
                    _greedyBranch = new GreedyBranch(this) { Logic = logic };
                    branch = _greedyBranch;
                } else if (endpoint.StartsWith("{")) {
                    endpoint = String.Format("^{0}$", endpoint.Trim('{', '}'));
                    _regexBranches[new Regex(endpoint)] = branch;
                } else {
                    _literalBranches[endpoint] = branch;
                }

                return branch;
            }
Exemplo n.º 49
0
        /// <summary>
        /// Add a REST stream handler to the underlying HTTP server.
        /// </summary>
        /// <param name="httpMethod">GET/PUT/POST/DELETE or
        /// similar</param>
        /// <param name="path">URL prefix</param>
        /// <param name="method">RestMethod handler doing the actual work</param>
        public virtual void AddRestStreamHandler(string httpMethod, string path, RestMethod method)
        {
            if (!IsEnabled) return;

            if (!path.StartsWith(_prefix))
            {
                path = String.Format("{0}{1}", _prefix, path);
            }

            RestStreamHandler h = new RestStreamHandler(httpMethod, path, method);
            _httpd.AddStreamHandler(h);
            _handlers.Add(h);

            m_log.DebugFormat("{0} Added REST handler {1} {2}", MsgID, httpMethod, path);
        }
Exemplo n.º 50
0
        public static RestMethodResponse InvokeRestApi(RestMethod r, bool trackTime)
        {
            bool isMethodAdded = false;
            string token = Guid.NewGuid().ToString();
            RestMethodResponse webResponse = new RestMethodResponse();
            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(r.Url);

                webRequest.ContentType = r.ContentType;
                webRequest.ContentLength = 0;
                webRequest.Method = r.Type.ToString().ToUpper();

                webRequest.AllowAutoRedirect = true;
                //set headers
                if (r.SelectedHeaderTab == 0)
                {
                    foreach (var kv in r.Headers)
                    {
                        webRequest.Headers.Add(string.Format("{0}:{1}", kv.Key, kv.Value));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(r.HeaderText))
                    {
                        var headers = r.HeaderText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                        foreach (var h in headers.Where(h => h.IndexOf(":", StringComparison.Ordinal) > -1))
                        {
                            webRequest.Headers.Add(h);
                        }
                    }
                }
                //set post data
                var postData = r.SelectedPayloadTab == 0
                    ? string.Join("&", r.PayloadValues.Select(kv => string.Format("{0}={1}", kv.Key, kv.Value)).ToArray())
                    : r.PayloadText.Replace(Environment.NewLine, " ");

                if (!string.IsNullOrEmpty(postData) && (r.Type == RequestType.Post || r.Type == RequestType.Put))
                {
                    var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
                    webRequest.ContentLength = bytes.Length;

                    using (var writeStream = webRequest.GetRequestStream())
                    {
                        writeStream.Write(bytes, 0, bytes.Length);
                    }
                }

                if (trackTime)
                    InsertNewMethodLog(r.Url, token);
                isMethodAdded = true;
                if (trackTime)
                    UpdateMethodLog(token, r.Url, MethodStatus.Started);

                var sw = new Stopwatch();
                sw.Start();
                try
                {
                    using (var response = (HttpWebResponse)webRequest.GetResponse())
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            webResponse.StatusCode = response.StatusCode;

                            var ellapsedTime2 = sw.ElapsedMilliseconds;
                            if (trackTime)
                                UpdateMethodLog(token, r.Url, MethodStatus.Fail, ellapsedTime2,
                                string.Format("Status Code returned : {0}", response.StatusCode));
                            return webResponse;
                        }
                        // grab the response
                        webResponse.StatusCode = response.StatusCode;
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream == null) return webResponse;
                            using (var reader = new StreamReader(responseStream))
                            {
                                webResponse.Response = reader.ReadToEnd();
                            }
                        }
                        var ellapsedTime = sw.ElapsedMilliseconds;
                        if (trackTime)
                            UpdateMethodLog(token, r.Url, MethodStatus.Pass, ellapsedTime);
                        return webResponse;
                    }
                }
                catch (Exception ex)
                {
                    var ellapsedTime1 = sw.ElapsedMilliseconds;
                    if (trackTime)
                        UpdateMethodLog(token, r.Url, MethodStatus.Fail, ellapsedTime1, ex.Message + " -- " + ex.StackTrace);
                    webResponse.Response = ex.Message;
                    webResponse.StatusCode = HttpStatusCode.InternalServerError;
                }
            }
            catch (Exception er)
            {
                if (isMethodAdded && trackTime)
                {
                    UpdateMethodLog(token, r.Url, MethodStatus.Error, null, er.Message + " -- " + er.StackTrace);
                }
                webResponse.Response = er.Message;
                webResponse.StatusCode = HttpStatusCode.InternalServerError;
            }
            return webResponse;
        }
Exemplo n.º 51
0
 public static RestServiceException InternalServer(
     string shortMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException(shortMsg,
         HttpStatusCode.InternalServerError,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 52
0
 public static RestServiceException Conflict(
     string conflictMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException(conflictMsg,
         HttpStatusCode.Conflict,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 53
0
 public static RestServiceException BadRequest(
     string specificMsg, RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException(specificMsg,
         HttpStatusCode.BadRequest,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 54
0
 public RestStreamHandler(string httpMethod, string path, RestMethod restMethod)
     : this(httpMethod, path, restMethod, null, null) {}
Exemplo n.º 55
0
 public RestStreamHandler(string httpMethod, string path, RestMethod restMethod) : base(httpMethod, path)
 {
     m_restMethod = restMethod;
 }
Exemplo n.º 56
0
 public static RestServiceException NotFound(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     return new RestServiceException("Requested resource does not exist on the server.",
         HttpStatusCode.NotFound,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 57
0
 public static RestServiceException NotAcceptable(
     RestMethod method, string baseUrl, string resource, Exception ex)
 {
     var msg = ex.Message.Between("406 (Not Acceptable : ", ").", true);
     return new RestServiceException(msg,
         HttpStatusCode.NotAcceptable,
         method, baseUrl, resource, ex);
 }
Exemplo n.º 58
0
        public XmlDocument Custom(string resourceKey, int? id, string action, RestMethod method, XmlDocument changedResource,
            Dictionary<string, string> queryParameters)
        {
            Resource resource = FindValidResource(resourceKey);

              string relativeUrl = resource.RelativeUri;
              if (id != null) relativeUrl += "/" + id;
              if (action != null) relativeUrl += "/" + action;
              relativeUrl += ".xml";

              var uriBuilder = new UriBuilder("http", uri.Host, uri.Port, AddQueryParametersTo(relativeUrl, queryParameters));
              if (UserName.Length != 0)
              {
            uriBuilder.UserName = UserName;
              }
              if (Password.Length != 0)
              {
            uriBuilder.Password = Password;
              }

              Uri serviceUri = uriBuilder.Uri;
              HttpWebRequest request = null;
              switch (method)
              {
            case RestMethod.GET:
              request = ConstructRequest(serviceUri, "GET", null, null);
              break;
            case RestMethod.POST:
              request = ConstructRequest(serviceUri, "POST", null, changedResource);
              break;
            case RestMethod.PUT:
              request = ConstructRequest(serviceUri, "POST", "PUT", changedResource);
              break;
            case RestMethod.DELETE:
              request = ConstructRequest(serviceUri, "POST", "DELETE", changedResource);
              break;
              }
              return PerformAction(request);
        }
Exemplo n.º 59
0
        public static void LoadTest(string loadTestFilePath = null)
        {
            if (string.IsNullOrEmpty(loadTestFilePath))
            {
                loadTestFilePath = Environment.CurrentDirectory + "\\" + ConfigurationManager.AppSettings["loadTestFile"];
            }
            _testConfigurationFile = loadTestFilePath;

            var sr = new StreamReader(_testConfigurationFile);
            var testXml = sr.ReadToEnd();
            sr.Close();

            TestPackage = new Package();

            var xDoc = XDocument.Parse(testXml);

            if (xDoc.Root != null)
            {
                TestPackage.ResultFileName = Convert.ToString(xDoc.Root.Attribute("resultFileName").Value);

                if (xDoc.Root.Attributes("intervalBetweenScenarios").Any())
                {
                    TestPackage.IntervalBetweenScenarios =
                        Convert.ToInt32(xDoc.Root.Attribute("intervalBetweenScenarios").Value);
                }

                TestPackage.Duration = Convert.ToInt32(xDoc.Root.Attribute("duration").Value);
                TestPackage.Clients = Convert.ToInt32(xDoc.Root.Attribute("clients").Value);

                TestPackage.DelayRangeStart = Convert.ToInt32(xDoc.Root.Attribute("delayRangeStart").Value);
                TestPackage.DelayRangeEnd = Convert.ToInt32(xDoc.Root.Attribute("delayRangeEnd").Value);

                TestPackage.ResultFileName = Convert.ToString(xDoc.Root.Attribute("resultFileName").Value);
                if (string.IsNullOrEmpty(TestPackage.ResultFileName))
                {
                    TestPackage.ResultFileName = "PerfResults.txt";
                }

                if (File.Exists(TestPackage.ResultFileName))
                {
                    File.Delete(TestPackage.ResultFileName);
                }

                if (xDoc.Root.Elements("nodes").Any())
                {
                    TestPackage.Nodes = new Nodes { NodeList = new List<string>() };

                    XElement nsE = xDoc.Root.Elements("nodes").ElementAt(0);
                    if (nsE.Attributes("noOfClientsPerNode").Any())
                    {
                        TestPackage.Nodes.NoOfClientsPerNode = Convert.ToInt32(nsE.Attribute("noOfClientsPerNode").Value);
                    }
                    foreach (XElement nE in nsE.Elements("node"))
                    {
                        TestPackage.Nodes.NodeList.Add(nE.Attribute("name").Value);
                    }
                }

                if (xDoc.Root.Elements("scenarios").Any())
                {
                    TestPackage.Scenarios = new List<Scenario>();

                    XElement scenariosE = xDoc.Root.Elements("scenarios").ElementAt(0);
                    foreach (XElement scenarioE in scenariosE.Elements("scenario"))
                    {
                        Scenario scen = new Scenario();
                        foreach (XElement sOrderE in scenarioE.Elements("order"))
                        {
                            ScenarioOrder sorder = new ScenarioOrder
                            {
                                MethodName = Convert.ToString(sOrderE.Attribute("methodName").Value),
                                Order = Convert.ToInt32(sOrderE.Attribute("order").Value),
                                MethodGuid =
                                    sOrderE.Attributes("methodGuid").Any()
                                        ? Convert.ToString(sOrderE.Attribute("methodGuid").Value)
                                        : string.Empty,
                                AssemblyGuid = sOrderE.Attributes("assemblyGuid").Any()
                                        ? Convert.ToString(sOrderE.Attribute("assemblyGuid").Value)
                                        : string.Empty,
                                IsRest = sOrderE.Attributes("isRest").Any() && Convert.ToBoolean(sOrderE.Attribute("isRest").Value)
                            };
                            scen.ScenarioOrder.Add(sorder);
                        }
                        TestPackage.Scenarios.Add(scen);
                    }
                }

                foreach (var suite in xDoc.Root.Elements("testSuite"))
                {
                    var newSuite = new TestSuite();
                    TestPackage.Suites.Add(newSuite);

                    newSuite.Guid = Convert.ToString(suite.Attribute("__guid__").Value);
                    newSuite.ServiceUrl = Convert.ToString(suite.Attribute("serviceUrl").Value);
                    newSuite.BaseUrl = newSuite.ServiceUrl;
                    newSuite.Wsdl = newSuite.ServiceUrl + "?wsdl";

                    if (suite.Attributes("bindingToTest").Any())
                        newSuite.BindingToTest = Convert.ToString(suite.Attribute("bindingToTest").Value);

                    if (suite.Attributes("configuration").Any())
                        newSuite.Configuration = Convert.ToString(suite.Attribute("configuration").Value);

                    foreach (XElement test in suite.Elements("test"))
                    {
                        LoadServiceElement(test, newSuite.Tests, false);
                    }

                    foreach (XElement test in suite.Elements("functionalTest"))
                    {
                        LoadServiceElement(test, newSuite.FunctionalTests, true);
                    }
                    GenerateProxyAssembly(newSuite.Wsdl, newSuite.Guid);
                }

                #region rest api
                foreach (var restNodeX in xDoc.Root.Elements("restApis"))
                {
                    foreach (XElement restMethodX in restNodeX.Elements("restMethod"))
                    {
                        RestMethod restMethod = new RestMethod()
                        {
                            Guid = Convert.ToString(restMethodX.Attribute("__guid__").Value),
                            Url = Convert.ToString(restMethodX.Attribute("url").Value),
                            SelectedHeaderTab = Convert.ToInt32(restMethodX.Attribute("selectedHeaderTab").Value),
                            SelectedPayloadTab = Convert.ToInt32(restMethodX.Attribute("selectedPayloadTab").Value),
                            Headers = (List<KeyValue>)TestHelper.Deserialize(restMethodX.Attribute("headers").Value, typeof(List<KeyValue>)),
                            HeaderText = Convert.ToString(restMethodX.Attribute("headerText").Value),
                            PayloadValues = (List<KeyValue>)TestHelper.Deserialize(restMethodX.Attribute("payload").Value, typeof(List<KeyValue>)),
                            PayloadText = Convert.ToString(restMethodX.Attribute("payloadText").Value),
                            ContentType = Convert.ToString(restMethodX.Attribute("contentType").Value),
                            Type = (RequestType)Enum.Parse(typeof(RequestType), Convert.ToString(restMethodX.Attribute("type").Value)),
                            IsAddedToFunctional = restMethodX.Attributes("isAddedToFunctional").Any() && Convert.ToBoolean(restMethodX.Attribute("isAddedToFunctional").Value),
                            MethodOutput = restMethodX.Attributes("methodOutput").Any() ?
                                Convert.ToString(restMethodX.Attribute("methodOutput").Value)
                                : string.Empty

                        };

                        TestPackage.RestMethods.Add(restMethod);
                    }
                }
                #endregion
            }
        }
Exemplo n.º 60
0
 public RestStreamHandler(string httpMethod, string path, RestMethod restMethod, string name, string description)
     : base(httpMethod, path, name, description)
 {
     m_restMethod = restMethod;
 }