/// <summary> /// Builds a <see cref="ParameterInfo"/> from a reflected <see cref="System.Reflection.ParameterInfo"/>. /// </summary> public static ParameterInfo FromParameter(System.Reflection.ParameterInfo parameter) { return(new ParameterInfo { Name = parameter.Name, IsRemainder = parameter.GetCustomAttribute <RemainderAttribute>() != null, IsParamsArray = parameter.ParameterType.IsArray && parameter.GetCustomAttribute <ParamArrayAttribute>() != null, Type = parameter.ParameterType, DefaultValue = parameter.DefaultValue }); }
public FileTriggerBinding(FilesConfiguration config, ParameterInfo parameter) { _config = config; _parameter = parameter; _attribute = parameter.GetCustomAttribute<FileTriggerAttribute>(inherit: false); _bindingContract = CreateBindingContract(); }
public FileBinding(FilesConfiguration config, ParameterInfo parameter, BindingTemplate bindingTemplate) { _config = config; _parameter = parameter; _bindingTemplate = bindingTemplate; _attribute = _parameter.GetCustomAttribute<FileAttribute>(inherit: false); }
/// <summary> /// Walk from the parameter up to the containing type, looking for a /// <see cref="StorageAccountAttribute"/>. If found, return the account. /// </summary> internal static string GetAccountOverrideOrNull(ParameterInfo parameter) { if (parameter == null || parameter.GetType() == typeof(AttributeBindingSource.FakeParameterInfo)) { return null; } StorageAccountAttribute attribute = parameter.GetCustomAttribute<StorageAccountAttribute>(); if (attribute != null) { return attribute.Account; } attribute = parameter.Member.GetCustomAttribute<StorageAccountAttribute>(); if (attribute != null) { return attribute.Account; } attribute = parameter.Member.DeclaringType.GetCustomAttribute<StorageAccountAttribute>(); if (attribute != null) { return attribute.Account; } return null; }
public async Task RegisterRoute(Uri route, ParameterInfo triggerParameter, ITriggeredFunctionExecutor executor) { await EnsureServerOpen(); string routeKey = route.LocalPath.ToLowerInvariant(); if (_functions.ContainsKey(routeKey)) { throw new InvalidOperationException(string.Format("Duplicate route detected. There is already a route registered for '{0}'", routeKey)); } _functions.AddOrUpdate(routeKey, executor, (k, v) => { return executor; }); WebHookTriggerAttribute attribute = triggerParameter.GetCustomAttribute<WebHookTriggerAttribute>(); IWebHookReceiver receiver = null; string receiverId = string.Empty; string receiverLog = string.Empty; if (attribute != null && _webHookReceiverManager.TryParseReceiver(route.LocalPath, out receiver, out receiverId)) { receiverLog = string.Format(" (Receiver: '{0}', Id: '{1}')", receiver.Name, receiverId); } MethodInfo method = (MethodInfo)triggerParameter.Member; string methodName = string.Format("{0}.{1}", method.DeclaringType, method.Name); _trace.Verbose(string.Format("WebHook route '{0}' registered for function '{1}'{2}", route.LocalPath, methodName, receiverLog)); }
private static object HandleArgumentNotResolved(ParsingContext context, ParameterInfo parameterInfo) { var attribute = parameterInfo.GetCustomAttribute<ArgumentAttribute>(); if(attribute == null) { throw new ArgumentException(string.Format("Could not resolve argument: {0}", parameterInfo.Name)); } var startPosition = context.CurrentPosition; var separatorPosition = attribute.Separator == '\0' ? -1 : context.Packet.Data.DataAsString.IndexOf(attribute.Separator, startPosition); var length = (separatorPosition == -1 ? context.Packet.Data.DataAsString.Length : separatorPosition) - startPosition; var valueToParse = context.Packet.Data.DataAsString.Substring(startPosition, length); context.CurrentPosition += length + 1; switch(attribute.Encoding) { case ArgumentAttribute.ArgumentEncoding.HexNumber: return Parse(parameterInfo.ParameterType, valueToParse, NumberStyles.HexNumber); case ArgumentAttribute.ArgumentEncoding.DecimalNumber: return Parse(parameterInfo.ParameterType, valueToParse); case ArgumentAttribute.ArgumentEncoding.BinaryBytes: return context.Packet.Data.DataAsBinary.Skip(startPosition).ToArray(); case ArgumentAttribute.ArgumentEncoding.HexBytesString: return valueToParse.Split(2).Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray(); default: throw new ArgumentException(string.Format("Unsupported argument type: {0}", parameterInfo.ParameterType.Name)); } }
internal static string GetParameterSoapName(ParameterInfo parameter) { var name = parameter.Name ?? parameter.Member.Name + "Result"; var at = (XmlElementAttribute)parameter.GetCustomAttribute(typeof(XmlElementAttribute)); if (at != null && !string.IsNullOrWhiteSpace(at.ElementName)) name = at.ElementName; return name; }
public FileTriggerBinding(FilesConfiguration config, ParameterInfo parameter, TraceWriter trace) { _config = config; _parameter = parameter; _trace = trace; _attribute = parameter.GetCustomAttribute<FileTriggerAttribute>(inherit: false); _bindingDataProvider = BindingDataProvider.FromTemplate(_attribute.Path); _bindingContract = CreateBindingContract(); }
public ParameterData(ParameterInfo parameterInfo) { Type = parameterInfo.ParameterType; Attribute[] attributes = parameterInfo.GetCustomAttributes(typeof(ServiceKeyAttribute)).ToArray(); if (attributes.Length > 0) ServiceKey = ((ServiceKeyAttribute)attributes.First()).Key; InjectableAttribute = parameterInfo.GetCustomAttribute<InjectableAttribute>(); }
public SyntaxParameter(ParameterInfo parameter) { if (parameter == null) throw new ArgumentNullException("parameter"); Name = parameter.Name; ParameterType = parameter.ParameterType; IsOptional = parameter.IsOptional; IsParams = parameter.GetCustomAttribute<ParamArrayAttribute>() != null; }
protected string BuildParameterDescription(System.Reflection.ParameterInfo parameterInfo) { //get parameter name and attribute string paramName = parameterInfo.Name; SummaryAttribute summAttrib = parameterInfo.GetCustomAttribute(typeof(SummaryAttribute)) as SummaryAttribute; //get parameter template string paramTmpl = _botStrings.getString("common", "parameter_description"); return(String.Format(paramTmpl, paramName, summAttrib.Text)); }
/// <summary> /// Gets a sequence of values that should be tested for the specified parameter. /// </summary> /// <param name="parameter">The parameter to get possible values for.</param> /// <returns>A sequence of values for the parameter.</returns> internal static IEnumerable<object> GetValuesFor(ParameterInfo parameter) { Requires.NotNull(parameter, nameof(parameter)); var valuesAttribute = parameter.GetCustomAttribute<CombinatorialValuesAttribute>(); if (valuesAttribute != null) { return valuesAttribute.Values; } return GetValuesFor(parameter.ParameterType); }
private object Load(HttpApiContext context, ParameterInfo p) { string key = p.Name; var source = ModelSource.FormOrQuery; var ms = p.GetCustomAttribute<ModelSourceAttribute>(); if (ms != null) { source = ms.ModelSource; if (!string.IsNullOrWhiteSpace(ms.Name)) { key = ms.Name; } } var pt = p.ParameterType; object value = LoadValue(context, source, key, pt) ?? p.DefaultValue; if (value == null) { if (pt.IsValueType) return Activator.CreateInstance(pt); if (pt == typeof(string)) return value; if (pt.GetGenericTypeDefinition() == typeof(Nullable<>)) return value; } /// load model from form.. if (source == ModelSource.FormOrQuery) { } else { var model = context.Request.Form["formModel"]; return JsonConvert.DeserializeObject(model, pt); } return value; }
private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState) { var validationAttributes = parameter.CustomAttributes; foreach (var attributeData in validationAttributes) { var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType); var validationAttribute = attributeInstance as ValidationAttribute; if (validationAttribute != null) { var isValid = validationAttribute.IsValid(argument); if (!isValid) { modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name)); } } } }
internal static string GetAccountOverrideOrNull(ParameterInfo parameter) { ServiceBusAccountAttribute attribute = parameter.GetCustomAttribute<ServiceBusAccountAttribute>(); if (attribute != null) { return attribute.Account; } attribute = parameter.Member.GetCustomAttribute<ServiceBusAccountAttribute>(); if (attribute != null) { return attribute.Account; } attribute = parameter.Member.DeclaringType.GetCustomAttribute<ServiceBusAccountAttribute>(); if (attribute != null) { return attribute.Account; } return null; }
/// <summary> /// Tries to get the valid range of a distribution's parameter. /// </summary> /// public static bool TryGetRange(ParameterInfo parameter, out DoubleRange range) { range = new DoubleRange(0, 0); var attrb = parameter.GetCustomAttribute<RangeAttribute>(); if (attrb == null) return false; double min = (double)Convert.ChangeType(attrb.Minimum, typeof(double)); double max = (double)Convert.ChangeType(attrb.Maximum, typeof(double)); range = new DoubleRange(min, max); return true; }
private static ITypeBinder GetParameterBinder(ParameterInfo parameter) { try { var typeBinderAttribute = parameter.GetCustomAttribute<TypeBinderAttribute>(false); return typeBinderAttribute ?? TypeBinderRegistry.GetBinder(parameter.ParameterType); } catch (AmbiguousMatchException) { throw new HttpResponseException(HttpStatusCode.InternalServerError, String.Format(CultureInfo.InvariantCulture, Resources.Global.MultipleTypeBindersPerParameter, parameter.Name, parameter.Member.Name, parameter.Member.DeclaringType != null ? parameter.Member.DeclaringType.Name : String.Empty)); } }
public Parameter(ParameterInfo info) { Name = info.Name; ParameterType = info.ParameterType; var id = info.GetCustomAttribute<IdAttribute>(); if (id == null) throw new Exception("expected an Id() attribute"); Id = id.Id; }
private ParameterBase GetParameter(TypeFormat typeFormat, ParameterInfo parameter, SwaggerWcfParameterAttribute settings, string uriTemplate, IList<Type> definitionsTypesList) { string description = settings != null ? settings.Description : null; bool required = settings != null && settings.Required; string name = parameter.Name; var dataMemberAttribute = parameter.GetCustomAttribute<DataMemberAttribute>(); if (dataMemberAttribute != null && !string.IsNullOrEmpty(dataMemberAttribute.Name)) name = dataMemberAttribute.Name; InType inType = GetInType(uriTemplate, parameter.Name); if (inType == InType.Path) required = true; if (!required && !parameter.HasDefaultValue) required = true; if (typeFormat.Type == ParameterType.Object) { return new ParameterSchema { Name = name, Description = description, In = inType, Required = required, SchemaRef = typeFormat.Format }; } if (inType == InType.Body) { //it's a complex type, so we'll need to map it later if (definitionsTypesList != null && !definitionsTypesList.Contains(parameter.ParameterType)) { definitionsTypesList.Add(parameter.ParameterType); } typeFormat = new TypeFormat(ParameterType.Object, HttpUtility.HtmlEncode(parameter.ParameterType.FullName)); return new ParameterSchema { Name = name, Description = description, In = inType, Required = required, SchemaRef = typeFormat.Format }; } var param = new ParameterPrimitive { Name = name, Description = description, In = inType, Required = required, TypeFormat = typeFormat }; if (typeFormat.Type == ParameterType.Array) { Type t = parameter.ParameterType.GetElementType(); param.Items = new ParameterItems { TypeFormat = new TypeFormat { Type = ParameterType.Object, Format = t.FullName }, Items = new ParameterSchema { SchemaRef = t.FullName } }; param.CollectionFormat = CollectionFormat.Csv; } return param; }
private static string GetParameterConstraint(ParameterInfo parameter) { var constraintAttribute = parameter.GetCustomAttribute<ConstraintAttribute>(false); return constraintAttribute != null ? constraintAttribute.Pattern.TrimStart('^').TrimEnd('$') : null; }
internal static TraceMonitor CreateTraceMonitor(ParameterInfo parameter, ITriggeredFunctionExecutor executor) { ErrorTriggerAttribute attribute = parameter.GetCustomAttribute<ErrorTriggerAttribute>(inherit: false); // Determine whether this is a method level filter, and if so, create the filter Func<TraceEvent, bool> methodFilter = null; MethodInfo method = (MethodInfo)parameter.Member; string functionLevelMessage = null; if (method.Name.EndsWith(ErrorHandlerSuffix, StringComparison.OrdinalIgnoreCase)) { string sourceMethodName = method.Name.Substring(0, method.Name.Length - ErrorHandlerSuffix.Length); MethodInfo sourceMethod = method.DeclaringType.GetMethod(sourceMethodName); if (sourceMethod != null) { string sourceMethodFullName = string.Format("{0}.{1}", method.DeclaringType.FullName, sourceMethod.Name); methodFilter = p => { FunctionInvocationException functionException = p.Exception as FunctionInvocationException; return p.Level == System.Diagnostics.TraceLevel.Error && functionException != null && string.Compare(functionException.MethodName, sourceMethodFullName, StringComparison.OrdinalIgnoreCase) == 0; }; string sourceMethodShortName = string.Format("{0}.{1}", method.DeclaringType.Name, sourceMethod.Name); functionLevelMessage = string.Format("Function '{0}' failed.", sourceMethodShortName); } } string errorHandlerFullName = string.Format("{0}.{1}", method.DeclaringType.FullName, method.Name); ErrorHandlers.Add(errorHandlerFullName); // Create the TraceFilter instance TraceFilter traceFilter = null; if (attribute.FilterType != null) { if (methodFilter != null) { TraceFilter innerTraceFilter = (TraceFilter)Activator.CreateInstance(attribute.FilterType); traceFilter = new CompositeTraceFilter(innerTraceFilter, methodFilter, attribute.Message ?? functionLevelMessage); } else { traceFilter = (TraceFilter)Activator.CreateInstance(attribute.FilterType); } } else if (!string.IsNullOrEmpty(attribute.Window)) { TimeSpan window = TimeSpan.Parse(attribute.Window); traceFilter = new SlidingWindowTraceFilter(window, attribute.Threshold, methodFilter, attribute.Message); } else { traceFilter = TraceFilter.Create(methodFilter, attribute.Message ?? functionLevelMessage); } TraceMonitor traceMonitor = new TraceMonitor().Filter(traceFilter); // Apply any additional monitor options if (!string.IsNullOrEmpty(attribute.Throttle)) { TimeSpan throttle = TimeSpan.Parse(attribute.Throttle); traceMonitor.Throttle(throttle); } // Subscribe the error handler function to the error stream traceMonitor.Subscribe(p => { TriggeredFunctionData triggerData = new TriggeredFunctionData { TriggerValue = p }; Task<FunctionResult> task = executor.TryExecuteAsync(triggerData, CancellationToken.None); task.Wait(); }); return traceMonitor; }
private static PrimitiveType GetStoreParameterPrimitiveType( this DbModel model, MethodInfo methodInfo, ParameterInfo parameterInfo, FunctionAttribute functionAttribute) { // <Parameter Name="PersonID" Type="int" Mode="In" /> Type parameterClrType = parameterInfo.ParameterType; ParameterAttribute parameterAttribute = parameterInfo.GetCustomAttribute<ParameterAttribute>(); Type parameterAttributeClrType = parameterAttribute?.ClrType; if (parameterClrType.IsGenericType) { Type parameterClrTypeDefinition = parameterClrType.GetGenericTypeDefinition(); if (parameterClrTypeDefinition == typeof(IEnumerable<>) || parameterClrTypeDefinition == typeof(IQueryable<>)) { if (functionAttribute.Type == FunctionType.AggregateFunction) { // Aggregate function has one IEnumerable<T> or IQueryable<T> parameter. parameterClrType = parameterClrType.GetGenericArguments().Single(); } else { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} is not supported. {typeof(IEnumerable<>).FullName} parameter must be used for {nameof(FunctionType)}.{nameof(FunctionType.AggregateFunction)} method."); } } } if (parameterClrType == typeof(ObjectParameter)) { // ObjectParameter must be used for stored procedure parameter. if (functionAttribute.Type != FunctionType.StoredProcedure) { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} is not supported. {nameof(ObjectParameter)} parameter must be used for {nameof(FunctionType)}.{nameof(FunctionType.StoredProcedure)} method."); } // ObjectParameter.Type is available only when methodInfo is called. // When building model, its store type/clr type must be provided by ParameterAttribute. if (parameterAttributeClrType == null) { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} is not supported. {nameof(ObjectParameter)} parameter must have {nameof(ParameterAttribute)} with {nameof(ParameterAttribute.ClrType)} specified, with optional {nameof(ParameterAttribute.DbType)}."); } parameterClrType = parameterAttributeClrType; } else { // When parameter is not ObjectParameter, ParameterAttribute.ClrType should be either not specified, or the same as parameterClrType. if (parameterAttributeClrType != null && parameterAttributeClrType != parameterClrType) { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} is not supported. It is of {parameterClrType.FullName} type, but its {nameof(ParameterAttribute)}.{nameof(ParameterAttribute.ClrType)} has a fifferent type {parameterAttributeClrType.FullName}"); } } string storePrimitiveTypeName = parameterAttribute?.DbType; return !string.IsNullOrEmpty(storePrimitiveTypeName) ? model.GetStorePrimitiveType(storePrimitiveTypeName, methodInfo, parameterInfo) : model.GetStorePrimitiveType(parameterClrType, methodInfo, parameterInfo); }
public Parameter(ParameterInfo info) { Name = info.Name; ParameterType = info.ParameterType; if (Generator.GetProperty((info.Member as MethodInfo)) != null) { Id = 0; return; } var id = info.GetCustomAttribute<IdAttribute>(); if (id == null) throw new Exception("expected an Id() attribute"); Id = id.Id; }
public static EasyTableAttribute GetEasyTableAttribute(this ParameterInfo parameter) { return(parameter.GetCustomAttribute <EasyTableAttribute>(inherit: false)); }
//----------------------------------------------------------------------------------------------------------------------------------------------------- public static DetailAttribute FromParameter(ParameterInfo parameter) { return parameter.GetCustomAttribute<DetailAttribute>(); }
internal static object ConvertToTargetType( ParameterInfo parameter, Type destinationType, object value ) { Contract.Requires( parameter != null ); Contract.Requires( destinationType != null ); var attribute = parameter.GetCustomAttribute<TypeConverterAttribute>( true ); return ConvertToTargetType( attribute, destinationType, value ); }
//----------------------------------------------------------------------------------------------------------------------------------------------------- public static bool IsDefinedOn(ParameterInfo parameter) { return (parameter.GetCustomAttribute<DetailAttribute>() != null); }
/// <summary> /// Tries to get the default value of a distribution's parameter. /// </summary> /// public static bool TryGetDefault(ParameterInfo parameter, out double value) { var attrb = parameter.GetCustomAttribute<DefaultValueAttribute>(); if (attrb != null) { value = (double)Convert.ChangeType(attrb.Value, typeof(double)); return true; } DoubleRange range; if (!TryGetRange(parameter, out range)) { value = 0; return false; } var a = parameter.GetCustomAttribute<RangeAttribute>(); value = 0; if (a is PositiveAttribute || a is PositiveIntegerAttribute) value = 1; else if (a is NegativeAttribute || a is NegativeIntegerAttribute) value = -1; else if (a is UnitAttribute) value = 0.5; if (value < range.Min) value = range.Min; if (value > range.Max) value = range.Max; return true; }
public string GetName(ParameterInfo param) { Guard.ArgumentNotNull(param, "param"); var paramAttr = param.GetCustomAttribute<SDataServiceParameterAttribute>(); if (paramAttr != null && !string.IsNullOrEmpty(paramAttr.Name)) { return paramAttr.Name; } return _transform(param.Name); }
internal static IArgumentEvaluator GetEvaluator(ParameterInfo paramInfo) { var att = paramInfo.GetCustomAttribute<ArgumentEvaluatorAttribute>(); if (att == null) { return new ValueArgumentEvaluator(); } return (IArgumentEvaluator) Activator.CreateInstance(att.ArgumentEvaluatorType); }
private void AppendEmbededAttribute(List<AttributeSymbol> list, ParameterInfo parameter) { if (parameter.GetCustomAttribute<ParamArrayAttribute>() != null) list.Add(Root.Variadic); if (parameter.IsOptional) list.Add(Root.Optional); }
private static PrimitiveType GetModelParameterPrimitiveType( this DbModel model, MethodInfo methodInfo, ParameterInfo parameterInfo) { // <Parameter Name="PersonID" Mode="In" Type="Int32" /> Type parameterClrType = parameterInfo.ParameterType; ParameterAttribute parameterAttribute = parameterInfo.GetCustomAttribute<ParameterAttribute>(); Type parameterAttributeClrType = parameterAttribute?.ClrType; if (parameterClrType == typeof(ObjectParameter)) { // ObjectParameter.Type is available only when methodInfo is called. // When building model, its store type/clr type must be provided by ParameterAttribute. if (parameterAttributeClrType == null) { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} is not supported. {nameof(ObjectParameter)} parameter must have {nameof(ParameterAttribute)} with {nameof(ParameterAttribute.ClrType)} specified."); } parameterClrType = parameterAttributeClrType; } else { // When parameter is not ObjectParameter, ParameterAttribute.ClrType should be the same as parameterClrType, or not specified. if (parameterAttributeClrType != null && parameterAttributeClrType != parameterClrType) { throw new NotSupportedException( $"Parameter {parameterInfo.Name} of method {methodInfo.Name} if of {parameterClrType.FullName}, but its {nameof(ParameterAttribute)}.{nameof(ParameterAttribute.ClrType)} has a fifferent type {parameterAttributeClrType.FullName}"); } } return model.GetModelPrimitiveType(parameterClrType, methodInfo); }
public static T GetCustomAttribute <T>(this ParameterInfo element, bool inherit) where T : Attribute { return((T)element.GetCustomAttribute(typeof(T), inherit)); }
public ParameterNode ReadParameter(ParameterInfo parameterInfo, XElement documentationNode, AssemblyNode assembly, Dictionary<string, bool> routeParameters, string version) { var parameterNode = new ParameterNode { Name = parameterInfo.Name }; var parameterType = parameterInfo.ParameterType; parameterNode.Documentation = documentation.ParseDocumentation(documentationNode); parameterNode.IsRequired = RemoveNullable(ref parameterType); if (parameterInfo.DefaultValue != null) parameterNode.IsRequired = false; FillType(parameterNode, parameterType, assembly, new Type[0], version); if (routeParameters.ContainsKey(parameterInfo.Name)) { parameterNode.Position = ParameterPosition.Path; parameterNode.IsRequired = !routeParameters[parameterInfo.Name]; } else if (parameterInfo.GetCustomAttribute<FromQueryAttribute>() != null) { parameterNode.Position = ParameterPosition.Query; } else if (parameterInfo.GetCustomAttribute<FromBodyAttribute>() != null || parameterNode.Type.Type == TypeIdentifier.Object) { parameterNode.Position = ParameterPosition.Body; parameterNode.IsRequired = true; } else { parameterNode.Position = ParameterPosition.Query; } GetConstraints(parameterInfo.GetCustomAttributes().ToArray(), parameterNode); return parameterNode; }
public static T GetCustomAttribute <T>(this ParameterInfo element) where T : Attribute { return((T)((object)element.GetCustomAttribute(typeof(T)))); }