Example #1
0
        public Level()
        {
            Vector2 levelSize = new Vector2(32, 18);

            grid = new int[(int)levelSize.X, (int)levelSize.Y];
            map = new int[(int)levelSize.X * 100, (int)levelSize.Y * 100];

            for (int i = 0; i < levelSize.X; i++)
                for (int j = 0; j < levelSize.Y; j++)
                    grid[i, j] = 0;

            for (int i = 0; i < levelSize.X * 100; i++)
                for (int j = 0; j < levelSize.Y * 100; j++)
                    map[i, j] = 0;

            enemies = new List<Enemy>();
            path = new List<PathBlock>();
            corpses = new List<Vector4>();

            allWaves = new Queue<Wave>();

            route = new Route();
            projectiles = new List<Projectile>();

            maxEnemies = 0;
        }
Example #2
0
        static Route CreateRoute(DependencyObject d)
        {
            var routeString = GetRoute(d);

            var action = routeString.Split(' ')[0];
            var resource = routeString.Split(' ')[1];

            var route = new Route(action, resource);

            var view = ViewProperties.GetView(d);
            route.AddParameter(KnownParameters.ParentView, view);
            var showAs = ViewProperties.GetShowAs(d);
            route.AddParameter(KnownParameters.ParentShowAs, showAs);

            var parameters = GetParams(d);

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    var element = d as FrameworkElement;
                    p.DataContext = element.DataContext;
                    route.AddParameter(p.Key, p.Value);
                }
            }

            return route;
        }
        public void Run()
        {
            var data = new BangaloreUniversityData();
            User user = null;
            while (true)
            {
                string inputLine = Console.ReadLine();
                if (inputLine == null)
                {
                    break;
                }

                var route = new Route(inputLine);
                var controllerType =
                    Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(type => type.Name == route.ControllerName);
                var controller = Activator.CreateInstance(controllerType, data, user) as Controller;
                var action = controllerType.GetMethod(route.ActionName);
                object[] @params = MapParameters(route, action);
                try
                {
                    var view = action.Invoke(controller, @params) as IView;
                    Console.WriteLine(view.Display());
                    user = controller.User;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
            }
        }
Example #4
0
        public void TestRoute()
        {
            string action = "/logInTrue/";
            Route route  = new Route(action, new TcpClient());

            Assert.AreEqual(route.Action, "logInTrue");
        }
Example #5
0
        // create an activity, start it and return it
        public static clsActivityMovement createActivityAndStart(clsGroundAtom atom, int speed, Route route)
        {
            clsActivityMovement activity = createActivity(atom, speed, route);
            startActivity(activity);

            return activity;
        }
Example #6
0
        public static void CsvLoadTripRoutes(string filename, bool lngFirst)
        {
            // load trip routes
            Dictionary<string, LinkedList<Waypoint>> routes = new Dictionary<string, LinkedList<Waypoint>>();
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row, ','))
                {
                    string routeID = row[0];
                    double distance = 0;
                    double lat = Convert.ToDouble(lngFirst ? row[2] : row[1]);
                    double lng = Convert.ToDouble(lngFirst ? row[1] : row[2]);
                    if (routes.ContainsKey(routeID))
                        distance = routes[routeID].First.Value.GetDistance(new Location(lat, lng, "null"));
                    Waypoint waypoint = new Waypoint(lat, lng, TimeSpan.Parse(row[3]), distance, row[4].Replace("\"", ""));

                    // Scenario #1
                    if (!routes.ContainsKey(routeID))
                        routes[routeID] = new LinkedList<Waypoint>();
                    routes[routeID].AddLast(waypoint);

                }
            }
            foreach (LinkedList<Waypoint> w in routes.Values)
            {
                Route r = new Route(w.ToArray());
                string key = Route.GetKey(r.start, r.end);
                MapTools.routes.Add(key, r);
            }
        }
Example #7
0
    public static void MapWebPageRoute(this RouteCollection routeCollection, string routeUrl, string virtualPath, object defaultValues = null, object constraints = null, string routeName = null)
    {
        routeName = routeName ?? routeUrl;

        Route item = new Route(routeUrl, new RouteValueDictionary(defaultValues), new RouteValueDictionary(constraints), new WebPagesRouteHandler(virtualPath));
        routeCollection.Add(routeName, item);
    }
Example #8
0
 public KmTool(List<Adres> adreslijst)
 {
     this._adresLijst = adreslijst;
     waypoints = new List<WayPoint>();
     route = new Route();
     calculate();
 }
 public EventRouteViewModel(Route evntRoute)
 {
     Title = evntRoute.Title;
     RouteId = evntRoute.RouteId;
     Distance = evntRoute.Distance;
     DateAdded = DateTime.Now.Date.ToString();
 }
Example #10
0
 /// <summary>
 /// Measures the performance.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="testTarget">The test target.</param>
 /// <param name="tests">The tests.</param>
 /// <returns>A performance value or null if performance could not be measured</returns>
 public ProxyPerformance MeasurePerformance(Route route, Uri testTarget, int tests = 3)
 {
     try
     {
         var ping = TimeSpan.Zero;
         var downloadTime = TimeSpan.Zero;
         var downloadSize = 0;
         var timer = new Stopwatch();
         timer.Start();
         for (int test = 0; test < tests; test++)
         {
             var t0 = timer.Elapsed;
             using (var stream = route.Connect(testTarget, NameResolver))
             {
                 var t1 = timer.Elapsed;
                 ping += t1 - t0;
                 HttpRequest.CreateGet(testTarget).Write(stream);
                 var t2 = timer.Elapsed;
                 var httpResponse = HttpResponse.FromStream(stream);
                 downloadSize += httpResponse.ReadContent(stream).Length;
                 var t3 = timer.Elapsed;
                 downloadTime += t3 - t2;
             }
         }
         return new ProxyPerformance(TimeSpan.FromTicks(ping.Ticks / tests), downloadSize / downloadTime.TotalSeconds);
     }
     catch (ProxyRouteException)
     { }
     catch (IOException)
     { }
     catch (SocketException)
     { }
     return null;
 }
		protected virtual bool IsIgnored(Route route)
		{
			if (route is IgnoredRoute)
				return true;

			return route.Tokens.GetValue<bool>(_ignoreKey);
		}
        private void considerRoute(MarketDatabase.Order sellOrder, MarketDatabase.Order buyOrder)
        {
            Route r = new Route();
            r.profitPerItem = buyOrder.price * (1.0 - TAX_RATE) - sellOrder.price;

            if (r.profitPerItem<=0.0)
                return;

            double volumePerItem = items.idToEntry[sellOrder.item.typeId].volume;

            //int outlayQuantityBound = (int)(constraints.maxOutlay / sellOrder.price);
            //int volumeQuantityBound = (int)(constraints.maxVolume / volumePerItem);
            //int constraintsQuantityBound = Math.Min(outlayQuantityBound, volumeQuantityBound);

            r.seller = sellOrder;
            r.buyer = buyOrder;
            r.jumps = pather.getDistance(sellOrder.location, buyOrder.location);
            //negative jumps indicates no path found
            if (r.jumps < 0)
                return;
            r.quantity = Math.Min(sellOrder.quantity, buyOrder.quantity);
            r.profitDensityRate = r.profitPerItem / (volumePerItem * Math.Max(r.jumps, 1));
            r.bulkProfitRate = r.profitPerItem * r.quantity / Math.Max(r.jumps, 1);

            if ((r.profitDensityRate > constraints.minProfitDensityRate)
                && (r.bulkProfitRate > constraints.minBulkProfitRate))
            {
                systemRoutes[pather.graph.nameToId[r.seller.location.name]].Add(r);
                addedRoutes++;
            }
        }
 public RandomStepOpt2Strategy()
     : base()
 {
     Planning = null;
     old_route = null;
     new_route = null;
 }
Example #14
0
 public static void RoutePassed(Route route)
 {
     Invoke(() => {
         Context.Log.Add(new Log {Route = route, Finish = DateTime.Now, Succeed = true});
         Context.SaveChanges();
     });
 }
