예제 #1
0
        private static string GetCmdletName(CmdletAttribute cmdletAttribute)
        {
            string verbName = cmdletAttribute.VerbName;
            string nounName = cmdletAttribute.NounName;

            return(verbName + "-" + nounName);
        }
        /// <summary>
        /// Gets the names of the static parameters defined for this cmdlet.
        /// </summary>
        protected string[] GetStaticParameterNames()
        {
            if (MyInvocation.MyCommand != null)
            {
                // We're running inside the shell... parameter information will already
                // be resolved for us:
                return(MyInvocation.MyCommand.Parameters.Keys.ToArray());
            }

            // This invocation is internal (e.g: through a unit test), fallback to
            // collecting the command/parameter info explicitly from our current type:

            CmdletAttribute cmdletAttribute = (CmdletAttribute)this.GetType()
                                              .GetCustomAttributes(typeof(CmdletAttribute), true)
                                              .FirstOrDefault();

            if (cmdletAttribute == null)
            {
                throw new InvalidOperationException(
                          $"Expected type '{this.GetType().Name}' to have CmdletAttribute."
                          );
            }

            // The command name we provide for the temporary CmdletInfo isn't consumed
            // anywhere other than instantiation, but let's resolve it anyway:
            string commandName = $"{cmdletAttribute.VerbName}-{cmdletAttribute.NounName}";

            CmdletInfo cmdletInfo = new CmdletInfo(commandName, this.GetType());

            return(cmdletInfo.Parameters.Keys.ToArray());
        }
예제 #3
0
        private static void WriteDetails(XmlWriter psHelpWriter, CmdletAttribute cmdletAttribute, string typeDocumentation, string cmdletName, string synopsis)
        {
            psHelpWriter.WriteStartElement("details");
            {
                psHelpWriter.WriteElementString("name", cmdletName);
                psHelpWriter.WriteStartElement("description");
                {
                    if (string.IsNullOrEmpty(synopsis))
                    {
                        synopsis = string.Format("{0}-{1}", cmdletAttribute.VerbName, cmdletAttribute.NounName);
                    }
                    psHelpWriter.WriteUnescapedElementString("para", synopsis);
                }
                psHelpWriter.WriteEndElement();

                psHelpWriter.WriteElementString("verb", cmdletAttribute.VerbName);
                psHelpWriter.WriteElementString("noun", cmdletAttribute.NounName);
                psHelpWriter.WriteStartElement("copyright");
                {
                    psHelpWriter.WriteElementString("para",
                                                    string.Format("&copy; Copyright 2012 - {0} Amazon.com, Inc.or its affiliates.All Rights Reserved.",
                                                                  DateTime.UtcNow.Year));
                }
                psHelpWriter.WriteEndElement();
            }
            psHelpWriter.WriteEndElement();

            psHelpWriter.WriteStartElement("description");
            {
                psHelpWriter.WriteUnescapedElementString("para", typeDocumentation);
            }
            psHelpWriter.WriteEndElement();
        }
예제 #4
0
 public CmdletInfo(Type type, CmdletAttribute cmdlet)
     : this()
 {
     Type = type;
     Verb = cmdlet.VerbName;
     Noun = cmdlet.NounName;
 }
예제 #5
0
            public override void VisitCmdlet(CmdletAttribute cmdlet)
            {
                _cmdletInfo = new CmdletInfo(CurrentType, cmdlet);
                _command._cmdlets.Add(_cmdletInfo);

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

                WriteParameter(pi, pa);
            }
            if (allParameterSets != null)
            {
                foreach (PropertyInfo pi in allParameterSets)
                {
                    List <ParameterAttribute> pas = GetAttribute <ParameterAttribute>(pi);
                    if (pas == null)
                    {
                        continue;
                    }
                    WriteParameter(pi, pas[0]);
                }
            }
            _writer.WriteEndElement(); //command:syntaxItem
        }
예제 #7
0
        private static void WriteSyntax(CmdletAttribute ca, Type type)
        {
            Dictionary <string, List <PropertyInfo> > parameterSets = new Dictionary <string, List <PropertyInfo> >();

            List <PropertyInfo> defaultSet = null;

            foreach (PropertyInfo pi in type.GetProperties())
            {
                List <ParameterAttribute> pas = GetAttribute <ParameterAttribute>(pi);
                if (pas == null)
                {
                    continue;
                }

                foreach (ParameterAttribute temp in pas)
                {
                    string set = temp.ParameterSetName + "";
                    List <PropertyInfo> piList = null;
                    if (!parameterSets.ContainsKey(set))
                    {
                        piList = new List <PropertyInfo>();
                        parameterSets.Add(set, piList);
                    }
                    else
                    {
                        piList = parameterSets[set];
                    }
                    parameterSets[set].Add(pi);
                }
            }

            if (parameterSets.Count > 0)
            {
                try
                {
                    defaultSet = parameterSets[DEFAULT_PARAMETER_SET_NAME];

                    if (parameterSets.Count > 1 && parameterSets.ContainsKey(DEFAULT_PARAMETER_SET_NAME))
                    {
                        parameterSets.Remove(DEFAULT_PARAMETER_SET_NAME);
                    }
                    else
                    {
                        defaultSet = null;
                    }
                }
                catch
                {
                    defaultSet = null;
                }

                writer.WriteStartElement("command", "syntax", null);
                foreach (string parameterSetName in parameterSets.Keys)
                {
                    WriteSyntaxItem(ca, parameterSets, parameterSetName, defaultSet);
                }
                writer.WriteEndElement(); //command:syntax
            }
        }
