コード例 #1
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);
        }
コード例 #2
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);
        }
コード例 #3
0
        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);
        }
        public void ConstructCorrectDynamicParameterBasedOnCurrentSku()
        {
            //Arrange
            CacheServiceSkuType skuType = CacheServiceSkuType.Standard;
            int    expectedValueNumber  = 10;
            string minValue             = "1GB";
            string maxValue             = "10GB";
            string secondMinValue       = "2GB";
            string memoryParameterName  = "Memory";
            MemoryDynamicParameterSet memoryDynamicParameter = new MemoryDynamicParameterSet();

            //Act
            RuntimeDefinedParameterDictionary parameters = memoryDynamicParameter.GetDynamicParameters(skuType)
                                                           as RuntimeDefinedParameterDictionary;
            RuntimeDefinedParameter parameter = parameters[memoryParameterName];

            //Assert
            Assert.Equal(memoryParameterName, parameter.Name);
            Assert.Equal(2, parameter.Attributes.Count);
            Assert.True(parameter.Attributes[1] is ValidateSetAttribute);
            ValidateSetAttribute validateSetAttribute = parameter.Attributes[1] as ValidateSetAttribute;

            Assert.Equal(expectedValueNumber, validateSetAttribute.ValidValues.Count);
            Assert.Equal(minValue, validateSetAttribute.ValidValues[0]);
            Assert.Equal(secondMinValue, validateSetAttribute.ValidValues[1]);
            Assert.Equal(maxValue, validateSetAttribute.ValidValues[expectedValueNumber - 1]);
        }
コード例 #5
0
ファイル: GetGitDir.cs プロジェクト: DavidWise/DWGitSH
        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);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        protected virtual void AddParameters()
        {
            var benutzer = this.GetClient().GetBenutzer().Select(b => b.Value).ToArray();

            if (benutzer.Any())
            {
                var validateSet = new ValidateSetAttribute(benutzer);
                this.AddParameter(BenutzerKey, typeof(string[]), 0, true, p => p.Add(validateSet), "Benutzer", true);
            }
        }
コード例 #8
0
ファイル: AssignedTagNode.cs プロジェクト: wgross/TreeStore
        private RuntimeDefinedParameterDictionary BuildItemPropertyParameters(ValidateSetAttribute validateSet)
        {
            var propertyNameParameter = new RuntimeDefinedParameter("TreeStorePropertyName", typeof(string), new Collection <Attribute>());

            propertyNameParameter.Attributes.Add(this.ParameterAttribute());
            propertyNameParameter.Attributes.Add(validateSet);
            var parameter = new RuntimeDefinedParameterDictionary();

            parameter.Add(propertyNameParameter.Name, propertyNameParameter);
            return(parameter);
        }
コード例 #9
0
        private static Collection <ValidateSetAttribute> GetValidateSetAttribute(Collection <Attribute> attributes)
        {
            Collection <ValidateSetAttribute> collection = new Collection <ValidateSetAttribute>();

            foreach (Attribute attribute in attributes)
            {
                ValidateSetAttribute item = attribute as ValidateSetAttribute;
                if (item != null)
                {
                    collection.Add(item);
                }
            }
            return(collection);
        }
コード例 #10
0
        /// <summary>
        /// Gets the validate set attribute from parameter metadata.
        /// </summary>
        /// <param name="attributes">Parameter attributes.</param>
        /// <returns>Collection of parameter attributes.</returns>
        private static Collection <ValidateSetAttribute> GetValidateSetAttribute(Collection <Attribute> attributes)
        {
            Collection <ValidateSetAttribute> validateSetAttributes = new Collection <ValidateSetAttribute>();

            foreach (Attribute attribute in attributes)
            {
                ValidateSetAttribute validateSetAttribute = (object)attribute as ValidateSetAttribute;

                if (validateSetAttribute != null)
                {
                    validateSetAttributes.Add(validateSetAttribute);
                }
            }

            return(validateSetAttributes);
        }
