/// <summary>
        /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
        /// and if yes, then returns the help target to display.
        /// </summary>
        /// <param name="helpTarget">Help target to request.</param>
        /// <param name="helpCategory">Help category to request.</param>
        /// <returns><see langword="true"/> if user requested help; <see langword="false"/> otherwise.</returns>
        internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
        {
            if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null)
            {
                foreach (CommandParameterInternal parameter in this.arguments)
                {
                    Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
                    if (parameter.IsDashQuestion())
                    {
                        Dictionary <Ast, Token[]> scriptBlockTokenCache = new Dictionary <Ast, Token[]>();
                        HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo,
                                                                     dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out _, helpUriFromDotLink: out _);
                        if (helpInfo == null)
                        {
                            break;
                        }

                        helpTarget   = helpInfo.Name;
                        helpCategory = helpInfo.HelpCategory;
                        return(true);
                    }
                }
            }

            return(base.IsHelpRequested(out helpTarget, out helpCategory));
        }
Esempio n. 2
0
        /// <summary>
        /// Creates a command processor for "get-help [helpTarget]"
        /// </summary>
        /// <param name="context">context for the command processor</param>
        /// <param name="helpTarget">help target</param>
        /// <param name="helpCategory">help category</param>
        /// <returns>command processor for "get-help [helpTarget]"</returns>
        internal static CommandProcessorBase CreateGetHelpCommandProcessor(
            ExecutionContext context,
            string helpTarget,
            HelpCategory helpCategory)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(helpTarget))
            {
                throw PSTraceSource.NewArgumentNullException("helpTarget");
            }

            CommandProcessorBase helpCommandProcessor = context.CreateCommand("get-help", false);
            var cpi = CommandParameterInternal.CreateParameterWithArgument(
                /*parameterAst*/ null, "Name", "-Name:",
                /*argumentAst*/ null, helpTarget,
                false);

            helpCommandProcessor.AddParameter(cpi);
            cpi = CommandParameterInternal.CreateParameterWithArgument(
                /*parameterAst*/ null, "Category", "-Category:",
                /*argumentAst*/ null, helpCategory.ToString(),
                false);
            helpCommandProcessor.AddParameter(cpi);
            return(helpCommandProcessor);
        }
Esempio n. 3
0
 private void ValidateAndThrowIfError(HelpCategory cat)
 {
     using (GetHelpCommand.tracer.TraceMethod(nameof(ValidateAndThrowIfError), new object[0]))
     {
         if (cat == HelpCategory.None)
         {
             return;
         }
         HelpCategory helpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ScriptCommand | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript;
         if ((cat & helpCategory) != HelpCategory.None)
         {
             return;
         }
         if (!string.IsNullOrEmpty(this._parameter))
         {
             throw GetHelpCommand.tracer.NewArgumentException("Parameter", "HelpErrors", "ParamNotSupported", (object)"-Parameter");
         }
         if (this._component != null)
         {
             throw GetHelpCommand.tracer.NewArgumentException("Component", "HelpErrors", "ParamNotSupported", (object)"-Component");
         }
         if (this._role != null)
         {
             throw GetHelpCommand.tracer.NewArgumentException("Role", "HelpErrors", "ParamNotSupported", (object)"-Role");
         }
         if (this._functionality != null)
         {
             throw GetHelpCommand.tracer.NewArgumentException("Functionality", "HelpErrors", "ParamNotSupported", (object)"-Functionality");
         }
     }
 }
Esempio n. 4
0
        internal MamlCommandHelpInfo Copy(HelpCategory newCategoryToUse)
        {
            MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), newCategoryToUse);

            result.FullHelp.Properties["Category"].Value = newCategoryToUse;
            return(result);
        }
Esempio n. 5
0
 /// <summary>
 /// Constructor for SyntaxHelpInfo
 /// </summary>
 private SyntaxHelpInfo(string name, string text, HelpCategory category)
     : base(category)
 {
     FullHelp = PSObject.AsPSObject(text);
     Name = name;
     Synopsis = text;
 }
Esempio n. 6
0
 private void ValidateAndThrowIfError(HelpCategory cat)
 {
     if (cat != HelpCategory.None)
     {
         HelpCategory category = HelpCategory.Workflow | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Cmdlet | HelpCategory.Alias;
         if ((cat & category) == HelpCategory.None)
         {
             if (!string.IsNullOrEmpty(this._parameter))
             {
                 throw PSTraceSource.NewArgumentException("Parameter", "HelpErrors", "ParamNotSupported", new object[] { "-Parameter" });
             }
             if (this._component != null)
             {
                 throw PSTraceSource.NewArgumentException("Component", "HelpErrors", "ParamNotSupported", new object[] { "-Component" });
             }
             if (this._role != null)
             {
                 throw PSTraceSource.NewArgumentException("Role", "HelpErrors", "ParamNotSupported", new object[] { "-Role" });
             }
             if (this._functionality != null)
             {
                 throw PSTraceSource.NewArgumentException("Functionality", "HelpErrors", "ParamNotSupported", new object[] { "-Functionality" });
             }
         }
     }
 }
Esempio n. 7
0
        private HelpCategory ToHelpCategory(string[] category, ref bool failed)
        {
            if ((category == null) || (category.Length == 0))
            {
                return(HelpCategory.None);
            }
            HelpCategory none = HelpCategory.None;

            failed = false;
            for (int i = 0; i < category.Length; i++)
            {
                try
                {
                    HelpCategory category3 = (HelpCategory)Enum.Parse(typeof(HelpCategory), category[i], true);
                    none |= category3;
                }
                catch (ArgumentException exception)
                {
                    Exception   exception2  = new HelpCategoryInvalidException(category[i], exception);
                    ErrorRecord errorRecord = new ErrorRecord(exception2, "InvalidHelpCategory", ErrorCategory.InvalidArgument, null);
                    base.WriteError(errorRecord);
                    failed = true;
                }
            }
            return(none);
        }
Esempio n. 8
0
 private HelpCategory ToHelpCategory(string[] category, ref bool failed)
 {
     using (GetHelpCommand.tracer.TraceMethod())
     {
         if (category == null || category.Length == 0)
         {
             return(HelpCategory.None);
         }
         HelpCategory helpCategory1 = HelpCategory.None;
         failed = false;
         for (int index = 0; index < category.Length; ++index)
         {
             try
             {
                 HelpCategory helpCategory2 = (HelpCategory)Enum.Parse(typeof(HelpCategory), category[index], true);
                 helpCategory1 |= helpCategory2;
             }
             catch (ArgumentException ex)
             {
                 this.WriteError(new ErrorRecord((Exception) new HelpCategoryInvalidException(category[index], (Exception)ex), "InvalidHelpCategory", ErrorCategory.InvalidArgument, (object)null));
                 failed = true;
             }
         }
         return(helpCategory1);
     }
 }
Esempio n. 9
0
 protected override void ProcessRecord()
 {
     using (GetHelpCommand.tracer.TraceMethod())
     {
         bool         failed       = false;
         HelpCategory helpCategory = this.ToHelpCategory(this._category, ref failed);
         if (failed)
         {
             return;
         }
         this.ValidateAndThrowIfError(helpCategory);
         HelpRequest helpRequest = new HelpRequest(this.Name, helpCategory);
         helpRequest.Provider        = this._provider;
         helpRequest.Component       = this._component;
         helpRequest.Role            = this._role;
         helpRequest.Functionality   = this._functionality;
         helpRequest.ProviderContext = new ProviderContext(this.Path, this.Context.Engine.Context, this.SessionState.Path);
         helpRequest.CommandOrigin   = this.MyInvocation.CommandOrigin;
         IEnumerable <HelpInfo> help = this.Context.HelpSystem.GetHelp(helpRequest);
         HelpInfo helpInfo1          = (HelpInfo)null;
         int      num = 0;
         foreach (HelpInfo helpInfo2 in help)
         {
             if (this.IsStopping)
             {
                 return;
             }
             if (num == 0)
             {
                 helpInfo1 = helpInfo2;
             }
             else
             {
                 if (helpInfo1 != null)
                 {
                     this.WriteObjectsOrShowOnlineHelp(helpInfo1, false);
                     helpInfo1 = (HelpInfo)null;
                 }
                 this.WriteObjectsOrShowOnlineHelp(helpInfo2, false);
             }
             ++num;
         }
         if (1 == num)
         {
             this.WriteObjectsOrShowOnlineHelp(helpInfo1, true);
         }
         else if (this.showOnlineHelp && num > 1)
         {
             throw GetHelpCommand.tracer.NewInvalidOperationException("HelpErrors", "MultipleOnlineTopicsNotSupported", (object)"Online");
         }
         if ((num != 0 || WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) && !this.Context.HelpSystem.VerboseHelpErrors || this.Context.HelpSystem.LastErrors.Count <= 0)
         {
             return;
         }
         foreach (ErrorRecord lastError in this.Context.HelpSystem.LastErrors)
         {
             this.WriteError(lastError);
         }
     }
 }
Esempio n. 10
0
 /// <summary>
 /// Constructor for SyntaxHelpInfo.
 /// </summary>
 private SyntaxHelpInfo(string name, string text, HelpCategory category)
     : base(category)
 {
     FullHelp = PSObject.AsPSObject(text);
     Name     = name;
     Synopsis = text;
 }
Esempio n. 11
0
            internal static void WriteValidationHelp()
            {
                HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpValidationCategory));

                helpCategory.Description = SR.Format(SR.HelpValidationDescription, Options.Cmd.ServiceName);
                helpCategory.Syntax      = SR.Format(SR.HelpValidationSyntax, ThisAssembly.Title, Options.Cmd.Validate,
                                                     Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName), SR.Format(SR.HelpInputAssemblyPath));

                helpCategory.Inputs = new ArgumentInfo[1];

                helpCategory.Inputs[0]          = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath));
                helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpValidationSyntaxInput1);

                helpCategory.Options = new ArgumentInfo[5];

                helpCategory.Options[0]          = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Validate);
                helpCategory.Options[0].HelpText = SR.Format(SR.HelpValidate, Options.Cmd.ServiceName, Options.Abbr.Validate);

                helpCategory.Options[1]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ServiceName, SR.Format(SR.ParametersServiceName));
                helpCategory.Options[1].HelpText = SR.Format(SR.HelpServiceNameValidate, Options.Abbr.Reference);

                helpCategory.Options[2]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference));
                helpCategory.Options[2].HelpText = SR.Format(SR.HelpReferenceOther, Options.Abbr.Reference);

                helpCategory.Options[3]          = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.DataContractOnly);
                helpCategory.Options[3].HelpText = SR.Format(SR.HelpDataContractOnly, Options.Abbr.DataContractOnly);

                helpCategory.Options[4]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType));
                helpCategory.Options[4].HelpText = SR.Format(SR.HelpValidationExcludeTypeExport, Options.Abbr.ExcludeType, Options.Abbr.DataContractOnly);

                helpCategory.WriteHelp();
            }
Esempio n. 12
0
        private HelpCategory ToHelpCategory(string[] category, ref bool failed)
        {
            if (category == null || category.Length == 0)
            {
                return(HelpCategory.None);
            }

            HelpCategory helpCategory = HelpCategory.None;

            failed = false;

            for (int i = 0; i < category.Length; i++)
            {
                try
                {
                    HelpCategory temp = (HelpCategory)Enum.Parse(typeof(HelpCategory), category[i], true);

                    helpCategory |= temp;
                }
                catch (ArgumentException argumentException)
                {
                    Exception   e           = new HelpCategoryInvalidException(category[i], argumentException);
                    ErrorRecord errorRecord = new ErrorRecord(e, "InvalidHelpCategory", ErrorCategory.InvalidArgument, null);
                    this.WriteError(errorRecord);

                    failed = true;
                }
            }

            return(helpCategory);
        }
Esempio n. 13
0
        private IEnumerable <HelpInfo> ForwardHelp(HelpInfo helpInfo, HelpRequest helpRequest)
        {
            new Collection <HelpInfo>();
            if ((helpInfo.ForwardHelpCategory == HelpCategory.None) && string.IsNullOrEmpty(helpInfo.ForwardTarget))
            {
                yield return(helpInfo);
            }
            else
            {
                HelpCategory forwardHelpCategory = helpInfo.ForwardHelpCategory;
                bool         iteratorVariable1   = false;
                for (int i = 0; i < this.HelpProviders.Count; i++)
                {
                    HelpProvider iteratorVariable3 = (HelpProvider)this.HelpProviders[i];
                    if ((iteratorVariable3.HelpCategory & forwardHelpCategory) != HelpCategory.None)
                    {
                        iteratorVariable1 = true;
                        foreach (HelpInfo iteratorVariable4 in iteratorVariable3.ProcessForwardedHelp(helpInfo, helpRequest))
                        {
                            foreach (HelpInfo iteratorVariable5 in this.ForwardHelp(iteratorVariable4, helpRequest))
                            {
                                yield return(iteratorVariable5);
                            }
                            goto Label_01FB;
                        }
                    }
                }
                if (!iteratorVariable1)
                {
                    yield return(helpInfo);
                }
            }
Label_01FB:
            yield break;
        }
Esempio n. 14
0
        /// <summary>
        /// 分类查询
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string QueryCategory(HttpContext context)
        {
            List <HelpCategory> list;//分页去掉 = bll.GetLit<BLLMJCMS.Model.HelpCategory>(rows, page, searchCondition, "CategoryID");

            list = bll.GetList <HelpCategory>().OrderBy(p => p.Sort).ToList();

            List <HelpCategory> showList = new List <HelpCategory>();

            MySpider.MyCategories m = new MySpider.MyCategories();

            foreach (ListItem item in m.GetCateListItem(m.GetCommCateModelList <HelpCategory>("CategoryID", "PreID", "NodeName", list), 0))
            {
                try
                {
                    HelpCategory tmpModel = list.Where(p => p.CategoryID.ToString().Equals(item.Value)).ToList()[0];
                    tmpModel.NodeName = item.Text;
                    showList.Add(tmpModel);
                }
                catch { }
            }

            int totalCount = showList.Count;

            string jsonResult = ZentCloud.Common.JSONHelper.ObjectToJson(totalCount, showList);

            return(jsonResult);
        }
