Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#4231
Cita de: Lekim en 12 Noviembre 2015, 11:43 AMTambién vale?

No, no me vale. Estás haciendo uso de málas prácticas, desaprovechando las ventajas del lenguaje utilizando métodos deprecados para llevar a cabo las cosas.

1. Usa la directiva Usings, esto aporta la ventaja de evitar bloques Try/Catch innecesarios, y mayor seguridad en general.

2. Usa IsNot Nothing en lugar de Not IsNothing()

3. Usa DirectCast para asumir de forma implícita el casting sin evaluaciones innecesarias, en lugar de CType, es algo innecesario en tu código y consume más tiempo, ya que ambos trabajan de manera distinta.

4. En tu bloque Try/Catch, estás lanzando una nueva excepción, no la excepción capturada en la expresión Catch.

Incorrecto:
Código (vbnet) [Seleccionar]
Catch ex As Exception
   Throw New Exception


No del todo correcto:
Código (vbnet) [Seleccionar]
Catch
   Throw


Tampoco del todo correcto:
Código (vbnet) [Seleccionar]
Catch ex As Exception
    Throw ex


Correcto:
Código (vbnet) [Seleccionar]
Catch ex As Exception
   Throw


También correcto:
Código (vbnet) [Seleccionar]
Catch ex As Exception
   Throw New Exception("Mensaje personalizado", innerException:=ex)


Saludos
#4232
Debes utilizar la codificación de caracteres adecuada, la misma en la que está escrito el documento Html, en este caso, CP1252 (o Windows-1252).

Código (vbnet) [Seleccionar]
Encoding.GetEncoding(name:="windows-1252")

Aparte de eso, el código lo tenías un poco "sucio", aquí tienes:
Código (vbnet) [Seleccionar]
Dim sourceCode As String
Dim url As String = "https://foro.elhacker.net/net/el_codigo_html_extraido_de_una_web_no_muestra_acentos_aeo-t444215.0.html;msg2046878#msg2046878"
Dim enc As Encoding = Encoding.GetEncoding(name:="windows-1252")
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)

req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" '".NET Framework Test Client"

Using resp As HttpWebResponse = DirectCast(req.GetResponse, HttpWebResponse)

   Using sr As New StreamReader(resp.GetResponseStream, enc)

       sourceCode = sr.ReadToEnd

   End Using

End Using


Nota: Te sugiero limpiar el código en el contexto de importar los namespaces necesaros para no llenar todo el código de nombres de miembros excesivamente repetitivos, eso lo vuelve muy tedioso de leer.

Código (vbnet) [Seleccionar]
Imports System.IO
Imports System.Net
Imports System.Text





Cita de: Lekim en 12 Noviembre 2015, 11:15 AMTambién me ha servido poner System.Text.Encoding.Default

Código (vbnet) [Seleccionar]
Dim streamRead As New System.IO.StreamReader(streamResponse, System.Text.Encoding.Default)

Ten cuidado con System.Text.Encoding.Default, en este caso te funciona por que el código de página o codepage por defecto del sistema (de tu sistema), es el mismo que el de la web a la que le haces el request, pero no siempre será así.

Saludos
#4233
Un snippet para monitorizar la inserción y extracción de dispositivos de almacenamiento (USB, discos duros, etc).