예제 #8
0
        /// <summary>
        /// Verifies the ConfirmImpact level on a cmdlet.
        /// </summary>
        /// <param name="cmdlet">The cmdlet to check.</param>
        /// <param name="confirmImpact">The expected confirm impact.</param>
        public static void CheckConfirmImpact(Type cmdlet, ConfirmImpact confirmImpact)
        {
            object[] cmdletAttributes = cmdlet.GetCustomAttributes(typeof(CmdletAttribute), true);
            Assert.AreEqual(1, cmdletAttributes.Length);
            CmdletAttribute attribute = (CmdletAttribute)cmdletAttributes[0];

            Assert.AreEqual(confirmImpact, attribute.ConfirmImpact);
        }
예제 #9
0
        public RelatedLinkAttribute(Type cmdletType)
        {
            CmdletAttribute attr = Utils.GetAttribute <CmdletAttribute>(cmdletType);

            PscxArgumentException.ThrowIfIsNull(attr, "The type {0} is not a cmdlet.", cmdletType);

            _text = attr.VerbName + '-' + attr.NounName;
        }
예제 #10
0
        /// <summary>
        ///     Execute the task.
        /// </summary>
        /// <returns>
        ///     <c>true</c>, if the task executed succesfully; otherwise, <c>false</c>.
        /// </returns>
        public override bool Execute()
        {
            FileInfo moduleAssemblyFile = new FileInfo(
                ModuleAssembly.GetMetadata("FullPath")
                );

            Log.LogMessage(MessageImportance.Low, "Scanning assembly '{0}'...",
                           moduleAssemblyFile.FullName
                           );

            DirectoryAssemblyLoadContext assemblyLoadContext = new DirectoryAssemblyLoadContext(
                fallbackDirectory: moduleAssemblyFile.Directory.FullName
                );

            HelpItems     help      = new HelpItems();
            MamlGenerator generator = new MamlGenerator();

            Assembly moduleAssembly = assemblyLoadContext.LoadFromAssemblyPath(moduleAssemblyFile.FullName);

            foreach (Type cmdletType in Reflector.GetCmdletTypes(moduleAssembly))
            {
                CmdletAttribute cmdletAttribute = cmdletType.GetTypeInfo().GetCustomAttribute <CmdletAttribute>();

                Log.LogMessage(MessageImportance.Low, "Generating help for cmdlet '{0}-{1}' ('{2}').",
                               cmdletAttribute.VerbName,
                               cmdletAttribute.NounName,
                               cmdletType.FullName
                               );

                help.Commands.Add(
                    generator.Generate(cmdletType)
                    );
            }

            FileInfo helpFile = new FileInfo(
                HelpFile.GetMetadata("FullPath")
                );

            if (helpFile.Exists)
            {
                helpFile.Delete();
            }

            using (StreamWriter writer = helpFile.CreateText())
            {
                help.WriteTo(writer);
            }

            Log.LogMessage(MessageImportance.Normal, "'{0}' -> '{1}'",
                           moduleAssemblyFile.Name,
                           helpFile.Name
                           );

            return(true);
        }
예제 #11
0
        /// <summary>
        /// Gets the name of the command from the type.
        /// </summary>
        /// <param name="type">The type for the command being invoked.</param>
        /// <returns>The name of the command from the type.</returns>
        private static string GetNameFromCmdletType(Type type)
        {
            string          cmdletName   = null;
            CmdletAttribute cmdletAttrib = (CmdletAttribute)type.GetCustomAttributes(typeof(CmdletAttribute), false).FirstOrDefault();

            if (cmdletAttrib != null)
            {
                cmdletName = cmdletAttrib.VerbName + "-" + cmdletAttrib.NounName;
            }

            return(cmdletName);
        }
예제 #12
0
        private void LoadCmdlets(ICollection <CmdletConfigurationEntry> cmdletsCollection)
        {
            Type cmdletType = typeof(Cmdlet);

            foreach (Assembly assembly in this.orchardModuleAssemblies)
            {
                try
                {
                    foreach (Type type in assembly.GetTypes())
                    {
                        try
                        {
                            if (cmdletType.IsAssignableFrom(type))
                            {
                                CmdletAttribute cmdletAttribute =
                                    type.GetCustomAttributes(typeof(CmdletAttribute), false)
                                    .Cast <CmdletAttribute>()
                                    .FirstOrDefault();

                                if (cmdletAttribute == null)
                                {
                                    Trace.WriteLine(
                                        "Cannot load cmdlet '" + type.FullName + "' because it's class not " +
                                        "decorated with CmdletAttribute.");
                                    continue;
                                }

                                string name     = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName;
                                string helpFile = this.GetHelpFile(name);
                                cmdletsCollection.Add(new CmdletConfigurationEntry(name, type, helpFile));

                                IEnumerable <CmdletAliasAttribute> assemblyAliases =
                                    type.GetCustomAttributes(typeof(CmdletAliasAttribute), false)
                                    .Cast <CmdletAliasAttribute>();

                                foreach (CmdletAliasAttribute aliasAttribute in assemblyAliases)
                                {
                                    this.Aliases.Add(aliasAttribute.Alias, name);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine("Failed to process type '" + type.FullName + "'. " + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Failed to get types for assembly '" + assembly.FullName + "'. " + ex.Message);
                }
            }
        }
예제 #13
0
 /// <summary>
 /// Creates a new instance based on the specified cmdlet type.
 /// </summary>
 /// <param name="cmdletType">The type of the cmdlet. Must be a sub-class of <see cref="Cmdlet"/>
 /// and have a <see cref="CmdletAttribute"/>.</param>
 public Command(Type cmdletType)
 {
     if (cmdletType == null)
     {
         throw new ArgumentNullException(nameof(cmdletType));
     }
     CmdletType = cmdletType;
     _attribute = CmdletType.GetCustomAttribute <CmdletAttribute>();
     if (_attribute == null)
     {
         throw new ArgumentException("Missing CmdletAttribute", nameof(cmdletType));
     }
 }
예제 #14
0
        public void GetAzureSqlDatabaseServiceObjectiveAttributeTest()
        {
            Type cmdlet = typeof(GetAzureSqlDatabaseServiceObjective);

            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.None);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, false);

            object[] cmdletAttributes = cmdlet.GetCustomAttributes(typeof(CmdletAttribute), true);
            Assert.AreEqual(1, cmdletAttributes.Length);
            CmdletAttribute attribute = (CmdletAttribute)cmdletAttributes[0];

            Assert.AreEqual("ByConnectionContext", attribute.DefaultParameterSetName);
        }
예제 #15
0
        /// <summary>
        /// Gets a string with the name of the cmdlet defined by the type t
        /// </summary>
        /// <returns>A string with the name of the cmdlet defined by the type t or a message indicating the name of the class t is the CmdletAttribute is not found in t</returns>
        protected string GetCmdletName()
        {
            Type            t = this.GetType();
            CmdletAttribute cmdletAttribute = (CmdletAttribute)Attribute.GetCustomAttribute(t, typeof(CmdletAttribute));

            if (cmdletAttribute == null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "Unknown cmdlet name. Type: {0}", t.Name));
            }
            else
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cmdletAttribute.VerbName, cmdletAttribute.NounName));
            }
        }
        internal static string GetCmdletName(Type type)
        {
            object[] customAttributes = type.GetCustomAttributes(typeof(CmdletAttribute), false);
            if (customAttributes.Length == 0)
            {
                return(string.Empty);
            }
            CmdletAttribute cmdletAttribute = customAttributes[0] as CmdletAttribute;
            StringBuilder   stringBuilder   = new StringBuilder(cmdletAttribute.VerbName);

            stringBuilder.Append("-");
            stringBuilder.Append(cmdletAttribute.NounName);
            return(stringBuilder.ToString());
        }
예제 #17
0
        public static void CheckCmdletModifiesData(Type cmdlet, bool supportsShouldProcess)
        {
            // If the Cmdlet modifies data, SupportsShouldProcess should be set to true.
            object[] cmdletAttributes = cmdlet.GetCustomAttributes(typeof(CmdletAttribute), true);
            Assert.AreEqual(1, cmdletAttributes.Length);
            CmdletAttribute attribute = (CmdletAttribute)cmdletAttributes[0];

            Assert.AreEqual(supportsShouldProcess, attribute.SupportsShouldProcess);

            if (supportsShouldProcess)
            {
                // If the Cmdlet modifies data, there needs to be a Force property to bypass ShouldProcess
                Assert.AreNotEqual(null, cmdlet.GetProperty("Force"), "Force property is expected for Cmdlets that modifies data.");
            }
        }
예제 #18
0
        public static void CheckConfirmImpact(Type cmdlet, ConfirmImpact confirmImpact)
        {
            object[] cmdletAttributes = cmdlet.GetCustomAttributes(typeof(CmdletAttribute), true);
            Assert.Single(cmdletAttributes);
            CmdletAttribute attribute = (CmdletAttribute)cmdletAttributes[0];

            if (attribute.SupportsShouldProcess)
            {
                Assert.Equal(confirmImpact, attribute.ConfirmImpact);
            }
            else
            {
                Assert.Equal(ConfirmImpact.None, attribute.ConfirmImpact);
            }
        }
예제 #19
0
        protected virtual bool CheckSessionCanDoInteractiveAction()
        {
            if (InteractiveSession)
            {
                return(InteractiveSession);
            }

            CmdletAttribute attribute = GetType().GetCustomAttributes(typeof(CmdletAttribute), true).FirstOrDefault() as CmdletAttribute;
            var             message   = attribute == null
                ? "Non interactive session cannot perform an interactive operation."
                : $"Non interactive session cannot perform an interactive operation requested by the '{attribute.VerbName}-{attribute.NounName}' command.";

            WriteError(typeof(InvalidOperationException), message,
                       ErrorIds.ScriptSessionIsNotInteractive, ErrorCategory.InvalidOperation, this);
            return(InteractiveSession);
        }
예제 #20
0
        public sealed override void VisitType(Type type)
        {
            currentCmdlet = GetAttribute <CmdletAttribute>(type, false);

            if (currentCmdlet != null)
            {
                try
                {
                    VisitCmdlet(currentCmdlet);
                    base.VisitType(type);
                }
                finally
                {
                    currentCmdlet = null;
                }
            }
        }
