/// <summary>
        /// Configures the services to add to the ASP.NET MVC 6 Injection of Control (IoC) container. This method gets
        /// called by the ASP.NET runtime. See:
        /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureOptionsServices(services, this.Configuration);
            ConfigureCachingServices(services);

            // Add many MVC services to the services container.
            IMvcBuilder mvcBuilder = services.AddMvc(
                mvcOptions =>
            {
                ConfigureCacheProfiles(mvcOptions.CacheProfiles, this.Configuration);
                ConfigureSecurityFilters(mvcOptions.Filters);
                ConfigureContentSecurityPolicyFilters(mvcOptions.Filters);
                ConfigureFormatters(mvcOptions);
            });

            ConfigureFormatters(mvcBuilder);
            // $Start-Swagger$

            ConfigureSwagger(services, this.Configuration);
            // $End-Swagger$

            // Configure MVC routing. We store the route options for use by ConfigureSearchEngineOptimizationFilters.
            RouteOptions routeOptions = null;

            services.ConfigureRouting(
                x =>
            {
                routeOptions = x;
                ConfigureRouting(routeOptions);
            });

            ConfigureAntiforgeryServices(services);
            ConfigureCustomServices(services);
        }
        public void add_api_versioning_should_configure_mvc_with_custom_options()
        {
            // arrange
            var services     = new ServiceCollection();
            var mvcOptions   = new MvcOptions();
            var routeOptions = new RouteOptions();

            services.AddMvc();
            services.AddApiVersioning(
                o =>
            {
                o.ReportApiVersions  = true;
                o.ApiVersionReader   = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version"));
                o.ApiVersionSelector = new ConstantApiVersionSelector(new ApiVersion(DateTime.Today));
            });

            var serviceProvider    = services.BuildServiceProvider();
            var mvcConfiguration   = serviceProvider.GetRequiredService <IConfigureOptions <MvcOptions> >();
            var routeConfiguration = serviceProvider.GetRequiredService <IConfigureOptions <RouteOptions> >();

            // act
            mvcConfiguration.Configure(mvcOptions);
            routeConfiguration.Configure(routeOptions);

            // assert
            services.Single(sd => sd.ServiceType == typeof(IApiVersionReader)).ImplementationInstance.Should().NotBeNull();
            services.Single(sd => sd.ServiceType == typeof(IApiVersionSelector)).ImplementationInstance.Should().BeOfType <ConstantApiVersionSelector>();
            services.Single(sd => sd.ServiceType == typeof(IActionSelector)).ImplementationType.Should().Be(typeof(ApiVersionActionSelector));
            services.Single(sd => sd.ServiceType == typeof(ReportApiVersionsAttribute)).ImplementationType.Should().Be(typeof(ReportApiVersionsAttribute));
            mvcOptions.Filters.OfType <TypeFilterAttribute>().Single().ImplementationType.Should().Be(typeof(ReportApiVersionsAttribute));
            mvcOptions.Conventions.Single().Should().BeOfType <ApiVersionConvention>();
            routeOptions.ConstraintMap["apiVersion"].Should().Be(typeof(ApiVersionRouteConstraint));
        }
示例#3
0
    private static RouteContext CreateRouteContext(
        string requestPath,
        ILoggerFactory loggerFactory = null,
        RouteOptions options         = null)
    {
        if (loggerFactory == null)
        {
            loggerFactory = NullLoggerFactory.Instance;
        }

        if (options == null)
        {
            options = new RouteOptions();
        }

        var request = new Mock <HttpRequest>(MockBehavior.Strict);

        request.SetupGet(r => r.Path).Returns(requestPath);

        var optionsAccessor = new Mock <IOptions <RouteOptions> >(MockBehavior.Strict);

        optionsAccessor.SetupGet(o => o.Value).Returns(options);

        var context = new Mock <HttpContext>(MockBehavior.Strict);

        context.Setup(m => m.RequestServices.GetService(typeof(ILoggerFactory)))
        .Returns(loggerFactory);
        context.Setup(m => m.RequestServices.GetService(typeof(IOptions <RouteOptions>)))
        .Returns(optionsAccessor.Object);
        context.SetupGet(c => c.Request).Returns(request.Object);

        return(new RouteContext(context.Object));
    }
示例#4
0
        private IInlineConstraintResolver GetInlineConstraintResolver(RouteOptions routeOptions)
        {
            var optionsAccessor = new Mock <IOptions <RouteOptions> >();

            optionsAccessor.SetupGet(o => o.Value).Returns(routeOptions);
            return(new DefaultInlineConstraintResolver(optionsAccessor.Object));
        }
示例#5
0
        private async Task <Uri> GetSwaggerUri(SwaggerEndPointConfig endPoint, RouteOptions route)
        {
            var conf = _configurationCreator.Create(_options.CurrentValue.GlobalConfiguration);

            var downstreamRoute = new DownstreamRouteBuilder()
                                  .WithUseServiceDiscovery(true)
                                  .WithServiceName(endPoint.Service.Name)
                                  .WithServiceNamespace(route?.ServiceNamespace)
                                  .Build();

            var serviceProvider = _serviceDiscovery.Get(conf, downstreamRoute);

            if (serviceProvider.IsError)
            {
                throw new InvalidOperationException(GetErrorMessage(endPoint));
            }

            ServiceHostAndPort service = (await serviceProvider.Data.Get()).FirstOrDefault()?.HostAndPort;

            if (service is null)
            {
                throw new InvalidOperationException(GetErrorMessage(endPoint));
            }

            var builder = new UriBuilder(GetScheme(service, route), service.DownstreamHost, service.DownstreamPort);

            builder.Path = endPoint.Service.Path;

            return(builder.Uri);
        }
示例#6
0
 public TimeSeriesImporter(TimeSeriesDatabase db,
                           RouteOptions routing = RouteOptions.None, DatabaseSaveOptions saveOption = DatabaseSaveOptions.UpdateExisting)
 {
     m_db         = db;
     m_routing    = routing;
     m_saveOption = saveOption;
 }