コード例 #11
0
        public void ConstructsDynamicParameter()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "computeMode";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <string>()
                {
                    "Mode1", "Mode2", "Mode3"
                },
                DefaultValue = "Mode1",
                MaxLength    = "5",
                MinLength    = "1",
                Type         = "string"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

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

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

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

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

            ValidateSetAttribute validateSetAttribute = (ValidateSetAttribute)dynamicParameter.Attributes[1];

            Assert.Equal(3, validateSetAttribute.ValidValues.Count);
            Assert.True(validateSetAttribute.IgnoreCase);
            Assert.True(value.AllowedValues.Contains(validateSetAttribute.ValidValues[0]));
            Assert.True(value.AllowedValues.Contains(validateSetAttribute.ValidValues[1]));
            Assert.True(value.AllowedValues.Contains(validateSetAttribute.ValidValues[2]));
            Assert.False(validateSetAttribute.ValidValues[0].Contains(' '));
            Assert.False(validateSetAttribute.ValidValues[1].Contains(' '));
            Assert.False(validateSetAttribute.ValidValues[2].Contains(' '));

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

            Assert.Equal(int.Parse(value.MinLength), validateLengthAttribute.MinLength);
            Assert.Equal(int.Parse(value.MaxLength), validateLengthAttribute.MaxLength);
        }
コード例 #12
0
        private RuntimeDefinedParameter GetParameter(string parameterName, string resourceAppId, string type)
        {
            var attributeCollection = new System.Collections.ObjectModel.Collection <Attribute>();
            var parameterAttribute  = new ParameterAttribute
            {
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                Mandatory = false
            };

            attributeCollection.Add(parameterAttribute);
            var validateSetAttribute = new ValidateSetAttribute(new PermissionScopes().GetIdentifiers(resourceAppId, type));

            attributeCollection.Add(validateSetAttribute);
            var parameter = new RuntimeDefinedParameter(parameterName, typeof(string[]), attributeCollection);

            return(parameter);
        }
コード例 #13
0
        public static RuntimeDefinedParameter GetAttributeNameParameter(string paramName, bool mandatory, int position, string objectType, string parameterSetName)
        {
            RuntimeDefinedParameter parameter = new RuntimeDefinedParameter();

            parameter.Name          = paramName;
            parameter.ParameterType = typeof(string);

            if (objectType == null)
            {
                List <string> attributeNames = new List <string>();

                IList <ObjectTypeDefinition> objectTypes = ResourceManagementSchema.GetObjectTypes().ToList();

                if (objectTypes.Count > 0)
                {
                    foreach (ObjectTypeDefinition type in objectTypes)
                    {
                        attributeNames.AddRange(type.Attributes.Select(t => t.SystemName));
                    }

                    if (attributeNames.Count > 0)
                    {
                        ValidateSetAttribute setAttribute = new ValidateSetAttribute(attributeNames.Distinct().OrderBy(t => t).ToArray());
                        parameter.Attributes.Add(setAttribute);
                    }
                }
            }
            else
            {
                if (ResourceManagementSchema.ContainsObjectType(objectType))
                {
                    ValidateSetAttribute setAttribute = new ValidateSetAttribute(ResourceManagementSchema.GetObjectType(objectType).Attributes.OrderBy(t => t.SystemName).Select(t => t.SystemName).ToArray());
                    parameter.Attributes.Add(setAttribute);
                }
            }

            ParameterAttribute paramAttribute = new ParameterAttribute();

            paramAttribute.Mandatory        = mandatory;
            paramAttribute.Position         = position;
            paramAttribute.ParameterSetName = parameterSetName;
            parameter.Attributes.Add(paramAttribute);
            return(parameter);
        }
コード例 #14
0
        /// <summary>
        /// Generate a RuntimeDefinedParameter based on the parameter name,
        /// the help message and the valid set of parameter values.
        /// </summary>
        public RuntimeDefinedParameter GenerateRuntimeParameter(
            string parameterName,
            string helpMessage,
            string[] validSet,
            bool isMandatory = false,
            params string[] parameterSetNames)
        {
            List <Attribute> attributeLists = new List <Attribute>();

            if (parameterSetNames.Length == 0)
            {
                ParameterAttribute paramAttribute = new ParameterAttribute()
                {
                    Mandatory   = isMandatory,
                    HelpMessage = helpMessage
                };
                attributeLists.Add(paramAttribute);
            }
            else
            {
                for (int i = 0; i < parameterSetNames.Length; i += 1)
                {
                    ParameterAttribute paramAttribute = new ParameterAttribute()
                    {
                        Mandatory   = isMandatory,
                        HelpMessage = helpMessage
                    };
                    paramAttribute.ParameterSetName = parameterSetNames[i];
                    attributeLists.Add(paramAttribute);
                }
            }

            if (validSet?.Length != 0)
            {
                var validateSetAttribute = new ValidateSetAttribute(validSet);
                validateSetAttribute.IgnoreCase = true;
                attributeLists.Add(validateSetAttribute);
            }

            Collection <Attribute> attributes = new Collection <Attribute>(attributeLists);

            return(new RuntimeDefinedParameter(parameterName, typeof(string), attributes));
        }