Ejemplo de uso:
Código (vbnet) [Seleccionar]
    Friend WithEvents DriveMon As New DriveWatcher

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Handles the <see cref="DriveWatcher.DriveStatusChanged"/> event of the <see cref="DriveMon"/> instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="sender">
    ''' The source of the event.
    ''' </param>
    '''
    ''' <param name="e">
    ''' The <see cref="DriveWatcher.DriveStatusChangedEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    Private Sub DriveMon_DriveStatusChanged(ByVal sender As Object, ByVal e As DriveWatcher.DriveStatusChangedEventArgs) _
    Handles DriveMon.DriveStatusChanged

        Select Case e.DeviceEvent

            Case DriveWatcher.DeviceEvents.Arrival
                Dim sb As New StringBuilder
                sb.AppendLine("New drive connected...'")
                sb.AppendLine(String.Format("Type......: {0}", e.DriveInfo.DriveType.ToString))
                sb.AppendLine(String.Format("Label.....: {0}", e.DriveInfo.VolumeLabel))
                sb.AppendLine(String.Format("Name......: {0}", e.DriveInfo.Name))
                sb.AppendLine(String.Format("Root......: {0}", e.DriveInfo.RootDirectory))
                sb.AppendLine(String.Format("FileSystem: {0}", e.DriveInfo.DriveFormat))
                sb.AppendLine(String.Format("Size......: {0} GB", (e.DriveInfo.TotalSize / (1024 ^ 3)).ToString("n1")))
                sb.AppendLine(String.Format("Free space: {0} GB", (e.DriveInfo.AvailableFreeSpace / (1024 ^ 3)).ToString("n1")))
                Console.WriteLine(sb.ToString)

            Case DriveWatcher.DeviceEvents.RemoveComplete
                Dim sb As New StringBuilder
                sb.AppendLine("Drive disconnected...'")
                sb.AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
                sb.AppendLine(String.Format("Root: {0}", e.DriveInfo.RootDirectory))
                Console.WriteLine(sb.ToString)

        End Select

    End Sub

    Private Sub StartMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Button_StartMon.Click

        Me.DriveMon.Start()

    End Sub

    Private Sub StopMon_Click(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Button_StopMon.Click

        Me.DriveMon.Stop()

    End Sub


Código fuente:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 11-November-2015
' ***********************************************************************
' <copyright file="DriveWatcher.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' A device insertion and removal monitor.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable

#Region " Properties "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the connected drives on this computer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public ReadOnly Property Drives As IEnumerable(Of DriveInfo)
        <DebuggerStepThrough>
        Get
            Return DriveInfo.GetDrives
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets a value that determines whether the monitor is running.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public ReadOnly Property IsRunning As Boolean
        <DebuggerStepThrough>
        Get
            Return Me.isRunningB
        End Get
    End Property
    Private isRunningB As Boolean

#End Region

#Region " Events "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' A list of event delegates.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private ReadOnly events As EventHandlerList

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Occurs when a drive is inserted, removed, or changed.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public Custom Event DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        AddHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
            Me.events.AddHandler("DriveStatusChangedEvent", value)
        End AddHandler

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        RemoveHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
            Me.events.RemoveHandler("DriveStatusChangedEvent", value)
        End RemoveHandler

        <DebuggerNonUserCode>
        <DebuggerStepThrough>
        RaiseEvent(ByVal sender As Object, ByVal e As DriveStatusChangedEventArgs)
            Dim handler As EventHandler(Of DriveStatusChangedEventArgs) =
                DirectCast(Me.events("DriveStatusChangedEvent"), EventHandler(Of DriveStatusChangedEventArgs))

            If (handler IsNot Nothing) Then
                handler.Invoke(sender, e)
            End If
        End RaiseEvent

    End Event

#End Region

#Region " Events Data "

#Region " DriveStatusChangedEventArgs "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Contains the event-data of a <see cref="DriveStatusChanged"/> event.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Public NotInheritable Class DriveStatusChangedEventArgs : Inherits EventArgs

#Region " Properties "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Gets the device event that occurred.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <value>
        ''' The drive info.
        ''' </value>
        ''' ----------------------------------------------------------------------------------------------------
        Public ReadOnly Property DeviceEvent As DeviceEvents
            <DebuggerStepThrough>
            Get
                Return Me.deviceEventsB
            End Get
        End Property
        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' ( Backing field )
        ''' The device event that occurred.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private ReadOnly deviceEventsB As DeviceEvents

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Gets the drive info.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <value>
        ''' The drive info.
        ''' </value>
        ''' ----------------------------------------------------------------------------------------------------
        Public ReadOnly Property DriveInfo As DriveInfo
            <DebuggerStepThrough>
            Get
                Return Me.driveInfoB
            End Get
        End Property
        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' ( Backing field )
        ''' The drive info.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private ReadOnly driveInfoB As DriveInfo

#End Region

#Region " Constructors "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Prevents a default instance of the <see cref="DriveStatusChangedEventArgs"/> class from being created.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerNonUserCode>
        Private Sub New()
        End Sub

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Initializes a new instance of the <see cref="DriveStatusChangedEventArgs"/> class.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <param name="driveInfo">
        ''' The drive info.
        ''' </param>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Sub New(ByVal deviceEvent As DeviceEvents, ByVal driveInfo As DriveInfo)

            Me.deviceEventsB = deviceEvent
            Me.driveInfoB = driveInfo

        End Sub

#End Region

    End Class

#End Region

#End Region

#Region " Event Invocators "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Raises <see cref="DriveStatusChanged"/> event.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="e">
    ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overridable Sub OnDriveStatusChanged(ByVal e As DriveStatusChangedEventArgs)

        RaiseEvent DriveStatusChanged(Me, e)

    End Sub

#End Region

#Region " Enumerations "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a change to the hardware configuration of a device.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx"/>
    ''' <para></para>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    Public Enum DeviceEvents As Integer

        ' *****************************************************************************
        '                            WARNING!, NEED TO KNOW...
        '
        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
        ' *****************************************************************************

        ''' <summary>
        ''' The current configuration has changed, due to a dock or undock.
        ''' </summary>
        Change = &H219

        ''' <summary>
        ''' A device or piece of media has been inserted and becomes available.
        ''' </summary>
        Arrival = &H8000

        ''' <summary>
        ''' Request permission to remove a device or piece of media.
        ''' <para></para>
        ''' This message is the last chance for applications and drivers to prepare for this removal.
        ''' However, any application can deny this request and cancel the operation.
        ''' </summary>
        QueryRemove = &H8001

        ''' <summary>
        ''' A request to remove a device or piece of media has been canceled.
        ''' </summary>
        QueryRemoveFailed = &H8002

        ''' <summary>
        ''' A device or piece of media is being removed and is no longer available for use.
        ''' </summary>
        RemovePending = &H8003

        ''' <summary>
        ''' A device or piece of media has been removed.
        ''' </summary>
        RemoveComplete = &H8004

    End Enum

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Specifies a computer device type.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363246%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    Private Enum DeviceType As Integer

        ' *****************************************************************************
        '                            WARNING!, NEED TO KNOW...
        '
        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS PROJECT
        ' *****************************************************************************

        ''' <summary>
        ''' Logical volume.
        ''' </summary>
        Logical = &H2

    End Enum