示例#7
0
        /// <summary>
        /// Routes a list of Series as a group 
        /// hydromet cbtt is copied from list[i].SiteName
        /// hydromet pcode is copied from list[i].Parameter
        /// </summary>
        /// <param name="list"></param>
        /// <param name="route"></param>
        /// <param name="name">identity used as part of filename </param>
        public static void RouteDaily(SeriesList list, string name, RouteOptions route = RouteOptions.Both)
        {
            if (list.Count == 0)
                return;

            string fileName = "";

            if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
            {
                fileName = GetOutgoingFileName("daily", name, "all");
                Console.WriteLine("saving daily outgoing to:"+fileName);
                HydrometDailySeries.WriteToArcImportFile(list, fileName);
            }

            if (route == RouteOptions.Both || route == RouteOptions.Incoming)
            {
                foreach (var s in list)
                {
                    fileName = GetIncommingFileName("daily", s.SiteID, s.Parameter);
                    Console.WriteLine("saving daily incoming to:" + fileName);
                    s.WriteCsv(fileName, true);
                }

            }
        }
示例#8
0
        private void RenameAndRemovePaths(IEnumerable <RouteOptions> routes, JToken paths, string basePath)
        {
            var forRemove = new List <JProperty>();

            for (int i = 0; i < paths.Count(); i++)
            {
                var          path           = paths.ElementAt(i) as JProperty;
                string       downstreamPath = path.Name.RemoveSlashFromEnd();
                RouteOptions route          = FindRoute(routes, path.Name.WithShashEnding(), basePath);

                if (route != null && RemoveMethods(path, route))
                {
                    RenameToken(path, ConvertDownstreamPathToUpstreamPath(downstreamPath, route.DownstreamPath, route.UpstreamPath, basePath));
                }
                else
                {
                    forRemove.Add(path);
                }
            }

            foreach (JProperty p in forRemove)
            {
                p.Remove();
            }
        }
示例#9
0
        private ActionResult <List <RouteInfo> > CreateRouteInfo(RouteOptions fullJourneyOptions, bool showPollution, bool showSchools)
        {
            if (fullJourneyOptions == null)
            {
                return(BadRequest());
            }

            List <EnrichedRoute> enrichedRoutes = fullJourneyOptions.EnrichedRoute.ToList();

            List <RouteInfo> routeInfos = new List <RouteInfo>();

            foreach (var enrichedRoute in enrichedRoutes)
            {
                routeInfos.Add(
                    new RouteInfo
                {
                    ColorInHex      = $"#{enrichedRoute.Colour.Substring(6, 2)}{enrichedRoute.Colour.Substring(4, 2)}{enrichedRoute.Colour.Substring(2, 2)}",
                    PollutionPoint  = enrichedRoute.GreenScore,
                    PollutionZone   = showPollution ? enrichedRoute.PollutionMarkers.Average(p => (decimal)p.Value) : (decimal?)null,
                    RouteLabel      = enrichedRoute.Label,
                    SchoolCount     = showSchools ? enrichedRoute.SchoolMarkers?.Count ?? 0 : (int?)null,
                    TravelCost      = enrichedRoute.Cost,
                    Duration        = CalculateTime(enrichedRoute),
                    Distance        = enrichedRoute.Distance,
                    ModeOfTransport = enrichedRoute.ModeOfTransport
                });
            }

            return(Ok(routeInfos));
        }
示例#10
0
        /// <summary>
        /// Routes a list of Series as a group
        /// hydromet cbtt is copied from list[i].SiteName
        /// hydromet pcode is copied from list[i].Parameter
        /// </summary>
        /// <param name="list"></param>
        /// <param name="route"></param>
        /// <param name="name">identity used as part of filename </param>
        public static void RouteDaily(SeriesList list, string name, RouteOptions route = RouteOptions.Both)
        {
            if (list.Count == 0)
            {
                return;
            }

            string fileName = "";

            if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
            {
                fileName = GetOutgoingFileName("daily", name, "all");
                Console.WriteLine("saving daily outgoing to:" + fileName);
                HydrometDailySeries.WriteToArcImportFile(list, fileName);
            }

            if (route == RouteOptions.Both || route == RouteOptions.Incoming)
            {
                foreach (var s in list)
                {
                    fileName = GetIncommingFileName("daily", s.SiteID, s.Parameter);
                    Console.WriteLine("saving daily incoming to:" + fileName);
                    s.WriteCsv(fileName, true);
                }
            }
        }
示例#11
0
 public RouteTotals GetRouteTotalsResponse(IList <RouteStop> routes, RouteOptions routeOptions)
 {
     using (var routeSoapClient = new RouteSoapClient())
     {
         return(routeSoapClient.getRouteTotals((List <RouteStop>)routes, routeOptions, Configuration.TokenValue));
     }
 }
示例#12
0
        /// <summary>
        /// Configures the services to add to the ASP.NET MVC 6 Injection of Control (IoC) container. This method gets
        /// called by the ASP.NET runtime. See:
        /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureDebuggingServices(services, this.hostingEnvironment);
            ConfigureOptionsServices(services, this.configuration);
            ConfigureCachingServices(services);

            // Configure MVC routing. We store the route options for use by ConfigureSearchEngineOptimizationFilters.
            RouteOptions routeOptions = null;

            services.ConfigureRouting(
                x =>
            {
                routeOptions = x;
                ConfigureRouting(x);
            });

            // Add many MVC services to the services container.
            IMvcBuilder mvcBuilder = services.AddMvc(
                mvcOptions =>
            {
                ConfigureCacheProfiles(mvcOptions.CacheProfiles, this.configuration);
                ConfigureSearchEngineOptimizationFilters(mvcOptions.Filters, routeOptions);
                ConfigureSecurityFilters(this.hostingEnvironment, mvcOptions.Filters);
                ConfigureContentSecurityPolicyFilters(this.hostingEnvironment, mvcOptions.Filters);
            });

#if !DEBUG
            // Use pre-compiled views in release mode for quicker application start-up.
            mvcBuilder.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
