/// <summary> /// <para> /// Creates a snapshot of the current state of the <see cref="RouteData"/> before appending /// <paramref name="router"/> to <see cref="Routers"/>, merging <paramref name="values"/> into /// <see cref="Values"/>, and merging <paramref name="dataTokens"/> into <see cref="DataTokens"/>. /// </para> /// <para> /// Call <see cref="RouteDataSnapshot.Restore"/> to restore the state of this <see cref="RouteData"/> /// to the state at the time of calling /// <see cref="PushState(IRouter, RouteValueDictionary, RouteValueDictionary)"/>. /// </para> /// </summary> /// <param name="router"> /// An <see cref="IRouter"/> to append to <see cref="Routers"/>. If <c>null</c>, then <see cref="Routers"/> /// will not be changed. /// </param> /// <param name="values"> /// A <see cref="RouteValueDictionary"/> to merge into <see cref="Values"/>. If <c>null</c>, then /// <see cref="Values"/> will not be changed. /// </param> /// <param name="dataTokens"> /// A <see cref="RouteValueDictionary"/> to merge into <see cref="DataTokens"/>. If <c>null</c>, then /// <see cref="DataTokens"/> will not be changed. /// </param> /// <returns>A <see cref="RouteDataSnapshot"/> that captures the current state.</returns> public RouteDataSnapshot PushState(IRouter router, RouteValueDictionary values, RouteValueDictionary dataTokens) { var snapshot = new RouteDataSnapshot( this, _dataTokens?.Count > 0 ? new RouteValueDictionary(_dataTokens) : null, _routers?.Count > 0 ? new List <IRouter>(_routers) : null, _values?.Count > 0 ? new RouteValueDictionary(_values) : null); if (router != null) { Routers.Add(router); } if (values != null) { foreach (var kvp in values) { if (kvp.Value != null) { Values[kvp.Key] = kvp.Value; } } } if (dataTokens != null) { foreach (var kvp in dataTokens) { DataTokens[kvp.Key] = kvp.Value; } } return(snapshot); }
public void Register(Func <object, IScope, RouteKey> retriever) { Routers.Add(new Router(retriever) { Key = "agg" + kid++ }); }
public void Register(IRouter router) { if (string.IsNullOrWhiteSpace(router.Key)) { router.Key = "agg" + kid++; } Routers.Add(router); }
/// <summary> /// 映射 解决与指定谓词所定义的条件相匹配的类型 到特定类型 【TResult】 的转换。 /// </summary> /// <typeparam name="TResult">目标类型。</typeparam> /// <param name="router">映射路由。</param> public void Map <TResult>(MapRouter <TResult> router) { if (router is null) { throw new ArgumentNullException(nameof(router)); } Routers.Add(router); }
/// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class from the given, possibly encrypted /// bytes. /// </summary> /// <param name="bytes">The bytes to read the settings from.</param> public ConfigFile(byte[] bytes) { // Detect if the bytes represent encrypted content. bool isEncrypted = false; foreach (byte b in bytes) { // Any byte with a value under 32 which is not a line break is not valid in. // decrypted files. if (b < 32 && b != '\r' && b != '\n') { isEncrypted = true; break; } } // Get the decrypted content. string text; if (isEncrypted) { text = Decrypt(bytes); } else { text = Encoding.ASCII.GetString(bytes); } string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Detect if the configuration has user settings. int numberInLine3 = Int32.Parse(lines[2]); bool hasUserConfiguration = numberInLine3 < 17; // Parse the possibly existing user configuration. int line = 0; if (hasUserConfiguration) { Username = lines[0]; Password = lines[1]; Routers = new List <Router>(numberInLine3); RouterName = lines[3]; line = 4; } else { Routers = new List <Router>(); } // Parse the router list. for (int i = line; i < lines.Length; i += 3) { string name = lines[i]; IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(lines[i + 1]), Int16.Parse(lines[i + 2])); Routers.Add(new Router(name, ipEndPoint)); } }
static void Initialize() { Computer c1 = new Computer { Id = 1, Model = "PC", Manufactured = DateTime.Now, HardwareAddress = "90-1F-12-22-33-55", LogicAddress = 2, }; Computer c2 = new Computer { Id = 2, Model = "PC2", Manufactured = DateTime.Now.AddDays(-1), HardwareAddress = "90-1F-12-22-33-54", LogicAddress = 22 }; Router r1 = new Router { Id = 1, Model = "R1", Manufactured = DateTime.Now, HardwareAddress = "90-1F-12-22-33-53", LogicAddress = 33, Mask = 4294967040, Computers = new List <Computer> { c1, c2 } }; Room rm1 = new Room { Id = 1, Number = 521, Routers = new List <Router> { r1 }, Computers = new List <Computer> { c1, c2 } }; Building b1 = new Building { Id = 1, Name = "MyBuilding", Rooms = new List <Room> { rm1 } }; c1.Router = r1; c1.RouterId = r1.Id; c1.Room = rm1; c1.RoomId = rm1.Id; c2.Router = r1; c2.RouterId = r1.Id; c2.Room = rm1; c2.RoomId = rm1.Id; r1.Room = rm1; r1.RoomId = rm1.Id; rm1.Building = b1; rm1.BuildingId = b1.Id; Computers.Add(c1); Computers.Add(c2); Routers.Add(r1); Rooms.Add(rm1); Buildings.Add(b1); }
public RouteDataSnapshot PushState(IRouter?router, RouteValueDictionary?values, RouteValueDictionary?dataTokens) { // Perf: this is optimized for small list sizes, in particular to avoid overhead of a native call in // Array.CopyTo inside the List(IEnumerable<T>) constructor. List <IRouter>?routers = null; var count = _routers?.Count; if (count > 0) { Debug.Assert(_routers != null); routers = new List <IRouter>(count.Value); for (var i = 0; i < count.Value; i++) { routers.Add(_routers[i]); } } var snapshot = new RouteDataSnapshot( this, _dataTokens?.Count > 0 ? new RouteValueDictionary(_dataTokens) : null, routers, _values?.Count > 0 ? new RouteValueDictionary(_values) : null); if (router != null) { Routers.Add(router); } if (values != null) { foreach (var kvp in values) { if (kvp.Value != null) { Values[kvp.Key] = kvp.Value; } } } if (dataTokens != null) { foreach (var kvp in dataTokens) { DataTokens[kvp.Key] = kvp.Value; } } return(snapshot); }
public void OnListenerAdding(string eventType, Delegate listenerBeingAdded) { #if LOG_ALL_MESSAGES || LOG_ADD_LISTENER Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" + listenerBeingAdded.Target + " -> " + listenerBeingAdded.Method + "}"); #endif if (!Routers.ContainsKey(eventType)) { Routers.Add(eventType, null); } Delegate d = Routers[eventType]; if (d != null && d.GetType() != listenerBeingAdded.GetType()) { throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name)); } }
private void AddTestRoutes() { Routers routers = new Routers(); //------------------------------------------------------------------------------------------------------------------ { Route route = new Route() { Name = "NetworkDLS", ListenPort = 80, TrafficType = TrafficType.Http, MaxBufferSize = 1021 * 1024, ListenOnAllAddresses = false, AutoStart = true, Description = "Default example route." }; route.Bindings.Add(new Binding { Enabled = true, Address = "127.0.0.1" }); route.Endpoints.ConnectionPattern = ConnectionPattern.FailOver; route.Endpoints.Add(new Endpoint("www.NetworkDLS.com", 80)); route.HttpHeaderRules.Add(new HttpHeaderRule(HttpHeaderType.Request, HttpVerb.Any, "Host", HttpHeaderAction.Upsert, "www.NetworkDLS.com")); routers.Add(new Router(route)); } //------------------------------------------------------------------------------------------------------------------ { Route route = new Route() { Name = "Ingenuity", ListenPort = 81, TrafficType = TrafficType.Http, MaxBufferSize = 1021 * 1024, ListenOnAllAddresses = true, AutoStart = true }; //route.Bindings.Add(new Binding { Enabled = true, Address = "127.0.0.1" }); route.Endpoints.ConnectionPattern = ConnectionPattern.FailOver; route.Endpoints.Add(new Endpoint("www.IngenuitySC.com", 80)); route.HttpHeaderRules.Add(new HttpHeaderRule(HttpHeaderType.Request, HttpVerb.Any, "Host", HttpHeaderAction.Upsert, "www.IngenuitySC.com")); routers.Add(new Router(route)); } //------------------------------------------------------------------------------------------------------------------ { Route route = new Route() { Name = "Microsoft LIVE!", ListenPort = 82, TrafficType = TrafficType.Https, MaxBufferSize = 1021 * 1024, ListenOnAllAddresses = true, AutoStart = true }; //route.Bindings.Add(new Binding { Enabled = true, Address = "127.0.0.1" }); route.Endpoints.ConnectionPattern = ConnectionPattern.FailOver; route.Endpoints.Add(new Endpoint("login.live.com", 443)); route.HttpHeaderRules.Add(new HttpHeaderRule(HttpHeaderType.Request, HttpVerb.Any, "Host", HttpHeaderAction.Upsert, "login.live.com")); routers.Add(new Router(route)); } //------------------------------------------------------------------------------------------------------------------ string routesText = JsonConvert.SerializeObject(routers.Routes()); string configPath = RegistryHelper.GetString(Registry.LocalMachine, Constants.RegsitryKey, "", "ConfigPath"); File.WriteAllText(Path.Combine(configPath, Constants.RoutesConfigFileName), routesText); }
private void Packeteer_OnMessageReceived(Packeteer sender, NetProxy.Hub.Common.Peer peer, NetProxy.Hub.Common.Packet packet) { //Console.WriteLine("{0}:{1}", packet.Label, packet.Payload); if (_loggedInPeers.Contains(peer.Id) == false) { if (packet.Label == Constants.CommandLables.GuiRequestLogin) { try { lock (_config) { var userLogin = JsonConvert.DeserializeObject <UserLogin>(packet.Payload); var singleUser = (from o in _config.Users.List where o.UserName.ToLower() == userLogin.UserName.ToLower() && o.PasswordHash.ToLower() == userLogin.PasswordHash.ToLower() select o).FirstOrDefault(); if (singleUser != null) { _loggedInPeers.Add(peer.Id); Console.WriteLine("Logged in session: {0}, User: {1} (Logged in users {2}).", peer.Id, userLogin.UserName.ToLower(), _loggedInPeers.Count()); } else { Console.WriteLine("Failed Login session: {0}, User: {1} (Logged in users {2}).", peer.Id, userLogin.UserName.ToLower(), _loggedInPeers.Count()); } _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(new GenericBooleanResult() { Value = singleUser != null })); } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "An error occured while logging in.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } return; //If the peer is not logged in, don't go any further. } if (packet.Label == Constants.CommandLables.GuiRequestRouteList) { try { List <RouteGridItem> routes = new List <RouteGridItem>(); lock (_config) { foreach (var router in _routers.List) { RouteGridItem augmentedRoute = new RouteGridItem() { Id = router.Route.Id, Name = router.Route.Name, TrafficType = router.Route.TrafficType, RouterType = router.Route.TrafficType.ToString() + " / " + router.Route.BindingProtocal.ToString(), BindingProtocal = router.Route.BindingProtocal, Description = router.Route.Description, IsRunning = router.IsRunning, ListenPort = router.Route.ListenPort, ListenOnAllAddresses = router.Route.ListenOnAllAddresses, Bindings = router.Route.Bindings }; routes.Add(augmentedRoute); } } _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(routes)); } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get route list.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiRequestRouteStatsList) { try { List <RouteGridStats> stats = new List <RouteGridStats>(); lock (_config) { foreach (var router in _routers.List) { RouteGridStats augmentedRoute = new RouteGridStats() { Id = router.Route.Id, IsRunning = router.IsRunning, BytesReceived = router.Stats.BytesReceived, BytesSent = router.Stats.BytesSent, TotalConnections = router.Stats.TotalConnections, CurrentConnections = router.CurrentConnectionCount }; stats.Add(augmentedRoute); } } _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(stats)); } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get route stats list.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiRequestRoute) { try { lock (_config) { Guid routerId = Guid.Parse(packet.Payload); Router router = _routers[routerId]; if (router != null) { string value = JsonConvert.SerializeObject(router.Route); _packeteer.SendTo(peer.Id, packet.Label, value); } } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get route.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiRequestUserList) { try { lock (_config) { string value = JsonConvert.SerializeObject(_config.Users); _packeteer.SendTo(peer.Id, packet.Label, value); } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get user list.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiPersistUserList) { try { var value = JsonConvert.DeserializeObject <Users>(packet.Payload); lock (_config) { _config.Users.List.Clear(); foreach (var user in value.List) { _config.Users.Add(user); } SaveConfiguration(); } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to save user list.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiPersistUpsertRoute) { try { var value = JsonConvert.DeserializeObject <Route>(packet.Payload); lock (_config) { var existingRoute = (from o in _routers.List where o.Route.Id == value.Id select o).FirstOrDefault(); if (existingRoute != null) { existingRoute.Stop(); _routers.List.Remove(existingRoute); } var newRouter = new Router(value); _routers.Add(newRouter); SaveConfiguration(); if (newRouter.Route.AutoStart) { newRouter.Start(); } } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to upsert route.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiPersistDeleteRoute) { try { Guid routeId = Guid.Parse(packet.Payload); lock (_config) { var existingRoute = (from o in _routers.List where o.Route.Id == routeId select o).FirstOrDefault(); if (existingRoute != null) { existingRoute.Stop(); _routers.List.Remove(existingRoute); } SaveConfiguration(); } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get delete route.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiPersistStopRoute) { try { Guid routeId = Guid.Parse(packet.Payload); lock (_config) { var existingRoute = (from o in _routers.List where o.Route.Id == routeId select o).FirstOrDefault(); if (existingRoute != null) { existingRoute.Stop(); } } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to get stop route.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to stop route: " + ex.Message); } } else if (packet.Label == Constants.CommandLables.GuiPersistStartRoute) { try { Guid routeId = Guid.Parse(packet.Payload); lock (_config) { var existingRoute = (from o in _routers.List where o.Route.Id == routeId select o).FirstOrDefault(); if (existingRoute != null) { if (existingRoute.Start() == false) { _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to start route."); } } } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Failed to start route.", Exception = ex }); _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to start route: " + ex.Message); } } }