public void GetRoutesForVerb_Called_ExpectOnlyRoutesMatchingVerbAreReturned(
			Route[] mixedVerbRoutes, string verb, string[] routes, MethodInfo method)
		{
			var specificVerbRoutes = routes.Select(x => new Route(verb, x, method)).ToArray();
			var table = new RouteTable(mixedVerbRoutes.Concat(specificVerbRoutes).Shuffle());
			table.GetRoutesForVerb(verb).Should().BeEquivalentTo(specificVerbRoutes);
		}
Exemplo n.º 2
0
        public async void TestRouter()
        {
            var routeTable = new RouteTable(
                Route.Get("/").With(() => new TextResponse("root")),
                Route.Get("/1").With(() => new TextResponse("one")),
                Route.Get("/2").With(() => new TextResponse("two")),
                Route.Get("/3").With(() => new TextResponse("three")),
                Route.Get("/{number}/capture").With(() => new TextResponse("some number"))
            );

            var router = new Router(routeTable);

            var req1 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/invalid"), "/invalid", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream());
            var result1 = await router.HandleRequest(req1, DateTime.UtcNow);
            var resp1 = result1.HttpResponse;
            Assert.AreEqual(HttpStatusCode.NotFound, resp1.StatusCode);

            var req2 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/1"), "/1", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream());
            var result2 = await router.HandleRequest(req2, DateTime.UtcNow);
            var resp2 = result2.HttpResponse;
            Assert.IsInstanceOf<TextResponse>(resp2);
            Assert.AreEqual(ContentTypes.Plain, resp2.ContentType);
            Assert.AreEqual("one", System.Text.Encoding.UTF8.GetString(resp2.Body));

            var req3 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/8/capture"), "/8/capture", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream());
            await router.HandleRequest(req3, DateTime.UtcNow);
            Assert.AreEqual("8", req3.PathVariables["number"]);

        }
    public void run()
    {
      var route_table = new RouteTable(startup_service.fetch<IProvideStartupServices>(),
        startup_service.fetch<IFetchDependencies>());

      startup_service.register_instance<PageFactory>(BuildManager.CreateInstanceFromVirtualPath);
      startup_service.register_instance<GetTheCurrentlyExecutingRequest>(() => HttpContext.Current);
      startup_service.register<ICreateControllerRequests, StubRequestFactory>();
      startup_service.register_instance<RawRedirect_Behaviour>(path => HttpContext.Current.Response.Redirect(path,true));
      startup_service.register<IRedirect, Redirect>();
      startup_service.register<ICreateOneReport, CreateOneReport>();
      startup_service.register<IFindPathsToViews, StubPathRegistry>();
      startup_service.register<IProcessOneRequest, StubMissingCommand>();
      startup_service.register<IFindViewsToDisplayReportModels, WebFormRegistry>();
      startup_service.register<IDisplayInformation, WebFormDisplayEngine>();
      startup_service.register_instance<IEnumerable<IProcessOneRequest>>(route_table);
      startup_service.register_instance<IRegisterRoutes>(route_table);
      startup_service.register_instance<GetTheCurrentPrincipal_Behaviour>(() => HttpContext.Current.User);
      startup_service.register_instance<CreateAuthenticationTicketBehaviour>(
        user => new FormsAuthenticationTicket(100, user, DateTime.Now, DateTime.Now.AddDays(1), false, "1001"));
      startup_service.register_instance<Authentication_Behaviour>((user,pass) => true);
      startup_service.register_instance<AssociateTicketWithCurrentUser_Behaviour>(
        ticket =>
        {
          var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                      FormsAuthentication.Encrypt(ticket));
          HttpContext.Current.Response.Cookies.Add(cookie);
        });
      startup_service.register<IFindCommands, CommandRegistry>();
      startup_service.register<IProcessRequests, FrontController>();

      startup_service.register_instance<GetTheCurrentTicket>(create_the_current_ticket);
      startup_service.register_instance<GetTheCurrentUserIDFromTicket>(ticket =>
        ticket == null ? 0 : long.Parse(ticket.UserData));
      startup_service.register_instance<PrincipalFactory>((id) => new StubPrincipal(id));
      startup_service.register_instance<GetTheCurrentUrl_Behaviour>(() => HttpContext.Current.Request.Url);
      startup_service.register_instance<IsAuthorizedUrl_Behaviour>(uri =>
      {
        return HttpContext.Current.User.cast_to<StubPrincipal>().user_id ==
          long.Parse(HttpContext.Current.Request.QueryString["id"]);
      });
      startup_service.register_instance<Logout_Behaviour>(() => FormsAuthentication.SignOut());
      startup_service.register_instance<PrincipalSwitch>(new_principal =>
      {
        Thread.CurrentPrincipal = new_principal;
        HttpContext.Current.User = new_principal;
      });

    }
    public void run()
    {
      var route_table = new RouteTable(startup_service.fetch<IProvideStartupServices>(),
        startup_service.fetch<IFetchDependencies>());

      startup_service.register_instance<PageFactory>(BuildManager.CreateInstanceFromVirtualPath);
      startup_service.register_instance<GetTheCurrentlyExecutingRequest>(() => HttpContext.Current);
      startup_service.register<ICreateControllerRequests, StubRequestFactory>();
      startup_service.register_instance<RawRedirect>(path => HttpContext.Current.Response.Redirect(path,true));
      startup_service.register<IRedirect, Redirect>();
      startup_service.register<ICreateOneReport, CreateOneReport>();
      startup_service.register<IFindPathsToViews, StubPathRegistry>();
      startup_service.register<IProcessOneRequest, StubMissingCommand>();
      startup_service.register<IFindViewsToDisplayReportModels, WebFormRegistry>();
      startup_service.register<IDisplayInformation, WebFormDisplayEngine>();
      startup_service.register_instance<IEnumerable<IProcessOneRequest>>(route_table);
      startup_service.register_instance<IRegisterRoutes>(route_table);
      startup_service.register<IFindCommands, CommandRegistry>();
      startup_service.register<IProcessRequests, FrontController>();
    }
Exemplo n.º 5
0
        public void TestRouteTable()
        {
            Action noOp = () => {};

            Endpoint ep1 = Route.Get("/files/*").WithAction(noOp);
            Endpoint ep2 = Route.Get("/accounts/{id}").WithAction(noOp);
            Endpoint ep3 = Route.Get("/").WithAction(noOp);
            Endpoint ep4 = Route.Post("/accounts/").WithAction(noOp);
            Endpoint ep5 = Route.Get("/accounts/{id}/data").WithAction(noOp);
            Endpoint ep6 = Route.Get("/*").WithAction(noOp);

            var routeTable = new RouteTable(ep1, ep2, ep3, ep4, ep5, ep6);

            int matchedIndex;
            IReadOnlyDictionary<string, string> pathVariables;

            matchedIndex = routeTable.TryMatchEndpoint(Method.GET, new Uri("http://localhost/"), out pathVariables);
            Assert.AreSame(ep3, routeTable[matchedIndex]);

            matchedIndex = routeTable.TryMatchEndpoint(Method.GET, new Uri("http://localhost/accounts/111/data?keys=name"), out pathVariables);
            Assert.AreSame(ep5, routeTable[matchedIndex]);
            Assert.AreEqual("111", pathVariables["id"]);
            Assert.AreEqual(-1, routeTable.TryMatchEndpoint(Method.POST, new Uri("http://localhost/accounts/111/data"), out pathVariables));
            Assert.IsNull(pathVariables);

            matchedIndex = routeTable.TryMatchEndpoint(Method.GET, new Uri("http://localhost/files/images/test.png"), out pathVariables);
            Assert.AreSame(routeTable[matchedIndex], ep1);

            matchedIndex = routeTable.TryMatchEndpoint(Method.GET, new Uri("http://localhost/accounts/222"), out pathVariables);
            Assert.AreSame(ep2, routeTable[matchedIndex]);
            Assert.AreEqual("222", pathVariables["id"]);

            matchedIndex = routeTable.TryMatchEndpoint(Method.GET, new Uri("http://localhost/whatever"), out pathVariables);
            Assert.AreSame(ep6, routeTable[matchedIndex]);

            Assert.AreEqual(-1, routeTable.TryMatchEndpoint(Method.POST, new Uri("http://localhost/"), out pathVariables));
        }
Exemplo n.º 6
0
        public async Task <Response <RouteTable> > GetAsync(string resourceGroupName, string routeTableName, string expand = null, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (routeTableName == null)
            {
                throw new ArgumentNullException(nameof(routeTableName));
            }

            using var message = CreateGetRequest(resourceGroupName, routeTableName, expand);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                RouteTable value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = RouteTable.DeserializeRouteTable(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
Exemplo n.º 7
0
        public void testHomepage()
        {
            string routecfg = @"
default;default:{controller=SiteMain, action=Index}
{owner};default:{ownertype=space}
~/{controller}/{id};default:{action=Show};requirements:{id=int}
~/{controller}/{action};requirements:{controller=letter}
~/{controller}/{id}/{action};
";


            RouteTable.GetRoutes().Clear();
            RouteTable.Init(routecfg);

            Route rt = RouteTool.RecognizePath("");

            Assert.AreEqual("site", rt.owner);
            Assert.AreEqual("site", rt.ownerType);

            Assert.AreEqual("SiteMain", rt.controller);
            Assert.AreEqual("Index", rt.action);
            Assert.AreEqual(0, rt.id);
            Assert.AreEqual("", rt.ns);
            Assert.AreEqual(0, rt.appId);


            Route rt2 = RouteTool.RecognizePath("http://www.abc.com");

            Assert.AreEqual("site", rt2.owner);
            Assert.AreEqual("site", rt2.ownerType);

            Route rt3 = RouteTool.RecognizePath("http://blog.abc.com");

            Assert.AreEqual("site", rt3.owner);
            Assert.AreEqual("site", rt3.ownerType);
        }
Exemplo n.º 8
0
        public void testNamedRoute()
        {
            string routecfg = @"
default;default:{controller=SiteMain, action=Index}
login;default:{controller=SiteMain,action=Login}
logout;default:{controller=SiteMain,action=Logout}
register;default:{controller=SiteMain,action=Register}

user;default:{ownertype=site,owner=site}
bbs;default:{ownertype=site,owner=site}
group;default:{ownertype=site,owner=site}

//~/{controller}/{id}/{action};requirements:{controller=letter,id=int,action=letter}
//~/{controller}/{id}/{action}/{page};requirements:{controller=letter,id=int,action=letter,page=page}

~/{controller}/{id};default:{action=Show};requirements:{id=int}
~/{controller}/{action};requirements:{controller=letter}
~/{controller}/{id}/{action};
";



            RouteTable.GetRoutes().Clear();
            RouteTable.Init(routecfg);

            Route rr1 = RouteTool.RecognizePath("login");

            Assert.AreEqual("", rr1.ns);
            Assert.AreEqual("site", rr1.ownerType);
            Assert.AreEqual("site", rr1.owner);
            Assert.AreEqual("SiteMain", rr1.controller);
            Assert.AreEqual("Login", rr1.action);

            Route rr2 = RouteTool.RecognizePath("logout");

            Assert.AreEqual("site", rr2.ownerType);
            Assert.AreEqual("site", rr2.owner);
            Assert.AreEqual("SiteMain", rr2.controller);
            Assert.AreEqual("Logout", rr2.action);

            Route rr3 = RouteTool.RecognizePath("register");

            Assert.AreEqual("site", rr3.ownerType);
            Assert.AreEqual("site", rr3.owner);
            Assert.AreEqual("SiteMain", rr3.controller);
            Assert.AreEqual("Register", rr3.action);

            Route rt4 = RouteTool.RecognizePath("default");

            Assert.AreEqual("site", rt4.ownerType);
            Assert.AreEqual("site", rt4.owner);
            Assert.AreEqual("SiteMain", rt4.controller);
            Assert.AreEqual("Index", rt4.action);

            Route rt41 = RouteTool.RecognizePath("");

            Assert.AreEqual("site", rt41.ownerType);
            Assert.AreEqual("site", rt41.owner);
            Assert.AreEqual("SiteMain", rt41.controller);
            Assert.AreEqual("Index", rt41.action);

            Route rr5 = RouteTool.RecognizePath("user");

            Assert.AreEqual("site", rr5.ownerType);
            Assert.AreEqual("site", rr5.owner);
            Assert.AreEqual("", rr5.controller);
            Assert.AreEqual("Index", rr5.action);

            Route rr6 = RouteTool.RecognizePath("bbs");

            Assert.AreEqual("site", rr6.ownerType);
            Assert.AreEqual("site", rr6.owner);
            Assert.AreEqual("", rr6.controller);
            Assert.AreEqual("Index", rr6.action);

            Route rr7 = RouteTool.RecognizePath("group");

            Assert.AreEqual("site", rr7.ownerType);
            Assert.AreEqual("site", rr7.owner);
            Assert.AreEqual("", rr7.controller);
            Assert.AreEqual("Index", rr7.action);
        }
 /// <summary>
 /// The Put RouteTable operation creates/updates a route tablein the
 /// specified resource group.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Network.IRouteTableOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='routeTableName'>
 /// Required. The name of the route table.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the create/update Route Table
 /// operation
 /// </param>
 /// <returns>
 /// Response for PUT RouteTables Api servive call
 /// </returns>
 public static RouteTablePutResponse BeginCreateOrUpdating(this IRouteTableOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IRouteTableOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, routeTableName, parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Exemplo n.º 10
0
        void mainLoopTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            lock (this)
            {
                mainLoopTimer.Enabled = false;
                RefreshNeigbors();
                TimeSpan iterationTime = new TimeSpan(DateTime.Now.Ticks);
                int      diff          = (int)(iterationTime - lastIterationTime).TotalMilliseconds;
                lastIterationTime = iterationTime;

                if (LookTable.Count > 0) //Check pending searches
                {
                    List <string> items = LookTable.Keys.ToList();
                    for (int i = 0; i < items.Count; i++)
                    {
                        string search = items[i];
                        var    aux    = LookTable[search];
                        if (aux.Value > 0)
                        {
                            int newCount = aux.Value - diff;

                            LookTable[search] = new KeyValuePair <string, int>(aux.Key, newCount);
                        }
                        else
                        {
                            LookTable.Remove(search);
                        }
                    }
                }

                if (outputBuffer.Count > 0)//Messages to send
                {
                    List <RFMessage> items = outputBuffer.Keys.ToList();
                    //List<RFMessage> removeList = new List<RFMessage>();

                    foreach (var outmsg in items)
                    {
                        if (!LookTable.ContainsKey(outmsg.To))//Look finished
                        {
                            transmitRF(outmsg);
                            //removeList.Add(outmsg);
                            outputBuffer.Remove(outmsg);
                        }
                        else if (LookTable[outmsg.To].Value <= 0)
                        {
                            Program.MessageBoxCustom("Timeout superado", "MESSAGE FROM " + outmsg.Root + " TO " + outmsg.To + "           ");
                            //removeList.Add(outmsg);
                            outputBuffer.Remove(outmsg);
                            LookTable.Remove(outmsg.To);
                        }
                    }
                    //outputBuffer.RemoveAll(x => removeList.Contains(x));
                }

                if (inputBuffer.Count > 0)//Messages to read
                {
                    RFMessage message    = inputBuffer[0];
                    byte      maskHeader = (byte)(message.Header & 0xC0);

                    if (maskHeader == 0x40)//Is RouteAnswer?
                    {
                        if (RouteTable.ContainsKey(message.Data))
                        {
                            RFMessage routeResponse = new RFMessage();
                            routeResponse.To     = message.From;
                            routeResponse.From   = Address;
                            routeResponse.Header = (byte)(0x20 | RouteTable[message.Data].Value); //RouteResponse OK y longitud almacenada en la routeTable
                            routeResponse.Data   = message.Data;                                  //Search Node

                            Node Dest = Program.NodeList.First <Node>(x => x.Address == message.From);
                            Dest.SendMessage(routeResponse);
                        }
                        else
                        {
                            LookFor(message.Data, message.From);
                        }
                    }
                    else if (maskHeader == 0x00)                     //Is RouteResponse?
                    {
                        bool isOK = (message.Header & 0xE0) == 0x20; //is OK?
                        if (isOK)
                        {
                            byte distance = (byte)(message.Header & 0x1F);
                            if (distance == 0x1F)
                            {
                                throw new IndexOutOfRangeException(); //Distance Overflow
                            }
                            if (RouteTable.ContainsKey(message.Data))
                            {
                                if ((distance + 1) < RouteTable[message.Data].Value) //Short way
                                {
                                    RouteTable[message.Data] = new KeyValuePair <string, int>(message.From, distance + 1);
                                }
                            }
                            else
                            {
                                RouteTable.Add(message.Data, new KeyValuePair <string, int>(message.From, distance + 1));
                            }
                        }
                        else if (RouteTable.ContainsKey(message.Data) && RouteTable[message.Data].Key == message.From)
                        {
                            RouteTable.Remove(message.Data);
                            //Avisar a mis vecinos de que ya no puedo llegar al destinatario del mensaje
                            foreach (var nodeAddress in NeighborsTable)
                            {
                                if (message.From != nodeAddress)
                                {
                                    RFMessage routeResponse = new RFMessage();
                                    routeResponse.To     = nodeAddress;
                                    routeResponse.From   = Address;
                                    routeResponse.Data   = message.Data; //Search Node
                                    routeResponse.Header = 0x00;         //RouteResponse FAIL
                                    routeResponse.Root   = message.Root; //TRAMPA

                                    Node Dest = Program.NodeList.First <Node>(x => x.Address == routeResponse.To);
                                    Dest.SendMessage(routeResponse);
                                }
                            }

                            //TODO: Si existen mensajes pendientes para este nodo, se reintenta para trazar una nueva ruta
                            if (message.Root == Address)//outputBuffer.Exists(x => x.To == message.Data))
                            {
                                //RFMessage retry = outputBuffer.First(x => x.To == message.Data);
                                //outputBuffer.Remove(retry);
                                //transmitRF(retry);
                                Program.MessageBoxCustom("Ha cambiado la topologia de la red. Reenviar", "MESSAGE FROM " + Address + " TO " + message.Data + "           ");
                            }
                        }

                        if (LookTable.ContainsKey(message.Data) && LookTable[message.Data].Key != null)
                        {
                            RFMessage routeResponse = new RFMessage();
                            routeResponse.To   = LookTable[message.Data].Key;
                            routeResponse.From = Address;
                            routeResponse.Data = message.Data; //Search Node

                            if (isOK)
                            {
                                routeResponse.Header = (byte)(0x20 | (byte)(message.Header & 0x1F) + 1); //RouteResponse OK y longitud recibida + 1
                            }
                            else
                            {
                                routeResponse.Header = 0x00; //RouteResponse FAIL
                            }
                            Node Dest = Program.NodeList.First <Node>(x => x.Address == routeResponse.To);
                            Dest.SendMessage(routeResponse);
                        }

                        LookTable.Remove(message.Data);
                    }
                    else //Is a message
                    {
                        if (message.To == Address) //it's to me?
                        {
                            message.Data += Address;
                            Program.MessageBoxCustom(message.Data, "MESSAGE FROM " + message.Root + " TO " + message.To + "           ");
                        }
                        else if (RouteTable.ContainsKey(message.To))
                        {
                            message.From  = Address;
                            message.Data += Address + " -> ";
                            Node Dest = Program.NodeList.First <Node>(x => x.Address == RouteTable[message.To].Key);
                            Dest.SendMessage(message);
                        }
                        else
                        {
                            RFMessage routeResponse = new RFMessage();
                            routeResponse.To     = message.From;
                            routeResponse.From   = Address;
                            routeResponse.Data   = message.To;   //Search Node
                            routeResponse.Header = 0x00;         //RouteResponse FAIL
                            routeResponse.Root   = message.Root; //TRAMPA

                            Node Dest = Program.NodeList.First <Node>(x => x.Address == routeResponse.To);
                            Dest.SendMessage(routeResponse);
                        }
                    }

                    inputBuffer.Remove(message);
                }
            }
        }
Exemplo n.º 11
0
        private static void RouteFromAzureToAzure(IConfiguration config, RouterConfiguration routerConfig, RouteTable staticRouting)
        {
            var connectionStringA         = config.GetConnectionString("NServiceBus:AzureServiceBusA");
            var azureServiceBusAInterface = routerConfig.AddInterface <AzureServiceBusTransport>("AzureServiceBusA", t => {
                t.ConnectionString(connectionStringA);
                t.Transactions(TransportTransactionMode.ReceiveOnly);
            });

            var connectionStringB         = config.GetConnectionString("NServiceBus:AzureServiceBusB");
            var azureServiceBusBInterface = routerConfig.AddInterface <AzureServiceBusTransport>("AzureServiceBusB", t =>
            {
                t.ConnectionString(connectionStringB);
                t.Transactions(TransportTransactionMode.ReceiveOnly);
            });

            staticRouting.AddForwardRoute("AzureServiceBusA", "AzureServiceBusB");
            staticRouting.AddForwardRoute("AzureServiceBusB", "AzureServiceBusA");
        }
Exemplo n.º 12
0
 /// <summary>
 /// Create or updates a route table in a specified resource group.
 /// </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='parameters'>
 /// Parameters supplied to the create or update route table operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <RouteTable> BeginCreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemplo n.º 13
0
        public static void Main(string[] args)
        {
            var procs = Environment.ProcessorCount;
            ThreadPool.SetMaxThreads(procs, Math.Max(1, procs / 4));
            ThreadPool.SetMaxThreads(procs * 2, Math.Max(1, procs / 2));
            
            LoggingProvider.Use(LoggingProvider.ConsoleLoggingProvider);

            var config = ConfigManager.Load<ServerConfig>();

            var server = new HttpBackend(IPAddress.Any, config.ListenPort);

            var wsService = new WebSocketService();
            var staticWebContentFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web");

            var routeTable = new RouteTable(
                Route.Get("/*").With(new DirectoryInfo(staticWebContentFolder)),
                Route.Get("/").With(wsService.Redirect),
                Route.Get("/plaintext").With(() => greeting),
                Route.Get("/plaintext/delayed").WithAsync(DelayedGreeter),
                Route.GetWebSocketUpgrade("/ws").With(wsService.HandleUpgradeRequest),
                Route.Get("/metrics").With(Lift.ToJsonHandler(server.GetMetricsReport))
                                     .ApplyResponseFilter(Filters.GZip)
                                     .LimitRate(100)
            );

            server.Start(routeTable);
        }
Exemplo n.º 14
0
        public async Task SubnetRouteTableTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/routeTables");

            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string routeTableName = Recording.GenerateAssetName("azsmnet");
            string route1Name     = Recording.GenerateAssetName("azsmnet");

            RouteTable routeTable = new RouteTable()
            {
                Location = location,
            };

            routeTable.Routes = new List <Route>();

            Route route1 = new Route()
            {
                AddressPrefix    = "192.168.1.0/24",
                Name             = route1Name,
                NextHopIpAddress = "23.108.1.1",
                NextHopType      = RouteNextHopType.VirtualAppliance
            };

            routeTable.Routes.Add(route1);

            // Put RouteTable
            RouteTablesCreateOrUpdateOperation putRouteTableResponseOperation = await NetworkManagementClient.RouteTables.StartCreateOrUpdateAsync(resourceGroupName, routeTableName, routeTable);

            Response <RouteTable> putRouteTableResponse = await WaitForCompletionAsync(putRouteTableResponseOperation);

            Assert.AreEqual("Succeeded", putRouteTableResponse.Value.ProvisioningState.ToString());

            // Get RouteTable
            Response <RouteTable> getRouteTableResponse = await NetworkManagementClient.RouteTables.GetAsync(resourceGroupName, routeTableName);

            // Verify that the subnet reference is null
            Assert.Null(getRouteTableResponse.Value.Subnets);

            // Create Vnet with subnet and add a route table
            string vnetName   = Recording.GenerateAssetName("azsmnet");
            string subnetName = Recording.GenerateAssetName("azsmnet");

            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16",
                    }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = new List <string>()
                    {
                        "10.1.1.1", "10.1.2.4"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = subnetName,
                        AddressPrefix = "10.0.0.0/24",
                        RouteTable    = new RouteTable()
                        {
                            Id = getRouteTableResponse.Value.Id,
                        }
                    }
                }
            };

            VirtualNetworksCreateOrUpdateOperation putVnetResponseOperation = await NetworkManagementClient.VirtualNetworks.StartCreateOrUpdateAsync(resourceGroupName, vnetName, vnet);

            Response <VirtualNetwork> putVnetResponse = await WaitForCompletionAsync(putVnetResponseOperation);

            Assert.AreEqual("Succeeded", putVnetResponse.Value.ProvisioningState.ToString());

            Response <Subnet> getSubnetResponse = await NetworkManagementClient.Subnets.GetAsync(resourceGroupName, vnetName, subnetName);

            Assert.AreEqual(getSubnetResponse.Value.RouteTable.Id, getRouteTableResponse.Value.Id);

            // Get RouteTable
            getRouteTableResponse = await NetworkManagementClient.RouteTables.GetAsync(resourceGroupName, routeTableName);

            Assert.AreEqual(1, getRouteTableResponse.Value.Subnets.Count);
            Assert.AreEqual(getSubnetResponse.Value.Id, getRouteTableResponse.Value.Subnets[0].Id);
        }