コード例 #15
0
        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>();

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

            attributeCollection.Add(parameterAttribute);
            attributeCollection.Add(new ObsoleteAttribute("Use either -GraphApplicationPermissions, -GraphDelegatePermissions, -SharePointApplicationPermissions or -SharePointDelegatePermissions"));

            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);

            // Graph
            parameterDictionary.Add("GraphApplicationPermissions", GetParameter("GraphApplicationPermissions", PermissionScopes.ResourceAppId_Graph, "Role"));
            parameterDictionary.Add("GraphDelegatePermissions", GetParameter("GraphDelegatePermissions", PermissionScopes.ResourceAppId_Graph, "Scope"));

            // SharePoint
            parameterDictionary.Add("SharePointApplicationPermissions", GetParameter("SharePointApplicationPermissions", PermissionScopes.ResourceAppId_SPO, "Role"));
            parameterDictionary.Add("SharePointDelegatePermissions", GetParameter("SharePointDelegatePermissions", PermissionScopes.ResourceAppId_SPO, "Scope"));

            // O365 Management
            parameterDictionary.Add("O365ManagementApplicationPermissions", GetParameter("O365ManagementApplicationPermissions", PermissionScopes.ResourceAppID_O365Management, "Role"));
            parameterDictionary.Add("O365ManagementDelegatePermissions", GetParameter("O365ManagementDelegatePermissions", PermissionScopes.ResourceAppID_O365Management, "Scope"));

            return(parameterDictionary);
        }
コード例 #16
0
        /// <summary>
        /// Returns an instance of an object that defines the
        /// dynamic parameters for this
        /// <see cref="T:System.Management.Automation.Cmdlet" /> or <see cref="T:System.Management.Automation.Provider.CmdletProvider" />.
        /// </summary>
        /// <returns>This method should return an object that has properties and fields
        /// decorated with parameter attributes similar to a
        /// <see cref="T:System.Management.Automation.Cmdlet" /> or <see cref="T:System.Management.Automation.Provider.CmdletProvider" />.
        /// These attributes include <see cref="T:System.Management.Automation.ParameterAttribute" />,
        /// <see cref="T:System.Management.Automation.AliasAttribute" />, argument transformation and
        /// validation attributes, etc.
        /// Alternately, it can return a
        /// <see cref="T:System.Management.Automation.RuntimeDefinedParameterDictionary" />
        /// instead.
        /// The <see cref="T:System.Management.Automation.Cmdlet" /> or <see cref="T:System.Management.Automation.Provider.CmdletProvider" />
        /// should hold on to a reference to the object which it returns from
        /// this method, since the argument values for the dynamic parameters
        /// specified by that object will be set in that object.
        /// This method will be called after all formal (command-line)
        /// parameters are set, but before <see cref="M:System.Management.Automation.Cmdlet.BeginProcessing" />
        /// is called and before any incoming pipeline objects are read.
        /// Therefore, parameters which allow input from the pipeline
        /// may not be set at the time this method is called,
        /// even if the parameters are mandatory.</returns>
        public object GetDynamicParameters()
        {
            var parameterName = "AccountName";
            var runTimeParameterDictionary = new RuntimeDefinedParameterDictionary();
            var attributeCollection        = new Collection <Attribute>();
            var parameterAttribute         = new ParameterAttribute();

            parameterAttribute.Mandatory = true;
            parameterAttribute.Position  = 1;
            attributeCollection.Add(parameterAttribute);
            var arraySet             = AzureDevOpsConfiguration.Config.Accounts.GetAccountNames();
            var validateSetAttribute = new ValidateSetAttribute(arraySet);

            attributeCollection.Add(validateSetAttribute);
            var runtimeParameter = new RuntimeDefinedParameter(parameterName, typeof(string), attributeCollection);

            runTimeParameterDictionary.Add(parameterName, runtimeParameter);
            return(runTimeParameterDictionary);
        }
