Obtener porcentaje de descarga desde un módulo

(1/2) > >>

okik:
Hola,

Pues aquí otra nueva duda.

No me gusta cargar demasiado de código el Form1, así que suelo poner las funciones por separado en módulos, o en módulos de clases.  El caso es que tengo un código de descarga de archivos desde un módulo y no consigo mostrar el proceso de descarga desde él.

Código
Imports System.Net
Module modDownloadURL
   Public Progress As String
   Private Sub DownloadProgressCallback(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
       Dim intBytes As Double = Double.Parse(e.BytesReceived.ToString()) 'Bytes recibidos
       Dim AllBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString()) 'Total bytes recibidos
       Dim percentage As Double = intBytes / AllBytes * 100
       Progress = CStr(e.ProgressPercentage & (" %"))
   End Sub
   Private Sub Client_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
       MessageBox.Show("Descarga completada")
   End Sub
 
   Public Sub DownLoadFileInBackground2(ByVal address As String, ByVal strDirFile As String)
       Dim Client As WebClient = New WebClient()
       AddHandler Client.DownloadProgressChanged, AddressOf DownloadProgressCallback
       AddHandler Client.DownloadFileCompleted, AddressOf client_DownloadCompleted
       Dim uri As Uri = New Uri(address)
       Client.DownloadFileAsync(uri, strDirFile)
   End Sub
End Module
 

El porcentaje se carga en la variable string Progress  , y desde un botón en el formulario llamo a DownLoadFileInBackground2(url, [Dir+Namefile]) para descargar el archivo

Gracias

Eleкtro:
Habría que analizar lo que haces con el Control de tipo Label, por que el código que has mostrado funciona.

De todas formas lo he simplificado (un poco) y he corregido varios conflictos de convención o estándares de VB.Net en los nombres que le diste a los miembros del código.

Esto te debería funcionar. Adapta el código a tus necesidades.

Código
DownLoadAsynchronously("http://download.thinkbroadband.com/5MB.zip")

Código
Module ModDownloadUrl
 
   Private WithEvents wc As WebClient
 
   Private Sub WC_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) _
   Handles wc.DownloadProgressChanged
 
       If Not e.ProgressPercentage = 100 Then
           Trace.WriteLine(String.Format("Progress: {0}", ((e.BytesReceived / e.TotalBytesToReceive) * 100.0R).ToString(format:="00.00 \%")))
       End If
 
   End Sub
 
   Private Sub WC_DownloadFileCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) _
   Handles wc.DownloadFileCompleted
 
       wc.Dispose()
       Trace.WriteLine(String.Format("Progress: {0}", 100.0R.ToString(format:="00.00 \%")))
       MessageBox.Show("Download Complete.", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
 
   End Sub
 
   Public Sub DownLoadAsynchronously(ByVal url As String,
                                     Optional ByVal targetFilepath As String = "",
                                     Optional ByVal ctrl As Control = Nothing)
 
       If String.IsNullOrWhiteSpace(targetFilepath) Then
           targetFilepath = Path.GetFileName(url)
       End If
 
       wc = New WebClient
       wc.DownloadFileAsync(New Uri(url), targetFilepath)
 
   End Sub
 
End Module

Saludos

okik:
Hola
Gracias por el código, funciona bien, pero no he conseguido que haga lo siguiente, ni aún añadiendo el opcional. Quizás es que no lo utilizo bien.

Lo que yo quería era pasar el porcentaje  a la variable Progress, para luego desde el Form capturar la información de esa variable y mostrarlo en un Label mientras se produce la descarta y en tiempo real, desde el evento Click. Pero pasa que  el label se queda en blanco. Tan solo muestra la información cuando hago esto, desde el módulo. Sustituyendo directamente la variable Progress por el control Label

Código
Private Sub DownloadProgressCallback(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
       Dim intBytes As Double = Double.Parse(e.BytesReceived.ToString()) 'Bytes recibidos
       Dim AllBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString()) 'Total bytes recibidos
       Dim percentage As Double = intBytes / AllBytes * 100
      Form1.Label1.text = CStr(e.ProgressPercentage & (" %"))
   End Sub

Con tu código quedaría así:

Código
   Private Sub WC_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles wc.DownloadProgressChanged
       If Not e.ProgressPercentage = 100 Then
           Form1.Label1.Text = String.Format("Progress: {0}", ((e.BytesReceived / e.TotalBytesToReceive) * 100.0R).ToString(format:="00.00 \%"))
       End If
   End Sub

Pero lo extraño es que la el porcentaje se para en 94%, 89%, etc. Nunca en 100%, aunque el archivo se descargue por completo. He usado el url de un archivo pequeño (el de mi avatar, el gif).

Queda corregido sustituyendo 100 por 101
Código
Not e.ProgressPercentage = 101

Probaré mañana, si puedo, creando un módulo de clase. Con la propiedad Get, creo que debería funcionar.

La idea es crear una función de código independiente y aparte sin tener que estar modificando dicho código para que devuelva la información de descarga a un determinado control.

Sl2

Eleкtro:
Cómo ya te digo, habría que ver el resto del código, por que las modificaciones que comentas en mi caso me funcionan correctamente, el label se actualiza correctamente.

De todas formas que estés utilizando un módulo para operaciones asíncronas, objetos disposables, y eventos, no me convence en absoluto, no debería causarte problemas, pero tampoco hay necesidad de que los miembros definidos en ese modulo sean compartidos con el resto de classes, por ese motivo yo usaría una Class instanciable y liberaría los objetos cuando sea necesario.

Aparte de eso, en otras circunstancias te diría que utilizases un BackgroundWorker, pero en este caso considero que sería practicamente el mismo resultado.

Prueba esto, si no te funciona entonces no sé que decirte a menos que muestres tu código completo para buscar un posible problema que en el código que has mostrado hasta ahora no aparece o no lo puedo detectar.

Así es más o menos cómo yo encapsularía esos datos:

Código
#Region " Imports "
 
Imports System
Imports System.ComponentModel
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Windows.Forms
Imports System.Threading.Tasks
 
#End Region
 
Public NotInheritable Class FileDownloader : Implements IDisposable
 
#Region " Disposable Members "
 
   Private WithEvents wc As WebClient
 
#End Region
 
#Region " Properties "
 
   Public ReadOnly Property IsBusy As Boolean
       Get
           If Me.wc IsNot Nothing Then
               Return Me.wc.IsBusy
           Else
               Return False
           End If
       End Get
   End Property
 
#End Region
 
#Region " Events "
 
   Public Event DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
   Public Event DownloadCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
 
#End Region
 
#Region " Event-Handlers "
 
   Private Sub WC_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) _
   Handles wc.DownloadProgressChanged
 
       If (Me.DownloadProgressChangedEvent IsNot Nothing) AndAlso (e.ProgressPercentage <> 100) Then
           RaiseEvent DownloadProgressChanged(sender, e)
       End If
 
   End Sub
 
   Private Sub WC_DownloadFileCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) _
   Handles wc.DownloadFileCompleted
 
       If (Me.DownloadCompletedEvent IsNot Nothing) Then
           RaiseEvent DownloadCompleted(sender, e)
       End If
 
   End Sub
 
#End Region
 
