none
Read text file in Droupbox using vb.net 2013 RRS feed

  • Question

  • Hi Friends,

    I need help to read text file located on droupbox using vb.net. my text file (https://www.dropbox.com/s/izc0xrq0jpctt02/Version.txt?dl=0) is here. there is version no 1.0.0.0 i need code for read this text from vb.net please help me 


    RohanD

    Sunday, July 2, 2017 7:17 PM

All replies

  • Hi Rohan,

    The REST API is a good place for you to start reading.

    Dim myWebClient As New System.Net.WebClient
            Dim file As New System.IO.StreamReader(myWebClient.OpenRead("https://www.dropbox.com/s/yfarlrua18vbajo/PRUEBA.txt?dl=1"))
            RichTextBox1.Text = file.ReadToEnd()
            file.Close()

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, July 4, 2017 2:55 AM
    Moderator
  • That file isn’t here anymore 
    Someone might’ve deleted the file or disabled the link.

    That being said, Dropbox has an API, using anything else may be a TOS violation


    • Edited by Devon_Nullman Wednesday, July 5, 2017 12:37 AM Added Link to API
    Wednesday, July 5, 2017 12:35 AM
  • Thank you But Same as Result,,,,,,

    RohanD


    • Edited by RAT_SL Wednesday, July 5, 2017 5:48 PM Not working
    Wednesday, July 5, 2017 5:37 PM
  • Thank you, I installed DB.API as you say, but not working..

    RohanD

    Wednesday, July 5, 2017 5:37 PM
  • Rohan,


    I have an idea, albeit not an answer about Dropbox.

    I don't use DropBox (or any like it) because I don't need it; I have several websites of my own. One in particular - that I pay the most for - is FTP only and that's the most reliable one of the bunch and the one I have in mind to use here.

    Given that there's no HTTP at all, obviously HTTP methods won't work so I'll have to build something to give you access to your stuff on my server.

    It'll be long in the making (particularly given that I have a real job after all), but if you're willing to be patient and you'll work with me to help develop it, I'm game to give you the space and get you set up to give your program the ability to check and install updates.

    Give it some thought and let me know please.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    • Marked as answer by RAT_SL Wednesday, July 5, 2017 7:06 PM
    • Unmarked as answer by RAT_SL Wednesday, July 5, 2017 7:16 PM
    Wednesday, July 5, 2017 6:40 PM
  • HI,

    Thank you for your helping. but i'm try to learn vb.net. if you can help me to learn this i like to be your student. and i never forget your help.... thank you again 


    RohanD

    Wednesday, July 5, 2017 7:01 PM
  • HI,

    Thank you for your helping. but i'm try to learn vb.net. if you can help me to learn this i like to be your student. and i never forget your help.... thank you again 


    RohanD

    I presume that you're talking to me? We don't all see this forum the same way so I can't tell.

    *****

    How about please un-mark me as the answerer -- I didn't answer anything!

    I'm not sure what you mean here though. Do you want to pursue this or do you want to stay with DropBox? I don't know the first thing about DropBox if that's the case.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, July 5, 2017 7:10 PM
  • Dear Sir,

    is there any other way to can i text with you...please 


    RohanD

    Wednesday, July 5, 2017 7:17 PM
  • I need learn without sleeping :)

    RohanD

    Wednesday, July 5, 2017 7:18 PM
  • Dear Sir,

    is there any other way to can i text with you...please 


    RohanD

    Rohan,

    Just call me Frank and I'll know you're talking to me (or quote what I said -- something so that I can tell). We can talk here - it's all a big community really.

    If you want to go the way that I have in mind then that's great - I want to pursue it also but I'm at work right now and I can't spend the time on it.

    I'll put some thought into the generalities and reply back tomorrow or Friday (I'm in the US, CDT).


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, July 5, 2017 7:22 PM
  • Thank you Mr. Frank. and please inform me when you are free... 1am here :) (UTC+05:30) Sri Lanka

    RohanD


    • Edited by RAT_SL Wednesday, July 5, 2017 7:27 PM
    Wednesday, July 5, 2017 7:25 PM
  • Thank you Mr. Frank. and please inform me when you are free... 1am here :) (UTC+05:30) Sri Lanka

    RohanD


    You're about 11 hours ahead of me then.

    *****

    I'll figure out what needs to be done as we work through this. I have some ideas but not a complete thought really.

    Tell me what you have in mind? Do you have a program created and distributed to people and now you have an update or just what's this for?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 6, 2017 12:52 PM
  • :)

    I plan to create IT Equipment Inventory for my office, it's using VB.NET/SQL Online Database, i plan to create this with learning my self.

    1st i need to create online update function for my app.

    after this done,

    2) i'm try to create login with SQL Online Database.

    before do all this i was watch lot of youtube videos and try all of them with my own samples in VS2013. but i field to create online update solution for my app.

    Dear Frank, i'm sorry about my bad English Typing.   


    RohanD

    Thursday, July 6, 2017 2:42 PM
  • :)

    I plan to create IT Equipment Inventory for my office, it's using VB.NET/SQL Online Database, i plan to create this with learning my self.

    1st i need to create online update function for my app.

    after this done,

    2) i'm try to create login with SQL Online Database.

    before do all this i was watch lot of youtube videos and try all of them with my own samples in VS2013. but i field to create online update solution for my app.

    Dear Frank, i'm sorry about my bad English Typing.   


    RohanD

    Oh you're doing fine with English - don't worry about that at all.

    *****

    I have an idea: Since you don't have an actual product just yet (an application and the upgrade installer), I'll put something together to explain what you're asking about in this thread and give you some background about what it all means, how you can use it, that sort of thing.

    Afterward, if you want, I'll set up an area on my website that you can use. Not the FTP site that I was talking about yesterday, but a 'regular' website.

    How's that sound?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 6, 2017 2:51 PM
  • Sounds Good, 


    RohanD

    Thursday, July 6, 2017 2:55 PM
  • Sounds Good, 


    RohanD

    Ok.

    It'll take a while to put together and I'm at work, so check back tomorrow and I'll have a reply here.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 6, 2017 2:57 PM
  • Have you facebook? it's better if i have text solution without this form serious :) 

    RohanD

    Thursday, July 6, 2017 2:58 PM
  • Have you facebook? it's better if i have text solution without this form serious :) 

    RohanD

    I don't but this is the right place.

    Be patient please. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 6, 2017 3:02 PM
  • Sounds Good, 


    RohanD


    Rohan,

    Before getting started here, I’ll explain that I use an older version of Visual Studio so if I show screenshots of VS then know that your version will look different but the function is in your version also – somewhere! ;-)

    The second thing that I’d like for you to pay attention to is when I show code, please take note of the Imports statements (if any). I’d like for you to try some of these things firsthand so you can get a real feel for how it works and if mine has one or more imports statements, yours will need to have the same.

    Lastly, I’ll include some links throughout this and I hope you’ll take time to read them; however, don’t stop with just these few references. Be inquisitive and do some research on your own to know more about all of this. Don’t worry so much about those details right now, but come back to it later and it’ll make more sense.

     

    *****

     

    How about start a new project and save it so that you can later go back and reference it. Call it whatever you want but it’s to be a standard WinForms project with one form: Form1. Please leave the name of the form as that so that we’ll be in sync for the code that I’ll show.

    Also, put one button (Button1) on the form and set up the event handler sub for the .Click event. We’ll change the code that goes in that sub as this progresses but this will give you an easy way to test these things that I’ll show.

    So far then, your code should look like the following:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
    
    
        End Sub
    End Class


    Do you notice those three lines at the top that start with the word “Option”? Leave them like I show them please. A discussion about options would take a while so let’s leave that for another day (but please do some research about them on your own).

     

    *****

     

    Let’s start by answering the first question that you have here: Reading a text file that’s on a website.

    All sites aren’t the same! If you use DropBox then you’ll need to comply with however they have set up for you to access and consume it, but for my website those rules don’t apply.

    I know that eventually this will be about checking version info, but for now I’ll just use a simple one-line text file. Have a look at it here:

    http://www.fls-online.net/VBNet_Forum/ExampleText.txt

    There’s one thing that I’d like to point out (if you haven’t already noticed): This example text file has literally one line; there is no carriage return/line feed character in it. A CRLF can be dealt with if need be but in all that I’ll show following, I’m assuming there’s literally just one line.

    If you wanted to create a file like this, open Notepad, type the one line of text and save it. Don’t press the <Enter> key after the line! Another option would be to have your program create the text file for you – something that we may do before this is all over with.

    I’ll show two ways that you can have your program “read” that online text file (HTTP methods).

    The first is by using a WebClient and specifically using the .DownloadString method. Note in the following bit of code that I’ll be using the first way (of two) to call that method.

    Also notice that there’s an asynchronous version of it but for this – don’t use it. My suggestion to not use async might sound unreasonable at first; after all, it’ll run on another thread (so your UI won’t ‘hang’ while it’s performing the method) so why isn’t that a great thing?

    If you want to go to the extent of setting up the event handler that you’ll need, then maybe show a wait cursor while it performs the operation (and don’t forget to disable all of the controls while it does this), then I can’t say that’s a bad idea at all. The code will get a lot more involved but so what?

    The “so what” in my opinion is this: For a tiny little one-line text file, that’s ludicrous! It should take less than a second (a good bit less, and a point I’ll come back to in a bit) to read the entire contents and end (unblock). Making the program a lot more complex just doesn’t make sense here – in my opinion.

    I said earlier that all of this will be on a regular website and as a reference back to something I said yesterday, this uses HTTP rather than FTP.

    FTP has its place; I prefer it for many things, but for something like this, HTTP is a better choice. FTP has to log in, those credentials are checked, the transmission protocol is established, then finally we can do what we want. That takes time and it’s something that HTTP doesn’t have to deal with.

    Ok, the code to do this (please change your code to match it) is shown below:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Using wc As New System.Net.WebClient
                Dim onlineText As String = _
                    wc.DownloadString("http://www.fls-online.net/VBNet_Forum/ExampleText.txt")
    
                If Not String.IsNullOrWhiteSpace(onlineText) Then
                    MessageBox.Show(onlineText, "Result")
                End If
            End Using
    
        End Sub
    End Class


    Once you’ve made these changes to the code, press the button and you should see the text shown in a MessageBox:

    If it doesn’t work for some reason, please let me know.

    In the code above, notice that I declared the WebClient (“wc”) inside a Using block.

    If a component/class implements IDisposable – and the WebClient does (internally it uses a stream is why) – then this is a great way to be sure that the .Dispose method is automatically called, even if an exception is thrown during the operation. You can’t always make use of the using block but when you can, it makes life a lot easier.

    If none of that makes sense right now then don’t worry about it. For now, focus on the topic at hand and later on maybe come back and look at the details like .Dispose and all that. ;-)

     

    *****

     

    There’ s a second way that you can get your program to read that text file and it’s my preferred way.

    In my view, it gives me more control over just how it works and I’ll show an example of how it gives me more control in the following bit of code (Note the Imports statements!). Please change your code to match the following then press the button:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Dim url As String = _
                "http://www.fls-online.net/VBNet_Forum/ExampleText.txt"
    
            Dim onlineText As String = GetTextFromURL(url)
    
            If Not String.IsNullOrWhiteSpace(onlineText) Then
                MessageBox.Show(onlineText, "Result")
            End If
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
                ' It's usually not a good idea to leave a catch
                ' empty like I'm doing here.
                ' 
                ' The one that I'm leaving open here is a
                ' WebException. This will be the most likely one
                ' to get thrown (if an exception is thrown at all,
                ' that is) as would happen if your users don’t
                ' have an internet connection or the website is
                ' down.
                ' 
                ' There’s nothing you or the user can do about
                ' this so I’m just letting this function return a
                ' null string which I have it defaulted to.
                ' 
                ' Be sure to test the return value before using
                ' it!
                ' 
                ' Other ‘more general’ exceptions are still caught
                ' using the catch shown below this one.
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
    End Class


    The timeout parameter – which I have set up to be an optional parameter defaulted to 500 milliseconds – isn’t easy to do with a WebClient. It’s not impossible, but it’s not nearly as easy as what you see there.

    Try it out and let’s see if it works by changing the call to that sub:

     

    Dim onlineText As String = GetTextFromURL(url, 1)

     

    What happened? That tells it to only give it 1/1000 of a second to respond! It’s not that fast…

     

    *****

     

    Did this help at all? Do you have questions?

    Do you want to talk about versions and how to check them using an online text file? If you do then we can go there next but do know that version control can be a very long and involved topic all by itself.

    It’s not my forte, but if you’re a single developer it at least gets somewhat easier.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 6, 2017 7:06 PM
  • Thank you Frank, i'll try to learn all of these good much as i can... thank you very much again for your contributing for this....

    RohanD

    Friday, July 7, 2017 4:37 PM
  • Thank you Frank, i'll try to learn all of these good much as i can... thank you very much again for your contributing for this....

    RohanD


    I'm glad it helped. :)

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 4:38 PM
  • Searching about "Option" >  for learning ATM :)

    Option Strict On
    Option Explicit On
    Option Infer Off


    RohanD

    Friday, July 7, 2017 5:01 PM
  • Searching about "Option" >  for learning ATM :)

    Option Strict On
    Option Explicit On
    Option Infer Off


    RohanD

    https://support.microsoft.com/en-us/help/311329/option-explicit-and-option-strict-in-visual-basic-.net-and-in-visual-b

    and

    https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-infer-statement

    ;-)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 5:07 PM
  • UPDATE>>>> ATM :)

    '@@@@@@@@@@ POWERED BY Frank L. Smith >>>> https://social.msdn.microsoft.com/profile/frank%20l.%20smith/?ws=usercard-mini @@@@@@@@@@
    
    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Using wc As New System.Net.WebClient
                Dim onlineText As String = wc.DownloadString("http://www.fls-online.net/VBNet_Forum/ExampleText.txt")
    
                If Not String.IsNullOrWhiteSpace(onlineText) Then
                    MessageBox.Show(onlineText, "Result")
                End If
            End Using
    
            With Button1
                .Enabled = True
                .Refresh()
            End With
    
        End Sub
    End Class



    RohanD


    • Edited by RAT_SL Friday, July 7, 2017 6:52 PM
    Friday, July 7, 2017 6:50 PM
  • UPDATE>>>> ATM :)

    '@@@@@@@@@@ POWERED BY Frank L. Smith >>>> https://social.msdn.microsoft.com/profile/frank%20l.%20smith/?ws=usercard-mini @@@@@@@@@@
    
    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Using wc As New System.Net.WebClient
                Dim onlineText As String = wc.DownloadString("http://www.fls-online.net/VBNet_Forum/ExampleText.txt")
    
                If Not String.IsNullOrWhiteSpace(onlineText) Then
                    MessageBox.Show(onlineText, "Result")
                End If
            End Using
    
            With Button1
                .Enabled = True
                .Refresh()
            End With
    
        End Sub
    End Class



    RohanD


    Good then. :)

    Are you starting to see how this all works?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 6:57 PM
  • Yes Frank thanks to you i think :)

    RohanD

    Friday, July 7, 2017 7:01 PM
  • Yes Frank thanks to you i think :)

    RohanD


    :)

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 7:01 PM
  • have a question for you:

    when i type "MessageBox" there is a sub option as "Show" >> MessageBox.Show()

    but if i type "MsgBox" there is not a sub option as "Show" >> MsgBox.???????

    Why?

     

    RohanD

    Friday, July 7, 2017 7:25 PM
  • Update 2nd Lvl : ATM

    Is this Result Right?????

    '@@@@@@@@@@ POWERED BY Frank L. Smith >>>> https://social.msdn.microsoft.com/profile/frank%20l.%20smith/?ws=usercard-mini @@@@@@@@@@
    
    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            'Using wc As New System.Net.WebClient
            '    Dim onlineText As String = wc.DownloadString("http://www.fls-online.net/VBNet_Forum/ExampleText.txt")
    
            '    If Not String.IsNullOrWhiteSpace(onlineText) Then
            '        MessageBox.Show(onlineText, "Result")
            '    End If
            'End Using
    
            Dim url As String = "http://www.fls-online.net/VBNet_Forum/ExampleText.txt"
    
            Dim onlineText As String = GetTextFromURL(url, 1)
    
    
    
            'With Button1
            '    .Enabled = True
            '    .Refresh()
            'End With
    
        End Sub
    
        Private Function GetTextFromURL(ByVal url As String, Optional ByVal timeoutMS As Integer = 500) As String
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using respoanse As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = respoanse.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An ERROR OCCURRED:{0}{0}{1}", vbCrLf, ex.Message), "Exception Thrown", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
    End Class


    RohanD

    Friday, July 7, 2017 7:42 PM
  • Is this Result Right?????

    Yes, in fact that was my whole point!

    If you wanted to set up a .Timeout feature with a WebClient, you'd end up creating a new one (inheriting from a WebClient) and then you'd be able to access the members.

    Using this alternate way though, I'm already at that level so I just set it and we're done.

    *****

    I'd like to show you one more thing.

    Rather than setting the timeout to a value of 1, set it to a negative number and press the button. Let's see what happens. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 7:46 PM
  • nothing Happens.... with -1


    RohanD

    Friday, July 7, 2017 7:51 PM
  • nothing Happens.... with -1


    RohanD

    That actually has a special meaning -- that'll teach me!

    Try a value of -2 and let's see.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 7:54 PM

  • RohanD

    Friday, July 7, 2017 8:06 PM

  • RohanD

    Right!

    My point here being that's how structured exception handling works.

    Notice that it "fell through" and was caught by the more general exception handler "Catch ex As Exception".

    *****

    The reason that -1 didn't throw an exception is because the message you see there is wrong! Sorry MSFT, it is: Notice that it shows that it has to be either equal to or greater than 0 -OR- it has to be "Infinite" as set by System.Threading?

    Let's just have a closer look:

    This is the documentation for the "Infinite" setting:

    https://msdn.microsoft.com/en-us/library/system.threading.timeout.infinite(v=vs.110).aspx

    The type is shown to be an Int32 (just a standard "Integer" type) and as such, that's a value type. How can it be "infinite" then?

    Read through to this:

    "The value of this field is -1 (0xFFFFFFFF)."

    That's why -1 didn't throw an exception. If it sees a value of -1, it takes that to mean that you want it to wait forever (ergo, "infinite").

    Sorry about the confusion! ;-)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, July 7, 2017 8:16 PM
  • Rohan,

    Let’s continue now to get closer to what you’re actually wanting: A comparison of versions to know when a program update is available.

    You’ve seen how you can read a text file that’s online so in the following I’ll use my preferred way from yesterday along with a different text file that’s on my site as shown below:

     

    http://www.fls-online.net/VBNet_Forum/ExampleVersionText.txt

     

    This will allow me to simulate what happens when there’s an update to your program and that update is reflected in that online text file.

    There are two ways that I want to show you: The first way just uses a string comparison and that works ok, but there’s a more appropriate way that I’ll explain afterward.

    Please change the code of yours to match the following then press the button afterward:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Const url As String = _
                "http://www.fls-online.net/VBNet_Forum/ExampleVersionText.txt"
    
            Dim onlineText As String = GetTextFromURL(url)
    
            If Not String.IsNullOrWhiteSpace(onlineText) Then
                Dim thisVersion As Version = _
                    GetThisAssemblyVersion()
    
                If thisVersion IsNot Nothing Then
                    Stop
    
                    ' When the program gets to "Stop" above, execution
                    ' will halt just like as though you'd put a
                    ' breakpoint in.
                    ' 
                    ' When it does, hover your mouse over the variable
                    ' named "thisVersion" then expand what you'll then
                    ' see.
                    ' 
                    ' What you'll see are the members of the Version
                    ' class.
                End If
            End If
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
        Private Function GetThisAssemblyVersion() As Version
            Return My.Application.Info.Version
        End Function
    
    End Class


    There’s a new function that I’ve included in this one called “GetThisAssemblyVersion” and it uses something that we have in VB to get the assembly’s version quite easily. It’s short and does the job well so I’ll use this function throughout.

    It’s based on the My namespace. If you’re not familiar with what I mean by that, do some research but know that it’s not part of the framework; it’s specific to VB Net. You might want to spend 15 minutes to watch this video.

    The function is very simply this:

    Private Function GetThisAssemblyVersion() As Version
        Return My.Application.Info.Version
    End Function


    The My namespace seems to irk some people and if you want, I’ll show you another way to get the version but you have to admit that for no more code than that, it’s hard to beat!

    The return value is a Version object (an instance of the Version class) and it’s worth a few minutes to talk about it some. MSDN’s documentation for the Version class is shown here:

     

    https://msdn.microsoft.com/en-us/library/system.version(v=vs.110).aspx

     

    This is a topic that’s worth doing some exploration about and the only thing I’ll add at this point is this: A string is a string; it’s never a version (or a number or anything else). A version can be represented by a string, but a string is still just a string and nothing more.

    I hope that will become obvious as we work through this and the start of that is to run your program now and press the button.

    When you hover your mouse over the variable named “thisVersion”, then expand that, you’ll see the properties of the version. So to not confuse you later on, the version information that you’ll see will be the version of your program – the one that you created to run this code. Unless you’ve changed it, it will be version 1.0.0.0.

     

    *****

     

    So how can we compare the version (the instance of the Version class) to the string that’s returned from the online text file? The first of two ways is by comparing two strings, so the challenge now is to get a string equivalent of “thisVersion”.

    There is rarely only ever one way to do anything in VB Net and this is definitely an example. Do some looking around and you’ll probably see several ways including Convert.ToString and explicit conversion.

    For the following though, I’ll use the .ToString method. The ToString function won’t always return anything meaningful, but in this case it will.

    Modify your code to the following then run it please:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Const url As String = _
                "http://www.fls-online.net/VBNet_Forum/ExampleVersionText.txt"
    
            Dim onlineText As String = GetTextFromURL(url)
    
            If Not String.IsNullOrWhiteSpace(onlineText) Then
                Dim thisVersion As Version = _
                    GetThisAssemblyVersion()
    
                If thisVersion IsNot Nothing Then
                    Dim thisVersionText As String = thisVersion.ToString
    
                    Stop
    
                    ' When the program gets to "Stop" this time, hover
                    ' your mouse over the variable above named
                    ' "thisVersionText" and you'll see the string
                    ' equivalent of the version of 'this' program.
                    ' 
                    ' Once you've seen the string, 'continue' the
                    ' program until it gets to the next "Stop" below:
    
                    Dim updateAvailable As Boolean = False
    
                    If onlineText <> thisVersionText Then
                        updateAvailable = True
                    End If
    
                    Dim sb As New System.Text.StringBuilder
    
                    sb.AppendLine("Local Version: " & thisVersionText)
                    sb.AppendLine("Online Version: " & onlineText)
                    sb.AppendLine()
    
                    If updateAvailable Then
                        sb.Append("An update is available.")
                    Else
                        sb.Append("Nothing to update.")
                    End If
    
                    MessageBox.Show(sb.ToString, "Version Status")
    
                    Stop
                End If
            End If
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
        Private Function GetThisAssemblyVersion() As Version
            Return My.Application.Info.Version
        End Function
    
    End Class


    The result should show this:

    The comparison to know whether there’s a new version available (based on the text read from the online file) is done via a string comparison. If the two strings aren’t the same then it deems that an online update is available (and vice versa).

    That’s very easy to do as you see there, but let’s continue and I’ll show you some drawbacks to it. In the following, please be sure to remember that I’m using an older version of VS so what you’ll see in yours will be different.

    Let’s now change the version of your local program: One way to do this is by double-clicking “My Project” in Solution Explorer:

    When you do, the application’s properties will then be shown in a tab control. Select the “Application” tab:

    Now click on “Assembly Information” and you’ll see the information that we need to change:

    Let’s stop for a minute here. What ‘version’ are we talking about anyhow? The program has two of them (and to further confuse things, when you create an installer, the installer also has a version) so know that the version I’m referring to here is the Assembly Version that you see me pointing to in the screenshot above.

     

    Do you back up your hard drives? That seems like an off-topic question but it’s not.

    What do you suppose would happen if you lost the drive that your program is on? Let’s say that happens and you re-write your program from scratch. Aside from the amount of time and work that would involve, would that be a problem for you and/or your users?

    Yes it will.

    Notice in that last screenshot that you see “GUID” there.

    When you create a new application, that’s a unique identifier that won’t be replicated so when you get to the installer, that’s where you’ll see it balk. It’s not the same “program” and it can tell it’s not!

    Something to consider then. ;-)

     

    Moving ahead here, how about change your program’s assembly version to 1.1.0.0:

    Be sure to click the “OK” then run it again and press the button. Did it work?

    Well … it definitely sees that the two strings aren’t the same and based on the logic that I put in there, it shows it correctly, but think about something please: My local version is 1.1 and the online version is 1.0. How is that an update?!?

    You could make the argument that that’s unlikely to happen (and I won’t disagree), but is there a better way to make this comparison?

     

     

    Continued in the next post


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, July 8, 2017 8:59 PM
  • Continued from previous post

     

     

    Rohan,

    Continuing, the Version class already has a great way to accurately make the comparison for us – and it’s not based on a string comparison:

     

    https://msdn.microsoft.com/en-us/library/a5ts8tb6(v=vs.110).aspx

     

    They’ve done a lot to make sure that everything is accounted for and if we use it correctly, 1.1 will never be seen as an update to 1.0! ;-)

    Skim through that and about halfway down you’ll see a table:

     

    Return value

    Meaning

    Less than zero

    The current Version object is a version before value.

    Zero

    The current Version object is the same version as value.

    Greater than zero

    The current Version object is a version subsequent to value.

    -or-

    value is null.

     

    *  I pasted the table into this so I’m not sure that it’ll come out right – I might end up removing it if didn’t turn out well.

     

    There’s something to consider here: Perspective.

    When it returns a value of +1, 0, or -1, it depends on the ‘point of view’ as to which version it means. That’s important because we need to know how to arrange the logic of our evaluation test.

    For this next part, please return your program’s version (Application Version) to 1.0.0.0:

    Now update your code to the following:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Const url As String = _
                "http://www.fls-online.net/VBNet_Forum/ExampleVersionText.txt"
    
            Dim onlineText As String = GetTextFromURL(url)
    
            If Not String.IsNullOrWhiteSpace(onlineText) Then
                Dim onlineVersion As Version = Nothing
    
                If Not Version.TryParse(onlineText, onlineVersion) Then
                    MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & _
                                    "The online text is malformed.", _
                                    "Exception Thrown", _
                                    MessageBoxButtons.OK, _
                                    MessageBoxIcon.Warning)
                Else
                    Dim thisVersion As Version = GetThisAssemblyVersion()
    
                    If thisVersion IsNot Nothing Then
                        Dim updateAvailable As Boolean = False
    
                        If onlineVersion.CompareTo(thisVersion) = 1 Then
                            updateAvailable = True
                        End If
    
                        Dim sb As New System.Text.StringBuilder
    
                        sb.AppendLine("Local Version: " & thisVersion.ToString)
                        sb.AppendLine("Online Version: " & onlineText)
                        sb.AppendLine()
    
                        If updateAvailable Then
                            sb.Append("An update is available.")
                        Else
                            sb.Append("Nothing to update.")
                        End If
    
                        MessageBox.Show(sb.ToString, "Version Status")
    
                        Stop
                    End If
                End If
            End If
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
        Private Function GetThisAssemblyVersion() As Version
            Return My.Application.Info.Version
        End Function
    
    End Class
    



    The perspective that I’ll use here will be from the online version’s point of view as compared to the local version. There’s a problem though: A string is still just a string – it’s not a version so I have to convert it to one, or more appropriately, I have to parse that string into an instance of the Version class.

    What if the text is messed up and it can’t be parsed into a Version instance? How can we handle that?

    In many of the dotNET classes, we have a great way: TryParse. It works like this (in general):

    You tell it the string to use to attempt to make the conversion (parsing – which may not be conversion at all, but you can think of it that way) and you give it a reference of that type to parse it to. You can think of that last part as the target of the parsing.

    IF it works, then your reference now has the value of the parse procedure and it will return a Boolean True to indicate that it worked.

    If it can’t parse that string to the type, then an exception is not thrown; the reference variable will have the value of whatever the default is for that type and the return value will be Boolean False.

    That probably sounds confusing at first but once you get the hang of it, you’ll understand and appreciate what they put in there for us.

    For the Version class, TryParse works like this:

     

    https://msdn.microsoft.com/en-us/library/system.version.tryparse(v=vs.110).aspx

     

    The code will first test that it returned true from the TryParse procedure (and show a message if it doesn’t) then it will get your program’s version using that new function that I put in called “GetThisAssemblyVersion”. Now it has everything that’s needed to make the comparison.

    Next it will evaluate the two versions and based on the result of that, it’ll show whether the online version – represented by the text of the online text file – is higher than the current version.

    Run the program and press the button -- you should see this:

    Now, just like before, change your Assembly Version to 1.1.0.0, click the ”OK” button and run it again:

    This time it sees that your local version is higher than the online version and it shows that as not being an update. Lastly then, change your local version to one that’s lower:

    Then run it again and you’ll see this:

     

    *****

     

    Do remember that the perspective of the comparison makes all the difference in the world here but honestly, this snippet of code is confusing isn’t it?

    If onlineVersion.CompareTo(thisVersion) = 1 Then
        updateAvailable = True
    End If



    How about let’s change that some and use operators that we’re used to then? It’s just simple math after all. Please change your code to the following:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            ' For now this will be empty but
            ' I'll use it later so go ahead
            ' and add it...
    
        End Sub
    
        Private Sub _
            Button1_Click(sender As System.Object, _
                          e As System.EventArgs) _
                          Handles Button1.Click
    
            With Button1
                .Enabled = False
                .Refresh()
            End With
    
            Const url As String = _
                "http://www.fls-online.net/VBNet_Forum/ExampleVersionText.txt"
    
            Dim onlineText As String = GetTextFromURL(url)
    
            If Not String.IsNullOrWhiteSpace(onlineText) Then
                Dim onlineVersion As Version = Nothing
    
                If Not Version.TryParse(onlineText, onlineVersion) Then
                    MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & _
                                    "The online text is malformed.", _
                                    "Exception Thrown", _
                                    MessageBoxButtons.OK, _
                                    MessageBoxIcon.Warning)
                Else
                    Dim thisVersion As Version = GetThisAssemblyVersion()
    
                    If thisVersion IsNot Nothing Then
                        Dim updateAvailable As Boolean = False
    
                        'If onlineVersion.CompareTo(thisVersion) = 1 Then
                        '    updateAvailable = True
                        'End If
    
                        If onlineVersion > thisVersion Then
                            updateAvailable = True
                        End If
    
                        Dim sb As New System.Text.StringBuilder
    
                        sb.AppendLine("Local Version: " & thisVersion.ToString)
                        sb.AppendLine("Online Version: " & onlineText)
                        sb.AppendLine()
    
                        If updateAvailable Then
                            sb.Append("An update is available.")
                        Else
                            sb.Append("Nothing to update.")
                        End If
    
                        MessageBox.Show(sb.ToString, "Version Status")
    
                        Stop
                    End If
                End If
            End If
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                If ex.Status = WebExceptionStatus.Timeout Then
                    MessageBox.Show("The method timed out.")
                End If
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    
        Private Function GetThisAssemblyVersion() As Version
            Return My.Application.Info.Version
        End Function
    
    End Class
    

    This is the change:

    'If onlineVersion.CompareTo(thisVersion) = 1 Then ' updateAvailable = True 'End If If onlineVersion > thisVersion Then updateAvailable = True End If



    Now it ‘makes more sense’ I hope?

     

    *****

     

    There’s a lot to take in here so take your time with it and I hope it helps.

    :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, July 8, 2017 9:03 PM
  • Hi Rohan,

    Please remember to close your thread by marking the helpful post as answer, it is very beneficial to other community members who face the same issue.

    Thanks for your understanding.

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 19, 2017 6:19 AM
    Moderator