コード例 #17
0
        public void AddToParamDictionary(RuntimeDefinedParameterDictionary paramDictionary)
        {
            var attributes = new Collection <Attribute>();

            var parameterAttribute = new ParameterAttribute();

            parameterAttribute.Mandatory = true;
            if (null != Position)
            {
                parameterAttribute.Position = 1;
            }
            if (null != HelpMessage)
            {
                parameterAttribute.HelpMessage = HelpMessage;
            }
            if (null != ParameterSetName)
            {
                parameterAttribute.ParameterSetName = ParameterSetName;
            }
            parameterAttribute.Mandatory = Mandatory;
            attributes.Add(parameterAttribute);

            if (null != ValidateSetValues)
            {
                var validateSetAttribute = new ValidateSetAttribute(ValidateSetValues);
                attributes.Add(validateSetAttribute);
            }

            RuntimeDefinedParameter OptionsRuntimeDefinedParam;

            if (AllowMultiple)
            {
                OptionsRuntimeDefinedParam = new RuntimeDefinedParameter(Name, typeof(string[]), attributes);
            }
            else
            {
                OptionsRuntimeDefinedParam = new RuntimeDefinedParameter(Name, typeof(string), attributes);
            }

            paramDictionary.Add(Name, OptionsRuntimeDefinedParam);
        }
コード例 #18
0
        public object GetDynamicParameters()
        {
            _lib = new RuntimeDefinedParameterDictionary();
            RuntimeDefinedParameter rtParam = new RuntimeDefinedParameter(PARAM, typeof(long[]), new Collection <Attribute>
            {
                new ParameterAttribute
                {
                    Mandatory = false,
                    Position  = 0
                }
            });

            if (History.IsInitialized() && History.Jobs.Count > 0)
            {
                var set = new ValidateSetAttribute(History.Jobs.Select(x => Convert.ToString(x.Id)).ToArray());
                rtParam.Attributes.Add(set);
            }

            _lib.Add(PARAM, rtParam);
            return(_lib);
        }
コード例 #19
0
        public RuntimeDefinedParameterDictionary GetDynamicParameters()
        {
            RuntimeDefinedParameterDictionary dictionary = new RuntimeDefinedParameterDictionary();
            Collection <Attribute>            collection = new Collection <Attribute>();
            ParameterAttribute parameter = new ParameterAttribute();

            parameter.ParameterSetName = "ByName";
            collection.Add(parameter);

            IEnumerable <string> names = RegistryHelper.ShellKeyNames;

            ValidateSetAttribute validateSet = new ValidateSetAttribute(names.ToArray());

            collection.Add(validateSet);

            RuntimeDefinedParameter nameParameter = new RuntimeDefinedParameter("Name", typeof(string), collection);

            dictionary.Add("Name", nameParameter);

            DynamicParameters = dictionary;
            return(dictionary);
        }
コード例 #20
0
        /// <summary>
        /// This function is part of the IDynamicParameters interface.
        /// PowerShell uses it to generate parameters dynamically.
        /// We have to generate -ResourceType parameter dynamically because the array
        /// of resources that we used to validate against are not generated before compile time,
        /// i.e. [ValidateSet(ArrayGeneratedAtRunTime)] will throw an error for parameters
        /// that are not generated dynamically.
        /// </summary>
        public object GetDynamicParameters()
        {
            if (_dynamicParameters == null)
            {
                ParameterAttribute paramAttribute = new ParameterAttribute()
                {
                    Mandatory = true
                };
                ValidateSetAttribute validateSetAttribute = new ValidateSetAttribute(AllResourceTypes);
                validateSetAttribute.IgnoreCase = true;
                Collection <Attribute> attributes =
                    new Collection <Attribute>(new Attribute[] { validateSetAttribute, paramAttribute });
                // This parameter can now be thought of as:
                // [Parameter(Mandatory = true)]
                // [ValidateSet(validTypeValues)]
                // public string { get; set; }
                RuntimeDefinedParameter typeParameter = new RuntimeDefinedParameter("ResourceType", typeof(string), attributes);
                _dynamicParameters = new RuntimeDefinedParameterDictionary();
                _dynamicParameters.Add("ResourceType", typeParameter);
            }

            return(_dynamicParameters);
        }