#Region " Public Methods "
 
   Public Sub DownloadAsync(ByVal url As String,
                            Optional ByVal targetFilepath As String = "")
 
       If String.IsNullOrWhiteSpace(url) Then
           Throw New ArgumentNullException(paramName:="url")
 
       Else
 
           If (Me.wc IsNot Nothing) AndAlso (Me.wc.IsBusy) Then
               Throw New Exception(message:="Another download is in progress.")
 
           Else
               Me.wc = New WebClient With
                {
                    .UseDefaultCredentials = True
                }
 
               If String.IsNullOrWhiteSpace(targetFilepath) Then
                   targetFilepath = Path.GetFileName(url)
               End If
 
               Task.Factory.StartNew(Sub() wc.DownloadFileAsync(New Uri(url), targetFilepath))
 
           End If
 
       End If
 
   End Sub
 
   ''' <summary>
   ''' Cancels the current asynchronous download.
   ''' </summary>
   Public Sub Cancel()
 
       If Me.wc Is Nothing Then
           Throw New NullReferenceException(message:="", innerException:=New ObjectDisposedException(objectName:="wc"))
 
       ElseIf Me.wc.IsBusy Then
           Me.wc.CancelAsync()
 
       End If
 
   End Sub
 
#End Region
 
#Region "IDisposable Support"
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' To detect redundant calls when disposing.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Private isDisposed As Boolean = False
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Public Sub Dispose() Implements IDisposable.Dispose
       Me.Dispose(isDisposing:=True)
       GC.SuppressFinalize(obj:=Me)
   End Sub
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Releases unmanaged and - optionally - managed resources.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="isDisposing">
   ''' <c>True</c> to release both managed and unmanaged resources;
   ''' <c>False</c> to release only unmanaged resources.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   Protected Sub Dispose(ByVal isDisposing As Boolean)
 
       If Not Me.isDisposed Then
 
           If isDisposing Then
 
               If Me.wc IsNot Nothing Then
                   Me.wc.Dispose()
               End If
 
           End If
 
       End If
 
       Me.isDisposed = True
 
   End Sub
 
#End Region
 
End Class

Y el uso que le daría ...más o menos también:

Código
Imports System.ComponentModel
Imports System.Threading.Tasks
 
Public NotInheritable Class Form1 : Inherits Form
 
   Dim WithEvents downloader As New FileDownloader
 
   Private Sub Test() Handles MyBase.Shown
 
       Me.downloader.DownloadAsync("http://download.thinkbroadband.com/10MB.zip")
 
   End Sub
 
   Private Sub Button1_Click(sender As Object, e As EventArgs) _
   Handles Button1.Click
 
       If Me.downloader.IsBusy Then
           Me.downloader.Cancel()
       End If
 
   End Sub
 
   Private Sub Downloader_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) _
   Handles downloader.DownloadProgressChanged
 
       Dim progress As Double = (e.BytesReceived / e.TotalBytesToReceive) * 100.0R
 
       If Me.Label1.InvokeRequired Then
           Me.Label1.Invoke(Sub() Me.Label1.Text = progress.ToString(format:="00.00 \%"))
 
       Else
           Me.Label1.Text = progress.ToString(format:="00.00 \%")
 
       End If
 
   End Sub
 
   Private Sub Downloader_DownloadCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) _
   Handles downloader.DownloadCompleted
 
       If e.Cancelled Then
           Exit Sub
       End If
 
       If Me.Label1.InvokeRequired Then
           Me.Label1.Invoke(Sub() Me.Label1.Text = 100.0R.ToString(format:="00.00 \%"))
 
       Else
           Me.Label1.Text = 100.0R.ToString(format:="00.00 \%")
 
       End If
 
   End Sub
 
End Class

Saludos.

okik:
Eres un maestro

Lo que busco es tan simple como esto, y te juro que el label se queda en blanco, la verdad que no lo entiendo

Código
Public Class Form1
 
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim ns As New modDownloadURL
       ns.DownLoadFileInBackground2("http://3.bp.blogspot.com/-08K8K-44ouk/VYg40YxJvxI/AAAAAAAAARw/wrLQDfGDW-8/s1600/OKIK2.gif", _
"E:\jk.gif")
       Label1.Text = ns.getProgress
   End Sub
End Class
 
Class modDownloadURL
   Public Progress As Object
   Private Sub DownloadProgressCallback(ByVal sender As Object, _
ByVal e As System.Net.DownloadProgressChangedEventArgs)
       Dim intBytes As Double = Double.Parse(e.BytesReceived.ToString()) 'Bytes recibidos
       Dim AllBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString()) 'Total bytes recibidos
       Dim percentage As Double = intBytes / AllBytes * 100
       Progress = (e.ProgressPercentage & (" %"))
   End Sub
   Private Sub Client_DownloadCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
       MessageBox.Show("Descarga completada")
   End Sub
 
   Public Sub DownLoadFileInBackground2(ByVal address As String, _
ByVal strDirFile As String)
       Dim Client As System.Net.WebClient = New System.Net.WebClient()
       AddHandler Client.DownloadProgressChanged, AddressOf DownloadProgressCallback
       AddHandler Client.DownloadFileCompleted, AddressOf Client_DownloadCompleted
       Dim uri As Uri = New Uri(address)
       Client.DownloadFileAsync(uri, strDirFile)
   End Sub
   ReadOnly Property getProgress() As String
       Get
           Return Progress
       End Get
   End Property
 
End Class

Me ha gustado tu opción de cancelar, también buscaba eso...

Navegación

[0] Índice de Mensajes

[#] Página Siguiente