#endif
            ConfigureFormatters(mvcBuilder);

            ConfigureAntiforgeryServices(services, this.hostingEnvironment);
            ConfigureCustomServices(services);
        }
        public void add_api_versioning_should_configure_mvc_with_default_options()
        {
            // arrange
            var services     = new ServiceCollection();
            var mvcOptions   = new MvcOptions();
            var routeOptions = new RouteOptions();

            services.AddMvc();
            services.AddApiVersioning();

            var serviceProvider    = services.BuildServiceProvider();
            var mvcConfiguration   = serviceProvider.GetRequiredService <IConfigureOptions <MvcOptions> >();
            var routeConfiguration = serviceProvider.GetRequiredService <IConfigureOptions <RouteOptions> >();

            // act
            mvcConfiguration.Configure(mvcOptions);
            routeConfiguration.Configure(routeOptions);

            // assert
            services.Single(sd => sd.ServiceType == typeof(IApiVersionReader)).ImplementationInstance.Should().BeOfType <QueryStringApiVersionReader>();
            services.Single(sd => sd.ServiceType == typeof(IApiVersionSelector)).ImplementationInstance.Should().BeOfType <DefaultApiVersionSelector>();
            services.Single(sd => sd.ServiceType == typeof(IActionSelector)).ImplementationType.Should().Be(typeof(ApiVersionActionSelector));
            mvcOptions.Conventions.Single().Should().BeOfType <ImplicitControllerVersionConvention>();
            routeOptions.ConstraintMap["apiVersion"].Should().Be(typeof(ApiVersionRouteConstraint));
        }
 public DefaultParameterPolicyFactory(
     IOptions <RouteOptions> options,
     IServiceProvider serviceProvider)
 {
     _options         = options.Value;
     _serviceProvider = serviceProvider;
 }
示例#15
0
        /// <summary>
        /// Routes a list of Series as a group
        /// hydromet cbtt is copied from list[i].SiteName
        /// hydromet pcode is copied from list[i].Parameter
        /// </summary>
        /// <param name="list"></param>
        /// <param name="route"></param>
        /// <param name="name">identity used as part of filename </param>
        public static void RouteInstant(SeriesList list, string name, RouteOptions route = RouteOptions.Both)
        {
            if (route == RouteOptions.None)
            {
                return;
            }

            if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
            {
                var tmpFileName = FileUtility.GetTempFileName(".txt");
                File.Delete(tmpFileName);
                Console.WriteLine(tmpFileName);
                foreach (var s in list)
                {
                    HydrometInstantSeries.WriteToHydrometFile(s, s.SiteID, s.Parameter, WindowsUtility.GetShortUserName(), tmpFileName, true);
                }

                Console.WriteLine("Moving: " + tmpFileName);
                var fileName = GetOutgoingFileName("instant", name, "all");
                Console.WriteLine("To: " + fileName);
                File.Move(tmpFileName, fileName);
            }
            else
            {
                throw new NotImplementedException("incoming not supported.");
            }
        }
示例#16
0
        private void GivenTheDependenciesAreSetUpCorrectly()
        {
            _expectedVersion = new Version("1.1");
            _rro             = new RouteOptions(false, false, false, false, false);
            _requestId       = "testy";
            _rrk             = "besty";
            _upt             = new UpstreamPathTemplateBuilder().Build();
            _ao     = new AuthenticationOptionsBuilder().Build();
            _ctt    = new List <ClaimToThing>();
            _qoso   = new QoSOptionsBuilder().Build();
            _rlo    = new RateLimitOptionsBuilder().Build();
            _region = "vesty";
            _hho    = new HttpHandlerOptionsBuilder().Build();
            _ht     = new HeaderTransformations(new List <HeaderFindAndReplace>(), new List <HeaderFindAndReplace>(), new List <AddHeader>(), new List <AddHeader>());
            _dhp    = new List <DownstreamHostAndPort>();
            _lbo    = new LoadBalancerOptionsBuilder().Build();

            _rroCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_rro);
            _ridkCreator.Setup(x => x.Create(It.IsAny <FileRoute>(), It.IsAny <FileGlobalConfiguration>())).Returns(_requestId);
            _rrkCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_rrk);
            _utpCreator.Setup(x => x.Create(It.IsAny <IRoute>())).Returns(_upt);
            _aoCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_ao);
            _cthCreator.Setup(x => x.Create(It.IsAny <Dictionary <string, string> >())).Returns(_ctt);
            _qosoCreator.Setup(x => x.Create(It.IsAny <FileQoSOptions>(), It.IsAny <string>(), It.IsAny <List <string> >())).Returns(_qoso);
            _rloCreator.Setup(x => x.Create(It.IsAny <FileRateLimitRule>(), It.IsAny <FileGlobalConfiguration>())).Returns(_rlo);
            _rCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_region);
            _hhoCreator.Setup(x => x.Create(It.IsAny <FileHttpHandlerOptions>())).Returns(_hho);
            _hfarCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_ht);
            _daCreator.Setup(x => x.Create(It.IsAny <FileRoute>())).Returns(_dhp);
            _lboCreator.Setup(x => x.Create(It.IsAny <FileLoadBalancerOptions>())).Returns(_lbo);
            _versionCreator.Setup(x => x.Create(It.IsAny <string>())).Returns(_expectedVersion);
        }
示例#17
0
        public RouteInfo GetRoute(Point origem, Point destino, TipoRota tp)
        {
            RouteStop[] a = new RouteStop[2] {
                new RouteStop {
                    description = "origem", point = origem
                },
                new RouteStop {
                    description = "destino", point = destino
                }
            };

            RouteOptions ro = new RouteOptions();

            ro.language = Language;

            //TODO: Criar enum com as possíveis opções: http://dev.maplink.com.br/webservices/rotas/#StructureVehicle
            ro.vehicle                    = new Vehicle();
            ro.vehicle.tollFeeCat         = 2;
            ro.vehicle.averageConsumption = 10;
            ro.vehicle.averageSpeed       = 60;
            ro.vehicle.tankCapacity       = 50;
            ro.vehicle.fuelPrice          = 2.60;

            //TODO: Criar as opções: http://dev.maplink.com.br/webservices/rotas/#StructureVehicle
            ro.routeDetails                 = new RouteDetails();
            ro.routeDetails.routeType       = (int)tp;
            ro.routeDetails.descriptionType = 0;

            return(_route.getRoute(a, ro, _token));
        }
示例#18
0
 public RouteTotals GetRouteTotalsResponse(IList<RouteStop> routes, RouteOptions routeOptions)
 {
     using (var routeSoapClient = new RouteSoapClient())
     {
         return routeSoapClient.getRouteTotals((List<RouteStop>) routes, routeOptions, Configuration.TokenValue);
     }
 }
