Using VB2008 to acccess the Betfair API: A tutorial

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • UncleScrooge
    Junior Member
    • Feb 2010
    • 2

    #346
    Originally posted by Mumbles0 View Post
    UncleScrooge,

    Looks like you've added a service reference instead of a web reference in Step 2. See this post.

    (You're not the first to do this.)
    works wonders now!

    Thnx again!!!!!!!!

    Comment

    • thewhistler
      Junior Member
      • Jun 2010
      • 3

      #347
      Hi folks,

      I have been trying to make a small app to place bets on betfair.

      I have worked my way through all the steps and vaguely understand how it all ties together.

      Currently a bit stuck

      I previously had a login button coded with a couple of input boxes to enter the user name and password but, I felt it looked better with another form.

      Now when you press the login button it pulls up the new form. Where you then enter your username and password then press login.

      This all seems to work fine apart from one vital bit it doesn't actually log in.

      I am guessing this is due to, I can't seem to reference tlog from the original form into the new login form. Therefore it won't print the api header returns and enable the login?

      Any help would be appreciated


      Code:
      Private Sub Bok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bok.Click
              Dim oLoginReq As New BFGlobal.LoginReq
              Dim oLoginResp As BFGlobal.LoginResp
              With oLoginReq
                  .username = Tbuser.Text
                  .password = Tbpass.Text
                  .productId = 82           'For free API
              End With
      
              oLoginResp = BetfairGL.login(oLoginReq)     'Call the API
              With oLoginResp
                  CheckHeader(.header)
                  Call Print("ErrorCode = " & .errorCode.ToString)
      
              End With
          End Sub
      Last edited by thewhistler; 30-06-2010, 04:07 PM.

      Comment

      • Mumbles0
        Junior Member
        • Jan 2009
        • 240

        #348
        Adding a Login form

        Whistler,

        I think you are having trouble trying to access members on the original form from your new Login form. You should be getting compiler errors because of this.

        Let’s assume that you have a main form (TestForm) which contains the existing code and you’ve added a new form (LoginForm) which has TextBoxes for User Name and Password entry.


        The TestForm code could be like this:

        Code:
        [COLOR="Gray"]Public Class TestForm
        
          [COLOR="Black"]Friend[/COLOR] BetFairGL As New BFGlobal.BFGlobalService      'The UK ExchangeService object
          Private SessionToken As String
        
          [COLOR="Black"]Private Sub bLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bLogin.Click
            LoginForm.Show()     'Display the Login form
          End Sub[/COLOR]
        
          [COLOR="Black"]Friend[/COLOR] Sub Print(ByVal Message As String)
            With tLog
              .SelectionStart = .Text.Length
              .SelectedText = vbCrLf & Message
            End With
          End Sub
        
         [COLOR="Black"] Friend[/COLOR] Sub CheckHeader(ByVal Header As BFGlobal.APIResponseHeader)
            With Header
              Print("HeaderCode = " & .errorCode.ToString)
              SessionToken = .sessionToken
            End With
          End Sub
        
          ...............
          ...............
          ...............
        
        End Class[/COLOR]
        Because the LoginForm code requires access to three members of the TestForm class (the object variable BetfairGL, Sub CheckHeader and Sub Print) we add the Friend keyword to permit this. This is called an access modifier and allows the member to be accessed from any other part of the project. Note that BetfairGL was originally declared Private, hence it was only accessible from code within the TestForm class.

        When the Login button is clicked the LoginForm is displayed (using the .Show method).

        LoginForm contains the code which performs the Login operation when the OK button is clicked:

        Code:
        [COLOR="Gray"]Public Class LoginForm
        
          Private Sub Bok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOK.Click
        
            Dim oLoginReq As New BFGlobal.LoginReq
            Dim oLoginResp As BFGlobal.LoginResp
        
            With oLoginReq
              .username = TBuser.Text
              .password = TBpass.Text
              .productId = 82           'For free API
            End With
        
            oLoginResp = [COLOR="Black"]TestForm.[/COLOR]BetFairGL.login(oLoginReq)     'Call the API
        
            With oLoginResp
              [COLOR="Black"]TestForm.[/COLOR]CheckHeader(.header)
              [COLOR="Black"]TestForm.[/COLOR]Print("ErrorCode = " & .errorCode.ToString)
            End With
        
          End Sub
        
        End Class[/COLOR]
        Because LoginForm views TestForm as being an external object, we must include the prefix TestForm whenever we refer to one of TestForm's members to let the compiler know what object these members belong to. (I hope that makes sense.)

        Try it. You should be able to login now.

        Comment

        • thewhistler
          Junior Member
          • Jun 2010
          • 3

          #349
          Ahhhh, so by declaring friend it basically allows reference from any form.

          Fantastic, works perfectly added in me.close at the end of the login so the window closes.

          Now have a fully functioning little login window


          I have since created a grid view form and plan to pull a table of runners for a specific market into the grid view.


          The table fields are as follows

          Checkbox (this will be used as my horse selection box)
          market Id text field
          Runner Name
          Back Odds
          Lay Odds
          Start Time
          Market Name
          Date


          I currently click through my list box menu and it provides today's racing market which double clicking on whatever market will return the market ID in Tlog

          At this point I am not sure how to reference the clicked market ID so I copy paste the number into input boxes I have created for runners and market prices.

          My main problem at this point is how to pull the data into the grid view from the tlog.

          Code for odds:

          Code:
           Sub ShowMprices(ByVal MpriceResp As BFUK.GetMarketPricesResp)
                  Dim Lay, Back As String
                  With MpriceResp
                      CheckHeader(.header)
                      Print("ErrorCode = " & .errorCode.ToString)
                      If .errorCode = BFUK.GetMarketPricesErrorEnum.OK Then
                          With .marketPrices
                              Print("MarketID = " & .marketId)
                              For i = 0 To .runnerPrices.Length - 1
                                  With .runnerPrices(i)
                                      Print("Runner " & i + 1 & "  LPM = " & .lastPriceMatched)
                                      Back = ""
                                      For j = 0 To .bestPricesToBack.Length - 1
                                          With .bestPricesToBack(j)
                                              Back = Back & "  " & .price & "/" & Int(.amountAvailable)
                                          End With
                                      Next
                                      Lay = ""
                                      For j = 0 To .bestPricesToLay.Length - 1
                                          With .bestPricesToLay(j)
                                              Lay = Lay & "  " & .price & "/" & Int(.amountAvailable)
                                          End With
                                      Next
                                      Print("Back = " & Back & "   Lay = " & Lay)
                                  End With
                              Next
                          End With
                      End If
                  End With
              End Sub

          Code for markets

          Code:
          Private Sub bMarkets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bmarkets.Click
                  Print("*** Horse Racing - Today's Card ***")
                  Dim oMarketsReq As New BFUK.GetAllMarketsReq
                  Dim oMarketsResp As BFUK.GetAllMarketsResp
          
                  With oMarketsReq
                      .header = oHeaderUK()
                      ReDim .eventTypeIds(0) : .eventTypeIds(0) = 7   'For horse racing
                      ReDim .countries(1) : .countries(0) = "GBR" : .countries(1) = "IRL"
                      .fromDate = Today
                      .toDate = Today.AddDays(1)
                  End With
                  oMarketsResp = BetFairUK.getAllMarkets(oMarketsReq)
                  With BetFairUK.getAllMarkets(oMarketsReq)  'Call getAllMarkets
                      CheckHeader(.header)
                      Print("ErrorCode = " & .errorCode.ToString)
                      If .errorCode = BFUK.GetAllMarketsErrorEnum.OK Then
                          Dim AllMarkets As New UnpackAllMarkets(.marketData)
                          Dim Names As String(), TodaysCard As New List(Of MarketDataType)
                          With AllMarkets
                              For i = 0 To .marketData.Length - 1
          
                                  Names = .marketData(i).menuPath.Split("\")   'This is the filter
                                  If Names.Length = 4 AndAlso Not Names(3).StartsWith("Daily") Then
                                      If .marketData(i).noOfWinners = 1 Then
          
                                          TodaysCard.Add(.marketData(i))    'Add win markets only
                                      End If
                                  End If
          
                              Next
                          End With
          
          
          
                          TodaysCard.Sort(New CompareMarketTimes)   'Sort according to market times 
                          For Each Race In TodaysCard    'Print the card
                              With Race
                                  Names = .menuPath.Split("\")
                                  lbmarkets.Items.Add(.eventDate.ToLocalTime.TimeOfDay.ToString & " " & .marketId & " " & Names(3) & " - " & .marketName)
                              End With
                          Next
          
                      End If
                  End With
          
              End Sub

          What I have been currently trying to do is dim .marketname into the gridview and print it in the column.

          My other thinking is to try and pull all the data into a datasource then pull it into the grid view.

          Although reading through the previous page I will see if I can achieve what I am after through table build
          Last edited by thewhistler; 02-07-2010, 03:50 PM.

          Comment

          • thewhistler
            Junior Member
            • Jun 2010
            • 3

            #350
            A little stuck

            I have build the basics of table build and all seems well and good.

            My main problem with the program still remains with the market id.

            Once I double click the market I am wanting to look at it prints the market id

            Code:
                 Private Sub lbMarkets_DoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lbmarkets.DoubleClick
                    Dim s As String, Part As String(), marketId As Integer
            
                    s = lbmarkets.SelectedItem    'The selected item
                    Part = s.Split(" ")           'Get the parts of the item separated by spaces
                    marketId = Val(Part(1))       'The marketId is the second part
                    Print("marketId = " & marketId)
            
            
            
            
                    Dim oCMPCreq As New BFUK.GetCompleteMarketPricesCompressedReq
                    With oCMPCreq
                        .header = oHeaderUK()
                        .marketId = marketId
                    End With
                    StateCount += 1
                    BetFairUK.getCompleteMarketPricesCompressedAsync(oCMPCreq, StateCount) 'Call the APi
            Which is marketID

            Is there a way to set this as the current market ID for a public string that can be used throughout all other requests, such as pressing buttons runners or prices?

            I have been trying to reference the marketID as it currently stands but keeps producing the error INVALID_MARKET.

            Perhaps I am missing a trick here

            Comment

            • Mumbles0
              Junior Member
              • Jan 2009
              • 240

              #351
              marketId

              Whistler,

              Access for marketId

              To make the marketId variable accessible from elsewhere in your project declare it outside the Sub using Friend (or Public):
              Friend marketId as Integer
              You must remove marketId from the Dim statement within the Sub. Note that marketId is an integer, not a string.

              Invalid market

              You tell me what’s wrong... What appears in tLog when you double click an item in the ListBox? Does it look like a valid market ID?

              Comment

              • waldjunge
                Junior Member
                • Apr 2009
                • 12

                #352
                Does anybody know which API command give me those information of a race:

                Group1
                Group2
                Group3

                Good to firm or Firm

                Handicap

                Thanks
                Martin

                Comment

                • gvigliani
                  Junior Member
                  • Jul 2010
                  • 17

                  #353
                  Events Function

                  Code:

                  Private Sub bEvents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bEvents.Click
                  Print("*** Events ***")
                  Dim oEventsReq As New BFGlobal.GetEventTypesReq 'Create the request object
                  Dim oEventsResp As BFGlobal.GetEventTypesResp 'Create a variable for the response object
                  oEventsReq.header = oHeaderGL 'Load request parameters
                  oEventsResp = BetfairGL.getActiveEventTypes(oEventsReq) 'Call the API
                  With oEventsResp
                  CheckHeader(.header) 'Check response header
                  Print("ErrorCode = " & .errorCode.ToString)
                  If .errorCode = BFGlobal.GetEventsErrorEnum.OK Then 'Check the response errorcode
                  For i = 0 To .eventTypeItems.Length - 1 'Process the received data
                  With .eventTypeItems(i)
                  Print(.name & " (" & .id & ")")
                  End With
                  Next
                  End If
                  End With
                  End Sub

                  ErrorCode=API_ERROR
                  Last edited by gvigliani; 15-07-2010, 05:37 PM. Reason: my error

                  Comment

                  • welcometomylair1
                    Junior Member
                    • Mar 2009
                    • 2

                    #354
                    Remember 'settings'

                    Hi Mumbles,

                    Thanks to your tutorial, I (like many others on here) have come on leaps and bounds in terms of vb programming and betting with the Betfair API - I would like to add my gratitude to the growing list!

                    I have a vb question which is not exactly related to the API that I was wondering if you could help with:

                    Let's say I am using the API to poll Betfair markets and I have a slider bar for 'frequency', a textbox which contains the location of the output file and any number of other customisible settings. What in your opinion would be the best way to 'remember' these settings so that if I adjust the frequency those adjustments are recorded and restored next time I load the application.

                    Hope that makes sense!

                    Thanks in advance

                    Comment

                    • Mumbles0
                      Junior Member
                      • Jan 2009
                      • 240

                      #355
                      Api_Error

                      gvigliani,

                      If the response's .errorcode is API_ERROR then the response's header.errorCode will give the reason. This is "printed" by the CheckHeader sub.

                      API_ERROR occurs if header.errorCode is anything other than OK.

                      Comment

                      • Mumbles0
                        Junior Member
                        • Jan 2009
                        • 240

                        #356
                        Saving your settings.

                        welcometomylair1,

                        If you want to save settings from one run to the next they must be saved in a file somewhere. There are many ways this can be done.

                        It’s fairly simple to extend the way we save the session token in the text file "SessToken.txt" so that other values are saved too. In step 3 we saved the session token in a text file with a single statement in the FormClosing event handler:

                        Code:
                        Private Sub TestForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
                        
                          My.Computer.FileSystem.WriteAllText(SessTokFile, oHeaderGL.sessionToken, False)
                        
                        End Sub
                        This sub executes whenever you close the form. To save other values too try something like this:

                        Code:
                        Private Sub TestForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
                        
                          With My.Computer.FileSystem.OpenTextFileWriter(SessTokFile, False)
                        
                            .WriteLine(oHeaderGL.sessionToken)   'Save the session token
                            .WriteLine(Setting1)                'Save setting 1
                            .WriteLine(Setting2)               'Save setting 2
                            .WriteLine(Setting3)              'Save setting 3
                            			             'etc.
                            .Close()                        'Done
                          End With
                        
                        End Sub
                        Here the settings can be any variable, object property or expression you like. You can examine what’s been written with Notepad. Note that each value appears on a new line in the file.

                        To read back the values when you restart your project change the Load event handler to incorporate the corresponding file reading code:

                        Code:
                        Private Sub TestForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
                        
                          With My.Computer.FileSystem.OpenTextFileReader(SessTokFile)
                        
                            oHeaderGL.sessionToken = .ReadLine   'Read the session token
                            Setting1 = .ReadLine                'Read setting 1
                            Setting2 = .ReadLine               'Read setting 2
                            Setting3 = .ReadLine              'Read setting 3
                        			             'etc.
                            .Close()                        'Done 
                          End With
                        
                          .......
                          .......
                        
                        End Sub
                        This sub executes whenever you restart your project, restoring your previously saved setting values. Note that the .ReadLine method returns the next line from the file as a string. If you are restoring a numeric value it’s more robust to use the Val function, for example:

                        Freq = Val(.ReadLine) 'Restore Freq setting
                        This will return zero if the line contains a non-numeric value or doesn’t exist.

                        Comment

                        • waldjunge
                          Junior Member
                          • Apr 2009
                          • 12

                          #357
                          I place Back and Lay bets with the PlaceBets object. Back bets are placed with 1.1 to get automatically the best Back price. It works fine without any problems.

                          In the past I placed Lay bets with a price of: price +3 to be sure to get automatically the best Lay price. Lay betting has worked also in the past.

                          Dim oPlaceBetsReq As New BFUK.PlaceBetsReq 'Create the request object
                          Dim oPlaceBetsResp As BFUK.PlaceBetsResp 'A variable to hold the response object

                          Now when I place a Lay bet, the oPlaceBetsResp.errorcode is OK, but in the next step I get oPlaceBetsResp.resultcode=FROM_COUNTRY_FORBIDDEN

                          I am betting from UK. Why do I get first a OK message, and in the next step "FROM_COUNTRY_FORBIDDEN "?

                          oPlaceBetsResp.errorCode = BFUK.PlaceBetsErrorEnum.OK
                          oPlaceBetsResp.resultCode = BFUK.PlaceBetsErrorEnum.FROM_COUNTRY_FORBIDDEN

                          Thanks for help
                          Martin

                          Comment

                          • waldjunge
                            Junior Member
                            • Apr 2009
                            • 12

                            #358
                            Bet less then minimum stake

                            I have tried to write code for betting less then the minimum stake for Lay betting, according to this guideline.

                            'Documentation will not help you with this issue. Trick is to do it in few steps.
                            'If you want, for example, to place £0.1 bet then place regular £2 bet on highest quote (1000 if you want to back)
                            'or lowest quote (1.01 if you want to lay). The bet will not be matched.
                            'Change its amount to 2.1£ and as result you will have two bets: one with £2 and the other with £0.1 amount.
                            'Cancel first one, change £0.1 bet quote on the desired value and that's it

                            But I can not really update the bet to get a new betID and a new stake.





                            Code:
                            Private Sub betSmallStake()                         'Place bet less then the minimum Stake of 2 on LAY bets
                                    Dim oPlaceBetsReq As New BFUK.PlaceBetsReq      'Create the request object
                                    Dim oPlaceBetsResp As BFUK.PlaceBetsResp        'A variable to hold the response object
                                    Dim oBet As New BFUK.PlaceBets                  'An object to specify the bet
                            
                                    Dim oUpdateBetsReq As New BFUK.UpdateBetsReq
                                    Dim oUpdateBetsResp As New BFUK.UpdateBetsResp
                                    Dim oUpdateFrage As New BFUK.UpdateBets
                                    Dim oUpdateAnswer As New BFUK.UpdateBetsResult
                            
                                    Dim ersteBET As Long
                                    Dim neueBetID As Long
                            
                                    Dim YourMarket As Long
                                    Dim YourSelection As Long
                                    Dim YourBetType As New BFUK.BetTypeEnum
                                    Dim BetSize, BetPrice As Double
                            
                                    YourMarket = 101560066
                                    YourSelection = 3079062
                                    YourBetType = BFUK.BetTypeEnum.L
                                    BetSize = 0.1
                                    BetPrice = 1.01
                            
                            
                                    'Documentation will not help you with this issue. Trick is to do it in few steps. 
                                    'If you want, for example, to place £0.1 bet then place regular £2 bet on highest quote (1000 if you want to back) 
                                    'or lowest quote (1.01 if you want to lay). The bet will not be matched. 
                                    'Change its amount to 2.1£ and as result you will have two bets: one with £2 and the other with £0.1 amount. 
                                    'Cancel first one, change £0.1 bet quote on the desired value and that's it
                            
                                    With oPlaceBetsReq
                                        .header = oHeaderUK()            'The standard header
                                        With oBet                        'Specify the bet details:
                                            .asianLineId = 0             'Non-asian handicap market 
                                            .betCategoryType = BFUK.BetCategoryTypeEnum.E    'Normal exchange bet
                                            .betPersistenceType = BFUK.BetPersistenceTypeEnum.NONE  'Standard bet (not SP or InPlay persistence)
                                            .betType = YourBetType       'Back or Lay
                                            .marketId = YourMarket       'The market of interest
                                            .price = 1.01                'The desired price (odds)
                                            .selectionId = YourSelection 'Your selection of interest
                                            .size = 2                    'The bet amount (stake)
                                            .bspLiability = 0            'Must be 0 for non-SP bet
                                        End With
                                        ReDim .bets(0)    'Array length = 1 to hold single bet
                                        .bets(0) = oBet   'Put the bet details object in element 0
                                    End With
                            
                                    oPlaceBetsResp = BetFairUK.placeBets(oPlaceBetsReq)
                            
                                    With oPlaceBetsResp                                             ' Place 1. bet 
                                        If .errorCode = BFUK.PlaceBetsErrorEnum.OK Then
                                            With .betResults(0)
                                                If .success Then
                                                    ersteBET = .betId
                            
                                                    '----------------------------------------------- ' Update 1. bet - Change Price and Stakesize
                                                    With oUpdateBetsReq
                                                        .header = oHeaderUK()            'The standard header
                                                        With oUpdateFrage
                                                            .oldBetPersistenceType = BFUK.BetPersistenceTypeEnum.NONE
                                                            .newBetPersistenceType = BFUK.BetPersistenceTypeEnum.NONE
                                                            .betId = ersteBET
                            
                                                            .oldPrice = 1.01
                                                            '.newPrice = 9.8
                            
                                                            .oldSize = 2
                                                            .newSize = 2.1
                                                        End With
                                                    End With
                            
                                                    oUpdateBetsResp = BetFairUK.updateBets(oUpdateBetsReq)
                            
                                                    With oUpdateBetsResp
                                                        CheckHeader(.header)
                                                        If .errorCode = BFUK.UpdateBetsErrorEnum.OK Then box("Error OK ")
                                                        With oUpdateAnswer
                                                            If .resultCode = BFUK.UpdateBetsResultEnum.OK Then box("   Update A OK " & .success)
                                                            If .success = True Then
                                                                neueBetID = .newBetId '?
                                                                BetPrice = .newPrice  '?
                                                                BetSize = .newSize    '?
                                                                cancelBets(ersteBET)  '?
                                                            End If
                                                        End With
                                                    End With
                                                End If
                                            End With
                                        End If
                                    End With
                                End Sub
                            
                                Sub CancelBet(ByVal betId As Long)
                            
                                    Dim oCancelBetsReq As New BFUK.CancelBetsReq   'Create the request object
                                    Dim oCancelBetsResp As BFUK.CancelBetsResp     'A variable to hold the response object
                                    With oCancelBetsReq
                                        .header = oHeaderUK()      'The standard request header
                                        ReDim .bets(0)                    'Single element array
                                        .bets(0) = New BFUK.CancelBets    'Create an object of type CancelBets
                                        .bets(0).betId = betId          'The BetId to be cancelled
                                    End With
                            
                                    oCancelBetsResp = BetFairUK.cancelBets(oCancelBetsReq)  'Call API to cancel the bet
                            
                                    With oCancelBetsResp     'The response
                                        CheckHeader(.header)
                                        Print("ErrorCode = " & .errorCode.ToString)
                                        If .errorCode = BFUK.CancelBetsErrorEnum.OK Then  'The call succeeded
                                            For i = 0 To .betResults.Length - 1   'In this case there should only be one result
                                                With .betResults(i)
                                                    Print(.resultCode.ToString)   'The result of the cancellation
                                                    If .success Then Print("BetId " & .betId & " cancelled")
                                                End With
                                            Next
                                        End If
                                    End With
                            
                                End Sub

                            Comment

                            • mbrylski
                              Junior Member
                              • Jul 2010
                              • 5

                              #359
                              Problem with deserialize

                              Hi Mumbles,

                              Thank you for the great tutorial it is very helpful. But I have a problem with function “getAllMarkets” almost all the time I receive error.

                              “Error in deserializing body of reply message for operation 'getAllMarkets'.”

                              I have no idea how to solve this problem. If you can please help me.

                              Code:
                                 Private Sub bMarkets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bMarkets.Click
                                      Print("*** Markets ***")
                                      Dim oMarketsReq As New BFUK.GetAllMarketsReq
                                      Dim oMarketsResp As BFUK.GetAllMarketsResp
                                      With oMarketsReq
                                          .header = oHeaderUK()
                                          ReDim .eventTypeIds(0) : .eventTypeIds(0) = 1
                                          .fromDate = Today.AddDays(2)
                                          .toDate = Today.AddDays(3)
                              
                                      End With
                                      oMarketsResp = BetFairUK.getAllMarkets(oMarketsReq)  'Call the UK API
                                      With oMarketsResp
                                          CheckHeader(.header)
                                          Print("ErrorCode = " & .errorCode.ToString)
                                          If .errorCode = BFUK.GetAllMarketsErrorEnum.OK Then
                                              Dim AllMarkets As New UnpackAllMarkets(.marketData)   'Create an object and unpack the string
                                              With AllMarkets
                                                  For i = 0 To .marketData.Length - 1
                                                      With .marketData(i)
                                                          Print(.marketId & " " & .marketStatus & "  " & .marketName & "  " & .menuPath)
                                                      End With
                                                  Next
                                              End With
                                          End If
                                      End With
                                  End Sub
                              Code:
                              System.ServiceModel.CommunicationException was unhandled
                                Message=Error in deserializing body of reply message for operation 'getAllMarkets'.
                                Source=mscorlib
                                StackTrace:
                                  Server stack trace: 
                                     at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)
                                     at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)
                                     at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
                                     at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeReply(Message message, Object[] parameters)
                                     at System.ServiceModel.Dispatcher.ProxyOperationRuntime.AfterReply(ProxyRpc& rpc)
                                     at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
                                     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
                                     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
                                     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
                                  Exception rethrown at [0]: 
                                     at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
                                     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
                                     at TestForm.BFUK.BFExchangeService.getAllMarkets(getAllMarketsIn request)
                                     at TestForm.BFUK.BFExchangeServiceClient.BFUK_BFExchangeService_getAllMarkets(getAllMarketsIn request) in C:\Users\Dom\documents\visual studio 2010\Projects\TestForm\TestForm\Service References\BFUK\Reference.vb:line 12966
                                     at TestForm.BFUK.BFExchangeServiceClient.getAllMarkets(GetAllMarketsReq request) in C:\Users\Dom\documents\visual studio 2010\Projects\TestForm\TestForm\Service References\BFUK\Reference.vb:line 12972
                                     at TestForm.Form1.bMarkets_Click(Object sender, EventArgs e) in C:\Users\Dom\documents\visual studio 2010\Projects\TestForm\TestForm\Form1.vb:line 104
                                     at System.Windows.Forms.Control.OnClick(EventArgs e)
                                     at System.Windows.Forms.Button.OnClick(EventArgs e)
                                     at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
                                     at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
                                     at System.Windows.Forms.Control.WndProc(Message& m)
                                     at System.Windows.Forms.ButtonBase.WndProc(Message& m)
                                     at System.Windows.Forms.Button.WndProc(Message& m)
                                     at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                                     at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                                     at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                                     at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
                                     at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
                                     at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
                                     at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
                                     at System.Windows.Forms.Application.Run(ApplicationContext context)
                                     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
                                     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
                                     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
                                     at TestForm.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
                                     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
                                     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
                                     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
                                     at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
                                     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
                                     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
                                     at System.Threading.ThreadHelper.ThreadStart()
                                InnerException: System.InvalidOperationException
                                     Message=There is an error in XML document (2, 41100).
                                     Source=System.Xml
                                     StackTrace:
                                          at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
                                          at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)
                                     InnerException: System.Xml.XmlException
                                          LineNumber=0
                                          LinePosition=0
                                          Message=The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 2, position 41100.
                                          Source=System.Runtime.Serialization
                                          StackTrace:
                                               at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
                                               at System.Xml.XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, Int32 maxStringContentLength)
                                               at System.Xml.XmlDictionaryReader.ReadString(Int32 maxStringContentLength)
                                               at System.Xml.XmlDictionaryReader.ReadString()
                                               at System.Xml.XmlBaseReader.ReadElementString()
                                               at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBFExchangeService.Read32_GetAllMarketsResp(Boolean isNullable, Boolean checkType)
                                               at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBFExchangeService.Read154_getAllMarketsResponse()
                                               at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer8.Deserialize(XmlSerializationReader reader)
                                               at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
                                          InnerException:
                              Last edited by mbrylski; 25-07-2010, 03:08 PM.

                              Comment

                              • Mumbles0
                                Junior Member
                                • Jan 2009
                                • 240

                                #360
                                Reply to mbrylski (re: getAllMarkets problem)

                                Message=The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 2, position 41100.
                                This error can occur when a large amount of data is returned by getAllMarkets. The length of the returned .marketData string exceeds a limit. The call should work if you request only a small number of markets.

                                As mentioned in the error message, the MaxStringContentLength property should be increased, but I don’t know how to do this.

                                Other people have had this problem too. Can someone suggest a way to fix it?

                                Comment

                                Working...
                                X