VBNet Sample (Yes really)

Collapse
This is a sticky topic.
X
X
 
  • Time
  • Show
Clear All
new posts
  • davecon
    Junior Member
    • Dec 2010
    • 86

    #16
    VBNet KeepAlive and Logout

    Hi Here is the Code for KeepAlive and Logout for VBNet – The problem with previous attempts was to just get a png image instead of the information returned in response
    For some strange reason Web Requests have to first be assigned to a HttpWebRequest in order the get the .Accept element to work then all is well
    The Only difference with KeepAlive and LogOut is the URL endpoint so have just put them in one sub
    I’m Sure you may use in a different way but in any case its straightforward to play with (now lol)
    In Case you haven’t done so already you need
    Imports System.Net '~~>Needed for Web requests
    Code:
     Private Sub KeepAliveOrKill(SessToken As String, _
                                    Optional AppKey As String = "", _
                                    Optional IsKeepAlive As Boolean = True)
    
            Dim strUrl As String = "" '~~> Holds Keep Alive Or LogOut String
            Dim htRequest As HttpWebRequest = Nothing  '~~~> *NOTE* HttpWebRequest NOT WebRequest then Convert
            Dim htResponse As Net.HttpWebResponse = Nothing '~~~> *NOTE* HttpWebResponse NOT WebResponse
            Dim oResponseStream As IO.StreamReader = Nothing '~~> Get the Text Stream
            Dim strResponseText As String = "" '~~> Holds the Response message for display if required
            Dim strMsg As String = "" '~~> Which one was used Keep or Kill?
            Try
                If IsKeepAlive = True Then '~~> Keep Alive If arg is set to True (Default) 
                    strUrl = "https://identitysso.betfair.com/api/keepAlive"
                    strMsg = "KEEP ALIVE" & vbCrLf '~~> For Display later
                Else '~~> Log Out if arg is set to false
                    strUrl = "https://identitysso.betfair.com/api/logout"
                    strMsg = "LOGGED OUT" & vbCrLf '~~> For Display later
                End If 'Keep or Kill
                htRequest = WebRequest.Create(strUrl) '~~~> *NOTE* Swap back HttpWebRequest to WebRequest to use Accept (strange)!
                With htRequest '~~> The .Accept doo dah will now work
                    .Method = "GET" '~~> I believe we use Get if we are just retrieving and Post if putting something? both work
                    .ContentType = "application/json" '~~> Normal
                    .Accept = "application/json" '~~> This is the cause of the recent problems returning a png (needs Http request)
                    '~~> Add Headers <~~'
                    .Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                    .Headers.Add("X-Authentication", SessToken) '~~> Mandatory
                    If AppKey <> "" Then '~~> Use the Current AppKey (Product) Not mandatory but advisable I suppose
                        .Headers.Add("X-Application", AppKey)
                    End If 'AppKey
                End With 'htRequest
                '~~> Get the response.<~~'
                htResponse = htRequest.GetResponse
                If htResponse.StatusCode = Net.HttpStatusCode.OK Then '~~> Proceed to get the Response details
                    oResponseStream = New IO.StreamReader(htResponse.GetResponseStream()) '~~> Convert to text
                    strResponseText = oResponseStream.ReadToEnd() '~~> Read all the Text to the String Variable
                Else '~~> Get outa here
                    Exit Sub
                End If 'Ht Error Check
                '~~> Successful Response Details for Log Text etc if required <~~'
                If Not strResponseText.Contains("FAIL") Then '~~> Everything is hunky dory
                    MsgBox("SUCCESS! " & strMsg & strResponseText, MsgBoxStyle.Exclamation, strMsg) '** Test
                Else '~~> Have we forgot something?
                    MsgBox("ERROR! " & strMsg & strResponseText, MsgBoxStyle.Critical, strMsg) '** Test
                End If 'Success or fail
            Catch ex As Exception
                MsgBox("KeepAliveOrKill Error" & vbCrLf & ex.Message, MsgBoxStyle.Critical)
                '~~~Clean Up
                htResponse.Close()
                htResponse = Nothing
                oResponseStream = Nothing
            End Try
            '~~~Clean Up
            htResponse.Close()
            oResponseStream = Nothing
        End Sub 'KeepAliveOrKill Decide what to do
    And Finally some Examples
    Code:
       '~~> Some Form Examples <~~
            KeepAliveOrKill(txtSessionToken.Text) '~~> Default Keep Alive Basic
            KeepAliveOrKill(txtSessionToken.Text, , False) '~~> Log Out Basic
            KeepAliveOrKill(txtSessionToken.Text, txtLiveKey.Text) '~~> Default Keep Alive With App Key
            KeepAliveOrKill(txtSessionToken.Text, txtLiveKey.Text, False) '~~> Log Out With App Key
            KeepAliveOrKill(txtSessionToken.Text, txtLiveKey.Text, rbKeepAlive.Checked) '~~> Default Checked Radio Button Value for either (If Unchecked will log out)
    Now I can sleep as well now Rich lol
    Dave

    Comment

    • davecon
      Junior Member
      • Dec 2010
      • 86

      #17
      Login and Session Token with Json

      Hi Just in case you want to Login - Logout - KeepAlive with Json
      The Identify Class will do for all 3 same as Login to return the values

      IDENTIFY CLASS

      Code:
      '===== Login Logout and KeepAlive Class (Identify) ==========
      Imports Newtonsoft.Json '~~> Enable the the use of Json Objects
      Imports Newtonsoft.Json.Converters
      Public Class Identify
          Private m_sessToken As String
          <JsonProperty(PropertyName:="token")> _
          Public Property SessionToken() As String
              Get
                  Return m_sessToken
              End Get
              Set(value As String)
                  m_sessToken = value
              End Set
          End Property '~~>Session Token
          Private m_productName As String
          <JsonProperty(PropertyName:="product")> _
       Public Property ProductName() As String
              Get
                  Return m_productName
              End Get
              Set(value As String)
                  m_productName = value
              End Set
          End Property '~~>ProductName
          Private m_statusResult As String
          <JsonProperty(PropertyName:="status")> _
          Public Property StatusResult() As String
              Get
                  Return m_statusResult
              End Get
              Set(value As String)
                  m_statusResult = value
              End Set
          End Property '~~>Status Result
          Private m_errorMsg As String
          <JsonProperty(PropertyName:="error")> _
          Public Property ErrorMessage() As String
              Get
                  Return m_errorMsg
              End Get
              Set(value As String)
                  If m_errorMsg <> "" Then
                      m_errorMsg = value
                  End If
              End Set
          End Property '~~>Error Message
      End Class 'Identify
      LOGIN_NG FUNCTION

      Code:
      Private Function NG_Login()
              '=============Interactive Login for a Desktop App for Json String ==================
              '** First get your required Endpoint if you are not a UK or International User see Documentation For Login URL definition
              'identitysso.betfair.com '~~> UK and International users (for Aus as well?)
              'identitysso.betfair.es '~~> Spanish
              'identitysso.betfair.it '~~> Italian
              'identitysso.w -con.betfair.com '~~> These 2 are Listed in Non-Interactive Doc?
              'identitysso.betfaironline.eu 'Europe
              Dim strUserEndpoint As String = "https://identitysso.betfair.com/api/login" '~~> UK and International
              '======== Construct the UserName and Password String =============
              '~~> This is the "Do Our Heads in Bit" EG: The UserName and Password HAS to be part of the Request String Itself!
              Dim strUserName As String = txtUserName.Text '~~> Your userName
              Dim strPassword As String = txtPassword.Text '~~> Your password
              Dim strID As String = "?username=" & strUserName & "&password=" & strPassword
              '========= Construct the Full Request Url ========= 
              Dim strUrl As String = strUserEndpoint & strID
              '===== Now just make the Normal Json request as used in the Logout and KeepAliv e==============
              Dim htRequest As HttpWebRequest = Nothing  '~~~> *NOTE* HttpWebRequest NOT WebRequest 
              Dim htResponse As Net.HttpWebResponse = Nothing '~~~> *NOTE* HttpWebResponse NOT WebResponse
              Dim oResponseStream As IO.StreamReader = Nothing '~~> Get the Text Stream
              Dim strResponseText As String = "" '~~> Holds the Response message for display if required
              Try
                  htRequest = WebRequest.Create(strUrl) '~~~> *Create Web Request
                  With htRequest '~~> To accept Json
                      .Method = "POST" '~~> Not GET
                      .ContentType = "application/json" '~~> Normal
                      .Timeout = 5000 '~~> Optional
                      .Accept = "application/json" '~~> Required
                      '~~> Add Headers <~~'
                      .Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                      '======= THIS is STRANGE! ==============
                      '.Headers.Add("X-Application", txtLiveKey.Text) '~~~> Use App Key here SEE BELOW!
                      .Headers.Add("X-Application", "CallmeAnyting") '~~> Use Product Key if required but you can Call this anything by look of it
                  End With 'htRequest
                  '~~> Get the response and return the Status and Session Token<~~'
                  htResponse = htRequest.GetResponse
                  If htResponse.StatusCode = Net.HttpStatusCode.OK Then '~~> Proceed to get the Response details
                      oResponseStream = New IO.StreamReader(htResponse.GetResponseStream()) '~~> Convert to text
                      strResponseText = oResponseStream.ReadToEnd() '~~> Read all the Text to the String Variable
                  Else '~~> Get outa here
                      oResponseStream.Close()
                      oResponseStream = Nothing
                      Return Nothing
                      Exit Function
                  End If 'Ht Error Check
              Catch ex As System.Exception
                  ' txtLog.Text = "Login Problem" & vbCrLf & ex.Message
                  MsgBox("Login Problem" & vbCrLf & ex.Message)
                  '==Clean Up==
                  htRequest = Nothing
                  htResponse = Nothing
                  oResponseStream.Close()
                  oResponseStream = Nothing
              End Try
              '===== Get Json Results for Editing =====
                   Return strResponseText
              '==Clean Up==
              htRequest = Nothing
              htResponse = Nothing
              oResponseStream.Close()
              oResponseStream = Nothing
          End Function 'Login and get Session Token String
      Finally the LOGIN SUB to get the Values (To use on the Form)

      Code:
      Sub Login()
              Dim strLogin As String = NG_Login() '~~>Use Directly
              Dim objJson = JsonConvert.DeserializeObject(Of Identify)(strLogin) '~~> Use the Identify Class
              With objJson
                  txtSessionToken.Text = .SessionToken '~~> Display Current Session Token
                  MsgBox(.ProductName & " " & .StatusResult & " " & .ErrorMessage) '~~> Other Stuff Example
              End With
          End Sub 'Login then Gets the Current Session token and other Json Properties
      Have a Nice day
      Dave

      Comment

      • Peter Simple
        Junior Member
        • Aug 2009
        • 32

        #18
        but why is there no "Accept" Equivalent with Net
        There is already an "accept" header in .net. The correct syntax is request.header = ... . So there is no need to create a custom header.

        Comment

        • davecon
          Junior Member
          • Dec 2010
          • 86

          #19
          Originally posted by Peter Simple View Post
          There is already an "accept" header in .net. The correct syntax is request.header = ... . So there is no need to create a custom header.
          Thanks Peter we all learn by our Mistakes
          Does not alter the fact that there are no Samples for Login-Logout-KeepAlive etc and Account Funds or that anybody else has bothered to share them on here
          Cheers
          Dave

          Comment

          • kawafan
            Junior Member
            • May 2011
            • 33

            #20
            hi
            thanks for your Code Posting it was really helpful for me to get started even i m interested in c# but Classes Seems complete.
            Please Keep sharing the code it was really helpful.

            Also ListmarketBook code too.

            Thanks

            Comment

            • davecon
              Junior Member
              • Dec 2010
              • 86

              #21
              Hi kawafan
              I have sent you a message
              Dave

              Originally posted by kawafan View Post
              hi
              thanks for your Code Posting it was really helpful for me to get started even i m interested in c# but Classes Seems complete.
              Please Keep sharing the code it was really helpful.

              Also ListmarketBook code too.

              Thanks

              Comment

              • daveg33
                Junior Member
                • Sep 2013
                • 6

                #22
                Has anyone managed a listCurrentOrders request successfully in vb yet? I have been trying and failed, have a thread opened about my error but still no resolution.

                Comment

                • Guest

                  #23
                  Not sure if you got an answer mate but I got it working and posted the response here

                  https://forum.bdp.betfair.com/showth...=9745#post9745

                  Comment

                  • JayBee
                    Junior Member
                    • Oct 2010
                    • 114

                    #24
                    Has anyone got any VB code for an async webrequest to the Betfair server?

                    Nothing I see in web examples contains the POST data, header ContentType etc.

                    Thanks.

                    Comment

                    • rphi6876
                      Junior Member
                      • Nov 2009
                      • 7

                      #25
                      Hi Davecon,

                      Thankyou so much for your sample code it has been the most helpful starting point I have found so far.

                      Just a few questions I am hoping you or somebody else can answer.

                      when I go to make a listMarketBook request I have the following

                      Code:
                         
                      Dim timeStart As DateTime = Date.UtcNow()
                      
                      priceData.Add(Api_ng_sample_code.TO.PriceData.EX_ALL_OFFERS)
                      priceData.Add(Api_ng_sample_code.TO.PriceData.EX_TRADED)
                      Dim priceProjection = New PriceProjection()
                      priceProjection.PriceData = priceData
                      
                      Dim marketBook = client1.listMarketBook(marketIds, priceProjection)
                      
                      Dim timeEnd As DateTime = Date.UtcNow
                      Dim diffTime = timeEnd - timeStart
                      MsgBox(diffTime.TotalMilliseconds.ToString)
                      This is so I can get the volume at each price level and the amount traded at each price level.
                      My concern is that the time taken is roughly 4000ms (I only have one marketId in marketIds). I am in Oz and hitting UK markets, but this seems super slow. On the old api a getMarketPrices call takes about 400ms. So I am 10 times slower, any suggestions how to improve this would be greatly appreciated.

                      Comment

                      • davecon
                        Junior Member
                        • Dec 2010
                        • 86

                        #26
                        Hi rph
                        I cant really suggest how you can improve this but I can give you the times that I get from UK and then trying Oz which I did notice was significantly slower when I was just throwing that basic app together from one of your guys earlier. I have not started to do anything with this new API yet until I have to (I'm still using the old one for now)
                        But just using the new API with the Tree view from this Basic App thingy and loading 99 Market ID's this gives the following times which I find Very Strange (Using your Msgbox time example with my Todays Races call)
                        From UK with 99 Strings and Market ID's The first load Takes about 270 ms then after that around 170
                        With 1 Market ID this takes first Load about 170 ms and then around 83 each time afterwards
                        The Information and the msgbox loads instantly on the screen
                        BUT THIS IS THE Weird BIT if I then change to OZ
                        The first call with 99 ids takes around 800 ms and then the same about 170 and with just one ID its around 250 ms but then can be as low as 25! But again usually in the 80's
                        BUT==== On EVERY occasion (With Oz only) I can Count up to 4 Seconds before I see anything on the screen and until the Message Box is displayed!! The message box which says 25 ms I can count to 2 Secs before I see this message or anything in treeview!
                        So what garbage is actually happening in between I have no idea SO Hope one of the Betfair Team or Tech guys can help you here as you seem to be having the same sort of problem but Vice Versa
                        I dont know how much actual ISP Internet speeds come into account but I use Virgin 50 meg broadband (Gives a constant 55 mb cable connection throughout the day)
                        Hope this can be of some assistance anyway
                        Cheers
                        Dave

                        Originally posted by rphi6876 View Post
                        Hi Davecon,

                        Thankyou so much for your sample code it has been the most helpful starting point I have found so far.

                        Just a few questions I am hoping you or somebody else can answer.

                        when I go to make a listMarketBook request I have the following

                        Code:
                           
                        Dim timeStart As DateTime = Date.UtcNow()
                        
                        priceData.Add(Api_ng_sample_code.TO.PriceData.EX_ALL_OFFERS)
                        priceData.Add(Api_ng_sample_code.TO.PriceData.EX_TRADED)
                        Dim priceProjection = New PriceProjection()
                        priceProjection.PriceData = priceData
                        
                        Dim marketBook = client1.listMarketBook(marketIds, priceProjection)
                        
                        Dim timeEnd As DateTime = Date.UtcNow
                        Dim diffTime = timeEnd - timeStart
                        MsgBox(diffTime.TotalMilliseconds.ToString)
                        This is so I can get the volume at each price level and the amount traded at each price level.
                        My concern is that the time taken is roughly 4000ms (I only have one marketId in marketIds). I am in Oz and hitting UK markets, but this seems super slow. On the old api a getMarketPrices call takes about 400ms. So I am 10 times slower, any suggestions how to improve this would be greatly appreciated.

                        Comment

                        • doctormike
                          Junior Member
                          • Nov 2012
                          • 55

                          #27
                          SSL Certificate

                          Great thread - many thanks in particular to davecon.
                          I write apps in Visual Basic only, so this was most welcome, along with guidance on json.

                          I started learning Visual Basic to write apps about 18 months ago, inspired by, and learning from, another excellent thread by mumbles (you may be familiar with this). I've now written apps for arbing and trading. As BF say they will withdraw the old API in Nov 2014 I thought I'd get started on coming to terms with API-NG, and this has been the best thread I've found.

                          I was spooked by a comment made in the API Getting Started section on the BF developers pages:

                          "Customers who are writing bots for their own use are strongly recommended to use the non-interactive endpoint with an SSL certificate."

                          I'm trying to follow the BF instructions, but they are a bit sparse on SSL. I've downloaded OpenSSL and generated a key, but I really don't know how to update/create the config file (was .cnf, now .cfg). I think I need step by step guidance! If anyone can help, this would be appreciated.

                          Comment

                          • john_baptiste_of_cheshire
                            Junior Member
                            • Apr 2012
                            • 8

                            #28
                            ta

                            thanks a lot davecon, it's always the practical threads like these that help those of us who are not au fait with programming get going.....much appreciated

                            Comment

                            • davecon
                              Junior Member
                              • Dec 2010
                              • 86

                              #29
                              Hi Mike
                              If you are using VBNet as a Windows desktop app you dont need that stuff - Thats for if you are going online via the web etc
                              You are using a direct feed to Betfair api sorta thing directly from your Comp and has nout to do with any Internet security
                              As long as its only you that uses the computer then it cant be a problem
                              So no need to worry about all that stuff unless you are from a Country that requires it
                              Relax and Have a good one
                              I stand corrected if I am wrong anybody
                              Dave

                              Originally posted by doctormike View Post
                              Great thread - many thanks in particular to davecon.
                              I write apps in Visual Basic only, so this was most welcome, along with guidance on json.

                              I started learning Visual Basic to write apps about 18 months ago, inspired by, and learning from, another excellent thread by mumbles (you may be familiar with this). I've now written apps for arbing and trading. As BF say they will withdraw the old API in Nov 2014 I thought I'd get started on coming to terms with API-NG, and this has been the best thread I've found.

                              I was spooked by a comment made in the API Getting Started section on the BF developers pages:

                              "Customers who are writing bots for their own use are strongly recommended to use the non-interactive endpoint with an SSL certificate."

                              I'm trying to follow the BF instructions, but they are a bit sparse on SSL. I've downloaded OpenSSL and generated a key, but I really don't know how to update/create the config file (was .cnf, now .cfg). I think I need step by step guidance! If anyone can help, this would be appreciated.

                              Comment

                              • davecon
                                Junior Member
                                • Dec 2010
                                • 86

                                #30
                                Thanks John
                                Glad I could be of some help even at my level
                                I will try to do something more elaborate in the Winter months if I have to dump the old api (The way its going with the new one I think it will be another Year before thats discontinued anyway)
                                Cheers Dave

                                Originally posted by john_baptiste_of_cheshire View Post
                                thanks a lot davecon, it's always the practical threads like these that help those of us who are not au fait with programming get going.....much appreciated

                                Comment

                                Working...
                                X