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


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Mensajes
Páginas: 1 ... 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 [530] 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 ... 1253
5291  Programación / .NET (C#, VB.NET, ASP) / Re: ¿Compronar la firma de una función P/Invoke en tiempo de ejecución? en: 17 Junio 2015, 04:02 am
Analizando bastante a fondo la TEDIOSA class MethodInfo descubrí cómo resolverlo:

Código
  1. Dim isSetLastError As Boolean =
  2.    CType(expr.Body, MethodCallExpression).Method.GetCustomAttributes(False).
  3.                                                  OfType(Of DllImportAttribute)().FirstOrDefault.SetLastError



EDITO:

Os dejo el método genérico si quereis testearlo, es simplemente el inicio de una solución todo-en-uno para ahorrar toneladas de repetición de escritura de código para llevar a cabo la misma tarea, y cómo tal puede no ser perfecto, de hecho no lo es, es imposible hacer una función de este estilo que sea "compatible" con la magnitud de funciones de la WinAPI, ya que la función GetLastError depende de la función "X" que haya sido llamada, en la que algunos casos no tiene por que devolver "0" para una salida exitosa, pero si estamos seguros del valor de retorno de las funciones que usemos entonces si que es bueno usarlo.

Código
  1.    ''' ----------------------------------------------------------------------------------------------------
  2.    ''' <remarks>
  3.    ''' Title : SafePInvoke
  4.    ''' Author: Elektro
  5.    ''' Date  : 17-June-2015
  6.    ''' </remarks>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    ''' <summary>
  9.    ''' Invokes the specified encapsulated function, trying to provide a higher safety level for error-handling.
  10.    ''' If the function that was called using platform invoke has the <see cref="DllImportAttribute.SetLastError"/>,
  11.    ''' then it checks the exit code returned by the function, and, if is not a success code, throws a <see cref="Win32Exception"/>.
  12.    ''' </summary>
  13.    ''' ----------------------------------------------------------------------------------------------------
  14.    ''' <typeparam name="T"></typeparam>
  15.    '''
  16.    ''' <param name="expr">
  17.    ''' The encapsulated function.
  18.    ''' </param>
  19.    '''
  20.    ''' <param name="refResult">
  21.    ''' The referenced result variable.
  22.    ''' </param>
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    ''' <returns>
  25.    ''' The type of the return value depends on the function definition.
  26.    ''' </returns>
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <exception cref="Win32Exception">
  29.    ''' Function 'X' thrown an unmanaged Win32 exception with error code 'X'.
  30.    ''' </exception>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    <DebuggerStepThrough>
  33.    Private Shared Function SafePInvoke(Of T)(ByVal expr As Expression(Of Func(Of T)),
  34.                                              Optional ByVal successCode As Integer = 0) As T
  35.  
  36.        Dim result As T = expr.Compile.Invoke()
  37.  
  38.        Dim method As MethodInfo =
  39.            CType(expr.Body, MethodCallExpression).Method
  40.  
  41.        Dim isSetLastError As Boolean =
  42.            method.GetCustomAttributes(inherit:=False).
  43.                   OfType(Of DllImportAttribute)().FirstOrDefault.SetLastError
  44.  
  45.        If isSetLastError Then
  46.  
  47.            Dim exitCode As Integer = Marshal.GetLastWin32Error
  48.  
  49.            If exitCode <> successCode Then
  50.                Throw New Win32Exception([error]:=exitCode,
  51.                                         message:=String.Format("Function '{0}' thrown an unmanaged Win32 exception with error code '{1}'.",
  52.                                                                method.Name, CStr(exitCode)))
  53.            End If
  54.  
  55.        End If
  56.  
  57.        Return result
  58.  
  59.    End Function
  60.  

Ejemplos de uso ...parciales:

Código
  1. Dim length As Integer = SafePInvoke(Function() NativeMethods.GetWindowTextLength(hWnd))

Código
  1. Dim sb As New StringBuilder(String.Empty, length)
  2. SafePInvoke(Function() NativeMethods.GetWindowText(hWnd, sb, sb.Capacity + 1))

Saludos!
5292  Programación / .NET (C#, VB.NET, ASP) / ¿Comprobar la firma de una función P/Invoke en tiempo de ejecución? en: 17 Junio 2015, 03:13 am
Cómo dice el título del tema, ¿alguien tiene puñetera idea de si es posible, tal vez mediante Reflection, cómo se puede comprobar los valores de los atributos de una firma de una declaración de invocación de plataforma?.

Código
  1. [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  2. private static extern int xxx();

Código
  1. <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  2. Private Shared Function xxx() As Integer
  3. End Function

Basicamente necesito comprobar el valor de SetLastError en tiempo de ejecución, para determinar si es True o es False, pero parece un misterio sin resolver.

¿Alguien sabe de alguna referencia oficial de MSDN donde expliquen este detalle tan específico?, ¿cómo obtener los metadatos del método?.

Es para mejorar la lógica de este método genérico, ya que sin poder determinar ese detalle que me falta, no sirve para nada realizar un checkeo:
Código
  1.    ''' <summary>
  2.    ''' Invokes the encapsulated function, Tthen checks the exit code returned by the function that was called using platform invoke
  3.    ''' that has the <see cref="DllImportAttribute.SetLastError"/> flag set.
  4.    ''' </summary>
  5.    ''' ----------------------------------------------------------------------------------------------------
  6.    ''' <exception cref="Win32Exception">
  7.    ''' Function 'X' thrown an unmanaged Win32 exception with error code 'X'.
  8.    ''' </exception>
  9.    ''' ----------------------------------------------------------------------------------------------------
  10.    Private Shared Sub SafePInvoke(Of T)(ByRef refResult As T, ByVal expr As expression(Of Func(Of T)))
  11.  
  12.        refResult = expr.Compile.Invoke()
  13.  
  14.        Dim exitCode As Integer = Marshal.GetLastWin32Error
  15.        If exitCode <> 0 Then
  16.            Throw New Win32Exception([error]:=exitCode, message:=String.Format("Function '{0}' thrown an unmanaged Win32 exception with error code '{1}'.",
  17.                                                                               CType(expr.Body, MethodCallExpression).Method.Name, CStr(exitCode)))
  18.        End If
  19.  
  20.    End Sub

Saludos!
5293  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets) en: 16 Junio 2015, 13:03 pm
¿Habeis sentido alguna vez la necesidad de mover una o varias filas de un DataGridView preservando el valor de algunas celdas en el transcurso?, pues yo si, así que comparto este código rehusable que me parece bastante sofisticado para llevar a cabo esa tarea, soporta multi-selección de filas, pero es para manipular directamente las filas de un DataGridViev, no el datasource.

Ejemplo de uso:
Código
  1. Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up)
Código
  1. Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up, {0, 2})

Código fuente:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-June-2015
  4. ' ***********************************************************************
  5. ' <copyright file="DataGridViewExtensions.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports System.Runtime.CompilerServices
  21. Imports System.Windows.Forms
  22.  
  23. #End Region
  24.  
  25. ''' <summary>
  26. ''' Contains two methods for moving DataRows up/down.
  27. ''' You could easily tweak the code to work for say a ListBox.
  28. ''' </summary>
  29. ''' <remarks></remarks>
  30. Public Module DataGridViewExtensions
  31.  
  32. #Region " Enumerations "
  33.  
  34.    ''' <summary>
  35.    ''' Specifies a direction to move the rows.
  36.    ''' </summary>
  37.    Public Enum DataGridViewMoveRowDirection As Integer
  38.  
  39.        ''' <summary>
  40.        ''' Move row up.
  41.        ''' </summary>
  42.        Up = 0
  43.  
  44.        ''' <summary>
  45.        ''' Move row down.
  46.        ''' </summary>
  47.        Down = 1
  48.  
  49.    End Enum
  50.  
  51. #End Region
  52.  
  53. #Region " Public Methods "
  54.  
  55.    ''' <summary>
  56.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  57.    ''' </summary>
  58.    ''' <param name="sender">The <see cref="DataGridView"/>.</param>
  59.    ''' <param name="direction">The row-move direction.</param>
  60.    <DebuggerStepThrough()>
  61.    <Extension()>
  62.    Public Sub MoveSelectedRows(ByVal sender As DataGridView,
  63.                                ByVal direction As DataGridViewMoveRowDirection)
  64.  
  65.        DoRowsMove(sender, direction)
  66.  
  67.    End Sub
  68.  
  69.    ''' <summary>
  70.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  71.    ''' </summary>
  72.    ''' <param name="sender">The <see cref="DataGridView"/>.</param>
  73.    ''' <param name="direction">The row-move direction.</param>
  74.    ''' <param name="preserveCellsIndex">A sequence of cell indexes to preserve its cell values when moving the row(s).</param>
  75.    <DebuggerStepThrough()>
  76.    <Extension()>
  77.    Public Sub MoveSelectedRows(ByVal sender As DataGridView,
  78.                                ByVal direction As DataGridViewMoveRowDirection,
  79.                                ByVal preserveCellsIndex As IEnumerable(Of Integer))
  80.  
  81.        DoRowsMove(sender, direction, preserveCellsIndex)
  82.  
  83.    End Sub
  84.  
  85. #End Region
  86.  
  87. #Region " Private Methods "
  88.  
  89.    ''' <summary>
  90.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  91.    ''' </summary>
  92.    ''' <param name="dgv">The <see cref="DataGridView"/>.</param>
  93.    ''' <param name="direction">The row-move direction.</param>
  94.    ''' <param name="preserveCellsIndex">Optionally, a sequence of cell indexes to preserve its cell values when moving the row(s).</param>
  95.    <DebuggerStepThrough()>
  96.    Private Sub DoRowsMove(ByVal dgv As DataGridView,
  97.                           ByVal direction As DataGridViewMoveRowDirection,
  98.                           Optional ByVal preserveCellsIndex As IEnumerable(Of Integer) = Nothing)
  99.  
  100.        ' Keeps tracks of a cell value to preserve, to swap them when moving rows.
  101.        Dim oldCellValue As Object
  102.        Dim newCellValue As Object
  103.  
  104.        ' Short row collection reference.
  105.        Dim rows As DataGridViewRowCollection = dgv.Rows
  106.  
  107.        ' Keeps track of the current row.
  108.        Dim curRow As DataGridViewRow
  109.  
  110.        ' The maximum row index.
  111.        Dim lastRowIndex As Integer =
  112.            If(dgv.AllowUserToAddRows,
  113.               rows.Count - 2,
  114.               rows.Count - 1)
  115.  
  116.        ' List of hash codes of the selected rows.
  117.        Dim selectedRows As New List(Of Integer)
  118.  
  119.        ' Get the hash codes of the selected rows
  120.        For i As Integer = 0 To (rows.Count - 1)
  121.            If (rows(i).IsNewRow = False) AndAlso (rows(i).Selected) Then
  122.                selectedRows.Add(rows(i).GetHashCode)
  123.                rows(i).Selected = False
  124.            End If
  125.        Next i
  126.  
  127.        ' Move the selected rows up or down.
  128.        Select Case direction
  129.  
  130.            Case DataGridViewMoveRowDirection.Up
  131.                For i As Integer = 0 To lastRowIndex
  132.  
  133.                    If Not rows(i).IsNewRow Then
  134.  
  135.                        If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso
  136.                           (i - 1 >= 0) AndAlso
  137.                           (Not selectedRows.Contains(rows(i - 1).GetHashCode)) Then
  138.  
  139.                            curRow = rows(i)
  140.                            rows.Remove(curRow)
  141.                            rows.Insert(i - 1, curRow)
  142.  
  143.                            If preserveCellsIndex IsNot Nothing Then
  144.  
  145.                                For Each cellIndex As Integer In preserveCellsIndex
  146.                                    oldCellValue = curRow.Cells(cellIndex).Value
  147.                                    newCellValue = rows(i).Cells(cellIndex).Value
  148.  
  149.                                    rows(i).Cells(cellIndex).Value = oldCellValue
  150.                                    curRow.Cells(cellIndex).Value = newCellValue
  151.                                Next cellIndex
  152.  
  153.                            End If
  154.  
  155.                        End If
  156.  
  157.                    End If
  158.  
  159.                Next i
  160.  
  161.            Case DataGridViewMoveRowDirection.Down
  162.                For i As Integer = lastRowIndex To 0 Step -1
  163.  
  164.                    If Not rows(i).IsNewRow Then
  165.  
  166.                        If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso
  167.                           (i + 1 <= lastRowIndex) AndAlso
  168.                           (Not selectedRows.Contains(rows(i + 1).GetHashCode)) Then
  169.  
  170.                            curRow = rows(i)
  171.                            rows.Remove(curRow)
  172.                            rows.Insert(i + 1, curRow)
  173.  
  174.                            If preserveCellsIndex IsNot Nothing Then
  175.  
  176.                                For Each cellIndex As Integer In preserveCellsIndex
  177.                                    oldCellValue = curRow.Cells(cellIndex).Value
  178.                                    newCellValue = rows(i).Cells(cellIndex).Value
  179.  
  180.                                    rows(i).Cells(cellIndex).Value = oldCellValue
  181.                                    curRow.Cells(cellIndex).Value = newCellValue
  182.                                Next cellIndex
  183.  
  184.                            End If
  185.  
  186.                        End If
  187.  
  188.                    End If
  189.  
  190.                Next i
  191.  
  192.        End Select
  193.  
  194.        ' Restore selected rows.
  195.        For i As Integer = 0 To (rows.Count - 1)
  196.  
  197.            If Not rows(i).IsNewRow Then
  198.                rows(i).Selected = selectedRows.Contains(rows(i).GetHashCode)
  199.            End If
  200.  
  201.        Next i
  202.  
  203.    End Sub
  204.  
  205. #End Region
  206.  
  207. End Module

Saludos!
5294  Programación / .NET (C#, VB.NET, ASP) / Re: [Ayuda] Extraer URL del código fuente de una web y ponerlo en un ListBox en: 16 Junio 2015, 02:18 am
Que deberia añadir o modificar?

El nombre + número del capítulo:
Código
  1. ETIQUETA.InnerText

El número del capítulo está en la etiqueta STRONG, bien puedes hacerlo así:
Código
  1. ETIQUETA.Children(0).InnerText

O así:
Código
  1. ETIQUETA.GetElementsByTagName("STRONG").Item(0).InnerText

Saludos!
5295  Programación / .NET (C#, VB.NET, ASP) / Re: [Ayuda] Extraer URL del código fuente de una web y ponerlo en un ListBox en: 16 Junio 2015, 01:25 am
Usa las etiquetas para insertar código, es una norma del foro.



si busco el manga "Gakuen Heaven"...

Debes modificar los espacios por guiones bajos (también deberías tratar de realizar una comparación ignorando mayusculas/minusculas), así, funciona:

Código
  1. ...
  2. If etiqueta.OuterHtml.ToLower.Contains(String.Format("http://submanga.com/{0}/", "Gakuen Heaven".ToLower.Replace(" "c, "_"c))) Then
  3. ...

Saludos!
5296  Programación / .NET (C#, VB.NET, ASP) / Re: Creando un bot para adfly en: 16 Junio 2015, 00:50 am
Ya, pero ¿cómo saben si es tráfico de proxy o no?.

Yo ahora mismo podría hacer de mi ordenador un proxy y estoy seguro de que si os conectarais a el y accedierais al link de adfly a través de mi no se darían cuenta y contarían la visita.

El optimismo llevado al extremo nunca es bueno.

Ahí tienes la información oficial de Adfly, lo que estás haciendo no sirve, lo siento, pero es la realidad.

Hazte las siguientee preguntas:

- ¿Crees que en toda la era de Internet, bueno, desde la aparición de este tipo de servicios, tú eres la primera persona que ha puesto en práctica un bot mediante proxyes para Adfly u otro tipo de servicios c2p?.

- Entonces, ¿crees que este tipo de compañias realmente no han ido evolucionando y desarrolladon ningún tipo de defensa desde entonces, hasta el punto de pensar que a día de hoy realmente son incapaces de detectar un proxy?.

EDITO: - ¿Por qué crees que hay decenas o cientos de niños rata vendiendo sus bots de Adfly y similares en internet?, si tanto dinero ganan con sus bots ...¿por qué tienen la necesidad de venderlos en lugar de estar despreocupados rascándose los webos en un jacuzzi?,
ah ...si, para sacarle el dinero a los inocentes que crean que un bot sirve, para ganar de ese modo el dinero que no pueden ganar en Adfly mediante los bots que están vendiendo.

No se exactamente que metodologías de detección habrá, lo que si se es que existen servicios profesionales dedicados a detectar proxyes anónimos o no, cómo MaxMind y FraudLabs, pregúntate si una compañia cómo Adfly, compañia que por cierto parece ganar más ingresos de los que pierde por que despues de muchos años sigue a flote (eso ya da que pensar en la ausencia de fraudes por bots en sus servicios), puede tener contratado algún tipo de servicio profesional para detectar este tipo de fraude por los usuarios.

Además, una cosa es un tráfico de proxyes normal, y otro tipo de tráfico muy distinto es un tráfico masivo intencionado usando Bots en tu propio beneficio, siendo lo segundo una anomalía notable, por lo primero directamente no pagan, y por lo segundo además de no pagar lo más probable es que acabes con tu cuenta baneada cuando detecten cierta anomalía de tráfico debido al uso de tu bot, y en consecuencia hayas perdido tiempo e ilusiones.

De todas formas, claro está que eres libre de poner en práctica cualquier idea que tengas y aprender de tus propias experiencias.



¿recorres el DOM y obtienes valores de ciertas etiquetas?

Practiamente en eso consiste el web-crawling, en parsear los documentos Html para obtener información específica.

Hay varios modos de hacerlo, la más ordinaria es utilizando las funciones built-in de .net para partir un string (String.Split) y filtrarla mediante substracciones (String.Substring, String.IndexOf, String.LastInfexOf, etc...),
otra manera sería utilizando expresiones regulares (RegEx),
y otra manera sería utilizando ciertas librerías (HtmlagilityPack en caso de .Net) para representar el árbol del documento Html orientado a objetos,
entre alguna que otra metodología más que habrá.

Dices que estás interesado en ello, pues aquí puedes ver un pequeño ejemplo con el que puedes empezar:
http://foro.elhacker.net/net/leer_datos_de_una_tabla_html-t436957.0.html

Y aquí tienes el source que compartí de un web-spider que recolecta los enlaces de una página de música en particular:
[SOURCE] Plixid Leecher - By Elektro

También existe una librería especializada en el web-scrapping para .Net, se llama aBot, aunque nunca la llegué a probar en profundidad:
https://github.com/sjdirect/abot
    (también la puedes descargar por la consola de NuGet)

EDITO: Aparte de algunas Classes de .Net Framework que puedes utilizar para el parseo de Html o Xml, cómo HtmlElement o Xelement



¿Cuando lea .NET debo asociar de que se trata de alguno de esos lenguajes sin poder determinar exactamente cuál?

.Net no es un lenguaje, sino un Framework (cómo ya has deducido) que soporta varios lenguajes, entre ellos los que has mencionado, VB.Net (Visual Basic.Net), C# (C-Sharp) y VC++ (Visual C++), y otro(s) cómo F# (F-Sharp);
también hay implementaciones de Python, Ruby, y otro(s) lenguaje(s) que corren bajo .Net, además, el soporte de la IDE Visual Studio para "hibridar" utilizando lenguajes alternos cómo Html, Xml, y PHP, es excelente, todo lo que concierne a .Net es muy grande, y muy sofisticado, por algo es de Microsoft, no hay competencia.

Saludos!
5297  Programación / .NET (C#, VB.NET, ASP) / Re: Creando un bot para adfly en: 15 Junio 2015, 23:10 pm
esto no es nada comparado con lo que se puede hacer.

...Adfly no paga absolutamente nada por tráfico de proxyes, salvo que el anunciante decida mostrar el anuncio a ese tipo de tráfico, y en estos casos el pago por este tipo de tráfico es el menos valorado.

http://kb.adf.ly/119/what-is-proxy-traffic-will-i-get-paid-for-it

PD: Aunque ilegal, sería mucho más rentable invertir el tiempo en desarrollar una botnet y propagarla para utilizar tráfico real.

Saludos!
5298  Programación / Scripting / Re: asociación de archivos en: 15 Junio 2015, 22:43 pm
¿Por qué debes poner dos %% aquí?
Código:
ftype JARFile="%direccionJava%" -jar "%%1" "%%*"

Lo he mencionado antes, para escapar el caracter "%", ya que es un símbolo reservado por el lenguaje ...para definir variables, por ende, obviamente si escribes el símbolo "%" tendrá un efecto muy distinto al que le querías dar, ya que tú pretendes escribir/interpretar dicho símbolo, no usarlo cómo si de una variable se tratase.



busco poder abrir el archivo como abrir con, seleccionar un programa y convertirlo en el predeterminado

Con los arreglos que mencione, aplicados en el código que mostraste, estás creando una asociación por defecto para los archivos con extensión ".jar", para que se ejecuten con la aplicación "javaw.exe" pasándole los argumentos: " -jar "C:\Ruta de archivo.jar" "Argumentos adicionales" ", por ende, al clickar sobre un archivo de tipo ".jar", éste se intentará abrir con la aplicación de Java.

Todo ese proceso que haces en Batch se resume en crear una clave de referencia en la clave de registro "HKCR\.jar" con el nombre que le diste (JARFile), y en esa clave referenciada (HKCR\JARFile) se crea el comando por defecto "Open" (HKCR\JARFile\Shell\Open\Command) con el valor que le diste.

En resumen, supuestamente ya has hecho la aplicación javaw.exe la predeterminada para archivos .jar.

Si no es eso lo que pretendes, intenta explicarlo con más detalles.

Saludos!
5299  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets) en: 15 Junio 2015, 20:01 pm
Comparto este snippet para compilar código fuente en tiempo de ejecución, una DLL, una app CLI o GUI, desde un string o desde un archivo que contenga el código guente.

Es útil por ejemplo para bindear archivos, o embedir tablas de recursos en una dll, o simplemente para compilar un código de C# o VB.Net.

Ejemplo de uso:
Código
  1. Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  2.  
  3.     Dim resultVB As CompilerResults =
  4.         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  5.                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  6.                                     targetFile:="C:\VB Assembly.dll",
  7.                                     resources:={"C:\MyResources.resx"},
  8.                                     referencedAssemblies:={"System.dll"},
  9.                                     mainClassName:="MainNamespace.MainClass",
  10.                                     sourceCode:=<a>
  11.                                                 Imports System
  12.  
  13.                                                 Namespace MainNamespace
  14.  
  15.                                                     Public NotInheritable MainClass
  16.  
  17.                                                     End Class
  18.  
  19.                                                 End Namespace
  20.                                                 </a>.Value)
  21.  
  22.     Dim warnings As IEnumerable(Of CompilerError) =
  23.         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  24.         Where ce.IsWarning
  25.  
  26.     Dim errors As IEnumerable(Of CompilerError) =
  27.         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  28.         Where Not ce.IsWarning
  29.  
  30.     For Each war As CompilerError In warnings
  31.         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  32.     Next war
  33.  
  34.     For Each err As CompilerError In errors
  35.         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  36.     Next err
  37.  
  38. End Using

Código fuente:
Código
  1.        ''' <summary>
  2.        ''' Specifies a <see cref="CompilerParameters"></see> target assembly.
  3.        ''' </summary>
  4.        Public Enum TargetAssembly As Integer
  5.  
  6.            ''' <summary>
  7.            ''' A Command line interface executable.
  8.            ''' </summary>
  9.            Cli = 0
  10.  
  11.            ''' <summary>
  12.            ''' A Graphical user interface executable.
  13.            ''' </summary>
  14.            Gui = 1
  15.  
  16.            ''' <summary>
  17.            ''' A Dynamic-link library.
  18.            ''' </summary>
  19.            Dll = 2
  20.  
  21.        End Enum
  22.  
  23.        ''' <remarks>
  24.        ''' *****************************************************************
  25.        ''' Title : Compile Assembly (from reaource).
  26.        ''' Author: Elektro
  27.        ''' Date  : 14-June-2015
  28.        ''' Usage :
  29.        '''
  30.        ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  31.        '''
  32.        '''     Dim resultVB As CompilerResults =
  33.        '''         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  34.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  35.        '''                                     targetFile:="C:\VB Assembly.dll",
  36.        '''                                     resources:={"C:\MyResources.resx"},
  37.        '''                                     referencedAssemblies:={"System.dll"},
  38.        '''                                     mainClassName:="MainNamespace.MainClass",
  39.        '''                                     sourceCode:=<a>
  40.        '''                                                 Imports System
  41.        '''
  42.        '''                                                 Namespace MainNamespace
  43.        '''
  44.        '''                                                     Public NotInheritable MainClass
  45.        '''
  46.        '''                                                     End Class
  47.        '''
  48.        '''                                                 End Namespace
  49.        '''                                                 </a>.Value)
  50.        '''
  51.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  52.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  53.        '''         Where ce.IsWarning
  54.        '''
  55.        '''     Dim errors As IEnumerable(Of CompilerError) =
  56.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  57.        '''         Where Not ce.IsWarning
  58.        '''
  59.        '''     For Each war As CompilerError In warnings
  60.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  61.        '''     Next war
  62.        '''
  63.        '''     For Each err As CompilerError In errors
  64.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  65.        '''     Next err
  66.        '''
  67.        ''' End Using
  68.        ''' -----------------------------------------------------------------
  69.        ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider
  70.        '''
  71.        '''     Dim resultCS As CompilerResults =
  72.        '''         CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider,
  73.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  74.        '''                                     targetFile:="C:\C# Assembly.dll",
  75.        '''                                     resources:={"C:\MyResources.resx"},
  76.        '''                                     referencedAssemblies:={"System.dll"},
  77.        '''                                     mainClassName:="MainNamespace.MainClass",
  78.        '''                                     sourceCode:=<a>
  79.        '''                                                 using System;
  80.        '''
  81.        '''                                                 namespace MainNamespace
  82.        '''                                                 {
  83.        '''                                                     class MainClass
  84.        '''                                                     {
  85.        '''
  86.        '''                                                     }
  87.        '''                                                 }
  88.        '''                                                 </a>.Value)
  89.        '''
  90.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  91.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  92.        '''         Where ce.IsWarning
  93.        '''
  94.        '''     Dim errors As IEnumerable(Of CompilerError) =
  95.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  96.        '''         Where Not ce.IsWarning
  97.        '''
  98.        '''     For Each war As CompilerError In warnings
  99.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  100.        '''     Next war
  101.        '''
  102.        '''     For Each err As CompilerError In errors
  103.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  104.        '''     Next err
  105.        '''
  106.        ''' End Using
  107.        ''' *****************************************************************
  108.        ''' </remarks>
  109.        ''' <summary>
  110.        ''' Compiles a .Net assembly as executable or link library.
  111.        ''' </summary>
  112.        ''' <param name="codeProvider">The code provider.</param>
  113.        ''' <param name="targetAssembly">The kind of assembly to generate.</param>
  114.        ''' <param name="targetFile">The target file to create.</param>
  115.        ''' <param name="resources">The embedded resources (if any).</param>
  116.        ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param>
  117.        ''' <param name="mainClassName">The code to compile (if any).</param>
  118.        ''' <param name="sourceCode">The sourcecode to compile (if any).</param>
  119.        ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception>
  120.        ''' <exception cref="NotImplementedException">Default sourcecode is not implemented for the specified CodeDomProvider. Please, set a sourcecode yourself.</exception>
  121.        ''' <returns>The results of the compiler operation.</returns>
  122.        Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider,
  123.                                               ByVal targetAssembly As TargetAssembly,
  124.                                               ByVal targetFile As String,
  125.                                               Optional ByVal resources As IEnumerable(Of String) = Nothing,
  126.                                               Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing,
  127.                                               Optional ByVal mainClassName As String = "MainNamespace.MainClass",
  128.                                               Optional ByVal sourceCode As String = Nothing) As CompilerResults
  129.  
  130.            ' Set a default assembly reference.
  131.            If referencedAssemblies Is Nothing Then
  132.                referencedAssemblies = {"System.dll"}
  133.            End If
  134.  
  135.            Dim cp As New CompilerParameters
  136.            With cp
  137.  
  138.                ' Set compiler arguments.
  139.                Select Case targetAssembly
  140.  
  141.                    Case CodeDomUtil.TargetAssembly.Gui
  142.                        .CompilerOptions = "/optimize /target:winexe"
  143.  
  144.                    Case Else
  145.                        .CompilerOptions = "/optimize"
  146.  
  147.                End Select
  148.  
  149.                ' Generate an exe or a dll.
  150.                .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll)
  151.  
  152.                ' Save the assembly as a physical file.
  153.                .GenerateInMemory = False
  154.  
  155.                ' Generate debug information (pdb).
  156.                .IncludeDebugInformation = False
  157.  
  158.                ' Set the assembly file name to generate.
  159.                .OutputAssembly = targetFile
  160.  
  161.                ' Add an assembly reference.
  162.                .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray)
  163.  
  164.                ' Set a temporary files collection.
  165.                ' The TempFileCollection stores the temporary files generated during a build in the current directory.
  166.                .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True)
  167.  
  168.                ' Set whether to treat all warnings as errors.
  169.                .TreatWarningsAsErrors = False
  170.  
  171.                ' Set the level at which the compiler should start displaying warnings.
  172.                ' 0 - Turns off emission of all warning messages.
  173.                ' 1 - Displays severe warning messages.
  174.                ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
  175.                ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
  176.                ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.
  177.                .WarningLevel = 3
  178.  
  179.                ' Set the embedded resource file of the assembly.
  180.                If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then
  181.                    .EmbeddedResources.AddRange(resources.ToArray)
  182.  
  183.                ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then
  184.                    Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.")
  185.  
  186.                End If
  187.  
  188.                ' Specify the class that contains the main method of the executable.
  189.                If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then
  190.  
  191.                    .MainClass = mainClassName
  192.  
  193.                    If (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso
  194.                       (String.IsNullOrEmpty(sourceCode)) AndAlso
  195.                       .GenerateExecutable Then
  196.  
  197.                        sourceCode =
  198.                            <a>
  199.                            Imports System
  200.  
  201.                            Namespace MainNamespace
  202.  
  203.                                Module MainClass
  204.  
  205.                                    Sub Main()
  206.                                    End Sub
  207.  
  208.                                End Module
  209.  
  210.                            End Namespace
  211.                            </a>.Value
  212.  
  213.                    ElseIf (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso
  214.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  215.                           Not .GenerateExecutable Then
  216.  
  217.                        sourceCode =
  218.                            <a>
  219.                            Imports System
  220.  
  221.                            Namespace MainNamespace
  222.  
  223.                                Public NotInheritable MainClass
  224.  
  225.                                End Class
  226.  
  227.                            End Namespace
  228.                            </a>.Value
  229.  
  230.                    ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso
  231.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  232.                          .GenerateExecutable Then
  233.  
  234.                        sourceCode =
  235.                            <a>
  236.                            using System;
  237.  
  238.                            namespace MainNamespace
  239.                            {
  240.                                class MainClass
  241.                                {
  242.                                    static void Main(string[] args)
  243.                                    {
  244.  
  245.                                    }
  246.                                }
  247.                            }
  248.                            </a>.Value
  249.  
  250.                    ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso
  251.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  252.                           Not .GenerateExecutable Then
  253.  
  254.                        sourceCode =
  255.                            <a>
  256.                            using System;
  257.  
  258.                            namespace MainNamespace
  259.                            {
  260.                                class MainClass
  261.                                {
  262.  
  263.                                }
  264.                            }
  265.                            </a>.Value
  266.  
  267.                    ElseIf String.IsNullOrEmpty(sourceCode) Then
  268.                        Throw New NotImplementedException(message:="Default sourcecode is not implemented for the specified CodeDomProvider. Please, specify a sourcecode.")
  269.  
  270.                    End If
  271.  
  272.                End If
  273.  
  274.            End With
  275.  
  276.            Return codeProvider.CompileAssemblyFromSource(cp, sourceCode)
  277.  
  278.        End Function
  279.  
  280.        ''' <remarks>
  281.        ''' *****************************************************************
  282.        ''' Title : Compile Assembly (from file).
  283.        ''' Author: Elektro
  284.        ''' Date  : 14-June-2015
  285.        ''' Usage :
  286.        '''
  287.        ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  288.        '''
  289.        '''     Dim resultVB As CompilerResults =
  290.        '''         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  291.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  292.        '''                                     sourceFile:="C:\SourceCode.vb",
  293.        '''                                     targetFile:="C:\VB Assembly.dll",
  294.        '''                                     resources:={"C:\MyResources.resx"},
  295.        '''                                     referencedAssemblies:={"System.dll"},
  296.        '''                                     mainClassName:="MainNamespace.MainClass")
  297.        '''
  298.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  299.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  300.        '''         Where ce.IsWarning
  301.        '''
  302.        '''     Dim errors As IEnumerable(Of CompilerError) =
  303.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  304.        '''         Where Not ce.IsWarning
  305.        '''
  306.        '''     For Each war As CompilerError In warnings
  307.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  308.        '''     Next war
  309.        '''
  310.        '''     For Each err As CompilerError In errors
  311.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  312.        '''     Next err
  313.        '''
  314.        ''' End Using
  315.        ''' -----------------------------------------------------------------
  316.        ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider
  317.        '''
  318.        '''     Dim resultCS As CompilerResults =
  319.        '''         CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider,
  320.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  321.        '''                                     sourceFile:="C:\SourceCode.cs",
  322.        '''                                     targetFile:="C:\CS Assembly.dll",
  323.        '''                                     resources:={"C:\MyResources.resx"},
  324.        '''                                     referencedAssemblies:={"System.dll"},
  325.        '''                                     mainClassName:="MainNamespace.MainClass")
  326.        '''
  327.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  328.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  329.        '''         Where ce.IsWarning
  330.        '''
  331.        '''     Dim errors As IEnumerable(Of CompilerError) =
  332.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  333.        '''         Where Not ce.IsWarning
  334.        '''
  335.        '''     For Each war As CompilerError In warnings
  336.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  337.        '''     Next war
  338.        '''
  339.        '''     For Each err As CompilerError In errors
  340.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  341.        '''     Next err
  342.        '''
  343.        ''' End Using
  344.        ''' *****************************************************************
  345.        ''' </remarks>
  346.        ''' <summary>
  347.        ''' Compiles a .Net assembly as executable or link library.
  348.        ''' </summary>
  349.        ''' <param name="codeProvider">The code provider.</param>
  350.        ''' <param name="targetAssembly">The kind of assembly to generate.</param>
  351.        ''' <param name="sourceFile">The source file to compile.</param>
  352.        ''' <param name="targetFile">The target file to create.</param>
  353.        ''' <param name="resources">The embedded resources (if any).</param>
  354.        ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param>
  355.        ''' <param name="mainClassName">The code to compile (if any).</param>
  356.        ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception>
  357.        ''' <returns>The results of the compiler operation.</returns>
  358.        Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider,
  359.                                               ByVal targetAssembly As TargetAssembly,
  360.                                               ByVal sourceFile As String,
  361.                                               ByVal targetFile As String,
  362.                                               Optional ByVal resources As IEnumerable(Of String) = Nothing,
  363.                                               Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing,
  364.                                               Optional ByVal mainClassName As String = "MainNamespace.MainClass") As CompilerResults
  365.  
  366.            ' Set a default assembly reference.
  367.            If referencedAssemblies Is Nothing Then
  368.                referencedAssemblies = {"System.dll"}
  369.            End If
  370.  
  371.            Dim cp As New CompilerParameters
  372.            With cp
  373.  
  374.                ' Set compiler arguments.
  375.                Select Case targetAssembly
  376.  
  377.                    Case CodeDomUtil.TargetAssembly.Gui
  378.                        .CompilerOptions = "/optimize /target:winexe"
  379.  
  380.                    Case Else
  381.                        .CompilerOptions = "/optimize"
  382.  
  383.                End Select
  384.  
  385.                ' Generate an exe or a dll.
  386.                .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll)
  387.  
  388.                ' Save the assembly as a physical file.
  389.                .GenerateInMemory = False
  390.  
  391.                ' Generate debug information (pdb).
  392.                .IncludeDebugInformation = False
  393.  
  394.                ' Set the assembly file name to generate.
  395.                .OutputAssembly = targetFile
  396.  
  397.                ' Add an assembly reference.
  398.                .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray)
  399.  
  400.                ' Set a temporary files collection.
  401.                ' The TempFileCollection stores the temporary files generated during a build in the current directory.
  402.                .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True)
  403.  
  404.                ' Set whether to treat all warnings as errors.
  405.                .TreatWarningsAsErrors = False
  406.  
  407.                ' Set the level at which the compiler should start displaying warnings.
  408.                ' 0 - Turns off emission of all warning messages.
  409.                ' 1 - Displays severe warning messages.
  410.                ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
  411.                ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
  412.                ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.
  413.                .WarningLevel = 3
  414.  
  415.                ' Set the embedded resource file of the assembly.
  416.                If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then
  417.                    .EmbeddedResources.AddRange(resources.ToArray)
  418.  
  419.                ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then
  420.                    Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.")
  421.  
  422.                End If
  423.  
  424.                ' Specify the class that contains the main method of the executable.
  425.                If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then
  426.                    .MainClass = mainClassName
  427.                End If
  428.  
  429.            End With
  430.  
  431.            Return codeProvider.CompileAssemblyFromFile(cp, {sourceFile})
  432.  
  433.        End Function
  434.  
  435.    End Class
  436.  
5300  Programación / Scripting / Re: asociación de archivos en: 15 Junio 2015, 17:23 pm
no lo consigo por mas vueltas que doy.

1. Encierra las variables
Código
  1. set "direccionJava=C:\Program Files\Java\jre1.8.0_40\bin\javaw.exe"
  2. set "direccionJava86=C:\Program Files(x86)\Java\jre1.8.0_40\bin\javaw.exe"

2. Escapa los caracteres reservados por el lenguaje (%)
Código
  1. ftype JARFile="%direccionJava%" -jar "%%1" "%%*"

Saludos!
Páginas: 1 ... 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 [530] 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 ... 1253
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines