C# .NET API Snippets


#1
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// Use a list of waypoints for convenience
List<Waypoint> wps = new List<Waypoint>();

// Create an add as many waypoints as needed. 
Waypoint wp = new Waypoint
{
                address = “address”,
                lat = Latitude,
                lng = StartLongitude
  };	


Wps.add(wp);

// Convert to an array prior to being converted in JSON.
   Waypoint[] Waypoints = wps.ToArray();

// Serialise array of waypoints into JSON using Newtonsoft
    string json = JsonConvert.SerializeObject(Waypoints);


APIReply OptimisedRoute;

byte[] responseArray;

NetworkCredential myNetworkCredential = new NetworkCredential(username, password);

using (var client = new ExtendedWebClient())
            {
                client.Timeout = -1;
                client.Credentials = myNetworkCredential;
                client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                NameValueCollection myNameValueCollection = new NameValueCollection();

                myNameValueCollection.Add("locations", json);

		// Service URL is the API URL
                responseArray = client.UploadValues(ServiceURL, myNameValueCollection);
            }


// Convert the response array into asci
   string ApiResponseJSONString = Encoding.ASCII.GetString(responseArray);

// Code for reading the route api return seems strange to me. I was expecting an array or list
// of waypoints items  but a series of classes numbered 0... onwards is returned
// the numerical nature of the class name then causes problems with deserialisation
// Work around this by looping through parameters
                dynamic ResponseRoute = Newtonsoft.Json.Linq.JObject.Parse(ApiResponseJSONString);

                // Get initial route attributes
                reply.id = ResponseRoute.id;
                reply.RouteFeasible = ResponseRoute.feasible;
                reply.RouteCount = ResponseRoute.count;

                // Get the entire route string
                string RouteString = Convert.ToString(ResponseRoute.route);
                dynamic Route = Newtonsoft.Json.Linq.JObject.Parse(RouteString);

                var RouteElements = Route.Children();

                foreach (JToken Element in RouteElements)
                {
                    ReplyPoint rp = new ReplyPoint();
                    foreach (JToken param in Element.Children())
                    {
                        rp.name = param["name"].ToString();
                        rp.arrival = (Int32)param["arrival"];
                        rp.distance = (double)param["distance"];
                    }
                    reply.ReplyPoints.Add(rp);
                }





public class Waypoint
    {
        public string address;
        public string lat;
        public string lng;
    }

// I pass the latitude/Longitude as part of the address and pass out using a $ delimiter. Not needed but convenient for the application
    public class ReplyPoint
    {
        public string name ;
        public Int32 arrival;
        public double distance;

        public double latitude
        { get
            {
                string[] fields = name.Split('$');                
                return Convert.ToDouble(fields[1]);
            }
        }

        public double longitude
        { get
            {
                string[] fields = name.Split('$');
                return Convert.ToDouble(fields[2]);
            }
        }

        public string addressonly
        {
            get
            {
                string[] fields = name.Split('$');
                return fields[0];
            }
        }



    }


// Used to prevent timeout of standard web client
public class ExtendedWebClient : WebClient
    {
        public int Timeout { get; set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request != null)
                request.Timeout = Timeout;
            return request;
        }

        public ExtendedWebClient()
        {
            Timeout = 100000; // the standard HTTP Request Timeout default
        }
    }

#2

Thank you for sharing this!

ps. I’ve adjusted the formatting a bit.


#3

Hi!
Can you explain about the type “APIReply” used for variable “OptimisedRoute”