public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     // Maybe the parameter is a key parameter, e.g., where Id in the URI path maps to a parameter named 'key'
     if (swaggerParameter.description != null && swaggerParameter.description.StartsWith("key:"))
     {
         // Find either a single 'key' in the route or composite keys
         // which take the form of key<parameter name>
         var keyParameterName = swaggerParameter
                                 .description
                                 .Replace(FindKeyReplacementSubStr, 
                                             String.Empty)
                                 .ToLower();
         var parameterDescriptor = 
             actionDescriptor
                 .GetParameters()?
                 .SingleOrDefault(descriptor =>
                     descriptor.ParameterName.ToLower() == KeyName
                     || descriptor.ParameterName.ToLower().Equals(keyParameterName)
                 );
         if (parameterDescriptor != null && !parameterDescriptor.IsODataLibraryType())
         {
             var httpControllerDescriptor = actionDescriptor.ControllerDescriptor;
             Contract.Assume(httpControllerDescriptor != null);
             return new ODataParameterDescriptor(swaggerParameter.name, parameterDescriptor.ParameterType, parameterDescriptor.IsOptional, parameterDescriptor)
             {
                 Configuration = httpControllerDescriptor.Configuration,
                 ActionDescriptor = actionDescriptor,
                 ParameterBinderAttribute = parameterDescriptor.ParameterBinderAttribute
             };
         }
     }
     return null;
 }
        private IList<ApiParameterDescription> CreateParameterDescription(HttpActionBinding actionBinding,HttpActionDescriptor actionDescriptor)
        {
            IList<ApiParameterDescription> parameterDescriptions = new List<ApiParameterDescription>();
            // try get parameter binding information if available
            if (actionBinding != null)
            {
                HttpParameterBinding[] parameterBindings = actionBinding.ParameterBindings;
                if (parameterBindings != null)
                {
                    foreach (HttpParameterBinding parameter in parameterBindings)
                    {
                        parameterDescriptions.Add(CreateParameterDescriptionFromBinding(parameter));
                    }
                }
            }
            else
            {
                Collection<HttpParameterDescriptor> parameters = actionDescriptor.GetParameters();
                if (parameters != null)
                {
                    foreach (HttpParameterDescriptor parameter in parameters)
                    {
                        parameterDescriptions.Add(CreateParameterDescriptionFromDescriptor(parameter));
                    }
                }
            }

            return parameterDescriptions;
        }
		internal static bool ActionHasChangeSetEntityParameter(HttpActionDescriptor actionDescriptor)
		{
			Contract.Assert(actionDescriptor != null);

			var parameters = actionDescriptor.GetParameters();
			return (parameters.Count > 0) && IsChangeSetEntityParameter(parameters[0]);
		}
        private IDictionary<string, object> GetParameterValuePairs(HttpActionDescriptor actionDescriptor)
        {
            IDictionary<string, object> parameterValuePairs = new Dictionary<string, object>();

            foreach (SwaggerDefaultValue defaultValue in actionDescriptor.GetCustomAttributes<SwaggerDefaultValue>())
            {
                parameterValuePairs.Add(defaultValue.Name, defaultValue.Value);
            }

            foreach (var parameter in actionDescriptor.GetParameters())
            {
                if (!parameter.ParameterType.IsPrimitive)
                {
                    foreach (PropertyInfo property in parameter.ParameterType.GetProperties())
                    {
                        var defaultValue = GetDefaultValue(property);

                        if (defaultValue != null)
                        {
                            parameterValuePairs.Add(property.Name, defaultValue);
                        }
                    }
                }
            }

            return parameterValuePairs;
        }
 public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     var httpParameterDescriptors = actionDescriptor.GetParameters();
     Contract.Assume(httpParameterDescriptors != null);
     return httpParameterDescriptors
         .SingleOrDefault(descriptor => string.Equals(descriptor.ParameterName, swaggerParameter.name, StringComparison.CurrentCultureIgnoreCase));
 }
        /// <summary>
        /// Returns an enumeration of filters.
        /// </summary>
        /// <param name="configuration">The HTTP configuration.</param>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <returns>
        /// An enumeration of filters.
        /// </returns>
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor) {
            if (actionDescriptor == null ||
                (!IsIQueryable(actionDescriptor.ReturnType)) ||
                actionDescriptor.GetCustomAttributes<QueryableAttribute>().Any() ||
                actionDescriptor.GetParameters().Any(parameter => typeof (ODataQueryOptions).IsAssignableFrom(parameter.ParameterType)))
                return Enumerable.Empty<FilterInfo>();

            return new[] {new FilterInfo(_filter, FilterScope.Global)};
        }
 private static string ParameterDescriptions(HttpActionDescriptor actionDescripton)
 {
     var description = new StringBuilder();
     foreach (var parameter in actionDescripton.GetParameters())
     {
         description.AppendFormat("{0}:{1}/", parameter.ParameterType, parameter.ParameterName);
     }
     return description.ToString();
 }
        private XPathNavigator GetNodeFor(HttpActionDescriptor actionDescriptor)
        {
            var controllerName = actionDescriptor.ControllerDescriptor.ControllerType.FullName;
            var actionName = actionDescriptor.ActionName;
            var parameters = String.Join(",", actionDescriptor.GetParameters()
                .Select(paramDesc => TypeNameFor(paramDesc.ParameterType)));

            var xpath = String.Format(MethodExpression, controllerName, actionName, parameters);
            return _navigator.SelectSingleNode(xpath);
        }
        public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
        {
            Contract.Requires(swaggerParameter != null);
            Contract.Requires(parameterIndex >= 0);
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(actionDescriptor.GetParameters() != null);
            //Contract.Ensures(Contract.Result<HttpParameterDescriptor>() == null || Contract.Result<HttpParameterDescriptor>().Configuration != null);

            throw new NotImplementedException();
        }
 public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     if ([email protected] != "query" && parameterIndex < actionDescriptor.GetParameters().Count)
     {
         var parameterDescriptor = actionDescriptor.GetParameters()[parameterIndex];
         if (parameterDescriptor != null && !parameterDescriptor.IsODataLibraryType())
         {
             var httpControllerDescriptor = actionDescriptor.ControllerDescriptor;
             Contract.Assume(httpControllerDescriptor != null);
             return new ODataParameterDescriptor(swaggerParameter.name, parameterDescriptor.ParameterType, parameterDescriptor.IsOptional, parameterDescriptor)
             {
                 Configuration = httpControllerDescriptor.Configuration,
                 ActionDescriptor = actionDescriptor,
                 ParameterBinderAttribute = parameterDescriptor.ParameterBinderAttribute
             };
         }
     }
     return null;
 }
        public static string ActionDescriptorToString(HttpActionDescriptor actionDescriptor)
        {
            Contract.Assert(actionDescriptor != null);

            string parameterList = String.Join(", ",
                                               actionDescriptor.GetParameters().Select<HttpParameterDescriptor, string>(
                                                   (p) => p.ParameterType.Name + " " + p.ParameterName));

            return actionDescriptor.ActionName + "(" + parameterList + ")";
        }
Example #12
0
        public override HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor)
        {
            var actionBinding = new MvcActionBinding();

            HttpParameterDescriptor[] parameters = actionDescriptor.GetParameters().ToArray();
            HttpParameterBinding[] binders = Array.ConvertAll(parameters, DetermineBinding);

            actionBinding.ParameterBindings = binders;

            return actionBinding;
        }
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null ||
              actionDescriptor.GetCustomAttributes<QueryableAttribute>().Any() || // if method already has a QueryableAttribute (or subclass) then skip it.
              actionDescriptor.GetParameters().Any(parameter => typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType))
            )
            {
                return Enumerable.Empty<FilterInfo>();
            }

            return new[] { new FilterInfo(_filter, FilterScope.Global) };
        }
        /// <summary>
        /// Provides filters to apply to the specified action.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="actionDescriptor">The action descriptor for the action to provide filters for.</param>
        /// <returns>
        /// The filters to apply to the specified action.
        /// </returns>
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            // Actions with a bound parameter of type ODataQueryOptions do not support the query filter
            // The assumption is that the action will handle the querying within the action implementation
            if (actionDescriptor != null && IsIQueryable(actionDescriptor.ReturnType) &&
                !actionDescriptor.GetParameters().Any(parameter => typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType)))
            {
                return new FilterInfo[] { new FilterInfo(QueryFilter, FilterScope.Global) };
            }

            return Enumerable.Empty<FilterInfo>();
        }
        private static string GetXPathFor(HttpActionDescriptor actionDescriptor)
        {
            var controllerName = actionDescriptor.ControllerDescriptor.ControllerType.FullName;
            var actionName = actionDescriptor.ActionName;

            var paramTypeNames = actionDescriptor.GetParameters()
                .Select(paramDesc => TypeNameFor(paramDesc.ParameterType))
                .ToArray();

            var parameters = (paramTypeNames.Any())
                ? String.Format("({0})", String.Join(",", paramTypeNames))
                : String.Empty;

            return String.Format(MethodExpression, controllerName, actionName, parameters);
        }
        /// <summary>
        /// Implementation of <see cref="IActionValueBinder"/>, Primary entry point for binding parameters for an action.
        /// </summary>           
        public virtual HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null)
            {
                throw Error.ArgumentNull("actionDescriptor");
            }

            HttpParameterDescriptor[] parameters = actionDescriptor.GetParameters().ToArray();
            HttpParameterBinding[] binders = Array.ConvertAll(parameters, GetParameterBinding);

            HttpActionBinding actionBinding = new HttpActionBinding(actionDescriptor, binders);

            EnsureOneBodyParameter(actionBinding);

            return actionBinding;
        }
        public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
        {
            var required = swaggerParameter.required;
            Contract.Assume(required != null);

            if ([email protected] == "body" && swaggerParameter.schema != null && swaggerParameter.schema.type == "object")
            {
                var odataActionParametersDescriptor = actionDescriptor.GetParameters().SingleOrDefault(descriptor => descriptor.ParameterType == typeof (ODataActionParameters));
                Contract.Assume(odataActionParametersDescriptor != null);
                return new ODataActionParameterDescriptor(odataActionParametersDescriptor.ParameterName, typeof(ODataActionParameters), !required.Value, swaggerParameter.schema, odataActionParametersDescriptor)
                {
                    Configuration = actionDescriptor.ControllerDescriptor.Configuration,
                    ActionDescriptor = actionDescriptor
                };
            }
            return null;
        }
        /// <summary>
        /// Provides filters to apply to the specified action.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="actionDescriptor">The action descriptor for the action to provide filters for.</param>
        /// <returns>
        /// The filters to apply to the specified action.
        /// </returns>
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            // Actions with a bound parameter of type ODataQueryOptions do not support the query filter
            // The assumption is that the action will handle the querying within the action implementation

            // Skip actions that contain QueryableAttribute as it causes problems in some scenarios. See
            // #2047 for details.
            if (actionDescriptor != null &&
                !(_skipQueryableAttribute && HasQueryableAttribute(actionDescriptor)) &&
                (IsIQueryable(actionDescriptor.ReturnType) || typeof(SingleResult).IsAssignableFrom(actionDescriptor.ReturnType)) &&
                !actionDescriptor.GetParameters().Any(parameter => typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType)))
            {
                return new FilterInfo[] { new FilterInfo(QueryFilter, FilterScope.Global) };
            }

            return Enumerable.Empty<FilterInfo>();
        }
		private static string XPathFor(HttpActionDescriptor actionDescriptor)
        {
            var controllerName = actionDescriptor.ControllerDescriptor.ControllerType.FullName;
            var reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
            var actionName = (reflectedActionDescriptor != null)
                ? reflectedActionDescriptor.MethodInfo.Name
                : actionDescriptor.ActionName;

            var paramTypeNames = actionDescriptor.GetParameters()
                .Select(paramDesc => paramDesc.ParameterType.XmlCommentsId())
                .ToArray();

            var parameters = (paramTypeNames.Any())
                ? String.Format("({0})", String.Join(",", paramTypeNames))
                : String.Empty;

            return String.Format(MethodExpression, controllerName, actionName, parameters);
        }
 public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     // Maybe the parameter is a key parameter, e.g., where Id in the URI path maps to a parameter named 'key'
     if (swaggerParameter.description != null && swaggerParameter.description.StartsWith("key:"))
     {
         var parameterDescriptor = actionDescriptor.GetParameters()?.SingleOrDefault(descriptor => descriptor.ParameterName == "key");
         if (parameterDescriptor != null && !parameterDescriptor.IsODataLibraryType())
         {
             var httpControllerDescriptor = actionDescriptor.ControllerDescriptor;
             Contract.Assume(httpControllerDescriptor != null);
             return new ODataParameterDescriptor(swaggerParameter.name, parameterDescriptor.ParameterType, parameterDescriptor.IsOptional, parameterDescriptor)
             {
                 Configuration = httpControllerDescriptor.Configuration,
                 ActionDescriptor = actionDescriptor,
                 ParameterBinderAttribute = parameterDescriptor.ParameterBinderAttribute
             };
         }
     }
     return null;
 }
		public static void PrepareByOptionAttribute(ResourceApi resource, HttpActionDescriptor actionDescriptor)
		{
			var parameters = actionDescriptor.GetParameters();

			foreach (var p in parameters)
			{
				var attributes = p.GetCustomAttributes<SwaggerOptionsAttribute>();

				if (attributes.Count > 0)
				{
					var att = attributes[0] as SwaggerOptionsAttribute;

					if (!String.IsNullOrWhiteSpace(att.Name))
					{
						resource.path = resource.path.Replace(
							String.Format(CultureInfo.InvariantCulture, "{{{0}}}", p.ParameterName), 
							String.Format(CultureInfo.InvariantCulture, "{{{0}}}", att.Name));
					}
				}
			}
		}	
		/// <summary>
		/// Determines the relative order of an action - used to select the lowest priority action in <see cref="SelectAction"/>.
		/// </summary>
		/// <param name="actionDescriptor"></param>
		/// <returns></returns>
		private static int DetermineActionOrder(HttpActionDescriptor actionDescriptor)
		{
			// Hard-coded rule: An action with first parameter "TEntity entity" is order 1
			// All others are order 2
			var parameters = actionDescriptor.GetParameters();
			if (parameters.Count >= 1)
			{
				if (ChangeSetEntityModelBinder.IsChangeSetEntityParameter(parameters[0]))
				{
					// Takes precedence
					return 1;
				}
			}

			return 2;
		}
 private IEnumerable<HttpActionRequestParameterDocumentation> CreateHttpActionRequestParameters(HttpActionDescriptor httpActionDescriptor, HttpActionDocumentationMetadata actionDocumentationMetadata)
 {
     return
         from parameterDescriptor in httpActionDescriptor.GetParameters()
         where parameterDescriptor.ParameterBinderAttribute is FromUriAttribute || TypeHelper.CanConvertFromString(parameterDescriptor.ParameterType)
         let parameterDescription =
             actionDocumentationMetadata.HttpActionParameters
                                        .Any(parameterDocumentation =>
                                             parameterDocumentation.Name.Equals(parameterDescriptor.ParameterName) &&
                                             parameterDocumentation.Type.Equals(parameterDescriptor.ParameterType))
                 ? actionDocumentationMetadata.HttpActionParameters
                                              .Single(parameterDocumentation =>
                                                      parameterDocumentation.Name.Equals(parameterDescriptor.ParameterName) &&
                                                      parameterDocumentation.Type.Equals(parameterDescriptor.ParameterType)).Description
                 : String.Empty
         select new HttpActionRequestParameterDocumentation(
             parameterDescriptor.ParameterName,
             GetProperyTypeName(parameterDescriptor.ParameterType),
             parameterDescription,
             !parameterDescriptor.IsOptional);
 }
        private void InvokeAction(HttpActionDescriptor action, object[] parameters, ChangeSetEntry changeSetEntry)
        {
            try
            {
                Collection<HttpParameterDescriptor> pds = action.GetParameters();
                Dictionary<string, object> paramMap = new Dictionary<string, object>(pds.Count);
                for (int i = 0; i < pds.Count; i++)
                {
                    paramMap.Add(pds[i].ParameterName, parameters[i]);
                }

                // TODO this method is not correctly observing the execution results, the catch block below is wrong. 385801
                action.ExecuteAsync(ActionContext.ControllerContext, paramMap);
            }
            catch (TargetInvocationException tie)
            {
                ValidationException vex = tie.GetBaseException() as ValidationException;
                if (vex != null)
                {
                    ValidationResultInfo error = new ValidationResultInfo(vex.Message, 0, String.Empty, vex.ValidationResult.MemberNames);
                    if (changeSetEntry.ValidationErrors != null)
                    {
                        changeSetEntry.ValidationErrors = changeSetEntry.ValidationErrors.Concat(new ValidationResultInfo[] { error }).ToArray();
                    }
                    else
                    {
                        changeSetEntry.ValidationErrors = new ValidationResultInfo[] { error };
                    }
                }
                else
                {
                    throw;
                }
            }
        }
        private void InvokeAction(HttpActionDescriptor action, object[] parameters, ChangeSetEntry changeSetEntry)
        {
            try
            {
                Collection<HttpParameterDescriptor> pds = action.GetParameters();
                Dictionary<string, object> paramMap = new Dictionary<string, object>(pds.Count);
                for (int i = 0; i < pds.Count; i++)
                {
                    paramMap.Add(pds[i].ParameterName, parameters[i]);
                }

                // TODO - Issue #103
                // This method is not correctly observing the execution results, the catch block below is wrong.
                // Submit should be Task<bool>, not bool, and should model bind for the CancellationToken which would then
                // be propagated through to all the helper methods (one or more of which might also need to be made async,
                // once we start respecting the fact that the read/write actions should be allowed to be async).
                action.ExecuteAsync(ActionContext.ControllerContext, paramMap, CancellationToken.None);
            }
            catch (TargetInvocationException tie)
            {
                ValidationException vex = tie.GetBaseException() as ValidationException;
                if (vex != null)
                {
                    ValidationResultInfo error = new ValidationResultInfo(vex.Message, 0, String.Empty, vex.ValidationResult.MemberNames);
                    if (changeSetEntry.ValidationErrors != null)
                    {
                        changeSetEntry.ValidationErrors = changeSetEntry.ValidationErrors.Concat(new ValidationResultInfo[] { error }).ToArray();
                    }
                    else
                    {
                        changeSetEntry.ValidationErrors = new ValidationResultInfo[] { error };
                    }
                }
                else
                {
                    throw;
                }
            }
        }
 public ActionSelectionInfo(HttpActionDescriptor descriptor)
 {
     ActionName = descriptor.ActionName;
     SupportedHttpMethods = descriptor.SupportedHttpMethods.ToArray();
     Parameters = descriptor.GetParameters().Select(p => new HttpParameterDescriptorInfo(p)).ToArray();
 }
 private HttpActionRequestDocumentation CreateDefaultRequestDocumentation(HttpActionDescriptor actionDescriptor)
 {
     return new HttpActionRequestDocumentation(
         actionDescriptor.GetParameters()
                         .Where(p => p.ParameterBinderAttribute is FromUriAttribute || TypeHelper.CanConvertFromString(p.ParameterType))
                         .Select(p => new HttpActionRequestParameterDocumentation(p.ParameterName, GetProperyTypeName(p.ParameterType), String.Empty, !p.IsOptional)),
         CreateHttpActionRequestBody(actionDescriptor));
 }