예제 #21
0
        protected override void ProcessRecord()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            if (null != assembly)
            {
                ArrayList al = new ArrayList();

                Type[] types = assembly.GetTypes();
                foreach (Type type in types)
                {
                    if (isDerivedFrom(type, typeof(PSCmdlet)))
                    {
                        object[] attrs = type.GetCustomAttributes(true);
                        if (null != attrs)
                        {
                            foreach (object o in attrs)
                            {
                                if (o.GetType().Equals(typeof(CmdletAttribute)))
                                {
                                    CmdletAttribute a = (CmdletAttribute)o;
                                    al.Add(a.VerbName + "-" + a.NounName);
                                }
                            }
                        }
                    }
                }

                al.Sort();

                for (int i = 0; i < al.Count; i++)
                {
                    String cmdName = al[i].ToString();
                    bool   bMatch  = true;
                    if (null != _name)
                    {
                        bMatch = matchString(cmdName, _name, RegexOptions.IgnoreCase);
                    }
                    if (bMatch)
                    {
                        WriteObject(cmdName);
                    }
                }
            }
        }
        public CmdletInfo GetCmdletByTypeName(string cmdletTypeName)
        {
            if (string.IsNullOrEmpty(cmdletTypeName))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(cmdletTypeName));
            }

            Exception e          = null;
            Type      cmdletType = TypeResolver.ResolveType(cmdletTypeName, out e);

            if (e != null)
            {
                throw e;
            }

            if (cmdletType == null)
            {
                return(null);
            }

            CmdletAttribute ca = null;

            foreach (var attr in cmdletType.GetCustomAttributes(true))
            {
                ca = attr as CmdletAttribute;
                if (ca != null)
                {
                    break;
                }
            }

            if (ca == null)
            {
                throw PSTraceSource.NewNotSupportedException();
            }

            string noun       = ca.NounName;
            string verb       = ca.VerbName;
            string cmdletName = verb + "-" + noun;

            return(new CmdletInfo(cmdletName, cmdletType, null, null, _context));
        }
예제 #23
0
        /// <summary>
        /// Constructor.
        /// </summary>
        protected VSEMODLCmdletBase()
        {
            var attributes = Attribute.GetCustomAttributes(this.GetType());

            // Assemble keywords into a cmdlet(XXX-YYY).
            foreach (var attr in attributes)
            {
                if (attr is CmdletAttribute)
                {
                    CmdletAttribute cmdletAttribute = attr as CmdletAttribute;
                    this.CmdletName = cmdletAttribute.VerbName + CMDLET_SEP + cmdletAttribute.NounName;
                    break;
                }
            }

            // string.Empty : Avoiding the ETW error.
            if (this.CmdletName == null)
            {
                this.CmdletName = string.Empty;
            }
        }
예제 #24
0
        private void UpdateCmdlets()
        {
            IEnumerable <Assembly> source = from assemb in AppDomain.CurrentDomain.GetAssemblies()
                                            where CmdletAssemblyHelper.IsCmdletAssembly(assemb.GetName().Name)
                                            select assemb;

            if (source.Count <Assembly>() == 0)
            {
                throw new ArgumentException("Microsoft.Exchange.Management dll is not loaded");
            }
            DDIValidCommandTextAttribute.cmdlets.Add("New-EdgeSubscription".ToUpper());
            IEnumerable <object> enumerable = from type in DDIValidationHelper.GetAssemblyTypes(source.First <Assembly>())
                                              where !type.IsAbstract && type.GetCustomAttributes(typeof(CmdletAttribute), false).Count <object>() == 1
                                              select type.GetCustomAttributes(typeof(CmdletAttribute), false)[0];

            foreach (object obj in enumerable)
            {
                CmdletAttribute cmdletAttribute = (CmdletAttribute)obj;
                DDIValidCommandTextAttribute.cmdlets.Add((cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName).ToUpper());
            }
        }
        private static void WriteRelatedLinks(Type type)
        {
            RelatedCmdletsAttribute attr = GetAttribute <RelatedCmdletsAttribute>(type);

            if (attr == null)
            {
                _writer.WriteElementString("maml", "relatedLinks", null, null);
            }
            else
            {
                _writer.WriteStartElement("maml", "relatedLinks", null);

                foreach (Type t in attr.RelatedCmdlets)
                {
                    CmdletAttribute ca = GetAttribute <CmdletAttribute>(t);
                    if (ca == null)
                    {
                        continue;
                    }

                    _writer.WriteStartElement("maml", "navigationLink", null);
                    _writer.WriteElementString("maml", "linkText", null, ca.VerbName + "-" + ca.NounName);
                    _writer.WriteElementString("maml", "uri", null, null);
                    _writer.WriteEndElement(); //maml:navigationLink
                }
                if (attr.ExternalCmdlets != null)
                {
                    foreach (string s in attr.ExternalCmdlets)
                    {
                        _writer.WriteStartElement("maml", "navigationLink", null);
                        _writer.WriteElementString("maml", "linkText", null, s);
                        _writer.WriteElementString("maml", "uri", null, null);
                        _writer.WriteEndElement(); //maml:navigationLink
                    }
                }
                _writer.WriteEndElement(); //maml:relatedLinks
            }
        }
