/// <summary>
        /// Factory for the  of the xServer generated client class granting access to the xRoute server.
        /// If xServers are used on an Azure environment, authentication data has to be integrated when
        /// requests are made.
        /// </summary>
        /// <param name="xUrl">The xServer base url. </param>
        /// <returns></returns>
        public static XTourWSClient CreateXTourClient(string xUrl)
        {
            string completeXServerUrl = XServerUrl.Complete(xUrl, "XTour");

            var binding = new BasicHttpBinding
            {
                ReceiveTimeout         = new TimeSpan(0, 0, 30),
                MaxReceivedMessageSize = int.MaxValue
            };

            var endpoint = new EndpointAddress(completeXServerUrl);
            var client   = new XTourWSClient(binding, endpoint);

            if (!XServerUrl.IsXServerInternet(completeXServerUrl))
            {
                return(client);
            }

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            client.ClientCredentials.SetConfiguredToken();

            return(client);
        }
        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            // reset old plan
            scenario.Tours = new List <Tour>();
            foreach (var o in scenario.Orders)
            {
                o.Tour = null;
            }

            var xTour = new XTourWSClient();

            if (xTour.ClientCredentials != null)
            {
                xTour.ClientCredentials.UserName.UserName = "******";
                xTour.ClientCredentials.UserName.Password = App.Token;
            }

            TransportOrder[] orders = (from o in scenario.Orders
                                       select new TransportDepot
            {
                id = orderMap.B2X(o, o.Id),
                transportPoint = new TransportPoint
                {
                    id = orderMap.B2X(o, o.Id),
                    servicePeriod = 0,                // 0sec; unrealistic but okay for this sample
                    location = new Point
                    {
                        point = new PlainPoint
                        {
                            x = o.Longitude,
                            y = o.Latitude
                        }
                    },
                    openingIntervalConstraint = OpeningIntervalConstraint.START_OF_SERVICE
                },
                deliveryQuantities = new Quantities {
                    wrappedQuantities = new[] { o.Quantity }
                }
            }).ToArray();

            var depots = (from d in scenario.Depots
                          select new XTourServiceReference.Depot
            {
                id = depotMap.B2X(d, d.Id),
                location = new Point
                {
                    point = new PlainPoint
                    {
                        y = d.Latitude,
                        x = d.Longitude
                    }
                }
            }).ToArray();

            var allVehicles = (from d in scenario.Depots select d.Fleet).SelectMany(x => x);

            var interval = new Interval
            {
                from = 0,
                till = Convert.ToInt32(scenario.OperatingPeriod.TotalSeconds)
            };

            var vehicles = (from v in allVehicles
                            select new XTourServiceReference.Vehicle
            {
                id = vehicleMap.B2X(v, v.Id),
                depotIdStart = depotMap.B2X(v.Depot, v.Depot.Id),
                depotIdEnd = depotMap.B2X(v.Depot, v.Depot.Id),
                isPreloaded = false,
                capacities = new Capacities
                {
                    wrappedCapacities = new[] { new Quantities {
                                                    wrappedQuantities =
                                                        new[] { v.Capacity }
                                                } }
                },
                wrappedOperatingIntervals = new[] { interval },
                dimaId = 1,
                dimaIdSpecified = true
            }).ToArray();

            var fleet = new Fleet {
                wrappedVehicles = vehicles
            };

            var planningParams = new StandardParams
            {
                wrappedDistanceMatrixCalculation = new DistanceMatrixCalculation[]
                {
                    new DistanceMatrixByRoad
                    {
                        dimaId                                 = 1,
                        deleteBeforeUsage                      = true,
                        deleteAfterUsage                       = true,
                        profileName                            = scenario.Profile,
                        enforceHighPerformanceRouting          = true, // requires xTour >= 1.32
                        enforceHighPerformanceRoutingSpecified = true
                    }
                },
                availableMachineTime          = 5,
                availableMachineTimeSpecified = true
            };

            var xTourJob = xTour.startPlanBasicTours(orders, depots, fleet, planningParams, null,
                                                     new CallerContext
            {
                wrappedProperties = new[] {
                    new CallerContextProperty {
                        key = "CoordFormat", value = "OG_GEODECIMAL"
                    },
                    //new CallerContextProperty { key = "TenantId", value = Guid.NewGuid().ToString() }
                }
            });

            backgroundWorker.ReportProgress(-1, xTourJob);
            var status = xTourJob.status;

            while (status == JobStatus.QUEUING || status == JobStatus.RUNNING || status == JobStatus.STOPPING)
            {
                if (backgroundWorker.CancellationPending)
                {
                    xTour.stopJob(xTourJob.id, null);
                    e.Cancel = true;
                    return;
                }

                xTourJob = xTour.watchJob(xTourJob.id, new WatchOptions
                {
                    maximumPollingPeriod          = 500,
                    maximumPollingPeriodSpecified = true,
                    progressUpdatePeriod          = 500,
                    progressUpdatePeriodSpecified = true
                }, null);
                status = xTourJob.status;

                backgroundWorker.ReportProgress(-1, xTourJob);

                // wait a bit on the client-side to reduce network+server load
                System.Threading.Thread.Sleep(500);
            }

            var result = xTour.fetchPlan(xTourJob.id, null);

            scenario.Tours = new List <Tour>();
            foreach (var c in result.wrappedChains)
            {
                foreach (var wt in c.wrappedTours)
                {
                    var tour = new Tour();

                    var tourPoints = new List <TourPoint>();
                    foreach (var tourPoint in wt.wrappedTourPoints)
                    {
                        switch (tourPoint.type)
                        {
                        case TourPointType.DEPOT:
                            tourPoints.Add(new TourPoint
                            {
                                Longitude = depotMap.X2B(tourPoint.id).Longitude,
                                Latitude  = depotMap.X2B(tourPoint.id).Latitude
                            });
                            break;

                        case TourPointType.TRANSPORT_POINT:
                            orderMap.X2B(tourPoint.id).Tour = tour;
                            tourPoints.Add(new TourPoint
                            {
                                Longitude = orderMap.X2B(tourPoint.id).Longitude,
                                Latitude  = orderMap.X2B(tourPoint.id).Latitude
                            });
                            break;
                        }
                    }

                    tour.Vehicle    = vehicleMap.X2B(c.vehicleId);
                    tour.TourPoints = tourPoints;
                    scenario.Tours.Add(tour);
                }
            }
        }