public override void VisitParameter(ParameterAttribute parameter)
            {
                _parameterInfo = new ParameterInfo(CurrentProperty, parameter);
                _cmdletInfo.AddParameter(_parameterInfo);

                base.VisitParameter(parameter);
            }
Esempio n. 2
0
        internal Parameter(
            PropertyAccessor propertyAccessor,
            ParameterAttribute parameterAttribute,
            IDefaultValuePolicy defaultValuePolicy
        )
        {
            if (propertyAccessor == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(propertyAccessor));
            }

            if (parameterAttribute == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(parameterAttribute));
            }

            if (defaultValuePolicy == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(defaultValuePolicy));
            }

            PropertyAccessor = propertyAccessor;
            ParameterAttribute = parameterAttribute;
            DefaultValuePolicy = defaultValuePolicy;

            ValidationAttributes = PropertyAccessor.PropertyInfo
                .GetCustomAttributes<ParameterValidationAttribute>(inherit: true)
                .ToImmutableArray();
        }
        private static void WriteSyntaxItem(CmdletAttribute ca, Dictionary <string, List <PropertyInfo> > parameterSets, string parameterSetName, List <PropertyInfo> allParameterSets)
        {
            _writer.WriteStartElement("command", "syntaxItem", null);
            _writer.WriteElementString("maml", "name", null, string.Format("{0}-{1}", ca.VerbName, ca.NounName));
            foreach (PropertyInfo pi in parameterSets[parameterSetName])
            {
                ParameterAttribute pa = GetParameterAttribute(pi, parameterSetName);
                if (pa == null)
                {
                    continue;
                }

                WriteParameter(pi, pa);
            }
            if (allParameterSets != null)
            {
                foreach (PropertyInfo pi in allParameterSets)
                {
                    List <ParameterAttribute> pas = GetAttribute <ParameterAttribute>(pi);
                    if (pas == null)
                    {
                        continue;
                    }
                    WriteParameter(pi, pas[0]);
                }
            }
            _writer.WriteEndElement(); //command:syntaxItem
        }
        public object GetDynamicParameters()
        {
            var          classAttribute = this.GetType().GetCustomAttributes(false).FirstOrDefault(a => a is PropertyLoadingAttribute);
            const string parameterName  = "Scopes";

            var parameterDictionary = new RuntimeDefinedParameterDictionary();
            var attributeCollection = new System.Collections.ObjectModel.Collection <Attribute>();

            var parameterAttribute = new ParameterAttribute
            {
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                Mandatory = false
            };

            attributeCollection.Add(parameterAttribute);

            var identifiers = new PermissionScopes().GetIdentifiers();

            var validateSetAttribute = new ValidateSetAttribute(identifiers);

            attributeCollection.Add(validateSetAttribute);

            var runtimeParameter = new RuntimeDefinedParameter(parameterName, typeof(string[]), attributeCollection);

            parameterDictionary.Add(parameterName, runtimeParameter);

            return(parameterDictionary);
        }
Esempio n. 5
0
        private static void EmitResolveParameter(ILGenerator il, ParameterInfo param)
        {
            ParameterAttribute attr     = GetParameterAttribute(param);
            IParameterResolver resolver = ParameterResolverMap.GetResolver(attr);

            resolver.EmitParameterResolution(il, attr, param.ParameterType);
        }