Exemplo n.º 15
0
        public void RoutesHopTypeTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/routeTables");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(
                    resourceGroupName,
                    new ResourceGroup {
                    Location = location
                });

                string routeTableName = TestUtilities.GenerateName();
                string route1Name     = TestUtilities.GenerateName();
                string route2Name     = TestUtilities.GenerateName();
                string route3Name     = TestUtilities.GenerateName();
                string route4Name     = TestUtilities.GenerateName();

                var routeTable = new RouteTable()
                {
                    Location = location,
                };
                routeTable.Routes = new List <Route>();

                // Add a route
                var route1 = new Route()
                {
                    AddressPrefix    = "192.168.1.0/24",
                    Name             = route1Name,
                    NextHopIpAddress = "23.108.1.1",
                    NextHopType      = RouteNextHopType.VirtualAppliance
                };

                routeTable.Routes.Add(route1);

                // Put RouteTable
                var putRouteTableResponse =
                    networkManagementClient.RouteTables.CreateOrUpdate(
                        resourceGroupName,
                        routeTableName,
                        routeTable);

                Assert.Equal("Succeeded", putRouteTableResponse.ProvisioningState);

                // Get RouteTable
                var getRouteTableResponse = networkManagementClient.RouteTables.Get(
                    resourceGroupName,
                    routeTableName);

                Assert.Equal(routeTableName, getRouteTableResponse.Name);
                Assert.Equal(1, getRouteTableResponse.Routes.Count);
                Assert.Equal(route1Name, getRouteTableResponse.Routes[0].Name);

                // Add another route
                var route2 = new Route()
                {
                    AddressPrefix = "10.0.1.0/24",
                    Name          = route2Name,
                    NextHopType   = RouteNextHopType.VnetLocal
                };

                networkManagementClient.Routes.CreateOrUpdate(
                    resourceGroupName,
                    routeTableName,
                    route2Name,
                    route2);

                // Add another route
                var route3 = new Route()
                {
                    AddressPrefix = "0.0.0.0/0",
                    Name          = route3Name,
                    NextHopType   = RouteNextHopType.Internet
                };

                networkManagementClient.Routes.CreateOrUpdate(
                    resourceGroupName,
                    routeTableName,
                    route3Name,
                    route3);

                // Add another route
                var route4 = new Route()
                {
                    AddressPrefix = "10.0.2.0/24",
                    Name          = route4Name,
                    NextHopType   = RouteNextHopType.None
                };

                networkManagementClient.Routes.CreateOrUpdate(
                    resourceGroupName,
                    routeTableName,
                    route4Name,
                    route4);

                getRouteTableResponse = networkManagementClient.RouteTables.Get(
                    resourceGroupName,
                    routeTableName);
                Assert.Equal(routeTableName, getRouteTableResponse.Name);
                Assert.Equal(4, getRouteTableResponse.Routes.Count);
                Assert.Equal(route2Name, getRouteTableResponse.Routes[1].Name);
                Assert.Equal(RouteNextHopType.VirtualAppliance, getRouteTableResponse.Routes[0].NextHopType);
                Assert.Equal(RouteNextHopType.VnetLocal, getRouteTableResponse.Routes[1].NextHopType);
                Assert.Equal(RouteNextHopType.Internet, getRouteTableResponse.Routes[2].NextHopType);
                Assert.Equal(RouteNextHopType.None, getRouteTableResponse.Routes[3].NextHopType);

                // Delete RouteTable
                networkManagementClient.RouteTables.Delete(resourceGroupName, routeTableName);

                // Verify delete
                var listRouteTableResponse = networkManagementClient.RouteTables.List(resourceGroupName);

                Assert.Equal(0, listRouteTableResponse.Count());
            }
        }
Exemplo n.º 16
0
 public void Start(RouteTable routeTable)
 {
     Start(new Router(routeTable));
 }
Exemplo n.º 17
0
        private static RouteTableItem matchRoute(HttpContext ctx, RouteTable routeTable)
        {
            var routeTableItem = new RouteTableItem();

            foreach (var routeItem in routeTable)
            {
                var mapKey = routeItem.Key.Split('_')[0];
                var mapMethod = routeItem.Key.Split('_')[1];
                var pathBlock = ctx.Request.Path.Value.Split('/').Where(x => x.IsTrue()).ToArray();

                if (ctx.Request.Path.Value == mapKey && mapKey == "/")
                {
                    routeTableItem = routeItem.Value;
                    //匹配模板路由
                    var routeValueDictionary = Match(mapKey, ctx.Request.Path.Value);
                    if (routeValueDictionary != null)
                    {
                        routeTableItem.RouteValue = routeValueDictionary;
                    }
                    break; ;
                }

                var tmpBlock = mapKey.Split('/').Where(x => x.IsTrue()).ToArray();

                //检查路由Method
                if ((ctx.Request.Method.ToLower() != mapMethod) || ctx.WebSockets.IsWebSocketRequest && mapMethod == "ws")
                {
                    continue;
                }

                //检查路由块数量
                if (pathBlock.Length == 0 || pathBlock.Length != tmpBlock.Length)
                {
                    continue;
                }

                //检查是否匹配了模板块{xxxx}
                var matched = true;
                for (int pathIndex = 0; pathIndex < pathBlock.Length; pathIndex++)
                {
                    var pathItem = pathBlock[pathIndex];
                    var tmpItem = tmpBlock[pathIndex].ToLower();
                    if (!tmpItem.StartsWith("{") && pathItem != tmpItem)
                    {
                        matched = false;
                    }
                }

                if (matched)
                {
                    //匹配模板路由
                    var routeValueDictionary = Match(mapKey.ToLower(), ctx.Request.Path.Value.ToLower());
                    if (routeValueDictionary != null)
                    {
                        routeTableItem = routeItem.Value;
                        routeTableItem.RouteValue = routeValueDictionary;
                        break;
                    }
                }
                else
                {
                    //匹配无模板路由
                    var diff = pathBlock.Except(tmpBlock);
                    if (diff.Count() == 0)
                    {
                        routeTableItem = routeItem.Value;
                        break;
                    }
                }
            }
            return routeTableItem;
        }
Exemplo n.º 18
0
 public OryxWebModule()
 {
     RouteTable       = new RouteTable();
     StaticFilesTable = new StaticFilesTable();
 }