Esempio n. 15
0
            internal static void WriteXmlSerializerTypeGenerationHelp()
            {
                HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpXmlSerializerTypeGenerationCategory));

                helpCategory.Description = SR.Format(SR.HelpXmlSerializerTypeGenerationDescription, ThisAssembly.Title);
                helpCategory.Syntax      = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntax, ThisAssembly.Title, SR.Format(SR.HelpInputAssemblyPath));

                helpCategory.Inputs = new ArgumentInfo[1];

                helpCategory.Inputs[0]          = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath));
                helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput1);

                helpCategory.Options = new ArgumentInfo[3];

                helpCategory.Options[0]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference));
                helpCategory.Options[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput2, Options.Abbr.Reference);

                helpCategory.Options[1]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType));
                helpCategory.Options[1].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput3, Options.Abbr.ExcludeType);

                helpCategory.Options[2]          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Out, SR.Format(SR.ParametersOut));
                helpCategory.Options[2].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput4, Options.Abbr.Out);

                helpCategory.WriteHelp();
            }
Esempio n. 16
0
        internal RemoteHelpInfo(
            ExecutionContext context,
            RemoteRunspace remoteRunspace,
            string localCommandName,
            string remoteHelpTopic,
            string remoteHelpCategory,
            HelpCategory localHelpCategory) : base(localHelpCategory)
        {
            Dbg.Assert(remoteRunspace != null, "Caller should verify arguments");

            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddCommand("Get-Help");
                powerShell.AddParameter("Name", remoteHelpTopic);
                if (!string.IsNullOrEmpty(remoteHelpCategory))
                {
                    powerShell.AddParameter("Category", remoteHelpCategory);
                }

                powerShell.Runspace = remoteRunspace;

                Collection <PSObject> helpResults;
                using (new PowerShellStopper(context, powerShell))
                {
                    helpResults = powerShell.Invoke();
                }

                if ((helpResults == null) || (helpResults.Count == 0))
                {
                    throw new Microsoft.PowerShell.Commands.HelpNotFoundException(remoteHelpTopic);
                }

                Dbg.Assert(helpResults.Count == 1, "Remote help should return exactly one result");
                _deserializedRemoteHelp = helpResults[0];
                _deserializedRemoteHelp.Methods.Remove("ToString");
                // Win8: bug9457: Remote proxy command's name can be changed locally using -Prefix
                // parameter of the Import-PSSession cmdlet. To give better user experience for
                // get-help (on par with get-command), it was decided to use the local command name
                // for the help content.
                PSPropertyInfo nameInfo = _deserializedRemoteHelp.Properties["Name"];
                if (nameInfo != null)
                {
                    nameInfo.Value = localCommandName;
                }

                PSObject commandDetails = this.Details;
                if (commandDetails != null)
                {
                    nameInfo = commandDetails.Properties["Name"];
                    if (nameInfo != null)
                    {
                        nameInfo.Value = localCommandName;
                    }
                    else
                    {
                        commandDetails.InstanceMembers.Add(new PSNoteProperty("Name", localCommandName));
                    }
                }
            }
        }
Esempio n. 17
0
 internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     if (base.arguments != null)
     {
         foreach (CommandParameterInternal internal2 in base.arguments)
         {
             if (internal2.IsDashQuestion())
             {
                 helpCategory = HelpCategory.All;
                 if (((base.Command != null) && (base.Command.MyInvocation != null)) && !string.IsNullOrEmpty(base.Command.MyInvocation.InvocationName))
                 {
                     helpTarget = base.Command.MyInvocation.InvocationName;
                     if (string.Equals(base.Command.MyInvocation.InvocationName, base.CommandInfo.Name, StringComparison.OrdinalIgnoreCase))
                     {
                         helpCategory = base.CommandInfo.HelpCategory;
                     }
                 }
                 else
                 {
                     helpTarget   = base.CommandInfo.Name;
                     helpCategory = base.CommandInfo.HelpCategory;
                 }
                 return(true);
             }
         }
     }
     return(base.IsHelpRequested(out helpTarget, out helpCategory));
 }
Esempio n. 18
0
 internal RemoteHelpInfo(
     ExecutionContext context,
     RemoteRunspace remoteRunspace,
     string remoteHelpTopic,
     string remoteHelpCategory,
     HelpCategory localHelpCategory)
     : base(localHelpCategory)
 {
     using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create())
     {
         powerShell.AddCommand("Get-Help");
         powerShell.AddParameter("Name", (object)remoteHelpTopic);
         if (!string.IsNullOrEmpty(remoteHelpCategory))
         {
             powerShell.AddParameter("Category", (object)remoteHelpCategory);
         }
         powerShell.Runspace = (Runspace)remoteRunspace;
         Collection <PSObject> collection;
         using (new PowerShellStopper(context, powerShell))
         {
             using (RemoteHelpInfo.tracer.TraceScope("Downloading remote help for {0}", (object)remoteHelpTopic))
                 collection = powerShell.Invoke();
         }
         this.deserializedRemoteHelp = collection != null && collection.Count != 0 ? collection[0] : throw new HelpNotFoundException(remoteHelpTopic);
         this.deserializedRemoteHelp.TypeNames.Clear();
         this.deserializedRemoteHelp.TypeNames.Add("MamlCommandHelpInfo");
         this.deserializedRemoteHelp.TypeNames.Add("HelpInfo");
         this.deserializedRemoteHelp.Methods.Remove("ToString");
     }
 }
Esempio n. 19
0
        internal MamlCommandHelpInfo Copy(HelpCategory newCategoryToUse)
        {
            MamlCommandHelpInfo info = new MamlCommandHelpInfo(this._fullHelpObject.Copy(), newCategoryToUse);

            info.FullHelp.Properties["Category"].Value = newCategoryToUse;
            return(info);
        }
Esempio n. 20
0
            internal static void WriteCommonOptionsHelp()
            {
                HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpCommonOptionsCategory));
                var          options      = new List <ArgumentInfo>();
                ArgumentInfo option;

                option          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Target, SR.Format(SR.ParametersOutputType));
                option.HelpText = SR.Format(SR.HelpTargetOutputType, Options.Targets.Code, Options.Targets.Metadata, Options.Targets.XmlSerializer);
                options.Add(option);

                option          = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Directory, SR.Format(SR.ParametersDirectory));
                option.HelpText = SR.Format(SR.HelpDirectory, Options.Abbr.Directory);
                options.Add(option);

                option          = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.NoLogo);
                option.HelpText = SR.Format(SR.HelpNologo);
                options.Add(option);

                option          = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Help);
                option.HelpText = SR.Format(SR.HelpHelp, Options.Abbr.Help);
                options.Add(option);

                helpCategory.Options = options.ToArray();
                helpCategory.WriteHelp();
            }
Esempio n. 21
0
 private SyntaxHelpInfo(string name, string text, HelpCategory category)
     : base(category)
 {
     this._fullHelpObject = PSObject.AsPSObject((object)text);
     this._name           = name;
     this._synopsis       = text;
 }
Esempio n. 22
0
        /// <summary>
        /// Constructor for MamlCommandHelpInfo. This constructor will call the corresponding
        /// constructor in CommandHelpInfo so that xmlNode will be converted a mamlNode.
        /// </summary>
        /// <remarks>
        /// This constructor is intentionally made private so that the only way to create
        /// MamlCommandHelpInfo is through static function
        ///     Load(XmlNode node)
        /// where some sanity check is done.
        /// </remarks>
        private MamlCommandHelpInfo(XmlNode xmlNode, HelpCategory helpCategory) : base(helpCategory)
        {
            MamlNode mamlNode = new MamlNode(xmlNode);

            _fullHelpObject = mamlNode.PSObject;

            this.Errors = mamlNode.Errors;

            // The type name hierarchy for mshObject doesn't necessary
            // reflect the hierarchy in source code. From display's point of
            // view MamlCommandHelpInfo is derived from HelpInfo.

            _fullHelpObject.TypeNames.Clear();
            if (helpCategory == HelpCategory.DscResource)
            {
                _fullHelpObject.TypeNames.Add("DscResourceHelpInfo");
            }
            else
            {
                _fullHelpObject.TypeNames.Add("MamlCommandHelpInfo");
                _fullHelpObject.TypeNames.Add("HelpInfo");
            }

            this.ForwardHelpCategory = HelpCategory.Provider;
        }
Esempio n. 23
0
        /// <summary>
        /// Get help based on the target, help type, etc
        ///
        /// Help engine retrieve help based on following schemes,
        ///
        ///     1. if help target is empty, get default help
        ///     2. if help target is not a search pattern, try to retrieve exact help
        ///     3. if help target is a search pattern or step 2 returns no helpInfo, try to search for help
        ///        (Search for pattern in command name followed by pattern match in help content)
        ///     4. if step 3 returns exact one helpInfo object, try to retrieve exact help.
        /// </summary>
        /// <param name="helpRequest">Help request object</param>
        /// <returns>An array of HelpInfo object</returns>
        private IEnumerable <HelpInfo> DoGetHelp(HelpRequest helpRequest)
        {
            _lastErrors.Clear();
            // Reset SearchPaths
            _searchPaths = null;

            _lastHelpCategory = helpRequest.HelpCategory;

            if (String.IsNullOrEmpty(helpRequest.Target))
            {
                HelpInfo helpInfo = GetDefaultHelp();

                if (helpInfo != null)
                {
                    yield return(helpInfo);
                }

                yield return(null);
            }
            else
            {
                bool isMatchFound = false;
                if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
                {
                    foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
                    {
                        isMatchFound = true;
                        yield return(helpInfo);
                    }
                }

                if (!isMatchFound)
                {
                    foreach (HelpInfo helpInfo in SearchHelp(helpRequest))
                    {
                        isMatchFound = true;
                        yield return(helpInfo);
                    }

                    if (!isMatchFound)
                    {
                        // Throwing exception here may not be the
                        // best thing to do. Instead we can choose to
                        //    a. give a hint
                        //    b. just silently return an empty search result.
                        // Solution:
                        //    If it is an exact help target, throw exception.
                        //    Otherwise, return empty result set.
                        if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target) && this.LastErrors.Count == 0)
                        {
                            Exception   e           = new HelpNotFoundException(helpRequest.Target);
                            ErrorRecord errorRecord = new ErrorRecord(e, "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
                            this.LastErrors.Add(errorRecord);
                            yield break;
                        }
                    }
                }
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
 /// and if yes, then returns the help target to display.
 /// </summary>
 /// <param name="helpTarget">help target to request</param>
 /// <param name="helpCategory">help category to request</param>
 /// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
 internal virtual bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     // by default we don't handle "-?" parameter at all
     // (we want to do the checks only for cmdlets - this method is overridden in CommandProcessor)
     helpTarget   = null;
     helpCategory = HelpCategory.None;
     return(false);
 }
Esempio n. 25
0
            internal static void WriteExamples()
            {
                HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpExamples));

                helpCategory.WriteHelp();

                WriteExample(SR.HelpExamples1, SR.HelpExamples2);
            }
Esempio n. 26
0
 private SyntaxHelpInfo(string name, string text, HelpCategory category) : base(category)
 {
     this._name = "";
     this._synopsis = "";
     this._fullHelpObject = PSObject.AsPSObject(text);
     this._name = name;
     this._synopsis = text;
 }
Esempio n. 27
0
        internal RemoteHelpInfo(
            ExecutionContext context,
            RemoteRunspace remoteRunspace,
            string localCommandName,
            string remoteHelpTopic,
            string remoteHelpCategory,
            HelpCategory localHelpCategory) : base(localHelpCategory)
        {
            Dbg.Assert(remoteRunspace != null, "Caller should verify arguments");

            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddCommand("Get-Help");
                powerShell.AddParameter("Name", remoteHelpTopic);
                if (!string.IsNullOrEmpty(remoteHelpCategory))
                {
                    powerShell.AddParameter("Category", remoteHelpCategory);
                }
                powerShell.Runspace = remoteRunspace;

                Collection<PSObject> helpResults;
                using (new PowerShellStopper(context, powerShell))
                {
                    helpResults = powerShell.Invoke();
                }

                if ((helpResults == null) || (helpResults.Count == 0))
                {
                    throw new Microsoft.PowerShell.Commands.HelpNotFoundException(remoteHelpTopic);
                }

                Dbg.Assert(helpResults.Count == 1, "Remote help should return exactly one result");
                _deserializedRemoteHelp = helpResults[0];
                _deserializedRemoteHelp.Methods.Remove("ToString");
                // Win8: bug9457: Remote proxy command's name can be changed locally using -Prefix
                // parameter of the Import-PSSession cmdlet. To give better user experience for
                // get-help (on par with get-command), it was decided to use the local command name
                // for the help content.
                PSPropertyInfo nameInfo = _deserializedRemoteHelp.Properties["Name"];
                if (nameInfo != null)
                {
                    nameInfo.Value = localCommandName;
                }
                PSObject commandDetails = this.Details;
                if (commandDetails != null)
                {
                    nameInfo = commandDetails.Properties["Name"];
                    if (nameInfo != null)
                    {
                        nameInfo.Value = localCommandName;
                    }
                    else
                    {
                        commandDetails.InstanceMembers.Add(new PSNoteProperty("Name", localCommandName));
                    }
                }
            }
        }
Esempio n. 28
0
        private static void WriteExamples()
        {
            HelpCategory helpCategory = new HelpCategory(SR.HelpExamples);

            helpCategory.WriteHelp();

            WriteExample(SR.HelpExamples2, SR.HelpExamples3);
            WriteExample(SR.HelpExamples8, SR.HelpExamples9);
        }
        /// <summary>
        /// Adds the help text to the paragraph
        /// </summary>
        internal void AddTextToParagraphBuilder()
        {
            this.ResetAllText();

            string strCategory = (HelpParagraphBuilder.GetProperty(this.psObj, "Category")).Value.ToString();

            HelpCategory category = HelpCategory.Default;

            if (String.Compare(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase) == 0)
            {
                category = HelpCategory.DscResource;
            }
            else if (String.Compare(strCategory, "Class", StringComparison.OrdinalIgnoreCase) == 0)
            {
                category = HelpCategory.Class;
            }

            if (HelpParagraphBuilder.GetProperty(this.psObj, "Syntax") == null)
            {
                if (category == HelpCategory.Default)
                {
                    // if there is no syntax, this is not the standard help
                    // it might be an about page
                    this.AddText(this.psObj.ToString(), false);
                    return;
                }
            }

            switch (category)
            {
            case HelpCategory.Class:
                this.AddDescription(HelpWindowSettings.Default.HelpSynopsysDisplayed, HelpWindowResources.SynopsisTitle, "Introduction");
                this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle);
                this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.MethodsTitle);
                break;

            case HelpCategory.DscResource:
                this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle);
                this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description");
                this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle, "Properties", HelpCategory.DscResource);
                break;

            default:
                this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle);
                this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description");
                this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.ParametersTitle, "Parameters", HelpCategory.Default);
                this.AddSyntax(HelpWindowSettings.Default.HelpSyntaxDisplayed, HelpWindowResources.SyntaxTitle);
                break;
            }

            this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpInputsDisplayed, HelpWindowResources.InputsTitle, "inputTypes", "inputType");
            this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpOutputsDisplayed, HelpWindowResources.OutputsTitle, "returnValues", "returnValue");
            this.AddNotes(HelpWindowSettings.Default.HelpNotesDisplayed, HelpWindowResources.NotesTitle);
            this.AddExamples(HelpWindowSettings.Default.HelpExamplesDisplayed, HelpWindowResources.ExamplesTitle);
            this.AddNavigationLink(HelpWindowSettings.Default.HelpRelatedLinksDisplayed, HelpWindowResources.RelatedLinksTitle);
            this.AddStringSection(HelpWindowSettings.Default.HelpRemarksDisplayed, "Remarks", HelpWindowResources.RemarksTitle);
        }
Esempio n. 30
0
 private MamlCommandHelpInfo(System.Xml.XmlNode xmlNode, HelpCategory helpCategory) : base(helpCategory)
 {
     MamlNode node = new MamlNode(xmlNode);
     this._fullHelpObject = node.PSObject;
     base.Errors = node.Errors;
     this._fullHelpObject.TypeNames.Clear();
     this._fullHelpObject.TypeNames.Add("MamlCommandHelpInfo");
     this._fullHelpObject.TypeNames.Add("HelpInfo");
     base.ForwardHelpCategory = HelpCategory.Provider;
 }
        public void Handle(GameClient Session, ClientMessage Event)
        {
            uint         uint_  = Event.PopWiredUInt();
            HelpCategory @class = GoldTree.GetGame().GetHelpTool().method_1(uint_);

            if (@class != null)
            {
                Session.SendMessage(GoldTree.GetGame().GetHelpTool().method_11(@class));
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Convert a XMLNode to HelpInfo object.
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="helpCategory"></param>
        private MamlClassHelpInfo(XmlNode xmlNode, HelpCategory helpCategory)
        {
            HelpCategory = helpCategory;

            MamlNode mamlNode = new MamlNode(xmlNode);
            _fullHelpObject = mamlNode.PSObject;

            this.Errors = mamlNode.Errors;
            _fullHelpObject.TypeNames.Clear();
            _fullHelpObject.TypeNames.Add("PSClassHelpInfo");
        }
Esempio n. 33
0
        private MamlCommandHelpInfo(System.Xml.XmlNode xmlNode, HelpCategory helpCategory) : base(helpCategory)
        {
            MamlNode node = new MamlNode(xmlNode);

            this._fullHelpObject = node.PSObject;
            base.Errors          = node.Errors;
            this._fullHelpObject.TypeNames.Clear();
            this._fullHelpObject.TypeNames.Add("MamlCommandHelpInfo");
            this._fullHelpObject.TypeNames.Add("HelpInfo");
            base.ForwardHelpCategory = HelpCategory.Provider;
        }
Esempio n. 34
0
        public void parse(GameClient Session, ClientMessage Event)
        {
            uint CategoryId = Event.PopWiredUInt();

            HelpCategory Category = PhoenixEnvironment.GetGame().GetHelpTool().GetCategory(CategoryId);

            if (Category != null)
            {
                Session.SendMessage(PhoenixEnvironment.GetGame().GetHelpTool().SerializeCategory(Category));
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Create a MamlClassHelpInfo object from an XmlNode.
        /// </summary>
        /// <param name="xmlNode">xmlNode that contains help info</param>
        /// <param name="helpCategory">help category this maml object fits into</param>
        /// <returns>MamlCommandHelpInfo object created</returns>
        internal static MamlClassHelpInfo Load(XmlNode xmlNode, HelpCategory helpCategory)
        {
            MamlClassHelpInfo mamlClassHelpInfo = new MamlClassHelpInfo(xmlNode, helpCategory);

            if (String.IsNullOrEmpty(mamlClassHelpInfo.Name))
                return null;

            mamlClassHelpInfo.AddCommonHelpProperties();

            return mamlClassHelpInfo;
        }
        public IActionResult Remove(int[] catIds)
        {
            foreach (int catId in catIds)
            {
                HelpCategory theCategory = context.Categories.Single(c => c.ID == catId);

                context.Categories.Remove(theCategory);
            }
            context.SaveChanges();
            return(RedirectToAction("Category", "Admin"));
        }
Esempio n. 37
0
 internal static SyntaxHelpInfo GetHelpInfo(string name, string text, HelpCategory category)
 {
     if (string.IsNullOrEmpty(name))
     {
         return null;
     }
     SyntaxHelpInfo info = new SyntaxHelpInfo(name, text, category);
     if (string.IsNullOrEmpty(info.Name))
     {
         return null;
     }
     info.AddCommonHelpProperties();
     return info;
 }
Esempio n. 38
0
 internal MamlCommandHelpInfo(PSObject helpObject, HelpCategory helpCategory) : base(helpCategory)
 {
     this._fullHelpObject = helpObject;
     base.ForwardHelpCategory = HelpCategory.Provider;
     base.AddCommonHelpProperties();
     if (helpObject.Properties["Component"] != null)
     {
         this._component = helpObject.Properties["Component"].Value as string;
     }
     if (helpObject.Properties["Role"] != null)
     {
         this._role = helpObject.Properties["Role"].Value as string;
     }
     if (helpObject.Properties["Functionality"] != null)
     {
         this._functionality = helpObject.Properties["Functionality"].Value as string;
     }
 }
Esempio n. 39
0
 internal RemoteHelpInfo(ExecutionContext context, RemoteRunspace remoteRunspace, string localCommandName, string remoteHelpTopic, string remoteHelpCategory, HelpCategory localHelpCategory) : base(localHelpCategory)
 {
     using (PowerShell shell = PowerShell.Create())
     {
         Collection<PSObject> collection;
         shell.AddCommand("Get-Help");
         shell.AddParameter("Name", remoteHelpTopic);
         if (!string.IsNullOrEmpty(remoteHelpCategory))
         {
             shell.AddParameter("Category", remoteHelpCategory);
         }
         shell.Runspace = remoteRunspace;
         using (new PowerShellStopper(context, shell))
         {
             collection = shell.Invoke();
         }
         if ((collection == null) || (collection.Count == 0))
         {
             throw new HelpNotFoundException(remoteHelpTopic);
         }
         this.deserializedRemoteHelp = collection[0];
         this.deserializedRemoteHelp.Methods.Remove("ToString");
         PSPropertyInfo info = this.deserializedRemoteHelp.Properties["Name"];
         if (info != null)
         {
             info.Value = localCommandName;
         }
         PSObject details = base.Details;
         if (details != null)
         {
             info = details.Properties["Name"];
             if (info != null)
             {
                 info.Value = localCommandName;
             }
             else
             {
                 details.InstanceMembers.Add(new PSNoteProperty("Name", localCommandName));
             }
         }
     }
 }
Esempio n. 40
0
 private IEnumerable<HelpInfo> DoGetHelp(HelpRequest helpRequest)
 {
     this._lastErrors.Clear();
     this._searchPaths = null;
     this._lastHelpCategory = helpRequest.HelpCategory;
     if (string.IsNullOrEmpty(helpRequest.Target))
     {
         HelpInfo defaultHelp = this.GetDefaultHelp();
         if (defaultHelp != null)
         {
             yield return defaultHelp;
         }
         yield return null;
     }
     else
     {
         bool iteratorVariable1 = false;
         if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
         {
             foreach (HelpInfo iteratorVariable2 in this.ExactMatchHelp(helpRequest))
             {
                 iteratorVariable1 = true;
                 yield return iteratorVariable2;
             }
         }
         if (!iteratorVariable1)
         {
             foreach (HelpInfo iteratorVariable3 in this.SearchHelp(helpRequest))
             {
                 iteratorVariable1 = true;
                 yield return iteratorVariable3;
             }
             if ((!iteratorVariable1 && !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) && (this.LastErrors.Count == 0))
             {
                 Exception exception = new HelpNotFoundException(helpRequest.Target);
                 ErrorRecord item = new ErrorRecord(exception, "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
                 this.LastErrors.Add(item);
             }
         }
     }
 }
Esempio n. 41
0
 internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     if (((base.arguments != null) && (base.CommandInfo != null)) && (!string.IsNullOrEmpty(base.CommandInfo.Name) && (this._scriptBlock != null)))
     {
         foreach (CommandParameterInternal internal2 in base.arguments)
         {
             if (internal2.IsDashQuestion())
             {
                 string str;
                 Dictionary<Ast, Token[]> scriptBlockTokenCache = new Dictionary<Ast, Token[]>();
                 HelpInfo info = this._scriptBlock.GetHelpInfo(base.Context, base.CommandInfo, false, scriptBlockTokenCache, out str, out str);
                 if (info == null)
                 {
                     break;
                 }
                 helpTarget = info.Name;
                 helpCategory = info.HelpCategory;
                 return true;
             }
         }
     }
     return base.IsHelpRequested(out helpTarget, out helpCategory);
 }
Esempio n. 42
0
        /// <summary>
        /// Constructor for MamlCommandHelpInfo. This constructor will call the corresponding
        /// constructor in CommandHelpInfo so that xmlNode will be converted a mamlNode. 
        /// </summary>
        /// <remarks>
        /// This constructor is intentionally made private so that the only way to create
        /// MamlCommandHelpInfo is through static function
        ///     Load(XmlNode node)
        /// where some sanity check is done.
        /// </remarks>
        private MamlCommandHelpInfo(XmlNode xmlNode, HelpCategory helpCategory) : base(helpCategory)
        {
            MamlNode mamlNode = new MamlNode(xmlNode);
            _fullHelpObject = mamlNode.PSObject;

            this.Errors = mamlNode.Errors;

            // The type name hierarchy for mshObject doesn't necessary
            // reflect the hierarchy in source code. From display's point of 
            // view MamlCommandHelpInfo is derived from HelpInfo.

            _fullHelpObject.TypeNames.Clear();
            if (helpCategory == HelpCategory.DscResource)
            {
                _fullHelpObject.TypeNames.Add("DscResourceHelpInfo");
            }
            else
            {
                _fullHelpObject.TypeNames.Add("MamlCommandHelpInfo");
                _fullHelpObject.TypeNames.Add("HelpInfo");
            }

            this.ForwardHelpCategory = HelpCategory.Provider;
        }
Esempio n. 43
0
 /// <summary>
 /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
 /// and if yes, then returns the help target to display.
 /// </summary>
 /// <param name="helpTarget">help target to request</param>
 /// <param name="helpCategory">help category to request</param>
 /// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
 internal virtual bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     // by default we don't handle "-?" parameter at all
     // (we want to do the checks only for cmdlets - this method is overridden in CommandProcessor)
     helpTarget = null;
     helpCategory = HelpCategory.None;
     return false;
 }
Esempio n. 44
0
 internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     if (base.arguments != null)
     {
         foreach (CommandParameterInternal internal2 in base.arguments)
         {
             if (internal2.IsDashQuestion())
             {
                 helpCategory = HelpCategory.All;
                 if (((base.Command != null) && (base.Command.MyInvocation != null)) && !string.IsNullOrEmpty(base.Command.MyInvocation.InvocationName))
                 {
                     helpTarget = base.Command.MyInvocation.InvocationName;
                     if (string.Equals(base.Command.MyInvocation.InvocationName, base.CommandInfo.Name, StringComparison.OrdinalIgnoreCase))
                     {
                         helpCategory = base.CommandInfo.HelpCategory;
                     }
                 }
                 else
                 {
                     helpTarget = base.CommandInfo.Name;
                     helpCategory = base.CommandInfo.HelpCategory;
                 }
                 return true;
             }
         }
     }
     return base.IsHelpRequested(out helpTarget, out helpCategory);
 }
Esempio n. 45
0
 /// <summary>
 /// Clone the help object with a new category.
 /// </summary>
 /// <param name="newCategoryToUse"></param>
 /// <returns>MamlClassHelpInfo</returns>
 internal MamlClassHelpInfo Copy(HelpCategory newCategoryToUse)
 {
     MamlClassHelpInfo result = new MamlClassHelpInfo(_fullHelpObject.Copy(), newCategoryToUse);
     result.FullHelp.Properties["Category"].Value = newCategoryToUse;
     return result;
 }
Esempio n. 46
0
 public ServerMessage method_11(HelpCategory class131_0)
 {
     ServerMessage Message = new ServerMessage(522u);
     Message.AppendUInt(class131_0.CategoryId);
     Message.AppendStringWithBreak("");
     Message.AppendInt32(this.method_6(class131_0.CategoryId));
     using (TimedLock.Lock(this.dictionary_1))
     {
         foreach (HelpTopic current in this.dictionary_1.Values)
         {
             if (current.uint_1 == class131_0.CategoryId)
             {
                 Message.AppendUInt(current.UInt32_0);
                 Message.AppendStringWithBreak(current.string_0);
             }
         }
     }
     return Message;
 }
Esempio n. 47
0
        /// <summary>
        /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
        /// and if yes, then returns the help target to display.
        /// </summary>
        /// <param name="helpTarget">help target to request</param>
        /// <param name="helpCategory">help category to request</param>
        /// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
        internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
        {
            if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null)
            {
                foreach (CommandParameterInternal parameter in this.arguments)
                {
                    Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
                    if (parameter.IsDashQuestion())
                    {
                        Dictionary<Ast, Token[]> scriptBlockTokenCache = new Dictionary<Ast, Token[]>();
                        string unused;
                        HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo,
                            dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused);
                        if (helpInfo == null)
                        {
                            break;
                        }

                        helpTarget = helpInfo.Name;
                        helpCategory = helpInfo.HelpCategory;
                        return true;
                    }
                }
            }

            return base.IsHelpRequested(out helpTarget, out helpCategory);
        }
Esempio n. 48
0
        /// <summary>
        /// Gets the HelpInfo object corresponding to the command.
        /// </summary>
        /// <param name="helpFileIdentifier">help file identifier (either name of PSSnapIn or simply full path to help file)</param>
        /// <param name="commandName">Name of the command.</param>
        /// <param name="helpCategory"> </param>
        /// <returns>HelpInfo object.</returns>
        private HelpInfo GetFromCommandCache(string helpFileIdentifier, string commandName, HelpCategory helpCategory)
        {
            Debug.Assert(!string.IsNullOrEmpty(commandName), "Cmdlet Name should not be null or empty.");

            string key = commandName;
            if (!string.IsNullOrEmpty(helpFileIdentifier))
            {
                key = helpFileIdentifier + "\\" + key;
            }

            HelpInfo result = GetCache(key);

            // Win8: Win8:477680: When Function/Workflow Use External Help, Category Property is "Cmdlet"
            if ((null != result) && (result.HelpCategory != helpCategory))
            {
                MamlCommandHelpInfo original = (MamlCommandHelpInfo)result;
                result = original.Copy(helpCategory);
            }

            return result;
        }
Esempio n. 49
0
        /// <summary>
        /// Adds the help parameters segment
        /// </summary>
        /// <param name="setting">true if it should add the segment</param>
        /// <param name="sectionTitle">title of the section</param>
        /// <param name="paramPropertyName">name of the property which has properties</param>
        /// <param name="helpCategory">category of help</param>
        private void AddParameters(bool setting, string sectionTitle, string paramPropertyName, HelpCategory helpCategory)
        {
            if (!setting)
            {
                return;
            }

            PSObject parameterRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, paramPropertyName) as PSObject;            
            if (parameterRootObject == null)
            {
                return;
            }

            object[] parameterObjects = null;

            //Root object for Class has members not parameters.
            if (helpCategory != HelpCategory.Class)
            {
                parameterObjects = HelpParagraphBuilder.GetPropertyObjectArray(parameterRootObject, "parameter");
            }

            if (parameterObjects == null || parameterObjects.Length == 0)
            {
                return;
            }

            this.AddText(sectionTitle, true);
            this.AddText("\r\n", false);

            foreach (object parameterObj in parameterObjects)
            {
                PSObject parameter = parameterObj as PSObject;
                if (parameter == null)
                {
                    continue;
                }

                string parameterValue = GetPropertyString(parameter, "parameterValue");
                string name = GetPropertyString(parameter, "name");
                string description = GetTextFromArray(parameter, "description");
                string required = GetPropertyString(parameter, "required");
                string position = GetPropertyString(parameter, "position");
                string pipelineinput = GetPropertyString(parameter, "pipelineInput");
                string defaultValue = GetPropertyString(parameter, "defaultValue");
                string acceptWildcard = GetPropertyString(parameter, "globbing");

                if (String.IsNullOrEmpty(name))
                {
                    continue;
                }

                // This syntax string is not localized

                if (helpCategory == HelpCategory.DscResource)
                    this.AddText(HelpParagraphBuilder.AddIndent(""), false);
                else
                    this.AddText(HelpParagraphBuilder.AddIndent("-"), false);

                this.AddText(name, true);
                string parameterText = String.Format(
                    CultureInfo.CurrentCulture,
                    " <{0}>\r\n",
                    parameterValue);

                this.AddText(parameterText, false);

                if (description != null)
                {
                    this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false);
                    this.AddText("\r\n", false);
                }

                this.AddText("\r\n", false);

                int largestSize = HelpParagraphBuilder.LargestSize(
                    HelpWindowResources.ParameterRequired,
                    HelpWindowResources.ParameterPosition,
                    HelpWindowResources.ParameterDefautValue,
                    HelpWindowResources.ParameterPipelineInput,
                    HelpWindowResources.ParameterAcceptWildcard);

                // justification of parameter values is not localized
                string formatString = String.Format(
                    CultureInfo.CurrentCulture,
                    "{{0,-{0}}}{{1}}",
                    largestSize + 2);

                string tableLine;

                tableLine = String.Format(
                    CultureInfo.CurrentCulture,
                    formatString,
                    HelpWindowResources.ParameterRequired,
                    required);
                this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
                this.AddText("\r\n", false);

                //these are not applicable for Dsc Resource help
                if (helpCategory != HelpCategory.DscResource)
                {
                    tableLine = String.Format(
                        CultureInfo.CurrentCulture,
                        formatString,
                        HelpWindowResources.ParameterPosition,
                        position);
                    this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
                    this.AddText("\r\n", false);

                    tableLine = String.Format(
                        CultureInfo.CurrentCulture,
                        formatString,
                        HelpWindowResources.ParameterDefautValue,
                        defaultValue);
                    this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
                    this.AddText("\r\n", false);

                    tableLine = String.Format(
                        CultureInfo.CurrentCulture,
                        formatString,
                        HelpWindowResources.ParameterPipelineInput,
                        pipelineinput);
                    this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
                    this.AddText("\r\n", false);

                    tableLine = String.Format(
                        CultureInfo.CurrentCulture,
                        formatString,
                        HelpWindowResources.ParameterAcceptWildcard,
                        acceptWildcard);
                    this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
                }

                this.AddText("\r\n\r\n", false);
            }

            this.AddText("\r\n\r\n", false);
        }
Esempio n. 50
0
        /// <summary>
        /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
        /// and if yes, then returns the help target to display.
        /// </summary>
        /// <param name="helpTarget">help target to request</param>
        /// <param name="helpCategory">help category to request</param>
        /// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
        internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
        {
            if (this.arguments != null)
            {
                foreach (CommandParameterInternal parameter in this.arguments)
                {
                    Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
                    if (parameter.IsDashQuestion())
                    {
                        helpCategory = HelpCategory.All;
                        // using InvocationName mainly to avoid bogus this.CommandInfo.Name 
                        // (when CmdletInfo.Name is initialized from "cmdlet" declaration 
                        //  of a scriptblock and when "cmdlet" declaration doesn't specify any name)
                        if ((this.Command != null) && (this.Command.MyInvocation != null) &&
                            (!string.IsNullOrEmpty(this.Command.MyInvocation.InvocationName)))
                        {
                            helpTarget = this.Command.MyInvocation.InvocationName;
                            // Win8: 391035 get-help does not work properly for aliased cmdlets
                            // For aliased cmdlets/functions,example Initialize-Volume -> Format-Volume,
                            // MyInvocation.InvocationName is different from CommandInfo.Name
                            // - CommandInfo.Name points to Format-Volume
                            // - MyInvocation.InvocationName points to Initialize-Volume
                            if (string.Equals(this.Command.MyInvocation.InvocationName, this.CommandInfo.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                helpCategory = this.CommandInfo.HelpCategory;
                            }
                        }
                        else
                        {
                            helpTarget = this.CommandInfo.Name;
                            helpCategory = this.CommandInfo.HelpCategory;
                        }

                        return true;
                    }
                }
            }

            return base.IsHelpRequested(out helpTarget, out helpCategory);
        }
Esempio n. 51
0
 internal BaseCommandHelpInfo(HelpCategory helpCategory)
     : base()
 {
     HelpCategory = helpCategory;
 }
Esempio n. 52
0
        /// <summary>
        /// Validates input parameters
        /// </summary>
        /// <param name="cat">Category specified by the user</param>
        /// <exception cref="ArgumentException">
        /// If the request cant be serviced.
        /// </exception>
        private void ValidateAndThrowIfError(HelpCategory cat)
        {
            if (cat == HelpCategory.None)
            {
                return;
            }

            // categories that support -Parameter, -Role, -Functionality, -Component parameters
            HelpCategory supportedCategories =
                HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript |
                HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow;

            if ((cat & supportedCategories) == 0)
            {
                if (!string.IsNullOrEmpty(Parameter))
                {
                    throw PSTraceSource.NewArgumentException("Parameter",
                        HelpErrors.ParamNotSupported, "-Parameter");
                }

                if (Component != null)
                {
                    throw PSTraceSource.NewArgumentException("Component",
                        HelpErrors.ParamNotSupported, "-Component");
                }

                if (Role != null)
                {
                    throw PSTraceSource.NewArgumentException("Role",
                        HelpErrors.ParamNotSupported, "-Role");
                }

                if (Functionality != null)
                {
                    throw PSTraceSource.NewArgumentException("Functionality",
                        HelpErrors.ParamNotSupported, "-Functionality");
                }
            }
        }
Esempio n. 53
0
        /// <summary>
        /// Gets the HelpInfo object corresponding to the command.
        /// </summary>
        /// <param name="helpFileIdentifier">help file identifier (either name of PSSnapIn or simply full path to help file)</param>
        /// <param name="helpCategory">Help Category for search.</param>
        /// <returns>HelpInfo object.</returns>
        private HelpInfo GetFromPSClasseHelpCache(string helpFileIdentifier, HelpCategory helpCategory)
        {
            Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty.");

            HelpInfo result = GetCache(helpFileIdentifier);

            if (result != null)
            {
                MamlClassHelpInfo original = (MamlClassHelpInfo)result;
                result = original.Copy(helpCategory);
            }

            return result;
        }
Esempio n. 54
0
 /// <summary>
 /// Constructor for HelpRequest
 /// </summary>
 /// <param name="target"></param>
 /// <param name="helpCategory"></param>
 internal HelpRequest(string target, HelpCategory helpCategory)
 {
     Target = target;
     HelpCategory = helpCategory;
     CommandOrigin = CommandOrigin.Runspace;
 }
Esempio n. 55
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="assemblyName">assembly that contains this help provider</param>
 /// <param name="className">the class that implements this help provider</param>
 /// <param name="helpCategory">help category of this help provider</param>
 internal HelpProviderInfo(string assemblyName, string className, HelpCategory helpCategory)
 {
     this.AssemblyName = assemblyName;
     this.ClassName = className;
     this.HelpCategory = helpCategory;
 }
Esempio n. 56
0
 private void ValidateAndThrowIfError(HelpCategory cat)
 {
     if (cat != HelpCategory.None)
     {
         HelpCategory category = HelpCategory.Workflow | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Cmdlet | HelpCategory.Alias;
         if ((cat & category) == HelpCategory.None)
         {
             if (!string.IsNullOrEmpty(this._parameter))
             {
                 throw PSTraceSource.NewArgumentException("Parameter", "HelpErrors", "ParamNotSupported", new object[] { "-Parameter" });
             }
             if (this._component != null)
             {
                 throw PSTraceSource.NewArgumentException("Component", "HelpErrors", "ParamNotSupported", new object[] { "-Component" });
             }
             if (this._role != null)
             {
                 throw PSTraceSource.NewArgumentException("Role", "HelpErrors", "ParamNotSupported", new object[] { "-Role" });
             }
             if (this._functionality != null)
             {
                 throw PSTraceSource.NewArgumentException("Functionality", "HelpErrors", "ParamNotSupported", new object[] { "-Functionality" });
             }
         }
     }
 }
Esempio n. 57
0
        /// <summary>
        /// Get help based on the target, help type, etc
        /// 
        /// Help engine retrieve help based on following schemes,
        /// 
        ///     1. if help target is empty, get default help
        ///     2. if help target is not a search pattern, try to retrieve exact help
        ///     3. if help target is a search pattern or step 2 returns no helpInfo, try to search for help
        ///        (Search for pattern in command name followed by pattern match in help content)
        ///     4. if step 3 returns exact one helpInfo object, try to retrieve exact help.
        /// 
        /// </summary>
        /// <param name="helpRequest">Help request object</param>
        /// <returns>An array of HelpInfo object</returns>
        private IEnumerable<HelpInfo> DoGetHelp(HelpRequest helpRequest)
        {
            _lastErrors.Clear();
            // Reset SearchPaths
            _searchPaths = null;

            _lastHelpCategory = helpRequest.HelpCategory;

            if (String.IsNullOrEmpty(helpRequest.Target))
            {
                HelpInfo helpInfo = GetDefaultHelp();

                if (helpInfo != null)
                {
                    yield return helpInfo;
                }

                yield return null;
            }
            else
            {
                bool isMatchFound = false;
                if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
                {
                    foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
                    {
                        isMatchFound = true;
                        yield return helpInfo;
                    }
                }

                if (!isMatchFound)
                {
                    foreach (HelpInfo helpInfo in SearchHelp(helpRequest))
                    {
                        isMatchFound = true;
                        yield return helpInfo;
                    }

                    if (!isMatchFound)
                    {
                        // Throwing exception here may not be the 
                        // best thing to do. Instead we can choose to
                        //    a. give a hint
                        //    b. just silently return an empty search result.
                        // Solution: 
                        //    If it is an exact help target, throw exception.
                        //    Otherwise, return empty result set.
                        if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target) && this.LastErrors.Count == 0)
                        {
                            Exception e = new HelpNotFoundException(helpRequest.Target);
                            ErrorRecord errorRecord = new ErrorRecord(e, "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
                            this.LastErrors.Add(errorRecord);
                            yield break;
                        }
                    }
                }
            }
        }
