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

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  un programa que quiero hacer, que cuando se ejecute puedas poner opciones
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: un programa que quiero hacer, que cuando se ejecute puedas poner opciones  (Leído 3,456 veces)
Sentex

Desconectado Desconectado

Mensajes: 87


Programador


Ver Perfil WWW
un programa que quiero hacer, que cuando se ejecute puedas poner opciones
« en: 30 Julio 2017, 01:45 am »

Hola!

Necesito ayuda en un programa que quiero hacer.
Necesito que el programa sea en vb o C# pero en aplicacion de consola.
Pero no se hacer que cuando se ejecute puedas poner opciones.

Ejemplo test.exe -ftp ftp.server.com -p hola123 -u user

Algo asi se podria hacer?


· Los titulos deben ser descriptivos
>aquí las reglas del foro
-Engel Lex


« Última modificación: 30 Julio 2017, 01:57 am por engel lex » En línea

Preguntas o peticiones en twitter o discord:

Discord: MrSentex#1227
Twitter: @fbi_sentex
engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Ayuda
« Respuesta #1 en: 30 Julio 2017, 01:56 am »

si, se puede hacer en cualquier lenguaje, pero primero tienes que aprender a programar lo basico en el

esto se llaman argumentos argumentos por linea de comandos


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
Sentex

Desconectado Desconectado

Mensajes: 87


Programador


Ver Perfil WWW
Re: un programa que quiero hacer, que cuando se ejecute puedas poner opciones
« Respuesta #2 en: 30 Julio 2017, 02:06 am »

Se lo basico.
En línea

Preguntas o peticiones en twitter o discord:

Discord: MrSentex#1227
Twitter: @fbi_sentex
PalitroqueZ


Desconectado Desconectado

Mensajes: 948



Ver Perfil
Re: un programa que quiero hacer, que cuando se ejecute puedas poner opciones
« Respuesta #3 en: 30 Julio 2017, 02:27 am »

en POO la función huerfana permite capturar argumentos externos.

En línea

"La Economía planificada lleva de un modo gradual pero seguro a la economía dirigida, a la economía autoritaria y al totalitarismo" Ludwig Erhard
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: un programa que quiero hacer, que cuando se ejecute puedas poner opciones
« Respuesta #4 en: 31 Julio 2017, 05:54 am »

Aquí tienes todo lo que necesitas saber:
( revisa las distintas secciones de la guía, en el panel lateral izquierdo de la página. )



El siguiente código lo puedes usar tal cual, o si lo prefieres tomarlo como un simple ejemplo que estudiar. Todo este código es un extracto reducido de mi framework comercial ElektroKit para .NET Framework, que si a alguien le interesa lo puede encontrar en mi firma de usuario...