Exemplo n.º 19
0
        private void loop()
        {
            TimeSpan iterationTime = new TimeSpan(DateTime.Now.Ticks);

            refreshNeigbors();

            if (routeBuffer.Count > 0) //check the outstanding route messages
            {
                ROUTE_MSG message = routeBuffer[0];

                if (message.header_restype == 1) //Route Answer
                {
                    bool isNeighbor = NeighborsTable.Contains(message.reference);

                    //Check if the first variable returns true, because in this case the second search is not needed
                    if (isNeighbor || RouteTable.ContainsKey(message.reference))
                    {
                        ROUTE_MSG routeResponse = new ROUTE_MSG();
                        if (isNeighbor)
                        {
                            routeResponse.header_distance = 1;
                        }
                        else
                        {
                            routeResponse.header_distance = (byte)(RouteTable[message.reference][1] + 1);
                        }
                        routeResponse.header_restype = 0; //RESPONSE
                        routeResponse.header_type    = 0; //ROUTE
                        routeResponse.header_ok      = 1;

                        routeResponse.from      = NodeAddress;
                        routeResponse.to        = message.from;
                        routeResponse.parent    = NodeAddress;
                        routeResponse.reference = message.reference;

                        NodeuC Dest = Program.GetNode(message.parent);
                        Dest.SendMessage(routeResponse);

                        //TODO: Notify the node sought to avoid a possible subsequent search in the opposite
                        routeResponse.header_distance = (byte)(message.header_distance + 1);
                        routeResponse.from            = NodeAddress;
                        routeResponse.to        = message.reference;
                        routeResponse.parent    = NodeAddress;
                        routeResponse.reference = message.from;
                        Dest = Program.GetNode(isNeighbor ? message.reference : RouteTable[message.reference][0]);
                        Dest.SendMessage(routeResponse);

                        addToRouteTable(message.from, message.parent, message.header_distance);
                    }
                    else
                    {
                        LookFor(message.reference, message.parent, message.from, (byte)(message.header_distance + 1));
                    }
                    Color = Color.Yellow;
                }
                else //Route Response
                {
                    if (message.header_ok > 0)
                    {
                        addToRouteTable(message.reference, message.parent, message.header_distance);

                        if (LookTable.ContainsKey(message.reference))
                        {
                            byte interested = LookTable[message.reference][0];
                            if (interested != 0)
                            {
                                ROUTE_MSG routeResponse = new ROUTE_MSG();
                                routeResponse.header_distance = (byte)(message.header_distance + 1);
                                routeResponse.header_restype  = 0; //RESPONSE
                                routeResponse.header_type     = 0; //ROUTE
                                routeResponse.header_ok       = 1;

                                routeResponse.from      = message.from;
                                routeResponse.to        = message.to;
                                routeResponse.parent    = NodeAddress;
                                routeResponse.reference = message.reference;

                                NodeuC Dest = Program.GetNode(interested);
                                Dest.SendMessage(routeResponse);

                                //Store the way back if distance > 0 (message.to is not a neighbor)
                                byte distance = LookTable[message.reference][2];
                                if (distance > 0)
                                {
                                    addToRouteTable(message.to, interested, distance);
                                }
                            }
                            LookTable.Remove(message.reference);
                            Color = Color.Purple;
                        }
                    }
                    //This case is given when it tried to route a message from a node that is no longer able to reach the recipient.
                    else if (RouteTable.ContainsKey(message.reference) && RouteTable[message.reference][0] == message.parent)
                    {
                        RouteTable.Remove(message.reference);

                        //Notify the neighbors that I can't reach the intended recipient
                        foreach (var neighborAddress in NeighborsTable)
                        {
                            if (message.parent != neighborAddress)
                            {
                                ROUTE_MSG routeResponse = new ROUTE_MSG();
                                routeResponse.header_restype  = 0; //RESPONSE
                                routeResponse.header_type     = 0; //ROUTE
                                routeResponse.header_ok       = 0; //FAIL
                                routeResponse.header_distance = message.header_distance;
                                routeResponse.from            = NodeAddress;
                                routeResponse.to        = message.to;
                                routeResponse.parent    = NodeAddress;
                                routeResponse.reference = message.reference;

                                NodeuC Dest = Program.GetNode(neighborAddress);
                                Dest.SendMessage(routeResponse);
                            }
                        }

                        //TODO: If there are pending messages for this node, try to trace a new route
                        if (message.to == NodeAddress)
                        {
                            Program.MessageBoxCustom("Ha cambiado la topología de la red. Reenviar", "MESSAGE " + message.header_distance +
                                                     " FROM " + NodeAddress + " TO " + message.reference + "           ");
                        }
                    }
                }

                routeBuffer.Remove(message);
            }

            if (dataInputBuffer.Count > 0)//Data messages to read
            {
                Color = Color.YellowGreen;
                DATA_MSG message = dataInputBuffer[0];
                bool     isNeighbor;
                if (message.to == NodeAddress) //it's to me?
                {
                    Color         = Color.Magenta;
                    message.data += NodeAddress;
                    Program.MessageBoxCustom(message.data, "MESSAGE " + message.header_id +
                                             " FROM " + message.from + " TO " + message.to + " BY " + message.parent + "           ");
                }
                else if ((isNeighbor = NeighborsTable.Contains(message.to)) || RouteTable.ContainsKey(message.to))
                {
                    message.parent = NodeAddress;
                    message.data  += NodeAddress + " -> ";
                    NodeuC Dest = Program.GetNode(isNeighbor ? message.to : RouteTable[message.to][0]);
                    Dest.SendMessage(message);
                }
                else
                {
                    ROUTE_MSG routeResponse = new ROUTE_MSG();
                    routeResponse.header_restype  = 0;                 //RESPONSE
                    routeResponse.header_type     = 0;                 //ROUTE
                    routeResponse.header_ok       = 0;                 //FAIL
                    routeResponse.header_distance = message.header_id; //Use the length field to store the id of the failed message
                    routeResponse.from            = NodeAddress;
                    routeResponse.to        = message.from;
                    routeResponse.parent    = NodeAddress;
                    routeResponse.reference = message.to;

                    NodeuC Dest = Program.GetNode(message.parent);
                    Dest.SendMessage(routeResponse);
                }
                dataInputBuffer.Remove(message);
            }

            if (dataOutputBuffer.Count > 0)//Messages to send
            {
                List <DATA_MSG> items = dataOutputBuffer.ToList();

                foreach (var message in items)
                {
                    if (!LookTable.ContainsKey(message.to))//Look finished
                    {
                        transmitRF(message);
                        dataOutputBuffer.Remove(message);
                    }
                    else if (LookTable[message.to][1] >= TIMEOUT)
                    {
                        Program.MessageBoxCustom("Timeout superado", "MESSAGE FROM " + message.from + " TO " + message.to + "           ");
                        dataOutputBuffer.Remove(message);
                        LookTable.Remove(message.to);
                    }
                }
            }

            int diff = (int)(iterationTime - lastLookTableUpdate).TotalMilliseconds;

            if (diff > 1000 && LookTable.Count > 0) //Check the pending searches every second
            {
                foreach (var item in LookTable.ToList())
                {
                    byte reference = item.Key;
                    byte counter   = item.Value[1];

                    if (counter < TIMEOUT)
                    {
                        LookTable[reference][1]++;
                    }
                    else
                    {
                        LookTable.Remove(reference); //TIMEOUT limit exceeded
                    }
                }

                lastLookTableUpdate = iterationTime;
            }
        }
Exemplo n.º 20
0
 public Selector(ApiContainer container)
 {
     _container = container ?? throw new ArgumentNullException(nameof(container));
     Data       = new NameDictionary();
     _route     = new RouteTable(_container.Apis);
 }
