示例#1
0
        public static void Add(PSCommand Command)
        {
            string route = (new Uri("http://localhost" + Command.GetRoutePath())).Segments.Take(4).Aggregate((current, next) => current + next.ToLower());

            Routes.Instance[Command.RestMethod][route] = Command;
        }
示例#2
0
        /// <summary>
        /// Get PSCommand object from information loaded by InvokePS()
        /// </summary>
        /// <returns></returns>
        public PSCommand GetPSCommand()
        {
            if (_cmdConfig == null || _cmdHelp == null || _cmdInfo == null)
            {
                throw new InvalidOperationException("Command information was not loaded. Use InvokePS() before to load it.");
            }


            FunctionInfo funcInfo = _cmdInfo as FunctionInfo;
            string       psVerb   = funcInfo?.Verb;

            //UriBuilder uriBuilder = new UriBuilder(_parentUri.ToString());
            //uriBuilder.Path += _cmdConfig.Name;

            var psCmd = new PSCommand(_cmdHelp.Name)
            {
                WebMethodName = _cmdConfig.Name,
                AsJob         = _cmdConfig.AsJob,
                Snapin        = _cmdConfig.Snapin,
                //Uri = uriBuilder.Uri,
                //Uri = new Uri(string.Format("{0}/{1}",_parentUri.ToString(),_cmdConfig.Name) ,UriKind.Relative),
                Uri        = new Uri(_parentUri.ToString() + "/" + _cmdConfig.Route, UriKind.Relative),
                Module     = _module,
                ModuleName = _cmdHelp.ModuleName ?? "",
                //Name = _cmdHelp.Name,
                Synopsis    = _cmdHelp.Synopsis ?? "",
                Description = _cmdHelp.description == null ? "" : _cmdHelp.description[0].Text,
                OutTypeName = _cmdInfo.OutputType.Select(x => x.Name.ToString()).ToArray(),

                /*
                 * RestMethod = _cmdConfig.RestMethod != null
                 *           ? (RestMethod)_cmdConfig.RestMethod
                 *           : psVerb != null && PsVerbMapping.ContainsKey(psVerb)
                 *              ? PsVerbMapping[psVerb]
                 *              : Constants.DefaultRestMethod
                 */
                RestMethod     = _cmdConfig.RestMethod,
                Roles          = _cmdConfig.Roles,
                Users          = _cmdConfig.Users,
                AllowAnonymous = _cmdConfig.AllowAnonymous,
                ApiName        = _apiName
            };

            // Not Available cmdInfo.Notes

            if (_cmdHelp.Parameters == null)
            {
                PowerShellRestApiEvents.Raise.VerboseMessaging(String.Format("Help of command {0} is malformed.", psCmd.Name));
                throw new MissingParametersException(String.Format("Help of command {0} is malformed.", psCmd.Name));
            }

            dynamic[] psHelpParamters = _cmdHelp.Parameters.parameter is Array
                                        ? (dynamic[])_cmdHelp.Parameters.parameter
                                        : new dynamic[] { _cmdHelp.Parameters.parameter };

            int position = 0;

            foreach (dynamic paramHelp in psHelpParamters)
            {
                // Get Paramter Name
                string paramName   = paramHelp.name.ToString();
                var    paramConfig = _cmdConfig.Parameters.Where(x => x.Name.Equals(paramName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                // Informations from CommandInfo and HelpInfo
                ParameterMetadata paramMeta = _cmdInfo.Parameters[paramName];

                object defaultValue = ((PSObject)paramHelp.defaultValue)?.BaseObject;
                if (paramHelp.defaultValue != null)
                {
                    if (paramMeta.ParameterType.Equals(typeof(string)))
                    {
                        defaultValue = paramHelp.defaultValue.BaseObject;
                    }
                    else if (paramMeta.ParameterType.Equals(typeof(int)))
                    {
                        defaultValue = int.Parse(defaultValue.ToString());
                    }
                }

                Type paramType = paramMeta.SwitchParameter ? typeof(bool) : paramMeta.ParameterType;

                var psParam = new PSParameter(paramName, paramType)
                {
                    // from HelpInfo
                    DefaultValue = defaultValue,
                    Description  = paramHelp.description?[0].Text,
                    Position     = int.TryParse(paramHelp.position, out int pos) ? position = pos : ++position,
                    IsSwitch     = paramMeta.SwitchParameter,
                };

                // Add validation attribute from CommandInfo
                psParam.AddValidate(paramMeta.Attributes.ToArray());

                // Set parameter name to ParameterForUser if it matches the name defined in config file
                if (paramName.Equals(_cmdConfig.ParameterForUserName, StringComparison.InvariantCultureIgnoreCase) &&
                    paramType == typeof(String))
                {
                    psCmd.ParameterForUser = paramName;
                    psParam.Hidden         = true;
                }
                // Set parameter name to ParameterForRoles if it matches the name defined in config file
                else if (paramName.Equals(_cmdConfig.ParameterForUserRoles, StringComparison.InvariantCultureIgnoreCase) &&
                         paramType == typeof(String[]))
                {
                    psCmd.ParameterForRoles = paramName;
                    psParam.Hidden          = true;
                }
                // Set parameter name to ParameterForClaims if it matches the name defined in config file
                else if (paramName.Equals(_cmdConfig.ParameterForUserClaims, StringComparison.InvariantCultureIgnoreCase) &&
                         paramType == typeof(Claim[]))
                {
                    psCmd.ParameterForClaims = paramName;
                    psParam.Hidden           = true;
                }
                // Set parameter name to ParameterForClaims if it is same type and ParameterForClaims is not defined in config file
                else if (string.IsNullOrWhiteSpace(_cmdConfig.ParameterForUserClaims) &&
                         paramType == typeof(Claim[]))
                {
                    psCmd.ParameterForClaims = paramName;
                    psParam.Hidden           = true;
                }
                //Override this parameter if it set in from App.config
                else if (paramConfig?.Hidden != null)
                {
                    psParam.Hidden = (bool)paramConfig.Hidden;
                }

                // Static file from configuration file
                if (!string.IsNullOrWhiteSpace(paramConfig?.Value))
                {
                    psParam.Location = RestLocation.ConfigFile;
                    psParam.Value    = paramConfig.Value;
                    psParam.Hidden   = true;
                }
                else
                {
                    // Parameter location
                    if (paramConfig?.Location == null)
                    {
                        if (psCmd.RestMethod == RestMethod.Get)
                        {
                            psParam.Location = RestLocation.Query;
                        }
                        else
                        {
                            psParam.Location = RestLocation.Body;
                        }
                    }
                    else
                    {
                        psParam.Location = (RestLocation)paramConfig.Location;
                    }
                }

                if (psParam.Location == RestLocation.Header && (psParam.Name == "Accept" || psParam.Name == "Content-Type" || psParam.Name == "Authorization"))
                {
                    //TO DO : Write warning

                    psParam.Location = RestLocation.Query;
                }

                if (!psParam.Hidden)
                {
                    psParam.GenerateModel();
                }

                // Add new parameter in collection
                psCmd.Parameters.Add(psParam);
            }

            return(psCmd);
        }