示例#19
0
        private List <Folder> GetRouteLabelsFolders(RouteOptions routeOptions)
        {
            var folders = new List <Folder>();

            foreach (var route in routeOptions.EnrichedRoute)
            {
                var markerCoordinate = route.RouteMarkers[route.RouteMarkers.Count / 2].Coordinate;
                folders.Add(
                    new Folder()
                {
                    Name      = $"From {routeOptions.StartLocation.Name} to {routeOptions.EndLocation.Name}",
                    Placemark = new List <Placemark>()
                    {
                        new Placemark()
                        {
                            Name     = route.Label,
                            StyleUrl = $"#line-{route.GreenScore}-{route.Cost}-{route.Colour}",
                            Point    = new MapApiCore.Models.Kml.Point()
                            {
                                Coordinates = $"{markerCoordinate.Longitude},{markerCoordinate.Latitude},0"
                            }
                        }
                    }
                });
            }

            return(folders);
        }
示例#20
0
        public void Import(string path, RouteOptions routing = RouteOptions.None,
                           bool computeDependencies          = false, bool computeDailyOnMidnight = false, string searchPattern = "*.*")
        {
            this.m_computeDailyDependencies = computeDailyOnMidnight;
            this.m_computeDependencies      = computeDependencies;
            Console.WriteLine(path);
            DirectoryInfo di = new DirectoryInfo(path);

            FileSystemInfo[] fsinfos = di.GetFileSystemInfos(searchPattern);
            var ordered1             = fsinfos.OrderBy(f => f.CreationTime);

            Console.WriteLine("found " + ordered1.Count() + " items");
            var ordered = ordered1.Where(f => (f.Attributes & FileAttributes.Directory) != FileAttributes.Directory);

            Console.WriteLine("Found " + ordered.Count() + " files to import");
            foreach (var fi in ordered)
            {
                var fn = fi.FullName;

                if (fi.CreationTime.AddSeconds(2) > DateTime.Now)
                {
                    Console.WriteLine(" skipping file newer than 2 seconds ago " + fn + " " + fi.CreationTime);
                    continue;
                }
                ProcessFile(routing, fi.FullName);
            }
            // needs .net 4.0 System.Threading.Tasks.Parallel.ForEach(ordered,(fi) => ProcessFile(routing,fi));
        }
示例#21
0
        /// <summary>
        /// Improve SEO by stopping duplicate URL's due to case differences or trailing slashes.
        /// See http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
        /// </summary>
        /// <param name="routeOptions">The routing options.</param>
        private static void ConfigureRouting(RouteOptions routeOptions)
        {
            // TODO: AppendTrailingSlash does not yet exist but will be added in the next version of MVC.
            // All generated URL's should append a trailing slash.
            // routeOptions.AppendTrailingSlash = true;

            // All generated URL's should be lower-case.
            routeOptions.LowercaseUrls = true;

            // TODO: IgnoreRoute does not yet exist in MVC 6.

            //            // IgnoreRoute - Tell the routing system to ignore certain routes for better performance.
            //            // Ignore .axd files.
            //            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //            // Ignore everything in the Content folder.
            //            routes.IgnoreRoute("Content/{*pathInfo}");
            //            // Ignore everything in the Scripts folder.
            //            routes.IgnoreRoute("Scripts/{*pathInfo}");
            //            // Ignore the Forbidden.html file.
            //            routes.IgnoreRoute("Error/Forbidden.html");
            //            // Ignore the GatewayTimeout.html file.
            //            routes.IgnoreRoute("Error/GatewayTimeout.html");
            //            // Ignore the ServiceUnavailable.html file.
            //            routes.IgnoreRoute("Error/ServiceUnavailable.html");
            //            // Ignore the humans.txt file.
            //            routes.IgnoreRoute("humans.txt");
        }
示例#22
0
        public void Import( string path, RouteOptions routing=RouteOptions.None,
            bool computeDependencies = false, bool computeDailyOnMidnight = false, string searchPattern = "*.*")
        {
            this.m_computeDailyDependencies = computeDailyOnMidnight;
            this.m_computeDependencies = computeDependencies;
            Console.WriteLine(path);
             DirectoryInfo di = new DirectoryInfo(path);
            FileSystemInfo[] fsinfos = di.GetFileSystemInfos(searchPattern);
            var ordered1 = fsinfos.OrderBy(f => f.CreationTime);
            Console.WriteLine("found "+ordered1.Count()+" items" );
            var ordered = ordered1.Where(f => (f.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
            Console.WriteLine("Found "+ordered.Count()+" files to import");
            foreach (var fi in ordered)
            {
                var fn = fi.FullName;

                if (fi.CreationTime.AddSeconds(2) > DateTime.Now)
                {
                    Console.WriteLine(" skipping file newer than 2 seconds ago " + fn + " " + fi.CreationTime);
                    continue;
                }
                ProcessFile(routing, fi.FullName);
            }
              // needs .net 4.0 System.Threading.Tasks.Parallel.ForEach(ordered,(fi) => ProcessFile(routing,fi));
        }
        public async Task <CalculDistanceRetourModel> ObtenirDistanceAsync(RouteOptions options)
        {
            HttpClient client = new HttpClient();

            //Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            CalculDistanceRetourModel retour;

            var response = await client.GetAsync(ObtenirUri(options)).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                //TODO: Doit être traité et retourné dans un RouteCamionModel
                JObject retourJson = (JObject)JToken.Parse(response.Content.ReadAsStringAsync().Result);
                retour          = new CalculDistanceRetourModel();
                retour.Distance = retourJson.SelectToken("response.route[0].summary.distance").Value <int>();
                retour.SetDelais(retourJson.SelectToken("response.route[0].summary.baseTime").Value <int>());
                retour.Notes = retourJson.ToString();
            }
            else
            {
                retour = null;
            }

            client.Dispose();
            return(retour);
        }
示例#24
0
        public async Task CalculateDurations()
        {
            if (calculatingDurations)
            {
                return;
            }

            calculatingDurations = true;
            try {
                var maps = Maps.MapService;

                while (RequestedDurations.Count > 0)
                {
                    var leg = RequestedDurations.Dequeue();
                    if (leg.Status == RouteLegStatus.Complete)
                    {
                        leg.DurationRequested = false;
                        continue;
                    }

                    try {
                        var waypoints = new Waypoint[2];
                        if (leg.Status == RouteLegStatus.Enroute)
                        {
                            var location = await Location.GetCurrentLocation();

                            waypoints[0] = Waypoint.FromLocation(WaypointType.SatrtPoint, location);
                        }
                        else
                        {
                            waypoints[0] = Waypoint.FromAddress(WaypointType.SatrtPoint, leg.StartPoint.Address);
                        }
                        waypoints[1] = Waypoint.FromAddress(WaypointType.EndPoint, leg.EndPoint.Address);

                        var options = new RouteOptions {
                            TravelMode          = TravelMode.Driving,
                            HighwaysRestriction = Restriction.None,
                            TollsRestriction    = Restriction.Avoid,
                            Optimization        = Optimization.Default
                        };

                        var info = await maps.GetRouteInfo(waypoints, options);

                        leg.Duration = info.TravelTime;
                        UpdateETAs();
                    }
                    catch (Exception exc) {
                        Debug.ExceptionCaught(exc);
                        leg.Duration = null;
                        UpdateETAs();
                    }
                    leg.DurationRequested = false;
                    leg.EndPoint.UpdateInfo();
                }
            }
            finally {
                calculatingDurations = false;
            }
        }
示例#25
0
        public JsonResult GetRoute(string routeId, string startString, string endString, string routeOptionsString)
        {
            Location     start        = JsonConvert.DeserializeObject <Location>(startString);
            Location     end          = JsonConvert.DeserializeObject <Location>(endString);
            RouteOptions routeOptions = JsonConvert.DeserializeObject <RouteOptions>(routeOptionsString);

            return(Json(((IRouteService)this).GetRoute(routeId, start, end, routeOptions), JsonRequestBehavior.AllowGet));
        }
示例#26
0
        public async Task <ActionResult <string> > Get(int journeyId, [FromQuery] bool showPollution, [FromQuery] bool showSchools, [FromQuery] TimeSpan startTime, [FromQuery] string startName, [FromQuery] decimal startLongitude, [FromQuery] decimal startLatitude, [FromQuery] string endName, [FromQuery] decimal endLongitude, [FromQuery] decimal endLatitude, [FromQuery] decimal rand)
        {
            RouteOptions fullJourneyOptions = await this.ProcessJourney(journeyId, startTime, showPollution, showSchools);

            var kmlString = await this.CreateTestKmlString(fullJourneyOptions, journeyId, showPollution, showSchools);

            return(kmlString);
        }
示例#27
0
 private void ThenTheFollowingIsReturned(RouteOptions expected)
 {
     _result.IsAuthenticated.ShouldBe(expected.IsAuthenticated);
     _result.IsAuthorised.ShouldBe(expected.IsAuthorised);
     _result.IsCached.ShouldBe(expected.IsCached);
     _result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
     _result.UseServiceDiscovery.ShouldBe(expected.UseServiceDiscovery);
 }
示例#28
0
    public void SetParameterPolicyThrowsIfTypeIsNotIParameterPolicy()
    {
        // Arrange
        var routeOptions = new RouteOptions();
        var ex           = Assert.Throws <InvalidOperationException>(() => routeOptions.SetParameterPolicy("custom", typeof(string)));

        Assert.Equal("System.String must implement Microsoft.AspNetCore.Routing.IParameterPolicy", ex.Message);
    }
示例#29
0
 public void ImportFile(string fileName, RouteOptions routing = RouteOptions.None,
    bool computeDependencies = false, bool computeDailyOnMidnight = false, string searchPattern = "*.*")
 {
     this.m_computeDailyDependencies = computeDailyOnMidnight;
     this.m_computeDependencies = computeDependencies;
     Console.WriteLine(fileName);
     ProcessFile(routing, fileName);
 }
示例#30
0
 public void ImportFile(string fileName, RouteOptions routing = RouteOptions.None,
                        bool computeDependencies = false, bool computeDailyOnMidnight = false, string searchPattern = "*.*")
 {
     this.m_computeDailyDependencies = computeDailyOnMidnight;
     this.m_computeDependencies      = computeDependencies;
     Console.WriteLine(fileName);
     ProcessFile(routing, fileName);
 }
        /// <summary>
        /// Configures the services to add to the ASP.NET MVC 6 Injection of Control (IoC) container. This method gets
        /// called by the ASP.NET runtime. See:
        /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // $Start-ApplicationInsights$
            // Add Azure Application Insights data collection services to the services container.
            services.AddApplicationInsightsTelemetry(this.configuration);

            // $End-ApplicationInsights$
            // $Start-Glimpse$
            ConfigureDebuggingServices(services, this.hostingEnvironment);
            // $End-Glimpse$
            ConfigureOptionsServices(services, this.configuration);
            ConfigureCachingServices(services);

            // $Start-RedirectToCanonicalUrl$
            // Configure MVC routing. We store the route options for use by ConfigureSearchEngineOptimizationFilters.
            RouteOptions routeOptions = null;

            // $End-RedirectToCanonicalUrl$
            services.ConfigureRouting(
                x =>
            {
                // $Start-RedirectToCanonicalUrl$
                routeOptions = x;
                // $End-RedirectToCanonicalUrl$
                ConfigureRouting(x);
            });

            // Add many MVC services to the services container.
            IMvcBuilder mvcBuilder = services.AddMvc(
                mvcOptions =>
            {
                ConfigureCacheProfiles(mvcOptions.CacheProfiles, this.configuration);
                // $Start-RedirectToCanonicalUrl$
                ConfigureSearchEngineOptimizationFilters(mvcOptions.Filters, routeOptions);
                // $End-RedirectToCanonicalUrl$
                ConfigureSecurityFilters(this.hostingEnvironment, mvcOptions.Filters);
                // $Start-NWebSec$
                ConfigureContentSecurityPolicyFilters(this.hostingEnvironment, mvcOptions.Filters);
                // $End-NWebSec$
            });

#if !DEBUG
            // Use pre-compiled views in release mode for quicker application start-up.
            mvcBuilder.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
#endif
            // $Start-CshtmlMinification$
            services.Configure <RazorViewEngineOptions>(
                options =>
            {
                options.ViewLocationExpanders.Add(new MinifiedViewLocationExpander());
            });
            // services.AddTransient<IRazorViewEngine, MinifiedRazorViewEngine>();
            // $End-CshtmlMinification$
            ConfigureFormatters(mvcBuilder);

            ConfigureAntiforgeryServices(services, this.hostingEnvironment);
            ConfigureCustomServices(services);
        }
        public RoteValuesCalculator(Vehicle vehicle)
        {
            _vehicle = vehicle;

            _routeOptions = new RouteOptions();
            _routeOptions.language = Config.Language;
            _routeOptions.routeDetails = _routeDetails;
            _routeOptions.vehicle = _vehicle;
        }
示例#33
0
 public EndpointMiddleware(
     ILogger <EndpointMiddleware> logger,
     RequestDelegate next,
     IOptions <RouteOptions> routeOptions)
 {
     _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
     _next         = next ?? throw new ArgumentNullException(nameof(next));
     _routeOptions = routeOptions?.Value ?? throw new ArgumentNullException(nameof(routeOptions));
 }
        public void ResolveConstraint_Invalid_Throws(string constraint)
        {
            // Arrange
            var routeOptions = new RouteOptions();
            var resolver     = GetInlineConstraintResolver(routeOptions);

            // Act & Assert
            Assert.Null(resolver.ResolveConstraint(constraint));
        }
示例#35
0
 private string GetScheme(ServiceHostAndPort service, RouteOptions route)
 => (route != null && !route.DownstreamScheme.IsNullOrEmpty())
     ? route.DownstreamScheme
     : !service.Scheme.IsNullOrEmpty()
     ? service.Scheme
     : service.DownstreamPort
 switch
 {
     443 => Uri.UriSchemeHttps,
示例#36
0
        public void ConstraintMap_SettingNullValue_Throws()
        {
            // Arrange
            var options = new RouteOptions();

            // Act & Assert
            var ex = Assert.Throws<ArgumentNullException>(() => options.ConstraintMap = null);
            Assert.Equal("The 'ConstraintMap' property of 'Microsoft.AspNet.Routing.RouteOptions' must not be null." +
                         Environment.NewLine + "Parameter name: value", ex.Message);
        }
示例#37
0
        public JsonResult GetInfoMapLink(MapLinkConsulta dados)
        {
            try
            {
                const string token = "c13iyCvmcC9mzwkLd0LCbmYC5mUF5m2jNGNtNGt6NmK6NJK=";

                var originRoute = new RouteStop
                {
                    description = "",
                    point = new Point { x = Convert.ToDouble(dados.origem.longitude,cult) , y = Convert.ToDouble(dados.origem.latitude, cult) }
                };

                var destinationRoute = new RouteStop
                {
                    description = "",
                    point = new Point { x = Convert.ToDouble(dados.destino.longitude,cult), y = Convert.ToDouble(dados.destino.latitude,cult) }
                };

                var routes = new[] { originRoute, destinationRoute };

                var routeOptions = new RouteOptions
                {
                    language = "portugues",
                    routeDetails = new RouteDetails { descriptionType = 0, routeType = 1, optimizeRoute = true },
                    vehicle = new Vehicle
                    {
                        tankCapacity = 20,
                        averageConsumption = 9,
                        fuelPrice = 3,
                        averageSpeed = 60,
                        tollFeeCat = 2
                    }
                };

                using (var routeSoapClient = new RouteSoapClient())
                {
                    var getRouteTotalsResponse = routeSoapClient.getRouteTotals(routes, routeOptions, token);

                    var resultado = new
                    {
                        consumo = getRouteTotalsResponse.totalFuelUsed.ToString(cult),
                        distancia = getRouteTotalsResponse.totalDistance.ToString(cult),
                        tempototal = getRouteTotalsResponse.totalTime.ToString(cult)
                    };
                    return Json(resultado, JsonRequestBehavior.AllowGet);
                }

                return null;

            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public void ResolveConstraint_AmbiguousConstructors_Throws()
        {
            // Arrange
            var routeOptions = new RouteOptions();
            routeOptions.ConstraintMap.Add("custom", typeof(MultiConstructorRouteConstraint));
            var resolver = GetInlineConstraintResolver(routeOptions);

            // Act & Assert
            var ex = Assert.Throws<InvalidOperationException>(() => resolver.ResolveConstraint("custom(5,6)"));
            Assert.Equal("The constructor to use for activating the constraint type 'MultiConstructorRouteConstraint' is ambiguous." +
                         " Multiple constructors were found with the following number of parameters: 2.",
                         ex.Message);
        }
        public void ResolveConstraint_CustomConstraintThatDoesNotImplementIRouteConstraint_Throws()
        {
            // Arrange
            var routeOptions = new RouteOptions();
            routeOptions.ConstraintMap.Add("custom", typeof(string));
            var resolver = GetInlineConstraintResolver(routeOptions);

            // Act & Assert
            var ex = Assert.Throws<InvalidOperationException>(() => resolver.ResolveConstraint("custom"));
            Assert.Equal("The constraint type 'System.String' which is mapped to constraint key 'custom'" +
                         " must implement the 'IRouteConstraint' interface.",
                         ex.Message);
        }
示例#40
0
        /// <summary>
        /// Improve SEO by stopping duplicate URL's due to case differences or trailing slashes.
        /// See http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
        /// </summary>
        /// <param name="routeOptions">The routing options.</param>
        private static void ConfigureRouting(RouteOptions routeOptions)
        {
            // All generated URL's should append a trailing slash.
            routeOptions.AppendTrailingSlash = true;

            // All generated URL's should be lower-case.
            routeOptions.LowercaseUrls = true;

            // TODO: IgnoreRoute does not yet exist in MVC 6.

            // // IgnoreRoute - Tell the routing system to ignore certain routes for better performance.
            // // Ignore .axd files.
            // routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            // // Ignore everything in the Content folder.
            // routes.IgnoreRoute("Content/{*pathInfo}");
            // // Ignore the humans.txt file.
            // routes.IgnoreRoute("humans.txt");
        }
示例#41
0
        public static void RouteDaily(Series s, string cbtt, string pcode, RouteOptions route = RouteOptions.Both)
        {
            if (s.Count == 0)
                return;
            string fileName = "";

            if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
            {
                fileName = GetOutgoingFileName("daily", cbtt, pcode);
                Console.WriteLine(fileName);
                HydrometDailySeries.WriteToArcImportFile(s, cbtt, pcode, fileName);
            }

            if (route == RouteOptions.Both || route == RouteOptions.Incoming)
            {
                fileName = GetIncommingFileName("daily", cbtt, pcode);
                s.WriteCsv(fileName, true);
            }
        }
        public RouteOptions GetRouteOptions(RouteType type, string language = "", Vehicle vehicle = null)
        {
            var options = new RouteOptions
            {
                language = string.IsNullOrWhiteSpace(language) ? "portugues" : language,
                routeDetails = new RouteDetails
                {
                    descriptionType = (int)DescriptionRoute.UrbanRoute,
                    routeType = (int)type
                }
            };

            if (vehicle != null)
            {
                options.vehicle = vehicle;
            }
            else
            {
                options.vehicle = GetDefaultVehicle();
            }

            return options;
        }
示例#43
0
 private static void ConfigureRouting(RouteOptions routeOptions)
 {
     routeOptions.AppendTrailingSlash = true;
     routeOptions.LowercaseUrls = true;
 }
示例#44
0
        public ActionResult Index(HttpPostedFileBase file)
        {
            MapLinkArquivoOutput resultado = new MapLinkArquivoOutput();

            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                resultado.itens = new List<MapLinkOutputItem>();

                StreamReader stream = new StreamReader(file.InputStream);
                string conteudo = stream.ReadToEnd();
                List<MapLinkFileInput> input = DecodeMapLinkInputFile(conteudo);

                const string token = "c13iyCvmcC9mzwkLd0LCbmYC5mUF5m2jNGNtNGt6NmK6NJK=";

                foreach(var item in input){
                    var originRoute = new RouteStop
                    {
                        description = "",
                        point = new Point { x = Convert.ToDouble(item.originCoordinate.longitude,cult) , y = Convert.ToDouble(item.originCoordinate.latitude, cult) }
                    };

                    var destinationRoute = new RouteStop
                    {
                        description = "",
                        point = new Point { x = Convert.ToDouble(item.destinationCoordinate.longitude,cult), y = Convert.ToDouble(item.destinationCoordinate.latitude,cult) }
                    };

                    var routes = new[] { originRoute, destinationRoute };

                    var routeOptions = new RouteOptions
                    {
                        language = "portugues",
                        routeDetails = new RouteDetails { descriptionType = 0, routeType = 1, optimizeRoute = true },
                        vehicle = new Vehicle
                        {
                            tankCapacity = 20,
                            averageConsumption = 9,
                            fuelPrice = 3,
                            averageSpeed = 60,
                            tollFeeCat = 2
                        }
                    };

                    using (var routeSoapClient = new RouteSoapClient())
                    {
                        var getRouteTotalsResponse = routeSoapClient.getRouteTotals(routes, routeOptions, token);

                        resultado.itens.Add(new MapLinkOutputItem(){
                             id=item.id,
                             consumo=getRouteTotalsResponse.totalFuelUsed.ToString(cult),
                             distancia=getRouteTotalsResponse.totalDistance.ToString(cult),
                             tempototal=getRouteTotalsResponse.totalTime.ToString(cult)
                        });
                    }
                }
            }
            // redirect back to the index action to show the form once again
            return View("Index",resultado);
        }
        private RouteOptions DefaultRouteOptions(int routeType)
        {
            if (routeType != Constants.ROUTE_TYPE_AVOID_TRAFFIC &&
                routeType != Constants.ROUTE_TYPE_STANDARD_FASTEST)
            {
                routeType = Constants.ROUTE_TYPE_STANDARD_FASTEST;
            }

            if (routeOptions == null)
            {
                this.routeOptions = new RouteOptions
                {
                    language = "portugues",
                    routeDetails = new RouteDetails { descriptionType = 0, routeType = routeType, optimizeRoute = true },
                    vehicle = this.DefaultPopularVehicle()
                };
            }
            else
            {
                routeOptions.routeDetails.routeType = routeType;
            }
            return routeOptions;
        }
示例#46
0
        /// <summary>
        /// Routes a list of Series as a group 
        /// hydromet cbtt is copied from list[i].SiteName
        /// hydromet pcode is copied from list[i].Parameter
        /// </summary>
        /// <param name="list"></param>
        /// <param name="route"></param>
        /// <param name="name">identity used as part of filename </param>
        public static void RouteInstant(SeriesList list, string name, RouteOptions route = RouteOptions.Both)
        {
            if (route == RouteOptions.None)
                return;

            if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
            {

                var tmpFileName = FileUtility.GetTempFileName(".txt");
                File.Delete(tmpFileName);
                Console.WriteLine("temp file:"+tmpFileName);
                foreach (var s in list)
                {
                  HydrometInstantSeries.WriteToHydrometFile(s, s.SiteID, s.Parameter, WindowsUtility.GetShortUserName(), tmpFileName,true);
                }

                Console.WriteLine("Moving: "+tmpFileName);
                var fileName = GetOutgoingFileName("instant", name, "all");
                Console.WriteLine("To: " + fileName);
                File.Move(tmpFileName, fileName);

            }
            else
            {
                throw new NotImplementedException("incoming not supported.");
            }
        }
        public void ResolveConstraint_Invalid_Throws(string constraint)
        {
            // Arrange
            var routeOptions = new RouteOptions();
            var resolver = GetInlineConstraintResolver(routeOptions);

            // Act & Assert
            Assert.Null(resolver.ResolveConstraint(constraint));
        }
 private IInlineConstraintResolver GetInlineConstraintResolver(RouteOptions routeOptions)
 {
     var optionsAccessor = new Mock<IOptions<RouteOptions>>();
     optionsAccessor.SetupGet(o => o.Value).Returns(routeOptions);
     return new DefaultInlineConstraintResolver(optionsAccessor.Object);
 }
 public DefaultInlineConstraintResolverTest()
 {
     var routeOptions = new RouteOptions();
     _constraintResolver = GetInlineConstraintResolver(routeOptions);
 }
        public void ResolveConstraint_SupportsCustomConstraints()
        {
            // Arrange
            var routeOptions = new RouteOptions();
            routeOptions.ConstraintMap.Add("custom", typeof(CustomRouteConstraint));
            var resolver = GetInlineConstraintResolver(routeOptions);

            // Act
            var constraint = resolver.ResolveConstraint("custom(argument)");

            // Assert
            Assert.IsType<CustomRouteConstraint>(constraint);
        }
示例#51
0
 /// <summary>
 /// Adds filters which help improve search engine optimization (SEO).
 /// </summary>
 private static void ConfigureSearchEngineOptimizationFilters(ICollection<IFilterMetadata> filters, RouteOptions routeOptions)
 {
     filters.Add(new RedirectToCanonicalUrlAttribute(
          appendTrailingSlash: routeOptions.AppendTrailingSlash,
          lowercaseUrls: routeOptions.LowercaseUrls));
 }
示例#52
0
 public static void RouteInstant(Series s, string cbtt, string pcode, RouteOptions route = RouteOptions.Both)
 {
     if (s.Count == 0)
         return;
     string fileName = "";
     if (route == RouteOptions.Both || route == RouteOptions.Outgoing)
     {
         fileName = GetOutgoingFileName("instant", cbtt, pcode);
          HydrometInstantSeries.WriteToHydrometFile(s, cbtt, pcode, WindowsUtility.GetShortUserName(),fileName);
     }
     if (route == RouteOptions.Both || route == RouteOptions.Incoming)
     {
         fileName = GetIncommingFileName("instant", cbtt, pcode);
         HydrometInstantSeries.WriteToHydrometFile(s, cbtt, pcode, WindowsUtility.GetShortUserName(), fileName);
     }
 }
示例#53
0
        private void ProcessFile(RouteOptions routing, string fileName)
        {
            string importTag = "import"; // used to make friendly export filename
            try
            {
                TextFile tf = new TextFile(fileName);
                SeriesList sl = new SeriesList();

                if (HydrometInstantSeries.IsValidDMS3(tf))
                {
                    importTag = "decodes";
                    sl = HydrometInstantSeries.HydrometDMS3DataToSeriesList(tf);
                }
                else if( HydrometDailySeries.IsValidArchiveFile(tf))
                {
                    importTag = "htools";
                    sl = HydrometDailySeries.HydrometDailyDataToSeriesList(tf);
                }
                else if (LoggerNetFile.IsValidFile(tf))
                {
                    LoggerNetFile lf = new LoggerNetFile(tf);

                    if (lf.IsValid && Array.IndexOf(validSites, lf.SiteName) >= 0)
                    {
                        importTag = lf.SiteName;
                        sl = lf.ToSeries(validPcodes);
                    }
                }
                //else if (DecodesRawFile.IsValidFile(tf))
                //{
                //    DecodesRawFile df = new DecodesRawFile(tf);
                //    importTag = "raw";
                //    sl = df.ToSeries();
                //}
                else
                {
                    Logger.WriteLine("skipped Unknown File Format: " + fileName);
                    return;
                }

                m_importer = new TimeSeriesImporter(m_db, routing,m_saveOption);
                Console.WriteLine("Found " + sl.Count + " series in " + fileName);
                foreach (var item in sl)
                {
                    Logger.WriteLine(item.Table.TableName);
                }

                if (sl.Count > 0)
                {
                    m_importer.Import(sl, m_computeDependencies, m_computeDailyDependencies,importTag);
                    FileUtility.MoveToSubDirectory(Path.GetDirectoryName(fileName), "attic", fileName);
                }

            }
            catch (Exception ex)
            {
                Logger.WriteLine("Error:" + ex.Message);
                Console.WriteLine("Error:  skipping file, will move to error subdirectory " + fileName);
                FileUtility.MoveToSubDirectory(Path.GetDirectoryName(fileName), "error", fileName);

            }
        }
示例#54
0
        private static DefaultInlineConstraintResolver CreateConstraintResolver()
        {
            var options = new RouteOptions();
            var optionsMock = new Mock<IOptions<RouteOptions>>();
            optionsMock.SetupGet(o => o.Value).Returns(options);

            return new DefaultInlineConstraintResolver(optionsMock.Object);
        }
        private Rota CalculaRota(Endereco end1, Endereco end2, EnumTipoRota tipoRota)
        {
            var address1 = new Address
            {
                street = end1.NomeRuaAvenida,
                houseNumber = end1.Numero.ToString(),
                city = new ServiceAddressFinder.City { name = end1.Cidade, state = end1.Estado }
            };

            var address2 = new Address
            {
                street = end2.NomeRuaAvenida,
                houseNumber = end2.Numero.ToString(),
                city = new ServiceAddressFinder.City { name = end2.Cidade, state = end2.Estado }
            };

            var afSoa = new AddressFinderSoapClient();
            afSoa.Endpoint.Address = new System.ServiceModel.EndpointAddress("http://services.maplink.com.br/webservices/v3/AddressFinder/AddressFinder.asmx");
            var addressXY1 = afSoa.getXY(address1, token);
            var addressXY2 = afSoa.getXY(address2, token);

            var rSoa = new RouteSoapClient();
            var routes = new[] {
                new RouteStop
                {
                    description = address1.street+ ", "+address1.houseNumber,
                    point = new ServiceRoute.Point { x = addressXY1.x, y = addressXY1.y }
                },
                new RouteStop
                {
                    description = address2.street+ ", "+address2.houseNumber,
                    point = new ServiceRoute.Point { x = addressXY2.x, y = addressXY2.y }
                }
            };
            var routeOptions = new RouteOptions
            {
                language = "portugues",
                routeDetails = new RouteDetails { descriptionType = 0, routeType = (int)tipoRota, optimizeRoute = true },
                vehicle = new Vehicle
                {
                    tankCapacity = 20,
                    averageConsumption = 9,
                    fuelPrice = 3,
                    averageSpeed = 60,
                    tollFeeCat = 2
                }
            };
            var getRouteResponse = rSoa.getRoute(routes, routeOptions, token);
            var rt = getRouteResponse.routeTotals;

            this.CustoCombustivel = rt.totalfuelCost;
            this.CustoComPedagio = this.CustoCombustivel + rt.totaltollFeeCost;
            this.DistanciaTotal = rt.totalDistance;
            this.TotalTempo = rt.totalTime;

            return this;
        }
示例#56
0
        private static RouteContext CreateRouteContext(
            string requestPath,
            ILoggerFactory loggerFactory = null,
            RouteOptions options = null)
        {
            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            if (options == null)
            {
                options = new RouteOptions();
            }

            var request = new Mock<HttpRequest>(MockBehavior.Strict);
            request.SetupGet(r => r.Path).Returns(requestPath);

            var optionsAccessor = new Mock<IOptions<RouteOptions>>(MockBehavior.Strict);
            optionsAccessor.SetupGet(o => o.Value).Returns(options);

            var context = new Mock<HttpContext>(MockBehavior.Strict);
            context.Setup(m => m.RequestServices.GetService(typeof(ILoggerFactory)))
                .Returns(loggerFactory);
            context.Setup(m => m.RequestServices.GetService(typeof(IOptions<RouteOptions>)))
                .Returns(optionsAccessor.Object);
            context.SetupGet(c => c.Request).Returns(request.Object);

            return new RouteContext(context.Object);
        }
示例#57
0
 private void EnsureOptions(HttpContext context)
 {
     if (_options == null)
     {
         _options = context.RequestServices.GetRequiredService<IOptions<RouteOptions>>().Value;
     }
 }