Mediante la clase CommandLineParameter se pueden representar parámetros sin valor ( ej. /Command1 ), mediante la clase CommandLineValueParameter(Of T) parámetros con valor ( ej. /Path="C:\Directory\" ). Mediante la clase CommandLineParameterCollection una coleccion de CommandLineParameter, y por último, mediante la clase CommandLineValueParameterCollection una coleccion de CommandLineValueParameter(Of T).

Como puedas usar esas clases, es algo que depende de las necesidades de cada programador.

Hay tres tipos de prefijos que puedes usar al asignar el nombre del parámetro: /Nombre \Nombre y -Nombre
Y dos tipos de sufijos o separadores disponibles para los parámetros con valor: /Nombre:Valor y /Nombre=Valor

(Sí, la sintaxis está enfocada al modo de empleo de argumentos command-line en el sistema de Microsoft Windows. )

Si por cualquier motivo no gusta o no entiendes como utilizar mi implementación, entonces puedes buscar otras en Google (que hay bastantes implementaciones en C# y VB.NET para representar argumentos command-line, la verdad).

En fin, aquí tienes el código:

Código
  1. ''' <summary>
  2. ''' Specifies the prefix character that indicates the start of the parameter's name of a <see cref="CommandLineParameter"/>
  3. ''' </summary>
  4. Public Enum CommandLineParameterPrefix As Integer
  5.  
  6.    ''' <summary>
  7.    ''' The dash character "-"
  8.    ''' <para></para>
  9.    ''' For example: "-ParameterName"
  10.    ''' </summary>
  11.    Dash = 0
  12.  
  13.    ''' <summary>
  14.    ''' The slash character "/"
  15.    ''' <para></para>
  16.    ''' For example: "/ParameterName"
  17.    ''' </summary>
  18.    Slash = 1
  19.  
  20.    ''' <summary>
  21.    ''' The slash character "\"
  22.    ''' <para></para>
  23.    ''' For example: "\ParameterName"
  24.    ''' </summary>
  25.    BackSlash = 2
  26.  
  27. End Enum
  28.  
  29. ''' <summary>
  30. ''' Specifies the suffix character that delimits the parameter's name from the parameter's value of a <see cref="CommandLineParameter"/>
  31. ''' </summary>
  32. Public Enum CommandLineParameterSuffix As Integer
  33.  
  34.    ''' <summary>
  35.    ''' The equals sign character "="
  36.    ''' <para></para>
  37.    ''' For example: "/ParameterName=Value"
  38.    ''' </summary>
  39.    EqualsSign = 0
  40.  
  41.    ''' <summary>
  42.    ''' The colon character ":"
  43.    ''' <para></para>
  44.    ''' For example: "/ParameterName:Value"
  45.    ''' </summary>
  46.    Colon = 1
  47.  
  48. End Enum

CommandLineParameter.vb
Código
  1. #Region " Command-Line Parameter "
  2.  
  3.    ''' <summary>
  4.    ''' Represents a command-line parameter that does not takes any value.
  5.    ''' </summary>
  6.    Public Class CommandLineParameter
  7.  
  8. #Region " Properties "
  9.  
  10.        ''' <summary>
  11.        ''' Gets or sets the prefix character that indicates the start of the parameter's name.
  12.        ''' <para></para>
  13.        ''' For example: "/ParameterName" where "/" is the prefix.
  14.        ''' </summary>
  15.        Public Property Prefix As CommandLineParameterPrefix = CommandLineParameterPrefix.Slash
  16.  
  17.        ''' <summary>
  18.        ''' Gets the name of the parameter.
  19.        ''' </summary>
  20.        Public ReadOnly Property Name As String
  21.            Get
  22.                Return Me.nameB
  23.            End Get
  24.        End Property
  25.        Private nameB As String
  26.  
  27.        ''' <summary>
  28.        ''' Gets or sets the short name of the parameter.
  29.        ''' <para></para>
  30.        ''' A short name should be an abbreviated name of the parameter. A short name is optional and can de null.
  31.        ''' </summary>
  32.        Public Property ShortName As String
  33.            Get
  34.                Return shortNameB
  35.            End Get
  36.            <DebuggerStepThrough>
  37.            Set(ByVal value As String)
  38.                Me.TrySetShortName(value)
  39.            End Set
  40.        End Property
  41.        Private shortNameB As String
  42.  
  43.        ''' <summary>
  44.        ''' Gets the full name of the parameter including the prefix.
  45.        ''' <para></para>
  46.        ''' For Example: "/ParameterName"
  47.        ''' </summary>
  48.        Public ReadOnly Property FullName As String
  49.            Get
  50.                Return Me.ToString()
  51.            End Get
  52.        End Property
  53.  
  54.        ''' <summary>
  55.        ''' Gets the full short name of the parameter including the prefix.
  56.        ''' <para></para>
  57.        ''' For Example: "/ParameterShortName"
  58.        ''' </summary>
  59.        Public ReadOnly Property FullShortName As String
  60.            Get
  61.                If Not String.IsNullOrEmpty(Me.shortNameB) Then
  62.                    Return String.Format("{0}{1}", Me.GetPrefixChar(), Me.shortNameB)
  63.  
  64.                Else
  65.                    Return Me.ToString()
  66.  
  67.                End If
  68.            End Get
  69.        End Property
  70.  
  71.        ''' <summary>
  72.        ''' Gets or sets a value indicating whether this parameter is required for the application.
  73.        ''' <para></para>
  74.        ''' A value of <see langword="False"/> means the user needs to pass this parameter to the application.
  75.        ''' <para></para>
  76.        ''' A value of <see langword="True"/> means this is an optional parameter so no matter if the user pass this parameter to the application.
  77.        ''' </summary>
  78.        Public Property IsOptional As Boolean
  79.  
  80. #End Region
  81.  
  82. #Region " Constructors "
  83.  
  84.        ''' <summary>
  85.        ''' Prevents a default instance of the <see cref="CommandLineParameter"/> class from being created.
  86.        ''' </summary>
  87.        Private Sub New()
  88.        End Sub
  89.  
  90.        ''' <summary>
  91.        ''' Initializes a new instance of the <see cref="CommandLineParameter" /> class.
  92.        ''' </summary>
  93.        ''' <param name="name">
  94.        ''' The name of the parameter.
  95.        ''' </param>
  96.        Public Sub New(ByVal name As String)
  97.            If String.IsNullOrWhiteSpace(name) Then
  98.                Throw New ArgumentNullException()
  99.            End If
  100.  
  101.            Me.TrySetName(name)
  102.        End Sub
  103.  
  104. #End Region
  105.  
  106. #Region " Public Methods "
  107.  
  108.        ''' <summary>
  109.        ''' Returns a <see cref="String"/> that represents this <see cref="CommandLineParameter"/>.
  110.        ''' </summary>
  111.        Public Overloads Function ToString() As String
  112.            Return String.Format("{0}{1}", Me.GetPrefixChar(), Me.nameB)
  113.        End Function
  114.  
  115.        ''' <summary>
  116.        ''' Gets the prefix character that indicates the start of the parameter's name.
  117.        ''' <para></para>
  118.        ''' For Example: "/"
  119.        ''' </summary>
  120.        Public Function GetPrefixChar() As Char
  121.            Select Case Me.Prefix
  122.                Case CommandLineParameterPrefix.Dash
  123.                    Return "-"c
  124.                Case CommandLineParameterPrefix.Slash
  125.                    Return "/"c
  126.                Case CommandLineParameterPrefix.BackSlash
  127.                    Return "\"c
  128.                Case Else
  129.                    Throw New InvalidEnumArgumentException()
  130.            End Select
  131.        End Function
  132.  
  133. #End Region
  134.  
  135. #Region " Private Methods "
  136.  
  137.        ''' <summary>
  138.        ''' Evaluates an attempt to assign the parameter name.
  139.        ''' </summary>
  140.        <DebuggerStepThrough>
  141.        Protected Overridable Sub TrySetName(ByVal name As String)
  142.  
  143.            For Each c As Char In name
  144.                If Not Char.IsLetterOrDigit(c) Then
  145.                    Throw New ArgumentException(message:="The name of the parameter only can contain letters and digits.",
  146.                                                paramName:="name")
  147.                End If
  148.            Next c
  149.  
  150.            Me.nameB = name
  151.  
  152.        End Sub
  153.  
  154.        ''' <summary>
  155.        ''' Evaluates an attempt to assign the short name of the parameter.
  156.        ''' </summary>
  157.        <DebuggerStepThrough>
  158.        Protected Overridable Sub TrySetShortName(ByVal shortName As String)
  159.  
  160.            If Not String.IsNullOrEmpty(shortName) Then
  161.  
  162.                For Each c As Char In shortName
  163.                    If Not Char.IsLetterOrDigit(c) Then
  164.                        Throw New ArgumentException(message:="The short name of the parameter only can contain letters and digits.",
  165.                                                    paramName:="shortName")
  166.                    End If
  167.                Next c
  168.  
  169.                If (shortName.Equals(Me.nameB, StringComparison.OrdinalIgnoreCase)) Then
  170.                    Throw New ArgumentException(message:="The short name of the parameter cannot be equals than the parameter's name.",
  171.                                                paramName:="shortName")
  172.                End If
  173.  
  174.            End If
  175.  
  176.            Me.shortNameB = shortName
  177.  
  178.        End Sub
  179.  
  180. #End Region
  181.  
  182.    End Class
  183.  
  184. #End Region

CommandLineValueParameter(Of T As IConvertible).vb
Código
  1. #Region " Command-Line Value Parameter (Of T) "
  2.  
  3.    ''' <summary>
  4.    ''' Represents a command-line parameter that takes a value of specific <see cref="Type"/>.
  5.    ''' </summary>
  6.    Public Class CommandLineValueParameter(Of T As IConvertible) : Inherits CommandLineParameter
  7.  
  8. #Region " Properties "
  9.  
  10.        ''' <summary>
  11.        ''' Gets or sets the suffix character that delimits the parameter's name from the parameter's value.
  12.        ''' <para></para>
  13.        ''' For example: "/ParameterName=Value" where "/" is the prefix and "=" the suffix.
  14.        ''' </summary>
  15.        Public Property Suffix As CommandLineParameterSuffix = CommandLineParameterSuffix.EqualsSign
  16.  
  17.        ''' <summary>
  18.        ''' Gets or sets the parameter's value defined by the end-user.
  19.        ''' <para></para>
  20.        ''' This value should be initially <see langword="Nothing"/> before parsing the commandline arguments of the application.
  21.        ''' <para></para>
  22.        ''' The value of the parameter should be assigned by the end-user when passing an argument to the application.
  23.        ''' <para></para>
  24.        ''' To set a default value for this parameter, use <see cref="CommandLineValueParameter(Of T).DefaultValue"/> property instead.
  25.        ''' </summary>
  26.        Public Property Value As T
  27.  
  28.        ''' <summary>
  29.        ''' Gets or sets the default parameter's value.
  30.        ''' <para></para>
  31.        ''' This value should be take into account if, after parsing the command-line arguments of the application,
  32.        ''' <see cref="CommandLineValueParameter(Of T).Value"/> is <see langword="Nothing"/>,
  33.        ''' meaning that the end-user did not assigned any value to this parameter.
  34.        ''' </summary>
  35.        Public Property DefaultValue As T
  36.  
  37. #End Region
  38.  
  39. #Region " Constructors "
  40.  
  41.        ''' <summary>
  42.        ''' Initializes a new instance of the <see cref="CommandLineValueParameter(Of T)" /> class.
  43.        ''' </summary>
  44.        ''' <param name="name">
  45.        ''' The name of the parameter.
  46.        ''' </param>
  47.        Public Sub New(ByVal name As String)
  48.            MyBase.New(name)
  49.        End Sub
  50.  
  51. #End Region
  52.  
  53. #Region " Public Methods "
  54.  
  55.        ''' <summary>
  56.        ''' Returns a <see cref="String"/> that represents this <see cref="CommandLineValueParameter(Of T)"/>.
  57.        ''' </summary>
  58.        Public Overloads Function ToString() As String
  59.            Return String.Format("{0}{1}""{2}""", MyBase.ToString(), Me.GetSuffixChar(),
  60.                                                  If(Me.Value IsNot Nothing, Me.Value.ToString(Nothing), Me.DefaultValue.ToString(Nothing)))
  61.        End Function
  62.  
  63.        ''' <summary>
  64.        ''' Gets the suffix character that delimits the parameter's name from the parameter's value.
  65.        ''' <para></para>
  66.        ''' For Example: "="
  67.        ''' </summary>
  68.        Public Function GetSuffixChar() As Char
  69.            Select Case Me.Suffix
  70.                Case CommandLineParameterSuffix.Colon
  71.                    Return ":"c
  72.                Case CommandLineParameterSuffix.EqualsSign
  73.                    Return "="c
  74.                Case Else
  75.                    Throw New InvalidEnumArgumentException()
  76.            End Select
  77.        End Function
  78.  
  79. #End Region
  80.  
  81. #Region " Operator Conversion "
  82.  
  83.        ''' <summary>
  84.        ''' Performs an implicit conversion from <see cref="CommandLineValueParameter(Of IConvertible)"/> to <see cref="CommandLineValueParameter(Of T)"/>.
  85.        ''' </summary>
  86.        <DebuggerStepThrough>
  87.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of IConvertible)) As CommandLineValueParameter(Of T)
  88.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of IConvertible)(cmd)
  89.        End Operator
  90.  
  91.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of String)) As CommandLineValueParameter(Of T)
  92.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of String)(cmd)
  93.        End Operator
  94.  
  95.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Char)) As CommandLineValueParameter(Of T)
  96.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Char)(cmd)
  97.        End Operator
  98.  
  99.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Boolean)) As CommandLineValueParameter(Of T)
  100.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Boolean)(cmd)
  101.        End Operator
  102.  
  103.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Date)) As CommandLineValueParameter(Of T)
  104.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Date)(cmd)
  105.        End Operator
  106.  
  107.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Byte)) As CommandLineValueParameter(Of T)
  108.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Byte)(cmd)
  109.        End Operator
  110.  
  111.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of SByte)) As CommandLineValueParameter(Of T)
  112.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of SByte)(cmd)
  113.        End Operator
  114.  
  115.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Short)) As CommandLineValueParameter(Of T)
  116.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Short)(cmd)
  117.        End Operator
  118.  
  119.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of UShort)) As CommandLineValueParameter(Of T)
  120.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of UShort)(cmd)
  121.        End Operator
  122.  
  123.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Integer)) As CommandLineValueParameter(Of T)
  124.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Integer)(cmd)
  125.        End Operator
  126.  
  127.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of UInteger)) As CommandLineValueParameter(Of T)
  128.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of UInteger)(cmd)
  129.        End Operator
  130.  
  131.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Long)) As CommandLineValueParameter(Of T)
  132.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Long)(cmd)
  133.        End Operator
  134.  
  135.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of ULong)) As CommandLineValueParameter(Of T)
  136.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of ULong)(cmd)
  137.        End Operator
  138.  
  139.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Single)) As CommandLineValueParameter(Of T)
  140.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Single)(cmd)
  141.        End Operator
  142.  
  143.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Double)) As CommandLineValueParameter(Of T)
  144.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Double)(cmd)
  145.        End Operator
  146.  
  147.        Public Shared Widening Operator CType(ByVal cmd As CommandLineValueParameter(Of Decimal)) As CommandLineValueParameter(Of T)
  148.            Return CommandLineValueParameter(Of T).ConvertCommandLineValueParameter(Of Decimal)(cmd)
  149.        End Operator
  150.  
  151. #End Region
  152.  
  153. #Region " Private Methods "
  154.  
  155.        ''' <summary>
  156.        ''' Converts a <see cref="CommandLineValueParameter(Of IConvertible)"/> to <see cref="CommandLineValueParameter(Of T)"/>.
  157.        ''' </summary>
  158.        Private Shared Function ConvertCommandLineValueParameter(Of I As IConvertible)(ByVal cmd As CommandLineValueParameter(Of I)) As CommandLineValueParameter(Of T)
  159.            Return New CommandLineValueParameter(Of T)(cmd.Name) With
  160.                   {
  161.                        .Prefix = cmd.Prefix,
  162.                        .Suffix = cmd.Suffix,
  163.                        .ShortName = cmd.ShortName,
  164.                        .DefaultValue = DirectCast(CObj(cmd.DefaultValue), T),
  165.                        .Value = DirectCast(CObj(cmd.Value), T),
  166.                        .IsOptional = cmd.IsOptional
  167.                    }
  168.        End Function
  169.  
  170. #End Region
  171.  
  172.    End Class
  173.  
  174. #End Region

CommandLineParameterCollection.vb
Código
  1. #Region " CommandLineParameter Collection "
  2.  
  3.    ''' <summary>
  4.    ''' Represents a strongly typed list of <see cref="CommandLineParameter"/> that can be accessed by an index.
  5.    ''' </summary>
  6.    <Serializable>
  7.    <XmlRoot("Items")>
  8.    <DebuggerDisplay("Count = {Count}")>
  9.    <DefaultMember("Item")>
  10.    Public Class CommandLineParameterCollection : Inherits Collection(Of CommandLineParameter)
  11.  
  12. #Region " Constructors "
  13.        Public Sub New()
  14.        End Sub
  15. #End Region
  16.  
  17. #Region " Indexers "
  18.  
  19.        ''' <summary>
  20.        ''' Gets or sets the <see cref="CommandLineParameter"/> that matches the specified key name.
  21.        ''' </summary>
  22.        ''' <param name="paramName">
  23.        ''' The parameter name.
  24.        ''' </param>
  25.        Default Public Overloads Property Item(ByVal paramName As String) As CommandLineParameter
  26.            <DebuggerStepThrough>
  27.            Get
  28.                Return Me.Find(paramName)
  29.            End Get
  30.            <DebuggerStepThrough>
  31.            Set(ByVal value As CommandLineParameter)
  32.                Me(Me.IndexOf(paramName)) = value
  33.            End Set
  34.        End Property
  35.  
  36. #End Region
  37.  
  38. #Region " Public Methods "
  39.  
  40.        ''' <summary>
  41.        ''' Adds a <see cref="CommandLineParameter"/> to the end of the <see cref="CommandLineParameterCollection"/>.
  42.        ''' </summary>
  43.        <DebuggerStepThrough>
  44.        Public Shadows Sub Add(ByVal param As CommandLineParameter)
  45.            If Me.Contains(param.Name) OrElse Me.Contains(param.ShortName) Then
  46.                Throw New ArgumentException(message:="Parameter already exists.", paramName:="refParam")
  47.            Else
  48.                MyBase.Add(param)
  49.            End If
  50.        End Sub
  51.  
  52.        ''' <summary>
  53.        ''' Adds the specified parameters to the end of the <see cref="CommandLineParameterCollection"/>.
  54.        ''' </summary>
  55.        <DebuggerStepThrough>
  56.        Public Shadows Sub AddRange(ByVal params As CommandLineParameter())
  57.            For Each param As CommandLineParameter In params
  58.                Me.Add(param)
  59.            Next param
  60.        End Sub
  61.  
  62.        Public Shadows Sub Remove(ByVal param As CommandLineParameter)
  63.            Dim indexOf As Integer = Me.IndexOf(param)
  64.            If (indexOf = -1) Then
  65.                Throw New ArgumentException(message:="Parameter doesn't exists.", paramName:="param")
  66.            Else
  67.                MyBase.RemoveAt(indexOf)
  68.            End If
  69.        End Sub
  70.  
  71.        Public Shadows Sub Remove(ByVal name As String)
  72.            Dim indexOf As Integer = Me.IndexOf(name)
  73.            If (indexOf = -1) Then
  74.                Throw New ArgumentException(message:="Parameter doesn't exists.", paramName:="name")
  75.            Else
  76.                MyBase.RemoveAt(indexOf)
  77.            End If
  78.        End Sub
  79.  
  80.        ''' <summary>
  81.        ''' Determines whether the <see cref="CommandLineParameterCollection"/> contains a <see cref="CommandLineParameter"/> that
  82.        ''' matches the specified key name.
  83.        ''' </summary>
  84.        ''' <returns>
  85.        ''' <see langword="True"/> if the <see cref="CommandLineParameterCollection"/> contains the <see cref="CommandLineParameter"/>,
  86.        ''' <see langword="False"/> otherwise.
  87.        ''' </returns>
  88.        <DebuggerStepThrough>
  89.        Public Overloads Function Contains(ByVal name As String) As Boolean
  90.            Return (From param As CommandLineParameter In MyBase.Items
  91.                    Where param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  92.                          param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase)).Any
  93.        End Function
  94.  
  95.        ''' <summary>
  96.        ''' Searches for an <see cref="CommandLineParameter"/> that matches the specified parameter name,
  97.        ''' and returns the first occurrence within the entire <see cref="CommandLineParameterCollection"/>.
  98.        ''' </summary>
  99.        <DebuggerStepThrough>
  100.        Public Overloads Function Find(ByVal name As String) As CommandLineParameter
  101.            Return (From param As CommandLineParameter In MyBase.Items
  102.                    Where param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  103.                          param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase)).
  104.                    DefaultIfEmpty(Nothing).
  105.                    SingleOrDefault()
  106.        End Function
  107.  
  108.        ''' <summary>
  109.        ''' Searches for an <see cref="CommandLineParameter"/> that matches the specified key name and
  110.        ''' returns the zero-based index of the first occurrence within the entire <see cref="CommandLineParameterCollection"/>.
  111.        ''' </summary>
  112.        ''' <returns>
  113.        ''' The zero-based index of the first occurrence of <see cref="CommandLineParameter"/> within the entire <see cref="CommandLineParameterCollection"/>, if found;
  114.        ''' otherwise, <c>–1</c>.
  115.        ''' </returns>
  116.        <DebuggerStepThrough>
  117.        Public Overloads Function IndexOf(ByVal name As String) As Integer
  118.  
  119.            Dim index As Integer = 0
  120.            Dim found As Boolean = False
  121.  
  122.            For Each param As CommandLineParameter In Me.Items
  123.  
  124.                If param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  125.                   param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase) Then
  126.                    found = True
  127.                    Exit For
  128.                End If
  129.  
  130.                index += 1
  131.  
  132.            Next param
  133.  
  134.            If (found) Then
  135.                Return index
  136.  
  137.            Else
  138.                Return -1
  139.  
  140.            End If
  141.  
  142.        End Function
  143.  
  144. #End Region
  145.  
  146.    End Class
  147.  
  148. #End Region

