elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [TUTORIAL] Crear una sección de ayuda (de consola) de forma dinámica usando XML
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [TUTORIAL] Crear una sección de ayuda (de consola) de forma dinámica usando XML  (Leído 2,246 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
[TUTORIAL] Crear una sección de ayuda (de consola) de forma dinámica usando XML
« en: 5 Enero 2014, 16:44 pm »

Este mini-tutorial es sólomente apto para los amantes de las aplicaciones commandline.





¿Les gusta la imagen de arriba?, ¿Creen que pueden mejorarlo?, entonces me alegro mucho ya que les voy a explicar como pueden hacer lo mismo de forma muy sencilla.

Se me ocurrió la idea de darle un poco de 'vida' a las secciones de ayuda de mis aplicaciones así que ideé un metodo de uso genérico ...y a mi parecer creo que quedó sencillo y eficaz.

Los pasos a seguir son estos:

1. Copien y peguen esta Class que contiene la documentación de ayuda, en su proyecto:

Código
  1. ' Name.......: Help Section
  2. ' Author.....: Elektro
  3. ' Description: Class that manages the Help documentation of a Console application with colorization capabilities.
  4. ' Last Update: 05/01/2014
  5. ' References.: LINQ, 'WriteColoredText' method by Elektro.
  6. ' Indications: Use *F##* as the ForeColor beginning delimiter, use *-F* to restore the console forecolor.
  7. '              Use *B##* as the BackColor beginning delimiter, use *-B* to restore the console BackColor.
  8.  
  9.  
  10. #Region " Usage Examples "
  11.  
  12. #Region " Example Without Colorization "
  13.  
  14. 'Module Module1
  15.  
  16. '    Sub Main()
  17.  
  18. '        Console.Title = HelpSection.Help.<Title>.Value
  19.  
  20. '        Dim sb As New System.Text.StringBuilder
  21. '        sb.AppendLine(HelpSection.Help.<Logo>.Value)
  22. '        sb.AppendLine(HelpSection.Help.<Separator>.Value)
  23. '        sb.AppendLine(String.Format("    Executable name.......: {0}", HelpSection.Help.<Process>.Value))
  24. '        sb.AppendLine(String.Format("    Application name......: {0}", HelpSection.Help.<Name>.Value))
  25. '        sb.AppendLine(String.Format("    Application version...: {0}", HelpSection.Help.<Version>.Value))
  26. '        sb.AppendLine(String.Format("    Application author....: {0}", HelpSection.Help.<Author>.Value))
  27. '        sb.AppendLine(String.Format("    Application copyright.: {0}", HelpSection.Help.<Copyright>.Value))
  28. '        sb.AppendLine(String.Format("    Author website........: {0}", HelpSection.Help.<Website>.Value))
  29. '        sb.AppendLine(String.Format("    Author Skype..........: {0}", HelpSection.Help.<Skype>.Value))
  30. '        sb.AppendLine(String.Format("    Author Email..........: {0}", HelpSection.Help.<Email>.Value))
  31. '        sb.AppendLine(HelpSection.Help.<Separator>.Value)
  32. '        sb.AppendLine(HelpSection.Help.<Syntax>.Value)
  33. '        sb.AppendLine(HelpSection.Help.<SyntaxExtra>.Value)
  34. '        sb.AppendLine(HelpSection.Help.<UsageExamples>.Value)
  35.  
  36. '         HelpSection.WriteLine(sb.ToString)
  37.  
  38. '        Threading.Thread.Sleep(60000)
  39.  
  40. '    End Sub
  41.  
  42. 'End Module
  43.  
  44. #End Region
  45.  
  46. #Region " Example With Colorization "
  47.  
  48. 'Module Module1
  49.  
  50. '    Sub Main()
  51.  
  52. '        Console.Title = HelpSection.ColorizedHelp.<Title>.Value
  53.  
  54. '        Dim sb As New System.Text.StringBuilder
  55. '        sb.AppendLine(HelpSection.ColorizedHelp.<Logo>.Value)
  56. '        sb.AppendLine(HelpSection.ColorizedHelp.<Separator>.Value)
  57. '        sb.AppendLine(String.Format("    Executable name.......: {0}", HelpSection.ColorizedHelp.<Process>.Value))
  58. '        sb.AppendLine(String.Format("    Application name......: {0}", HelpSection.ColorizedHelp.<Name>.Value))
  59. '        sb.AppendLine(String.Format("    Application version...: {0}", HelpSection.ColorizedHelp.<Version>.Value))
  60. '        sb.AppendLine(String.Format("    Application author....: {0}", HelpSection.ColorizedHelp.<Author>.Value))
  61. '        sb.AppendLine(String.Format("    Application copyright.: {0}", HelpSection.ColorizedHelp.<Copyright>.Value))
  62. '        sb.AppendLine(String.Format("    Author website........: {0}", HelpSection.ColorizedHelp.<Website>.Value))
  63. '        sb.AppendLine(String.Format("    Author Skype..........: {0}", HelpSection.ColorizedHelp.<Skype>.Value))
  64. '        sb.AppendLine(String.Format("    Author Email..........: {0}", HelpSection.ColorizedHelp.<Email>.Value))
  65. '        sb.AppendLine(HelpSection.ColorizedHelp.<Separator>.Value)
  66. '        sb.AppendLine(HelpSection.ColorizedHelp.<Syntax>.Value)
  67. '        sb.AppendLine(HelpSection.ColorizedHelp.<SyntaxExtra>.Value)
  68. '        sb.AppendLine(HelpSection.ColorizedHelp.<UsageExamples>.Value)
  69.  
  70. '        WriteColoredTextLine(sb.ToString, {"*"c})
  71.  
  72. '        Threading.Thread.Sleep(60000)
  73.  
  74. '    End Sub
  75.  
  76. 'End Module
  77.  
  78. #End Region
  79.  
  80. #End Region
  81.  
  82. #Region " ConsoleColor Enumeration Helper "
  83.  
  84. ' Black = 0
  85. ' DarkBlue = 1
  86. ' DarkGreen = 2
  87. ' DarkCyan = 3
  88. ' DarkRed = 4
  89. ' DarkMagenta = 5
  90. ' DarkYellow = 6
  91. ' Gray = 7
  92. ' DarkGray = 8
  93. ' Blue = 9
  94. ' Green = 10
  95. ' Cyan = 11
  96. ' Red = 12
  97. ' Magenta = 13
  98. ' Yellow = 14
  99. ' White = 15
  100.  
  101. #End Region
  102.  
  103. #Region " HelpSection "
  104.  
  105. Friend Class HelpSection
  106.  
  107. #Region " Members "
  108.  
  109.    ''' <summary>
  110.    ''' Indicates dynamically the name of the current process.
  111.    ''' </summary>
  112.    Private Shared ReadOnly ProcessName As String =
  113.        Process.GetCurrentProcess().MainModule.ModuleName
  114.  
  115.    ''' <summary>
  116.    ''' Use this var into an XML if need to escape an 'GreaterThan' character.
  117.    ''' </summary>
  118.    Private ReadOnly c_GreaterThan As Char = ">"c
  119.  
  120.    ''' <summary>
  121.    ''' Use this var into an XML if need to escape an 'LowerThan' character.
  122.    ''' </summary>
  123.    Private ReadOnly c_LowerThan As Char = "<"c
  124.  
  125. #End Region
  126.  
  127. #Region " Help Text "
  128.  
  129.    ''' <summary>
  130.    ''' Contains Help information such as Author, Syntax and Example usages.
  131.    ''' </summary>
  132.    Friend Shared ReadOnly Help As XElement =
  133. <Help>
  134.  
  135.    <!-- Current process name -->
  136.    <!-- That means even when the user manually changes the executable name -->
  137.    <Process><%= ProcessName %></Process>
  138.  
  139.    <!-- Application title -->
  140.    <Title>My Application .:: By Elektro ::.</Title>
  141.  
  142.    <!-- Application name -->
  143.    <Name>My Application</Name>
  144.  
  145.    <!-- Application author -->
  146.    <Author>Elektro</Author>
  147.  
  148.    <!-- Application version -->
  149.    <Version>1.0</Version>
  150.  
  151.    <!-- Copyright information -->
  152.    <Copyright>© Elektro Software 2014</Copyright>
  153.  
  154.    <!-- Website information -->
  155.    <Website>http://foro.elhacker.net</Website>
  156.  
  157.    <!-- Skype contact information -->
  158.    <Skype>ElektroStudios</Skype>
  159.  
  160.    <!-- Email contact information -->
  161.    <Email>ElektroStudios@ElHacker.Net</Email>
  162.  
  163.    <!-- Application Logotype -->
  164.    <Logo>
  165.    .____                        
  166.    |    |    ____   ____   ____  
  167.    |    |   / _  \ / ___\ /  _ \
  168.    |    |__( |_|  ) /_/  >  |_| )
  169.    |_______ \____/\___  / \____/
  170.            \/     /____/  
  171.    </Logo>
  172.  
  173.    <!-- Separator shape -->
  174.    <Separator>
  175.    ------------------------------------------------------>>>>
  176.    </Separator>
  177.  
  178.    <!-- Application Syntax -->
  179.    <Syntax>
  180.    [+] Syntax
  181.  
  182.        <%= ProcessName %> (SWITCH)=(VALUE) (IN FILE)
  183.    </Syntax>
  184.  
  185.    <!-- Application Syntax (Additional Specifications) -->
  186.    <SyntaxExtra>
  187.    [+] Switches
  188.  
  189.        /Switch1  | Description.
  190.        /Switch2  | Description.
  191.                  |
  192.        /?        | Display this help.
  193.  
  194.  
  195.    [+] Switch value types
  196.  
  197.        /Switch1  (INT)
  198.        /Switch2  (X,Y)
  199.    </SyntaxExtra>
  200.  
  201.    <!-- Application Usage Examples -->
  202.    <UsageExamples>
  203.    [+] Usage examples
  204.  
  205.        <%= ProcessName %> /Switch1=Value "C:\File.txt"
  206.        ( Command explanation )
  207.    </UsageExamples>
  208.  
  209. </Help>
  210.  
  211.    ''' <summary>
  212.    ''' Contains Help information such as Author, Syntax and Example usages.
  213.    ''' These strings are color-delimited to print a colorized output console,
  214.    ''' using the 'WriteColoredText' methods written by Elektro.
  215.    ''' </summary>
  216.    Friend Shared ReadOnly ColorizedHelp As XElement =
  217. <Help>
  218.  
  219.    <!-- Current process name -->
  220.    <!-- That means even when the user manually changes the executable name -->
  221.    <Process>*F10*<%= ProcessName %>*-F*</Process>
  222.  
  223.    <!-- Application title -->
  224.    <Title>My Application .:: By Elektro ::.</Title>
  225.  
  226.    <!-- Application name -->
  227.    <Name>*F10*My Application*-F*</Name>
  228.  
  229.    <!-- Application author -->
  230.    <Author>*f10*Elektro*-F*</Author>
  231.  
  232.    <!-- Application version -->
  233.    <Version>*F10*1.0*-F*</Version>
  234.  
  235.    <!-- Copyright information -->
  236.    <Copyright>*F10*© Elektro Software 2014*-F*</Copyright>
  237.  
  238.    <!-- Website information -->
  239.    <Website>*F10*http://foro.elhacker.net*-F*</Website>
  240.  
  241.    <!-- Skype contact information -->
  242.    <Skype>*F10*ElektroStudios*-F*</Skype>
  243.  
  244.    <!-- Email contact information -->
  245.    <Email>*F10*ElektroStudios@ElHacker.Net*-F*</Email>
  246.  
  247.    <!-- Application Logotype -->
  248.    <Logo>*F11*
  249.    .____                        
  250.    |    |    ____   ____   ____  
  251.    |    |   / _  \ / ___\ /  _ \
  252.    |    |__( |_|  ) /_/  >  |_| )
  253.    |_______ \____/\___  / \____/
  254.            \/     /____/  
  255.    *-F*</Logo>
  256.  
  257.    <!-- Separator shape -->
  258.    <Separator>
  259.    *F11*------------------------------------------------------>>>>*-F*
  260.    </Separator>
  261.  
  262.    <!-- Application Syntax -->
  263.    <Syntax>
  264.    *F11*[+]*-F* *F14*Syntax*-F*
  265.  
  266.        <%= ProcessName %> *F10*(SWITCH)*-F*=*F10*(VALUE)*-F* *F10*(IN FILE)*-F*
  267.    </Syntax>
  268.  
  269.    <!-- Application Syntax (Additional Specifications) -->
  270.    <SyntaxExtra>
  271.    *F11*[+]*-F* *F14*Switches*-F*
  272.  
  273.        *F10*/Switch1*-F*  | *F11*Description.*-F*
  274.        *F10*/Switch2*-F*  | *F11*Description.*-F*
  275.        *F10*        *-F*  |
  276.        *F10*/?      *-F*  | *F11*Display this help.*-F*
  277.  
  278.  
  279.    *F11*[+]*-F* *F14*Switch value types*-F*
  280.  
  281.        *F10*/Switch1*-F*  (*F11*INT*-F*)
  282.        *F10*/Switch2*-F*  (*F11*X,Y*-F*)
  283.    </SyntaxExtra>
  284.  
  285.    <!-- Application Usage Examples -->
  286.    <UsageExamples>
  287.    *F11*[+]*-F* *F14*Usage examples*-F*
  288.  
  289.        <%= ProcessName %> /Switch1=Value "C:\File.txt"
  290.        *F11*( Command explanation )*-F*
  291.    </UsageExamples>
  292.  
  293. </Help>
  294.  
  295. #End Region
  296.  
  297. End Class
  298.  
  299. #End Region

2. Copien y peguen en su proyecto estos métodos para parsear y colorear los strings:

Código
  1. #Region " Write Colored Text "
  2.  
  3.    ' Name.......: Write Colored Text
  4.    ' Author.....: Elektro
  5.    ' Description: Methods to write colorized strings.
  6.    ' Last Update: 05/01/2014
  7.    ' References.: LINQ
  8.    ' Indications: Use *F##* as the ForeColor beginning delimiter, use *-F* to restore the console forecolor.
  9.    '              Use *B##* as the BackColor beginning delimiter, use *-B* to restore the console BackColor.
  10.    '
  11.    ' Example Usages:
  12.    '
  13.    ' WriteColoredText(    " Hello World! ", ConsoleColor.Blue,    ConsoleColor.Blue)
  14.    ' WriteColoredTextLine(" Hello World! ", ConsoleColor.Magenta, ConsoleColor.Gray)
  15.    ' WriteColoredTextLine(" Hello World! ", Nothing,              Nothing)
  16.    '
  17.    ' WriteColoredText("*F10*Hello *F14*World!*-F*", {"*"c})
  18.    ' WriteColoredTextLine("{B15}{F12} Hello World! {-F}{-B}", {"{"c, "}"c})
  19.    ' WriteColoredTextLine(String.Format("*B15**F12* {0} *F0*{1} *-F**-B*", "Hello", "World!"), {"*"c})
  20.  
  21.    ''' <summary>
  22.    ''' Writes colored text on the Console.
  23.    ''' </summary>
  24.    ''' <param name="Text">Indicates the color-delimited text to parse and then write.</param>
  25.    ''' <param name="Delimiters">Indicates a set of (1 or 2) delimiters to parse a color-delimited string.</param>
  26.    Friend Sub WriteColoredText(ByVal Text As String,
  27.                                ByVal Delimiters As Char())
  28.  
  29.        ' Store the current console colors to restore them later.
  30.        Dim CurrentForegroundColor As ConsoleColor = Console.ForegroundColor
  31.        Dim CurrentBackgroundColor As ConsoleColor = Console.BackgroundColor
  32.  
  33.        ' Split the string to retrieve and parse the color-delimited strings.
  34.        Dim StringParts As String() =
  35.            Text.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries)
  36.  
  37.        ' Parse the string parts
  38.        For Each part As String In StringParts
  39.  
  40.            If part.ToUpper Like "F#" _
  41.            OrElse part.ToUpper Like "F##" Then ' Change the ForeColor.
  42.  
  43.                Console.ForegroundColor = CInt(part.Substring(1))
  44.  
  45.            ElseIf part.ToUpper Like "B#" _
  46.            OrElse part.ToUpper Like "B##" Then ' Change the BackgroundColor.
  47.  
  48.                Console.BackgroundColor = CInt(part.Substring(1))
  49.  
  50.            ElseIf part.ToUpper Like "-F" Then  ' Restore the original Forecolor.
  51.  
  52.                Console.ForegroundColor = CurrentForegroundColor
  53.  
  54.            ElseIf part.ToUpper Like "-B" Then ' Restore the original BackgroundColor.
  55.  
  56.                Console.BackgroundColor = CurrentBackgroundColor
  57.  
  58.            Else ' String part is not a delimiter so we can print it.
  59.  
  60.                Console.Write(part)
  61.  
  62.            End If
  63.  
  64.        Next part
  65.  
  66.        ' Finish by restoring the original console colors.
  67.        Console.BackgroundColor = CurrentBackgroundColor
  68.        Console.ForegroundColor = CurrentForegroundColor
  69.  
  70.    End Sub
  71.  
  72.    ''' <summary>
  73.    ''' Writes colored text on the Console.
  74.    ''' </summary>
  75.    ''' <param name="Text">Indicates the text to write.</param>
  76.    ''' <param name="ForeColor">Indicates the text color.</param>
  77.    ''' <param name="BackColor">Indicates the background color.</param>
  78.    Friend Sub WriteColoredText(ByVal Text As String,
  79.                                ByVal ForeColor As ConsoleColor,
  80.                                ByVal BackColor As ConsoleColor)
  81.  
  82.        ' Store the current console colors to restore them later.
  83.        Dim CurrentForegroundColor As ConsoleColor = Console.ForegroundColor
  84.        Dim CurrentBackgroundColor As ConsoleColor = Console.BackgroundColor
  85.  
  86.        ' Set the new temporal console colors.
  87.        Console.ForegroundColor = If(ForeColor = Nothing, CurrentForegroundColor, ForeColor)
  88.        Console.BackgroundColor = If(BackColor = Nothing, CurrentBackgroundColor, BackColor)
  89.  
  90.        ' Print the text.
  91.        Console.Write(Text)
  92.  
  93.        ' Finish by restoring the original console colors.
  94.        Console.ForegroundColor = CurrentForegroundColor
  95.        Console.BackgroundColor = CurrentBackgroundColor
  96.  
  97.    End Sub
  98.  
  99.    ''' <summary>
  100.    ''' Writes colored text on the Console and adds an empty line at the end.
  101.    ''' </summary>
  102.    ''' <param name="Text">Indicates the color-delimited text to parse and then write.</param>
  103.    ''' <param name="Delimiters">Indicates a set of (1 or 2) delimiters to parse a color-delimited string.</param>
  104.    Friend Sub WriteColoredTextLine(ByVal Text As String,
  105.                                    ByVal Delimiters As Char())
  106.  
  107.        WriteColoredText(Text & Environment.NewLine, Delimiters)
  108.  
  109.    End Sub
  110.  
  111.    ''' <summary>
  112.    ''' Writes colored text on the Console and adds an empty line at the end.
  113.    ''' </summary>
  114.    ''' <param name="Text">Indicates the color-delimited text to parse and then write.</param>
  115.    ''' <param name="ForeColor">Indicates the text color.</param>
  116.    ''' <param name="BackColor">Indicates the background color.</param>
  117.    Friend Sub WriteColoredTextLine(ByVal Text As String,
  118.                                    ByVal ForeColor As ConsoleColor,
  119.                                    ByVal BackColor As ConsoleColor)
  120.  
  121.        WriteColoredText(Text & Environment.NewLine, ForeColor, BackColor)
  122.  
  123.    End Sub
  124.  
  125. #End Region


3. En la sección regionada 'Help Text' deben especificar lo que deseen, el logo, la sintaxis, la información de contacto, etc... eso es lo único que deben hardcodear (óbviamente no va a ser un click&go, pues toda aplicación tiene distintos parámetros así pues distinta información).

Por ejemplo, inspeccionemos este nodo:
Código
  1.    <!-- Application Usage Examples -->
  2.    <UsageExamples>
  3.    {f11}[+]{-f} {f14}Usage examples{-f}
  4.  
  5.        <%= ProcessName %> /Switch1=Value "C:\File.txt"
  6.        {f11}( Command explanation ){-f}
  7.    </UsageExamples>

¿Que significan todos esos parámetros 'F'?, bien, son los delimitadores que establecí para indicar el principio y el fínal de un cambio de color (color de texto o color de fondo),
un cambio de color de texto debe empezar con la letra "F" (de Forecolor), y un cambio de color de fondo debe empezar con la letra "B" (de BackgroundColor),
seguídamente le añadiremos un número del 0-15 que hace referencia a un color de consola (solo existen 15), por ejemplo: el inicio de cambio de color de texto "{F11}" hace referencia al color de consola número 11, que es el color 'Cyan'

Para restaurar el color original usaremos el delimitador {-f} o {-b} respectívamente del tipo de cambio de color del que se trate.

Y para mostrar el texto coloreado es necesario usar un método que ideé el cual se encarga de parsear los delimitadores de cambio de colores.


Un ejemplo de uso de los método:

Código
  1. Module Module1
  2.  
  3.    Sub Main()
  4.  
  5.        Console.Title = HelpSection.ColorizedHelp.<Title>.Value
  6.  
  7.        Dim sb As New System.Text.StringBuilder
  8.        sb.AppendLine(HelpSection.ColorizedHelp.<Logo>.Value)
  9.        sb.AppendLine(HelpSection.ColorizedHelp.<Separator>.Value)
  10.        sb.AppendLine(HelpSection.ColorizedHelp.<Syntax>.Value)
  11.        sb.AppendLine(HelpSection.ColorizedHelp.<UsageExamples>.Value)
  12.  
  13.        WriteColoredTextLine(sb.ToString, {"*"c})
  14.        ' WriteColoredText(sb.ToString, {"*"c})
  15.  
  16.        Threading.Thread.Sleep(60000)
  17.  
  18.    End Sub
  19.  
  20. End Module

Además, los métodos son de uso genérico y hay 1 overload para los dos métodos, esto significa que pueden reutilizarlos de forma individual en cualquier otro tipo de proyecto, de la siguiente manera:
Código
  1. WriteColoredText(" Hello World! ", ConsoleColor.Blue, ConsoleColor.Blue)
  2. WriteColoredTextLine(" Hello World! ", ConsoleColor.Magenta, ConsoleColor.Gray)
  3. WriteColoredTextLine(" Hello World! ", Nothing, Nothing)
  4.  
  5. WriteColoredText("*F10*Hello *F14*World!*-F*", {"*"c})
  6. WriteColoredTextLine("{B15}{F12} Hello World! {-F}{-B}", {"{"c, "}"c})
  7. WriteColoredTextLine(String.Format("*B15**F12* {0} *F0*{1} *-F**-B*", "Hello", "World!"), {"*"c})
  8.  

Eso es todo, ¿te resultó facil?, espero que este mini-tutorial le haya servido a alguien.

Saludos!


« Última modificación: 28 Agosto 2018, 04:57 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines