public static async Task <object> Process(string function, string routeName, RouteRequest request) { var functionAndName = function + "_" + routeName; if (!routes.ContainsKey(functionAndName)) { //var delContainer = DelegateManager.GetDelegate(routeName); //if (delContainer) return(await routes[function + "_" + "*"].action(request)); } return(await routes[functionAndName].action(request)); }
public async Task <Object> CallRunMethod(string url, string contentStr, RouteRequest request) { List <object> parameters = Parameters == null || Parameters.Count == 0 ? null : new List <object>(); if (url == null) { url = ""; } //consider doing a urldecode here. This was requried for here maps url = url.ToLower();// .Replace("%26", "&"); var urlElements = url.Split('&'); JObject contentArgs = new JObject(); //temp hack var tempParams = Parameters.ToList(); if (tempParams.Count > 0 && tempParams[0].ParameterType == typeof(RouteRequest)) { parameters.Add(request); tempParams.RemoveAt(0); } try { if (contentStr != "") { contentArgs = JObject.Parse(contentStr); } } catch (Exception ex) { } #region append url tokens foreach (var param in tempParams) { //var paramFoundInUrl = false; foreach (var urlElement in urlElements) { if (urlElement.StartsWith(param.Name.ToLower() + "=")) { var strVal = urlElement.Substring(urlElement.IndexOf("=") + 1); //only parse if the following types if (param.ParameterType == typeof(int) || param.ParameterType == typeof(string) || param.ParameterType == typeof(double) || param.ParameterType == typeof(float) || param.ParameterType == typeof(bool)) { contentArgs.AddFirst(new JProperty(param.Name, strVal)); continue; } //nullable types else if (param.ParameterType == typeof(int?) || param.ParameterType == typeof(double?) || param.ParameterType == typeof(float?) || param.ParameterType == typeof(bool?)) { contentArgs.AddFirst(new JProperty(param.Name, strVal)); continue; } else { if (strVal.StartsWith("{")) { var jProp = new JProperty(param.Name, JObject.Parse(strVal)); contentArgs.AddFirst(jProp); } } } //if (paramFoundInUrl) continue; } } #endregion var paramCount = tempParams.Count(); if (paramCount == 1 && contentArgs.GetValue(tempParams[0].Name, StringComparison.InvariantCultureIgnoreCase) == null) { if (tempParams[0].ParameterType == typeof(int)) { var jObj = contentArgs.GetValue(Parameters[0].Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null && Parameters[0].IsOptional) { var defaultVal = Parameters[0].DefaultValue; //GetDefaultValue(command.GetType(), Parameters[0].Name); parameters.Add(defaultVal); } else { var intValue = (int)jObj; parameters.Add(intValue); } } else if (tempParams[0].ParameterType == typeof(string)) { var jObj = contentArgs.GetValue(tempParams[0].Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null && tempParams[0].IsOptional) { parameters.Add(tempParams[0].DefaultValue); } else { var strValue = (string)jObj; parameters.Add(strValue); } } else if (tempParams[0].ParameterType == typeof(double)) { var jObj = contentArgs.GetValue(tempParams[0].Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null && tempParams[0].IsOptional) { parameters.Add(tempParams[0].DefaultValue); } else { var dblValue = (double)jObj; parameters.Add(dblValue); } } else if (tempParams[0].ParameterType == typeof(bool)) { var jObj = contentArgs.GetValue(tempParams[0].Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null && tempParams[0].IsOptional) { //parameters.Add(Parameters[0].DefaultValue); parameters.Add(false); } else { var boolValue = (bool)jObj; parameters.Add(boolValue); } } else if (tempParams[0].ParameterType == typeof(DateTime)) { var jObj = contentArgs.GetValue(tempParams[0].Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null && tempParams[0].IsOptional) { parameters.Add(tempParams[0].DefaultValue); } else { var dtValue = (DateTime)jObj; parameters.Add(dtValue); } } } else { foreach (var param in tempParams) { if (contentArgs[param.Name] == null) { if (param.IsOptional) { var defaultVal = param.DefaultValue; //GetDefaultValue(command.GetType(), param.Name); parameters.Add(defaultVal); continue; } else if (param.ParameterType.IsGenericType && param.ParameterType.IsClass == false) { //if (param.ParameterType.IsNullable()) //{ // parameters.Add(request); //} } else if (param.ParameterType == typeof(RouteRequest)) { parameters.Add(request); continue; } else { throw new Exception($"Paramater missing from request: {param.Name}"); } } var jObj = contentArgs.GetValue(param.Name, StringComparison.InvariantCultureIgnoreCase); if (jObj == null) { //do nothing } else if (param.ParameterType == typeof(int)) { var intValue = (int)jObj; parameters.Add(intValue); } else if (param.ParameterType == typeof(int?)) { var intStr = jObj.ToString(); var intValue = intStr.EqualsIgnoreCase("null") ? (int?)null : (int?)jObj; parameters.Add(intValue); } else if (param.ParameterType == typeof(string)) { var strValue = (string)jObj; parameters.Add(strValue); } else if (param.ParameterType == typeof(double)) { var dblValue = (double)jObj; parameters.Add(dblValue); } else if (param.ParameterType == typeof(bool)) { var boolValue = (bool)jObj; parameters.Add(boolValue); } else if (param.ParameterType == typeof(DateTime)) { var dtValue = (DateTime)jObj; parameters.Add(dtValue); } else { try { var obj = jObj.ToObject(param.ParameterType, customSerializer); parameters.Add(obj); } catch (Exception ex) { throw new Exception($"Error serializaing object for param {param.Name}: {ex.Message}"); } } } } //var newCommand = command; //UnityManager.Create(command.GetType()) as ICommandBase; //newCommand.Request = request; //var target = newCommand; //input.Target as ICommandBase; object result = null; request.action.AddEvent("Paramaters Set"); var isCacheCall = CacheMinutes != null && CacheMinutes > 0; if (isCacheCall) { Func <object> methodReturn = () => { var res = RunMethod.DynamicInvoke(parameters == null ? null : parameters.ToArray()); //newCommand.Dispose(); return(res); }; if (parameters == null) { parameters = new List <object>(); } var args = parameters.ToList(); //args.Remove(request); //remove any routerequests as they will always be different (hence no caching) args = args.Where(a => a == null || a.GetType() != typeof(RouteRequest)).ToList(); if (CacheBypass(result)) { result = RunMethod.DynamicInvoke(parameters == null ? null : parameters.ToArray()); //newCommand.Dispose(); } } else { result = RunMethod.DynamicInvoke(parameters == null ? null : parameters.ToArray()); //newCommand.Dispose(); } //handle async functions if (result is Task) { dynamic task = result; return(await task); } if (isCacheCall) { request.action.AddEvent("Cache call completed"); } else { request.action.AddEvent("Non-cache call completed"); } //var result = RunMethod.Invoke(command, parameters == null ? null : parameters.ToArray()); return(result); }
public static async Task <bool> RouteRequest(HttpResponse httpResponse, string requestPath, string requestMethod, string requestContentStr, string accepts, string user, string token, HttpRequest request = null, ActiveAction action = null) { if (accepts == null) { accepts = "*/*"; } if (requestPath.StartsWith("/")) { requestPath = requestPath.Substring(1); } var path = requestPath; var query = ""; if (path.Contains("?")) { path = requestPath.Substring(0, requestPath.IndexOf("?")); query = requestPath.Substring(requestPath.IndexOf("?")); } ; //check for any pre-defined routes ActionRoute route = null; if (routes.ContainsKey(path)) { route = routes[path]; requestPath = route.replacement + query; } else { //default to files if no function path if (!requestPath.StartsWith("s/") && !requestPath.StartsWith("q/") && !requestPath.StartsWith("ui/") && !requestPath.StartsWith("f/") && !requestPath.StartsWith("c/")) { if (requestPath.Contains(".")) { requestPath = "f/" + requestPath; } else { requestPath = "f/index.html"; } } } var isFileRequest = requestPath.StartsWith("f/"); var function = requestPath.Substring(0, requestPath.IndexOf("/")); var serviceName = requestPath.Substring(function.Length + 1); var parameters = ""; if (serviceName.Contains("?")) { var questionIndex = serviceName.IndexOf("?"); parameters = serviceName.Substring(questionIndex + 1); serviceName = serviceName.Substring(0, questionIndex); } if (isFileRequest == false && user == null && route?.anonymous == false) { var reqPath = request.Path.ToUriComponent(); if (reqPath.Contains("?")) { reqPath = reqPath.Substring(0, reqPath.IndexOf("?")); } var redirectResponse = new HttpResponseMessage(HttpStatusCode.OK) { StatusCode = HttpStatusCode.Moved }; var redirPath = "http://" + request.Host.Value + "/login?r=" + reqPath; httpResponse.Redirect(redirPath); return(true); } var routeRequest = new RouteRequest(); routeRequest.contentStr = requestContentStr; routeRequest.fullUrl = requestPath; routeRequest.parameters = parameters; routeRequest.hostName = ""; routeRequest.user = user; routeRequest.function = function; routeRequest.service = serviceName; routeRequest.httpRequest = request; routeRequest.action = action; routeRequest.token = token; var result = await RouteManager.Process(function, serviceName, routeRequest); action.AddEvent("Route Processed"); if (result == null) { result = ""; } //if (result != null) //if (result.GetType() != typeof(RequestError)) //{ var resultStr = ""; if (routeRequest.responseContentType != "") { accepts = routeRequest.responseContentType; } if (requestPath.Contains("plugins/cordova")) { accepts = "application/javascript"; } var returnType = ""; if (result is CommandResponse) { var commandResponse = ((CommandResponse)result); httpResponse.StatusCode = commandResponse.Status; if (!String.IsNullOrEmpty(request?.ContentType)) { accepts = request.ContentType; } if (request.Headers.ContainsKey("Accept")) { var firstHeader = request.Headers["Accept"].FirstOrDefault(); if (firstHeader == null) { firstHeader = ""; } if (firstHeader.Split(',')[0] != "*/*") { returnType = request.Headers["Accept"].First().Split(',')[0]; } if (accepts != "*/*") { returnType = accepts; } } if (commandResponse.ContentType != "") { returnType = commandResponse.ContentType; } if (returnType == "") { returnType = "application/json"; } httpResponse.Headers.Append("Content-Type", returnType); foreach (var header in commandResponse.Headers) { httpResponse.Headers.Append(header.Key, header.Value); } if (commandResponse.Bytes != null) { var bytes = commandResponse.Bytes.ToArray(); await httpResponse.Body.WriteAsync(bytes, 0, bytes.Length); } else if (!String.IsNullOrWhiteSpace(commandResponse.Content)) { await httpResponse.WriteAsync(commandResponse.Content); } else if (commandResponse.value is MemoryStream) { var bytes = ((MemoryStream)commandResponse.value).ToArray(); await httpResponse.Body.WriteAsync(bytes, 0, bytes.Length); } else { await httpResponse.WriteAsync(commandResponse.value == null? "" : commandResponse.value.ToString()); } return(true); } //else if (result is IEntity) resultStr = ((IEntity)result).ToJson(); else { try { resultStr = JsonManager.Serialize(result); } catch (Exception ex) { var resultType = result == null ? "null" : result.GetType().ToString(); resultStr = $"Error with serialization of type {resultType}. {ex.Message} "; } } if (request.Headers.ContainsKey("Accept")) { var firstHeader = request.Headers["Accept"].FirstOrDefault(); if (firstHeader == null) { firstHeader = ""; } if (firstHeader.Split(',')[0] != "*/*") { returnType = request.Headers["Accept"].First().Split(',')[0]; } if (accepts != "*/*") { returnType = accepts; } } if (returnType == "") { returnType = "application/json"; } var writeStart = DateTime.Now; resultStr = resultStr == null ? "" : resultStr; httpResponse.StatusCode = 200; httpResponse.Headers.Append("Content-Type", returnType); await httpResponse.WriteAsync(resultStr); //log the write time TotalWriteMs += (DateTime.Now - writeStart).TotalMilliseconds; TotalBytesSent += resultStr.Length * 2; TotalRequests++; // if (TotalRequests >= 1000) { TotalWriteMs = 0; TotalBytesSent = 0; TotalRequests = 0; } //response.Content.Headers.ContentType = new MediaTypeHeaderValue(returnType); return(true); //} //return false; }