Esempio n. 6
0
        /// <summary>
        /// Extracts the data from the ParameterAttribute and creates the member data as necessary.
        /// </summary>
        /// <param name="parameterName">
        /// The name of the parameter.
        /// </param>
        /// <param name="parameter">
        /// The instance of the ParameterAttribute to extract the data from.
        /// </param>
        /// <exception cref="MetadataException">
        /// If a parameter set name has already been declared on this parameter.
        /// </exception>
        private void ProcessParameterAttribute(
            string parameterName,
            ParameterAttribute parameter)
        {
            // If the parameter set name already exists on this parameter and the set name is the default parameter
            // set name, it is an error.

            if (ParameterSetData.ContainsKey(parameter.ParameterSetName))
            {
                MetadataException e =
                    new MetadataException(
                        "ParameterDeclaredInParameterSetMultipleTimes",
                        null,
                        DiscoveryExceptions.ParameterDeclaredInParameterSetMultipleTimes,
                        parameterName,
                        parameter.ParameterSetName);

                throw e;
            }

            if (parameter.ValueFromPipeline || parameter.ValueFromPipelineByPropertyName)
            {
                IsPipelineParameterInSomeParameterSet = true;
            }

            if (parameter.Mandatory)
            {
                IsMandatoryInSomeParameterSet = true;
            }

            // Construct an instance of the parameter set specific data
            ParameterSetSpecificMetadata parameterSetSpecificData = new ParameterSetSpecificMetadata(parameter);

            ParameterSetData.Add(parameter.ParameterSetName, parameterSetSpecificData);
        }
        public Parameter(string variantName, string parameterName, ParameterMetadata metadata)
        {
            VariantName   = variantName;
            ParameterName = parameterName;
            Metadata      = metadata;

            Attributes             = Metadata.Attributes.ToArray();
            ParameterType          = Attributes.OfType <ExportAsAttribute>().FirstOrDefault()?.Type ?? Metadata.ParameterType;
            Categories             = Attributes.OfType <CategoryAttribute>().SelectMany(ca => ca.Categories).Distinct().ToArray();
            DefaultValue           = Attributes.OfType <PSDefaultValueAttribute>().FirstOrDefault();
            ParameterAttribute     = Attributes.OfType <ParameterAttribute>().First();
            SupportsWildcards      = Attributes.OfType <SupportsWildcardsAttribute>().Any();
            InfoAttribute          = Attributes.OfType <InfoAttribute>().FirstOrDefault();
            CompleterInfoAttribute = Attributes.OfType <CompleterInfoAttribute>().FirstOrDefault();

            ValueFromPipeline = ParameterAttribute.ValueFromPipeline;
            ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName;
            Position    = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position;
            DontShow    = ParameterAttribute.DontShow;
            IsMandatory = ParameterAttribute.Mandatory;

            var complexParameterName = ParameterName.ToUpperInvariant();

            ComplexInterfaceInfo = InfoAttribute?.ToComplexInterfaceInfo(complexParameterName, ParameterType, true);
            IsComplexInterface   = ComplexInterfaceInfo?.IsComplexInterface ?? false;
            HelpMessage          = $"{ParameterAttribute.HelpMessage}{(IsComplexInterface ? $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table." : String.Empty)}";
        }