Example #15
0
        //Loading data from data file
        public async void loadData() {
            Debug.WriteLine("Load Data Came");
            String[] lines;
            String[] temp;
            Route route;

            //Reading the text file
            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var file = await folder.GetFileAsync("data.txt");
            var contents =  await Windows.Storage.FileIO.ReadTextAsync(file);

            //Seperate into variables
            lines = contents.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

            //Clear the buffers
            routes.Clear();
            //Read line by line to get the route number and the locations through the route
            for (int i = 0; i < lines.Length; i++)
            {
                temp = lines[i].Split('|');
                route = new Route(temp[0]);
                //Debug.WriteLine(temp[0] + "-------" + temp[1] + "------------" + temp[2]);
                route = processInput(temp[1], route);
                route = processInput(temp[2], route);
                
                //if else statements for preventing any exceptions due to duplicate key values
                if (!routes.ContainsKey(temp[0]))
                {
                    routes.Add(temp[0], route);
                }
            }

        }
        public static void PostPlanRouteCallback(Route r, string routeType, string result)
        {
            try
            {
                if ((r.Follower != null) && (r.Follower.Target is Sim))
                {
                    if (((r.GetOption(Route.RouteOption.EnableSubwayPlanning)) || (r.GetOption2(Route.RouteOption2.EnableHoverTrainPlanning))) && !r.GetOption(Route.RouteOption.EnableUFOPlanning))
                    {
                        CheckAndUpdateRouteForPortals(r);
                    }

                    if (((routeType == "Replan") || (routeType == "ReplanFromPoint")) && r.GetOption(Route.RouteOption.PlanUsingStroller))
                    {
                        r.SetOption(Route.RouteOption.ReplanUsingStroller, false);
                    }

                    if (RoutingComponent.sPostPlanProfileCallback != null)
                    {
                        RoutingComponent.sPostPlanProfileCallback(r, routeType, result);
                    }
                }
            }
            catch (Exception e)
            {
                Common.Exception("PostPlanRouteCallback", e);
            }
        }
