C# .NET API Snippets

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
        }
    }
1 Like

Thank you for sharing this!

ps. I’ve adjusted the formatting a bit.

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

Thanks a lot for the sharing!
Copy and pase does not work for biginers as.
Could you please explain how the code should be implemented, the best way is to run the project in VS and then share it again, then nor errors should appear.

I have a cs file called RouteXL.cs that have this code inside.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace Library.RouteXl

{

    public class RouteXLConnector

    {

        private String url { get { return "https://api.routexl.com/"; } }

        

        private String utente;

        private String password;

        String auth

        {

            get

            {

                byte[] bytes = Encoding.GetEncoding(28591).GetBytes(utente + ":" + password);

                string toReturn = System.Convert.ToBase64String(bytes);

                return toReturn;

                

            }

        }

        public RouteXLConnector()

        {

        }

        public RouteXLConnector(String utente, String password)

        {

            this.ImpostaAutenticazione(utente, password);

        }

        public void ImpostaAutenticazione(String utente, String password)

        {

            this.utente = utente;

            this.password = password;

        }

        public RisultatoRouteXL Ottimizza(List<LocationRouteXl> listaLocalita)

        {

            RisultatoRouteXL res = new RisultatoRouteXL();

            String json = JsonConvert.SerializeObject(listaLocalita);

            RestClient client = new RestClient(this.url);

            RestRequest request = new RestRequest("tour", Method.POST);

            request.AddHeader("Authorization", "Basic " + auth);

            request.AddHeader("Accept", @"application\json");

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            

            request.AddParameter("locations", json, ParameterType.GetOrPost);

            IRestResponse response = client.Execute(request);

            

            Console.WriteLine(response.Content);

            String content = response.Content;

                        

            if (response.StatusCode != HttpStatusCode.OK)

            {

                res.Result = false;

                res.Message = "Richiesta di ottimizzazione fallita : " + response.StatusDescription + Environment.NewLine + content;

            }

            else

            {

                dynamic ResponseRoute = JObject.Parse(content);

                res.Risultato.id = ResponseRoute.id;

                res.Risultato.RouteFeasible = ResponseRoute.feasible;

                res.Risultato.RouteCount = ResponseRoute.count;

                // Get the entire route string

                string RouteString = Convert.ToString(ResponseRoute.route);

                dynamic Route = JObject.Parse(RouteString);

                var RouteElements = Route.Children();

                res.Risultato.ReplyPoints = new List<ReplyPoint>();

                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"];

                    }

                    res.Risultato.ReplyPoints.Add(rp);

                }

            }

            return res;

        }

    }

    public class LocationRouteXl

    {

        public String name { get; set; }

        public String lat { get; set; }

        public String lng { get; set; }

        public Int32 servicetime { get; set; }

        public RestrizioniLocation restrictions { get; set; }

    }

    public class RestrizioniLocation

    {

        public Int32 ready { get; set; }

        public Int32 due { get; set; }

        public Int32 before { get; set; }

        public Int32 after { get; set; }

    }

    public class RisultatoRouteXL

    {

        public String Message { get; set; }

        public Boolean Result { get; set; }

        public RisultatoOttimizzazione Risultato { get; set; }

        public RisultatoRouteXL ()

        {

            this.Result = true;

            this.Risultato = new RisultatoOttimizzazione();

        }

    }

    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

        }

    }

    public class ReplyPoint

    {

        public string name;

        public int 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];

            }

        }

    }

    public class RisultatoOttimizzazione

    {

        public string id { get; set; }

        public bool RouteFeasible { get; set; }

        public int RouteCount { get; set; }

        public List<ReplyPoint> ReplyPoints { get; set; }

    }

}

to use it you have to do so:

List<LocationRouteXl> routes = new List<LocationRouteXl>()
            {
                 new LocationRouteXl() { lat="41.901202", lng="12.499968", name="Start", servicetime=0 },
                new LocationRouteXl() { lat="41.901571", lng="12.459103", name="49491", servicetime=60 },
                new LocationRouteXl() { lat="41.901202", lng="12.499968", name="End", servicetime=0 }
            };

RouteXLConnector conn = new RouteXLConnector(routeXlLogin, routeXlPassword);
RisultatoRouteXL res = conn.Ottimizza(routes);
                if (!res.Result)
                {
                    // error handler
                }

i hope it helps.

1 Like