Esempio n. 8
0
        public static RuntimeDefinedParameter GetObjectTypeParameter(string paramName, bool mandatory, int position, bool allowWildcard, string parameterSetName)
        {
            RuntimeDefinedParameter parameter = new RuntimeDefinedParameter();

            parameter.Name          = paramName;
            parameter.ParameterType = typeof(string);
            IList <ObjectTypeDefinition> objectTypes = ResourceManagementSchema.GetObjectTypes().ToList();

            if (objectTypes.Count > 0)
            {
                List <string> objectTypeNames = objectTypes.OrderBy(t => t.SystemName).Select(t => t.SystemName).ToList();
                if (allowWildcard)
                {
                    objectTypeNames.Add("*");
                }

                ValidateSetAttribute setAttribute = new ValidateSetAttribute(objectTypeNames.ToArray());
                parameter.Attributes.Add(setAttribute);
            }

            ParameterAttribute paramAttribute = new ParameterAttribute();

            paramAttribute.Mandatory        = mandatory;
            paramAttribute.Position         = position;
            paramAttribute.ParameterSetName = parameterSetName;
            parameter.Attributes.Add(paramAttribute);
            return(parameter);
        }
        public override IParameter ReadParameterAttribute(MemberInfo memberInfo)
        {
            ParameterBase parameter = new ParameterBase();

            ParameterAttribute       statementParameterAttribute = (ParameterAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(ParameterAttribute), true);
            SQLiteParameterAttribute sqliteParameterAttribute    = (SQLiteParameterAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(SQLiteParameterAttribute), true);

            if (statementParameterAttribute == null)
            {
                if (sqliteParameterAttribute != null)
                {
                    throw AttributeException.ColumnAttributeNotFoundException(memberInfo, typeof(SQLiteParameterAttribute));
                }
                else
                {
                    return(null);
                }
            }


            SetParameterValue(parameter, memberInfo, statementParameterAttribute, sqliteParameterAttribute);


            if (string.IsNullOrWhiteSpace(statementParameterAttribute.ParameterName))
            {
                parameter.ParameterName = "@" + memberInfo.Name;
            }
            if (sqliteParameterAttribute != null && string.IsNullOrWhiteSpace(sqliteParameterAttribute.ParameterName))
            {
                parameter.ParameterName = "@" + memberInfo.Name;
            }

            return(null);
        }
        protected virtual void SetParameterSize(LocalBuilder parameterBuilder, ParameterInfo parameterInfo, ILGenerator generator)
        {
            ParameterAttribute attribute = parameterInfo.GetCustomAttribute <ParameterAttribute>();

            // If we don't have a ParameterAttribute, then the size is the default
            if (attribute == null)
            {
                return;
            }

            // If the size is not set then use the default
            if (attribute.Size == 0)
            {
                return;
            }

            // Load the local variable associated with this parameter
            generator.Emit(OpCodes.Ldloc, parameterBuilder);

            // Load the parameter direction
            generator.Emit(OpCodes.Ldc_I4, attribute.Size);

            // Call the set method on the Value property
            generator.Emit(OpCodes.Callvirt, ClassUtils.GetPropertySetMethod <DbParameter>(nameof(DbParameter.Size)));
        }
        public void ResolvesDuplicatedDynamicParameterName()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "Name";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    "Mode1", "Mode2", "Mode3"
                },
                MaxLength = "5",
                MinLength = "1",
                Type      = "bool"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal(key + "FromTemplate", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(bool), dynamicParameter.ParameterType);
            Assert.Equal(2, dynamicParameter.Attributes.Count);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.True(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);

            ValidateLengthAttribute validateLengthAttribute = (ValidateLengthAttribute)dynamicParameter.Attributes[1];

            Assert.Equal(int.Parse(value.MinLength), validateLengthAttribute.MinLength);
            Assert.Equal(int.Parse(value.MaxLength), validateLengthAttribute.MaxLength);
        }
        public static RuntimeDefinedParameterDictionary Attributes(string SqlInstance)
        {
            List <string> sourceList = new List <string>();
            Server        server     = new Server(SqlInstance);

            PropertyInfo[] props = server.Configuration.GetType().GetProperties();

            foreach (PropertyInfo prop in props)
            {
                sourceList.Add(prop.Name);
            }

            string[] sources = sourceList.ToArray();

            ParameterAttribute paramAttribute = new ParameterAttribute()
            {
                Mandatory = true,
                ValueFromPipelineByPropertyName = false
            };

            System.Collections.ObjectModel.Collection <System.Attribute> attributeCollection = new System.Collections.ObjectModel.Collection <System.Attribute>();
            paramAttribute.HelpMessage = "This is the help message.";
            attributeCollection.Add(paramAttribute);

            ValidateSetAttribute sourceFromConfig = new ValidateSetAttribute(sources);

            attributeCollection.Add(sourceFromConfig);
            RuntimeDefinedParameter           dynamicParam = new RuntimeDefinedParameter("ConfigurationItem", typeof(string), attributeCollection);
            RuntimeDefinedParameterDictionary paramDict    = new RuntimeDefinedParameterDictionary();

            paramDict.Add("ConfigurationItem", dynamicParam);

            return(paramDict);
        }
Esempio n. 13
0
        private static string GetPipelineInputString(ParameterAttribute paramAttrib)
        {
            ArrayList list = new ArrayList();

            if (paramAttrib.ValueFromPipeline)
            {
                list.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue, new object[0]));
            }
            if (paramAttrib.ValueFromPipelineByPropertyName)
            {
                list.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName, new object[0]));
            }
            if (paramAttrib.ValueFromRemainingArguments)
            {
                list.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments, new object[0]));
            }
            if (list.Count == 0)
            {
                return(StringUtil.Format(HelpDisplayStrings.FalseShort, new object[0]));
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(StringUtil.Format(HelpDisplayStrings.TrueShort, new object[0]));
            builder.Append(" (");
            for (int i = 0; i < list.Count; i++)
            {
                builder.Append((string)list[i]);
                if (i != (list.Count - 1))
                {
                    builder.Append(", ");
                }
            }
            builder.Append(")");
            return(builder.ToString());
        }
Esempio n. 14
0
        public static string GetParameterDisplayType([NotNull] PropertyInfo property)
        {
            ParameterAttribute attr = GetParameterAttribute(property);

            if (attr != null && !string.IsNullOrEmpty(attr.DisplayType))
            {
                return(attr.DisplayType);
            }

            // Translate a few common types to "user friendly" names:

            if (property.PropertyType == typeof(bool))
            {
                return("Boolean");
            }

            if (property.PropertyType == typeof(int))
            {
                return("Integer");
            }

            if (property.PropertyType == typeof(double))
            {
                return("Number");
            }

            if (property.PropertyType == typeof(string))
            {
                return("String");
            }

            // All other types use their technical name:

            return(property.PropertyType.Name);
        }
Esempio n. 15
0
 public object GetDynamicParameters()
 {
     if (_dynLib == null)
     {
         _dynLib = new DynamicLibrary();
         DynamicParameter <Assembly> dp      = null;
         RuntimeDefinedParameter     rtParam = null;
         Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
         if (!Scope.Equals("File"))
         {
             dp = new DynamicParameter <Assembly>(PNAME, Assemblies, x => x.FullName, "FullName")
             {
                 Mandatory = false
             };
             rtParam = dp.AsRuntimeParameter();
         }
         else
         {
             var pAtt = new ParameterAttribute
             {
                 Mandatory = true
             };
             rtParam = new RuntimeDefinedParameter(PNAME, PTYPE, new Collection <Attribute>
             {
                 pAtt
             });
         }
         _dynLib.Add(PNAME, rtParam);
     }
     return(_dynLib);
 }
Esempio n. 16
0
        private static void ConstructorDetails(Type t)
        {
            var consttr = t.GetConstructors();

            foreach (ConstructorInfo ci in consttr)
            {
                System.Console.WriteLine("constructor info " + ci.ToString());
                if (ci.ContainsGenericParameters)
                {
                    var genericArg = ci.GetGenericArguments();
                    System.Console.WriteLine("Constructor genericArg : " + genericArg.Length);
                }

                foreach (var pm in ci.GetParameters())
                {
                    Type type = pm.ParameterType;

                    ParameterAttribute named = pm.GetCustomAttribute <ParameterAttribute>();
                    if (named != null)
                    {
                        System.Console.WriteLine("Named Parameter name " + named.Value.AssemblyQualifiedName);
                        Type nt = Type.GetType(named.Value.AssemblyQualifiedName);
                        System.Console.WriteLine("Named Parameter Type " + nt.FullName);
                    }
                    System.Console.WriteLine("constructor param " + pm.Name);
                }
            }
        }
Esempio n. 17
0
        internal Parameter(
            PropertyAccessor propertyAccessor,
            ParameterAttribute parameterAttribute,
            IDefaultValuePolicy defaultValuePolicy
            )
        {
            if (propertyAccessor == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(propertyAccessor));
            }

            if (parameterAttribute == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(parameterAttribute));
            }

            if (defaultValuePolicy == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(defaultValuePolicy));
            }

            PropertyAccessor   = propertyAccessor;
            ParameterAttribute = parameterAttribute;
            DefaultValuePolicy = defaultValuePolicy;

            ValidationAttributes = PropertyAccessor.PropertyInfo
                                   .GetCustomAttributes <ParameterValidationAttribute>(inherit: true)
                                   .ToImmutableArray();
        }
        public static async Task <List <DbParameter> > UseDbParameterGenerator <TParameter>(this object sender) where TParameter : DbParameter, new ()
        {
            List <DbParameter> _dbParameters = new List <DbParameter>();

            try
            {
                _dbParameters = await Task.Run(() => {
                    List <DbParameter> _list          = new List <DbParameter>();
                    PropertyInfo[] _paramPropertyInfo = sender.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                    foreach (PropertyInfo item in _paramPropertyInfo)
                    {
                        SqlDataTypeAttribute _sqlDataTypeAttribute = (SqlDataTypeAttribute)item.GetCustomAttribute(typeof(SqlDataTypeAttribute));
                        ParameterAttribute _parameterAttribute     = (ParameterAttribute)item.GetCustomAttribute(typeof(ParameterAttribute));
                        var _value = item.GetValue(sender);
                        DbParameter _dbParameter   = (DbParameter) new TParameter();
                        _dbParameter.DbType        = _sqlDataTypeAttribute.SqlDbType;
                        _dbParameter.ParameterName = _parameterAttribute.value;
                        _dbParameter.Value         = _value == null ? DBNull.Value : _value;
                        _list.Add(_dbParameter);
                    }
                    return(_list);
                });

                return(_dbParameters);
            }
            catch (Exception ex)
            {
                throw new Exception("");
            }
        }
Esempio n. 19
0
 public SlashCommandParameter(ParameterAttribute attribute, PropertyInfo property)
 {
     Name        = attribute.Name;
     Description = attribute.Description;
     IsRequired  = attribute.IsRequired;
     Property    = property;
 }
        public void ConstructsArrayTypeDynamicParameter()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "ranks";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    JArray.Parse("[\"1\", \"3\", \"5\"]"),
                    JArray.Parse("[\"A\", \"D\", \"F\"]"),
                },
                DefaultValue = JArray.Parse("[\"A\", \"D\", \"F\"]"),
                Type         = "array"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("ranks", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(object[]), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
Esempio n. 21
0
        public void ConstructsDynamicParameterNoValidation()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "computeMode";
            TemplateFileParameter value = new TemplateFileParameter()
            {
                AllowedValues = new List <string>(),
                DefaultValue  = "Mode1",
                Type          = "securestring"
            };
            KeyValuePair <string, TemplateFileParameter> parameter = new KeyValuePair <string, TemplateFileParameter>(key, value);

            RuntimeDefinedParameter dynamicParameter = galleryTemplatesClient.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("computeMode", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(SecureString), dynamicParameter.ParameterType);
            Assert.Equal(1, dynamicParameter.Attributes.Count);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
        public void ConstructsDynamicParameterWithNullAllowedValues()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "computeMode";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = null,
                DefaultValue  = "Mode1",
                Type          = "securestring"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("computeMode", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(SecureString), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
Esempio n. 23
0
        public object GetDynamicParameters()
        {
            // initial logic came from https://foxdeploy.com/2017/01/13/adding-tab-completion-to-your-powershell-functions/

            if (_gitDirs.Count == 0)
            {
                return(null);
            }
            var names     = _gitDirs.OrderBy(x => x.Key).Select(x => x.Key).ToArray();
            var paramName = "RepoName";

            var rtDict             = new RuntimeDefinedParameterDictionary();
            var attributes         = new System.Collections.ObjectModel.Collection <Attribute>();
            var parameterAttribute = new ParameterAttribute
            {
                Mandatory = false,
                Position  = 0
            };

            attributes.Add(parameterAttribute);
            var validateSetAttribute = new ValidateSetAttribute(names);

            attributes.Add(validateSetAttribute);

            RepoName = new RuntimeDefinedParameter(paramName, typeof(string), attributes);
            rtDict.Add(paramName, RepoName);


            return(rtDict);
        }
        /// <summary>
        /// Creates dynamic parameters for all parameters defined on a <see cref="NewSensorParameters"/> object.
        /// </summary>
        /// <param name="dictionary">The dynamic parameters dictionary to add parameters to.</param>
        private void AddParametersObjectDynamicParameters(RuntimeDefinedParameterDictionaryEx dictionary)
        {
            //If TypeAttribute.Class is null (i.e. creating the parameters are not actually supported) a SwitchParameter wouldn't have been created
            //and we won't actually get to this point
            var parametersType = Type.GetEnumAttribute <TypeAttribute>(true);

            var properties = ReflectionCacheManager.Get(parametersType.Class).Properties.Where(p => p.GetAttribute <PropertyParameterAttribute>() != null);

            var parameterConfig = Type.GetEnumAttribute <NewSensorAttribute>() ?? new NewSensorAttribute();

            int?position = null;

            foreach (var property in properties)
            {
                var parameterAttributes = new List <Attribute>();

                var isNameParameter = property.Property.Name == nameof(NewObjectParameters.Name);

                position = GetPosition(property, isNameParameter, parameterConfig, position);

                foreach (var set in ParameterSets.Where(s => PropertyIsAllowedInSet(property, s)))
                {
                    parameterAttributes.Add(new ParameterAttribute
                    {
                        Mandatory        = GetMandatory(property, isNameParameter, parameterConfig),
                        Position         = position.Value,
                        ParameterSetName = $"{Type}{set.Name}"
                    });
                }

                var name = GetParameterName(property);

                var type = property.Property.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
                {
                    var underlying = type.GetGenericArguments()[0];
                    type = underlying.MakeArrayType();
                }

                dictionary.AddOrMerge(name, type, parameterAttributes.ToArray());

                if (alternateSet != null)
                {
                    IAlternateParameter alternateParameter;

                    if (TryGetAlternateProperty(property, alternateSet.Name, out alternateParameter))
                    {
                        var parameterAttribute = new ParameterAttribute
                        {
                            Mandatory        = HasRequireValueTrue(property),
                            Position         = position.Value,
                            ParameterSetName = $"{Type}{alternateSet.Name}"
                        };

                        dictionary.AddOrMerge(alternateParameter.Name, alternateParameter.Type, parameterAttribute);
                    }
                }
            }
        }
Esempio n. 25
0
        private void AddParameter(string name, Type type, bool mandatory = false, bool valueFromPipeline = false)
        {
            var attributeCollection = new Collection <Attribute>();

            foreach (var set in ParameterSetNames)
            {
                var attribute = new ParameterAttribute {
                    ParameterSetName = set
                };

                if (mandatory)
                {
                    attribute.Mandatory = true;
                }

                if (valueFromPipeline)
                {
                    attribute.ValueFromPipeline = true;
                }

                attributeCollection.Add(attribute);
            }

            Parameters.Add(name, new RuntimeDefinedParameter(name, Nullable.GetUnderlyingType(type) ?? type, attributeCollection));
        }
        public void ConstructsObjectTypeDynamicParameter()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "appSku";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    JObject.Parse("{\"code\" : \"F1\", \"name\" : \"Free\"}"),
                    JObject.Parse("{\"code\" : \"F2\", \"name\" : \"Shared\"}"),
                },
                DefaultValue = JObject.Parse("{\"code\" : \"F1\", \"name\" : \"Free\"}"),
                Type         = "object"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("appSku", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(Hashtable), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
Esempio n. 27
0
        public object GetDynamicParameters()
        {
            var          classAttribute      = this.GetType().GetCustomAttributes(false).FirstOrDefault(a => a is PropertyLoadingAttribute);
            var          maxDepth            = ((PropertyLoadingAttribute)classAttribute)?.Depth ?? 2;
            const string parameterName       = "Includes";
            var          parameterDictionary = new RuntimeDefinedParameterDictionary();
            var          attributeCollection = new System.Collections.ObjectModel.Collection <Attribute>();

            var parameterAttribute = new ParameterAttribute
            {
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                Mandatory = false
            };

            attributeCollection.Add(parameterAttribute);

            var attributes = GetProperties(typeof(TType), typeof(TType), maxDepth);

            var validateSetAttribute = new ValidateSetAttribute(attributes.ToArray());

            attributeCollection.Add(validateSetAttribute);

            var runtimeParameter = new RuntimeDefinedParameter(parameterName, typeof(string[]), attributeCollection);

            parameterDictionary.Add(parameterName, runtimeParameter);

            return(parameterDictionary);
        }
Esempio n. 28
0
        //---------------------------------------------------------------------------------------------

        protected virtual void ValidateRequire()
        {
            foreach (PropertyInfo pInfo in this.GetType().GetProperties())
            {
                ParameterAttribute attrParam = (ParameterAttribute)this.GetAttribute(pInfo, typeof(ParameterAttribute));
                if (attrParam != null)
                {
                    Require attr = (Require)this.GetAttribute(pInfo, typeof(Require));
                    if (attr != null)
                    {
                        object value = null;
                        if (pInfo.PropertyType.GetInterface("Caleb.Library.CAL.ICalBusiness") != null)
                        {
                            value = ((ICalBusiness)pInfo.GetValue(this, null)).ID;
                        }
                        else
                        {
                            value = pInfo.GetValue(this, null);
                        }
                        if (value == null)
                        {
                            this.StatusMessages.Add(CalStatusMessageType.Error, this.GetType().Name + " - " + attrParam.Name + " je povinny!");
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        //---------------------------------------------------------------------------------------------

        protected virtual void ValidateUnique()
        {
            foreach (PropertyInfo pInfo in this.GetType().GetProperties())
            {
                ParameterAttribute attrParam = (ParameterAttribute)this.GetAttribute(pInfo, typeof(ParameterAttribute));
                if (attrParam != null)
                {
                    Unique attr = (Unique)this.GetAttribute(pInfo, typeof(Unique));
                    if (attr != null)
                    {
                        string strVal = "";
                        if (pInfo.PropertyType.GetInterface("Caleb.Library.CAL.ICalBusiness") != null)
                        {
                            strVal = ((ICalBusiness)pInfo.GetValue(this, null)).ID + "";
                        }
                        else
                        {
                            strVal = pInfo.GetValue(this, null) + "";
                        }

                        if (!this.IsDistinctByParam(attrParam.Name, strVal))
                        {
                            this.StatusMessages.Add(CalStatusMessageType.Error, this.GetType().Name + " - " + attrParam.Name + " musi byt unikatni!");
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        //---------------------------------------------------------------------------------------------

        public void FillFromDataRow(DataRow row)
        {
            foreach (PropertyInfo pInfo in this.GetType().GetProperties())
            {
                ParameterAttribute attrParam = (ParameterAttribute)this.GetAttribute(pInfo, typeof(ParameterAttribute));

                if (attrParam != null)
                {
                    Usages defaultUsage = Usages.Add | Usages.Load | Usages.Save;

                    UsageAttribute usage = (UsageAttribute)this.GetAttribute(pInfo, typeof(UsageAttribute));
                    if (usage != null)
                    {
                        defaultUsage = usage.Usage;
                    }

                    if ((defaultUsage & Usages.Load) == Usages.Load)
                    {
                        object value = (row.Table.Columns.Contains(attrParam.Name)) ? Utils.DBNullToNull(row[attrParam.Name]) : null;

                        if (pInfo.PropertyType.GetInterface("Caleb.Library.CAL.ICalBusiness") != null)
                        {
                            ICalBusiness business = (ICalBusiness)pInfo.GetValue(this, null);
                            business.ID = CalBusiness.ToID(value);
                        }
                        else
                        {
                            pInfo.SetValue(this, value, null);
                        }
                    }
                }
            }
        }
Esempio n. 31
0
        private static string GetTooltipText(ParameterAttribute param)
        {
            var sb = new StringBuilder(param.Description);

            if (param.Property.PropertyType == typeof(double))
            {
                sb.AppendLine().Append("Type: real number");
            }
            else if (param.Property.PropertyType == typeof(int))
            {
                sb.AppendLine().Append("Type: integer");
            }
            else if (param.Property.PropertyType.IsEnum)
            {
                sb.AppendLine();
                foreach (var desc in Enum.GetValues(param.Property.PropertyType).Cast <Enum>().Select(e => e.GetDescriptionForEnum()))
                {
                    sb.AppendLine().Append(desc.DisplayName + ": " + desc.Description);
                }
            }

            if (param.HasMinValue())
            {
                sb.Append(Environment.NewLine).Append("Min value: ").Append(param.MinValue);
            }
            if (param.HasMaxValue())
            {
                sb.Append(Environment.NewLine).Append("Max value: ").Append(param.MaxValue);
            }

            return(sb.ToString());
        }
        private static int ParameterOrder(string name, System.Reflection.ParameterInfo[] mParameters, ParameterAttribute parameter)
        {
            var methodParameter = mParameters.SingleOrDefault(x => x.Name == parameter.Name);
            if (methodParameter == null)
                throw new InvalidOperationException("Cannot find method parameter " + parameter.Name + " on " + name);

            return Array.IndexOf(mParameters, methodParameter);
        }
        /// <summary>
        /// Constructs an instance of the ParameterSetSpecificMetadata using the instance of the attribute
        /// that is specified.
        /// </summary>
        /// 
        /// <param name="attribute">
        /// The attribute to be compiled.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="attribute"/> is null.
        /// </exception>
        /// 
        internal ParameterSetSpecificMetadata(ParameterAttribute attribute)
        {
            if (attribute == null)
            {
                throw PSTraceSource.NewArgumentNullException("attribute");
            }

            _attribute = attribute;
            IsMandatory = attribute.Mandatory;
            Position = attribute.Position;
            ValueFromRemainingArguments = attribute.ValueFromRemainingArguments;
            this.valueFromPipeline = attribute.ValueFromPipeline;
            this.valueFromPipelineByPropertyName = attribute.ValueFromPipelineByPropertyName;
            HelpMessage = attribute.HelpMessage;
            HelpMessageBaseName = attribute.HelpMessageBaseName;
            HelpMessageResourceId = attribute.HelpMessageResourceId;
        }
 private static Channel ChannelFromParameter(ParameterAttribute parameter)
 {
     return (Channel)Enum.Parse(typeof(Channel), parameter.DisplayName);
 }
        /// <summary>
        /// Gets the pipeline input type
        /// </summary>
        /// <param name="paramAttrib">parameter attribute</param>
        /// <returns>pipeline input type</returns>
        private static string GetPipelineInputString(ParameterAttribute paramAttrib)
        {
            Debug.Assert(paramAttrib != null);

            ArrayList values = new ArrayList();

            if (paramAttrib.ValueFromPipeline)
            {
                values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue));
            }
            if (paramAttrib.ValueFromPipelineByPropertyName)
            {
                values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName));
            }
            if (paramAttrib.ValueFromRemainingArguments)
            {
                values.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments));
            }

            if (values.Count == 0)
            {
                return StringUtil.Format(HelpDisplayStrings.FalseShort);
            }

            StringBuilder sb = new StringBuilder();

            sb.Append(StringUtil.Format(HelpDisplayStrings.TrueShort));
            sb.Append(" (");

            for (int i = 0; i < values.Count; i++)
            {
                sb.Append((string)values[i]);

                if (i != (values.Count - 1))
                {
                    sb.Append(", ");
                }
            }

            sb.Append(")");

            return sb.ToString();
        }
Esempio n. 36
0
 public Node UpdateAttribute(ParameterAttribute attribute)
 {
     this.Attribute = attribute;
     return this;
 }
Esempio n. 37
0
        private static Attribute NewParameterAttribute(AttributeAst ast)
        {
            CheckNoPositionalArgs(ast);

            var cvv = new ConstantValueVisitor { AttributeArgument = true };

            var result = new ParameterAttribute();

            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;

                if (argumentName.Equals("Position", StringComparison.OrdinalIgnoreCase))
                {
                    result.Position = s_attrArgToIntConverter.Target(s_attrArgToIntConverter, argValue);
                }
                else if (argumentName.Equals("ParameterSetName", StringComparison.OrdinalIgnoreCase))
                {
                    result.ParameterSetName = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("Mandatory", StringComparison.OrdinalIgnoreCase))
                {
                    result.Mandatory = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromPipeline", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromPipeline = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromPipelineByPropertyName", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromPipelineByPropertyName = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromRemainingArguments", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromRemainingArguments = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessage", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessage = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessageBaseName", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessageBaseName = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessageResourceId", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessageResourceId = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("DontShow", StringComparison.OrdinalIgnoreCase))
                {
                    result.DontShow = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
Esempio n. 38
0
 public DataParameterInfo(ParameterAttribute attribute, PropertyInfo property)
 {
     Attribute = Verify.ArgumentNotNull(attribute, "attribute");
     Property = Verify.ArgumentNotNull(property, "property");
 }