IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

[VB.NET]Gestion évènement dans un download FTP


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Avril 2013
    Messages : 57
    Par défaut [VB.NET]Gestion évènement dans un download FTP
    Bonjour,

    Je suis actuellement en stage et je dois télécharger un fichier d'un serveur ftp. Ma fonction fonctionne cependant, je dois faire la gestion d'évenement : Downloading et Download completed. Ainsi via une progressbar j'aurai l'avancement de mon téléchargment. J'ai essayé de gérer mais ces évènements mais ceci ne fonctionne pas du tout . Voici mon code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
     
    Public Class FtpManager
     
     
        'Création d'un délegué
        Public Delegate Sub FileManagerEventHandler(ByVal sender As Object, ByVal e As FtpEventArgs)
        'Evènements
        Public Event Downloading As FileManagerEventHandler
        Public Event DownloadCompleted As FileManagerEventHandler
     
     
     
        Public Sub FtpDownload(ByVal user As String, ByVal password As String, ByVal source As String, ByVal cible As String)
            Dim uri As New Uri(source)
     
            Dim request As FtpWebRequest = DirectCast(WebRequest.Create(uri), FtpWebRequest)
            request.Credentials = New NetworkCredential(user, password)
            request.UseBinary = True
            request.Method = WebRequestMethods.Ftp.DownloadFile
            'Utilisé pour envoyer la commande "QUIT" au serveur afin de fermer correctement la connexion
            request.KeepAlive = False
     
            ' Variable de mesure de la taille du morceau de fichier lu. Permet d'indiquer que le fichier a été lu et écrit en totalité.
            ' Recupération de la réponse
            Dim res As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
            'fi = New FileInfo(String.Concat(source, uri.Segments(uri.Segments.Length - 1))
            Dim stream As Stream = (res.GetResponseStream())
            Dim writeStream As New FileStream(cible, FileMode.Create)
     
            ' Taille du tableau servant à stocker les morceaux du fichier.
            ' On épargne ainsi les ressources du serveur en ne chargeant pas la totalité du fichier.
            ' Cela permet de transférer rapidement des fichiers volumineux.
            Dim buffer As [Byte]() = New [Byte](2048) {}
            Dim bytesRead As Integer = stream.Read(buffer, 0, 2048)
            Dim test As New FileInfo(source)
            Dim totalByte As Double = test.Length
            Dim pourcentage As Double = 0
     
            While bytesRead > 0
                pourcentage = bytesRead / totalByte * 100
                Dim t As FtpEventArgs = New FtpEventArgs(pourcentage)
                If Not t Is Nothing Then
                    RaiseEvent Downloading(Me, t)
                End If
                writeStream.Write(buffer, 0, bytesRead)
                bytesRead = stream.Read(buffer, 0, 2048)
            End While
            Dim e As FtpEventArgs = New FtpEventArgs("Download completed")
            If Not e Is Nothing Then
                RaiseEvent DownloadCompleted(Me, e)
            End If
            writeStream.Close()
            stream.Close()
     
     
        End Sub
     
    End Class
     
    Public Class FtpEventArgs
        Inherits EventArgs
     
        Private _pourcentage As Double
        Public Property POURCENTAGE() As Double
            Get
                Return _pourcentage
            End Get
            Set(ByVal value As Double)
                _pourcentage = value
            End Set
        End Property
     
        Public Sub New(ByVal theEventText As Double)
            POURCENTAGE = theEventText
        End Sub
     
        Public Sub completeDownload(ByVal pourcentage As String)
            If pourcentage.Contains("100%") Or pourcentage.Contains("Download Completed") Then
                MsgBox("Download Completed")
            End If
        End Sub
    End Class
    ps: je n'arrive pas non a avoir la taille du fichier que je télécharge

    cordialement,
    Kévin

  2. #2
    Membre chevronné Avatar de Vince
    Profil pro
    Inscrit en
    Mars 2002
    Messages
    369
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2002
    Messages : 369

  3. #3
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Avril 2013
    Messages : 57
    Par défaut
    Oui excusez moi mais je ne savais pas comment déplacer mon post dans cette partie du forum.

  4. #4
    Membre Expert
    Homme Profil pro
    Développeur .Net / Delphi
    Inscrit en
    Juillet 2002
    Messages
    738
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .Net / Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Juillet 2002
    Messages : 738
    Par défaut
    Bonjour,

    FtpEventArgs est un argument qui pourra être utilisé par l'abonné à l'évènement.
    Tu peux simplifier
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    Dim t As FtpEventArgs = New FtpEventArgs(pourcentage)
                If Not t Is Nothing Then
                    RaiseEvent Downloading(Me, t)
                End If
    par :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    RaiseEvent Downloading(Me,New FtpEventArgs(pourcentage))
    Concernant cet évènement, ça devrait fonctionner. Quand tu dis que ça ne marche pas, ça veut dire quoi ? Comment t'abonnes-tu à cet event.

    Autre chose, la méthode FtpEventArgs.completeDownload me paraît mal placée... C'est l'abonné qui va l'appeler lors du déclenchement de l'event ?

    Bon courage.
    eb.

  5. #5
    Modérateur
    Avatar de DotNetMatt
    Homme Profil pro
    CTO
    Inscrit en
    Février 2010
    Messages
    3 611
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : CTO
    Secteur : Finance

    Informations forums :
    Inscription : Février 2010
    Messages : 3 611
    Billets dans le blog
    3
    Par défaut
    A mon avis tu fais trop compliqué, on peut faire ce que tu veux en utilisant un BackgroundWorker. Voici une implémentation :

    Tout d'abord la classe DownloadManager (DownloadManager.vb) :
    Code VB.NET : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    Public Class DownloadManager
    	Private _bw As BackgroundWorker
    	Private _progressBar As ProgressBar
    	Private _user As String
    	Private _password As String
    	Private _source As String
    	Private _cible As String
     
    	''' <summary>
    	''' Sets the ProgressBar object.
    	''' </summary>
    	Public WriteOnly Property ProgressBar() As ProgressBar
    		Set
    			Me._progressBar = value
    		End Set
    	End Property
     
    	Public Sub New(user As String, password As String, source As String, cible As String)
    		Me._user = user
    		Me._password = password
    		Me._source = source
    		Me._cible = cible
    		Me._bw = New BackgroundWorker()
    		Me._bw.WorkerReportsProgress = True
    		Me._bw.WorkerSupportsCancellation = True
     
    		Me._bw.DoWork += New DoWorkEventHandler(_bw_DoWork)
    		Me._bw.ProgressChanged += New ProgressChangedEventHandler(_bw_ProgressChanged)
    		Me._bw.RunWorkerCompleted += New RunWorkerCompletedEventHandler(_bw_RunWorkerCompleted)
    	End Sub
     
    	''' <summary>
    	''' Starts the async operation.
    	''' </summary>
    	Public Sub StartDownloadAsync()
    		Me._bw.RunWorkerAsync()
    	End Sub
     
    	''' <summary>
    	''' Cancels the async operation.
    	''' </summary>
    	Public Sub CancelDownloadAsync()
    		If Me._bw.IsBusy Then
    			Me._bw.CancelAsync()
    		End If
    	End Sub
     
    	''' <summary>
    	''' Display a message on async operation completed.
    	''' </summary>
    	Private Sub _bw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
    		If e.Cancelled Then
    			MessageBox.Show("Operation has been cancelled.")
    		ElseIf e.[Error] IsNot Nothing Then
    			MessageBox.Show("An error occured:" + e.[Error].Message)
    		Else
    			Me._progressBar.Value = 100
    			MessageBox.Show("Operation successfuly completed.")
    		End If
    	End Sub
     
    	''' <summary>
    	''' Report async operation progress changed.
    	''' </summary>
    	Private Sub _bw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
    		Me._progressBar.Value = e.ProgressPercentage
    	End Sub
     
    	''' <summary>
    	''' Download the file.
    	''' </summary>
    	Private Sub _bw_DoWork(sender As Object, e As DoWorkEventArgs)
    		' Get the size of the file to download
    		Dim url = New Uri(Me._source)
     
    		Dim request = DirectCast(WebRequest.Create(url), HttpWebRequest)
    		Dim response = DirectCast(request.GetResponse(), HttpWebResponse)
    		response.Close()
     
    		' Gets file size
    		Dim sourceFileSize = response.ContentLength
     
    		' Stores total downloaded bytes in order to allow progress reporting
    		Dim totalBytesDownloaded As Long = 0
     
    		' Download the file using a WebClient object
    		Using webClient = New WebClient()
    			' Open source file and read it
    			Using stream = webClient.OpenRead(url)
    				' Write downloaded bytes to hard drive
    				Using fileStream = New FileStream(Me._cible, FileMode.Create, FileAccess.Write, FileShare.None)
    					' Get file into buffer
    					Dim bufferSize = 0
    					Dim buffer = New Byte(sourceFileSize - 1) {}
    					While (InlineAssignHelper(bufferSize, stream.Read(buffer, 0, buffer.Length))) > 0
    						fileStream.Write(buffer, 0, bufferSize)
    						totalBytesDownloaded += bufferSize
     
    						' Compute progress in base 100
    						Dim index = CDbl(totalBytesDownloaded)
    						Dim total = CDbl(buffer.Length)
    						Dim progressPercentage As Double = (index / total)
    						Dim progress = CInt(progressPercentage * 100)
     
    						' Report progress
    						Me._bw.ReportProgress(progress)
    					End While
    				End Using
    			End Using
    		End Using
    	End Sub
    	Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
    		target = value
    		Return value
    	End Function
    End Class

    Sur le formulaire, rajouter une ProgressBar (progressBar1) et deux boutons (btnStart et btnCancel) :
    Code VB.NET : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    Public Partial Class Form1
    	Inherits Form
    	Private _downloaderAsync As DownloadManager
     
    	Public Sub New()
    		InitializeComponent()
     
    		Me._downloaderAsync = New DownloadManager("", "", "http://download.microsoft.com/download/9/b/3/9b37f157-123d-41fd-a3f4-f4aedd0cc847/Office2003SP2-KB887616-Client-ENU.exe", "Office2003SP2-KB887616-Client-ENU.exe")
    		Me._downloaderAsync.ProgressBar = Me.progressBar1
    	End Sub
     
    	Private Sub btnStart_Click(sender As Object, e As EventArgs)
    		Me._downloaderAsync.StartDownloadAsync()
     
    		Me.btnStart.Enabled = False
    		Me.btnCancel.Enabled = True
    	End Sub
     
    	Private Sub btnCancel_Click(sender As Object, e As EventArgs)
    		Me._downloaderAsync.CancelDownloadAsync()
     
    		Me.btnStart.Enabled = True
    		Me.btnCancel.Enabled = False
    	End Sub
    End Class
    Le fichier qui est téléchargé est Office 2003 Service Pack 2 (SP2), qui pèse ~50 Mo.

    Je n'ai pas repris totalement ton code, donc il y a sûrement des choses à adapter mais tu as déjà l'idée.
    Less Is More
    Pensez à utiliser les boutons , et les balises code
    Desole pour l'absence d'accents, clavier US oblige
    Celui qui pense qu'un professionnel coute cher n'a aucune idee de ce que peut lui couter un incompetent.

  6. #6
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Avril 2013
    Messages : 57
    Par défaut
    Bonjour,


    Tout d'abord merci a vous deux pour votre intérêt pour cette discussion.
    DotNetMatt ta solution me paraît etre la plus adapter pour mes besoin. Malheureusement, je ne peux pas l'essayer aujourd'hui car je suis sur un autre projet, de ce fait je te tiendrais au courant de l'évolution de ce problème vendredi.

    Cordialement,
    Kévin

  7. #7
    Membre Expert
    Homme Profil pro
    Développeur .Net / Delphi
    Inscrit en
    Juillet 2002
    Messages
    738
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .Net / Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Juillet 2002
    Messages : 738
    Par défaut
    Bonjour,
    Ok avec la solution de DotNetMatt.
    Un petit détail juste :
    Citation Envoyé par DotNetMatt Voir le message
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Me._bw.DoWork += New DoWorkEventHandler(_bw_DoWork)
    C'est la syntaxe C#. En VB.NET :
    Code VB.NET : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    AddHandler Me._bw.DoWork, AddressOf _bw_DoWork
    eb.

  8. #8
    Modérateur
    Avatar de DotNetMatt
    Homme Profil pro
    CTO
    Inscrit en
    Février 2010
    Messages
    3 611
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : CTO
    Secteur : Finance

    Informations forums :
    Inscription : Février 2010
    Messages : 3 611
    Billets dans le blog
    3
    Par défaut
    Effectivement merci pour la correction

    Je l'avais codé en C# et j'ai utilisé un outil de conversion, mais il a dû laisser passer ça
    Less Is More
    Pensez à utiliser les boutons , et les balises code
    Desole pour l'absence d'accents, clavier US oblige
    Celui qui pense qu'un professionnel coute cher n'a aucune idee de ce que peut lui couter un incompetent.

Discussions similaires

  1. [VB.NET]Gestion évènement dans un download FTP
    Par kevin01330 dans le forum Général Dotnet
    Réponses: 0
    Dernier message: 24/04/2013, 12h19
  2. [VB.NEt/CF] Conflit dll mscorlib dans mon projet ftp
    Par sane79 dans le forum Windows Mobile
    Réponses: 3
    Dernier message: 03/11/2006, 08h26
  3. [VB.NET]Gestion de radioButton dans une GroupBox
    Par Yeti_in dans le forum Windows Forms
    Réponses: 1
    Dernier message: 24/05/2006, 09h06
  4. [PHP-JS] Gestion des évènements dans PHP
    Par haffouff dans le forum Langage
    Réponses: 5
    Dernier message: 25/04/2006, 18h51
  5. [MFC][VC++.NET]gestion évènement clavier
    Par Rafoo dans le forum MFC
    Réponses: 2
    Dernier message: 14/12/2005, 09h29

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo