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

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] Plantilla aplicación de consola (sin menú).
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] Plantilla aplicación de consola (sin menú).  (Leído 1,453 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
[APORTE] Plantilla aplicación de consola (sin menú).
« en: 5 Diciembre 2013, 16:40 pm »

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
  1. Module Main
  2.  
  3. #Region " Variables "
  4.  
  5.    ''' <summary>
  6.    ''' Here will be stored the commandline arguments for this application.
  7.    ''' If DebugArguments is nothing then the normal arguments are used,
  8.    ''' Otherwise, the custom debug arguments are used.
  9.    ''' </summary>
  10.    Private Arguments As IEnumerable(Of String) =
  11.        Set_CommandLine_Arguments(<a><![CDATA[/Switch1=Value1 /Switch2="Value2"]]></a>.Value)
  12.  
  13.    ''' <summary>
  14.    ''' Something.
  15.    ''' </summary>
  16.    Private Something As String = Nothing
  17.  
  18.    ''' <summary>
  19.    ''' To manage known errors.
  20.    ''' </summary>
  21.    Private ReadOnly KnownErrors As New Dictionary(Of Integer, String) From
  22.    {
  23.        {1, "Wrong parameter"},
  24.        {2, "Parameter not specified"},
  25.        {9999, "Unknown Error"}
  26.    }
  27.  
  28. #End Region
  29.  
  30. #Region " DEBUG CommandLine Arguments "
  31.  
  32.    ''' <summary>
  33.    ''' Set the commandline arguments of this application for testing purposes.
  34.    ''' </summary>
  35.    Public Function Set_CommandLine_Arguments(Optional ByVal DebugArguments As String = Nothing) As IEnumerable(Of String)
  36.  
  37. #If DEBUG Then
  38.  
  39.    ' Código eliminado porque el foro tiene un bug al parsear los caracteres...
  40.  
  41.    End Function
  42.  
  43. #End Region
  44.  
  45. #Region " Main Procedure "
  46.  
  47.    ''' <summary>
  48.    ''' The main procedure of this application.
  49.    ''' </summary>
  50.    Public Sub Main()
  51.        Console.Title = HelpSection.Title ' Set the Console Title.
  52.        Write_Colored_Text(HelpSection.Logo, True, ConsoleColor.Green) ' Print the Logo.
  53.        Write_Colored_Text("Arguments: " & Join_Arguments(Arguments), True, ConsoleColor.DarkGray) ' Print the Arguments.
  54.        Parse_Arguments() ' Processes the arguments passed to the application.
  55.        DoSomething() ' Do Something and wait.
  56.        Environment.Exit(0) ' Exit succesfully.
  57.    End Sub
  58.  
  59. #End Region
  60.  
  61. #Region " Methods "
  62.  
  63.    ''' <summary>
  64.    ''' Parses the Arguments passed to this application.
  65.    ''' </summary>
  66.    Private Sub Parse_Arguments()
  67.  
  68.        ' Arguments Are Empty?.
  69.        If Arguments_Are_Empty(Arguments) Then
  70.            PrintHelp()
  71.        End If
  72.  
  73.        ' Parse arguments.
  74.        For Each Argument As String In Arguments
  75.  
  76.            Select Case True
  77.  
  78.                Case Argument.StartsWith("/Switch1=", StringComparison.InvariantCultureIgnoreCase)
  79.                    ' Something = Argument.Substring(Argument.IndexOf("=") + 1)
  80.  
  81.            End Select
  82.  
  83.        Next Argument
  84.  
  85.        If Something Is Nothing Then
  86.            LaunchError(1, "/Switch1")
  87.        End If
  88.  
  89.    End Sub
  90.  
  91.    ''' <summary>
  92.    ''' Do something and wait.
  93.    ''' </summary>
  94.    Private Sub DoSomething()
  95.  
  96.        Do Until Something = "Something Else"
  97.            Application.DoEvents()
  98.        Loop
  99.  
  100.    End Sub
  101.  
  102. #End Region
  103.  
  104. #Region " Miscellaneous Methods "
  105.  
  106.    ''' <summary>
  107.    ''' Check if the arguments are empty.
  108.    ''' </summary>
  109.    ''' <param name="DebugArguments">Indicates a custom arguments to check.</param>
  110.    Private Function Arguments_Are_Empty(Optional ByVal DebugArguments As IEnumerable(Of String) = Nothing) As Boolean
  111.  
  112.        Return Not Convert.ToBoolean(If(DebugArguments IsNot Nothing,
  113.                                        DebugArguments.Count,
  114.                                        Environment.GetCommandLineArgs.Skip(1).Count))
  115.  
  116.    End Function
  117.  
  118.    ''' <summary>
  119.    ''' Joins the Arguments to return a single String.
  120.    ''' </summary>
  121.    ''' <param name="DebugArguments">Indicates a custom arguments to join.</param>
  122.    Private Function Join_Arguments(Optional ByVal DebugArguments As IEnumerable(Of String) = Nothing) As String
  123.  
  124.        Return String.Join(Convert.ToChar(Keys.Space),
  125.                           If(DebugArguments IsNot Nothing,
  126.                              DebugArguments,
  127.                              Environment.GetCommandLineArgs.Skip(1)))
  128.  
  129.    End Function
  130.  
  131.    ''' <summary>
  132.    ''' Writes colored text on the Console.
  133.    ''' </summary>
  134.    ''' <param name="Text">Indicates the text to write.</param>
  135.    ''' <param name="AddNewLine">Adds an empty line at the end of the text.</param>
  136.    ''' <param name="ForeColor">Indicates the text color.</param>
  137.    ''' <param name="BackColor">Indicates the background color.</param>
  138.    Private Sub Write_Colored_Text(ByVal Text As String,
  139.                                   Optional ByVal AddNewLine As Boolean = False,
  140.                                   Optional ByVal ForeColor As ConsoleColor = Nothing,
  141.                                   Optional ByVal BackColor As ConsoleColor = Nothing)
  142.  
  143.        Console.ForegroundColor = If(ForeColor = Nothing, Console.ForegroundColor, ForeColor)
  144.        Console.BackgroundColor = If(ForeColor = Nothing, Console.BackgroundColor, BackColor)
  145.  
  146.        If AddNewLine Then
  147.            Console.WriteLine(Text)
  148.        Else
  149.            Console.Write(Text)
  150.        End If
  151.  
  152.        Console.ForegroundColor = If(ForeColor = Nothing, Console.ForegroundColor, ForeColor)
  153.        Console.BackgroundColor = If(ForeColor = Nothing, Console.BackgroundColor, BackColor)
  154.  
  155.    End Sub
  156.  
  157.    ''' <summary>
  158.    ''' Set the window state of the console.
  159.    ''' </summary>
  160.    ''' <param name="WindowState">Indicates the new state of the console window.</param>
  161.    Public Function SetWindow(ByVal WindowState As ConsoleWindowState.WindowState) As Boolean
  162.        Return ConsoleWindowState.SetWindowState(WindowState)
  163.    End Function
  164.  
  165.    ''' <summary>
  166.    ''' Print the Help section and exits from the application.
  167.    ''' </summary>
  168.    Private Sub PrintHelp()
  169.        Console.WriteLine(HelpSection.Help)
  170.        Environment.Exit(0) ' Exit succesfully.
  171.    End Sub
  172.  
  173.    ''' <summary>
  174.    ''' Launch a known error and exits from the application.
  175.    ''' </summary>
  176.    ''' <param name="ErrorID">
  177.    ''' Indicates the known Error Identifier.
  178.    ''' This value is also used to specify the ExitCode.
  179.    ''' </param>
  180.    ''' <param name="MoreInfo">Indicates additional information.</param>
  181.    Private Sub LaunchError(ByVal ErrorID As Integer, Optional ByVal MoreInfo As String = Nothing)
  182.  
  183.        Console.WriteLine()
  184.        Write_Colored_Text(KnownErrors(ErrorID) &
  185.                           If(MoreInfo IsNot Nothing, ": " & MoreInfo, Nothing),
  186.                           True, ConsoleColor.White, ConsoleColor.DarkRed)
  187.  
  188.        Environment.Exit(ErrorID) ' Exit with error exitcode.
  189.  
  190.    End Sub
  191.  
  192. #End Region
  193.  
  194. #Region " Event Handlers "
  195.  
  196.    ' Add here your EventHandlers.
  197.  
  198. #End Region
  199.  
  200. End Module

Saludos.


« Última modificación: 5 Diciembre 2013, 19:30 pm por EleKtro H@cker » 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