Esempio n. 58
0
 internal virtual bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
 {
     helpTarget = null;
     helpCategory = HelpCategory.None;
     return false;
 }
Esempio n. 59
0
        /// <summary>
        /// Creates a command processor for "get-help [helpTarget]"
        /// </summary>
        /// <param name="context">context for the command processor</param>
        /// <param name="helpTarget">help target</param>
        /// <param name="helpCategory">help category</param>
        /// <returns>command processor for "get-help [helpTarget]"</returns>
        internal static CommandProcessorBase CreateGetHelpCommandProcessor(
            ExecutionContext context,
            string helpTarget,
            HelpCategory helpCategory)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(helpTarget))
            {
                throw PSTraceSource.NewArgumentNullException("helpTarget");
            }

            CommandProcessorBase helpCommandProcessor = context.CreateCommand("get-help", false);
            var cpi = CommandParameterInternal.CreateParameterWithArgument(
                PositionUtilities.EmptyExtent, "Name", "-Name:",
                PositionUtilities.EmptyExtent, helpTarget,
                false);
            helpCommandProcessor.AddParameter(cpi);
            cpi = CommandParameterInternal.CreateParameterWithArgument(
                PositionUtilities.EmptyExtent, "Category", "-Category:",
                PositionUtilities.EmptyExtent, helpCategory.ToString(),
                false);
            helpCommandProcessor.AddParameter(cpi);
            return helpCommandProcessor;
        }
Esempio n. 60
0
 /// <summary>
 /// Constructor for custom HelpInfo object creation.
 /// </summary>
 /// <param name="helpObject"></param>
 /// <param name="helpCategory"></param>
 internal MamlClassHelpInfo(PSObject helpObject, HelpCategory helpCategory)
 {
     HelpCategory = helpCategory;
     _fullHelpObject = helpObject;
 }