[APORTE] Plantilla aplicación de consola (sin menú).

Iniciado por Eleкtro, 5 Diciembre 2013, 16:40 PM

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

Quiero compartir mi plantilla de aplicación de consola por defecto para parsear argumentos,
para importar la plantilla a VisualStudio símplemente deben copiar el archivo ZIP al directorio "...Mis Documentos\Visual Studio\Templates\ProjectTemplates\"  (o donde lo hayan establecido en la configuración de VisualStudio).

Esto es lo que le añadí:

· Sección de ayuda. (Logo, sintaxis, título)
· Método para escribir texto coloreado.
· Método para ocultar la consola.
· Método para lanzar un error conocido.
· Método para establecer los argumentos de la aplicación. (Ojo, esto es con fines de debug, no usarlo en el Release, ya que el regex no es perfecto.)
· Método para procesar argumentos.
· Método para comprobar si los argumentos están vacios.
· Método para unir los argumentos en un String.

Todo documentado y en no muchas lineas de código.

Descarga: http://elektrostudios.tk/ElektroStudios%20Console%20Application.zip




Una imagen:





Este es el código principal, junto a 2 Classes adicionales que se encuentran dentro de la plantilla.

Código (vbnet) [Seleccionar]
Module Main

#Region " Variables "

   ''' <summary>
   ''' Here will be stored the commandline arguments for this application.
   ''' If DebugArguments is nothing then the normal arguments are used,
   ''' Otherwise, the custom debug arguments are used.
   ''' </summary>
   Private Arguments As IEnumerable(Of String) =
       Set_CommandLine_Arguments(<a><![CDATA[/Switch1=Value1 /Switch2="Value2"]]></a>.Value)

   ''' <summary>
   ''' Something.
   ''' </summary>
   Private Something As String = Nothing

   ''' <summary>
   ''' To manage known errors.
   ''' </summary>
   Private ReadOnly KnownErrors As New Dictionary(Of Integer, String) From
   {
       {1, "Wrong parameter"},
       {2, "Parameter not specified"},
       {9999, "Unknown Error"}
   }

#End Region

#Region " DEBUG CommandLine Arguments "

   ''' <summary>
   ''' Set the commandline arguments of this application for testing purposes.
   ''' </summary>
   Public Function Set_CommandLine_Arguments(Optional ByVal DebugArguments As String = Nothing) As IEnumerable(Of String)

#If DEBUG Then

   ' Código eliminado porque el foro tiene un bug al parsear los caracteres...

   End Function

#End Region