コード例 #21
0
ファイル: Compiler.cs プロジェクト: 40a/PowerShell
        private static Attribute NewValidateSetAttribute(AttributeAst ast)
        {
            var cvv = new ConstantValueVisitor { AttributeArgument = true };
            var args = new string[ast.PositionalArguments.Count];
            for (int i = 0; i < ast.PositionalArguments.Count; i++)
            {
                args[i] = _attrArgToStringConverter.Target(_attrArgToStringConverter,
                    ast.PositionalArguments[i].Accept(cvv));
            }

            var result = new ValidateSetAttribute(args);
            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;
                if (argumentName.Equals("IgnoreCase", StringComparison.OrdinalIgnoreCase))
                {
                    result.IgnoreCase = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
コード例 #22
0
ファイル: InvokeRemoteOpenRPA.cs プロジェクト: xmkodi/openrpa
        public object GetDynamicParameters()
        {
            try
            {
                callcount++;
                if (_Collections == null)
                {
                    Initialize().Wait(5000);
                }
                if (global.webSocketClient == null || !global.webSocketClient.isConnected || global.webSocketClient.user == null)
                {
                    return(new RuntimeDefinedParameterDictionary());
                }
                RuntimeDefinedParameter targetnameparameter   = null;
                RuntimeDefinedParameter workflownameparameter = null;
                if (_robots == null)
                {
                    WriteStatus("Getting possible robots and roles");
                    _robots = global.webSocketClient.Query <apiuser>("users", "{\"$or\":[ {\"_type\": \"user\"}, {\"_type\": \"role\", \"rparole\": true} ]}", top: 2000).Result;
                }
                var TargetName = this.GetUnboundValue <string>("TargetName");
                if (_staticStorage != null)
                {
                    _staticStorage.TryGetValue("TargetName", out targetnameparameter);
                    _staticStorage.TryGetValue("WorkflowName", out workflownameparameter);
                    //WriteStatus(2, "targetname: " + targetnameparameter.Value + " workflowname: " + workflownameparameter.Value + " test: " + TargetName + "    ");
                    //WriteStatus(1, "targetname: " + targetnameparameter.IsSet + " workflowname: " + workflownameparameter.IsSet + "     ");
                }
                else
                {
                    var robotnames     = _robots.Select(x => x.name).ToArray();
                    var targetnameattr = new Collection <Attribute>()
                    {
                        new ParameterAttribute()
                        {
                            HelpMessage = "Targer username or group name",
                            Position    = 1
                        },
                        new ValidateSetAttribute(robotnames)
                    };
                    targetnameparameter = new RuntimeDefinedParameter("TargetName", typeof(string), targetnameattr);
                    var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary();
                    runtimeDefinedParameterDictionary.Add("TargetName", targetnameparameter);
                    _staticStorage = runtimeDefinedParameterDictionary;
                }

                apiuser robot    = null;
                string  targetid = TargetId;

                if (targetnameparameter.Value != null)
                {
                    TargetName = targetnameparameter.Value.ToString();
                }
                if (!string.IsNullOrEmpty(TargetName))
                {
                    robot = _robots.Where(x => x.name == TargetName).FirstOrDefault();
                    if (robot != null)
                    {
                        targetid = robot._id;
                    }
                }
                else if (!string.IsNullOrEmpty(targetid))
                {
                    robot = _robots.Where(x => x._id == targetid).FirstOrDefault();
                }

                if ((_workflows == null || lasttargetid != targetid) && robot != null)
                {
                    WriteStatus("Getting possible workflows for " + robot.name);
                    _workflows   = global.webSocketClient.Query <workflow>("openrpa", "{_type: 'workflow'}", projection: "{\"projectandname\": 1}", queryas: targetid, top: 2000).Result;
                    lasttargetid = targetid;
                }
                int wflen = 0;
                if (_workflows != null)
                {
                    wflen = _workflows.Length;
                }
                if (robot != null)
                {
                    WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen + " for " + robot.name);
                }
                else
                {
                    WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen);
                }

                if (workflownameparameter == null)
                {
                    var workflownameattr = new Collection <Attribute>()
                    {
                        new ParameterAttribute()
                        {
                            HelpMessage = "Workflow name",
                            Position    = 2
                        }
                    };
                    workflownameparameter = new RuntimeDefinedParameter("WorkflowName", typeof(string), workflownameattr);
                    _staticStorage.Add("WorkflowName", workflownameparameter);
                }
                if (workflownameparameter != null)
                {
                    ValidateSetAttribute wfname = (ValidateSetAttribute)workflownameparameter.Attributes.Where(x => x.GetType() == typeof(ValidateSetAttribute)).FirstOrDefault();
                    if (wfname != null)
                    {
                        workflownameparameter.Attributes.Remove(wfname);
                    }
                    if (_workflows != null && _workflows.Length > 0)
                    {
                        var workflownames = _workflows.Select(x => x.ProjectAndName).ToArray();
                        wfname = new ValidateSetAttribute(workflownames);
                        workflownameparameter.Attributes.Add(wfname);
                    }
                }
                return(_staticStorage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine(ex.Message);
                throw;
            }
        }
コード例 #23
0
        public void CanGenerateValidators()
        {
            Type         type     = Assembly.GetExecutingAssembly().GetType("Debugging.Tests.ClassWithProperties");
            PropertyInfo property = type.GetProperty("PropertyWithValidators");

            ValidateCreditCardAttribute ccAttribute = property.GetCustomAttributes(typeof(ValidateCreditCardAttribute), false)[0] as ValidateCreditCardAttribute;

            Assert.IsNotNull(ccAttribute);

            ValidateEmailAttribute emailAttribute = property.GetCustomAttributes(typeof(ValidateEmailAttribute), false)[0] as ValidateEmailAttribute;

            Assert.IsNotNull(emailAttribute);

            ValidateRegExpAttribute regExpAttribute = property.GetCustomAttributes(typeof(ValidateRegExpAttribute), false)[0] as ValidateRegExpAttribute;

            Assert.IsNotNull(regExpAttribute);

            ValidateLengthAttribute lengthAttribute = property.GetCustomAttributes(typeof(ValidateLengthAttribute), false)[0] as ValidateLengthAttribute;

            Assert.IsNotNull(lengthAttribute);

            ValidateDateAttribute dateAttribute = property.GetCustomAttributes(typeof(ValidateDateAttribute), false)[0] as ValidateDateAttribute;

            Assert.IsNotNull(dateAttribute);

            ValidateDateTimeAttribute dateTimeAttribute = property.GetCustomAttributes(typeof(ValidateDateTimeAttribute), false)[0] as ValidateDateTimeAttribute;

            Assert.IsNotNull(dateTimeAttribute);

            ValidateDecimalAttribute decimalAttribute = property.GetCustomAttributes(typeof(ValidateDecimalAttribute), false)[0] as ValidateDecimalAttribute;

            Assert.IsNotNull(decimalAttribute);

            ValidateDoubleAttribute doubleAttribute = property.GetCustomAttributes(typeof(ValidateDoubleAttribute), false)[0] as ValidateDoubleAttribute;

            Assert.IsNotNull(doubleAttribute);

            ValidateIntegerAttribute integerAttribute = property.GetCustomAttributes(typeof(ValidateIntegerAttribute), false)[0] as ValidateIntegerAttribute;

            Assert.IsNotNull(integerAttribute);

            ValidateNonEmptyAttribute nonEmptyAttribute = property.GetCustomAttributes(typeof(ValidateNonEmptyAttribute), false)[0] as ValidateNonEmptyAttribute;

            Assert.IsNotNull(nonEmptyAttribute);

            ValidateRangeAttribute rangeAttribute = property.GetCustomAttributes(typeof(ValidateRangeAttribute), false)[0] as ValidateRangeAttribute;

            Assert.IsNotNull(rangeAttribute);

            ValidateSameAsAttribute sameAsAttribute = property.GetCustomAttributes(typeof(ValidateSameAsAttribute), false)[0] as ValidateSameAsAttribute;

            Assert.IsNotNull(sameAsAttribute);

            ValidateSetAttribute setAttribute = property.GetCustomAttributes(typeof(ValidateSetAttribute), false)[0] as ValidateSetAttribute;

            Assert.IsNotNull(setAttribute);

            ValidateSingleAttribute singleAttribute = property.GetCustomAttributes(typeof(ValidateSingleAttribute), false)[0] as ValidateSingleAttribute;

            Assert.IsNotNull(singleAttribute);
        }
コード例 #24
0
        protected override void ProcessRecord()
        {
            ParameterAttribute paramAttrib = new ParameterAttribute()
            {
                ParameterSetName = _parameterSetName,
                Mandatory        = _mandatory,
                ValueFromPipelineByPropertyName = _valueFromPipelineByPropertyName,
                ValueFromPipeline           = _valueFromPipeline,
                ValueFromRemainingArguments = _valueFromRemainingArguments
            };

            if (_positionSpecified == true)
            {
                paramAttrib.Position = _position;
            }

            if (!string.IsNullOrEmpty(HelpMessage))
            {
                paramAttrib.HelpMessage = HelpMessage;
            }

            // add common param attributes and ValidateSet (if any) to a collection
            Collection <Attribute> attribCollection = new Collection <Attribute>();

            attribCollection.Add(paramAttrib);

            // === Attributes ===

            if (ParameterSetName == "Validate")
            {
                ValidateSetAttribute paramValidateSet = new ValidateSetAttribute(ValidateSet);
                attribCollection.Add(paramValidateSet);
            }

            if (Alias != null && Alias.Length != 0)
            {
                attribCollection.Add(new AliasAttribute(Alias));
            }

            if (_allowEmptyCollection == true)
            {
                attribCollection.Add(new AllowEmptyCollectionAttribute());
            }

            if (_allowEmptyString == true)
            {
                attribCollection.Add(new AllowEmptyStringAttribute());
            }

            if (_allowNull == true)
            {
                attribCollection.Add(new AllowNullAttribute());
            }

            if (_hidden == true)
            {
                attribCollection.Add(new HiddenAttribute());
            }

            //if (_validateUserDrive == true)
            //    attribCollection.Add(new ValidateUserDriveAttribute());

            //if (_validateDrive == true)
            //    attribCollection.Add(new ValidateDriveAttribute());

            if (_validateNotNullOrEmpty == true)
            {
                attribCollection.Add(new ValidateNotNullOrEmptyAttribute());
            }

            if (_validateNotNull == true)
            {
                attribCollection.Add(new ValidateNotNullAttribute());
            }

            if (ValidateScript != null)
            {
                attribCollection.Add(new ValidateScriptAttribute(ValidateScript));
            }

            if (!string.IsNullOrEmpty(ValidatePattern))
            {
                attribCollection.Add(new ValidatePatternAttribute(ValidatePattern));
            }

            if (ValidateRange != null)
            {
                if (ValidateRange.Length == 2)
                {
                    attribCollection.Add(new ValidateRangeAttribute(ValidateRange[0], ValidateRange[1]));
                }
                else
                {
                    attribCollection.Add(new ValidateRangeAttribute(ValidateRange[0], Int32.MaxValue));
                }
            }

            if (ValidateLength != null)
            {
                if (ValidateLength.Length == 2)
                {
                    attribCollection.Add(new ValidateLengthAttribute(ValidateLength[0], ValidateLength[1]));
                }
                else
                {
                    attribCollection.Add(new ValidateLengthAttribute(ValidateLength[0], Int32.MaxValue));
                }
            }

            // === /Attributes ===

            // add parameter to parameter list
            RuntimeDefinedParameter dynParam = new RuntimeDefinedParameter(Name, Type, attribCollection);

            if (_defaultValueSpecified == true && _mandatory != true)
            {
                dynParam.Value = _defaultValue;
            }

            if (ParameterObject == null)
            {
                ParameterObject        = new RuntimeDefinedParameterDictionary();
                _addToExistingPipeline = false;
            }
            else
            {
                _addToExistingPipeline = true;
            }

            ParameterObject.Add(Name, dynParam);
        }