Results 1 to 9 of 9

Thread: Display images from a FTP folder in datagridview cell

  1. #1

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,205

    Display images from a FTP folder in datagridview cell

    http://www.vbforums.com/showthread.p...b-net-win-app)this post is the linked continue of the this thread, Saving images in the database.

    I Chosen to store the images in the FTP server than into the MySQL database, and that's fine, I am struck in display of the image(s) of any particular UNIQUE case from a FTP folder on to the datagridview cell.

    Here the case documents contains not only images but the Excel, Pdf, Word and Ppt documents too.
    there fore I decided to follow the sequence steps like this

    1) Down load all the images and office files pertaining to the selected case from FTP to the clients local system, Of course
    only if the file not exists in the clients local folder.


    2) Then display the images in the datagridview cell from the local folder
    3) For office files just display an icon or png image in the datagridview cell

    The Pit falls Here I guess is
    (a) in the above approach I need to delete the local client folder image, if I delete the file in the FTP
    (b) What if the files are deleted from other client(s),

    I need advice, how this is being handled by professionals (I often see this kind of app like in Amazon Apps.. etc)
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,895

    Re: Display images from a FTP folder in datagridview cell

    There's probably no point to downloading the files locally and then loading them from there. You can download the file data directly into your application and store it in the DataTable that is bound to the grid and it will display. That gets rid of any synchronisation issues. Here's a quick example of how it might be done:
    vb.net Code:
    1. Imports System.ComponentModel
    2. Imports System.Data.SqlClient
    3. Imports System.Net
    4.  
    5. Public Class Form1
    6.  
    7.     Private table As New DataTable
    8.  
    9.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    10.         Using adapter As New SqlDataAdapter("SQL query here", "connection string here")
    11.             adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
    12.             adapter.Fill(table)
    13.         End Using
    14.  
    15.         'Add a column for the images.
    16.         table.Columns.Add("Image", GetType(Byte()))
    17.  
    18.         BindingSource1.DataSource = table
    19.  
    20.         'Don't automatically generate columns so that the column containing the file name is not shown.
    21.         'This means creating the required columns in the designer and setting the DataPropertyName of each.
    22.         DataGridView1.AutoGenerateColumns = False
    23.  
    24.         DataGridView1.DataSource = BindingSource1
    25.  
    26.         'Load images in the background, which means that they will appear in the grid as they are downloaded.
    27.         BackgroundWorker1.RunWorkerAsync()
    28.     End Sub
    29.  
    30.     Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    31.         Dim baseUrl = "FTP folder URL here"
    32.         Dim downloader As New WebClient
    33.  
    34.         For Each row As DataRow In table.Rows
    35.             Dim id = CInt(row("Id"))
    36.             Dim fileName = CStr(row("FileName"))
    37.             Dim fileUrl = baseUrl & fileName
    38.             Dim fileData = downloader.DownloadData(fileUrl)
    39.  
    40.             BackgroundWorker1.ReportProgress(id, fileData)
    41.         Next
    42.     End Sub
    43.  
    44.     Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    45.         Dim id = e.ProgressPercentage
    46.         Dim fileData = DirectCast(e.UserState, Byte())
    47.         Dim row = table.Rows.Find(id)
    48.  
    49.         row("Image") = fileData
    50.     End Sub
    51.  
    52. End Class

  3. #3

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,205

    Re: Display images from a FTP folder in datagridview cell

    Sir
    Thanks for the reply,
    I have a problem here I need to download and display the file, only if the file is an image
    I need to do it before I could down load the image stream from the FTP to just to save the resources
    .
    since after been download the file data and then check it's a image/not then bind the Image column, in this approach invariably I have to download the file data.

    advice please sir
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,895

    Re: Display images from a FTP folder in datagridview cell

    Quote Originally Posted by make me rain View Post
    in this approach invariably I have to download the file data.
    Um, no. I said:
    Here's a quick example of how it might be done
    If you need to add some logic then add some logic. I'm not stopping you. It sounds like you simply need to add an If statement inside the For Each loop to determine whether the associated file is an image. That's for you to decide and implement. I'm just showing you how to do what you asked for, not giving you a turnkey solution to copy and paste. If you want to display a different image for non-image files then obviously you need to use a Byte array containing the data for that other image. How you get that is up to you.

  5. #5

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,205

    Re: Display images from a FTP folder in datagridview cell

    Sir
    How can i get the progress percentage of file uploading And display in the progress bar, which object does this job
    here is my code

    PrivateSub BckgWkr_DoWork(sender AsObject, e As System.ComponentModel.DoWorkEventArgs) Handles BckgWkr.DoWork

    Dim ByteArray() As Byte = File.ReadAllBytes(_UPLOADINGFILEPATH)
    Dim Fc As New FtpClient(_HOST, "remoteclient", "remoteclient")

    '' Check file size
    Dim Fi As New FileInfo(_UPLOADINGFILEPATH)

    '' Restrict file size
    If Fi.Length > 3072 * 1000 Then '' 1024*3mb
    InfoMsg("File size must be 3MB maximum & Current size is " & Math.Round(Fi.Length / 1000, 2))
    Exit Sub
    End If

    '' Check FTP directory exists
    If Fc.DirectoryExists(_ACCID) = False Then
    Fc.CreateDirectory(_ACCID)
    End If

    Dim Wc As New WebClient
    With Wc
    .Credentials = New NetworkCredential(_HOST, "remoteclient", "remoteclient")

    '' How do i get the Numeric value for the progress here

    BckgWkr.ReportProgress(.UploadData(_UPLOADINGFILE_FTPSERVERPATH, ByteArray).Length)

    End With
    e.Result = ByteArray.Length()

    EndSub

    Private Sub BckgWkr_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles

    '' this doing nothing
    TsPbar.Value = e.ProgressPercentage

    End Sub
    Last edited by make me rain; Jul 31st, 2018 at 12:08 AM.
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,895

    Re: Display images from a FTP folder in datagridview cell

    That last question has nothing to do with the topic of this thread and belongs in its own thread with a title that reflects that topic. That said, what do you not understand about the information you found when you did the obvious thing and searched the web for "vb.net file upload progress webclient" or the like?

  7. #7

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,205

    Re: Display images from a FTP folder in datagridview cell

    Sir
    while i do the download using Webclient & do display images in the datagridview image cell, the DownloadDataCompleted event is not triggering, what i am doing wrong here


    vb.net Code:
    1. Imports System.IOImports System.Net
    2.  
    3.  
    4. Public Class LoadImages
    5.  
    6.  
    7.     Dim WithEvents Wclinet As New WebClient
    8.     Private Property _DOWNLOADEDBYTE As Byte() = Nothing
    9.  
    10.  
    11.     Private Sub GetAndLoadFiledata(FTPfileAdress As String, RowId As Int16)
    12.  
    13.  
    14.         '' Download the file data from FTP
    15.         Dim Ae As New AESencryptionProvider(My.Settings.IP, True)
    16.         Dim _HOST As String = Ae.DecryptedOutput
    17.  
    18.  
    19.         Dim URLsource As String = String.Format("ftp://{0}/remoteclient:remoteclient{1}", _HOST, FTPfileAdress).Replace("", "/")
    20.         Dim URL As New Uri(URLsource)
    21.  
    22.  
    23.         AddHandler Wclinet.DownloadProgressChanged, AddressOf DownloadProgressCallBack
    24.         AddHandler Wclinet.DownloadDataCompleted, AddressOf DownloadDataCompletedCallBack '' event not triggered
    25.  
    26.  
    27.         With Wclinet
    28.             .DownloadDataAsync(URL)
    29.         End With
    30.  
    31.  
    32.         '' set image
    33.         '' since the DownloadDataCompletedCallBack is not triggered
    34.         '' _DOWNLOADEDBYTE is always nothing
    35.         '' & hence getting error buffer is null
    36.  
    37.  
    38.         Dim Fs As MemoryStream = New MemoryStream(_DOWNLOADEDBYTE)
    39.         Dim Img As Image
    40.  
    41.  
    42.         Try
    43.             '' bind the image to image cell on demand
    44.             '' only if the stream is valid image
    45.             '' else exit
    46.  
    47.  
    48.             Img = Image.FromStream(Fs)
    49.             With Dgv_LoadProffs
    50.                 .Rows(RowId).Cells("DocumentImage").Value = Img
    51.             End With
    52.         Catch ex As Exception
    53.             '' else exit sub
    54.         End Try
    55.  
    56.  
    57.     End Sub
    58.  
    59.  
    60.     Private Sub DownloadProgressCallBack(sender As Object, e As DownloadProgressChangedEventArgs)
    61.  
    62.  
    63.         TsPbar.Value = e.ProgressPercentage '' toolstrip progress bar set progress
    64.  
    65.  
    66.     End Sub
    67.     Private Sub DownloadDataCompletedCallBack(sender As Object, e As DownloadDataCompletedEventArgs)
    68.  
    69.  
    70.         '' this sub is not firing
    71.  
    72.  
    73.         If Not e.Cancelled Then
    74.             _DOWNLOADEDBYTE = e.Result
    75.             TsPbar.Value = 0 '' toolstrip progress bar set progress
    76.         Else
    77.             _DOWNLOADEDBYTE = Nothing
    78.         End If
    79.  
    80.  
    81.     End Sub
    82. End Class
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,895

    Re: Display images from a FTP folder in datagridview cell

    Why are you using AddHandler at all when you've declared the Wclinet field WithEvents? The whole point of doing that is so that you can use a Handles clause. I'd make that change and see if you still have the same issue, although I'm not sure why you would in either case.

    The structure of your code is wrong though. You call DownloadDataAsync and then immediately try to use _DOWNLOADEDBYTE. The whole point of an async method is that it carries on in the background. The data is not available until the Completed event is raised. You get the data in that event handler and then use it. I imagine that that is related to your issue but it's hard to tell. Frankly, that code doesn't make much sense as it is. How are you trying to use it?

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,895

    Re: Display images from a FTP folder in datagridview cell

    I haven't tested this but this is the sort of thing that would make sense to me:
    vb.net Code:
    1. Private ReadOnly bytesReceivedById As New Dictionary(Of Integer, Long)
    2. Private totalBytesToReceive As Long
    3. Private ReadOnly table As New DataTable
    4.  
    5. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    6.     Using adapter As New SqlDataAdapter("SQL query here", "connection string here")
    7.         adapter.Fill(table)
    8.     End Using
    9.  
    10.     table.Columns.Add("Image", GetType(Byte()))
    11.  
    12.     DataGridView1.DataSource = table
    13.  
    14.     'Start a download for each row.
    15.     For Each row As DataRow In table.Rows
    16.         Dim client As New WebClient
    17.  
    18.         'Handle pertinent events.
    19.         AddHandler client.DownloadProgressChanged, AddressOf WebClient_DownloadProgressChanged
    20.         AddHandler client.DownloadDataCompleted, AddressOf WebClient_DownloadDataCompleted
    21.  
    22.         'Identify each download with the record ID.
    23.         client.DownloadDataAsync(New Uri(CStr(row("URL"))), row("ID"))
    24.     Next
    25. End Sub
    26.  
    27. Private Sub WebClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
    28.     'Update the progress on the UI thread.
    29.     BeginInvoke(New Action(Of Integer, Long, Long)(AddressOf UpdateProgress),
    30.                 {CInt(e.UserState), e.BytesReceived, e.TotalBytesToReceive})
    31. End Sub
    32.  
    33. Private Sub WebClient_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
    34.     'Update the DataTable on the UI thread because it is bound to a DataGridView, which is a control.
    35.     BeginInvoke(New Action(Of Integer, Byte())(AddressOf SetImage),
    36.                 {CInt(e.UserState), e.Result})
    37.  
    38.     Dim client = DirectCast(sender, WebClient)
    39.  
    40.     'Unregister event handlers.
    41.     RemoveHandler client.DownloadProgressChanged, AddressOf WebClient_DownloadProgressChanged
    42.     RemoveHandler client.DownloadDataCompleted, AddressOf WebClient_DownloadDataCompleted
    43. End Sub
    44.  
    45. Private Sub UpdateProgress(id As Integer, bytesReceived As Long, totalBytesToReceive As Long)
    46.     If Not bytesReceivedById.ContainsKey(id) Then
    47.         'This is the first progress event for this download.
    48.         bytesReceivedById.Add(id, bytesReceived)
    49.         Me.totalBytesToReceive += totalBytesToReceive
    50.     Else
    51.         'Update progress for existing download.
    52.         bytesReceivedById(id) = bytesReceived
    53.     End If
    54.  
    55.     'Calculate the percentage for all downloads combined.
    56.     Dim progressPercent = bytesReceivedById.Values.Sum() / Me.totalBytesToReceive * 100L
    57.  
    58.     ProgressBar1.Value = CInt(progressPercent)
    59. End Sub
    60.  
    61. Private Sub SetImage(id As Integer, img As Byte())
    62.     Dim row = table.Rows.Find(id)
    63.  
    64.     row("Image") = img
    65. End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width