#Region " Main Procedure "

   ''' <summary>
   ''' The main procedure of this application.
   ''' </summary>
   Public Sub Main()
       Console.Title = HelpSection.Title ' Set the Console Title.
       Write_Colored_Text(HelpSection.Logo, True, ConsoleColor.Green) ' Print the Logo.
       Write_Colored_Text("Arguments: " & Join_Arguments(Arguments), True, ConsoleColor.DarkGray) ' Print the Arguments.
       Parse_Arguments() ' Processes the arguments passed to the application.
       DoSomething() ' Do Something and wait.
       Environment.Exit(0) ' Exit succesfully.
   End Sub

#End Region

#Region " Methods "

   ''' <summary>
   ''' Parses the Arguments passed to this application.
   ''' </summary>
   Private Sub Parse_Arguments()

       ' Arguments Are Empty?.
       If Arguments_Are_Empty(Arguments) Then
           PrintHelp()
       End If

       ' Parse arguments.
       For Each Argument As String In Arguments

           Select Case True

               Case Argument.StartsWith("/Switch1=", StringComparison.InvariantCultureIgnoreCase)
                   ' Something = Argument.Substring(Argument.IndexOf("=") + 1)

           End Select

       Next Argument

       If Something Is Nothing Then
           LaunchError(1, "/Switch1")
       End If

   End Sub

   ''' <summary>
   ''' Do something and wait.
   ''' </summary>
   Private Sub DoSomething()

       Do Until Something = "Something Else"
           Application.DoEvents()
       Loop

   End Sub

#End Region

#Region " Miscellaneous Methods "

   ''' <summary>
   ''' Check if the arguments are empty.
   ''' </summary>
   ''' <param name="DebugArguments">Indicates a custom arguments to check.</param>
   Private Function Arguments_Are_Empty(Optional ByVal DebugArguments As IEnumerable(Of String) = Nothing) As Boolean

       Return Not Convert.ToBoolean(If(DebugArguments IsNot Nothing,
                                       DebugArguments.Count,
                                       Environment.GetCommandLineArgs.Skip(1).Count))

   End Function

   ''' <summary>
   ''' Joins the Arguments to return a single String.
   ''' </summary>
   ''' <param name="DebugArguments">Indicates a custom arguments to join.</param>
   Private Function Join_Arguments(Optional ByVal DebugArguments As IEnumerable(Of String) = Nothing) As String

       Return String.Join(Convert.ToChar(Keys.Space),
                          If(DebugArguments IsNot Nothing,
                             DebugArguments,
                             Environment.GetCommandLineArgs.Skip(1)))

   End Function

   ''' <summary>
   ''' Writes colored text on the Console.
   ''' </summary>
   ''' <param name="Text">Indicates the text to write.</param>
   ''' <param name="AddNewLine">Adds an empty line at the end of the text.</param>
   ''' <param name="ForeColor">Indicates the text color.</param>
   ''' <param name="BackColor">Indicates the background color.</param>
   Private Sub Write_Colored_Text(ByVal Text As String,
                                  Optional ByVal AddNewLine As Boolean = False,
                                  Optional ByVal ForeColor As ConsoleColor = Nothing,
                                  Optional ByVal BackColor As ConsoleColor = Nothing)

       Console.ForegroundColor = If(ForeColor = Nothing, Console.ForegroundColor, ForeColor)
       Console.BackgroundColor = If(ForeColor = Nothing, Console.BackgroundColor, BackColor)

       If AddNewLine Then
           Console.WriteLine(Text)
       Else
           Console.Write(Text)
       End If

       Console.ForegroundColor = If(ForeColor = Nothing, Console.ForegroundColor, ForeColor)
       Console.BackgroundColor = If(ForeColor = Nothing, Console.BackgroundColor, BackColor)

   End Sub

   ''' <summary>
   ''' Set the window state of the console.
   ''' </summary>
   ''' <param name="WindowState">Indicates the new state of the console window.</param>
   Public Function SetWindow(ByVal WindowState As ConsoleWindowState.WindowState) As Boolean
       Return ConsoleWindowState.SetWindowState(WindowState)
   End Function

   ''' <summary>
   ''' Print the Help section and exits from the application.
   ''' </summary>
   Private Sub PrintHelp()
       Console.WriteLine(HelpSection.Help)
       Environment.Exit(0) ' Exit succesfully.
   End Sub

   ''' <summary>
   ''' Launch a known error and exits from the application.
   ''' </summary>
   ''' <param name="ErrorID">
   ''' Indicates the known Error Identifier.
   ''' This value is also used to specify the ExitCode.
   ''' </param>
   ''' <param name="MoreInfo">Indicates additional information.</param>
   Private Sub LaunchError(ByVal ErrorID As Integer, Optional ByVal MoreInfo As String = Nothing)

       Console.WriteLine()
       Write_Colored_Text(KnownErrors(ErrorID) &
                          If(MoreInfo IsNot Nothing, ": " & MoreInfo, Nothing),
                          True, ConsoleColor.White, ConsoleColor.DarkRed)

       Environment.Exit(ErrorID) ' Exit with error exitcode.

   End Sub

#End Region

#Region " Event Handlers "

   ' Add here your EventHandlers.

#End Region

End Module


Saludos.