API-NG: C# Example

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Peter Simple
    Junior Member
    • Aug 2009
    • 32

    #1

    API-NG: C# Example

    I post here my my little C# solution to get access to the new API.I had some problems running the official example and it is in my opinion to complex to give you an insight about the work flow. My code is more protoypical so that i could understand much better the basic operations. That`s why you will not find any error handling because i run the code in the debugger.

    To reproduce the project you should create a new project with Visual Studio. Then you should add Newtonsoft Json (VS 2012 has a nice NuGet installer - menu: Projects / look for online submittals). We add now a new class "ResponseClass". On the "form 1" i have dropped a simple button and added the following code:

    Code:
    private void button1_Click(object sender, EventArgs e)
            {
                ResponseClass resp = new ResponseClass();
                resp.ResponseTest();
            }
    Our aim is to make a simple request that should reutrn all EventTypes. The filter should be empty. To create the correct Json i use "Linq to JSON".

    We are going now to the ResponseClass form. We add the following using directives:

    Code:
    using System.Net;
    using System.IO;
    using Newtonsoft.Json.Linq;
    At the end we insert the EventTypes Class. The class is empty because we have no filter criteria and my first aim was to get a json response so that i know that the request code works.

    Code:
    public class EventTypes
        { }
    Here is the code of the ResponseClass. It is based on the official "code snippet" (https://api.developer.betfair.com/se...pageId=3834049)and for the JSON part i used the Json.Net Documentation (http://james.newtonking.com/json/help/index.html) / Samples / LINQ to JSON / Create Json form anonymous Type)

    Code:
    public class ResponseClass : WebClient
        {
            public void ResponseTest()
            {
                // 1. Request Object
    
                string token = "your_token";
                string key = "your_app_key"; // delayed AppKey
                string address = "https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/";
    
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = 0;
                request.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");
                request.Accept = "application/json";
                request.Headers.Add("X-Application", key);
                request.Headers.Add("X-Authentication", token);
    
                // 2. Market Filter (as JSON)
                JObject postData = CreateFilter();
    
                // 3. Transfer MarketFilter in Request
                var bytes = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
                request.ContentLength = bytes.Length;
    
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
    
                // 4. Get WebResponse 
                
                WebResponse response = GetWebResponse(request);
    
                // 5. Process Response
    
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    var jsonResponse = reader.ReadToEnd();
                    string result = jsonResponse;
                }
    
            }
    
            public JObject CreateFilter()
            {
                List<EventTypes> evt = new List<EventTypes> 
                {
                    new EventTypes
                    {
                    } 
                };
    
                JObject json_obj = JObject.FromObject(new
                {
                    filter = new
                    {
                    }
                });
    
                return json_obj;
            }
        }
    As result of the operation you will get string with all datas but interpreting these datas will be much easier. I struggled a long time to get a response. At moment i think that writing the code in VB is more difficult because the syntax in VB is not suited for JSON. There will be of course a solution, but this will be done by better programmers. I do not claim that i present the best solution but i have not now a solution which i understand and from here i can build on.
  • kawafan
    Junior Member
    • May 2011
    • 33

    #2
    are u going to expand your examples to more complex situations like building tree view type hierarchy.

    Comment

    • Peter Simple
      Junior Member
      • Aug 2009
      • 32

      #3
      That may be possible. At the moment i explore an other idea. To create a filter it should be possible to create a XML element and convert it to JSON. JSON.net supports it. This would also help Visual Basic.

      Comment

      • davecon
        Junior Member
        • Dec 2010
        • 86

        #4
        Hi Peter
        Thanks for taking the time to post this as nobody else seems to be interested in helping us amateurs on here
        I was intrigued how you used Jobject in the request and I will have to take a look at this in vbnet as I dont use C# and cant convert it
        However at the moment I can get everything by using the full String horror which has to be with Double Double quotes (You Can split it of course for actual use with controls and functions etc)
        So this is the similar request for Json Rpc I use in VBNet for Market Catalogue for First 6 Horse Races for all you other Netters out there
        You Will need to add the Textboxes and Buttons of Course
        Code:
         '~~> Begin Request Strings Json Rpc Web Request
            Function CreateRequest(AppKey As String, SessToken As String, postData As String)
                Dim Url As String = "https://api.betfair.com/exchange/betting/json-rpc/v1/"
                Dim request As WebRequest = Nothing
                Dim dataStream As Stream = Nothing
                Dim response As WebResponse = Nothing
                Dim strResponseStatus As String = ""
                Dim reader As StreamReader = Nothing
                Dim responseFromServer As String = ""
                Try
                    request = WebRequest.Create(New Uri(Url))
                    request.Method = "POST"
                    request.ContentType = "application/json-rpc"
                    request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                    request.Headers.Add("X-Application", AppKey)
                    request.Headers.Add("X-Authentication", SessToken)
                    '~~> Data to post such as ListEvents, ListMarketCatalogue etc
                    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
                    '~~> Set the ContentLength property of the WebRequest.
                    request.ContentLength = byteArray.Length
                    '~~> Get the request stream.
                    dataStream = request.GetRequestStream()
                    '~~> Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length)
                    '~~> Close the Stream object.
                    dataStream.Close()
                    '~~> Get the response.
                    response = request.GetResponse()
                    '~~> Display the status below if required
                    '~~> Dim strStatus as String = CType(response, HttpWebResponse).StatusDescription
                    strResponseStatus = CType(response, HttpWebResponse).StatusDescription
                    '~~> Get the stream containing content returned by the server.
                    dataStream = response.GetResponseStream()
                    '~~> Open the stream using a StreamReader for easy access.
                    reader = New StreamReader(dataStream)
                    '~~> Read the content.
                    responseFromServer = reader.ReadToEnd()
                    '~~> Display the content below if required
                    '~~>Dim strShowResponse as String = responseFromServer  '~~>If required
                Catch ex As Exception
                    '~~> Show any errors in this method for an error log etc Just use a messagebox for now
                    MsgBox("CreateRequest Error" & vbCrLf & ex.Message)
                End Try
                Return responseFromServer   '~~> Function Output
                '~~> Clean up the streams.
                reader.Close()
                dataStream.Close()
                response.Close()
            End Function '~~>Creates the requst for Data to be loaded
        '*** here is the Requst String for you to play around with the parameters
            Dim strCatReq = "{""jsonrpc"": ""2.0"",""method"":""SportsAPING/v1.0/listMarketCatalogue"",""params"":{""filter"":{""eventTypeIds"":[""7""],""marketCountries"":[""GB""] ,""marketTypeCodes"":[""WIN""]},""marketStartTime"":[],""venues"":[],""sort"":""FIRST_TO_START"",""maxResults"":""6"",""marketProjection"":[""RUNNER_DESCRIPTION"",""MARKET_START_TIME"",""EVENT""],""marketStatus"":""OPEN"" },""id"": 1}"
        Then the Form Code to Display the Response
        Code:
         Private Sub btnTestJson_Click(sender As Object, e As EventArgs) Handles btnTestJson.Click
                txtTester.Text = CreateRequest(txtLiveKey.Text, txtSessionToken.Text, strCatReq)
            End Sub
        Hope this helps a few of you other greenies
        Dave

        Comment

        • Peter Simple
          Junior Member
          • Aug 2009
          • 32

          #5
          To create the json object XML is an interesting alternative. The Newtonsoft docu shows an interesting example how to use a XML node.

          This solution is perhaps not suited for Visual Basic because it has problems with literals like "<" when you use a selfcreated XML. Even creating a XElement does not help because Newtonsoft requires a node and converting a XElement in a XNode is not straigthforward. MSDN shows some workarounds for both problems but it adds a not necessary complexity to the code.

          Besides LINQ (as in my example) and XML an other way (and this seems best solution) is using Classes. I have now realized in a Visual Basic prototype which i will post soon.

          Comment

          • onix250
            Junior Member
            • Nov 2009
            • 6

            #6
            Hi, thank you for the example

            I would like to ask what is the best way to extract info the the response? (i mean no string operations sr regexes)

            [{"eventType":{"id":"468328","name":"Handball"},"ma rketCount":75},{"eventType":{"id":"1","name":"Socc er"},"marketCount":25670},{"eventType":{"id":"2"," name":"Tennis"},"marketCount":451},{"eventType":{" id":"3","name":"Golf"},"marketCount":55},{"eventTy pe":{"id":"4","name":"Cricket"},"marketCount":195} ,{"eventType":{"id":"5","name":"Rugby Union"},"marketCount":121},{"eventType":{"id":"6", "name":"Boxing"},"marketCount":14},{"eventType":{" id":"7","name":"Horse Racing"},"marketCount":212},{"eventType":{"id":"8" ,"name":"Motor Sport"},"marketCount":6},{"eventType":{"id":"7524" ,"name":"Ice Hockey"},"marketCount":493},{"eventType":{"id":"10 ","name":"Special Bets"},"marketCount":48},{"eventType":{"id":"11"," name":"Cycling"},"marketCount":5},{"eventType":{"i d":"451485","name":"Winter Sports"},"marketCount":7},{"eventType":{"id":"7522 ","name":"Basketball"},"marketCount":539},{"eventT ype":{"id":"1477","name":"Rugby League"},"marketCount":35},{"eventType":{"id":"433 9","name":"Greyhound Racing"},"marketCount":297},{"eventType":{"id":"62 31","name":"Financial Bets"},"marketCount":51},{"eventType":{"id":"23789 61","name":"Politics"},"marketCount":26},{"eventTy pe":{"id":"998917","name":"Volleyball"},"marketCou nt":2},{"eventType":{"id":"998919","name":"Bandy"} ,"marketCount":4},{"eventType":{"id":"998918","nam e":"Bowls"},"marketCount":20},{"eventType":{"id":" 26420387","name":"Mixed Martial Arts"},"marketCount":38},{"eventType":{"id":"3503" ,"name":"Darts"},"marketCount":95},{"eventType":{" id":"72382","name":"Pool"},"marketCount":1},{"even tType":{"id":"2152880","name":"Gaelic Games"},"marketCount":22},{"eventType":{"id":"6422 ","name":"Snooker"},"marketCount":224},{"eventType ":{"id":"27105927","name":"Winter Olympics 2014"},"marketCount":128},{"eventType":{"id":"6423 ","name":"American Football"},"marketCount":1},{"eventType":{"id":"75 11","name":"Baseball"},"marketCount":3}

            Comment

            • Peter Simple
              Junior Member
              • Aug 2009
              • 32

              #7
              You can look on my Visual Basic example. It should be easy to convert and the Json.Net documentation has also a similar example in C#.

              Comment

              • Drifter
                Junior Member
                • Mar 2009
                • 30

                #8
                By string token = "your_token"; are you referring to the session token?

                Do you not need code to login and get the ssoid first?

                Comment

                Working...
                X