Exemplo n.º 21
0
        public static void Init()
        {
            s_RouteTable = new RouteTable(

                new RouteTable("^default$"
                               , "~/max-templates/default/forums/default.aspx"
                               )

                #region 群组

                , new RouteTable("^club/"
                                 , new RouteTable(
                                     @"\Gcreate$"
                                     , "~/max-templates/default/icenter/club-create.aspx"
                                     )
                                 , new RouteTable(
                                     @"\Glist$"
                                     , "~/max-templates/default/icenter/club-list.aspx"
                                     )

                                 , new RouteTable(
                                     @"\G(?<cid>\d+)/"

                                     , new RouteTable(
                                         @"\Ginvite$"
                                         , "~/max-templates/default/icenter/club-invite.aspx?id=${cid}"
                                         )
                                     , new RouteTable(
                                         @"\Gmembers$"
                                         , "~/max-templates/default/icenter/club-members.aspx?id=${cid}"
                                         )
                                     , new RouteTable(
                                         @"\Gsetting$"
                                         , "~/max-templates/default/icenter/club-setting.aspx?id=${cid}"
                                         )
                                     )

                                 , new RouteTable(
                                     @"\G(?<cid>\d+)$"

                                     , "~/max-templates/default/club/home.aspx?cid=${cid}"
                                     )
                                 )

                #endregion

                #region SNS

                #region 空间

                , new RouteTable(@"^space/(?<uid>\d+)/"

                                 , new RouteTable(@"\Gblog/"

                                                  , new RouteTable(
                                                      @"\Garticle-(?<id>\d+)/(?<page>\d+)$"
                                                      , "~/max-templates/default/space/blog-view.aspx?uid=${uid}&id=${id}&page=${page}"
                                                      )
                                                  , new RouteTable(
                                                      @"\Garticle-(?<id>\d+)$"
                                                      , "~/max-templates/default/space/blog-view.aspx?uid=${uid}&id=${id}"
                                                      )
                                                  , new RouteTable(
                                                      @"\Gcategory-(?<cat>\d+)/(?<page>\d+)$"
                                                      , "~/max-templates/default/space/blog-list.aspx?uid=${uid}&cat=${cat}&page=${page}"
                                                      )
                                                  , new RouteTable(
                                                      @"\Gcategory-(?<cat>\d+)$"
                                                      , "~/max-templates/default/space/blog-list.aspx?uid=${uid}&cat=${cat}"
                                                      )
                                                  , new RouteTable(
                                                      @"\Gtag-(?<tag>\d+)$"
                                                      , "~/max-templates/default/space/blog-list.aspx?uid=${uid}&tag=${tag}"
                                                      )
                                                  , new RouteTable(
                                                      @"\G(?<page>\d+)$"
                                                      , "~/max-templates/default/space/blog-list.aspx?uid=${uid}&page=${page}"
                                                      )
                                                  )

                                 , new RouteTable(
                                     @"\Gblog$"
                                     , "~/max-templates/default/space/blog-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(
                                     @"\Gdoing$"
                                     , "~/max-templates/default/space/doing-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(
                                     @"\Galbum/album-(?<id>\d+)$"
                                     , "~/max-templates/default/space/album-view.aspx?uid=${uid}&id=${id}"
                                     )
                                 , new RouteTable(
                                     @"\Galbum/photo-(?<id>\d+)/(?<page>\d+)$"
                                     , "~/max-templates/default/space/album-photo.aspx?uid=${uid}&id=${id}&page=${page}"
                                     )
                                 , new RouteTable(
                                     @"\Galbum/photo-(?<id>\d+)$"
                                     , "~/max-templates/default/space/album-photo.aspx?uid=${uid}&id=${id}"
                                     )
                                 , new RouteTable(
                                     @"\Galbum$"
                                     , "~/max-templates/default/space/album-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(
                                     @"\Gshare/share-(?<id>\d+)$"
                                     , "~/max-templates/default/space/share-view.aspx?uid=${uid}&id=${id}"
                                     )
                                 , new RouteTable(
                                     @"\Gshare$"
                                     , "~/max-templates/default/space/share-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(
                                     @"\Gboard$"
                                     , "~/max-templates/default/space/board-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(
                                     @"\Gfriend$"
                                     , "~/max-templates/default/space/friend-list.aspx?uid=${uid}"
                                     )

                                 , new RouteTable(@"\G(?<path>.*)", "~/max-templates/default/space/${path}.aspx?uid=${uid}")
                                 )

                , new RouteTable(
                    @"^space/(?<uid>\d+)"
                    , "~/max-templates/default/space/space.aspx?uid=${uid}"
                    )

                #endregion

                #region 杂项

                , new RouteTable(
                    @"^logout/(?<uid>\d+)$"
                    , "~/max-templates/default/logout.aspx?uid=${uid}"
                    )

                , new RouteTable(
                    @"^register/(?<invite>[\w\-\{\}%]+)$"
                    , "~/max-templates/default/register.aspx?invite=${invite}"
                    )

                , new RouteTable(
                    @"^favorite$"
                    , "~/max-templates/default/icenter/share.aspx?type=private"
                    )

                , new RouteTable(
                    "^tag/"

                    , new RouteTable(
                        @"\Glist$"
                        , "~max-templates/default/tag-list.aspx"
                        )

                    , new RouteTable(
                        @"\G(?<id>\d+)/(?<type>\w+)$"
                        , "~max-templates/default/tag-view.aspx?tagid=${id}&type=${type}"
                        )
                    )

                , new RouteTable(
                    @"^vistor/(?<id>\d+)$"
                    , "~/max-templates/default/vistors-view.aspx?uid=${id}"
                    )

                , new RouteTable(
                    "^vistor$"
                    , "~/max-templates/default/vistors.aspx"
                    )

                #endregion

                #endregion

                #region 论坛


//            #region 公告

//, new RouteTable("^announcement/"

//                    , new RouteTable(
//                        @"\G(?<id>\d+)$"
//                        , "~/max-templates/default/announcements.aspx?id=${id}"
//                    )
//                )

//                , new RouteTable("^announcement$"
//                    , "~/max-templates/default/announcements.aspx"
//                )

//            #endregion

                , new RouteTable("^archiver/default$"
                                 , "~/archiver/default.aspx"
                                 )
                , new RouteTable("^archiver/"

                                 , new RouteTable(
                                     @"\G(?<codename>.+)/list-(?<page>[\{\}\d]+)$"
                                     , "~/archiver/showforum.aspx?codename=${codename}&page=${page}"
                                     )

                                 //, new RouteTable(
                                 //    @"\G(?<codename>.+)$"
                                 //    , "~/max-templates/default/forums/archiver_showforum.aspx?codename=${codename}"
                                 //)
                                 )

                , new RouteTable("^archiver/"

                                 , new RouteTable(
                                     @"\G(?<codename>.+)/thread-(?<tid>\d+)-(?<page>[\{\}\d]+)$"
                                     , "~/archiver/showthread.aspx?codename=${codename}&threadid=${tid}&page=${page}"
                                     )

                                 //, new RouteTable(
                                 //    @"\G(?<codename>.+)/thread-(?<tid>\d+)$"
                                 //    , "~/max-templates/default/forums/archiver_showthread.aspx?codename=${codename}&threadid=${tid}"
                                 //)
                                 )

                //, new RouteTable("^threadmanagelogs/"

                //    , new RouteTable(
                //        @"\G(?<codename>.+)/(?<stype>\d+)/(?<keyword>.+)/(?<page>[\{\}\d]+)$"
                //        , "~/max-templates/default/forums/threadmanagelogs.aspx?codename=${codename}&searchtype=${stype}&keyword=${keyword}&page=${page}"
                //    )

                //    , new RouteTable(
                //        @"\G(?<codename>.+)/(?<stype>\d+)/(?<keyword>.+)$"
                //        , "~/max-templates/default/forums/threadmanagelogs.aspx?codename=${codename}&searchtype=${stype}&keyword=${keyword}"
                //    )

                //)



                , new RouteTable(@"^new/(?<page>[\{\}\d]+)$"
                                 , "~/max-templates/default/forums/new.aspx?page=${page}"
                                 )

                , new RouteTable("^systemforum/"

                                 , new RouteTable(
                                     @"\G(?<type>.+)/code-(?<codename>.+)/(?<page>[\{\}\d]+)$"
                                     , "~/max-templates/default/forums/showsystemforum.aspx?type=${type}&codename=${codename}&page=${page}"
                                     )

                                 , new RouteTable(
                                     @"\G(?<type>.+)/code-(?<codename>.+)$"
                                     , "~/max-templates/default/forums/showsystemforum.aspx?type=${type}&codename=${codename}"
                                     )


                                 , new RouteTable(
                                     @"\G(?<type>.+)/(?<page>[\{\}\d]+)$"
                                     , "~/max-templates/default/forums/showsystemforum.aspx?type=${type}&page=${page}"
                                     )


                                 , new RouteTable(
                                     @"\G(?<type>.+)$"
                                     , "~/max-templates/default/forums/showsystemforum.aspx?type=${type}"
                                     )

                                 )


                , new RouteTable("^systemforum$"
                                 , "~/max-templates/default/forums/showsystemforum.aspx"
                                 )

                , new RouteTable("^moderatorcenter/"

                                 , new RouteTable(
                                     @"\Gcode-(?<codename>.*)/action-(?<action>.+)/tid-(?<tid>\d+)/pid-(?<pid>\d+)/pindex-(?<pindex>\d+)$"
                                     , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&threadid=${tid}&postid=${pid}&pageIndex=${pindex}"
                                     )

                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/tid-(?<tid>\d+)/pid-(?<pid>\d+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&threadid=${tid}&postid=${pid}"
                                 //)

                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/tid-(?<tid>\d+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&threadid=${tid}"
                                 //)

                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/stype-(?<stype>.+)/keyword-(?<keyword>.+)/(?<page>[\{\}\d]+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&searchtype=${stype}&keyword=${keyword}&page=${page}"
                                 //)

                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/stype-(?<stype>.+)/keyword-(?<keyword>.+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&searchtype=${stype}&keyword=${keyword}"
                                 //)


                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/type-(?<type>.+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&type=${type}"
                                 //)


                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)/(?<page>[\{\}\d]+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}&page=${page}"
                                 //)


                                 //, new RouteTable(
                                 //    @"\Gcode-(?<codename>.*)/action-(?<action>.+)$"
                                 //    , "~/max-templates/default/forums/moderatorcenter.aspx?codename=${codename}&action=${action}"
                                 //)

                                 //, new RouteTable(
                                 //    @"\Gpid-(?<pid>\d+)/action-rate$"
                                 //    , "~/max-dialogs/post-rate.aspx?postID=${pid}"
                                 //)

                                 //, new RouteTable(
                                 //    @"\Gpid-(?<pid>\d+)/action-cancelrate$"
                                 //    , "~/max-dialogs/post-cancelrate.aspx?postID=${pid}"
                                 //)

                                 , new RouteTable(
                                     @"\Gpid-(?<pid>\d+)/action-(?<action>.+)$"
                                     , "~/max-templates/default/forums/moderatorcenter.aspx?postID=${pid}&action=${action}"
                                     )

                                 )


                , new RouteTable(
                    @"^moderatorcenter$"
                    , "~/max-templates/default/forums/moderatorcenter.aspx"
                    )

                , new RouteTable(
                    @"^rankusers/(?<tid>\d+)$"
                    , "~/max-templates/default/forums/showrankusers.aspx?threadid=${tid}"
                    )

                , new RouteTable(
                    @"^threadlogs/(?<tid>\d+)$"
                    , "~/max-templates/default/forums/showthreadlogs.aspx?threadid=${tid}"
                    )

                , new RouteTable(
                    @"^attachmentexchanges/(?<attachid>\d+)/(?<pid>\d+)$"
                    , "~/max-templates/default/forums/attachmentexchanges.aspx?attachmentID=${attachid}&postID=${pid}"
                    )

                , new RouteTable(
                    @"^votedusers/(?<tid>\d+)$"
                    , "~/max-templates/default/forums/showvotedusers.aspx?threadid=${tid}"
                    )

                , new RouteTable(
                    @"^js$"
                    , "~/max-templates/default/forums/js.aspx"
                    )

                , new RouteTable(
                    @"^new$"
                    , "~/max-templates/default/forums/new.aspx"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/thread-(?<tid>\d+)-(?<page>[\{\}\d]+)-(?<listpage>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_thread.aspx?codename=${codename}&threadid=${tid}&page=${page}&listpage=${listpage}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/thread-(?<tid>\d+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_thread.aspx?codename=${codename}&threadid=${tid}&page=${page}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/question-(?<tid>\d+)-(?<page>[\{\}\d]+)-(?<listpage>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_question.aspx?codename=${codename}&threadid=${tid}&page=${page}&listpage=${listpage}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/question-(?<tid>\d+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_question.aspx?codename=${codename}&threadid=${tid}&page=${page}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/poll-(?<tid>\d+)-(?<page>[\{\}\d]+)-(?<listpage>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_poll.aspx?codename=${codename}&threadid=${tid}&page=${page}&listpage=${listpage}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/poll-(?<tid>\d+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_poll.aspx?codename=${codename}&threadid=${tid}&page=${page}"
                    )


                , new RouteTable(
                    @"^(?<codename>.+)/polemize-(?<tid>\d+)-(?<page>[\{\}\d]+)-(?<listpage>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_polemize.aspx?codename=${codename}&threadid=${tid}&page=${page}&listpage=${listpage}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/polemize-(?<tid>\d+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/view_polemize.aspx?codename=${codename}&threadid=${tid}&page=${page}"
                    )

//, new RouteTable("^search/"

//                    // , new RouteTable(
//                //    @"\G(?<fid>\d+)/(?<mode>\d+)/(?<page>[\{\}\d]+)/(?<keyword>.+)$"
//                //    , "~/max-templates/default/forums/search.aspx?fid=${fid}&mode=${mode}&page=${page}&searchtext=${keyword}"
//                //)

//                    // , new RouteTable(
//                //    @"\G(?<fid>\d+)/(?<mode>\d+)/(?<keyword>.+)$"
//                //    , "~/max-templates/default/forums/search.aspx?fid=${fid}&mode=${mode}&searchtext=${keyword}"
//                //)

//                     , new RouteTable(
//                        @"\G(?<fid>\d+)/(?<mode>\d+)$"
//                        , "~/max-templates/default/forums/search.aspx?fid=${fid}&mode=${mode}"
//                    )

//                    // , new RouteTable(
//                //    @"\G(?<mode>\d+)/(?<keyword>.+)$"
//                //    , "~/max-templates/default/forums/search.aspx?mode=${mode}&searchtext=${keyword}"
//                //)
//                )

//                , new RouteTable(
//                    @"^search$"
//                    , "~/max-templates/default/forums/search.aspx"
//                )


                // , new RouteTable(
                //    @"^rss$"
                //    , "~/rss.aspx"
                //)

                , new RouteTable(
                    @"^finalquestion/(?<fid>\d+)/(?<tid>\d+)$"
                    , "~/max-templates/default/forums/finalquestion.aspx?forumid=${fid}&threadid=${tid}"
                    )


                , new RouteTable(
                    @"^onlines/(?<type>.+)/(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/onlines.aspx?type=${type}&page=${page}"
                    )


                , new RouteTable("^onlines$"
                                 , "~/max-templates/default/forums/onlines.aspx"
                                 )

                , new RouteTable(
                    @"^(?<codename>.+)/catalog-(?<cid>\d+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/list.aspx?codename=${codename}&threadcatalogid=${cid}&page=${page}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/(?<action>[a-zA-Z]+)-(?<page>[\{\}\d]+)$"
                    , "~/max-templates/default/forums/list.aspx?codename=${codename}&action=${action}&page=${page}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/post$"
                    , "~/max-templates/default/forums/post.aspx?codename=${codename}"
                    )

                , new RouteTable(
                    @"^(?<codename>.+)/signinforum$"
                    , "~/max-templates/default/forums/signinforum.aspx?codename=${codename}"
                    )


                #region Post

                /*
                 *
                 * , new RouteTable("^post/"
                 *
                 *   , new RouteTable(
                 *      @"\G(?<codename>.+)/(?<action>.+)/(?<tid>\d+)/(?<pid>\d+)/type-(?<type>.+)$"
                 *      , "~/max-templates/default/forums/post.aspx?codename=${codename}&action=${action}&threadID=${tid}&postid=${pid}&type=${type}"
                 *  )
                 *
                 *  // , new RouteTable(
                 *  //    @"\G(?<codename>.+)/(?<action>.+)/(?<tid>\d+)/(?<pid>\d+)/pia-(?<pia>.+)$"
                 *  //    , "~/max-templates/default/forums/post.aspx?codename=${codename}&action=${action}&threadID=${tid}&postid=${pid}&posttndexalias=${pia}"
                 *  //)
                 *
                 *   , new RouteTable(
                 *      @"\G(?<codename>.+)/(?<action>.+)/(?<tid>\d+)/(?<pid>\d+)$"
                 *      , "~/max-templates/default/forums/post.aspx?codename=${codename}&action=${action}&threadID=${tid}&postid=${pid}"
                 *  )
                 *
                 *   , new RouteTable(
                 *      @"\G(?<codename>.+)/(?<action>.+)/(?<tid>\d+)$"
                 *      , "~/max-templates/default/forums/post.aspx?codename=${codename}&action=${action}&threadID=${tid}"
                 *  )
                 *
                 *   , new RouteTable(
                 *      @"\G(?<codename>.+)/(?<action>.+)$"
                 *      , "~/max-templates/default/forums/post.aspx?codename=${codename}&action=${action}"
                 *  )
                 * )
                 *
                 */

                #endregion

                #endregion

                , new RouteTable(@"^handler/(?<name>\w+)$", "~/handler.aspx?max_handler=${name}")

#if Publish
                , new RouteTable(@"^(?<path>max-js/.*)", "~/${path}.aspx")
#else
                , new RouteTable(@"^(?<path>max-(admin|dialogs|js)/.*)", "~/${path}.aspx")
                , new RouteTable(@"^(?<path>archiver/.*)", "~/${path}.aspx")
#endif
                //, new RouteTable(@"^(?<path>.*)", "~/max-templates/default/${path}.aspx")
                , new RouteTable(@"^(?<path>.*)", delegate(UrlScheme urlScheme) {
                if (TemplateManager.IsTemplateFile(string.Concat("~/max-templates/default/", urlScheme.Main, ".aspx")))
                {
                    return(string.Concat("~/max-templates/default/", urlScheme.Main, ".aspx", urlScheme.QueryString));
                }

                else
                {
                    return(string.Empty);
                }
            })
                );
        }
Exemplo n.º 22
0
 public void PrintRoutingTable()
 {
     Console.WriteLine($"Router: {OwnIP.ToString()} Route entries: {RouteTable.Count}");
     RouteTable.PrintItems();
 }
Exemplo n.º 23
0
 public ServerBase()
 {
     _routeGenerator = new RouteGenerator();
     _routeTable     = new RouteTable();
     _serverContext  = new ServerContext(GetType().Assembly, _routeTable);
 }
Exemplo n.º 24
0
        public virtual RouteTablesCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (routeTableName == null)
            {
                throw new ArgumentNullException(nameof(routeTableName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("RouteTablesOperations.StartCreateOrUpdate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, routeTableName, parameters, cancellationToken);
                return(new RouteTablesCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, routeTableName, parameters).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
Exemplo n.º 25
0
        public CreateRouteTableModelWorkItemImpl NewCreateRouteTableModelWorkItem(Package pkg, RouteTable routeTable)
        {
            CreateRouteTableModelWorkItemImpl workItem = new CreateRouteTableModelWorkItemImpl();

            workItem.Pkg        = pkg;
            workItem.RouteTable = routeTable;
            return(workItem);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Create or updates a route table in a specified resource group.
 /// </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='parameters'>
 /// Parameters supplied to the create or update route table operation.
 /// </param>
 public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters).GetAwaiter().GetResult());
 }
Exemplo n.º 27
0
        public static RouteTable InitializeRouteTable()
        {
            RouteTable routeTable = new RouteTable(websitePath);

            // Test parameterized URL
            routeTable.AddRoute("get", "param/{p1}/subpage/{p2}", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, parms) =>
                {
                    wrapper.SetPendingResponse("<p>p1 = " + parms["p1"] + "</p><p>p2 = " + parms["p2"] + "</p>");

                    return(WorkflowState.Continue);
                }
            });

            // Example usage where we re-use the expirable session and authorization checks.
            // routeTable.AddExpirableRoute("get", "somepath", myRouteHandler);
            // routeTable.AddExpirableAuthorizedRoute("get", "someotherpath", myRouteHandler);

            // Test session expired and authorization flags
            routeTable.AddRoute("get", "testsession", new RouteEntry()
            {
                SessionExpirationHandler = (continuation, wrapper, session, parms) =>
                {
                    if (session.Expired)
                    {
                        // Redirect instead of throwing an exception.
                        wrapper.Context.Redirect(@"ErrorPages\expiredSession");
                        return(WorkflowState.Abort);
                    }
                    else
                    {
                        return(WorkflowState.Continue);
                    }
                },
                AuthorizationHandler = (continuation, wrapper, session, parms) =>
                {
                    if (!session.Authorized)
                    {
                        // Redirect instead of throwing an exception.
                        wrapper.Context.Redirect(@"ErrorPages\notAuthorized");
                        return(WorkflowState.Abort);
                    }
                    else
                    {
                        return(WorkflowState.Continue);
                    }
                },
                RouteHandler = (continuation, wrapper, session, parms) =>
                {
                    wrapper.SetPendingResponse("<p>Looking good!</p>");

                    return(WorkflowState.Continue);
                }
            });

            // Set the session expired and authorization flags for testing purposes.
            routeTable.AddRoute("get", "SetState", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, pathParams) =>
                {
                    Dictionary <string, string> parms = wrapper.Context.GetUrlParameters();
                    session.Expired    = GetBooleanState(parms, "Expired", false);
                    session.Authorized = GetBooleanState(parms, "Authorized", false);
                    wrapper.SetPendingResponse(
                        "<p>Expired has been set to " + session.Expired + "</p>" +
                        "<p>Authorized has been set to " + session.Authorized + "</p>");

                    return(WorkflowState.Continue);
                }
            });

            // Test a form post
            routeTable.AddRoute("post", "login", "application/x-www-form-urlencoded", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, pathParams) =>
                {
                    string data = new StreamReader(wrapper.Context.Request.InputStream, wrapper.Context.Request.ContentEncoding).ReadToEnd();
                    wrapper.Context.Redirect("Welcome");

                    // As a redirect, we don't want any downstream processing.
                    return(WorkflowState.Done);
                }
            });

            // Test a form post with JSON content
            routeTable.AddRoute("post", "login", "application/json; charset=UTF-8", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, pathParams) =>
                {
                    string data = new StreamReader(wrapper.Context.Request.InputStream, wrapper.Context.Request.ContentEncoding).ReadToEnd();
                    wrapper.Context.RespondWith("Welcome!");

                    // As an AJAX response, we don't want any downstream processing.
                    return(WorkflowState.Done);
                }
            });

            routeTable.AddRoute("get", "loadtests", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, pathParams) =>
                {
                    long nanosecondsPerTick = (1000L * 1000L * 1000L) / System.Diagnostics.Stopwatch.Frequency;

                    if (Server.Samples == 0)
                    {
                        wrapper.SetPendingResponse("<p>No samples!</p>");
                    }
                    else
                    {
                        long avgTime          = Server.CumulativeTime * nanosecondsPerTick / Server.Samples;
                        string info           = String.Format("<p>{0} responses, avg. response time = {1}ns</p><p>Resetting sample info.</p>", Server.Samples, avgTime.ToString("N0"));
                        Server.CumulativeTime = 0;
                        Server.Samples        = 0;
                        wrapper.SetPendingResponse(info);
                    }

                    return(WorkflowState.Continue);
                }
            });

            routeTable.AddRoute("get", "sayhi", new RouteEntry()
            {
                RouteHandler = (continuation, wrapper, session, pathParams) =>
                {
                    wrapper.SetPendingResponse("<p>hello</p>");

                    return(WorkflowState.Continue);
                }
            });


            return(routeTable);
        }
Exemplo n.º 28
0
        private static void RouteFromLearningToAzure(RouterConfiguration routerConfig, IConfiguration config, RouteTable staticRouting)
        {
            routerConfig.AddInterface <LearningTransport>("LearningTransportA", t => { });
            var connectionStringB         = config.GetConnectionString("NServiceBus:AzureServiceBusA");
            var azureServiceBusBInterface = routerConfig.AddInterface <AzureServiceBusTransport>("AzureServiceBusA", t => { t.ConnectionString(connectionStringB); });

            staticRouting.AddForwardRoute("LearningTransportA", "AzureServiceBusA");
        }
Exemplo n.º 29
0
 private void RegisterRoutes(RouteTable routeTable, object routes)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 30
0
        public async Task RoutesApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("csmrg");

            string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/routeTables");

            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string     routeTableName = Recording.GenerateAssetName("azsmnet");
            string     route1Name     = Recording.GenerateAssetName("azsmnet");
            string     route2Name     = Recording.GenerateAssetName("azsmnet");
            RouteTable routeTable     = new RouteTable()
            {
                Location = location,
            };

            // Add a route
            Route route1 = new Route()
            {
                AddressPrefix    = "192.168.1.0/24",
                Name             = route1Name,
                NextHopIpAddress = "23.108.1.1",
                NextHopType      = RouteNextHopType.VirtualAppliance
            };

            routeTable.Routes.Add(route1);

            // Put RouteTable
            RouteTablesCreateOrUpdateOperation putRouteTableResponseOperation = await NetworkManagementClient.RouteTables.StartCreateOrUpdateAsync(resourceGroupName, routeTableName, routeTable);

            Response <RouteTable> putRouteTableResponse = await WaitForCompletionAsync(putRouteTableResponseOperation);

            Assert.AreEqual("Succeeded", putRouteTableResponse.Value.ProvisioningState.ToString());

            // Get RouteTable
            Response <RouteTable> getRouteTableResponse = await NetworkManagementClient.RouteTables.GetAsync(resourceGroupName, routeTableName);

            Assert.AreEqual(routeTableName, getRouteTableResponse.Value.Name);
            Assert.AreEqual(1, getRouteTableResponse.Value.Routes.Count);
            Assert.AreEqual(route1Name, getRouteTableResponse.Value.Routes[0].Name);
            Assert.AreEqual("192.168.1.0/24", getRouteTableResponse.Value.Routes[0].AddressPrefix);
            Assert.AreEqual("23.108.1.1", getRouteTableResponse.Value.Routes[0].NextHopIpAddress);
            Assert.AreEqual(RouteNextHopType.VirtualAppliance, getRouteTableResponse.Value.Routes[0].NextHopType);

            // Get Route
            Response <Route> getRouteResponse = await NetworkManagementClient.Routes.GetAsync(resourceGroupName, routeTableName, route1Name);

            Assert.AreEqual(routeTableName, getRouteTableResponse.Value.Name);
            Assert.AreEqual(1, getRouteTableResponse.Value.Routes.Count);
            Assert.AreEqual(getRouteResponse.Value.Name, getRouteTableResponse.Value.Routes[0].Name);
            Assert.AreEqual(getRouteResponse.Value.AddressPrefix, getRouteTableResponse.Value.Routes[0].AddressPrefix);
            Assert.AreEqual(getRouteResponse.Value.NextHopIpAddress, getRouteTableResponse.Value.Routes[0].NextHopIpAddress);
            Assert.AreEqual(getRouteResponse.Value.NextHopType, getRouteTableResponse.Value.Routes[0].NextHopType);

            // Add another route
            Route route2 = new Route()
            {
                AddressPrefix = "10.0.1.0/24",
                Name          = route2Name,
                NextHopType   = RouteNextHopType.VnetLocal
            };

            await NetworkManagementClient.Routes.StartCreateOrUpdateAsync(resourceGroupName, routeTableName, route2Name, route2);

            getRouteTableResponse = await NetworkManagementClient.RouteTables.GetAsync(resourceGroupName, routeTableName);

            Assert.AreEqual(routeTableName, getRouteTableResponse.Value.Name);
            Assert.AreEqual(2, getRouteTableResponse.Value.Routes.Count);
            Assert.AreEqual(route2Name, getRouteTableResponse.Value.Routes[1].Name);
            Assert.AreEqual("10.0.1.0/24", getRouteTableResponse.Value.Routes[1].AddressPrefix);
            Assert.True(string.IsNullOrEmpty(getRouteTableResponse.Value.Routes[1].NextHopIpAddress));
            Assert.AreEqual(RouteNextHopType.VnetLocal, getRouteTableResponse.Value.Routes[1].NextHopType);

            Response <Route> getRouteResponse2 = await NetworkManagementClient.Routes.GetAsync(resourceGroupName, routeTableName, route2Name);

            Assert.AreEqual(getRouteResponse2.Value.Name, getRouteTableResponse.Value.Routes[1].Name);
            Assert.AreEqual(getRouteResponse2.Value.AddressPrefix, getRouteTableResponse.Value.Routes[1].AddressPrefix);
            Assert.AreEqual(getRouteResponse2.Value.NextHopIpAddress, getRouteTableResponse.Value.Routes[1].NextHopIpAddress);
            Assert.AreEqual(getRouteResponse2.Value.NextHopType, getRouteTableResponse.Value.Routes[1].NextHopType);

            // list route
            AsyncPageable <Route> listRouteResponseAP = NetworkManagementClient.Routes.ListAsync(resourceGroupName, routeTableName);
            List <Route>          listRouteResponse   = await listRouteResponseAP.ToEnumerableAsync();

            Assert.AreEqual(2, listRouteResponse.Count());
            Assert.AreEqual(getRouteResponse.Value.Name, listRouteResponse.First().Name);
            Assert.AreEqual(getRouteResponse.Value.AddressPrefix, listRouteResponse.First().AddressPrefix);
            Assert.AreEqual(getRouteResponse.Value.NextHopIpAddress, listRouteResponse.First().NextHopIpAddress);
            Assert.AreEqual(getRouteResponse.Value.NextHopType, listRouteResponse.First().NextHopType);
            Assert.AreEqual(getRouteResponse2.Value.Name, listRouteResponse.ElementAt(1).Name);
            Assert.AreEqual(getRouteResponse2.Value.AddressPrefix, listRouteResponse.ElementAt(1).AddressPrefix);
            Assert.AreEqual(getRouteResponse2.Value.NextHopIpAddress, listRouteResponse.ElementAt(1).NextHopIpAddress);
            Assert.AreEqual(getRouteResponse2.Value.NextHopType, listRouteResponse.ElementAt(1).NextHopType);

            // Delete a route
            await NetworkManagementClient.Routes.StartDeleteAsync(resourceGroupName, routeTableName, route1Name);

            listRouteResponseAP = NetworkManagementClient.Routes.ListAsync(resourceGroupName, routeTableName);
            listRouteResponse   = await listRouteResponseAP.ToEnumerableAsync();

            Has.One.EqualTo(listRouteResponse);
            Assert.AreEqual(getRouteResponse2.Value.Name, listRouteResponse.First().Name);
            Assert.AreEqual(getRouteResponse2.Value.AddressPrefix, listRouteResponse.First().AddressPrefix);
            Assert.AreEqual(getRouteResponse2.Value.NextHopIpAddress, listRouteResponse.First().NextHopIpAddress);
            Assert.AreEqual(getRouteResponse2.Value.NextHopType, listRouteResponse.First().NextHopType);

            // Delete route
            await NetworkManagementClient.Routes.StartDeleteAsync(resourceGroupName, routeTableName, route2Name);

            listRouteResponseAP = NetworkManagementClient.Routes.ListAsync(resourceGroupName, routeTableName);
            listRouteResponse   = await listRouteResponseAP.ToEnumerableAsync();

            Assert.IsEmpty(listRouteResponse);

            // Delete RouteTable
            await NetworkManagementClient.RouteTables.StartDeleteAsync(resourceGroupName, routeTableName);

            // Verify delete
            AsyncPageable <RouteTable> listRouteTableResponseAP = NetworkManagementClient.RouteTables.ListAsync(resourceGroupName);
            List <RouteTable>          listRouteTableResponse   = await listRouteTableResponseAP.ToEnumerableAsync();

            Assert.IsEmpty(listRouteTableResponse);
        }
        private Template GetSqlExpressDbTemplate()
        {
            var template = new Template("corp.getthebuybox.com", "vpcBasicDbInstanceTest", "StackBasicDbInstanceTest", "10.0.0.0/16");

            var vpc = template.Vpcs.First();

            vpc.EnableDnsHostnames = true;
            vpc.EnableDnsSupport   = true;

            var subnet1 = new Subnet(vpc, "10.0.128.0/28", AvailabilityZone.UsEast1A, true);

            template.Resources.Add("subnetDb1", subnet1);
            RouteTable routeTable4Subnet1 = new RouteTable(vpc);

            template.Resources.Add("routeTable4Subnet1", routeTable4Subnet1);

            Route route4subnet1 = new Route(vpc.InternetGateway, "0.0.0.0/0", routeTable4Subnet1);

            template.Resources.Add("route4subnet1", route4subnet1);

            SubnetRouteTableAssociation subnetRouteTableAssociationSubnet1 = new SubnetRouteTableAssociation(subnet1, routeTable4Subnet1);

            template.Resources.Add(subnetRouteTableAssociationSubnet1.LogicalId, subnetRouteTableAssociationSubnet1);


            var subnet2 = new Subnet(template.Vpcs.First(), "10.0.64.0/28", AvailabilityZone.UsEast1E, true);

            template.Resources.Add("subnetDb2", subnet2);

            RouteTable routeTable4Subnet2 = new RouteTable(vpc);

            template.Resources.Add("routeTable4Subnet2", routeTable4Subnet2);

            Route route4subnet2 = new Route(vpc.InternetGateway, "0.0.0.0/0", routeTable4Subnet2);

            template.Resources.Add("route4subnet2", route4subnet2);


            SubnetRouteTableAssociation subnetRouteTableAssociationSubnet2 = new SubnetRouteTableAssociation(subnet2, routeTable4Subnet2);

            template.Resources.Add(subnetRouteTableAssociationSubnet2.LogicalId, subnetRouteTableAssociationSubnet2);


            var subnetGroup = new DbSubnetGroup("this is my subnet group description");

            template.Resources.Add("dbSubnetGroup", subnetGroup);
            subnetGroup.AddSubnet(subnet1);
            subnetGroup.AddSubnet(subnet2);

            SecurityGroup securityGroup = new SecurityGroup("Allows access to SqlServer from everywhere", vpc);

            template.Resources.Add("securityGroupWorldWide", securityGroup);

            securityGroup.AddIngress(PredefinedCidr.TheWorld, Protocol.Tcp, Ports.MsSqlServer);

            var dbSecurityGroup = new DbSecurityGroup(vpc, "Why is a description required?");

            template.Resources.Add("dbSecurityGroup", dbSecurityGroup);
            var dbSecurityGroupIngress = new DbSecurityGroupIngress();

            dbSecurityGroupIngress.CIDRIP = "0.0.0.0/0";
            dbSecurityGroup.AddDbSecurityGroupIngress(dbSecurityGroupIngress);

            DbInstance instance = new DbInstance(DbInstanceClassEnum.DbT2Micro,
                                                 EngineType.SqlServerExpress,
                                                 LicenseModelType.LicenseIncluded,
                                                 Ebs.VolumeTypes.GeneralPurpose,
                                                 20,
                                                 "MyMasterUsername",
                                                 "YellowBeard123",
                                                 subnetGroup,
                                                 dbSecurityGroup);

            template.Resources.Add("instanceBasicDbInstanceTest", instance);



            instance.PubliclyAccessible = true.ToString().ToLowerInvariant();
            return(template);
        }
Exemplo n.º 32
0
 public HostController(RouteTable routeTable, IAuthProvider authProvider, RouteTableStorage routeTableStorage)
 {
     RouteTable        = routeTable;
     AuthProvider      = authProvider;
     RouteTableStorage = routeTableStorage;
 }
Exemplo n.º 33
0
        public void SubnetRouteTableTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/routeTables");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(
                    resourceGroupName,
                    new ResourceGroup {
                    Location = location
                });

                string routeTableName = TestUtilities.GenerateName();
                string route1Name     = TestUtilities.GenerateName();

                var routeTable = new RouteTable()
                {
                    Location = location,
                };
                routeTable.Routes = new List <Route>();

                var route1 = new Route()
                {
                    AddressPrefix    = "192.168.1.0/24",
                    Name             = route1Name,
                    NextHopIpAddress = "23.108.1.1",
                    NextHopType      = RouteNextHopType.VirtualAppliance
                };

                routeTable.Routes.Add(route1);

                // Put RouteTable
                var putRouteTableResponse =
                    networkManagementClient.RouteTables.CreateOrUpdate(
                        resourceGroupName,
                        routeTableName,
                        routeTable);

                Assert.Equal("Succeeded", putRouteTableResponse.ProvisioningState);

                // Get RouteTable
                var getRouteTableResponse = networkManagementClient.RouteTables.Get(
                    resourceGroupName,
                    routeTableName);

                // Verify that the subnet reference is null
                Assert.Null(getRouteTableResponse.Subnets);

                // Create Vnet with subnet and add a route table
                string vnetName   = TestUtilities.GenerateName();
                string subnetName = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnetName,
                            AddressPrefix = "10.0.0.0/24",
                            RouteTable    = new RouteTable()
                            {
                                Id = getRouteTableResponse.Id,
                            }
                        }
                    }
                };

                var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

                var getSubnetResponse = networkManagementClient.Subnets.Get(resourceGroupName, vnetName, subnetName);
                Assert.Equal(getSubnetResponse.RouteTable.Id, getRouteTableResponse.Id);

                // Get RouteTable
                getRouteTableResponse = networkManagementClient.RouteTables.Get(
                    resourceGroupName,
                    routeTableName);
                Assert.Equal(1, getRouteTableResponse.Subnets.Count);
                Assert.Equal(getSubnetResponse.Id, getRouteTableResponse.Subnets[0].Id);
            }
        }
 /// <summary>
 /// The Put RouteTable operation creates/updates a route tablein the
 /// specified resource group.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Network.IRouteTableOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='routeTableName'>
 /// Required. The name of the route table.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the create/update Route Table
 /// operation
 /// </param>
 /// <returns>
 /// Response for PUT RouteTables Api servive call
 /// </returns>
 public static Task <RouteTablePutResponse> BeginCreateOrUpdatingAsync(this IRouteTableOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
 {
     return(operations.BeginCreateOrUpdatingAsync(resourceGroupName, routeTableName, parameters, CancellationToken.None));
 }
Exemplo n.º 35
0
        public void EmptyRouteTableTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/routeTables");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(
                    resourceGroupName,
                    new ResourceGroup {
                    Location = location
                });

                string routeTableName = TestUtilities.GenerateName();

                var routeTable = new RouteTable()
                {
                    Location = location,
                };

                // Put RouteTable
                var putRouteTableResponse =
                    networkManagementClient.RouteTables.CreateOrUpdate(
                        resourceGroupName,
                        routeTableName,
                        routeTable);

                Assert.Equal("Succeeded", putRouteTableResponse.ProvisioningState);

                // Get RouteTable
                var getRouteTableResponse = networkManagementClient.RouteTables.Get(
                    resourceGroupName,
                    routeTableName);

                Assert.Equal(routeTableName, getRouteTableResponse.Name);
                Assert.False(getRouteTableResponse.Routes.Any());

                // List RouteTable
                var listRouteTableResponse = networkManagementClient.RouteTables.List(resourceGroupName);

                Assert.Single(listRouteTableResponse);
                Assert.Equal(getRouteTableResponse.Name, listRouteTableResponse.First().Name);
                Assert.Equal(getRouteTableResponse.Id, listRouteTableResponse.First().Id);

                // Delete RouteTable
                networkManagementClient.RouteTables.Delete(resourceGroupName, routeTableName);

                // Verify delete
                listRouteTableResponse = networkManagementClient.RouteTables.List(resourceGroupName);

                Assert.Empty(listRouteTableResponse);
            }
        }