CommandLineValueParameterCollection.vb
Código
  1. #Region " CommandLineValueParameter Collection "
  2.  
  3.    ''' <summary>
  4.    ''' Represents a strongly typed list of <see cref="CommandLineValueParameter"/> that can be accessed by an index.
  5.    ''' </summary>
  6.    <Serializable>
  7.    <XmlRoot("Items")>
  8.    <DebuggerDisplay("Count = {Count}")>
  9.    <DefaultMember("Item")>
  10.    Public Class CommandLineValueParameterCollection : Inherits Collection(Of CommandLineValueParameter(Of IConvertible))
  11.  
  12. #Region " Constructors "
  13.  
  14.        Public Sub New()
  15.        End Sub
  16.  
  17. #End Region
  18.  
  19. #Region " Indexers "
  20.  
  21.        ''' <summary>
  22.        ''' Gets or sets the <see cref="CommandLineValueParameter"/> that matches the specified key name.
  23.        ''' </summary>
  24.        ''' <param name="name">
  25.        ''' The parameter name.
  26.        ''' </param>
  27.        Default Public Overloads Property Item(ByVal name As String) As CommandLineValueParameter(Of IConvertible)
  28.            <DebuggerStepThrough>
  29.            Get
  30.                Dim result As CommandLineValueParameter(Of IConvertible) = Me.Find(name)
  31.                If (result Is Nothing) Then
  32.                    Throw New NullReferenceException(message:="Item not found with the specified name.")
  33.                End If
  34.                Return result
  35.            End Get
  36.            <DebuggerStepThrough>
  37.            Set(ByVal value As CommandLineValueParameter(Of IConvertible))
  38.                Me(Me.IndexOf(name)) = value
  39.            End Set
  40.        End Property
  41.  
  42. #End Region
  43.  
  44. #Region " Public Methods "
  45.  
  46.        Public Shadows Sub Add(ByVal param As CommandLineValueParameter(Of IConvertible))
  47.  
  48.            If Me.Contains(param.Name) OrElse Me.Contains(param.ShortName) Then
  49.                Throw New ArgumentException(message:="Parameter already exists.", paramName:="param")
  50.  
  51.            Else
  52.                MyBase.Add(refParam)
  53.  
  54.            End If
  55.  
  56.        End Sub
  57.  
  58.        Public Shadows Sub AddRange(ByVal params As CommandLineValueParameter(Of IConvertible)())
  59.  
  60.            For Each param As CommandLineValueParameter(Of IConvertible) In params
  61.                Me.Add(param)
  62.            Next param
  63.  
  64.        End Sub
  65.  
  66.        Public Shadows Sub Remove(ByVal param As CommandLineValueParameter(Of IConvertible))
  67.  
  68.            Dim indexOf As Integer = Me.IndexOf(param)
  69.  
  70.            If (indexOf = -1) Then
  71.                Throw New ArgumentException(message:="Parameter doesn't exists.", paramName:="param")
  72.  
  73.            Else
  74.                MyBase.RemoveAt(indexOf)
  75.  
  76.            End If
  77.  
  78.        End Sub
  79.  
  80.        Public Shadows Sub Remove(ByVal name As String)
  81.            Dim indexOf As Integer = Me.IndexOf(name)
  82.            If (indexOf = -1) Then
  83.                Throw New ArgumentException(message:="Parameter doesn't exists.", paramName:="name")
  84.            Else
  85.                MyBase.RemoveAt(indexOf)
  86.            End If
  87.        End Sub
  88.  
  89.        ''' <summary>
  90.        ''' Determines whether the <see cref="CommandLineValueParameterCollection"/> contains a <see cref="CommandLineValueParameter"/> that
  91.        ''' matches the specified key name.
  92.        ''' </summary>
  93.        ''' <returns>
  94.        ''' <see langword="True"/> if the <see cref="CommandLineValueParameterCollection"/> contains the <see cref="CommandLineValueParameter"/>,
  95.        ''' <see langword="False"/> otherwise.
  96.        ''' </returns>
  97.        <DebuggerStepThrough>
  98.        Public Overloads Function Contains(ByVal name As String) As Boolean
  99.            Return (From param As CommandLineValueParameter(Of IConvertible) In MyBase.Items
  100.                    Where param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  101.                          param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase)).Any
  102.        End Function
  103.  
  104.        ''' <summary>
  105.        ''' Searches for an <see cref="CommandLineValueParameter"/> that matches the specified parameter name,
  106.        ''' and returns the first occurrence within the entire <see cref="CommandLineValueParameterCollection"/>.
  107.        ''' </summary>
  108.        <DebuggerStepThrough>
  109.        Public Overloads Function Find(ByVal name As String) As CommandLineValueParameter(Of IConvertible)
  110.            Return (From param As CommandLineValueParameter(Of IConvertible) In MyBase.Items
  111.                    Where param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  112.                          param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase)).
  113.                    DefaultIfEmpty(Nothing).
  114.                    SingleOrDefault()
  115.        End Function
  116.  
  117.        ''' <summary>
  118.        ''' Searches for an <see cref="CommandLineValueParameter"/> that matches the specified key name and
  119.        ''' returns the zero-based index of the first occurrence within the entire <see cref="CommandLineValueParameterCollection"/>.
  120.        ''' </summary>
  121.        ''' <returns>
  122.        ''' The zero-based index of the first occurrence of <see cref="CommandLineValueParameter"/> within the entire <see cref="CommandLineValueParameterCollection"/>, if found;
  123.        ''' otherwise, <c>–1</c>.
  124.        ''' </returns>
  125.        <DebuggerStepThrough>
  126.        Public Overloads Function IndexOf(ByVal name As String) As Integer
  127.            Dim index As Integer = 0
  128.            Dim found As Boolean = False
  129.  
  130.            For Each param As CommandLineValueParameter(Of IConvertible) In Me.Items
  131.  
  132.                If param.Name.Equals(name, StringComparison.OrdinalIgnoreCase) OrElse
  133.                   param.ShortName.Equals(name, StringComparison.OrdinalIgnoreCase) Then
  134.                    found = True
  135.                    Exit For
  136.                End If
  137.  
  138.                index += 1
  139.  
  140.            Next param
  141.  
  142.            If (found) Then
  143.                Return index
  144.  
  145.            Else
  146.                Return -1
  147.  
  148.            End If
  149.        End Function
  150.  
  151. #End Region
  152.  
  153.    End Class
  154.  
  155. #End Region



Un ejemplo de uso:
Código
  1. Module Module1
  2.  
  3.    Dim params As New CommandLineValueParameterCollection From {
  4.        New CommandLineValueParameter(Of String)("ParameterName1") With {
  5.            .Prefix = CommandLineParameterPrefix.Slash,
  6.            .Suffix = CommandLineParameterSuffix.EqualsSign,
  7.            .ShortName = "Param1",
  8.            .DefaultValue = "",
  9.            .IsOptional = False
  10.        },
  11.        New CommandLineValueParameter(Of Boolean)("ParameterName2") With {
  12.            .Prefix = CommandLineParameterPrefix.Slash,
  13.            .Suffix = CommandLineParameterSuffix.EqualsSign,
  14.            .ShortName = "Param2",
  15.            .DefaultValue = False,
  16.            .IsOptional = True
  17.        },
  18.        New CommandLineValueParameter(Of Integer)("ParameterName3") With {
  19.            .Prefix = CommandLineParameterPrefix.Slash,
  20.            .Suffix = CommandLineParameterSuffix.EqualsSign,
  21.            .ShortName = "Param3",
  22.            .DefaultValue = -1I,
  23.            .IsOptional = True
  24.        }
  25.    }
  26.  
  27.    Public Function IsParameterAssignedInArgument(Of T As IConvertible)(ByVal parameter As CommandLineValueParameter(Of T), ByVal argument As String) As Boolean
  28.        Return (argument.StartsWith(parameter.FullName & parameter.GetSuffixChar(), StringComparison.OrdinalIgnoreCase) OrElse
  29.                argument.StartsWith(parameter.FullShortName & parameter.GetSuffixChar(), StringComparison.OrdinalIgnoreCase))
  30.    End Function
  31.  
  32.    Public Sub SetParameterValue(Of T As IConvertible)(ByRef parameter As CommandLineValueParameter(Of T), ByVal argument As String)
  33.  
  34.        If IsParameterAssignedInArgument(parameter, argument) Then
  35.  
  36.            Dim value As String = argument.Substring(argument.IndexOf(parameter.GetSuffixChar()) + 1).Trim({ControlChars.Quote})
  37.  
  38.            If String.IsNullOrEmpty(value) Then
  39.                parameter.Value = parameter.DefaultValue
  40.  
  41.            Else
  42.                Try
  43.                    parameter.Value = DirectCast(Convert.ChangeType(value, parameter.DefaultValue.GetType()), T)
  44.  
  45.                Catch ex As InvalidCastException
  46.                    Throw
  47.  
  48.                Catch ex As FormatException
  49.                    Throw
  50.  
  51.                End Try
  52.  
  53.            End If
  54.  
  55.        End If
  56.  
  57.    End Sub
  58.  
  59.    Sub Main()
  60.  
  61.        ' Parse command-line arguments to set the values of the parameters.
  62.        ParseArguments(params, AddressOf OnSyntaxError, AddressOf OnMissingParameterRequired)
  63.  
  64.        ' Display the parameters and each value assigned.
  65.        For Each param As CommandLineValueParameter(Of IConvertible) In params
  66.            Console.WriteLine(param.ToString())
  67.        Next
  68.  
  69.    End Sub
  70.  
  71.    ''' <summary>
  72.    ''' Loop through all the command-line arguments of this application.
  73.    ''' </summary>
  74.    Friend Sub ParseArguments(ByVal cmds As CommandLineValueParameterCollection,
  75.                              ByVal callbackSyntaxError As Action(Of CommandLineValueParameter(Of IConvertible)),
  76.                              ByVal callbackMissingRequired As Action(Of CommandLineValueParameter(Of IConvertible)))
  77.  
  78.        ParseArguments(cmds, Environment.GetCommandLineArgs.Skip(1), callbackSyntaxError, callbackMissingRequired)
  79.  
  80.    End Sub
  81.  
  82.    Friend Sub ParseArguments(ByVal cmds As CommandLineValueParameterCollection,
  83.                              ByVal args As IEnumerable(Of String),
  84.                              ByVal callbackSyntaxError As Action(Of CommandLineValueParameter(Of IConvertible)),
  85.                              ByVal callbackMissingRequired As Action(Of CommandLineValueParameter(Of IConvertible)))
  86.  
  87.        If Not (args.Any) Then
  88.            PrintHelp()
  89.        End If
  90.  
  91.        ' Required parameters. Not optional ones.
  92.        Dim cmdRequired As List(Of CommandLineValueParameter(Of IConvertible)) =
  93.            (From cmd As CommandLineValueParameter(Of IConvertible) In cmds
  94.             Where Not cmd.IsOptional).ToList()
  95.  
  96.        For Each arg As String In args
  97.  
  98.            For Each cmd As CommandLineValueParameter(Of IConvertible) In cmds
  99.  
  100.                If arg.Equals("/?") Then
  101.                    PrintHelp()
  102.                End If
  103.  
  104.                If IsParameterAssignedInArgument(cmd, arg) Then
  105.  
  106.                    If (cmdRequired.Contains(cmd)) Then
  107.                        cmdRequired.Remove(cmd)
  108.                    End If
  109.  
  110.                    Try
  111.                        SetParameterValue(Of IConvertible)(cmd, arg)
  112.  
  113.                    Catch ex As Exception
  114.                        callbackSyntaxError.Invoke(cmd)
  115.  
  116.                    End Try
  117.  
  118.                End If
  119.  
  120.            Next cmd
  121.  
  122.        Next arg
  123.  
  124.        If (cmdRequired.Any) Then
  125.            callbackMissingRequired.Invoke(cmdRequired.First())
  126.        End If
  127.  
  128.    End Sub
  129.  
  130.    Friend Sub OnSyntaxError(ByVal cmd As CommandLineValueParameter(Of IConvertible))
  131.        Console.WriteLine(String.Format("[X] Syntax error in parameter: {0})", cmd.FullName))
  132.        Environment.Exit(exitCode:=1)
  133.    End Sub
  134.  
  135.    Friend Sub OnMissingParameterRequired(ByVal cmd As CommandLineValueParameter(Of IConvertible))
  136.        Console.WriteLine(String.Format("[X] Parameter {0} is required. ", cmd.FullName))
  137.        Environment.Exit(exitCode:=1)
  138.    End Sub
  139.  
  140.    Friend Sub PrintHelp()
  141.        Dim sb As New StringBuilder
  142.        sb.AppendLine("Commands Help:")
  143.        For Each param As CommandLineValueParameter(Of IConvertible) In params
  144.            sb.AppendFormat("{0} {{{1}}}", param.FullName, param.DefaultValue.GetType().Name)
  145.            sb.AppendLine()
  146.        Next
  147.        Console.WriteLine(sb.ToString())
  148.        Environment.Exit(exitCode:=1)
  149.    End Sub
  150.  
  151. End Module

Resultados de ejecución:

Ayuda del programa:
Código:
ConsoleApp1.exe /?
Commands Help:
/ParameterName1 {String}
/ParameterName2 {Boolean}
/ParameterName3 {Int32}

Error-handling de parametros requeridos no especificados:
Código:
ConsoleApp1.exe /param2=true  /param3=100
[X] Parameter "/ParameterName1" is required.

Error-handling de fallos en el parsing de valores:
Código:
ConsoleApp1.exe /param2=nul
[X] Syntax error in parameter: /ParameterName2 {Boolean}

Resultado de asignación de valores de cada parámetro tras un parsing exitoso de los argumentos command-line:
Código:
ConsoleApp1.exe /param1="hello world" /param2=true /param3=100
/ParameterName1="hello world"
/ParameterName2="True"
/ParameterName3="100"

PD: El código de arriba es solo un ejemplo, se puede extender para controlar nombres de parámetros que no existen y/o nombres repetidos, por ejemplo.

Saludos.
« Última modificación: 31 Julio 2017, 06:11 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