Esempio n. 1
0
		public async Task<MapResult> MapAsync(HttpContextBase context, Type type, MethodInfo method, ParameterInfo parameter)
		{
			context.ThrowIfNull("context");
			type.ThrowIfNull("type");
			method.ThrowIfNull("method");
			parameter.ThrowIfNull("parameter");

			Type parameterType = parameter.ParameterType;
			object model = _container != null ? _container.GetInstance(parameterType) : Activator.CreateInstance(parameterType);
			Type modelType = model.GetType();

			foreach (PropertyInfo property in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
			{
				object mappedValue = await GetMappedValueAsync(context, modelType, property);

				if (mappedValue == null)
				{
					throw new ApplicationException(String.Format("Unable to map property '{0} {1}' of type '{2}'.", property.PropertyType.FullName, property.Name, modelType.FullName));
				}

				property.SetValue(model, mappedValue, null);
			}

			return MapResult.ValueMapped(model);
		}
Esempio n. 2
0
        public IdResult Map(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            return IdResult.IdMapped(_guidFactory.Random());
        }
		public Task<MapResult> MapAsync(HttpContextBase context, Type type, MethodInfo method, ParameterInfo parameter)
		{
			context.ThrowIfNull("request");
			type.ThrowIfNull("type");
			method.ThrowIfNull("method");
			parameter.ThrowIfNull("parameter");

			Type parameterType = parameter.ParameterType;
			var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
			string json = reader.ReadToEnd();
			object jsonModel;

			try
			{
				jsonModel = JsonConvert.DeserializeObject(json, parameterType, _serializerSettings);
			}
			catch (Exception exception)
			{
				if (_errorHandling == DataConversionErrorHandling.ThrowException)
				{
					throw new ApplicationException(String.Format("Request content could not be deserialized to '{0}'.", parameterType.FullName), exception);
				}
				jsonModel = parameterType.GetDefaultValue();
			}

			return MapResult.ValueMapped(jsonModel).AsCompletedTask();
		}
        public Task<bool> MustAuthenticateAsync(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            return method.GetCustomAttributes(typeof(AuthenticateAttribute), false).Any().AsCompletedTask();
        }
        public bool MustAuthenticate(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            return method.GetCustomAttributes(typeof(AuthenticateAttribute), false).Any();
        }
		public async Task<IEnumerable<object>> GetParameterValuesAsync(HttpContextBase context, Type type, MethodInfo method)
		{
			context.ThrowIfNull("context");
			type.ThrowIfNull("type");
			method.ThrowIfNull("method");

			ParameterInfo[] parameterInfos = method.GetParameters();
			var parameterValues = new List<object>();

			foreach (ParameterInfo parameterInfo in parameterInfos)
			{
				Type parameterType = parameterInfo.ParameterType;
				string parameterName = parameterInfo.Name;
				Type currentParameterType = parameterType;

				do
				{
					bool mapped = false;

					foreach (IParameterMapper parameterMapper in _parameterMappers)
					{
						if (!await parameterMapper.CanMapTypeAsync(context, parameterType))
						{
							continue;
						}
						MapResult mapResult = await parameterMapper.MapAsync(context, type, method, parameterInfo);

						if (mapResult.ResultType == MapResultType.ValueNotMapped)
						{
							continue;
						}

						parameterValues.Add(mapResult.Value);
						mapped = true;
						break;
					}
					if (mapped)
					{
						break;
					}

					currentParameterType = currentParameterType.BaseType;
				} while (currentParameterType != null);

				if (currentParameterType == null)
				{
					throw new ApplicationException(
						String.Format(
							"No request parameter mapper was found for parameter '{0} {1}' of {2}.{3}.",
							parameterType.FullName,
							parameterName,
							type.FullName,
							method.Name));
				}
			}

			return parameterValues;
		}
Esempio n. 7
0
        public void Map(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            route.RespondWithNoContent();
        }
        public Task<MapResult> MapAsync(HttpContextBase context, Type type, MethodInfo method, ParameterInfo parameter)
        {
            context.ThrowIfNull("context");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            parameter.ThrowIfNull("parameter");

            return MapResult.ValueMapped(context.Server).AsCompletedTask();
        }
        public Task<NameResult> MapAsync(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            NameAttribute attribute = method.GetCustomAttributes(typeof(NameAttribute), false).Cast<NameAttribute>().SingleOrDefault();

            return (attribute != null ? NameResult.NameMapped(attribute.Name) : NameResult.NameNotMapped()).AsCompletedTask();
        }
        public Task<IdResult> MapAsync(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            IdAttribute attribute = method.GetCustomAttributes(typeof(IdAttribute), false).Cast<IdAttribute>().SingleOrDefault();

            return (attribute != null ? IdResult.IdMapped(attribute.Id) : IdResult.IdNotMapped()).AsCompletedTask();
        }
Esempio n. 11
0
        public MapResult Map(HttpRequestBase request, Type type, MethodInfo method, ParameterInfo parameter)
        {
            request.ThrowIfNull("request");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            parameter.ThrowIfNull("parameter");

            return MapResult.ValueMapped(parameter.ParameterType.GetDefaultValue());
        }
Esempio n. 12
0
 public virtual MethodInfo GetControllerMethod(string methodName)
 {
     methodName = _namingConvention.GetMethodInfoByMethodNameFromInstance(_BusinessInstance, methodName);
     if (_requestedMethod == null)
     {
         _requestedMethod = _BusinessInstance.GetType().GetMethod(methodName);
         _requestedMethod.ThrowIfNull("methodInfo");
     }
     return _requestedMethod;
 }
        public ResolvedRelativeUrlResult Map(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            ResolvedRelativeUrlAttribute attribute = method.GetCustomAttributes(typeof(ResolvedRelativeUrlAttribute), false).Cast<ResolvedRelativeUrlAttribute>().SingleOrDefault();

            return attribute != null
                       ? ResolvedRelativeUrlResult.ResolvedRelativeUrlMapped(attribute.ResolvedRelativeUrl)
                       : ResolvedRelativeUrlResult.ResolvedRelativeUrlNotMapped();
        }
Esempio n. 14
0
        public Task MapAsync(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            route.RespondWithNoContent();

            return Task.Factory.Empty();
        }
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            IEnumerable<RelativeUrlResolverAttribute> attributes = method.GetCustomAttributes<RelativeUrlResolverAttribute>(false);

            foreach (RelativeUrlResolverAttribute attribute in attributes)
            {
                attribute.Map(route, container);
            }
        }
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            HttpMethod httpMethod;

            if (Enum<HttpMethod>.TryParse(method.Name, true, out httpMethod))
            {
                route.RestrictByMethods(httpMethod);
            }
        }
		public Task MapAsync(Type type, MethodInfo method, Routing.Route route, IContainer container)
		{
			type.ThrowIfNull("type");
			method.ThrowIfNull("method");
			route.ThrowIfNull("route");
			container.ThrowIfNull("container");

			HttpMethod httpMethod;
			string methodName = method.Name.TrimEnd("Async");

			if (Enum<HttpMethod>.TryParse(methodName, true, out httpMethod))
			{
				route.RestrictByMethods(httpMethod);
			}

			return Task.Factory.Empty();
		}
        public ResolvedRelativeUrlResult Map(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            if (!type.NamespaceStartsWith(_rootNamespace))
            {
                return ResolvedRelativeUrlResult.ResolvedRelativeUrlNotMapped();
            }

            var pathParts = new List<string>();
            string relativeNamespace = Regex.Replace(type.Namespace, String.Format(@"^{0}\.?(?<RelativeNamespace>.*)", Regex.Escape(_rootNamespace)), "${RelativeNamespace}");

            pathParts.AddRange(ParseWords(relativeNamespace));
            pathParts.AddRange(ParseWords(type.Name));
            string resolvedRelativeUrl = String.Join("/", pathParts);

            return ResolvedRelativeUrlResult.ResolvedRelativeUrlMapped(resolvedRelativeUrl);
        }
        public NameResult Map(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            if (!type.NamespaceStartsWith(_rootNamespace))
            {
                return NameResult.NameNotMapped();
            }

            var pathParts = new List<string>();
            string relativeNamespace = Regex.Replace(type.Namespace, String.Format(@"^{0}\.?(?<RelativeNamespace>.*)", Regex.Escape(_rootNamespace)), "${RelativeNamespace}");

            pathParts.AddRange(ParseWords(relativeNamespace));
            pathParts.AddRange(ParseWords(type.Name));
            string name = String.Join(_wordSeparator, pathParts);

            return NameResult.NameMapped(name);
        }
        public void Map(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            if (method.ReturnType == typeof(void))
            {
                route.RespondWithNoContent();
                return;
            }
            if (!method.ReturnType.ImplementsInterface<IResponse>())
            {
                throw new ApplicationException(String.Format("The return type of '{0}.{1}' does not implement '{2}'.", type.FullName, method.Name, typeof(IResponse).Name));
            }

            route.RespondWith(
                request =>
                    {
                        object instance;

                        try
                        {
                            instance = container().GetInstance(type);
                        }
                        catch (Exception exception)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type '{0}'.", type.FullName), exception);
                        }
                        if (instance == null)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type '{0}'.", type.FullName));
                        }

                        var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                        IEnumerable<object> parameterValues = parameterValueRetriever.GetParameterValues(request, type, method);

                        return (IResponse)method.Invoke(instance, parameterValues.ToArray());
                    },
                method.ReturnType);
        }
		public Task<MapResult> MapAsync(HttpContextBase context, Type type, MethodInfo method, ParameterInfo parameter)
		{
			context.ThrowIfNull("context");
			type.ThrowIfNull("type");
			method.ThrowIfNull("method");
			parameter.ThrowIfNull("parameter");

			Type parameterType = parameter.ParameterType;
			string parameterName = parameter.Name;
			string field = context.Request.Form.AllKeys.LastOrDefault(arg => String.Equals(arg, parameterName, _caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));

			if (field == null)
			{
				return MapResult.ValueNotMapped().AsCompletedTask();
			}

			IConvertible value = context.Request.Form[field];
			object convertedValue;

			try
			{
				convertedValue = value.ToType(parameterType, CultureInfo.InvariantCulture);
			}
			catch (Exception exception)
			{
				if (_errorHandling == DataConversionErrorHandling.ThrowException)
				{
					throw new ApplicationException(
						String.Format(
							"Value for form field '{0}' could not be converted to parameter '{1} {2}' of {3}.{4}.",
							field,
							parameterType.FullName,
							parameterName,
							type.FullName,
							method.Name),
						exception);
				}
				convertedValue = parameterType.GetDefaultValue();
			}

			return MapResult.ValueMapped(convertedValue).AsCompletedTask();
		}
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (!type.NamespaceStartsWith(_rootNamespace))
            {
                return;
            }

            var pathParts = new List<string>();
            string relativeNamespace = Regex.Replace(type.Namespace, String.Format(@"^{0}\.?(?<RelativeNamespace>.*)", Regex.Escape(_rootNamespace)), "${RelativeNamespace}");

            pathParts.AddRange(ParseWords(relativeNamespace));
            pathParts.AddRange(ParseWords(type.Name));
            string relativePath = String.Join("/", pathParts);
            var httpRuntime = container.GetInstance<IHttpRuntime>();

            route.RestrictByUrlRelativePath(relativePath, _caseSensitive ? (IRequestValueComparer)CaseSensitivePlainComparer.Instance : CaseInsensitivePlainComparer.Instance, httpRuntime);
        }
Esempio n. 23
0
        public MapResult Map(HttpRequestBase request, Type type, MethodInfo method, ParameterInfo parameter)
        {
            request.ThrowIfNull("request");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            parameter.ThrowIfNull("parameter");

            Type parameterType = parameter.ParameterType;
            object model = _container != null ? _container.GetInstance(parameterType) : Activator.CreateInstance(parameterType);
            Type modelType = model.GetType();

            foreach (PropertyInfo property in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                PropertyInfo closureProperty = property;
                var mappedValue = _modelPropertyMappers
                    .Select(arg => new { Mapper = arg, MapResult = arg.Map(request, modelType, closureProperty) })
                    .FirstOrDefault(arg => arg.MapResult.ResultType == MapResultType.ValueMapped);

                if (mappedValue == null)
                {
                    throw new ApplicationException(String.Format("Unable to map property '{0} {1}' of type '{2}'.", property.PropertyType.FullName, property.Name, modelType.FullName));
                }

                property.SetValue(model, mappedValue.MapResult.Value, null);
            }

            return MapResult.ValueMapped(model);
        }
Esempio n. 24
0
 public string GetMethodNameByMethodInfo(MethodInfo method)
 {
     method.ThrowIfNull("method");
     return method.Name;
 }
Esempio n. 25
0
        public Task<bool> MatchesAsync(MethodInfo method)
        {
            method.ThrowIfNull("method");

            return _matchDelegate(method).AsCompletedTask();
        }
Esempio n. 26
0
        public bool Matches(MethodInfo method)
        {
            method.ThrowIfNull("method");

            return _matchDelegate(method);
        }
        public Task MapAsync(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            bool methodReturnTypeImplementsIResponse = method.ReturnType.ImplementsInterface<IResponse>();
            bool methodReturnTypeIsTaskT = method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>);
            bool methodReturnTypeIsVoid = method.ReturnType == typeof(void);

            if (methodReturnTypeImplementsIResponse)
            {
                ParameterInfo[] parameterInfos = method.GetParameters();
                ParameterExpression instanceParameterExpression = Expression.Parameter(typeof(object), "instance");
                ParameterExpression parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                UnaryExpression unaryExpression =
                    Expression.Convert(
                        Expression.Call(
                            Expression.Convert(instanceParameterExpression, type),
                            method,
                            parameterInfos.Select((arg, index) => Expression.Convert(
                                Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                                arg.ParameterType))),
                        typeof(IResponse));
                Func<object, object[], IResponse> @delegate = Expression.Lambda<Func<object, object[], IResponse>>(unaryExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWith(
                    async context =>
                    {
                        object instance;

                        try
                        {
                            instance = container().GetInstance(type);
                        }
                        catch (Exception exception)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                        }
                        if (instance == null)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                        }

                        var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                        object[] parameterValues = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();
                        var mappedDelegateContexts = new List<IMappedDelegateContext>();

                        try
                        {
                            mappedDelegateContexts.AddRange(_contextFactories.Select(arg => arg.CreateContext(context, type, method)).Where(arg => arg != null));

                            IResponse response = @delegate(instance, parameterValues);

                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Complete();
                            }

                            return response;
                        }
                        finally
                        {
                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Dispose();
                            }
                        }
                    },
                    method.ReturnType);
            }
            else if (methodReturnTypeIsTaskT)
            {
                ParameterInfo[] parameterInfos = method.GetParameters();
                ParameterExpression instanceParameterExpression = Expression.Parameter(typeof(object), "instance");
                ParameterExpression parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                Type methodGenericArgumentType = method.ReturnType.GetGenericArguments()[0];
                MethodInfo upcastMethodInfo = typeof(TaskExtensions)
                    .GetMethod("Upcast", BindingFlags.Static | BindingFlags.Public)
                    .MakeGenericMethod(methodGenericArgumentType, typeof(IResponse));
                UnaryExpression unaryExpression =
                    Expression.Convert(
                        Expression.Call(
                            upcastMethodInfo,
                            Expression.Call(
                                Expression.Convert(instanceParameterExpression, type),
                                method,
                                parameterInfos.Select((arg, index) => Expression.Convert(
                                    Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                                    arg.ParameterType)))),
                        upcastMethodInfo.ReturnType);
                Func<object, object[], Task<IResponse>> @delegate = Expression.Lambda<Func<object, object[], Task<IResponse>>>(unaryExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWith(
                    async context =>
                    {
                        object instance;

                        try
                        {
                            instance = container().GetInstance(type);
                        }
                        catch (Exception exception)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                        }
                        if (instance == null)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                        }

                        var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                        object[] parameterValues = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();
                        var mappedDelegateContexts = new List<IMappedDelegateContext>();

                        try
                        {
                            mappedDelegateContexts.AddRange(_contextFactories.Select(arg => arg.CreateContext(context, type, method)).Where(arg => arg != null));

                            IResponse response = await @delegate(instance, parameterValues);

                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Complete();
                            }

                            return response;
                        }
                        finally
                        {
                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Dispose();
                            }
                        }
                    },
                    methodGenericArgumentType);
            }
            else if (methodReturnTypeIsVoid)
            {
                ParameterInfo[] parameterInfos = method.GetParameters();
                ParameterExpression instanceParameterExpression = Expression.Parameter(typeof(object), "instance");
                ParameterExpression parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                MethodCallExpression methodCallExpression =
                    Expression.Call(
                        Expression.Convert(instanceParameterExpression, type),
                        method,
                        parameterInfos.Select((arg, index) => Expression.Convert(
                            Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                            arg.ParameterType)));
                Action<object, object[]> @delegate = Expression.Lambda<Action<object, object[]>>(methodCallExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWithNoContent(
                    async context =>
                    {
                        object instance;

                        try
                        {
                            instance = container().GetInstance(type);
                        }
                        catch (Exception exception)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                        }
                        if (instance == null)
                        {
                            throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                        }

                        var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                        object[] parameterValues = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();
                        var mappedDelegateContexts = new List<IMappedDelegateContext>();

                        try
                        {
                            mappedDelegateContexts.AddRange(_contextFactories.Select(arg => arg.CreateContext(context, type, method)).Where(arg => arg != null));

                            @delegate(instance, parameterValues);

                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Complete();
                            }
                        }
                        finally
                        {
                            foreach (IMappedDelegateContext mappedDelegateContext in mappedDelegateContexts)
                            {
                                mappedDelegateContext.Dispose();
                            }
                        }
                    });
            }
            else
            {
                throw new ApplicationException(String.Format("The return type of {0}.{1} must implement {2} or be a {3} whose generic type argument implements {2}.", type.FullName, method.Name, typeof(IResponse).Name, typeof(Task<>)));
            }

            return Task.Factory.Empty();
        }