protected override void QuerySettings() { NetworkSettings section = (NetworkSettings)ConfigurationManager.GetSection("Saga.Manager.NetworkSettings"); if (section != null) { NetworkElement Element = section.Connections["public"]; if (Element != null) { _host_1 = Element.Host; _port_1 = Element.Port; } NetworkElement Element2 = section.Connections["internal"]; if (Element2 != null) { _host_2 = Element2.Host; _port_2 = Element2.Port; } _worldid = section.WorldId; _playerlimit = section.PlayerLimit; _requiredage = (byte)section.Agelimit; _proof = section.Proof; } }
public void TestChatClient(ClientEntity sender, byte channel, string content, uint instance_id) { if (sender is null) { throw new ArgumentNullException(nameof(sender)); } if (channel < 0) { throw new ArgumentOutOfRangeException(nameof(channel)); } if (content is null) { throw new ArgumentNullException(nameof(content)); } if (instance_id < 0) { throw new ArgumentOutOfRangeException(nameof(instance_id)); } NetworkElement element = BotofuProtocolManager.Protocol[ProtocolKeyEnum.Messages, x => x.name == "ChatClientMultiMessage"]; NetworkContentElement element_content = new NetworkContentElement() { fields = { { "channel", channel }, { "content", content } } }; Send(true, sender, element, element_content, instance_id); }
private void ClientTreatment_OnMessageParsed(NetworkElement arg1, ProtocolJsonContent arg2) { var hooker = HookManager <T> .Instance[LocalClient.localIp.Port]; if (hooker is null) { logger.Error("no proxy found"); return; } if (ClientTreatment.Informations is MessageBuffer informations) { hooker.Proxy.LAST_GLOBAL_INSTANCE_ID = informations.InstanceId; } uint instance_id = hooker.Proxy.LAST_GLOBAL_INSTANCE_ID + hooker.Proxy.FAKE_MESSAGE_SENT; StartupConfiguration configuration = Configurations.ConfigurationManager.Instance.Startup; if (configuration.show_message) { logger.Info($"[client {RemoteClient.remoteIp}] {arg1.BasicString()}"); if (configuration.show_message_content) { logger.Info($"{arg2}"); } } HandlerManager.Instance.Handle(arg1.protocolID, LocalClient, RemoteClient, arg2); RemoteClient.Send(ClientTreatment.Informations.ReWriteInstanceId(instance_id)); }
public override void Handle() { DofusProxyClientReceiveCallback _proxy_callback = _casted_callback <DofusProxyClientReceiveCallback>(); if (DofusProxy._proxy_api.GetData(null).custom_servers.FirstOrDefault(x => x.ServerId == (int)_content["serverId"]) is ProxyCustomServerData _data) { NetworkElement element = BotofuProtocolManager.Protocol[ProtocolKeyEnum.Messages, x => x.name == "SelectedServerDataMessage"]; logger.Info("request connection in custom server"); Send(false, _callback._client, element, new NetworkContentElement() { fields = { { "serverId", _data.ServerId }, { "address", _data.IpAddress }, { "ports", _data.Ports }, { "canCreateNewCharacter", true }, { "ticket", _rnd_ticket() } } }); _proxy_callback._proxy.AccountData.ConnectedToCustomServer = true; _callback._client_disconnector.Handle(_callback._client); } else { Send(true, _callback._remote, _element, _content, _callback.InstanceId); _proxy_callback._proxy.AccountData.ConnectedToCustomServer = false; } }
// Setup travel to next network element to be visited (target, direction, etc..) public void SetUpTravel() { nextNetworkElement = networkQueue.Dequeue(); direction = nextNetworkElement.transform.position - transform.position; moving = true; }
public void EndTurn() { if (CorrectUnit != null) { CorrectUnit.unit.EndingTurn(); CorrectUnit.unit.TimeReusePerc--; } TurnNum++; ClearGrid(); if (!correctUnitturn().unit.Alive) { EndTurn(); } IsLock = false; CorrectUnit = correctUnitturn(); GetUnitInfo(); if (CorrectUnit.Controlled) { CameraFollow.transform.position = new Vector3(CorrectUnit.transform.position.x + Camera.main.transform.position.y / 1.5f, 0, CorrectUnit.transform.position.z - Camera.main.transform.position.y / 1.5f) + new Vector3(0, Camera.main.transform.position.y, 0); } MarcerCorrectUnit.transform.position = CorrectUnit.transform.position - Vector3.right * .25f + Vector3.forward * .1f; MarcerCorrectUnit.transform.parent = CorrectUnit.transform; CorrectUnit.unit.DamageSystem.CheckEffect(); TurnMode = EnumTurnMode._noneMode; }
public void InstantiateUnitTeams() { for (int i = 0; i < teamASize; i++) { NetworkElement unit = TeamA[i]; if (TeamName == TeamType.TeamA) { unit.Controlled = true; } unit.transform.position = Vector3.right * 4 + Vector3.forward * i; unit.SetElements(); unit.unit.Manger = this; } for (int i = 0; i < teamBSize; i++) { NetworkElement unit = TeamB[i]; if (TeamName == TeamType.TeamB) { unit.Controlled = true; } unit.transform.position = -Vector3.right * 5 + Vector3.back + Vector3.forward * i; unit.SetElements(); unit.unit.Manger = this; } CorrectUnit = correctUnitturn(); EndTurn(); }
public void GetNetworkFromNetworkCollectionDoesntGetNull() { EndpointSection section = (EndpointSection)ConfigurationManager.GetSection("Endpoints"); NetworkElement element = section.EndpointItemCollection.GetEndpoint("MyHost").Networks.GetNetwork("Internet"); Assert.IsNotNull(element); }
public NodeA(Vector3 position, int xCor, int yCor, NodeType type) { TypeBloc = type; x = xCor; y = yCor; Position = position; iUnitOnNode = null; }
private static void CreateLoginClient() { //HELPER VARIABLES string host = "127.0.0.1"; int port = 64001; try { //GET THE NETWORK SETTINGS NetworkSettings section = (NetworkSettings)ConfigurationManager.GetSection("Saga.NetworkSettings"); if (section != null) { NetworkElement Element = section.Connections["internal"]; if (Element != null) { host = Element.Host; port = Element.Port; } } lock (Synroot) { error = NetworkError.Unknown; instance = new LoginClient(host, port); Trace.TraceInformation("Sending header token"); Saga.Packets.SMSG_HEADERTOKEN p = new Saga.Packets.SMSG_HEADERTOKEN(); instance.Send((byte[])p); error = NetworkError.None; } } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionRefused) { error = NetworkError.Refused; Trace.TraceError("Target machine refused connection on: {0}-{1}", host, port); throw; } else if (e.SocketErrorCode == SocketError.HostUnreachable) { error = NetworkError.Unreachable; Trace.TraceError("Target machine is unreachable: {0}-{1}", host, port); throw; } else if (e.SocketErrorCode == SocketError.HostNotFound) { error = NetworkError.InvalidHost; Trace.TraceError("Target machine has an invalid host name: {0}-{1}", host, port); throw; } } catch (Exception e) { error = NetworkError.Unknown; Trace.WriteLine(e); } }
private void AddLinkSheet(NetworkElement ne, ExcelPackage p, NeType type) { if (ne.LinksOnEnd1.Where(x => x.End2.NetworkType == type).Count() == 0) { return; } var ws = p.Workbook.Worksheets.Add($"{ne.Name} ({type})"); int col = 1; int row = 6; ws.Cells[row, col++].Value = "Name"; ws.Cells[row, col++].Value = "Exchange"; ws.Cells[row, col++].Value = "Channels"; ws.Cells[row, col++].Value = "[STM1,E1,Channel]"; ws.Cells[row, col++].Value = "Direction"; ws.Cells[row, col++].Value = "Type"; ws.Cells[row, col++].Value = "Remark"; row++; foreach (var link in ne.LinksOnEnd1.Where(x => x.End2.NetworkType == type)) { col = 1; ws.Cells[row, col++].Value = link.End2.Name; ws.Cells[row, col++].Value = $"{link.End2.Exchange.Abb} ({link.End2.Exchange.Name})"; ws.Cells[row, col++].Value = link.Channels; ws.Cells[row, col++].Value = link.GetStm1E1(); ws.Cells[row, col++].Value = link.Direction; ws.Cells[row, col++].Value = link.Type; ws.Cells[row, col++].Value = link.Remark; row++; } var range = ws.Cells[6, 1, row - 1, 7]; var tbl = ws.Tables.Add(range, $"{ne.Name}_{type}"); tbl.TableStyle = TableStyles.Medium1; range.AutoFitColumns(); row = 1; ws.Cells[row++, 1].Value = $"Name: {ne.Name}"; ws.Cells[row++, 1].Value = $"Exchange: {ne.Exchange.Name} ({ne.Exchange.Abb})"; if (ne.NetworkType == NeType.Core) { ws.Cells[row++, 1].Value = $"Model: {ne.Model}"; ws.Cells[row++, 1].Value = $"Manufacturer: {ne.Manufacturer}"; } else { //ws.Cells[row++, 1].Value = $"Customer: {ne.Customer.Name} ({ne.Customer.Abb})"; } PrinterSettings(ws, 6); HeaderFooter(ws); }
private IActionResult PbxElement(NetworkElement ne) { var model = new RemoteElementViewModel() { Miscs = repository.Miscs.OrderBy(x => x.Name).ToArray(), NE = repository.NetworkElements.Where(x => x.Id == ne.Id).Include(x => x.Parent).Include(x => x.Exchange).First() }; return(View("RemoteElement", model)); }
public void AddNetwork() { var network = new NetworkElement() { Name = "New Server" }; Networks.Add(network); SelectedNetwork = network; }
private void DashboardRoot_Drop(object sender, DragEventArgs e) { if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey) && e.Data.GetDataPresent(NetworkDataFormats.NetworkElement)) { //offer to create the bound control here NetworkElement dataSource = (NetworkElement)e.Data.GetData(NetworkDataFormats.NetworkElement); //all available types IEnumerable <Type> controlTypes = PluginLoader.GetControls(); IEnumerable <Type> allowedControls; //check whether this is a primitive or complex data and filter the controls appropriately if (dataSource.Type == typeof(NetworkTree)) { //get the expected type of the element NetworkTable table = NetworkTable.GetTable(dataSource.FullPath); string dataType = table.GetString("type", null); allowedControls = controlTypes .Where((t) => SourcedControl.GetAllowedComplexTypes(t).Contains(dataType)); } else { allowedControls = controlTypes .Where((t) => SourcedControl.GetAllowedPrimitiveTypes(t).Contains(dataSource.Type)); } if (allowedControls.Count() != 0) { ControlPreviewDialog previewDialog = new ControlPreviewDialog(); PopulateControlPreviewWrapPanel(previewDialog.availableControls, allowedControls); if (previewDialog.ShowDialog() == true) { Type controlType = previewDialog.SelectedType; if (controlType != null) { SourcedControl c = (SourcedControl)controlType.GetConstructor(Type.EmptyTypes).Invoke(null); PlaceAtDropPoint(c, e); dashboardRoot.Children.Add(c); c.Source = dataSource.FullPath.Replace("/SmartDashboard/", ""); } } } else { MessageBox.Show("There are no controls that can display this entry!", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } else if (e.Data.GetDataPresent(NetworkDataFormats.SourcedControl)) { //create the control here Type controlType = (Type)e.Data.GetData(NetworkDataFormats.SourcedControl); SourcedControl c = (SourcedControl)controlType.GetConstructor(Type.EmptyTypes).Invoke(null); PlaceAtDropPoint(c, e); dashboardRoot.Children.Add(c); } e.Handled = true; }
public int GetUnitId(NetworkElement element) { for (int i = 0; i < teamASize + teamBSize; i++) { if (ElementsInGame[i] == element) { return(i); } } throw new Exception("No in GameIndex"); }
public void Send(NetworkElement message, ProtocolJsonContent content, bool clientSide) { if (message is null) { return; } using (BigEndianWriter writer = new BigEndianWriter()) { byte[] data = ProtocolTreatmentExtension.FromContent(content, message); int cmpLen = _cmpLen(data.Length); writer.WriteShort((short)((message.protocolID << 2) | cmpLen)); if (clientSide) { writer.WriteUnsignedInt(GetCustomInstanceId()); } switch (cmpLen) { case 0: break; case 1: writer.WriteByte((byte)data.Length); break; case 2: writer.WriteShort((short)data.Length); break; case 3: writer.WriteByte((byte)((data.Length >> 16) & 255)); writer.WriteShort((short)(data.Length & 65535)); break; } writer.WriteBytes(data); Send(writer.Data); OnCustomMessageSent?.Invoke(message, content); StartupConfiguration configuration = Configurations.ConfigurationManager.Instance.Startup; if (configuration.show_fake_message) { logger.Info($"fake message sent to {remoteIp} |{message.BasicString()}]"); if (configuration.show_fake_message_content) { logger.Info($"{content}"); } } } }
public void LinksReport(NetworkElement ne) { var file = new FileInfo(path); using (var p = new ExcelPackage(file)) { var ws = p.Workbook.Worksheets.Add("Links"); FillLinkWS(ws, ne.LinksOnEnd1); p.Save(); } }
public async Task <bool> Handle(AbstractClientReceiveCallback callback, NetworkElement element, NetworkContentElement content) { IEnumerable <Type> _handlers = _handlers_type.Where(x => x.GetCustomAttribute <Attribute>().BaseMessage.protocolID == element.protocolID); bool _all_true = true; foreach (Type _handler in _handlers) { _all_true = _all_true && await _handle(_handler, callback, element, content); } return(_all_true); }
public virtual void MakeShoot(NodeA node) { if (_unit == null) { _unit = transform.parent.GetComponent <NetworkElement> (); } if (_bullet == null) { _bullet = Resources.Load <GameObject> ("Staff/Bullet") as GameObject; } _target = node.UnitOnNode.unit; StartCoroutine(MoveBullet(node)); }
void GetBoom() { Instantiate(ImportVisualEffect((int)Granades[currentGranade].granade), _point, Quaternion.identity); for (int i = 0; i < vectorsOfGrande.Length; i++) { Vector2 n = vectorsOfGrande[i]; NetworkElement unitTarget = GridABS.NodeFromWorldPoint(new Vector3(n.x, 0, n.y)).UnitOnNode; if (unitTarget != null) { int PowerPerc = Granades[currentGranade].PowerPerc; int Range = Granades[currentGranade].Range; switch ((int)Granades[currentGranade].granade) { case 0: unitTarget.unit.GetDamage(PowerPerc); ClientReciverMK1.WriteMsg("/Damage" + ThisUnit.Manger.GetUnitId(unitTarget) + ":" + PowerPerc + ":" + 0 + ":" + 0); break; case 1: unitTarget.unit.GetDamage(0, PowerPerc, (int)BasicUnit.DamageType.Stan); ClientReciverMK1.WriteMsg("/Damage" + ThisUnit.Manger.GetUnitId(unitTarget) + ":" + 0 + ":" + PowerPerc + ":" + (int)BasicUnit.DamageType.Stan); break; case 2: unitTarget.unit.GetDamage(PowerPerc, Range, (int)BasicUnit.DamageType.Fire); ClientReciverMK1.WriteMsg("/Damage" + ThisUnit.Manger.GetUnitId(unitTarget) + ":" + PowerPerc + ":" + Range + ":" + (int)BasicUnit.DamageType.Fire); break; case 3: Vector3 poitionToChek = unitTarget.transform.position + (unitTarget.transform.position - _point).normalized * PowerPerc; var node = GridABS.NodeFromWorldPoint(poitionToChek); if (node.TypeBloc == NodeA.NodeType.Walkable && node.UnitOnNode == null) { ClientReciverMK1.WriteMsg("/Move" + ThisUnit.Manger.GetUnitId(unitTarget) + ":" + node.x + ":" + node.y); unitTarget.MoveToCord(node.x, node.y); } break; case 4: break; } } } Granades[currentGranade].count -= 1; currentGranade = -1; ThisUnit.Manger.EndTurn(); ClientReciverMK1.WriteMsg("/EndTurn"); }
private void SourcedControl_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(NetworkDataFormats.NetworkElement)) { NetworkElement element = e.Data.GetData(NetworkDataFormats.NetworkElement) as NetworkElement; if (ValidateDropType(element)) { //source = full path Source = element.FullPath.Replace("/SmartDashboard/", ""); //only handle if successful drop e.Handled = true; } } }
public virtual void Send(bool fromClient, ClientEntity sender, NetworkElement element, NetworkContentElement content, uint?instance_id = null) { if (fromClient && instance_id is null) { throw new ArgumentNullException(nameof(instance_id)); } byte[] _data = new MessageDataBufferWriter(element).Parse(content); byte[] _final_data = new MessageBufferWriter(fromClient).Build((ushort)(element.protocolID == 6253 ? 8892 /*rdm*/ : element.protocolID), instance_id, _data).Data; _callback._client_sender.Handle(sender, _final_data); logger.Info($"fake message sent : {element.BasicString} {(instance_id.HasValue ? instance_id.Value : 0)}"); }
public IActionResult Exchange(Area district, string exchange, [Bind(Prefix = nameof(ExchangeViewModel.NewNE))] NetworkElement newNe) { if (ModelState.IsValid) { newNe.Username = User.Identity.Name; repository.AddNetworkElement(newNe); TempData["message"] = $"{newNe.Name} added succesfully."; return(RedirectToAction(nameof(Exchange), new { district, exchange })); } else { return(Exchange(district, exchange)); } }
public static byte[] FromContent(ProtocolJsonContent content, NetworkElement field) { if (content is null) { return(new byte[0]); } if (field is null) { throw new Exception("field cannot be null"); } try { using (BigEndianWriter writer = new BigEndianWriter()) { if (field.super_serialize) { NetworkElement super = ProtocolManager.Instance.Protocol[ProtocolKeyEnum.MessagesAndTypes, x => x.name == field.super]; byte[] super_data = FromContent(content, super); writer.WriteBytes(super_data); } IEnumerable <ClassField> boolWrapper = field.fields.Where(x => x.use_boolean_byte_wrapper).OrderBy(x => x.boolean_byte_wrapper_position); IEnumerable <ClassField> vars = field.fields.Where(x => !boolWrapper.Contains(x)).OrderBy(x => x.position); if (boolWrapper.Count() > 0) { byte[] flags = new byte[boolWrapper.LastOrDefault().position.Value + 1]; foreach (ClassField _bool in boolWrapper) { flags[_bool.position.Value] = BooleanByteWrapper.SetFlag(flags[_bool.position.Value], (byte)((_bool.boolean_byte_wrapper_position.Value - 1) % 8), content[_bool.name]); } } foreach (ClassField _var in vars) { Parse(_var, content[_var.name], writer); } return(writer.Data); } } catch (Exception e) { logger.Error(e); return(new byte[0]); } }
private IActionResult CoreElement(NetworkElement ne) { var childrenCap = repository.NetworkElements .Where(x => x.ParentId == ne.Id) .GroupBy(x => x.NetworkType) .Select(x => new CapacitySpecs { Type = x.Key, Count = x.Count(), SumInstalled = x.Sum(y => (long)y.InstalledCapacity), SumUsed = x.Sum(y => (long)y.UsedCapacity) }) .ToList(); var linksSpecsByLinkType = repository.Links .Where(l => l.End1Id == ne.Id) .GroupBy(x => x.Type) .Select(x => new LinksSpecsByLinkType() { Type = x.Key, Count = x.Count(), SumChannels = x.Sum(y => y.Channels) }) .ToList(); var linksSpecsByNeType = repository.Links .Where(l => l.End1Id == ne.Id) .GroupBy(x => x.End2.NetworkType) .Select(x => new LinksSpecsByNeType() { Type = x.Key, Count = x.Count(), SumChannels = x.Sum(y => y.Channels) }) .ToList(); var model = new CoreViewModel() { NE = repository.NetworkElements.Where(x => x.Id == ne.Id).Include(x => x.Exchange).First(), Remotes = childrenCap.Where(x => x.Type == NeType.Remote).FirstOrDefault(), Accesses = childrenCap.Where(x => x.Type == NeType.Access).FirstOrDefault(), CoreLinks = linksSpecsByNeType.Where(x => x.Type == NeType.Core).FirstOrDefault(), IsupLinks = linksSpecsByLinkType.Where(x => x.Type == LinkType.ISUP).FirstOrDefault(), SipLinks = linksSpecsByLinkType.Where(x => x.Type == LinkType.SIP).FirstOrDefault(), Miscs = repository.Miscs.OrderBy(x => x.Name).ToArray() }; return(View("Core", model)); }
private void ServerTreatment_OnMessageParsed(NetworkElement arg1, ProtocolJsonContent arg2) { StartupConfiguration configuration = Configurations.ConfigurationManager.Instance.Startup; if (configuration.show_message) { logger.Info($"[server {RemoteClient.remoteIp}] {arg1.BasicString()}"); if (configuration.show_message_content) { logger.Info($"{arg2}"); } } HandlerManager.Instance.Handle(arg1.protocolID, LocalClient, RemoteClient, arg2); }
public IActionResult EditNe([Bind(Prefix = nameof(CoreViewModel.NE))] NetworkElement ne) { var exch = repository.Exchanges.Where(x => x.Id == ne.ExchangeId).FirstOrDefault(); if (ModelState.IsValid) { repository.EditNetworkElement(ne); TempData["message"] = $"{ne.Name} edited successfully."; return(RedirectToAction(nameof(Specifications), new { district = exch.Area, exchange = exch.Abb, ne = ne.Name })); } else { return(Specifications(exch.Area, exch.Abb, ne.Name)); } }
public List <NetworkElementProxy> GetNetworks() { UIElementCollection networks = PLBlockEditorControlElement.NetworksContainer.GetNetworks(); List <NetworkElementProxy> proxies = new List <NetworkElementProxy>(); foreach (UIElement network in networks) { if (network is NetworkElement) { NetworkElement ne = network as NetworkElement; NetworkElementProxy proxy = new NetworkElementProxy(ne); proxies.Add(proxy); } } return(proxies); }
private bool ValidateDropType(NetworkElement e) { if (e.Type == typeof(NetworkTree)) { //deal with complex types NetworkTable table = NetworkTable.GetTable(e.FullPath); string dataType = table.GetString("type", null); return(GetAllowedComplexTypes(GetType()).Contains(dataType)); } else { //deal with primitives //get all the unique primitive types allowed return(GetAllowedPrimitiveTypes(GetType()).Contains(e.Type)); } }
public static ProtocolJsonContent FromBytes(ProtocolJsonContent content, NetworkElement field, IDataReader reader) { if (content is null) { content = new ProtocolJsonContent(); } if (field is null) { return(content); } try { if (field.super_serialize) { NetworkElement super = ProtocolManager.Instance.Protocol[ProtocolKeyEnum.MessagesAndTypes, x => x.name == field.super]; content = FromBytes(content, super, reader); } IEnumerable <ClassField> boolWrapper = field.fields.Where(x => x.use_boolean_byte_wrapper).OrderBy(x => x.boolean_byte_wrapper_position); IEnumerable <ClassField> vars = field.fields.Where(x => !boolWrapper.Contains(x)).OrderBy(x => x.position); byte flag = 0; for (byte i = 0; i < boolWrapper.Count(); i++) { ClassField _bool = boolWrapper.ElementAt(i); if (i % 8 == 0) { flag = reader.ReadByte(); } content[_bool.name] = BooleanByteWrapper.GetFlag(flag, i); } foreach (ClassField _var in vars) { content[_var.name] = _var.Parse(ref reader); } } catch (Exception e) { Console.WriteLine($"{e}"); } return(content); }
private static void FirstRunConfiguration() { IPAddress gatewayip = IPAddress.Loopback; int gatewayport = 64001; IPAddress mapip = IPAddress.Loopback; int mapport = 64002; string databaseusername = "******"; string databasepassword = "******"; uint dbport = 3306; string databasename = "saga_auth"; string dbhost = "localhost"; string provider = "Saga.Authentication.Data.Mysql.dll, Saga.Authentication.Data.Mysql.MysqlProvider"; ConsoleReader reader = new ConsoleReader(); reader.Clear(null); System.Configuration.Configuration b = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (CheckConfigExists() == false) { Console.WriteLine("First time run-configuration"); char key; provider = FindPlugin(typeof(IDatabase), "Saga.Authentication.Data.Mysql.dll, Saga.Authentication.Data.Mysql.MysqlProvider"); ConfigureGatewayNetwork: Console.WriteLine("Do you wan to configure the authentication-gateway network settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What ip should the authentication-gateway server listen to?"); while (!IPAddress.TryParse(Console.ReadLine(), out gatewayip)) { Console.WriteLine("Incorrect value please use an ipv4 adress, recommended 0.0.0.0"); } Console.WriteLine("What port should the authentication-gateway server listen to?"); while (!int.TryParse(Console.ReadLine(), out gatewayport)) { Console.WriteLine("Incorrect value please use an number between 1024�49151, recommended 64001"); } } else if (key != 'n') goto ConfigureGatewayNetwork; ConfigureWorldNetwork: Console.WriteLine("Do you wan to configure the authentication-map network settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What ip should the authentication-map server listen to?"); while (!IPAddress.TryParse(Console.ReadLine(), out mapip)) { Console.WriteLine("Incorrect value please use an ipv4 adress, recommended 0.0.0.0"); } Console.WriteLine("On what port is the authentication server listening"); while (!int.TryParse(Console.ReadLine(), out mapport)) { Console.WriteLine("Incorrect value please use an number between 1024�49151, recommended 64000"); } } else if (key != 'n') goto ConfigureWorldNetwork; DatabaseName: Console.WriteLine("Do you wan to configure the database settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What is the database name?"); databasename = Console.ReadLine(); Console.WriteLine("What is the database username?"); databaseusername = Console.ReadLine(); Console.WriteLine("What is the database password?"); databasepassword = Console.ReadLine(); Console.WriteLine("What is the database port?"); while (!uint.TryParse(Console.ReadLine(), out dbport)) { Console.WriteLine("Incorrect value please use an number between 1024�49151, recommended 3306"); } Console.WriteLine("What is the database host?"); dbhost = Console.ReadLine(); } else if (key != 'n') goto DatabaseName; //Adjust network settings NetworkSettings networkSettings = b.Sections["Saga.NetworkSettings"] as NetworkSettings; if (networkSettings == null) networkSettings = new NetworkSettings(); NetworkFileCollection collection = networkSettings.Connections; collection["public"] = new NetworkElement("public", gatewayip.ToString(), gatewayport); collection["internal"] = new NetworkElement("internal", mapip.ToString(), mapport); b.Sections.Remove("Saga.NetworkSettings"); b.Sections.Add("Saga.NetworkSettings", networkSettings); //Adjust database settings DatabaseSettings databaseSettings = b.Sections["Saga.Manager.Database"] as DatabaseSettings; if (databaseSettings == null) databaseSettings = new DatabaseSettings(); databaseSettings.Database = databasename; databaseSettings.Username = databaseusername; databaseSettings.Password = databasepassword; databaseSettings.Port = dbport; databaseSettings.Host = dbhost; databaseSettings.DbType = provider; b.Sections.Remove("Saga.Manager.Database"); b.Sections.Add("Saga.Manager.Database", databaseSettings); b.Save(); ConfigurationManager.RefreshSection("Saga.NetworkSettings"); ConfigurationManager.RefreshSection("Saga.Manager.Database"); Console.WriteLine("Everything configured"); } }
private static void Main(string[] args) { reader = new ConsoleReader(); reader.Title = "Gateway server, type help for commands"; reader.Initialize += new EventHandler(reader_Initialize); reader.Register(new ConsoleCommandHandler(Version)); reader.Register(new ConsoleCommandHandler(CrcValidationCheck)); reader.Register(new ConsoleCommandHandler(CheckHost)); reader.Register(new ConsoleCommandHandler(Shutdown)); reader.Clear(null); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); //SagaConfigurationManager.read(); string file = System.Reflection.Assembly.GetExecutingAssembly().Location; string fname = Path.GetFileNameWithoutExtension(file); //TRACELOG Trace.AutoFlush = true; Trace.IndentSize = 4; if (System.Diagnostics.Trace.Listeners.Count <= 1 && (System.Diagnostics.Trace.Listeners["Default"] == null || System.Diagnostics.Trace.Listeners["Default"].GetType() == typeof(System.Diagnostics.DefaultTraceListener))) { DelimitedListTraceListener del = new System.Diagnostics.DelimitedListTraceListener((fname + ".log.csv"), "text"); del.Delimiter = ","; System.Diagnostics.Trace.Listeners.Add(del); } Trace.WriteLine("#############################################################################"); Trace.WriteLine(string.Format("Saga Gateway Server starting on: {0}", DateTime.Now)); Trace.WriteLine(string.Format("OS Information: {0}", Environment.OSVersion)); Trace.WriteLine(string.Format("Number of Processors: {0}", Environment.ProcessorCount)); Trace.WriteLine(string.Format("CLR Version: {0}", Environment.Version)); Trace.WriteLine(string.Format("Working set: {0}", Environment.WorkingSet)); Trace.WriteLine(string.Format("OS Bit Version: {0} Bit", IntPtr.Size * 8)); Trace.WriteLine("#############################################################################"); System.Configuration.Configuration b = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (CheckConfigExists() == false) { Console.WriteLine("First time run-configuration"); char key; ConfigureGatewayNetwork: Console.WriteLine("Do you wan to configure the gateway-network settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What ip should the gateway server listen to?"); while (!IPAddress.TryParse(Console.ReadLine(), out gatewayip)) { Console.WriteLine("Incorrect value please use an ipv4 adress, recommended 0.0.0.0"); } Console.WriteLine("What port should the gateway server listen to?"); while (!int.TryParse(Console.ReadLine(), out gatewayport)) { Console.WriteLine("Incorrect value please use an number between 1024–49151, recommended 64000"); } } else if (key != 'n') goto ConfigureGatewayNetwork; ConfigureAuthenticationNetwork: Console.WriteLine("Do you wan to configure the authentication-network settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What is the ip of the authentication server"); while (!IPAddress.TryParse(Console.ReadLine(), out authenticationip)) { Console.WriteLine("Incorrect value please use an ipv4 adress, recommended 0.0.0.0"); } Console.WriteLine("On what port is the authentication server listening"); while (!int.TryParse(Console.ReadLine(), out authenticationport)) { Console.WriteLine("Incorrect value please use an number between 1024–49151, recommended 64000"); } } else if (key != 'n') goto ConfigureAuthenticationNetwork; ConfigureGUID: Console.WriteLine("Do you wan to configure the gateway-guid settings? Y/N"); key = Console.ReadKey(true).KeyChar; if (key == 'y') { Console.WriteLine("What is the crc key"); byte[] ncrckey; while (!Conversions.TryParse(Console.ReadLine(), out ncrckey) || crckey.Length != 20) { Console.WriteLine("Crc key key must be 20 hex digit string, recommended: A928CDC9DBE8751B3BC99EB65AE07E0C849CE739"); } Console.WriteLine("What is the guid key"); byte[] nguidkey; while (!Conversions.TryParse(Console.ReadLine(), out nguidkey) || guidkey.Length != 20) { Console.WriteLine("Guid key key must be 20 hex digit string, recommended: ED90AA25AE906FB36308C8523A4737A7E7B1FC6F"); } crckey = Conversions.ByteToHexString(ncrckey); guidkey = Conversions.ByteToHexString(nguidkey); } else if (key != 'n') goto ConfigureGUID; NetworkSettings networkSettings = new NetworkSettings(); NetworkFileCollection collection = networkSettings.Connections; collection["public"] = new NetworkElement("public", gatewayip.ToString(), gatewayport); collection["internal"] = new NetworkElement("internal", authenticationip.ToString(), authenticationport); networkSettings.Crckey = crckey; networkSettings.Guidkey = guidkey; b.Sections.Remove("Saga.NetworkSettings"); b.Sections.Add("Saga.NetworkSettings", networkSettings); b.Save(); ConfigurationManager.RefreshSection("Saga.NetworkSettings"); Console.WriteLine("Everything configured"); LoginClient client; for (int i = 0; i < 3; i++) { if (NetworkManager.TryGetLoginClient(out client)) { Console.WriteLine("Test connection created"); client.Close(); break; } else { Thread.Sleep(3000); Console.WriteLine("Test connection failed retrying in 3 secconds"); } } } else { LoginClient client; Console.WriteLine("Configuration file exists"); Console.WriteLine("Trying to connect to authentication-server..."); if (NetworkManager.TryGetLoginClient(out client)) { client.ExchangeIpAdress(IPAddress.Loopback); Console.WriteLine("Connection to authentication-server is create"); } else { switch (NetworkManager.LastError) { case NetworkManager.NetworkError.InvalidHost: Console.WriteLine("Host is invalid"); break; case NetworkManager.NetworkError.Refused: Console.WriteLine("Target machine activly refused the connection"); break; case NetworkManager.NetworkError.Unknown: Console.WriteLine("Unknown exception occured"); break; case NetworkManager.NetworkError.Unreachable: Console.WriteLine("Target machin is unreachable"); break; } } } reader.Start(); }