#End Region

#Region " Types "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Contains information about a logical volume.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <remarks>
    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx"/>
    ''' </remarks>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    <StructLayout(LayoutKind.Sequential)>
    Private Structure DevBroadcastVolume

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' The size of this structure, in bytes.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Size As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Set to DBT_DEVTYP_VOLUME (2).
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Type As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Reserved parameter; do not use this.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Reserved As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' The logical unit mask identifying one or more logical units.
        ''' Each bit in the mask corresponds to one logical drive.
        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Mask As UInteger

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' This parameter can be one of the following values:
        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
        ''' '0x0002': Indicated logical volume is a network volume.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public Flags As UShort

    End Structure

#End Region

#Region " Constructor "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of <see cref="DriveWatcher"/> class.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New()

        Me.events = New EventHandlerList

    End Sub

#End Region

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Starts monitoring.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="Exception">
    ''' Monitor is already running.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Overridable Sub Start()

        If (Me.Handle = IntPtr.Zero) Then
            MyBase.CreateHandle(New CreateParams)
            Me.isRunningB = True

        Else
            Throw New Exception(message:="Monitor is already running.")

        End If

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Stops monitoring.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="Exception">
    ''' Monitor is already stopped.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Overridable Sub [Stop]()

        If (Me.Handle <> IntPtr.Zero) Then
            MyBase.DestroyHandle()
            Me.isRunningB = False

        Else
            Throw New Exception(message:="Monitor is already stopped.")

        End If

    End Sub

#End Region

#Region " Private Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the drive letter stored in a <see cref="DevBroadcastVolume"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="Device">
    ''' The <see cref="DevBroadcastVolume"/> structure containing the device mask.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The drive letter.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Function GetDriveLetter(ByVal device As DevBroadcastVolume) As Char

        Dim driveLetters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray

        Dim deviceID As New BitArray(BitConverter.GetBytes(device.Mask))

        For i As Integer = 0 To deviceID.Length

            If deviceID(i) Then
                Return driveLetters(i)
            End If

        Next i

        Return Nothing

    End Function

#End Region

