public Magic(string _name, string _info, int _cost, CastDelegate _castDelegate) { name = _name; info = _info; cost = _cost; castDelegate = _castDelegate; }
protected override CastDelegate GetFileNameCastDelegate( IHttpRequest request, IApplication httpApp, string[] componentsMatched, out string[] pathKeys) { pathKeys = PathComponents(request) .Skip(componentsMatched.Length + 1) .ToArray(); var paths = pathKeys; CastDelegate fileNameCastDelegate = (paramInfo, onParsed, onFailure) => { if (!paths.Any()) { return(onFailure("No URI filename value provided.")); } if (paths.Length > 1) { return(onFailure($"More than 1 path key `{paths.Join(',')}` not supported.")); } return(httpApp.Bind(paths.First(), paramInfo, v => onParsed(v), (why) => onFailure(why))); }; return(fileNameCastDelegate); }
public async Task <IHttpResponse> ParseContentValuesAsync( IApplication httpApp, IHttpRequest request, Func < CastDelegate, string[], Task <IHttpResponse> > onParsedContentValues) { var formData = request.Form; var parameters = formData.SelectKeys().ToArray(); CastDelegate parser = (paramInfo, onParsed, onFailure) => { return(paramInfo .GetAttributesInterface <IBindFormDataApiValue>(true) .First( (formBinder, next) => formBinder.ParseContentDelegate(formData, paramInfo, httpApp, request, onParsed, onFailure), () => onFailure($"{paramInfo.Name} does not handle form data."))); }; return(await onParsedContentValues(parser, parameters)); }
public async Task <IHttpResponse> ParseContentValuesAsync( IApplication httpApp, IHttpRequest request, Func < CastDelegate, string[], Task <IHttpResponse> > onParsedContentValues) { if (!request.RequestUri.IsDefaultOrNull()) { return(await UrlMissingAsync("URL was not provided")); } var contentLookup = request.RequestUri.ParseQuery(); if (contentLookup.IsDefaultOrNull()) { return(await UrlMissingAsync("Query is empty")); } CastDelegate parser = (paramInfo, onParsed, onFailure) => { return(paramInfo .GetAttributeInterface <IBindQueryApiValue>() .ParseContentDelegate(contentLookup, paramInfo, httpApp, request, onParsed, onFailure)); }; var keys = contentLookup .Keys .ToArray(); return(await onParsedContentValues(parser, keys)); Task <IHttpResponse> UrlMissingAsync(string failureMessage) { CastDelegate emptyParser = (paramInfo, onParsed, onFailure) => { var key = paramInfo .GetAttributeInterface <IBindApiValue>() .GetKey(paramInfo) .ToLowerNullSafe(); var type = paramInfo.ParameterType; return(onFailure($"[{key}] could not be parsed ({failureMessage}).")); }; var exceptionKeys = new string[] { }; return(onParsedContentValues(emptyParser, exceptionKeys)); } }
public void testDelegate2() { CastDelegate cast2; cast2 = testCastStatic; cast2("type1"); cast2 = new CastDelegate(testCast); cast2 = testCast; cast2("tooStupid"); Dely = (CastDelegate)testCastStatic; ((CastDelegate)Dely)("Whaaaaat"); Console.ReadKey(); }
public static void testDelegate(Class1 ins) { CastDelegate cast; cast = testCastStatic; cast("type1"); cast = new CastDelegate(ins.testCast); cast = ins.testCast; cast("tooStupid"); ins.Dely = (CastDelegate)testCastStatic; ((CastDelegate)ins.Dely)("Whaaaaat"); Console.ReadKey(); }
public async virtual Task <IHttpResponse> CreateResponseAsync(Type controllerType, IApplication httpApp, IHttpRequest request, string[] componentsMatched) { var matchingActionMethods = GetHttpMethods(controllerType, httpApp, request, componentsMatched); if (!matchingActionMethods.Any()) { return(request.CreateResponse(HttpStatusCode.NotImplemented)); } return(await httpApp.GetType() .GetAttributesInterface <IParseContent>(true, true) .Where(contentParser => contentParser.DoesParse(request)) .First( (contentParser, next) => { return contentParser.ParseContentValuesAsync(httpApp, request, (bodyCastDelegate, bodyValues) => InvokeMethod( matchingActionMethods, componentsMatched, httpApp, request, bodyCastDelegate, bodyValues)); }, () => { if (!request.HasBody) { CastDelegate parserEmpty = (paramInfo, onParsed, onFailure) => onFailure( $"Request did not contain any content."); return InvokeMethod( matchingActionMethods, componentsMatched, httpApp, request, parserEmpty, new string[] { }); } var mediaType = request.GetMediaType(); CastDelegate parser = (paramInfo, onParsed, onFailure) => onFailure( $"Could not parse content of type {mediaType}"); return InvokeMethod( matchingActionMethods, componentsMatched, httpApp, request, parser, new string[] { }); })); }
protected virtual CastDelegate GetFileNameCastDelegate( IHttpRequest request, IApplication httpApp, string [] componentsMatched, out string [] pathKeys) { pathKeys = PathComponents(request) .Skip(componentsMatched.Length) .ToArray(); var path = pathKeys; CastDelegate fileNameCastDelegate = (paramInfo, onParsed, onFailure) => { if (!path.Any()) { return(onFailure("No URI filename value provided.")); } var fileName = path.First(); return(httpApp.Bind(fileName, paramInfo, v => onParsed(v), (why) => onFailure(why))); }; return(fileNameCastDelegate); }
protected virtual CastDelegate GetQueryCastDelegate( IHttpRequest request, IApplication httpApp, out string[] queryKeys) { var queryParameters = request.RequestUri.ParseQuery() .Select(kvp => kvp.Key.ToLower().PairWithValue(kvp.Value)) .ToDictionary(); queryKeys = queryParameters.SelectKeys().ToArray(); var queryParameterCollections = GetCollectionParameters(httpApp, queryParameters).ToDictionary(); CastDelegate queryCastDelegate = (paramInfo, onParsed, onFailure) => { var queryKey = paramInfo .GetAttributeInterface <IBindApiValue>() .GetKey(paramInfo) .ToLower(); var type = paramInfo.ParameterType; if (!queryParameters.ContainsKey(queryKey)) { if (!queryParameterCollections.ContainsKey(queryKey)) { return(onFailure($"Missing query parameter `{queryKey}`")); } return(queryParameterCollections[queryKey]( type, vs => onParsed(vs), why => onFailure(why))); } var queryValueString = queryParameters[queryKey]; return(httpApp.Bind(queryValueString, paramInfo, v => onParsed(v), (why) => onFailure(why))); }; return(queryCastDelegate); }
/// <summary> /// Creates a new LRU (Least-Recently Used) cache of GrainReferences. /// </summary> /// <param name="maxSize">Maximum number of entries to allow.</param> /// <param name="maxAge">Maximum age of an entry.</param> /// <param name="f"> Delegate for fetching the value associated with a given key</param> /// <param name="c"> Delegate for casting IAddressable to TValue</param> public GrainReferenceCache(int maxSize, TimeSpan maxAge, FetchValueDelegate f, CastDelegate c) { maximumCount = maxSize; requiredFreshness = maxAge; fetcher = f; cache = new Dictionary <TKey, TimestampedValue>(); rwLock = new ReaderWriterLockSlim(); }
protected virtual async Task <IHttpResponse> InvokeMethod( IEnumerable <MethodInfo> matchingActionMethods, string[] componentsMatched, IApplication httpApp, IHttpRequest routeData, CastDelegate bodyCastDelegate, string[] bodyValues) { var evaluatedMethods = matchingActionMethods .Select( method => { var routeMatcher = method.GetAttributesInterface <IMatchRoute>().Single(); return(routeMatcher.IsRouteMatch(method, componentsMatched, this, routeData, httpApp, bodyValues, bodyCastDelegate)); }); var validMethods = evaluatedMethods .Where(methodCast => methodCast.isValid); return(await validMethods .First( (methodCast, next) => { return methodCast.parametersWithValues .Aggregate <SelectParameterResult, ValidateHttpDelegate>( (parameterSelectionUnvalidated, methodFinalUnvalidated, httpAppFinalUnvalidated, requestFinalUnvalidated) => { return methodFinalUnvalidated .GetAttributesInterface <IValidateHttpRequest>(true, true) .Aggregate <IValidateHttpRequest, ValidateHttpDelegate>( (parameterSelection, methodFinal, httpAppFinal, routeDataFinal) => { return InvokeValidatedMethodAsync( httpAppFinal, routeDataFinal, methodFinal, parameterSelection); }, (callback, validator) => { return (parametersSelected, methodCurrent, httpAppCurrent, requestCurrent) => { return validator.ValidateRequest(parametersSelected, methodCurrent, httpAppCurrent, requestCurrent, callback); }; }) .Invoke( parameterSelectionUnvalidated, methodFinalUnvalidated, httpAppFinalUnvalidated, requestFinalUnvalidated); }, (callback, parameterSelection) => { ValidateHttpDelegate boundCallback = (parametersSelected, methodCurrent, httpAppCurrent, requestCurrent) => { var paramKvp = parameterSelection.parameterInfo .PairWithValue(parameterSelection.value); var updatedParameters = parametersSelected .Append(paramKvp) .ToArray(); return callback(updatedParameters, methodCurrent, httpAppCurrent, requestCurrent); }; var validators = parameterSelection.parameterInfo.ParameterType .GetAttributesInterface <IValidateHttpRequest>(true, true); if (!validators.Any()) { return boundCallback; } var validator = validators.First(); return (parametersSelected, methodCurrent, httpAppCurrent, requestCurrent) => { return validator.ValidateRequest(parametersSelected, methodCurrent, httpAppCurrent, requestCurrent, boundCallback); }; }) .Invoke( new KeyValuePair <ParameterInfo, object>[] { }, methodCast.method, httpApp, routeData); }, () => { return Issues(evaluatedMethods).AsTask(); })); IHttpResponse Issues(IEnumerable <RouteMatch> methodsCasts) { var reasonStrings = methodsCasts .Select( methodCast => { var errorMessage = methodCast.ErrorMessage; return(errorMessage); }) .ToArray(); if (!reasonStrings.Any()) { return(routeData .CreateResponse(System.Net.HttpStatusCode.NotImplemented) .AddReason("No methods that implement Action")); } var content = reasonStrings.Join(";"); return(routeData .CreateResponse(System.Net.HttpStatusCode.NotImplemented) .AddReason(content)); } }
public async Task <IHttpResponse> ParseContentValuesAsync( IApplication httpApp, IHttpRequest request, Func < CastDelegate, string[], Task <IHttpResponse> > onParsedContentValues) { if (!request.HasBody) { return(await BodyMissing("Body was not provided")); } var contentString = await request.ReadContentAsStringAsync(); if (contentString.IsNullOrWhiteSpace()) { return(await BodyMissing("XML body content was empty")); } var xmldoc = new XmlDocument(); var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, // prevents XXE attacks, such as Billion Laughs MaxCharactersFromEntities = 1024, XmlResolver = null, // prevents external entity DoS attacks, such as slow loading links or large file requests }; try { using (var strReader = new StringReader(contentString)) using (var xmlReader = XmlReader.Create(strReader, settings)) { xmldoc.Load(xmlReader); } } catch (Exception ex) { return(await BodyMissing(ex.Message)); } CastDelegate parser = (paramInfo, onParsed, onFailure) => { return(paramInfo .GetAttributeInterface <IBindXmlApiValue>() .ParseContentDelegate(xmldoc, contentString, paramInfo, httpApp, request, onParsed, onFailure)); }; return(await onParsedContentValues(parser, new string[] { })); Task <IHttpResponse> BodyMissing(string failureMessage) { CastDelegate emptyParser = (paramInfo, onParsed, onFailure) => { var key = paramInfo .GetAttributeInterface <IBindApiValue>() .GetKey(paramInfo) .ToLower(); var type = paramInfo.ParameterType; return(onFailure($"XML [{key}] could not be parsed ({failureMessage}).")); }; var exceptionKeys = new string[] { }; return(onParsedContentValues(emptyParser, exceptionKeys)); } }
//---------------------------------------------------------------Casting public void AddCastIntrinsics(ShaderType castToType, ShaderType castFromType, CastDelegate castDelegate) { var tuple = new Tuple <ShaderType, ShaderType>(castToType, castFromType); CastIntrinsics.Add(tuple, castDelegate); }
public RouteMatch IsRouteMatch( MethodInfo method, string[] componentsMatched, IInvokeResource resourceInvoker, IHttpRequest request, IApplication httpApp, IEnumerable <string> bodyKeys, CastDelegate fetchBodyParam) { var fileNameCastDelegate = GetFileNameCastDelegate(request, httpApp, componentsMatched, out string[] pathKeys); var fetchQueryParam = GetQueryCastDelegate(request, httpApp, out string[] queryKeys); var parametersCastResults = method .GetParameters() .Where(param => param.ContainsAttributeInterface <IBindApiValue>()) .Select( (param) => { var castValue = param.GetAttributeInterface <IBindApiValue>(); var bindingData = new BindingData { httpApp = httpApp, fetchDefaultParam = fileNameCastDelegate, fetchQueryParam = fetchQueryParam, fetchBodyParam = fetchBodyParam, method = method, parameterRequiringValidation = param, request = request, resourceInvoker = resourceInvoker, }; return(castValue.TryCast(bindingData)); }) .ToArray(); var failedValidations = parametersCastResults .Where(pcr => !pcr.valid) .ToArray(); return(HasExtraParameters(method, pathKeys, queryKeys, bodyKeys, parametersCastResults, () => { if (failedValidations.Any()) { return new RouteMatch { isValid = false, failedValidations = failedValidations, method = method, }; } //var parametersWithValues = parametersCastResults // .Select(parametersCastResult => // parametersCastResult.parameterInfo.PairWithValue(parametersCastResult.value)) // .ToArray(); return new RouteMatch { isValid = true, method = method, parametersWithValues = parametersCastResults, }; }, (extraFileParams, extraQueryParams, extraBodyParams) => { return new RouteMatch { isValid = false, failedValidations = failedValidations, method = method, extraFileParams = extraFileParams, extraQueryParams = extraQueryParams, extraBodyParams = extraBodyParams, }; })); }
public async Task <IHttpResponse> ParseContentValuesAsync( IApplication httpApp, IHttpRequest request, Func < CastDelegate, string[], Task <IHttpResponse> > onParsedContentValues) { if (!request.HasBody) { return(await BodyMissing("Body was not provided")); } var contentString = await request.ReadContentAsStringAsync(); if (contentString.IsNullOrWhiteSpace()) { return(await BodyMissing("JSON body content is empty")); } var bindConvert = new BindConvert(request, httpApp as HttpApplication); try { var contentJObject = Newtonsoft.Json.Linq.JObject.Parse(contentString); CastDelegate parser = (paramInfo, onParsed, onFailure) => { return(paramInfo .GetAttributeInterface <IBindJsonApiValue>() .ParseContentDelegate(contentJObject, contentString, bindConvert, paramInfo, httpApp, request, onParsed, onFailure)); }; var keys = contentJObject .Properties() .Select(jProperty => jProperty.Name) .ToArray(); return(await onParsedContentValues(parser, keys)); } catch (Newtonsoft.Json.JsonReaderException) { try { var contentJArray = Newtonsoft.Json.Linq.JArray.Parse(contentString); CastDelegate parser = (paramInfo, onParsed, onFailure) => { return(paramInfo .GetAttributeInterface <IBindJsonApiValue>() .ParseContentDelegate(contentJArray, contentString, bindConvert, paramInfo, httpApp, request, onParsed, onFailure)); }; var keys = new string[] { }; return(await onParsedContentValues(parser, keys)); } catch (Exception ex) { return(await BodyMissing(ex.Message)); } } catch (Exception ex) { return(await BodyMissing(ex.Message)); } Task <IHttpResponse> BodyMissing(string failureMessage) { CastDelegate emptyParser = (paramInfo, onParsed, onFailure) => { var key = paramInfo .GetAttributeInterface <IBindApiValue>() .GetKey(paramInfo) .ToLowerNullSafe(); var type = paramInfo.ParameterType; return(onFailure($"[{key}] could not be parsed ({failureMessage}).")); }; var exceptionKeys = new string[] { }; return(onParsedContentValues(emptyParser, exceptionKeys)); } }