예제 #26
0
 private static string GetCmdletName(CmdletAttribute cmdletAttribute) => cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName;
        public static void GenerateHelp(Assembly asm, string outputPath, bool oneFile, string cmdletName)
        {
            Console.WriteLine(string.Format("MamlGenerator.GenerateHelp(): asm={0}; outputPath={1}; oneFile={2}", asm.FullName, outputPath, oneFile));

            var attr = asm.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);

            if (attr.Length == 1)
            {
                _copyright = ((AssemblyCopyrightAttribute)attr[0]).Copyright;
            }
            attr = asm.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
            if (attr.Length == 1)
            {
                _copyright += ((AssemblyDescriptionAttribute)attr[0]).Description;
            }


            StringBuilder sb = new StringBuilder();

            _writer            = new XmlTextWriter(new StringWriter(sb));
            _writer.Formatting = Formatting.Indented;

            if (oneFile)
            {
                _writer.WriteStartElement("helpItems");
                _writer.WriteAttributeString("xmlns", "http://msh");
                _writer.WriteAttributeString("schema", "maml");
            }

            foreach (Type type in asm.GetExportedTypes())
            {
                CmdletAttribute ca = GetAttribute <CmdletAttribute>(type);
                if (ca != null)
                {
                    if (!string.IsNullOrEmpty(cmdletName) && cmdletName.ToLower() != string.Format("{0}-{1}", ca.VerbName, ca.NounName).ToLower())
                    {
                        continue;
                    }

                    Console.WriteLine(string.Format("MamlGenerator.GenerateHelp(): Found Cmdlet: {0}-{1}", ca.VerbName, ca.NounName));

                    if (!oneFile)
                    {
                        _writer.WriteStartElement("helpItems");
                        _writer.WriteAttributeString("xmlns", "http://msh");
                        _writer.WriteAttributeString("schema", "maml");
                    }


                    _writer.WriteStartElement("command", "command", "http://schemas.microsoft.com/maml/dev/command/2004/10");
                    _writer.WriteAttributeString("xmlns", "maml", null, "http://schemas.microsoft.com/maml/2004/1");
                    _writer.WriteAttributeString("xmlns", "dev", null, "http://schemas.microsoft.com/maml/dev/2004/10");
                    _writer.WriteAttributeString("xmlns", "gl", null, "http://schemas.falchionconsulting.com/maml/gl/2013/02");

                    _writer.WriteStartElement("command", "details", null);

                    _writer.WriteElementString("command", "name", null, string.Format("{0}-{1}", ca.VerbName, ca.NounName));

                    CmdletGroupAttribute group = GetAttribute <CmdletGroupAttribute>(type);
                    if (group != null && !string.IsNullOrEmpty(group.Group))
                    {
                        _writer.WriteElementString("gl", "group", null, group.Group);
                    }
                    else
                    {
                        _writer.WriteElementString("gl", "group", null, ca.NounName);
                    }

                    WriteDescription(type, true, false);

                    WriteCopyright();

                    _writer.WriteElementString("command", "verb", null, ca.VerbName);
                    _writer.WriteElementString("command", "noun", null, ca.NounName);

                    _writer.WriteElementString("dev", "version", null, asm.GetName().Version.ToString());

                    _writer.WriteEndElement(); //command:details

                    WriteDescription(type, false, true);

                    WriteSyntax(ca, type);

                    _writer.WriteStartElement("command", "parameters", null);

                    foreach (PropertyInfo pi in type.GetProperties())
                    {
                        List <ParameterAttribute> pas = GetAttribute <ParameterAttribute>(pi);
                        if (pas == null)
                        {
                            continue;
                        }

                        ParameterAttribute pa = null;
                        if (pas.Count == 1)
                        {
                            pa = pas[0];
                        }
                        else
                        {
                            // Determine the defualt property parameter set to use for details.
                            ParameterAttribute defaultPA = null;
                            foreach (ParameterAttribute temp in pas)
                            {
                                string defaultSet = ca.DefaultParameterSetName;
                                if (string.IsNullOrEmpty(ca.DefaultParameterSetName))
                                {
                                    defaultSet = string.Empty;
                                }

                                string set = temp.ParameterSetName;
                                if (string.IsNullOrEmpty(set) || set == ALL_PARAMETER_SETS_NAME)
                                {
                                    set       = string.Empty;
                                    defaultPA = temp;
                                }
                                if (set.ToLower() == defaultSet.ToLower())
                                {
                                    pa        = temp;
                                    defaultPA = temp;
                                    break;
                                }
                            }
                            if (pa == null && defaultPA != null)
                            {
                                pa = defaultPA;
                            }
                            if (pa == null)
                            {
                                pa = pas[0];
                            }
                        }

                        _writer.WriteStartElement("command", "parameter", null);
                        _writer.WriteAttributeString("required", pa.Mandatory.ToString().ToLower());

                        bool supportsWildcard = GetAttribute <SupportsWildcardsAttribute>(pi) != null;
                        _writer.WriteAttributeString("globbing", supportsWildcard.ToString().ToLower());

                        if (!pa.ValueFromPipeline && !pa.ValueFromPipelineByPropertyName)
                        {
                            _writer.WriteAttributeString("pipelineInput", "false");
                        }
                        else if (pa.ValueFromPipeline && pa.ValueFromPipelineByPropertyName)
                        {
                            _writer.WriteAttributeString("pipelineInput", "true (ByValue, ByPropertyName)");
                        }
                        else if (!pa.ValueFromPipeline && pa.ValueFromPipelineByPropertyName)
                        {
                            _writer.WriteAttributeString("pipelineInput", "true (ByPropertyName)");
                        }
                        else if (pa.ValueFromPipeline && !pa.ValueFromPipelineByPropertyName)
                        {
                            _writer.WriteAttributeString("pipelineInput", "true (ByValue)");
                        }

                        if (pa.Position < 0)
                        {
                            _writer.WriteAttributeString("position", "named");
                        }
                        else
                        {
                            _writer.WriteAttributeString("position", (pa.Position + 1).ToString());
                        }

                        bool variableLength = pi.PropertyType.IsArray;
                        _writer.WriteAttributeString("variableLength", variableLength.ToString().ToLower());

                        _writer.WriteElementString("maml", "name", null, pi.Name);

                        if (pi.PropertyType.Name == "SPAssignmentCollection")
                        {
                            WriteSPAssignmentCollectionDescription();
                        }
                        else
                        {
                            WriteDescription(pa.HelpMessage, false);
                        }

                        _writer.WriteStartElement("command", "parameterValue", null);
                        _writer.WriteAttributeString("required", pa.Mandatory.ToString().ToLower());
                        _writer.WriteAttributeString("variableLength", variableLength.ToString().ToLower());
                        _writer.WriteValue(pi.PropertyType.Name);
                        _writer.WriteEndElement(); //command:parameterValue

                        WriteDevType(pi.PropertyType.Name, null);

                        _writer.WriteEndElement(); //command:parameter
                    }
                    _writer.WriteEndElement();     //command:parameters

                    //TODO: Find out what is supposed to go here
                    _writer.WriteStartElement("command", "inputTypes", null);
                    _writer.WriteStartElement("command", "inputType", null);
                    WriteDevType(null, null);
                    _writer.WriteEndElement(); //command:inputType
                    _writer.WriteEndElement(); //command:inputTypes

                    _writer.WriteStartElement("command", "returnValues", null);
                    _writer.WriteStartElement("command", "returnValue", null);
                    WriteDevType(null, null);
                    _writer.WriteEndElement(); //command:returnValue
                    _writer.WriteEndElement(); //command:returnValues

                    _writer.WriteElementString("command", "terminatingErrors", null, null);
                    _writer.WriteElementString("command", "nonTerminatingErrors", null, null);

                    _writer.WriteStartElement("maml", "alertSet", null);
                    _writer.WriteElementString("maml", "title", null, null);
                    _writer.WriteStartElement("maml", "alert", null);
                    WritePara(string.Format("For more information, type \"Get-Help {0}-{1} -detailed\". For technical information, type \"Get-Help {0}-{1} -full\".",
                                            ca.VerbName, ca.NounName));
                    _writer.WriteEndElement(); //maml:alert
                    _writer.WriteEndElement(); //maml:alertSet

                    WriteExamples(type);
                    WriteRelatedLinks(type);

                    _writer.WriteEndElement(); //command:command

                    if (!oneFile)
                    {
                        _writer.WriteEndElement(); //helpItems
                        _writer.Flush();
                        File.WriteAllText(Path.Combine(outputPath, string.Format("{0}.dll-help.xml", type.Name)), sb.ToString());
                        sb                 = new StringBuilder();
                        _writer            = new XmlTextWriter(new StringWriter(sb));
                        _writer.Formatting = Formatting.Indented;
                    }
                }
            }

            if (oneFile)
            {
                _writer.WriteEndElement(); //helpItems
                _writer.Flush();
                File.WriteAllText(Path.Combine(outputPath, string.Format("{0}.dll-help.xml", asm.GetName().Name)), sb.ToString());
            }
        }
예제 #28
0
 /// <summary>
 /// Creates a new instance based on the specified cmdlet type.
 /// </summary>
 /// <param name="cmdletType">The type of the cmdlet. Must be a sub-class of <see cref="Cmdlet"/>
 /// and have a <see cref="CmdletAttribute"/>.</param>
 public Command(Type cmdletType)
 {
     CmdletType = cmdletType ?? throw new ArgumentNullException(nameof(cmdletType));
     _attribute = CmdletType.GetCustomAttribute <CmdletAttribute>() ?? throw new ArgumentException("Missing CmdletAttribute", nameof(cmdletType));
 }
예제 #29
0
파일: Program.cs 프로젝트: vsvr/PnP
        static void Main(string[] args)
        {
            string    inFile  = args[0];
            string    outFile = args[1];
            XDocument doc     = new XDocument(new XDeclaration("1.0", "UTF-8", string.Empty));

            XNamespace ns        = "http://msh";
            XElement   helpItems = new XElement(ns + "helpItems", new XAttribute("schema", "maml"));

            doc.Add(helpItems);


            XNamespace maml    = "http://schemas.microsoft.com/maml/2004/10";
            XNamespace command = "http://schemas.microsoft.com/maml/dev/command/2004/10";
            XNamespace dev     = "http://schemas.microsoft.com/maml/dev/2004/10";

            XAttribute mamlNsAttr    = new XAttribute(XNamespace.Xmlns + "maml", "http://schemas.microsoft.com/maml/2004/10");
            XAttribute commandNsAttr = new XAttribute(XNamespace.Xmlns + "command", "http://schemas.microsoft.com/maml/dev/command/2004/10");
            XAttribute devNsAttr     = new XAttribute(XNamespace.Xmlns + "dev", "http://schemas.microsoft.com/maml/dev/2004/10");

            string   output   = string.Empty;
            Assembly assembly = Assembly.LoadFrom(inFile);

            Type[] types = assembly.GetTypes();
            foreach (Type t in types)
            {
                if (t.BaseType.Name == "SPOCmdlet" || t.BaseType.Name == "PSCmdlet" || t.BaseType.Name == "SPOWebCmdlet" || t.BaseType.Name == "SPOAdminCmdlet")
                {
                    //XElement examples = new XElement(command + "examples");

                    string verb                            = string.Empty;
                    string noun                            = string.Empty;
                    string description                     = string.Empty;
                    string detaileddescription             = string.Empty;
                    string details                         = string.Empty;
                    string copyright                       = string.Empty;
                    string version                         = string.Empty;
                    var    attrs                           = t.GetCustomAttributes();
                    List <CmdletExampleAttribute> examples = new List <CmdletExampleAttribute>();

                    //System.Attribute.GetCustomAttributes(t);

                    foreach (System.Attribute attr in attrs)
                    {
                        if (attr is CmdletAttribute)
                        {
                            CmdletAttribute a = (CmdletAttribute)attr;
                            verb = a.VerbName;
                            noun = a.NounName;
                        }
                        if (attr is CmdletHelpAttribute)
                        {
                            CmdletHelpAttribute a = (CmdletHelpAttribute)attr;
                            description         = a.Description;
                            details             = a.Details;
                            copyright           = a.Copyright;
                            version             = a.Version;
                            detaileddescription = a.DetailedDescription;
                        }
                        if (attr is CmdletExampleAttribute)
                        {
                            CmdletExampleAttribute a = (CmdletExampleAttribute)attr;
                            examples.Add(a);
                        }
                    }

                    XElement commandElement = new XElement(command + "command", mamlNsAttr, commandNsAttr, devNsAttr);
                    XElement detailsElement = new XElement(command + "details");
                    commandElement.Add(detailsElement);

                    detailsElement.Add(new XElement(command + "name", string.Format("{0}-{1}", verb, noun)));
                    detailsElement.Add(new XElement(maml + "description", new XElement(maml + "para", description)));
                    detailsElement.Add(new XElement(maml + "copyright", new XElement(maml + "para", copyright)));
                    detailsElement.Add(new XElement(command + "verb", verb));
                    detailsElement.Add(new XElement(command + "noun", noun));
                    detailsElement.Add(new XElement(dev + "version", version));

                    commandElement.Add(new XElement(maml + "description", new XElement(maml + "para", detaileddescription)));

                    XElement syntaxElement = new XElement(command + "syntax");
                    commandElement.Add(syntaxElement);

                    FieldInfo[]       fields      = t.GetFields();
                    List <SyntaxItem> syntaxItems = new List <SyntaxItem>();
                    foreach (FieldInfo field in fields)
                    {
                        foreach (System.Attribute attr in field.GetCustomAttributes(typeof(ParameterAttribute), true))
                        {
                            if (attr is ParameterAttribute)
                            {
                                SyntaxItem         syntaxItem = null;
                                ParameterAttribute a          = (ParameterAttribute)attr;

                                if (a.ParameterSetName != ParameterAttribute.AllParameterSets)
                                {
                                    syntaxItem = syntaxItems.Where(x => x.Name == a.ParameterSetName).FirstOrDefault();
                                    if (syntaxItem == null)
                                    {
                                        syntaxItem = new SyntaxItem(a.ParameterSetName);
                                        syntaxItems.Add(syntaxItem);
                                    }
                                    syntaxItem.Parameters.Add(new SyntaxItem.Parameter()
                                    {
                                        Name = field.Name, Description = a.HelpMessage, Position = a.Position, Required = a.Mandatory, Type = field.FieldType.Name
                                    });
                                }
                            }
                        }
                    }

                    // all parameters
                    foreach (FieldInfo field in fields)
                    {
                        foreach (System.Attribute attr in field.GetCustomAttributes(typeof(ParameterAttribute), true))
                        {
                            if (attr is ParameterAttribute)
                            {
                                ParameterAttribute a = (ParameterAttribute)attr;
                                if (a.ParameterSetName == ParameterAttribute.AllParameterSets)
                                {
                                    foreach (var si in syntaxItems)
                                    {
                                        si.Parameters.Add(new SyntaxItem.Parameter()
                                        {
                                            Name = field.Name, Description = a.HelpMessage, Position = a.Position, Required = a.Mandatory, Type = field.FieldType.Name
                                        });
                                    }
                                }
                            }
                        }
                    }

                    //
                    foreach (var syntaxItem in syntaxItems)
                    {
                        XElement syntaxItemElement = new XElement(command + "syntaxItem");
                        syntaxElement.Add(syntaxItemElement);

                        syntaxItemElement.Add(new XElement(maml + "name", string.Format("{0}-{1}", verb, noun)));
                        foreach (var parameter in syntaxItem.Parameters)
                        {
                            XElement parameterElement = new XElement(command + "parameter", new XAttribute("required", parameter.Required), new XAttribute("position", parameter.Position > 0 ? parameter.Position.ToString() : "named"));

                            parameterElement.Add(new XElement(maml + "name", parameter.Name));

                            parameterElement.Add(new XElement(maml + "description", new XElement(maml + "para", parameter.Description)));
                            parameterElement.Add(new XElement(command + "parameterValue", parameter.Type));

                            syntaxItemElement.Add(parameterElement);
                        }
                    }

                    XElement parametersElement = new XElement(command + "parameters");
                    commandElement.Add(parametersElement);

                    foreach (FieldInfo field in fields)
                    {
                        foreach (System.Attribute attr in field.GetCustomAttributes(typeof(ParameterAttribute), true))
                        {
                            if (attr is ParameterAttribute)
                            {
                                ParameterAttribute a = (ParameterAttribute)attr;
                                XElement           parameter2Element = new XElement(command + "parameter", new XAttribute("required", a.Mandatory), new XAttribute("position", a.Position > 0 ? a.Position.ToString() : "named"));

                                parameter2Element.Add(new XElement(maml + "name", field.Name));

                                parameter2Element.Add(new XElement(maml + "description", new XElement(maml + "para", a.HelpMessage)));
                                var parameterValueElement = new XElement(command + "parameterValue", field.FieldType.Name, new XAttribute("required", a.Mandatory));
                                parameter2Element.Add(parameterValueElement);

                                var devElement = new XElement(dev + "type");
                                devElement.Add(new XElement(maml + "name", field.FieldType.Name));
                                devElement.Add(new XElement(maml + "uri"));

                                parameter2Element.Add(devElement);

                                parametersElement.Add(parameter2Element);
                                break;
                            }
                        }
                    }

                    commandElement.Add(
                        new XElement(command + "inputTypes",
                                     new XElement(command + "inputType",
                                                  new XElement(dev + "type",
                                                               new XElement(maml + "name", "String"),
                                                               new XElement(maml + "uri"),
                                                               new XElement(maml + "description",
                                                                            new XElement(maml + "para", "description"))))));
                    helpItems.Add(commandElement);

                    commandElement.Add(
                        new XElement(command + "returnValues",
                                     new XElement(command + "returnValue",
                                                  new XElement(dev + "type",
                                                               new XElement(maml + "name", "String"),
                                                               new XElement(maml + "uri"),
                                                               new XElement(maml + "description",
                                                                            new XElement(maml + "para", "description"))))));

                    XElement examplesElement = new XElement(command + "examples");
                    int      exampleCount    = 1;
                    foreach (var exampleAttr in examples.OrderBy(e => e.SortOrder))
                    {
                        XElement example = new XElement(command + "example");
                        string   title   = string.Format("------------------EXAMPLE {0}---------------------", exampleCount);
                        example.Add(new XElement(maml + "title", title));
                        example.Add(new XElement(maml + "introduction", new XElement(maml + "para", exampleAttr.Introduction)));
                        example.Add(new XElement(dev + "code", exampleAttr.Code));
                        example.Add(new XElement(maml + "remarks", new XElement(maml + "para", exampleAttr.Remarks)));
                        example.Add(new XElement(command + "commandLines",
                                                 new XElement(command + "commandLine",
                                                              new XElement(command + "commandText"))));
                        examplesElement.Add(example);
                        exampleCount++;
                    }
                    commandElement.Add(examplesElement);
                }
            }
            doc.Save(outFile);
        }
예제 #30
0
        /// <summary>
        ///     Generate MAML documentation for the specified Cmdlet.
        /// </summary>
        /// <param name="cmdletType">
        ///     The CLR type that implements the Cmdlet.
        /// </param>
        /// <returns>
        ///     A <see cref="Command"/> representing the Cmdlet documentation.
        /// </returns>
        public Command Generate(Type cmdletType)
        {
            if (cmdletType == null)
            {
                throw new ArgumentNullException(nameof(cmdletType));
            }

            if (!Reflector.IsCmdlet(cmdletType))
            {
                throw new ArgumentException($"'{cmdletType.FullName}' does not implement a Cmdlet (must be public, non-abstract, derive from '{typeof(Cmdlet).FullName}', and be decorated with '{typeof(CmdletAttribute).FullName}').", nameof(cmdletType));
            }

            TypeInfo        cmdletTypeInfo  = cmdletType.GetTypeInfo();
            CmdletAttribute cmdletAttribute = cmdletTypeInfo.GetCustomAttribute <CmdletAttribute>();

            Debug.Assert(cmdletAttribute != null, "cmdletAttribute != null");

            Command commandHelp = new Command
            {
                Details =
                {
                    Name     = $"{cmdletAttribute.VerbName}-{cmdletAttribute.NounName}",
                    Synopsis = ToParagraphs(
                        GetCmdletSynopsis(cmdletTypeInfo) ?? String.Empty
                        ),
                    Verb = cmdletAttribute.VerbName,
                    Noun = cmdletAttribute.NounName
                },
                Description = ToParagraphs(
                    GetCmdletDescription(cmdletTypeInfo) ?? String.Empty
                    )
            };

            var parameterSets = new Dictionary <string, SyntaxItem>();

            foreach (PropertyInfo property in cmdletType.GetProperties().OrderBy(property => property.CanRead))
            {
                if (!Reflector.IsCmdletParameter(property))
                {
                    continue;
                }

                ParameterAttribute parameterAttribute = property.GetCustomAttributes <ParameterAttribute>().First();

                // TODO: Add support for localised help from resources.

                Parameter parameter = new Parameter
                {
                    Name        = property.Name,
                    Description = ToParagraphs(parameterAttribute.HelpMessage),
                    Value       =
                    {
                        IsMandatory = parameterAttribute.Mandatory,
                        DataType    = property.PropertyType.Namespace == "System" ? // This is a PowerShell convention.
                                      property.PropertyType.Name
                            :
                                      property.PropertyType.FullName,
                    },
                    IsMandatory      = parameterAttribute.Mandatory,
                    SupportsGlobbing = property.GetCustomAttribute <SupportsWildcardsAttribute>() != null
                };
                commandHelp.Parameters.Add(parameter);

                // Update command syntax for the current parameter set.
                string parameterSetName = parameterAttribute.ParameterSetName ?? String.Empty;

                SyntaxItem parameterSetSyntax;
                if (!parameterSets.TryGetValue(parameterSetName, out parameterSetSyntax))
                {
                    parameterSetSyntax = new SyntaxItem
                    {
                        CommandName = commandHelp.Details.Name
                    };
                    parameterSets.Add(parameterSetName, parameterSetSyntax);
                }

                parameterSetSyntax.Parameters.Add(parameter);
            }

            foreach (string parameterSetName in parameterSets.Keys.OrderBy(name => name))
            {
                commandHelp.Syntax.Add(
                    parameterSets[parameterSetName]
                    );
            }

            return(commandHelp);
        }