#Region " Window Procedure (WndProc) "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Invokes the default window procedure associated with this window to process messages for this Window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="m">
    ''' A <see cref="T:System.Windows.Forms.Message"/> that is associated with the current Windows message.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overrides Sub WndProc(ByRef m As Message)

        Select Case m.Msg

            Case DeviceEvents.Change ' The hardware has changed.

                If (m.LParam = IntPtr.Zero) Then
                    Exit Select
                End If

                ' If it's an storage device then...
                If Marshal.ReadInt32(m.LParam, 4) = DeviceType.Logical Then

                    ' Transform the LParam pointer into the data structure.
                    Dim currentWDrive As DevBroadcastVolume =
                        DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DevBroadcastVolume)), DevBroadcastVolume)

                    Dim driveLetter As Char = Me.GetDriveLetter(currentWDrive)
                    Dim deviceEvent As DeviceEvents = DirectCast(m.WParam.ToInt32, DeviceEvents)
                    Dim driveInfo As New DriveInfo(driveLetter)

                    Me.OnDriveStatusChanged(New DriveStatusChangedEventArgs(deviceEvent, driveInfo))

                End If

        End Select

        ' Return Message to base message handler.
        MyBase.WndProc(m)

    End Sub

#End Region

#Region " Hidden methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function GetHashCode() As Integer
        Return MyBase.GetHashCode
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the <see cref="System.Type"/> of the current instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The exact runtime type of the current instance.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function [GetType]() As Type
        Return MyBase.GetType
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the specified <see cref="System.Object"/> instances are considered equal.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function Equals(ByVal obj As Object) As Boolean
        Return MyBase.Equals(obj)
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function ToString() As String
        Return MyBase.ToString
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Assigns a handle to this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub AssignHandle(ByVal handle As IntPtr)
        MyBase.AssignHandle(handle)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Creates a window and its handle with the specified creation parameters.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub CreateHandle(ByVal cp As CreateParams)
        MyBase.CreateHandle(cp)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Destroys the window and its handle.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub DestroyHandle()
        MyBase.DestroyHandle()
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Releases the handle associated with this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub ReleaseHandle()
        MyBase.ReleaseHandle()
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function GetLifeTimeService() As Object
        Return MyBase.GetLifetimeService
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function InitializeLifeTimeService() As Object
        Return MyBase.InitializeLifetimeService
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Creates an object that contains all the relevant information to generate a proxy used to communicate with a remote object.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Function CreateObjRef(ByVal requestedType As Type) As System.Runtime.Remoting.ObjRef
        Return MyBase.CreateObjRef(requestedType)
    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Invokes the default window procedure associated with this window.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <EditorBrowsable(EditorBrowsableState.Never)>
    <DebuggerNonUserCode>
    Public Shadows Sub DefWndProc(ByRef m As Message)
        MyBase.DefWndProc(m)
    End Sub

#End Region

#Region " IDisposable Implementation "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private isDisposed As Boolean

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Releases all the resources used by this instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Dispose() Implements IDisposable.Dispose

        Me.Dispose(isDisposing:=True)
        GC.SuppressFinalize(obj:=Me)

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="isDisposing">
    ''' <see langword="True"/>  to release both managed and unmanaged resources;
    ''' <see langword="False"/> to release only unmanaged resources.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)

        If (Not Me.isDisposed) AndAlso (isDisposing) Then

            Me.events.Dispose()
            Me.Stop()

        End If

        Me.isDisposed = True

    End Sub

#End Region

End Class
#4234
Normal que no encuentres las plantillas de proyecto, por que no las has instalado el soporte para el desarrollo bajo Visual C++.

El instalador de VS2015 es distinto a los anteriores, los componentes a instalar ahora están mejor "separados" o clasificados (por suerte es así). El soporte para Visual C++ se instala de manera opcional, debes elegir una instalación personalizada y seleccionar el componente "Common Tools for Visual C++ 2015"



Aquí tienes más info:

Saludos
#4235
Cita de: elqueteconte en  9 Noviembre 2015, 21:48 PMdesde el 01 al 02

entre el 01 y el 09.

siempre habrá un rango

En este caso te pregunto como sería la función Enumerable.Range ?

Código (vbnet) [Seleccionar]
Enumerable.Range(inicio, fin)
Código (vbnet) [Seleccionar]
Enumerable.Range(1, 2)
Código (vbnet) [Seleccionar]
Enumerable.Range(1, 9)




Cita de: elqueteconte en  9 Noviembre 2015, 21:48 PMOtra cosa:
Al función SelectDirectories espera 4 parámetros y en el llamaddo yo le estoy colocando solo 3, me falta el dateFormat, de donde lo saco?

Código (vbnet) [Seleccionar]

Dim directories As IEnumerable(Of DirectoryInfo) = DateUtil.SelectDirectories(dateDir, Me.year, monthNumber, ME FALTA ESTE PARÁMETRO)



El método original que estaba sutilizando era este:
Código (vbnet) [Seleccionar]
Public Sub MoveDateDirectories(ByVal year As Integer,
                                      ByVal month As Integer,
                                      ByVal dateFormat As String,
                                      ByVal sourceDir As String,
                                      ByVal targetDir As String)


Revisa en el código fuente que valor le estabas enviando al parámetro dateFormat de ese método. Usa el mismo valor al llamar a esta nueva función. No recuerdo el formato, está escrito en tu código fuente y también en alguna de las páginas de tus preguntas anteriores, era un string más o menos así "MM-dd-YYYY".

Saludos
#4236
Lo has entendido todo a la perfección y lo has sabido adaptar al código sin aydua :).

Solo que, aquí, no se si lo has entendido del todo, yo creo que deberías averiguar el día/semana que haya seleccionado en tu control DateTimePicker, y usarlo en el rango, por que esta función lo que hace es devolver un rango de valores desde X hasta Y: Enumerable.Range(desde_primer_dia_X, hasta_último_dia_Y):

Código (vbnet) [Seleccionar]
Dim directories As IEnumerable(Of DirectoryInfo) = SelectDirectories(dateDir, Me.year, monthNumber, Enumerable.Range(1, semana))

Si solo quieres seleccionar la primera semana, deberías utilizarlo así Enumerable.Range(1, 7)

Auqnue bueno, eso es como tú lo quieras hacer.

Saludos!
#4237
Windows / Re: LETREROS FASTIDIOSOS !
9 Noviembre 2015, 19:36 PM
Cita de: marmolito en  9 Noviembre 2015, 19:11 PMMás seguro que los hagas funcionar mínimo un par de veces cada uno.

Adwcleaner, JunkWare, MalwareBytes...son buenas opciones.

Añado: Y desinstalarlos en seguida, justo despues de haberlos utilizado, por el elevado consumo de memoria (y recursos) que provocaría al ya excesivo consumo de memoria que existe en el equipo en cuestión.

No conviene mantener un software antiviral en segundo plano chupando recursos en el estado de ese PC, al menos, a simple vista, sin saber la causa del consumo, si se debe a limitaciones naturales de hardware, un uso indebido por parte del usuario/a, o software malicioso que lo esté causando.




1. Descarga cualquier buen antivirus, y realiza un escaneo profundo/exhaustivo.

2. Haz una limpieza general tanto de archivos como de claves del registro, con el programa CCLEANER (no te recomiendo utilizar otro software para limpiar el registro, existe cierto nivel de peligro con otros programas que no sean el que he mencionado).

3. Con cualquier administrador de tareas, yo te recomiendo Anvir Task Manager o AutoRuns, haz un análisis a ojo de los programas y servicios que se inician junto a windows, y desactiva los que no necesites.
De esta forma deberías poder localizar el proceso que causa el mensaje de la primera imagen, si te sucede siempre al iniciar sesión en Windows significa que o bien existe un acceso directo y/o entrada en el registro de inicio de aplicaciones (run) hacia el proceso RunDll32.exe, o bien otro programa diferente que se inicia junto a windows y hace una lamada a RunDll32.exe. Y en caso de que sea un virus, pues ya lo habrás desinfectado/eliminado con las indicaciones que te dieron arriba.

4. NO ABUSES DE LAS MAYÚSCULAS, SE CONSIDERA GRITAR! :P

Saludos
#4238
Cita de: Darux en  9 Noviembre 2015, 16:58 PMque trabaje con CMD (No se si soy muy especifico), lo que quiero decir, es que no es una aplicacion con diseño, sino que al abrir el archivo .exe, se abra una ventana CMD

La definición que buscas es CLI, o Command-Line Interface (Interfáz por linea de comandos).




Cita de: Darux en  9 Noviembre 2015, 16:58 PMno se en que tipo de lenguaje esta (Si es C, C++, ya que no se a que se refiere con C#) y hay varias cosas que no entiendo y varias que hay que sacar.

No es C ni tampoco C++ ni Visual C++ (VC++), el lenguaje en el que está escrito ese código fuente es C#, también conocido como C-Sharp (por la rejilla #), el cual forma parte de los lenguajes soportados por la plataforma .Net.

Para desarrollar bajo dicho lenguaje, necesitarás una IDE como Visual Studio, habiendo otras alternativas menos importantes e ineficientes que no voy a mencionar.




Cita de: Darux en  9 Noviembre 2015, 16:58 PMsacar toda la parte de la rcon que no me interesa en el programa y ponerle la funcion que cada contraseña que "Escriba", la copie al clipboard y la pegue en otra aplicacion o juego.

No puedes hacer eso tan a la ligera. Ese código fuente está ideado para utilizar sockets como método de ataque, por ende, primero debes confirmar si puedes comunicarte mediante sockets con la aplicación a la que deseas lanzar un ataque brute-force.

Hay otras técnicas IPC (Inter-process communication) para comunicarse con otra APP, como por ejemplo los espacios de asignación de memoria compartida, o el framework de automación de .Net ( conocido como Windows UI Automation ), o lo que sería un equivalente minimalista recuerriendo a unas simples llamadas a la API de Windows para asignarle texto a un control mediante la función SendMessage y enviando el mensaje de ventana WM_SETTEXT, lo que sería la opción más corriente y viable para todo tipo de escenarios.




Cita de: Darux en  9 Noviembre 2015, 16:58 PMEl fin de hacer esto, es hackear contraseñas de un juego (Si, parezco idiota buscando esto, pero de paso aprendo a programar).

El fin no justifica los medios. Así no se aprende a programar, copiando un código aleatorio el cual ni siquiera comprendes en que lenguaje está escrito.

Si quieres aprender a programar, entonces aprende de la manera habitual, y haciéndolo de esta forma, en un punto determinado del aprendizaje llegarás a tener un nivel de conocimiento adecuado para plantearte el desarrollo de este tipo de cosas.

Aquí te podemos ayudar a aprender, pero aquí no te vamos a ayudar a conseguir "hackear cuentas", ya que hay unas reglas en el foro, las cuales deben ser respetadas, y en una de esas reglas se prohibe por completo proporcionar ayuda a cualquier tema no ético o ilegal, como es el caso.

De todas formas, te diré que si pretendes desarrollar un algoritmo brute-force yo no tomaría ese código en C# como ejemplo, como una especie de plantilla o "guía" para principiantes, ya que me llevaría a malas prácticas de programación.
Te aconsejo aprender lo básico de programación, y luego, leer y practicar el asincronismo, el paralelismo y multi-threading en .Net, lo que te llevará a desarrollar algoritmos optimizados, ya que un algoritmo de fuerza bruta debe estar minimamente optimizado.

Tema cerrado

Saludos!
#4239
Cita de: elqueteconte en  9 Noviembre 2015, 17:17 PMQuiero tambien disculparme si he cometido alguna falta al mencionar que la función la habias hecho tu, pero me pareció poco etico y profesional que yo me atribuyera algo que no me pertenece, sería un plagio.

No xD, para nada, todo lo contrario, solo que el código estaba un poco ""feo"" y yo soy muy "tiquismiquis" para ciertas cosas.

Sobre lo demás, te comentaré en privado.

Saludos!
#4240
Cita de: elqueteconte en  9 Noviembre 2015, 14:50 PMEsta función fue desarrollada por Elektro y aquí se las comparto.

Que conste que agradezco cualquier mención hacia mi persona como autor de algo, sin embargo, no quiero que se me asocie con malos hábitos de programación, en el código hay una gran ausencia de indentación, ya que lo has modificado bastante, los comentarios abusivos (y en español, cosa que lo hice para el caso) y el desorden en general que hay montado en ese bloque de código xD.




Ese método está quedando excesivamente grande. Cuanto más grande o complejo sea un método más complejo será también para el compiler/intérprete (complejidad ciclomática).

Vamos a separar el trabajo en varios métodos, primero una función para obtener los directorios, segundo un overload de esa función para poder especificar un rango de días, y por último un método para mover los directorios obtenidos.

y... voilà:

Código (vbnet) [Seleccionar]
   <DebuggerStepThrough>
   Public Iterator Function SelectDirectories(ByVal sourceDir As String,
                                              ByVal year As Integer,
                                              ByVal month As Integer,
                                              ByVal days As IEnumerable(Of Integer),
                                              ByVal dateFormat As String) As IEnumerable(Of DirectoryInfo)

       If (CStr(year).Length <> 4) Then
           Throw New ArgumentOutOfRangeException(paramName:="year",
                                                 actualvalue:=year,
                                                 message:="A value of 4 digits is required.")

       ElseIf (month < 1) OrElse (month > 12) Then
           Throw New ArgumentOutOfRangeException(paramName:="month",
                                                 actualvalue:=month,
                                                 message:="A value from range '1' to '12' is required.")

       ElseIf (dateFormat.Replace("y", "").
                          Replace("M", "").
                          Replace("d", "").Length <> 0) Then

           Throw New NotImplementedException(
               message:="Specified date format is not implemented, only 'yyyy', 'MM' and 'dd' are interchangeable.")

       ElseIf Not Directory.Exists(sourceDir) Then
           Throw New DirectoryNotFoundException(
               message:=String.Format("Source directory not found: '{0}'", sourceDir))

       End If

       Dim sourceDirInfo As New DirectoryInfo(sourceDir)

       ' Obtengo una colección con los nombres de directorio con el formato de fecha especificado.
       ' (ej. de Octubre 2015:  20151001 ... 20151031)
       Dim dateDirNames As IEnumerable(Of String) =
           From day As Integer In days
           Select dateFormat.Replace("yyyy", CStr(year)).
                             Replace("MM", CStr(month).PadLeft(2, "0"c)).
                             Replace("dd", CStr(day).PadLeft(2, "0"c))

       ' Itero y devuelvo una colección con las rutas absolutas de los directorios que cumplen los requisitos.
       For Each dirInfo As DirectoryInfo In sourceDirInfo.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)

           If dateDirNames.Contains(dirInfo.Name) Then
               Yield dirInfo
           End If

       Next

   End Function

   <DebuggerStepThrough>
   Public Function SelectDirectories(ByVal sourceDir As String,
                                     ByVal year As Integer,
                                     ByVal month As Integer,
                                     ByVal dateFormat As String) As IEnumerable(Of DirectoryInfo)

       Dim days As IEnumerable(Of Integer) = Enumerable.Range(1, DateTime.DaysInMonth(year, month))

       Return SelectDirectories(sourceDir, year, month, days, dateFormat)

   End Function

   <DebuggerStepThrough>
   Public Sub MoveDirectories(ByVal directories As IEnumerable(Of DirectoryInfo),
                              ByVal targetDir As String)

       If Not Directory.Exists(targetDir) Then
           Throw New DirectoryNotFoundException(
               message:=String.Format("Target directory not found: '{0}'", targetDir))

       Else
           Dim trgDirInfo As New DirectoryInfo(targetDir)

           For Each srcDirInfo As DirectoryInfo In directories

               If Not Directory.Exists(srcDirInfo.FullName) Then
                   Throw New DirectoryNotFoundException(
                       message:=String.Format("Source directory not found: '{0}'", srcDirInfo.FullName))
               Else
                   Debug.WriteLine(String.Format("Moviendo: {0}", srcDirInfo.FullName))
                   srcDirInfo.MoveTo(Path.Combine(trgDirInfo.FullName, srcDirInfo.Name))

               End If

           Next

       End If

   End Sub


PD: Lo he escrito al vuelo, no lo he testeado, ya no conservo la estructura de carpetas para testearlo, pero creo que no hay ninguna fisura en el código.




Ejemplo de uso:

Seleccionar las carpetas del mes entero:
Código (vbnet) [Seleccionar]
Dim directories As IEnumerable(Of DirectoryInfo) = SelectDirectories("C:\Directorio\", 2015, 11, "formato de fecha")

o de un rango de días (del día 1 al 15):
Código (vbnet) [Seleccionar]
Dim directories As IEnumerable(Of DirectoryInfo) = SelectDirectories("C:\Directorio\", 2015, 11, Enumerable.Range(1, 15), "formato de fecha")

o de ciertos dias:
Código (vbnet) [Seleccionar]
Dim directories As IEnumerable(Of DirectoryInfo) = SelectDirectories("C:\Directorio\", 2015, 11, {5, 3, 9, 12}, "formato de fecha")

y por último, mover los directorios:
Código (vbnet) [Seleccionar]
MoveDirectories(directories, "C:\Destino\")

Saludos