Exemplo n.º 36
0
        public static VirtualNetwork CreateVirtualNetwork(SqlManagementTestContext context, ResourceGroup resourceGroup, string location)
        {
            NetworkManagementClient networkClient = context.GetClient <NetworkManagementClient>();

            // Create vnet andinitialize subnets
            string vnetName = SqlManagementTestUtilities.GenerateName();

            // Create network security group
            NetworkSecurityGroup networkSecurityGroupParams = new NetworkSecurityGroup()
            {
                Location      = TestEnvironmentUtilities.DefaultLocationId,
                SecurityRules = new List <SecurityRule>()
                {
                    new SecurityRule()
                    {
                        Direction = "Inbound",
                        Name      = "allow_management_inbound",
                        DestinationAddressPrefix = "*",
                        DestinationPortRanges    = new List <string>()
                        {
                            "1433", "1434", "5022", "9000", "9003", "1438", "1440", "1452", "80", "443"
                        },
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Protocol            = "Tcp",
                        Access   = "Allow",
                        Priority = 100
                    },
                    new SecurityRule()
                    {
                        Direction                = "Inbound",
                        Name                     = "allow_misubnet_inbound",
                        DestinationPortRange     = "*",
                        DestinationAddressPrefix = "*",
                        SourceAddressPrefix      = "10.0.0.0/26",
                        SourcePortRange          = "*",
                        Protocol                 = "*",
                        Access                   = "Allow",
                        Priority                 = 200
                    },
                    new SecurityRule()
                    {
                        Direction = "Inbound",
                        Name      = "allow_health_probe",
                        DestinationAddressPrefix = "*",
                        DestinationPortRange     = "*",
                        SourceAddressPrefix      = "AzureLoadBalancer",
                        SourcePortRange          = "*",
                        Protocol = "*",
                        Access   = "Allow",
                        Priority = 300
                    },
                    new SecurityRule()
                    {
                        Direction = "Outbound",
                        Name      = "allow_management_outbound",
                        DestinationAddressPrefix = "*",
                        DestinationPortRanges    = new List <string>()
                        {
                            "80", "443", "12000"
                        },
                        Protocol            = "*",
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Access   = "Allow",
                        Priority = 100
                    },
                    new SecurityRule()
                    {
                        Direction = "Outbound",
                        Name      = "allow_misubnet_outbound",
                        DestinationAddressPrefix = "10.0.0.0/26",
                        DestinationPortRange     = "*",
                        Protocol            = "*",
                        SourceAddressPrefix = "*",
                        SourcePortRange     = "*",
                        Access   = "Allow",
                        Priority = 200
                    }
                }
            };
            string networkSecurityGroupName = SqlManagementTestUtilities.GenerateName();

            networkClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroup.Name, networkSecurityGroupName, networkSecurityGroupParams);
            NetworkSecurityGroup securityGroup = networkClient.NetworkSecurityGroups.Get(resourceGroup.Name, networkSecurityGroupName);

            // Create route table
            RouteTable routeTableParams = new RouteTable()
            {
                Location = TestEnvironmentUtilities.DefaultLocationId,
                Routes   = new List <Route>()
                {
                    new Route()
                    {
                        Name          = SqlManagementTestUtilities.GenerateName(),
                        AddressPrefix = "0.0.0.0/0",
                        NextHopType   = "Internet"
                    },
                    new Route()
                    {
                        Name          = SqlManagementTestUtilities.GenerateName(),
                        AddressPrefix = "10.0.0.0/26",
                        NextHopType   = "VnetLocal"
                    }
                }
            };
            string routeTableName = SqlManagementTestUtilities.GenerateName();

            networkClient.RouteTables.CreateOrUpdate(resourceGroup.Name, routeTableName, routeTableParams);
            RouteTable routeTable = networkClient.RouteTables.Get(resourceGroup.Name, routeTableName);

            // Create subnet
            List <Subnet> subnetList = new List <Subnet>();
            Subnet        subnet     = new Subnet()
            {
                Name                 = "MISubnet",
                AddressPrefix        = "10.0.0.0/26",
                NetworkSecurityGroup = securityGroup,
                RouteTable           = routeTable
            };

            subnetList.Add(subnet);

            // Create vnet
            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/22",
                    }
                },
                Subnets = subnetList
            };

            // Put Vnet
            var putVnetResponse = networkClient.VirtualNetworks.CreateOrUpdate(resourceGroup.Name, vnetName, vnet);

            Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

            // Get Vnets
            var getVnetResponse = networkClient.VirtualNetworks.Get(resourceGroup.Name, vnetName);

            return(getVnetResponse);
        }
        public async Task DeleteData(String[][] primaryKeys, String email)
        {
            List <DatabaseChange> databaseChanges = new List <DatabaseChange>();
            String changeType = "DELETE";
            String changeData = "";

            for (var i = 0; i < primaryKeys.Length; i++)
            {
                for (var j = 1; j < primaryKeys[i].Length; j++)
                {
                    switch (primaryKeys[i][0])
                    {
                    case "stops":
                        Stop foundStop = await _db.Stops.FindAsync(Int32.Parse(primaryKeys[i][j]));

                        if (foundStop == null)
                        {
                            break;
                        }

                        changeData = "Stop: " + foundStop.Name;
                        _db.Stops.Remove(foundStop);
                        break;

                    case "routes":
                        // Route.Label is a foreign key in several tables, and each connection need be set to null
                        // However, a table in a database may have a "on delete set null" setting
                        Models.Route foundRoute = await _db.Routes.FindAsync(primaryKeys[i][j]);

                        if (foundRoute == null)
                        {
                            break;
                        }

                        changeData = "Route: " + foundRoute.Label;

                        foreach (var stop in _db.Stops)
                        {
                            if (stop.Route.Equals(foundRoute))
                            {
                                stop.Route = null;
                            }
                        }

                        foreach (var routeTable in _db.RouteTables)
                        {
                            if (routeTable.Route.Equals(foundRoute))
                            {
                                routeTable.Route = null;
                            }
                        }

                        foreach (var tick in _db.Tickets)
                        {
                            if (tick.Route.Equals(foundRoute))
                            {
                                tick.Route = null;
                            }
                        }

                        _db.Routes.Remove(foundRoute);
                        break;

                    case "route-tables":
                        RouteTable foundRouteTable = await _db.RouteTables.FindAsync(Int32.Parse(primaryKeys[i][j]));

                        if (foundRouteTable == null)
                        {
                            break;
                        }

                        changeData = "RouteTable: " + foundRouteTable.Id + " " + foundRouteTable.StartTime;
                        _db.RouteTables.Remove(foundRouteTable);
                        break;

                    case "tickets":     // Disallow remove
                        break;

                    case "ticket-types":
                        TicketType foundTicketType = await _db.TicketTypes.FindAsync(primaryKeys[i][j]);

                        if (foundTicketType == null)
                        {
                            break;
                        }

                        changeData = "TicketType: " + foundTicketType.Label;
                        _db.TicketTypes.Remove(foundTicketType);
                        break;

                    case "ticket-type-compositions":     // Disallow remove
                        break;

                    case "users":
                        // Skip first element as it is a default admin user
                        User foundUser = await _db.Users.FindAsync(Int32.Parse(primaryKeys[i][j]));

                        if (foundUser == null)
                        {
                            break;
                        }

                        if (foundUser.Id != 1)
                        {
                            _db.Users.Remove(foundUser);
                            changeData = "User: "******"INVALID ACTION";
                            changeData = "Tried to delete main admin account";
                        }

                        break;

                    default:
                        throw new Exception();
                    }

                    databaseChanges.Add(new DatabaseChange {
                        Type = changeType, Change = changeData
                    });
                }
            }
            await _db.SaveChangesAsync();

            await LogDatabaseAccess(email, changeType, databaseChanges);
        }