Example #17
0
        public IRouter Build()
        {
            var routeCollection = new RouteCollection();

            foreach (var route in Routes.OfType<Route>())
            {
                var constraints = new Dictionary<string, object>();

                foreach (var kv in route.Constraints)
                {
                    constraints.Add(kv.Key, kv.Value);
                }

                var prefixedRoute = new Route(
                    _baseRouteBuilder.DefaultHandler,
                    route.Name,
                    _routePrefix + route.RouteTemplate,
                    route.Defaults,
                    constraints,
                    route.DataTokens,
                    _constraintResolver);

                _baseRouteBuilder.Routes.Add(prefixedRoute);
            }

            return _baseRouteBuilder.Build();
        }
        private void BindDDL()
        {
            try
            {
                IList<RouteInfo> dRouteList = new Route().GetList();
                ddlRouteName.DataSource = dRouteList;
                ddlRouteName.DataBind();

                IList<ShipInfo> dShipList = new Ship().GetList();
                ddlShipName.DataSource = dShipList;
                ddlShipName.DataBind();
                ddlShipName.Items.Insert(0, new ListItem("全部", ""));

                //tbStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
                //tbEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd");

            }
            catch (ArgumentNullException aex)
            {
                ShowMsg(aex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
                Log(ex);
            }
        }
        private static object[] MapParameters(Route route, MethodInfo action)
        {
            // return action.GetParameters()
            //    .Select<ParameterInfo, object>(p =>
            //    {
            //        if (p.ParameterType == typeof(int))
            //            return int.Parse(route.Parameters[p.Name]);
            //        else
            //            return route.Parameters[p.Name];
            //    })
            ////    .ToArray();

            var expectedMethodParameters = action.GetParameters();
            var argumentsToPass = new List<object>();
            foreach (ParameterInfo param in expectedMethodParameters)
            {
                var currentArgument = route.Parameters[param.Name];
                if (param.ParameterType == typeof(int))
                {
                    argumentsToPass.Add(int.Parse(currentArgument));
                }
                else
                {
                    argumentsToPass.Add(currentArgument);
                }
            }

            return argumentsToPass.ToArray();
        }
Example #20
0
 public void AddExistingRouteTest()
 {
     Administration admin = new Administration();
     Route route = new Route(1);
     admin.Add(route);
     Assert.AreEqual(false, admin.Add(route));
 }
Example #21
0
        public void Run()
        {
            while (true)
            {
                string input = this.UserInterface.ReadLine();
                if (input == null)
                {
                    break;
                }

                var route = new Route(input);
                var controllerType =
                    Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(type => type.Name == route.ControllerName);
                var controller = Activator.CreateInstance(controllerType, this.Database, this.User) as Controller;
                var action = controllerType.GetMethod(route.ActionName);
                object[] @params = MapParameters(route, action);
                try
                {
                    var view = action.Invoke(controller, @params) as IView;
                    this.UserInterface.WriteLine(view.Display());
                    this.User = controller.CurrentUser;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
            }
        }
Example #22
0
	// Use this for initialization
	void Start () {
	   rb = GetComponent<Rigidbody2D>();
       route = GetComponent<Route>();
       s_anim = GetComponent<Animator>();
       hitbox = GetComponent<BoxCollider2D>();
       transform.position = route.GetDest();
	}
        public void TestCreateAndGetAll()
        {
            ICountryDao countryDao = new CountryDao(_graphClient);
            Country country = new Country() {Name = "D"};
            countryDao.Create(country);

            IRoutesDao routeDao = new RouteDao(_graphClient);
            Route route = new Route() {Name = "Route1"};
            routeDao.CreateIn(country, route);

            IDifficultyLevelScaleDao scaleDao = new DifficultyLevelScaleDao(_graphClient);
            DifficultyLevelScale scale = new DifficultyLevelScale() {Name = "sächsisch"};
            scaleDao.Create(scale);

            IDifficultyLevelDao levelDao = new DifficultyLevelDao(_graphClient);
            DifficultyLevel level = new DifficultyLevel() {Name = "7b"};
            levelDao.Create(scale, level);

            IVariationDao variationDao = new VariationDao(_graphClient);
            Variation variation = new Variation() {Name = "Ein Weg der Route1 als 7b"};
            Variation created = variationDao.Create(variation, route, level);

            IList<Variation> variationsOnRoute = variationDao.GetAllOn(route);
            Assert.AreEqual(1, variationsOnRoute.Count);
            Assert.AreEqual(variation.Name, variationsOnRoute.First().Name);
            Assert.AreEqual(variation.Id, variationsOnRoute.First().Id);
            Assert.AreEqual(created.Id, variationsOnRoute.First().Id);
        }
 public static void MapRoute(this RouteCollection routes, string name, string url, string handlerToken, object defaults, object constraints)
 {
     Route route = new Route(url,
         new RouteValueDictionary(defaults),
         new RouteValueDictionary(constraints), GetRouteHandler(handlerToken));
     routes.Add(name, route);
 }
Example #25
0
        public void ReturnOneMethod(IProxyFactory proxyFactory, ILogger logger)
        {
            var alternationImplementation = new Route(proxyFactory, logger);

            Assert.Equal(2, alternationImplementation.AllMethodsRouteBase.Count());
            Assert.Equal(3, alternationImplementation.AllMethodsRoute.Count());
        } 
Example #26
0
	public void append(Route r){
		if(r != null){
			this.locations.AddRange (r.locations);
			this.length += r.length;
		}

	}
 private void Draw(Route route)
 {
     var line = _polyLineCreator.Create(route);
     _canvas.Children.Add(line);
     Canvas.SetZIndex(line, 0);
     _polyLineCreator.SetNextRandomBrush();
 }
        public override Solution executeStrategy(Solution toStartFrom)
        {
            Planning = toStartFrom.GetRandomPlanning();
            if (Planning.Item3.Count == 0)
                return toStartFrom;

            OriginalRoute = Planning.Item3[random.Next(Planning.Item3.Count)];
            if (OriginalRoute == null || OriginalRoute.Orders.Count < 2)
                return toStartFrom;

            int orderIndex = random.Next(OriginalRoute.Orders.Count - 1);
            OrderRemoved = OriginalRoute.Orders[orderIndex];
            OrderBefore = orderIndex == 0 ? null : OriginalRoute.Orders[orderIndex - 1];
            OrderRemoved.AddAvailableOrderBackToCluster();
            OriginalRoute.RemoveOrder(OrderRemoved);

            if (OriginalRoute.Orders.Count == 1)
            { // Basically delete the route (remove it from planning)
                toStartFrom.RemoveRouteFromPlanning(Planning.Item1, Planning.Item2, OriginalRoute);
                toStartFrom.RemoveRoute(OriginalRoute);
            }

            strategyHasExecuted = true;
            return toStartFrom;
        }
Example #29
0
        int CalculateHousesVisited(string input, bool includeRobot)
        {
            if (!includeRobot)
            {
                var route = new Route();

                for (var i = 0; i < input.Length; i++)
                    route.VisitNextHouse(input[i]);

                return route.Houses.Count;
            }
            else
            {
                var route1 = new Route();
                var route2 = new Route();

                for (var i = 0; i < input.Length; i++)
                {
                    if (i % 2 == 0)
                        route1.VisitNextHouse(input[i]);
                    else
                        route2.VisitNextHouse(input[i]);
                }

                var combined = route1.Houses;
                
                foreach (var robotRoute in route2.Houses)
                    if (!combined.Any(x => x.X == robotRoute.X && x.Y == robotRoute.Y))
                        combined.Add(robotRoute);
                
                return combined.Count;
            }
        }
 public GeneticOneRandomRouteStrategy()
     : base()
 {
     originalRoute = null;
     bestAbominationOffspringRoute = null;
     planningForSelectedRoute = null;
 }
Example #31
0
        public override bool Run()
        {
            try
            {
                Definition interactionDefinition = InteractionDefinition as Definition;
                if (interactionDefinition != null)
                {
                    mLookForAutonomousActionsUponArrival = interactionDefinition.mLookForAutonomousActionsUponArrival;
                }
                else
                {
                    mLookForAutonomousActionsUponArrival = true;
                }

                if ((Target.CommercialLotSubType == CommercialLotSubType.kEP10_Resort) &&
                    (Actor.IsHuman) &&
                    (Actor.SimDescription.ChildOrAbove) &&
                    (Actor.LotHome == null) &&
                    (Autonomous) &&
                    (NumFollowers == 0) &&
                    (Actor.GetSituationOfType <Situation>() == null) &&
                    (!Actor.SimDescription.HasActiveRole) &&
                    (Actor.Service == null))
                {
                    IResortTower[] objects = Target.GetObjects <IResortTower>();
                    if (objects.Length > 0)
                    {
                        IResortTower        randomObjectFromList = RandomUtil.GetRandomObjectFromList <IResortTower>(objects);
                        InteractionInstance instance             = randomObjectFromList.GetExitTowerDefinition().CreateInstance(randomObjectFromList, Actor, new InteractionPriority(InteractionPriorityLevel.Autonomous), Autonomous, false);
                        if (Actor.InteractionQueue.PushAsContinuation(instance, false))
                        {
                            if (!Actor.Household.IsServiceNpcHousehold)
                            {
                                foreach (SimDescription description in Actor.Household.SimDescriptions)
                                {
                                    if ((description.IsHuman && description.ChildOrAbove) && (description.CreatedSim == null))
                                    {
                                        Sim actor = description.InstantiateOffScreen(Target);
                                        InteractionInstance entry = randomObjectFromList.GetExitTowerDefinition().CreateInstance(randomObjectFromList, actor, new InteractionPriority(InteractionPriorityLevel.Autonomous), Autonomous, false);
                                        actor.InteractionQueue.Add(entry);
                                    }
                                }
                            }
                            return(true);
                        }
                    }
                }

                if ((Target.CommercialLotSubType == CommercialLotSubType.kEP10_Diving) && Actor.SimDescription.Child)
                {
                    return(false);
                }

                if (!CarpoolManager.WaitForCarpool(Actor))
                {
                    return(false);
                }

                if (ShouldReenqueueWithStandingPrecondition())
                {
                    ChildUtils.SetPosturePrecondition(this, CommodityKind.Standing, new CommodityKind[0x0]);
                    return(Actor.InteractionQueue.PushAsContinuation(this, false));
                }

                if (mFollowers == null)
                {
                    if (InteractionDefinition is DateDefinition)
                    {
                        mFollowers = new List <Sim>();
                    }
                    else
                    {
                        mFollowers = GetFollowers(Actor);
                        if (Actor.IsNPC)
                        {
                            if (mFollowers.Count == 0)
                            {
                                Sim sim;
                                if (HorseManager.NpcShouldRideHorse(Actor, out sim))
                                {
                                    mFollowers.Add(sim);
                                }
                            }
                            else if ((Autonomous && RandomUtil.RandomChance01(Sim.GoForWalkWithDog.kChanceOfAutonomousDogWalk)) && sAcceptableCommercialLotSubTypes.Contains(Target.CommercialLotSubType))
                            {
                                foreach (Sim sim2 in new List <Sim>(mFollowers))
                                {
                                    if (Sim.GoForWalkWithDog.ActorCanWalkTarget(Actor, sim2))
                                    {
                                        InteractionInstance entry = Sim.GoForWalkWithDog.Singleton.CreateInstance(sim2, Actor, GetPriority(), true, false);
                                        (entry as Sim.GoForWalkWithDog).TargetLot = Target;
                                        Actor.InteractionQueue.AddNext(entry);
                                        return(true);
                                    }
                                }
                            }

                            foreach (Sim sim3 in new List <Sim>(mFollowers))
                            {
                                GroupingSituation.StartGroupingSituation(Actor, sim3, false);
                            }
                        }
                        else
                        {
                            GroupingSituation situationOfType = Actor.GetSituationOfType <GroupingSituation>();
                            if ((situationOfType != null) && !situationOfType.ConfirmLeaveGroup(Actor, "Gameplay/Situations/GroupingSituation:ContinueVisitAloneInteraction"))
                            {
                                return(false);
                            }
                        }
                    }
                }

                if (Sim.SwitchToFormalOutfitIfCocktail(Actor, Target))
                {
                    foreach (Sim sim in new List <Sim> (mFollowers))
                    {
                        sim.OutfitCategoryToUseForRoutingOffLot = OutfitCategories.Formalwear;
                    }
                }

                Occupation occupation = Actor.Occupation;
                if (((occupation != null) && (occupation.ActiveCareerLotID == Target.LotId)) && occupation.IsAllowedToWork())
                {
                    Actor.Occupation.EnsureSimHasOccupationOutfit();
                    if (Actor.Posture == Actor.Standing)
                    {
                        Actor.SwitchToOutfitWithSpin(Sim.ClothesChangeReason.GoingToWork);
                    }
                    else
                    {
                        OutfitCategories categories;
                        Actor.GetOutfitForClothingChange(Sim.ClothesChangeReason.GoingToWork, out categories);
                        Actor.OutfitCategoryToUseForRoutingOffLot = categories;
                    }
                }

                bool flag2 = false;

                MetaAutonomyVenueType metaAutonomyVenueType = Target.LotCurrent.GetMetaAutonomyVenueType();

                // Custom
                if ((mFollowers.Count == 0) && (GoHereEx.Teleport.Perform(Actor, Target, true)))
                {
                    flag2 = true;
                }
                else
                {
                    Door door = Target.FindFrontDoor();
                    if (door != null)
                    {
                        bool wantToBeOutside = true;
                        if (Target.IsOpenVenue())
                        {
                            wantToBeOutside = false;
                        }

                        Route r = null;
                        Target.RouteToFrontDoor(Actor, Sim.MinDistanceFromDoorWhenVisiting, Sim.MaxDistanceFromDoorWhenGoingInside, ref door, wantToBeOutside, ref r, false);
                        if (r != null)
                        {
                            r.DoRouteFail = false;
                            flag2         = GoHereSpace.Helpers.SimRoutingComponentEx.DoRouteWithFollowers(Actor.SimRoutingComponent, r, mFollowers);
                            Lot.ValidateFollowers(mFollowers);
                        }
                    }
                }

                if (!flag2)
                {
                    Actor.RemoveExitReason(ExitReason.RouteFailed);
                    Route route = Actor.CreateRoute();
                    if (Autonomous && mLookForAutonomousActionsUponArrival)
                    {
                        bool flag4 = RandomUtil.RandomChance(Lot.ChanceOfGoingToCommunityLotByCar);
                        if (!flag4)
                        {
                            route.SetOption(Route.RouteOption.EnablePlanningAsCar, flag4);
                        }
                    }
                    route.SetRouteMetaType(Route.RouteMetaType.GoCommunityLot);

                    if ((metaAutonomyVenueType == MetaAutonomyVenueType.Diving) && Actor.SimDescription.IsMermaid)
                    {
                        Lot lotCurrent = Actor.LotCurrent;
                        if ((lotCurrent != null) && lotCurrent.IsHouseboatLot())
                        {
                            route.SetOption2(Sims3.SimIFace.Route.RouteOption2.EnablePlanningAsBoat, true);
                        }
                    }

                    Target.PlanToLotEx(route);
                    if (!route.PlanResult.Succeeded())
                    {
                        foreach (Shell shell in Target.GetObjects <Shell>())
                        {
                            route = shell.GetRouteToShell(Actor);
                            if (route.PlanResult.Succeeded())
                            {
                                break;
                            }
                        }
                    }

                    // Custom Function
                    flag2 = GoHereSpace.Helpers.SimRoutingComponentEx.DoRouteWithFollowers(Actor.SimRoutingComponent, route, mFollowers);
                    Lot.ValidateFollowers(mFollowers);
                }

                if (flag2)
                {
                    NumSuccess++;
                    if (Autonomous)
                    {
                        Target.MakeSimDoSomethingAfterArrivingAtVenue(metaAutonomyVenueType, Actor);
                        if (mFollowers != null)
                        {
                            foreach (Sim sim3 in new List <Sim>(mFollowers))
                            {
                                Target.MakeSimDoSomethingAfterArrivingAtVenue(metaAutonomyVenueType, sim3);
                            }
                        }
                    }

                    // Custom check
                    if ((!GoHere.Settings.DisallowAutoGroup(Actor)) &&
                        (Actor.Household != null) &&
                        (!GroupingSituation.DoesGroupingSituationExistForFamily(Actor)))
                    {
                        bool selectable = false;

                        if (SimTypes.IsSelectable(Actor))
                        {
                            selectable = true;
                        }
                        else
                        {
                            foreach (Sim follower in new List <Sim>(mFollowers))
                            {
                                if (SimTypes.IsSelectable(follower))
                                {
                                    selectable = true;
                                    break;
                                }
                            }
                        }

                        // Stop the romantic prompt from appearing
                        GroupingSituation situation = Actor.GetSituationOfType <GroupingSituation>();
                        if (situation != null)
                        {
                            if (situation.Participants == null)
                            {
                                situation.Exit();
                            }

                            if (!selectable)
                            {
                                situation.RomanticGrouping = false;
                            }
                        }

                        GroupingSituation.StartGroupingSitatuationWithFollowers(Actor, mFollowers);
                    }
                    return(flag2);
                }

                if (((Actor.ExitReason & ExitReason.HigherPriorityNext) == ExitReason.None) && ((Actor.ExitReason & ExitReason.UserCanceled) == ExitReason.None))
                {
                    NumFail++;
                }
                return(flag2);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, e);
                return(false);
            }
        }
Example #32
0
        public void BodyQueryI18N_RouteCompilation(string condition)
        {
            var route = new Route("id", condition, "hub", TelemetryMessageSource.Instance, new HashSet <Endpoint>());

            Assert.Throws <RouteCompilationException>(() => RouteCompiler.Instance.Compile(route, RouteCompilerFlags.BodyQuery));
        }
Example #33
0
        public static IEnumerable <object[]> GetEdgeHubConfigData()
        {
            var r1 = new Route("id", string.Empty, "iotHub", Mock.Of <IMessageSource>(), new Mock <Endpoint>("endpoint1").Object, 0, 3600);
            var r2 = new Route("id", string.Empty, "iotHub", Mock.Of <IMessageSource>(), new Mock <Endpoint>("endpoint2").Object, 0, 3600);

            var routeConfig1 = new RouteConfig("r1", "FROM /* INTO $upstream", r1);
            var routeConfig2 = new RouteConfig("r2", "FROM /messages/* INTO $upstream", r2);

            var routes1 = new Dictionary <string, RouteConfig>
            {
                [routeConfig1.Name] = routeConfig1,
                [routeConfig2.Name] = routeConfig2
            };

            var routes2 = new Dictionary <string, RouteConfig>
            {
                [routeConfig1.Name] = routeConfig1
            };

            var routes3 = new Dictionary <string, RouteConfig>
            {
                [routeConfig2.Name] = routeConfig2
            };

            var storeAndForwardConfig1 = new StoreAndForwardConfiguration(-1);
            var storeAndForwardConfig2 = new StoreAndForwardConfiguration(7200);
            var storeAndForwardConfig3 = new StoreAndForwardConfiguration(3600);

            StoreLimits s1 = new StoreLimits(100L);
            StoreLimits s2 = new StoreLimits(200L);
            var         storeAndForwardConfig4 = new StoreAndForwardConfiguration(3600, s1);
            var         storeAndForwardConfig5 = new StoreAndForwardConfiguration(3600, s2);
            var         storeAndForwardConfig6 = new StoreAndForwardConfiguration(3600);

            var bridge1 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.In, "topic/a", "local/", "remote/")
                })
            };

            var bridge2 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.Out, "/topic/b", "local", "remote")
                })
            };

            var bridge3 = new BridgeConfig
            {
                new Bridge("endpoint1", new List <Settings>
                {
                    new Settings(Direction.In, "topic/a", "local/", "remote/")
                })
            };

            var statement1 = new Statement(
                effect: Effect.Allow,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read",
                "write"
            },
                resources: new List <string>
            {
                "file1",
                "file2"
            });

            var statement2 = new Statement(
                effect: Effect.Deny,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read"
            },
                resources: new List <string>
            {
                "root1",
                "root2"
            });

            var statement3 = new Statement(
                effect: Effect.Allow,
                identities: new List <string>
            {
                "device_1"
            },
                operations: new List <string>
            {
                "read",
                "write"
            },
                resources: new List <string>
            {
                "file1",
                "file2"
            });

            var brokerConfig1 = new BrokerConfig(
                Option.Some(bridge1),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement1
            })));
            var brokerConfig2 = new BrokerConfig(
                Option.Some(bridge2),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement2
            })));
            var brokerConfig3 = new BrokerConfig(
                Option.Some(bridge3),
                Option.Some(new AuthorizationConfig(new List <Statement> {
                statement3
            })));

            string version = "1.0";

            var edgeHubConfig1  = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig2  = new EdgeHubConfig(version, routes2, storeAndForwardConfig1, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig3  = new EdgeHubConfig(version, routes3, storeAndForwardConfig1, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig4  = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig5  = new EdgeHubConfig(version, routes1, storeAndForwardConfig2, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig6  = new EdgeHubConfig(version, routes1, storeAndForwardConfig3, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig7  = new EdgeHubConfig(version, routes2, storeAndForwardConfig2, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig8  = new EdgeHubConfig(version, routes2, storeAndForwardConfig3, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig9  = new EdgeHubConfig(version, routes3, storeAndForwardConfig3, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig10 = new EdgeHubConfig(version, routes3, storeAndForwardConfig3, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig11 = new EdgeHubConfig(version, routes3, storeAndForwardConfig4, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig12 = new EdgeHubConfig(version, routes3, storeAndForwardConfig5, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());
            var edgeHubConfig13 = new EdgeHubConfig(version, routes3, storeAndForwardConfig6, Option.Some(brokerConfig1), Option.None <ManifestIntegrity>());

            yield return(new object[] { edgeHubConfig1, edgeHubConfig2, false });

            yield return(new object[] { edgeHubConfig2, edgeHubConfig3, false });

            yield return(new object[] { edgeHubConfig3, edgeHubConfig4, false });

            yield return(new object[] { edgeHubConfig4, edgeHubConfig5, false });

            yield return(new object[] { edgeHubConfig5, edgeHubConfig6, false });

            yield return(new object[] { edgeHubConfig6, edgeHubConfig7, false });

            yield return(new object[] { edgeHubConfig7, edgeHubConfig8, false });

            yield return(new object[] { edgeHubConfig8, edgeHubConfig9, false });

            yield return(new object[] { edgeHubConfig9, edgeHubConfig10, true });

            yield return(new object[] { edgeHubConfig10, edgeHubConfig11, false });

            yield return(new object[] { edgeHubConfig11, edgeHubConfig12, false });

            yield return(new object[] { edgeHubConfig10, edgeHubConfig13, true });

            yield return(new object[] { edgeHubConfig12, edgeHubConfig13, false });

            // authorization config equality check
            var edgeHubConfig14 = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig2), Option.None <ManifestIntegrity>());
            var edgeHubConfig15 = new EdgeHubConfig(version, routes1, storeAndForwardConfig1, Option.Some(brokerConfig3), Option.None <ManifestIntegrity>());

            yield return(new object[] { edgeHubConfig1, edgeHubConfig14, false });

            yield return(new object[] { edgeHubConfig1, edgeHubConfig15, true });
        }
Example #34
0
        public void RoutePositionAfterRegressionTest1()
        {
            var delta = .00001;

            // a route of approx 30 m along the following coordinates:
            // 50.98624687752063, 2.902620979360633
            // 50.98624687752063, 2.9027639004471673 (10m)
            // 50.986156907620895, 2.9027639004471673  (20m)
            // 50.9861564788317, 2.902620884621392 (30m)

            var route1 = new Route();

            route1.Vehicle = Vehicle.Car.UniqueName;
            var route1entry1 = new RouteSegment();

            route1entry1.Distance                = -1;
            route1entry1.Latitude                = 50.98624687752063f;
            route1entry1.Longitude               = 2.902620979360633f;
            route1entry1.Metrics                 = null;
            route1entry1.Points                  = new RoutePoint[1];
            route1entry1.Points[0]               = new RoutePoint();
            route1entry1.Points[0].Name          = "TestPoint1";
            route1entry1.Points[0].Tags          = new RouteTags[1];
            route1entry1.Points[0].Tags[0]       = new RouteTags();
            route1entry1.Points[0].Tags[0].Value = "TestValue1";
            route1entry1.Points[0].Tags[0].Key   = "TestKey1";
            route1entry1.SideStreets             = new RouteSegmentBranch[] {
                new RouteSegmentBranch()
                {
                    Latitude  = 51,
                    Longitude = 3.999f,
                    Tags      = new RouteTags[] {
                        new RouteTags()
                        {
                            Key = "name", Value = "Street B"
                        },
                        new RouteTags()
                        {
                            Key = "highway", Value = "residential"
                        }
                    },
                    Name = "Street B"
                }
            };
            route1entry1.Tags          = new RouteTags[1];
            route1entry1.Tags[0]       = new RouteTags();
            route1entry1.Tags[0].Key   = "highway";
            route1entry1.Tags[0].Value = "residential";
            route1entry1.Time          = 10;
            route1entry1.Type          = RouteSegmentType.Start;
            route1entry1.Name          = string.Empty;
            route1entry1.Names         = null;

            RouteSegment route1entry2 = new RouteSegment();

            route1entry2.Distance                = -1;
            route1entry2.Latitude                = 50.98624687752063f;
            route1entry2.Longitude               = 2.9027639004471673f;
            route1entry2.Metrics                 = null;
            route1entry2.Points                  = new RoutePoint[1];
            route1entry2.Points[0]               = new RoutePoint();
            route1entry2.Points[0].Name          = "TestPoint2";
            route1entry2.Points[0].Tags          = new RouteTags[1];
            route1entry2.Points[0].Tags[0]       = new RouteTags();
            route1entry2.Points[0].Tags[0].Value = "TestValue2";
            route1entry1.Points[0].Tags[0].Key   = "TestKey2";
            route1entry2.SideStreets             = new RouteSegmentBranch[] {
                new RouteSegmentBranch()
                {
                    Latitude  = 51,
                    Longitude = 3.999f,
                    Tags      = new RouteTags[] {
                        new RouteTags()
                        {
                            Key = "name", Value = "Street B"
                        },
                        new RouteTags()
                        {
                            Key = "highway", Value = "residential"
                        }
                    },
                    Name = "Street B"
                }
            };
            route1entry2.Tags          = new RouteTags[1];
            route1entry2.Tags[0]       = new RouteTags();
            route1entry2.Tags[0].Key   = "highway";
            route1entry2.Tags[0].Value = "residential";
            route1entry2.Time          = 10;
            route1entry2.Type          = RouteSegmentType.Start;
            route1entry2.Name          = string.Empty;
            route1entry2.Names         = null;

            RouteSegment route1entry3 = new RouteSegment();

            route1entry3.Distance                = -1;
            route1entry3.Latitude                = 50.986156907620895f;
            route1entry3.Longitude               = 2.9027639004471673f;
            route1entry3.Metrics                 = null;
            route1entry3.Points                  = new RoutePoint[1];
            route1entry3.Points[0]               = new RoutePoint();
            route1entry3.Points[0].Name          = "TestPoint3";
            route1entry3.Points[0].Tags          = new RouteTags[1];
            route1entry3.Points[0].Tags[0]       = new RouteTags();
            route1entry3.Points[0].Tags[0].Value = "TestValue3";
            route1entry1.Points[0].Tags[0].Key   = "TestKey3";
            route1entry3.SideStreets             = new RouteSegmentBranch[] {
                new RouteSegmentBranch()
                {
                    Latitude  = 51,
                    Longitude = 3.999f,
                    Tags      = new RouteTags[] {
                        new RouteTags()
                        {
                            Key = "name", Value = "Street B"
                        },
                        new RouteTags()
                        {
                            Key = "highway", Value = "residential"
                        }
                    },
                    Name = "Street B"
                }
            };
            route1entry3.Tags          = new RouteTags[1];
            route1entry3.Tags[0]       = new RouteTags();
            route1entry3.Tags[0].Key   = "highway";
            route1entry3.Tags[0].Value = "residential";
            route1entry3.Time          = 10;
            route1entry3.Type          = RouteSegmentType.Start;
            route1entry3.Name          = string.Empty;
            route1entry3.Names         = null;

            RouteSegment route1entry4 = new RouteSegment();

            route1entry4.Distance                = -1;
            route1entry4.Latitude                = 50.9861564788317f;
            route1entry4.Longitude               = 2.902620884621392f;
            route1entry4.Metrics                 = null;
            route1entry4.Points                  = new RoutePoint[1];
            route1entry4.Points[0]               = new RoutePoint();
            route1entry4.Points[0].Name          = "TestPoint4";
            route1entry4.Points[0].Tags          = new RouteTags[1];
            route1entry4.Points[0].Tags[0]       = new RouteTags();
            route1entry4.Points[0].Tags[0].Value = "TestValue4";
            route1entry1.Points[0].Tags[0].Key   = "TestKey4";
            route1entry4.SideStreets             = new RouteSegmentBranch[] {
                new RouteSegmentBranch()
                {
                    Latitude  = 51,
                    Longitude = 3.999f,
                    Tags      = new RouteTags[] {
                        new RouteTags()
                        {
                            Key = "name", Value = "Street B"
                        },
                        new RouteTags()
                        {
                            Key = "highway", Value = "residential"
                        }
                    },
                    Name = "Street B"
                }
            };
            route1entry4.Tags          = new RouteTags[1];
            route1entry4.Tags[0]       = new RouteTags();
            route1entry4.Tags[0].Key   = "highway";
            route1entry4.Tags[0].Value = "residential";
            route1entry4.Time          = 10;
            route1entry4.Type          = RouteSegmentType.Start;
            route1entry4.Name          = string.Empty;
            route1entry4.Names         = null;

            route1.Segments    = new RouteSegment[4];
            route1.Segments[0] = route1entry1;
            route1.Segments[1] = route1entry2;
            route1.Segments[2] = route1entry3;
            route1.Segments[3] = route1entry4;

            // create the route tracker.
            var routeTracker = new RouteTracker(route1, new OsmRoutingInterpreter());

            var distance = 5.0;
            var location = route1.PositionAfter(distance);

            routeTracker.Track(location);
            Assert.AreEqual(distance, routeTracker.DistanceFromStart.Value, delta);
            Assert.AreEqual(location.Latitude, routeTracker.PositionRoute.Latitude, delta);
            Assert.AreEqual(location.Longitude, routeTracker.PositionRoute.Longitude, delta);
            Assert.AreEqual(new GeoCoordinate(route1.Segments[1].Latitude, route1.Segments[1].Longitude).DistanceReal(location).Value, routeTracker.DistanceNextInstruction.Value, delta);
            var locationAfter = routeTracker.PositionAfter(10.0);

            distance = 15.0;
            location = route1.PositionAfter(distance);
            Assert.AreEqual(location.Latitude, locationAfter.Latitude, delta);
            Assert.AreEqual(location.Longitude, locationAfter.Longitude, delta);
            routeTracker.Track(location);
            Assert.AreEqual(distance, routeTracker.DistanceFromStart.Value, delta);
            Assert.AreEqual(location.Latitude, routeTracker.PositionRoute.Latitude, delta);
            Assert.AreEqual(location.Longitude, routeTracker.PositionRoute.Longitude, delta);
            Assert.AreEqual(new GeoCoordinate(route1.Segments[2].Latitude, route1.Segments[2].Longitude).DistanceReal(location).Value, routeTracker.DistanceNextInstruction.Value, delta);

            location = new GeoCoordinate(route1.Segments[3].Latitude, route1.Segments[3].Longitude);
            Meter distanceFromStart;

            route1.ProjectOn(location, out distanceFromStart);
            distance = distanceFromStart.Value;
            routeTracker.Track(location);
            Assert.AreEqual(distance, routeTracker.DistanceFromStart.Value, delta);
            Assert.AreEqual(location.Latitude, routeTracker.PositionRoute.Latitude, delta);
            Assert.AreEqual(location.Longitude, routeTracker.PositionRoute.Longitude, delta);
            Assert.AreEqual(0, routeTracker.DistanceNextInstruction.Value, delta);
        }
Example #35
0
    void InitRoutes()
    {
        //forward in our world is +x and left is +y
        //use those vectors to construct the routes
        Vector2 forward       = new Vector2(1, 0);
        Vector2 forward_left  = new Vector2(1, 1);
        Vector2 forward_right = new Vector2(1, -1);
        Vector2 left          = new Vector2(0, 1);
        Vector2 right         = new Vector2(0, -1);


        //post
        Vector2[] postPoints = new Vector2[1];

        postPoints[0] = forward * 7;

        Route postRoute = new Route(RouteName.Post, postPoints);

        routes.Add(postRoute.routeName, postRoute);

        //--------------------------------------------------------------

        //slant-left
        Vector2[] slantLPoints = new Vector2[2];

        slantLPoints[0] = forward * 2;
        slantLPoints[1] = forward_left * 4;

        Route slantLRoute = new Route(RouteName.Slant_Left, slantLPoints);

        routes.Add(slantLRoute.routeName, slantLRoute);

        //--------------------------------------------------------------

        //slant-right
        Vector2[] slantRPoints = new Vector2[2];

        slantRPoints[0] = forward * 2;
        slantRPoints[1] = forward_right * 4;

        Route slantRRoute = new Route(RouteName.Slant_Right, slantRPoints);

        routes.Add(slantRRoute.routeName, slantRRoute);

        //--------------------------------------------------------------

        //insode-left
        Vector2[] insideLPoints = new Vector2[2];

        insideLPoints[0] = forward * 2;
        insideLPoints[1] = left * 5;

        Route insideLRoute = new Route(RouteName.Inside_Left, insideLPoints);

        routes.Add(insideLRoute.routeName, insideLRoute);

        //--------------------------------------------------------------

        //insode-right
        Vector2[] insideRPoints = new Vector2[2];

        insideRPoints[0] = forward * 2;
        insideRPoints[1] = right * 5;

        Route insideRRoute = new Route(RouteName.Inside_Right, insideRPoints);

        routes.Add(insideRRoute.routeName, insideRRoute);

        //--------------------------------------------------------------
    }
Example #36
0
 public Task RemoveRoute(Route route)
 {
     _routes.Remove(route);
     return(Task.CompletedTask);
 }
Example #37
0
 public Task AddRoute(Route route)
 {
     _routes.Add(route);
     return(Task.CompletedTask);
 }
Example #38
0
 /// <summary>
 /// Updates the route.
 /// </summary>
 /// <param name="from">From.</param>
 /// <param name="to">To.</param>
 public static void UpdateRoute(Route from, ref Route to)
 {
     to.DepartureId = from.DepartureId;
     to.ArrivalId = from.ArrivalId;
     to.Active = from.Active;
 }
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(routeDirection == RouteDirection.IncomingRequest);
 }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var isMobileDevice = httpContext.Request.Browser.IsMobileDevice;

            return(!isMobileDevice);
        }
Example #41
0
 public void ConnectRouteToCell(Procescell cell, Route route)
 {
     OrderObservableList.AddSorted(cell.Routes, route);
     route.ProcesCell = cell;
 }
Example #42
0
 public void RemoveRouteFromCell(Procescell cell, Route route)
 {
     cell.Routes.Remove(route);
     route.ProcesCell = null;
 }
        private async Task SendProxyAsync(HttpContext httpContext)
        {
            var req   = httpContext.Request;
            var query = httpContext.Request.Query;

            var path = (string)query["path"];

            if (path != null)
            {
                Proxy proxy = registry.FindExact(path);
                if (proxy == null)
                {
                    var ret = HttpEntity.Create(
                        route: req.GetRequestUri(),
                        status: HttpStatusCode.NotFound,
                        message: $"Proxy não registrado: {path}"
                        );
                    await SendStatusAsync(httpContext, ret);
                }
                else
                {
                    var href           = req.GetRequestUri();
                    var allProxiesHref = new Route(href).UnsetArgs("path");

                    var entity = new Entity();
                    entity.Title = $"Configuração de proxy: {proxy.Path}";
                    entity.Class = KnownClasses.Single;
                    entity.Links = new LinkCollection();
                    entity.Links.AddSelf(href);
                    entity.Links.Add("link", "Todas as configurações de proxy", allProxiesHref);
                    entity.Properties = new PropertyCollection();
                    entity.Properties.AddFromGraph(proxy);
                    entity.Properties.AddDataHeadersFromGraph <Proxy>();

                    await SendStatusAsync(httpContext, Ret.Ok(entity));
                }
            }
            else
            {
                var entity = new Entity();
                entity.Class = KnownClasses.Rows;
                entity.Title = "Todas as configurações de proxy";
                entity.Links = new LinkCollection();
                entity.Links.AddSelf(req.GetRequestUri());
                entity.Entities   = new EntityCollection();
                entity.Properties = new PropertyCollection();
                entity.Properties.AddRowsHeadersFromGraph <Proxy>();

                foreach (var knownPath in registry.Paths)
                {
                    var proxy = registry.FindExact(knownPath);
                    var href  =
                        new Route(req.GetRequestUri())
                        .SetArg("path", proxy.Path)
                        .ToString();

                    var row = new Entity();
                    row.Title = $"Configuração de proxy: {proxy.Path}";
                    row.Class = KnownClasses.Row;
                    row.Rel   = KnownRelations.Row;
                    row.Links = new LinkCollection();
                    row.Links.AddSelf(href);
                    row.Properties = new PropertyCollection();
                    row.Properties.AddFromGraph(proxy);

                    entity.Entities.Add(row);
                }

                await SendStatusAsync(httpContext, Ret.Ok(entity));
            }
        }
Example #44
0
        //creates a route and returns if success
        private Boolean createRoute()
        {
            Route    route        = null;
            Airport  destination1 = (Airport)cbDestination1.SelectedItem;
            Airport  destination2 = (Airport)cbDestination2.SelectedItem;
            Airport  stopover1    = (Airport)cbStopover1.SelectedItem;
            Airport  stopover2    = cbStopover2.Visibility == System.Windows.Visibility.Visible ? (Airport)cbStopover2.SelectedItem : null;
            DateTime startDate    = dpStartDate.IsEnabled && dpStartDate.SelectedDate.HasValue ? dpStartDate.SelectedDate.Value : GameObject.GetInstance().GameTime;

            Weather.Season season = rbSeasonAll.IsChecked.Value ? Weather.Season.All_Year : Weather.Season.Winter;
            season = rbSeasonSummer.IsChecked.Value ? Weather.Season.Summer : season;
            season = rbSeasonWinter.IsChecked.Value ? Weather.Season.Winter : season;

            try
            {
                if (AirlineHelpers.IsRouteDestinationsOk(GameObject.GetInstance().HumanAirline, destination1, destination2, this.RouteType, stopover1, stopover2))
                {
                    Guid id = Guid.NewGuid();

                    //passenger route
                    if (this.RouteType == Route.RouteType.Passenger)
                    {
                        //Vis på showroute
                        route = new PassengerRoute(id.ToString(), destination1, destination2, startDate, 0);

                        foreach (MVVMRouteClass rac in this.Classes)
                        {
                            ((PassengerRoute)route).getRouteAirlinerClass(rac.Type).FarePrice = rac.FarePrice;

                            foreach (MVVMRouteFacility facility in rac.Facilities)
                            {
                                ((PassengerRoute)route).getRouteAirlinerClass(rac.Type).addFacility(facility.SelectedFacility);
                            }
                        }
                    }
                    //cargo route
                    else if (this.RouteType == Route.RouteType.Cargo)
                    {
                        double cargoPrice = Convert.ToDouble(txtCargoPrice.Text);
                        route = new CargoRoute(id.ToString(), destination1, destination2, startDate, cargoPrice);
                    }
                    else if (this.RouteType == Route.RouteType.Mixed)
                    {
                        double cargoPrice = Convert.ToDouble(txtCargoPrice.Text);

                        route = new CombiRoute(id.ToString(), destination1, destination2, startDate, 0, cargoPrice);

                        foreach (MVVMRouteClass rac in this.Classes)
                        {
                            ((PassengerRoute)route).getRouteAirlinerClass(rac.Type).FarePrice = rac.FarePrice;

                            foreach (MVVMRouteFacility facility in rac.Facilities)
                            {
                                ((PassengerRoute)route).getRouteAirlinerClass(rac.Type).addFacility(facility.SelectedFacility);
                            }
                        }
                    }

                    FleetAirlinerHelpers.CreateStopoverRoute(route, stopover1, stopover2);

                    route.Season = season;

                    GameObject.GetInstance().HumanAirline.addRoute(route);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", ex.Message), Translator.GetInstance().GetString("MessageBox", ex.Message, "message"), WPFMessageBoxButtons.Ok);

                return(false);
            }

            return(false);
        }
 public Replace([NotNull] Route route) => Route = route;
Example #46
0
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(RoutingConfigurationProvider
            .GetRoutingConfiguration()
            .SeNameOnlyRoutesEnabled);
 }
 public PopTo([CanBeNull] Route route) => Route = route;
 public Push([NotNull] Route route) => Route = route;
Example #49
0
        public PanelRoute(PageRoutes parent, Route route)
        {
            this.Classes = new Dictionary <Route, Dictionary <AirlinerClass.ClassType, RouteAirlinerClass> >();

            this.ParentPage = parent;

            this.Route = route;

            this.Margin = new Thickness(0, 0, 50, 0);

            TextBlock txtHeader = new TextBlock();

            txtHeader.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            txtHeader.SetResourceReference(TextBlock.BackgroundProperty, "HeaderBackgroundBrush2");
            txtHeader.FontWeight = FontWeights.Bold;
            txtHeader.Uid        = "1000";
            txtHeader.Text       = Translator.GetInstance().GetString("PanelRoute", txtHeader.Uid);
            this.Children.Add(txtHeader);

            ListBox lbRouteInfo = new ListBox();

            lbRouteInfo.ItemContainerStyleSelector = new ListBoxItemStyleSelector();
            lbRouteInfo.SetResourceReference(ListBox.ItemTemplateProperty, "QuickInfoItem");

            this.Children.Add(lbRouteInfo);

            double distance = MathHelpers.GetDistance(this.Route.Destination1.Profile.Coordinates, this.Route.Destination2.Profile.Coordinates);

            lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1016"), UICreator.CreateTextBlock(this.Route.Type.ToString())));
            lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1001"), UICreator.CreateTextBlock(this.Route.Destination1.Profile.Name)));
            lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1002"), UICreator.CreateTextBlock(this.Route.Destination2.Profile.Name)));

            if (this.Route.HasStopovers)
            {
                lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1003"), UICreator.CreateTextBlock(string.Join(", ", from s in this.Route.Stopovers select new AirportCodeConverter().Convert(s.Stopover).ToString()))));
            }

            lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1004"), UICreator.CreateTextBlock(string.Format("{0:0} {1}", new NumberToUnitConverter().Convert(distance), new StringToLanguageConverter().Convert("km.")))));

            if (this.Route.Type == Route.RouteType.Passenger || this.Route.Type == Route.RouteType.Mixed)
            {
                this.Classes.Add(route, new Dictionary <AirlinerClass.ClassType, RouteAirlinerClass>());

                foreach (AirlinerClass.ClassType type in Enum.GetValues(typeof(AirlinerClass.ClassType)))
                {
                    RouteAirlinerClass rClass = ((PassengerRoute)this.Route).getRouteAirlinerClass(type);
                    this.Classes[route].Add(type, rClass);

                    WrapPanel panelClassButtons = new WrapPanel();

                    Button btnEdit = new Button();
                    btnEdit.Background = Brushes.Transparent;
                    btnEdit.Tag        = new KeyValuePair <Route, AirlinerClass.ClassType>(this.Route, type);
                    btnEdit.Click     += new RoutedEventHandler(btnEdit_Click);


                    Image imgEdit = new Image();
                    imgEdit.Width  = 16;
                    imgEdit.Source = new BitmapImage(new Uri(@"/Data/images/edit.png", UriKind.RelativeOrAbsolute));
                    RenderOptions.SetBitmapScalingMode(imgEdit, BitmapScalingMode.HighQuality);

                    btnEdit.Content = imgEdit;

                    Boolean inRoute = route.getAirliners().Exists(a => a.Status != FleetAirliner.AirlinerStatus.Stopped);
                    //btnEdit.Visibility = this.Route.HasAirliner && (this.Route.getCurrentAirliner() != null && this.Route.getCurrentAirliner().Status != FleetAirliner.AirlinerStatus.Stopped) ? Visibility.Collapsed : System.Windows.Visibility.Visible;
                    btnEdit.Visibility = inRoute ? Visibility.Collapsed : System.Windows.Visibility.Visible;

                    panelClassButtons.Children.Add(btnEdit);

                    Image imgInfo = new Image();
                    imgInfo.Width             = 16;
                    imgInfo.Source            = new BitmapImage(new Uri(@"/Data/images/info.png", UriKind.RelativeOrAbsolute));
                    imgInfo.Margin            = new Thickness(5, 0, 0, 0);
                    imgInfo.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                    RenderOptions.SetBitmapScalingMode(imgInfo, BitmapScalingMode.HighQuality);

                    Border brdToolTip = new Border();
                    brdToolTip.Margin  = new Thickness(-4, 0, -4, -3);
                    brdToolTip.Padding = new Thickness(5);
                    brdToolTip.SetResourceReference(Border.BackgroundProperty, "HeaderBackgroundBrush2");

                    ContentControl lblClass = new ContentControl();
                    lblClass.SetResourceReference(ContentControl.ContentTemplateProperty, "RouteAirlinerClassItem");
                    lblClass.Content = rClass;

                    brdToolTip.Child = lblClass;


                    imgInfo.ToolTip = brdToolTip;

                    panelClassButtons.Children.Add(imgInfo);



                    lbRouteInfo.Items.Add(new QuickInfoValue(new TextUnderscoreConverter().Convert(type, null, null, null).ToString(), panelClassButtons));
                }
            }
            if (this.Route.Type == Model.AirlinerModel.RouteModel.Route.RouteType.Mixed || this.Route.Type == Model.AirlinerModel.RouteModel.Route.RouteType.Cargo)
            {
                this.CargoPrice = ((CargoRoute)this.Route).PricePerUnit;

                WrapPanel panelCargo = new WrapPanel();

                txtCargo = UICreator.CreateTextBlock(new ValueCurrencyConverter().Convert(this.CargoPrice).ToString());
                txtCargo.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                panelCargo.Children.Add(txtCargo);

                Button btnEditCargo = new Button();
                btnEditCargo.Margin     = new Thickness(5, 0, 0, 0);
                btnEditCargo.Background = Brushes.Transparent;
                btnEditCargo.Click     += new RoutedEventHandler(btnEditCargo_Click);

                Image imgEdit = new Image();
                imgEdit.Width  = 16;
                imgEdit.Source = new BitmapImage(new Uri(@"/Data/images/edit.png", UriKind.RelativeOrAbsolute));
                RenderOptions.SetBitmapScalingMode(imgEdit, BitmapScalingMode.HighQuality);

                btnEditCargo.Content = imgEdit;

                panelCargo.Children.Add(btnEditCargo);

                lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1015"), panelCargo));
            }
            foreach (StopoverRoute stopover in this.Route.Stopovers)
            {
                foreach (Route leg in stopover.Legs)
                {
                    lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1005"), UICreator.CreateTextBlock(string.Format("{0}-{1}", new AirportCodeConverter().Convert(leg.Destination1), new AirportCodeConverter().Convert(leg.Destination2)))));

                    if (this.Route.Type == Route.RouteType.Passenger || this.Route.Type == Route.RouteType.Mixed)
                    {
                        this.Classes.Add(leg, new Dictionary <AirlinerClass.ClassType, RouteAirlinerClass>());

                        foreach (AirlinerClass.ClassType type in Enum.GetValues(typeof(AirlinerClass.ClassType)))
                        {
                            RouteAirlinerClass rClass = ((PassengerRoute)leg).getRouteAirlinerClass(type);
                            this.Classes[leg].Add(type, rClass);

                            WrapPanel panelClassButtons = new WrapPanel();

                            Button btnEdit = new Button();
                            btnEdit.Background = Brushes.Transparent;
                            btnEdit.Tag        = new KeyValuePair <Route, AirlinerClass.ClassType>(leg, type);
                            btnEdit.Click     += new RoutedEventHandler(btnEdit_Click);

                            Image imgEdit = new Image();
                            imgEdit.Width  = 16;
                            imgEdit.Source = new BitmapImage(new Uri(@"/Data/images/edit.png", UriKind.RelativeOrAbsolute));
                            RenderOptions.SetBitmapScalingMode(imgEdit, BitmapScalingMode.HighQuality);

                            btnEdit.Content = imgEdit;

                            btnEdit.Visibility = this.Route.HasAirliner && (this.Route.getCurrentAirliner() != null && this.Route.getCurrentAirliner().Status != FleetAirliner.AirlinerStatus.Stopped) ? Visibility.Collapsed : System.Windows.Visibility.Visible;

                            panelClassButtons.Children.Add(btnEdit);

                            Image imgInfo = new Image();
                            imgInfo.Width             = 16;
                            imgInfo.Source            = new BitmapImage(new Uri(@"/Data/images/info.png", UriKind.RelativeOrAbsolute));
                            imgInfo.Margin            = new Thickness(5, 0, 0, 0);
                            imgInfo.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                            RenderOptions.SetBitmapScalingMode(imgInfo, BitmapScalingMode.HighQuality);

                            Border brdToolTip = new Border();
                            brdToolTip.Margin  = new Thickness(-4, 0, -4, -3);
                            brdToolTip.Padding = new Thickness(5);
                            brdToolTip.SetResourceReference(Border.BackgroundProperty, "HeaderBackgroundBrush2");

                            ContentControl lblClass = new ContentControl();
                            lblClass.SetResourceReference(ContentControl.ContentTemplateProperty, "RouteAirlinerClassItem");
                            lblClass.Content = rClass;

                            brdToolTip.Child = lblClass;


                            imgInfo.ToolTip = brdToolTip;

                            panelClassButtons.Children.Add(imgInfo);

                            lbRouteInfo.Items.Add(new QuickInfoValue(new TextUnderscoreConverter().Convert(type).ToString(), panelClassButtons));
                        }
                    }
                }
            }

            int numberOfInboundFlights  = this.Route.TimeTable.Entries.Count(e => e.DepartureAirport == this.Route.Destination2);
            int numberOfOutboundFlights = this.Route.TimeTable.Entries.Count(e => e.DepartureAirport == this.Route.Destination1);

            lbRouteInfo.Items.Add(new QuickInfoValue(Translator.GetInstance().GetString("PanelRoute", "1006"), UICreator.CreateTextBlock(string.Format("{0} / {1}", numberOfOutboundFlights, numberOfInboundFlights))));

            WrapPanel buttonsPanel = new WrapPanel();

            buttonsPanel.Margin = new Thickness(0, 5, 0, 0);

            this.Children.Add(buttonsPanel);

            buttonsPanel.Visibility = this.Route.HasAirliner && (this.Route.getCurrentAirliner() != null && this.Route.getCurrentAirliner().Status != FleetAirliner.AirlinerStatus.Stopped) ? Visibility.Collapsed : System.Windows.Visibility.Visible;

            Button btnOk = new Button();

            btnOk.SetResourceReference(Button.StyleProperty, "RoundedButton");
            btnOk.Height  = Double.NaN;
            btnOk.Width   = Double.NaN;
            btnOk.Uid     = "100";
            btnOk.Content = Translator.GetInstance().GetString("General", btnOk.Uid);
            btnOk.SetResourceReference(Button.BackgroundProperty, "ButtonBrush");
            btnOk.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            btnOk.Click += new RoutedEventHandler(btnOk_Click);
            buttonsPanel.Children.Add(btnOk);

            Button btnLoad = new Button();

            btnLoad.SetResourceReference(Button.StyleProperty, "RoundedButton");
            btnLoad.Height  = Double.NaN;
            btnLoad.Width   = Double.NaN;
            btnLoad.Uid     = "115";
            btnLoad.Content = Translator.GetInstance().GetString("General", btnLoad.Uid);
            btnLoad.SetResourceReference(Button.BackgroundProperty, "ButtonBrush");
            btnLoad.Click     += new RoutedEventHandler(btnLoad_Click);
            btnLoad.Margin     = new Thickness(5, 0, 0, 0);
            btnLoad.Visibility = this.Route.Type == Route.RouteType.Cargo ? Visibility.Collapsed : System.Windows.Visibility.Visible;
            buttonsPanel.Children.Add(btnLoad);

            Button btnDelete = new Button();

            btnDelete.SetResourceReference(Button.StyleProperty, "RoundedButton");
            btnDelete.Height  = Double.NaN;
            btnDelete.Width   = Double.NaN;
            btnDelete.Uid     = "200";
            btnDelete.Content = Translator.GetInstance().GetString("PanelRoute", btnDelete.Uid);
            btnDelete.SetResourceReference(Button.BackgroundProperty, "ButtonBrush");
            btnDelete.Margin = new System.Windows.Thickness(5, 0, 0, 0);
            btnDelete.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            btnDelete.Click += new RoutedEventHandler(btnDelete_Click);
            buttonsPanel.Children.Add(btnDelete);

            //if (this.Route.HasStopovers)
            {
                this.Children.Add(createStopoverStatisticsPanel());
            }
            //else
            {
                //  this.Children.Add(createRouteFinancesPanel());
            }

            showRouteFinances();
        }
Example #50
0
        private void sbLeg_Click(object sender, RoutedEventArgs e)
        {
            Route leg = (Route)((ucSelectButton)sender).Tag;

            frmStopoverStatistics.Navigate(createLegStatistics(leg));
        }
Example #51
0
 /// <summary>
 /// Creates or updates a route in the specified route table.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='routeTableName'>
 /// The name of the route table.
 /// </param>
 /// <param name='routeName'>
 /// The name of the route.
 /// </param>
 /// <param name='routeParameters'>
 /// Parameters supplied to the create or update route operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Route> BeginCreateOrUpdateAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
Example #52
0
 private void GivenTheRoute(Route route)
 {
     _route = route;
 }
 public void Apply(IReadModelContext context, IDomainEvent <CargoAggregate, CargoId, CargoBookedEvent> domainEvent)
 {
     Id    = domainEvent.AggregateIdentity;
     Route = domainEvent.AggregateEvent.Route;
 }
Example #54
0
 /// <summary>
 /// Creates or updates a route in the specified route table.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='routeTableName'>
 /// The name of the route table.
 /// </param>
 /// <param name='routeName'>
 /// The name of the route.
 /// </param>
 /// <param name='routeParameters'>
 /// Parameters supplied to the create or update route operation.
 /// </param>
 public static Route BeginCreateOrUpdate(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters)
 {
     return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters).GetAwaiter().GetResult();
 }
Example #55
0
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var controller = values["controller"] as string;

            return(controllers.Contains(controller));
        }
Example #56
0
 /// <summary>
 /// Class constructor
 /// </summary>
 /// <param name="uriInformation"></param>
 /// <param name="route"></param>
 protected ProcessorBase(UriDescriptor uriInformation, Route route)
 {
     UriInformation = uriInformation;
     Route          = route;
 }
Example #57
0
        /// <summary>
        /// Creates or updates a route in the specified route table.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='routeTableName'>
        /// The name of the route table.
        /// </param>
        /// <param name='routeName'>
        /// The name of the route.
        /// </param>
        /// <param name='routeParameters'>
        /// Parameters supplied to the create or update route operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <Route> > BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (routeTableName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
            }
            if (routeName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
            }
            if (routeParameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters");
            }
            if (routeParameters != null)
            {
                routeParameters.Validate();
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2020-11-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("routeTableName", routeTableName);
                tracingParameters.Add("routeName", routeName);
                tracingParameters.Add("routeParameters", routeParameters);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
            _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (routeParameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 201)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <Route>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Route>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Route>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #58
0
 protected override void DoRun()
 {
     this._empty = new TagsCollection();
     if (this._path.Count == 0)
     {
         this.ErrorMessage = "Path was empty.";
         this.HasSucceeded = false;
     }
     else
     {
         uint vertex1 = this._path[0];
         if ((int)vertex1 != -2 && !this._source.IsVertex(this._routerDb, vertex1))
         {
             this.ErrorMessage = "The source is a vertex but the source is not a match.";
             this.HasSucceeded = false;
         }
         else
         {
             uint vertex2 = this._path[this._path.Count - 1];
             if ((int)vertex2 != -2 && !this._target.IsVertex(this._routerDb, vertex2))
             {
                 this.ErrorMessage = "The target is a vertex but the target is not a match.";
                 this.HasSucceeded = false;
             }
             else
             {
                 this._route          = new Route();
                 this._route.Segments = new List <RouteSegment>();
                 this.AddSource();
                 if (this._path.Count == 1)
                 {
                     this.HasSucceeded = true;
                 }
                 else
                 {
                     int index;
                     for (index = 0; index < this._path.Count - 2; ++index)
                     {
                         this.Add(this._path[index], this._path[index + 1], this._path[index + 2]);
                     }
                     this.Add(this._path[index], this._path[index + 1]);
                     this.HasSucceeded = true;
                 }
                 if (this._route.Segments.Count == 1)
                 {
                     this._route.Segments[0].SetStop(new ICoordinate[2]
                     {
                         this._source.Location(),
                         this._target.Location()
                     }, new TagsCollectionBase[2]
                     {
                         this._source.Tags,
                         this._target.Tags
                     });
                 }
                 else
                 {
                     this._route.Segments[0].SetStop(this._source.Location(), this._source.Tags);
                     this._route.Segments[this._route.Segments.Count - 1].SetStop(this._target.Location(), this._target.Tags);
                     this._route.TotalDistance = this._route.Segments[this._route.Segments.Count - 1].Distance;
                     this._route.TotalTime     = this._route.Segments[this._route.Segments.Count - 1].Time;
                 }
             }
         }
     }
 }
Example #59
0
 public void InitWithData(Vehicle vehicle, Route route, bool runUpdates)
 {
     _runUpdates  = runUpdates;
     this.Vehicle = vehicle;
     this.Route   = route;
 }
Example #60
0
        /// <summary>
        /// Creates or updates a route in the specified route table.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='routeTableName'>
        /// The name of the route table.
        /// </param>
        /// <param name='routeName'>
        /// The name of the route.
        /// </param>
        /// <param name='routeParameters'>
        /// Parameters supplied to the create or update route operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <Route> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }