private void OnClosed(ConfigurationData data) { if (data != null) { this.Hide(); } else { return; } if (data.OperateType == OperateScreenType.CreateScreenAndOpenConfigFile) { if (data.ProjectLocationPath != "") { // this.Hide(); MainWindow win = new MainWindow(data); Application.Current.MainWindow = win; win.Show(); } } else if (data.OperateType == OperateScreenType.CreateScreen) { MainWindow win = new MainWindow(data); Application.Current.MainWindow = win; win.Show(); } //else if (data.OperateType = OperateScreenType.CreateScreen) //{ // this.Hide(); //} }
public Server(string XMLConfigFile, ConfigurationData configData) { ConfigurationFile = XMLConfigFile; Config = configData; SaveConfig(); ServerInit(); }
public MainWindow(ConfigurationData data) { InitializeComponent(); _vm = (MainWindow_VM)this.FindResource("MainWindow_VMDataSource"); _vm.MyConfigurationData = data; Messenger.Default.Register<object>(this, MsgToken.MSG_EXIT, OnExit); }
public Configuration(string configFile) { var serializer = new XmlSerializer(typeof(ConfigurationData)); using (var stream = new FileStream(configFile, FileMode.Open)) { configuration = (ConfigurationData)serializer.Deserialize(stream); } }
private void OnCreateAndShowScreen(ConfigurationData data) { this.Hide(); Messenger.Default.Unregister<object>(this, MsgToken.MSG_CLOSE_GUIDETWOFORM, OnCloseForm); //Messenger.Default.Unregister<ConfigurationData>(this, MsgToken.MSG_CREATEANDSHOWSCREEN, OnCreateAndShowScreen); //MainWindow win = new MainWindow(data); //win.ShowDialog(); }
/// <summary> /// Loads the configuration in a file. /// </summary> /// <param name="filename"></param> protected void LoadConfig(string filename) { XmlSerializer x = new XmlSerializer(Config.GetType()); if (!File.Exists(filename)) return; using (StreamReader sr = new StreamReader(filename)) { Config = (ConfigurationData)x.Deserialize(sr); sr.Close(); } }
public MainWindowold(ConfigurationData data) { this.DataContext = _vm; InitializeComponent(); this.Loaded += MainWindow_Loaded; //_vm = (MainWindow_VM)this.FindResource("MainWindow_VMDataSource"); //_vm = new MainWindow_VM(); _vm.MyConfigurationData = data; Messenger.Default.Register<object>(this, MsgToken.MSG_EXIT, OnExit); }
/// <summary> /// Setup Role /// </summary> private void Setup() { string json = MediaButler.Common.Configuration.GetConfigurationValue("roleconfig", this.GetType().FullName, CloudConfigurationManager.GetSetting("MediaButler.ConfigurationStorageConnectionString")); myConfigData = Newtonsoft.Json.JsonConvert.DeserializeObject<ConfigurationData>(json); myConfigData.poisonQueue = MediaButler.Common.Configuration.ButlerFailedQueue; myConfigData.inWorkQueueName = MediaButler.Common.Configuration.ButlerSendQueue; myConfigData.ProcessConfigConn = RoleEnvironment.GetConfigurationSettingValue("MediaButler.ConfigurationStorageConnectionString"); myConfigData.MaxCurrentProcess = myConfigData.MaxCurrentProcess; myConfigData.SleepDelay = myConfigData.SleepDelay; myConfigData.MaxDequeueCount = myConfigData.MaxDequeueCount; }
public App() { // StartupUri = new Uri("ConfigurationWindow.xaml", UriKind.Relative); ConfigurationData data = new ConfigurationData { Title = "Standard options", ItemsInWindow = 18, IsUppercase = true, Color = "Red", }; ConfigurationWindow w = new ConfigurationWindow(data); w.Show(); }
private void LoadConfigurationData() { if (_data == null) { object objLock; lock (objLock = new object()) { if (_data == null) { var json = File.ReadAllText(ConfigurationFileName); _data = JsonConvert.DeserializeObject<ConfigurationData>(json); } } } }
public Func<NodeUri, INodeLocator, Task<INode>> CreateNodeFactory(INodeLocatorRegistry registry, ConfigurationData configuration) { Debug.Print($"Create ServiceLocatorBuilder for service factory descriptor '{GetType().FullName}'"); var serviceLocatorRegistry = new ServiceLocatorRegistry(registry); Debug.Print($"Configure NodeFactory Services of ServiceFactory Descriptor '{GetType().FullName}'"); Configure(serviceLocatorRegistry, configuration); return (nodeUri, nodeLocator) => Task.Run(async () => { Debug.Print($"Configure service dependencies for Node at '{nodeUri}'"); await Configure(new ServiceLocator(nodeLocator), configuration); Debug.Print($"All done for Node at '{nodeUri}' - create an instance"); return (INode)nodeLocator; }); }
// standard constructor used by most indexers public BaseIndexer(string name, string link, string description, IIndexerManagerService manager, IWebClient client, Logger logger, ConfigurationData configData, IProtectionService p, TorznabCapabilities caps = null, string downloadBase = null) : this(manager, client, logger, p) { if (!link.EndsWith("/")) throw new Exception("Site link must end with a slash."); DisplayName = name; DisplayDescription = description; SiteLink = link; this.downloadUrlBase = downloadBase; this.configData = configData; if (caps == null) caps = TorznabUtil.CreateDefaultTorznabTVCaps(); TorznabCaps = caps; }
public EntityFrameworkEntities() : base("name=EntityFrameworkEntities") { // Inicializo los valores de autenticación de la base de datos ConfigurationData configurationData = new ConfigurationData(); // Compruebo los campos de configuracion para acceder a la base de datos if (configurationData.Server != "" && configurationData.Database != "" && configurationData.User != "" && configurationData.Password != "") { // Creo la cadena de conexión this.Database.Connection.ConnectionString = "server=" + configurationData.Server + ";user id=" + configurationData.User + ";password="******";database=" + configurationData.Database; } }
/// <summary> /// Constructor /// </summary> /// <param name="configuration">Configuration</param> public PrivacyController(IOptions <ConfigurationData> configuration) { _configData = configuration.Value; }
protected void Init(string DefinitionString) { this.DefinitionString = DefinitionString; var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .IgnoreUnmatchedProperties() .Build(); Definition = deserializer.Deserialize<IndexerDefinition>(DefinitionString); // Add default data if necessary if (Definition.Settings == null) Definition.Settings = new List<settingsField>(); if (Definition.Settings.Count == 0) { Definition.Settings.Add(new settingsField { Name = "username", Label = "Username", Type = "text" }); Definition.Settings.Add(new settingsField { Name = "password", Label = "Password", Type = "password" }); } if (Definition.Encoding == null) Definition.Encoding = "iso-8859-1"; if (Definition.Login != null && Definition.Login.Method == null) Definition.Login.Method = "form"; // init missing mandatory attributes DisplayName = Definition.Name; DisplayDescription = Definition.Description; SiteLink = Definition.Links[0]; // TODO: implement alternative links Encoding = Encoding.GetEncoding(Definition.Encoding); if (!SiteLink.EndsWith("/")) SiteLink += "/"; Language = Definition.Language; TorznabCaps = TorznabUtil.CreateDefaultTorznabTVCaps(); // TODO implement caps // init config Data configData = new ConfigurationData(); foreach (var Setting in Definition.Settings) { configData.AddDynamic(Setting.Name, new StringItem { Name = Setting.Label }); } foreach (var Category in Definition.Caps.Categories) { var cat = TorznabCatType.GetCatByName(Category.Value); if (cat == null) { logger.Error(string.Format("CardigannIndexer ({0}): Can't find a category for {1}", ID, Category.Value)); continue; } AddCategoryMapping(Category.Key, TorznabCatType.GetCatByName(Category.Value)); } }
/// <summary> /// Initializes the configuration utils /// </summary> public static void Initialize() { configurationData = new ConfigurationData(); }
/// <summary> /// Constructor /// </summary> /// <param name="options"></param> /// <param name="logger"></param> public LruCache(IOptions <ConfigurationData> options, ILogger logger) { _logger = logger; _options = options.Value; _logger.LogInformation("Initializing LRU cache."); }
internal static void Initialize() { Console.Clear(); DateTime Start = DateTime.Now; SystemMute = false; IrcEnabled = false; ServerStarted = DateTime.Now; Console.Title = PiciEnvironment.Title + " " + PiciEnvironment.Version; Console.WindowHeight = 30; DefaultEncoding = Encoding.Default; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(""); Console.WriteLine(" ______ _ _ _______ "); Console.WriteLine(" (_____ (_) (_) (_______) "); Console.WriteLine(" _____) ) ____ _ _____ ____ _ _ "); Console.WriteLine(@" | ____/ |/ ___) | | ___) | \| | | |"); Console.WriteLine(@" | | | ( (___| | | |_____| | | | |_| |"); Console.WriteLine(@" |_| |_|\____)_| |_______)_|_|_|____/ "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" "+PiciEnvironment.Title+" " + PiciEnvironment.Version + " (Build " + PiciEnvironment.Build + ")"); Console.WriteLine(); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(); cultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); LanguageLocale.Init(); try { ChatCommandRegister.Init(); PetCommandHandeler.Init(); PetLocale.Init(); Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath,@"config.conf")); DateTime Starts = DateTime.Now; dbType = DatabaseType.MySQL; manager = new DatabaseManager(uint.Parse(PiciEnvironment.GetConfig().data["db.pool.maxsize"]), uint.Parse(PiciEnvironment.GetConfig().data["db.pool.minsize"]), int.Parse(PiciEnvironment.GetConfig().data["db.pool.minsize"]), dbType); manager.setServerDetails( PiciEnvironment.GetConfig().data["db.hostname"], uint.Parse(PiciEnvironment.GetConfig().data["db.port"]), PiciEnvironment.GetConfig().data["db.username"], PiciEnvironment.GetConfig().data["db.password"], PiciEnvironment.GetConfig().data["db.name"]); manager.init(); TimeSpan TimeUsed2 = DateTime.Now - Starts; LanguageLocale.InitSwearWord(); Game = new Game(int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conlimit"])); Game.ContinueLoading(); ConnectionManager = new ConnectionHandeling(int.Parse(PiciEnvironment.GetConfig().data["game.tcp.port"]), int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conlimit"]), int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conperip"]), PiciEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); ConnectionManager.init(); ConnectionManager.Start(); StaticClientMessageHandler.Initialize(); ClientMessageFactory.Init(); string[] arrayshit = PiciEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(",")); MusSystem = new MusSocket(PiciEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(PiciEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0); //InitIRC(); groupsEnabled = true; useSSO = true; TimeSpan TimeUsed = DateTime.Now - Start; Logging.WriteLine("Server -> Started! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)"); isLive = true; Console.Beep(); if (bool_0_12) { Console.WriteLine("Coffee team, I appreciate you testing. ;-*"); System.Threading.Thread.Sleep(2500); PreformShutDown(true); return; } } catch (KeyNotFoundException e) { Logging.WriteLine("Please check your configuration file - some values appear to be missing."); Logging.WriteLine("Press any key to shut down ..."); Logging.WriteLine(e.ToString()); Console.ReadKey(true); PiciEnvironment.Destroy(); return; } catch (InvalidOperationException e) { Logging.WriteLine("Failed to initialize PiciEmulator: " + e.Message); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); PiciEnvironment.Destroy(); return; } catch (Exception e) { Console.WriteLine("Fatal error during startup: " + e.ToString()); Console.WriteLine("Press a key to exit"); Console.ReadKey(); Environment.Exit(1); } }
void SaveConfigAsJSON(ConfigurationData configurationData) { string JSON = JsonUtility.ToJson(configurationData); File.WriteAllText(Application.dataPath + "/ConfigurationsOfGame/JSON/DefaultConfiguration.json", JSON); }
/// <summary> /// Reads a configuration file and creates an object that represents it and it's parameters. /// </summary> /// <param name="filename">The relative or absolute path of the configuration file.</param> public ConfigurationFileObject(string filename) { ConfigurationNodes = new List <ConfigurationData>(); Script = new List <ConfigScriptLine>(); string[] lines = System.IO.File.ReadAllLines(@filename); // Display the file contents by using a foreach loop. foreach (string line in lines) { string[] readLine = line.Split('%'); string information = readLine[0]; Regex regex; List <string> words; if (information.Contains("Semantics") || information.Contains("semantics") || information.Contains("LoggingLevel")) { regex = new Regex(@"[^\p{L}]*\p{Z}[^\p{L}]*"); words = regex.Split(information).Where(x => !string.IsNullOrEmpty(x)).ToList(); switch (words[1]) { case "at-most-once": Semantics = DataTypes.SemanticsType.at_most_once; break; case "at-least-once": Semantics = DataTypes.SemanticsType.at_least_once; break; case "exactly-once": Semantics = DataTypes.SemanticsType.exactly_once; break; case "light": Logging = DataTypes.LoggingLevel.light; break; case "full": Logging = DataTypes.LoggingLevel.full; break; } continue; } if (information.Contains("INPUT_OPS") || information.Contains("input ops")) //This is a configuration { ConfigurationData data = new ConfigurationData(); regex = new Regex(SplitWordRegexString); words = regex.Split(information).Where(x => !string.IsNullOrEmpty(x)).ToList(); data.NumberofReplicas = Convert.ToInt32(words[words.IndexOf("fact") + 1]); data.NodeName = words[0]; data.TargetData = words[3]; switch (words[words.IndexOf("routing") + 1]) { case "random": data.Routing = RoutingType.random; break; case "primary": data.Routing = RoutingType.primary; break; default: data.Routing = RoutingType.hashing; data.RoutingArg = Convert.ToInt32(words[words.IndexOf("routing") + 2]); break; } data.Addresses = new List <string>(data.NumberofReplicas); for (int i = 0; i < data.NumberofReplicas; i++) { data.Addresses.Add(words[words.IndexOf("address") + 1 + i]); } int operationIndex = words.IndexOf("spec") + 1; switch (words[operationIndex]) { case "FILTER": data.Operation = OperatorType.filter; break; case "CUSTOM": data.Operation = OperatorType.custom; break; case "UNIQ": data.Operation = OperatorType.uniq; break; case "COUNT": data.Operation = OperatorType.count; break; } data.OperationArgs = new List <string>(); int pos = 1; string arg; try { while (!string.IsNullOrWhiteSpace(arg = words[operationIndex + pos])) { data.OperationArgs.Add(arg); pos++; } } catch (ArgumentOutOfRangeException) { } //it is expected to be out of range ConfigurationNodes.Add(data); continue; } regex = new Regex(SplitWordRegexString); words = regex.Split(information).Where(x => !string.IsNullOrEmpty(x)).ToList(); if (words.Count > 0) { Script.Add(new ConfigScriptLine(words)); } } }
private void OnCreateScreenWithConfigurationData(ConfigurationData data) { string projectPath = data.ProjectLocationPath + "\\" + data.ProjectName + SmartLCTViewModeBase.ProjectExtension; if (data.OperateType == OperateScreenType.CreateScreenAndOpenConfigFile) { OpenConfigFileAndHandleData(projectPath); return; } SelectedLayerAndElement selectedLayerAndElement = new SelectedLayerAndElement(); ObservableCollection<IRectElement> selectedElementCollection = new ObservableCollection<IRectElement>(); Dictionary<int, IRectElement> groupframeList = new Dictionary<int, IRectElement>(); RectLayer screen = (RectLayer)SelectedValue.ElementCollection[0]; if (data.IsCreateEmptyProject) { // 创建空工程 return; } CurrentSenderConfigInfo = data.SelectedSenderConfigInfo; //更新发送卡连线数据 MyScreen.SenderConnectInfoList.Clear(); ObservableCollection<PortConnectInfo> portConnectList = new ObservableCollection<PortConnectInfo>(); for (int i = 0; i < CurrentSenderConfigInfo.PortCount; i++) { portConnectList.Add(new PortConnectInfo(i, 0, -1, null, null, new Rect())); } MyScreen.SenderConnectInfoList.Add(new SenderConnectInfo(0, portConnectList, new Rect())); #region 添加接收卡 ObservableCollection<IElement> addCollection = new ObservableCollection<IElement>(); Point pointInCanvas = new Point(0, 0); int cols = data.Cols; int rows = data.Rows; ScannerCofigInfo scanConfig = data.SelectedScannerConfigInfo; ScanBoardProperty scanBdProp = scanConfig.ScanBdProp; int width = scanBdProp.Width; int height = scanBdProp.Height; //每个网口行的整数倍和列的整数倍 double rowIndex = -1; double colIndex = -1; //需要多少网口可以带载完 Size portLoadPoint = Function.CalculatePortLoadSize(60, 24); double portLoadSize = portLoadPoint.Height * portLoadPoint.Width; //1、需要几个网口 double portCount = Math.Ceiling(rows * cols / (portLoadSize / (height * width))); //2、计算每个网口的行列数(水平串线则是列的整数倍,垂直串线则是行的整数倍) while (true) { if (data.SelectedArrangeType == ArrangeType.LeftBottom_Hor || data.SelectedArrangeType == ArrangeType.LeftTop_Hor || data.SelectedArrangeType == ArrangeType.RightBottom_Hor || data.SelectedArrangeType == ArrangeType.RightTop_Hor)//水平串线 { rowIndex = Math.Ceiling(rows * cols / portCount / cols); if (rowIndex * cols * height * width > portLoadSize) { portCount += 1; if (portCount > data.SelectedSenderConfigInfo.PortCount) { string msg = ""; CommonStaticMethod.GetLanguageString("超出带载,请重新设置!", "Lang_ScanBoardConfigManager_OverLoad", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Warning); return; } } else { break; } } else { colIndex = Math.Ceiling(rows * cols / portCount / rows); if (colIndex * rows * height * width > portLoadSize) { portCount += 1; if (portCount > data.SelectedSenderConfigInfo.PortCount) { string msg = ""; CommonStaticMethod.GetLanguageString("超出带载,请重新设置!", "Lang_ScanBoardConfigManager_OverLoad", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Warning); return; } } else { break; } } } RectElement groupframe; if (cols == 1 && rows == 1) { groupframe = new RectElement(0, 0, width * cols, height * rows, null, -1); RectElement rectElement = new RectElement(0, 0, width * cols, height * rows, screen, screen.MaxZorder + 1); rectElement.EleType = ElementType.receive; screen.MaxZorder += 1; rectElement.Tag = scanConfig.Clone(); rectElement.IsLocked = true; rectElement.ZIndex = 4; rectElement.GroupName = -1; rectElement.ElementSelectedState = SelectedState.None; rectElement.SenderIndex = 0; rectElement.PortIndex = 0; screen.ElementCollection.Add(rectElement); selectedElementCollection.Add(rectElement); addCollection.Add(rectElement); } else { for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { RectElement rectElement = new RectElement(width * i, height * j, width, height, screen, screen.MaxZorder + 1); rectElement.EleType = ElementType.receive; screen.MaxZorder += 1; rectElement.Tag = scanConfig.Clone(); rectElement.IsLocked = true; rectElement.ZIndex = 4; rectElement.ElementSelectedState = SelectedState.None; rectElement.SenderIndex = 0; if (rowIndex != -1) { rectElement.PortIndex = (int)Math.Ceiling((j + 1) / rowIndex) - 1; } else if (colIndex != -1) { rectElement.PortIndex = (int)Math.Ceiling((i + 1) / colIndex) - 1; } screen.ElementCollection.Add(rectElement); addCollection.Add(rectElement); selectedElementCollection.Add(rectElement); } } } ////记录添加 //AddAction addAction = new AddAction(SelectedScreenLayer, addCollection); //SmartLCTActionManager.RecordAction(addAction); Dictionary<int, ObservableCollection<IRectElement>> eachPortElement = new Dictionary<int, ObservableCollection<IRectElement>>(); for (int j = 0; j < portCount; j++) { eachPortElement.Add(j, new ObservableCollection<IRectElement>()); } for (int i = 0; i < selectedElementCollection.Count; i++) { eachPortElement[selectedElementCollection[i].PortIndex].Add(selectedElementCollection[i]); } foreach (int key in eachPortElement.Keys) { if (eachPortElement[key].Count == 0) { continue; } ScreenRealParameters screenRealPara = new ScreenRealParameters(); screen.CurrentPortIndex = key; screen.CurrentSenderIndex = 0; screenRealPara.ScreenLayer = screen; screenRealPara.SelectedElement = eachPortElement[key]; #region 每个网口添加组框 Rect groupRect = new Rect(); for (int i = 0; i < screenRealPara.SelectedElement.Count; i++) { IRectElement rectElement = screenRealPara.SelectedElement[i]; rectElement.GroupName = screen.MaxGroupName + 1; Rect rect = new Rect(rectElement.X, rectElement.Y, rectElement.Width, rectElement.Height); if (i == 0) { groupRect = rect; } groupRect = Rect.Union(groupRect, rect); } groupframe = new RectElement(groupRect.X, groupRect.Y, groupRect.Width, groupRect.Height, screen, screen.MaxZorder + 1); groupframe.EleType = ElementType.groupframe; groupframe.ZIndex = 5; groupframe.GroupName = screen.MaxGroupName + 1; screen.MaxGroupName += 1; screen.MaxZorder += 1; groupframe.ElementSelectedState = SelectedState.SelectedAll; groupframeList.Add(groupframe.GroupName, groupframe); screen.ElementCollection.Add(groupframe); #endregion ScreenRealParametersValue = screenRealPara; SelectedArrangeType = data.SelectedArrangeType; IsConnectLine = !IsConnectLine; } #endregion }
public ElasticSearchGateway(IOptions <ConfigurationData> options, ILogger logger, GeometryFactory geometryFactory) { _options = options.Value; _logger = logger; _geometryFactory = geometryFactory; }
public static void Initialize() { ServerStarted = DateTime.Now; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(); Console.WriteLine(" ____ __ ________ _____ __"); Console.WriteLine(@" / __ \/ /_ _______/ ____/ |/ / / / /"); Console.WriteLine(" / /_/ / / / / / ___/ __/ / /|_/ / / / / "); Console.WriteLine(" / ____/ / /_/ (__ ) /___/ / / / /_/ / "); Console.WriteLine(@" /_/ /_/\__,_/____/_____/_/ /_/\____/ "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" " + PrettyVersion + " <Build " + PrettyBuild + ">"); Console.WriteLine(" http://PlusIndustry.com"); Console.WriteLine(""); Console.Title = "Loading Plus Emulator"; _defaultEncoding = Encoding.Default; Console.WriteLine(""); Console.WriteLine(""); CultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); try { _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"config.ini")); var connectionString = new MySqlConnectionStringBuilder { ConnectionTimeout = 10, Database = GetConfig().data["db.name"], DefaultCommandTimeout = 30, Logging = false, MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]), MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]), Password = GetConfig().data["db.password"], Pooling = true, Port = uint.Parse(GetConfig().data["db.port"]), Server = GetConfig().data["db.hostname"], UserID = GetConfig().data["db.username"], AllowZeroDateTime = true, ConvertZeroDateTime = true, }; _manager = new DatabaseManager(connectionString.ToString()); if (!_manager.IsConnected()) { log.Error("Failed to connect to the specified MySQL server."); Console.ReadKey(true); Environment.Exit(1); return; } log.Info("Connected to Database!"); //Reset our statistics first. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor()) { dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`"); dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';"); dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'"); dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'"); } //Get the configuration & Game set. ConfigData = new ConfigData(); _game = new Game(); //Have our encryption ready. HabboEncryptionV2.Initialize(new RSAKeys()); //Make sure MUS is working. MusSystem = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";")), 0); //Accept connections. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); _connectionManager.init(); _game.StartGameLoop(); TimeSpan TimeUsed = DateTime.Now - ServerStarted; Console.WriteLine(); log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)"); } catch (KeyNotFoundException e) { Logging.WriteLine("Please check your configuration file - some values appear to be missing.", ConsoleColor.Red); Logging.WriteLine("Press any key to shut down ..."); Logging.WriteLine(e.ToString()); Console.ReadKey(true); Environment.Exit(1); return; } catch (InvalidOperationException e) { Logging.WriteLine("Failed to initialize PlusEmulator: " + e.Message, ConsoleColor.Red); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); Environment.Exit(1); return; } catch (Exception e) { Logging.WriteLine("Fatal error during startup: " + e, ConsoleColor.Red); Logging.WriteLine("Press a key to exit"); Console.ReadKey(); Environment.Exit(1); } }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Services</param> public void ConfigureServices(IServiceCollection services) { ConfigurationData configData = Configuration.Get <ConfigurationData>(); // Add Identity services.AddIdentity <GoNorthUser, GoNorthRole>(options => { // Password settings options.Password.RequireDigit = true; options.Password.RequiredLength = Constants.MinPasswordLength; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; options.Password.RequireLowercase = false; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; // User settings options.User.RequireUniqueEmail = true; }).AddUserManager <GoNorthUserManager>().AddRoleManager <GoNorthRoleManager>(). AddUserStore <GoNorthUserStore>().AddRoleStore <GoNorthRoleStore>().AddErrorDescriber <GoNorthIdentityErrorDescriber>(). AddUserValidator <GoNorthUserValidator>().AddDefaultTokenProviders(); // Ensure that the correct status is returned for api calls services.ConfigureApplicationCookie(o => { o.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = (ctx) => { if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) { ctx.Response.StatusCode = 401; } else { ctx.Response.Redirect(ctx.RedirectUri); } return(Task.CompletedTask); }, OnRedirectToAccessDenied = (ctx) => { if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) { ctx.Response.StatusCode = 403; } else { ctx.Response.Redirect(ctx.RedirectUri); } return(Task.CompletedTask); } }; }); if (configData.Misc.UseGdpr) { services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.Configure <CookieTempDataProviderOptions>(options => { options.Cookie.IsEssential = true; }); } // Framework services services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // Application services services.AddTransient <IConfigViewAccess, AppSettingsConfigViewAccess>(); services.AddTransient <IProjectConfigProvider, ProjectConfigProvider>(); services.AddTransient <IEmailSender, EmailSender>(); services.AddTransient <IEncryptionService, AesEncryptionService>(); services.AddTransient <IXssChecker, XssChecker>(); services.AddTransient <ITimelineService, TimelineService>(); services.AddTransient <ITimelineTemplateService, HtmlTimelineTemplateService>(); services.AddTransient <IKortistoNpcImageAccess, KortistoFileSystemNpcImageAccess>(); services.AddTransient <IStyrItemImageAccess, StyrFileSystemItemImageAccess>(); services.AddTransient <IEvneSkillImageAccess, EvneFileSystemSkillImageAccess>(); services.AddTransient <IKirjaPageParserService, KirjaPageParserService>(); services.AddTransient <IKirjaFileAccess, KirjaFileSystemAccess>(); services.AddTransient <IKartaImageProcessor, ImageSharpKartaImageProcessor>(); services.AddTransient <IKartaImageAccess, KartaFileSystemImageAccess>(); services.AddTransient <IKartaMarkerLabelSync, KartaMarkerLabelSync>(); services.AddTransient <ITaskImageAccess, TaskImageFileSystemAccess>(); services.AddTransient <ITaskImageParser, TaskImageParser>(); services.AddTransient <ITaskNumberFill, TaskNumberFill>(); services.AddTransient <ITaskTypeDefaultProvider, TaskTypeDefaultProvider>(); services.AddTransient <IKortistoThumbnailService, ImageSharpKortistoThumbnailService>(); services.AddTransient <IEvneThumbnailService, ImageSharpEvneThumbnailService>(); services.AddTransient <IStyrThumbnailService, ImageSharpStyrThumbnailService>(); services.AddTransient <IImplementationStatusComparer, GenericImplementationStatusComparer>(); services.AddTransient <IUserCreator, UserCreator>(); services.AddTransient <IUserDeleter, UserDeleter>(); services.AddTransient <IExportTemplatePlaceholderResolver, ExportTemplatePlaceholderResolver>(); services.AddTransient <IExportDialogParser, ExportDialogParser>(); services.AddTransient <IExportDialogFunctionGenerator, ExportDialogFunctionGenerator>(); services.AddTransient <IExportDialogRenderer, ExportDialogRenderer>(); services.AddScoped <ILanguageKeyGenerator, LanguageKeyGenerator>(); services.AddScoped <ILanguageKeyReferenceCollector, LanguageKeyReferenceCollector>(); services.AddScoped <IExportDialogFunctionNameGenerator, ExportDialogFunctionNameGenerator>(); services.AddScoped <IDailyRoutineFunctionNameGenerator, DailyRoutineFunctionNameGenerator>(); services.AddTransient <IConditionRenderer, ConditionRenderer>(); services.AddTransient <IDailyRoutineEventPlaceholderResolver, DailyRoutineEventPlaceholderResolver>(); services.AddTransient <IDailyRoutineEventContentPlaceholderResolver, DailyRoutineEventContentPlaceholderResolver>(); services.AddTransient <IDailyRoutineNodeGraphRenderer, DailyRoutineNodeGraphRenderer>(); services.AddTransient <IDailyRoutineNodeGraphFunctionGenerator, DailyRoutineNodeGraphFunctionGenerator>(); services.AddScoped <IExportCachedDbAccess, ExportCachedDbAccess>(); services.AddTransient <INodeGraphExporter, NodeGraphExporter>(); services.AddTransient <INodeGraphParser, NodeGraphParser>(); services.AddTransient <IExportSnippetParser, ExportSnippetParser>(); services.AddTransient <IExportTemplateParser, ExportTemplateParser>(); services.AddTransient <IExportSnippetFunctionNameGenerator, ExportSnippetFunctionNameGenerator>(); services.AddTransient <IExportSnippetNodeGraphFunctionGenerator, ExportSnippetNodeGraphFunctionGenerator>(); services.AddTransient <IExportSnippetNodeGraphRenderer, ExportSnippetNodeGraphRenderer>(); services.AddTransient <IExportSnippetRelatedObjectUpdater, ExportSnippetRelatedObjectUpdater>(); services.AddScoped <GoNorthUserManager>(); services.AddScoped <IUserClaimsPrincipalFactory <GoNorthUser>, GoNorthUserClaimsPrincipalFactory>(); // Database services.AddScoped <ILockServiceDbAccess, LockServiceMongoDbAccess>(); services.AddScoped <IUserDbAccess, UserMongoDbAccess>(); services.AddScoped <IUserPreferencesDbAccess, UserPreferencesMongoDbAccess>(); services.AddScoped <IRoleDbAccess, RoleMongoDbAccess>(); services.AddScoped <ITimelineDbAccess, TimelineMongoDbAccess>(); services.AddScoped <IProjectDbAccess, ProjectMongoDbAccess>(); services.AddScoped <IProjectConfigDbAccess, ProjectConfigMongoDbAccess>(); services.AddScoped <IKortistoFolderDbAccess, KortistoFolderMongoDbAccess>(); services.AddScoped <IKortistoNpcTemplateDbAccess, KortistoNpcTemplateMongoDbAccess>(); services.AddScoped <IKortistoNpcDbAccess, KortistoNpcMongoDbAccess>(); services.AddScoped <IKortistoNpcTagDbAccess, KortistoNpcTagMongoDbAccess>(); services.AddScoped <IKortistoNpcImplementationSnapshotDbAccess, KortistoNpcImplementationSnapshotMongoDbAccess>(); services.AddScoped <IStyrFolderDbAccess, StyrFolderMongoDbAccess>(); services.AddScoped <IStyrItemTemplateDbAccess, StyrItemTemplateMongoDbAccess>(); services.AddScoped <IStyrItemDbAccess, StyrItemMongoDbAccess>(); services.AddScoped <IStyrItemTagDbAccess, StyrItemTagMongoDbAccess>(); services.AddScoped <IStyrItemImplementationSnapshotDbAccess, StyrItemImplementationSnapshotMongoDbAccess>(); services.AddScoped <IEvneFolderDbAccess, EvneFolderMongoDbAccess>(); services.AddScoped <IEvneSkillTemplateDbAccess, EvneSkillTemplateMongoDbAccess>(); services.AddScoped <IEvneSkillDbAccess, EvneSkillMongoDbAccess>(); services.AddScoped <IEvneSkillTagDbAccess, EvneSkillTagMongoDbAccess>(); services.AddScoped <IEvneSkillImplementationSnapshotDbAccess, EvneSkillImplementationSnapshotMongoDbAccess>(); services.AddScoped <IKirjaPageDbAccess, KirjaPageMongoDbAccess>(); services.AddScoped <IKirjaPageVersionDbAccess, KirjaPageVersionMongoDbAccess>(); services.AddScoped <IKartaMapDbAccess, KartaMapMongoDbAccess>(); services.AddScoped <IKartaMarkerImplementationSnapshotDbAccess, KartaMarkerImplementationSnapshotMongoDbAccess>(); services.AddScoped <ITaleDbAccess, TaleMongoDbAccess>(); services.AddScoped <ITaleDialogImplementationSnapshotDbAccess, TaleDialogImplementationSnapshotMongoDbAccess>(); services.AddScoped <IAikaChapterOverviewDbAccess, AikaChapterOverviewMongoDbAccess>(); services.AddScoped <IAikaChapterDetailDbAccess, AikaChapterDetailMongoDbAccess>(); services.AddScoped <IAikaQuestDbAccess, AikaQuestMongoDbAccess>(); services.AddScoped <IAikaQuestImplementationSnapshotDbAccess, AikaQuestImplementationSnapshotMongoDbAccess>(); services.AddScoped <IExportTemplateDbAccess, ExportTemplateMongoDbAccess>(); services.AddScoped <IExportDefaultTemplateProvider, ExportDefaultTemplateProvider>(); services.AddScoped <ICachedExportDefaultTemplateProvider, CachedExportDefaultTemplateProvider>(); services.AddScoped <IExportSettingsDbAccess, ExportSettingsMongoDbAccess>(); services.AddScoped <IDialogFunctionGenerationConditionDbAccess, DialogFunctionGenerationConditionMongoDbAccess>(); services.AddScoped <IDialogFunctionGenerationConditionProvider, DialogFunctionGenerationConditionProvider>(); services.AddScoped <IExportFunctionIdDbAccess, ExportFunctionIdMongoDbAccess>(); services.AddScoped <IObjectExportSnippetDbAccess, ObjectExportSnippetMongoDbAccess>(); services.AddScoped <IObjectExportSnippetSnapshotDbAccess, ObjectExportSnippetSnapshotMongoDbAccess>(); services.AddScoped <ILanguageKeyDbAccess, LanguageKeyMongoDbAccess>(); services.AddScoped <ITaskBoardDbAccess, TaskBoardMongoDbAccess>(); services.AddScoped <ITaskTypeDbAccess, TaskTypeMongoDbAccess>(); services.AddScoped <ITaskGroupTypeDbAccess, TaskGroupTypeMongoDbAccess>(); services.AddScoped <ITaskBoardCategoryDbAccess, TaskBoardCategoryMongoDbAccess>(); services.AddScoped <ITaskNumberDbAccess, TaskNumberMongoDbAccess>(); services.AddScoped <IUserTaskBoardHistoryDbAccess, UserTaskBoardHistoryMongoDbAccess>(); services.AddScoped <IDbSetup, MongoDbSetup>(); // Localization CultureInfo defaultCulture = new CultureInfo("en"); List <CultureInfo> supportedCultures = new List <CultureInfo> { new CultureInfo("de"), new CultureInfo("en") }; services.AddJsonLocalization(options => { options.FallbackCulture = defaultCulture; options.ResourcesPath = "Resources"; }); services.Configure <RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture(defaultCulture, defaultCulture); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); services.AddMvcCore().AddViewLocalization().AddMvcLocalization().AddApiExplorer().AddAuthorization().AddRazorPages().AddJsonOptions(jsonOptions => { jsonOptions.JsonSerializerOptions.PropertyNameCaseInsensitive = true; jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); // Configuration services.Configure <ConfigurationData>(Configuration); // Register the Swagger generator services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GoNorth API", Version = "v1", Description = "A portal to build storys for RPGs and other open world games.", Contact = new OpenApiContact { Name = "Steffen Nörtershäuser" }, License = new OpenApiLicense { Name = "Use under MIT", Url = new Uri("https://github.com/steffendx/GoNorth/blob/master/LICENSE") } }); string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; string commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML"; string commentsFile = Path.Combine(baseDirectory, commentsFileName); c.IncludeXmlComments(commentsFile); }); services.AddHostedService <AutoDataMigrator>(); }
private void SaveChanges() { ConfigurationData.SaveChanges(); SaveChangesButton.Enabled = ConfigurationData.HasChanges(); }
public void Initialize() { GoldTree.ServerStarted = DateTime.Now; Console.Clear(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(); Console.WriteLine(" _______ _________ ______ "); Console.WriteLine(" | _____| |___ ___| | _____|"); Console.WriteLine(" | | ___ | | | |____"); Console.WriteLine(" | | |_ | | | | ____|"); Console.WriteLine(" | |___| | | | | |____"); Console.WriteLine(" |_______| |_| |______|"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(" " + PrettyVersion); Console.WriteLine(); try { UserAdMessage = new List <string>(); WebClient client2 = new WebClient(); Stream stream2 = client2.OpenRead("https://raw.github.com/JunioriRetro/Gold-Tree-Emulator/master/useradtype.txt"); StreamReader reader2 = new StreamReader(stream2); String content2 = reader2.ReadLine(); try { UserAdType = int.Parse(content2); } catch { } WebClient client3 = new WebClient(); Stream stream3 = client3.OpenRead("https://raw.github.com/JunioriRetro/Gold-Tree-Emulator/master/useradmessage.txt"); StreamReader reader3 = new StreamReader(stream3); string line2; while ((line2 = reader3.ReadLine()) != null) { UserAdMessage.Add(line2); } WebClient client4 = new WebClient(); Stream stream4 = client4.OpenRead("https://raw.github.com/JunioriRetro/Gold-Tree-Emulator/master/useradlink.txt"); StreamReader reader4 = new StreamReader(stream4); String content4 = reader4.ReadLine(); UserAdLink = content4; try { WebClient client = new WebClient(); Stream stream = client.OpenRead("https://raw.github.com/JunioriRetro/Gold-Tree-Emulator/master/consoleads.txt"); StreamReader reader = new StreamReader(stream); string line; while ((line = reader.ReadLine()) != null) { if (line.StartsWith(":")) { string[] Params = line.Split(new char[] { ' ' }); if (Params[0] == ":textcolor") { if (!string.IsNullOrEmpty(Params[1])) { ConsoleColor Color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), Params[1]); Console.ForegroundColor = Color; } } else if (Params[0] == ":colorchangingtext") { string text = line.Substring(Params[0].Length + Params[1].Length + Params[2].Length + Params[3].Length + Params[4].Length + 5); RainbowText(text, IntToArray(Params[1]), 0, int.Parse(Params[2]), 0, int.Parse(Params[3]), bool.Parse(Params[4]), -1); } } else { Console.WriteLine(line); Console.ForegroundColor = ConsoleColor.White; } } } catch { } } catch { Console.WriteLine("Sad cant find ads :("); } Console.ResetColor(); try { GoldTree.Configuration = new ConfigurationData("config.conf"); DateTime now = DateTime.Now; //Lookds = new Random().Next(Int32.MaxValue).ToString(); DatabaseServer dbServer = new DatabaseServer(GoldTree.GetConfig().data["db.hostname"], uint.Parse(GoldTree.GetConfig().data["db.port"]), GoldTree.GetConfig().data["db.username"], GoldTree.GetConfig().data["db.password"]); Database database = new Database(GoldTree.GetConfig().data["db.name"], uint.Parse(GoldTree.GetConfig().data["db.pool.minsize"]), uint.Parse(GoldTree.GetConfig().data["db.pool.maxsize"])); GoldTree.DatabaseManager = new DatabaseManager(dbServer, database); try { using (DatabaseClient dbClient = GoldTree.GetDatabase().GetClient()) { dbClient.ExecuteQuery("UPDATE users SET online = '0'"); dbClient.ExecuteQuery("UPDATE rooms SET users_now = '0'"); DataRow DataRow; DataRow = dbClient.ReadDataRow("SHOW COLUMNS FROM `items` WHERE field = 'fw_count'"); DataRow DataRow2; DataRow2 = dbClient.ReadDataRow("SHOW COLUMNS FROM `items` WHERE field = 'extra_data'"); if (DataRow != null || DataRow2 != null) { if (DoYouWantContinue("Remember get backups before continue! Do you want continue? [Y/N]")) { if (DataRow != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("UPDATING ITEMS POSSIBLY TAKE A LONG TIME! DONT SHUTDOWN EMULATOR! PLEASE WAIT!"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("Updating items (Fireworks) ..."); dbClient.ExecuteQuery("DROP TABLE IF EXISTS items_firework"); dbClient.ExecuteQuery("CREATE TABLE IF NOT EXISTS `items_firework` (`item_id` int(10) unsigned NOT NULL, `fw_count` int(10) NOT NULL, PRIMARY KEY (`item_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;"); DataTable dataTable = dbClient.ReadDataTable("SELECT Id, fw_count FROM items;"); int fails1 = 0; if (dataTable != null) { foreach (DataRow dataRow in dataTable.Rows) { try { if (dataRow != null && !string.IsNullOrEmpty(dataRow["Id"].ToString()) && !string.IsNullOrEmpty(dataRow["fw_count"].ToString()) && (uint)dataRow["Id"] > 0 && (int)dataRow["fw_count"] > 0) { uint id = (uint)dataRow["Id"]; int wf_count = (int)dataRow["fw_count"]; if (wf_count > 0) { dbClient.AddParamWithValue("fkey" + id, id); dbClient.AddParamWithValue("fvalue" + id, wf_count); dbClient.ExecuteQuery("INSERT INTO items_firework(item_id, fw_count) VALUES (@fkey" + id + ", @fvalue" + id + ")"); } } } catch (Exception ex) { Console.WriteLine("OOPS! Error when updating.. Firework count lost :( Lets continue..."); Logging.LogItemUpdateError(ex.ToString()); fails1++; } } } if (fails1 > 0 && !DoYouWantContinue("Failed update " + fails1 + " item firework count. Do you want continue? YOU LOST THEIR ITEMS FIREWORK COUNT! [Y/N]")) { Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); GoldTree.Destroy(); Logging.WriteLine("Press any key to close window ..."); Console.ReadKey(true); Environment.Exit(0); return; } if (dataTable != null) { dataTable.Clear(); } dataTable = null; dbClient.ExecuteQuery("ALTER TABLE items DROP fw_count"); Console.WriteLine("completed!"); } if (DataRow2 != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("UPDATING ITEMS POSSIBLY TAKE A LONG TIME! DONT SHUTDOWN EMULATOR! PLEASE WAIT!"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("Updating items (Extra data) ..."); dbClient.ExecuteQuery("DROP TABLE IF EXISTS items_extra_data"); dbClient.ExecuteQuery("CREATE TABLE IF NOT EXISTS `items_extra_data` (`item_id` int(10) unsigned NOT NULL, `extra_data` text NOT NULL, PRIMARY KEY (`item_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;"); DataTable dataTable2 = dbClient.ReadDataTable("SELECT Id, extra_data FROM items;"); int fails2 = 0; if (dataTable2 != null) { foreach (DataRow dataRow in dataTable2.Rows) { try { if (dataRow != null && !string.IsNullOrEmpty(dataRow["Id"].ToString()) && !string.IsNullOrEmpty(dataRow["extra_data"].ToString()) && (uint)dataRow["Id"] > 0) { uint id = (uint)dataRow["Id"]; string extra_data = (string)dataRow["extra_data"]; if (!string.IsNullOrEmpty(extra_data)) { dbClient.AddParamWithValue("ekey" + id, id); dbClient.AddParamWithValue("evalue" + id, extra_data); dbClient.ExecuteQuery("INSERT INTO items_extra_data(item_id, extra_data) VALUES (@ekey" + id + ", @evalue" + id + ")"); } Console.WriteLine("Step 1 | ID: " + id + " | Extra data: " + extra_data); } } catch (Exception ex) { Console.WriteLine("OOPS! Error when updating.. Extra data lost :( Lets continue..."); Logging.LogItemUpdateError(ex.ToString()); fails2++; } } } if (dataTable2 != null) { dataTable2.Clear(); } dataTable2 = null; if (fails2 > 0 && !DoYouWantContinue("Failed update " + fails2 + " item extra data. Do you want continue? YOU LOST THEIR ITEMS EXTRA DATA! [Y/N]")) { Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); GoldTree.Destroy(); Logging.WriteLine("Press any key to close window ..."); Console.ReadKey(true); Environment.Exit(0); return; } dbClient.ExecuteQuery("ALTER TABLE items DROP extra_data"); Console.WriteLine("completed!"); } } else { Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); GoldTree.Destroy(); Logging.WriteLine("Press any key to close window ..."); Console.ReadKey(true); Environment.Exit(0); return; } } } //GoldTree.ConnectionManage.method_7(); GoldTree.Internal_Game.ContinueLoading(); } catch { } GoldTree.Internal_Game = new Game(int.Parse(GoldTree.GetConfig().data["game.tcp.conlimit"])); GoldTree.PacketManager = new PacketManager(); GoldTree.PacketManager.Handshake(); GoldTree.PacketManager.Messenger(); GoldTree.PacketManager.Navigator(); GoldTree.PacketManager.RoomsAction(); GoldTree.PacketManager.RoomsAvatar(); GoldTree.PacketManager.RoomsChat(); GoldTree.PacketManager.RoomsEngine(); GoldTree.PacketManager.RoomsFurniture(); GoldTree.PacketManager.RoomsPets(); GoldTree.PacketManager.RoomsPools(); GoldTree.PacketManager.RoomsSession(); GoldTree.PacketManager.RoomsSettings(); GoldTree.PacketManager.Catalog(); GoldTree.PacketManager.Marketplace(); GoldTree.PacketManager.Recycler(); GoldTree.PacketManager.Quest(); GoldTree.PacketManager.InventoryAchievements(); GoldTree.PacketManager.InventoryAvatarFX(); GoldTree.PacketManager.InventoryBadges(); GoldTree.PacketManager.InventoryFurni(); GoldTree.PacketManager.InventoryPurse(); GoldTree.PacketManager.InventoryTrading(); GoldTree.PacketManager.Avatar(); GoldTree.PacketManager.Users(); GoldTree.PacketManager.Register(); GoldTree.PacketManager.Help(); GoldTree.PacketManager.Sound(); GoldTree.PacketManager.Wired(); GoldTree.PacketManager.Jukebox(); GoldTree.MusListener = new MusListener(GoldTree.GetConfig().data["mus.tcp.bindip"], int.Parse(GoldTree.GetConfig().data["mus.tcp.port"]), GoldTree.GetConfig().data["mus.tcp.allowedaddr"].Split(new char[] { ';' }), 20); GoldTree.SocketsManager = new SocketsManager(GoldTree.GetConfig().data["game.tcp.bindip"], int.Parse(GoldTree.GetConfig().data["game.tcp.port"]), int.Parse(GoldTree.GetConfig().data["game.tcp.conlimit"])); //ConnectionManage = new ConnectionHandeling(GoldTree.GetConfig().data["game.tcp.port"], int.Parse(GoldTree.GetConfig().data["game.tcp.conlimit"]), int.Parse(GoldTree.GetConfig().data["game.tcp.conlimit"]), true); GoldTree.SocketsManager.method_3().method_0(); //ConnectionManage.init(); //ConnectionManage.Start(); /*try * { * if (int.Parse(GoldTree.GetConfig().data["automatic-error-report"]) < 1 || int.Parse(GoldTree.GetConfig().data["automatic-error-report"]) > 2) * { * Console.ForegroundColor = ConsoleColor.Red; * Logging.WriteLine("Erroreita ei raportoida automaattisesti!!!"); * Console.ForegroundColor = ConsoleColor.Gray; * } * if (int.Parse(GoldTree.GetConfig().data["automatic-error-report"]) == 1) * { * Console.ForegroundColor = ConsoleColor.Green; * Logging.WriteLine("Kaikki errorit reportoidaan automaattisesti"); * Console.ForegroundColor = ConsoleColor.Gray; * } * if (int.Parse(GoldTree.GetConfig().data["automatic-error-report"]) > 1) * { * Console.ForegroundColor = ConsoleColor.Green; * Logging.WriteLine("Vain kritikaaliset virheiden reportoidaan automaattisesti"); * Console.ForegroundColor = ConsoleColor.Gray; * } * } * catch * { * Console.ForegroundColor = ConsoleColor.Red; * Logging.WriteLine("Erroreita ei raportoida automaattisesti!!!"); * Console.ForegroundColor = ConsoleColor.Gray; * }*/ TimeSpan timeSpan = DateTime.Now - now; Logging.WriteLine(string.Concat(new object[] { "Server -> READY! (", timeSpan.Seconds, " s, ", timeSpan.Milliseconds, " ms)" })); Console.Beep(); } catch (KeyNotFoundException KeyNotFoundException) { Logging.WriteLine("Failed to boot, key not found: " + KeyNotFoundException); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); GoldTree.Destroy(); } catch (InvalidOperationException ex) { Logging.WriteLine("Failed to initialize GoldTreeEmulator: " + ex.Message); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); GoldTree.Destroy(); } }
public static void Load() { string ConfigurationData; string FileName; char[] delimiterChars = { ',', '\t' }; StreamReader MyStreamReader; string CurrentItem; string StateName = "NONE"; double Lat; double Lon; System.Collections.Generic.List <GeoCordSystemDegMinSecUtilities.LatLongClass> Sector_Points = new List <GeoCordSystemDegMinSecUtilities.LatLongClass>(); FileName = @"C:\ASTERIX\ADAPTATION\States.txt"; Exception Bad_States = new Exception("Bad States.txt file"); if (System.IO.File.Exists(FileName)) { MyStreamReader = System.IO.File.OpenText(FileName); while (MyStreamReader.Peek() >= 0) { ConfigurationData = MyStreamReader.ReadLine(); string[] words = ConfigurationData.Split(delimiterChars); if (words[0][0] != '#') { // Get Item CurrentItem = words[0]; // If the is a name, then it is a new sector if (words[0] == "STATE_NAME") { // If we have reached a new name it means that we have parsed // the data for previous sector if (StateName != "NONE") { // Now add the new sector to the data set SystemAdaptationDataSet.StateBorderDataSet.Add(new SystemAdaptationDataSet.StateBorder(StateName, Sector_Points)); // Save off the new name StateName = words[1]; // Empty the list so it is ready for the next sector Sector_Points = new List <GeoCordSystemDegMinSecUtilities.LatLongClass>(); } // This is first sector so just save off the name else { StateName = words[1]; } } // This a new point, so extract it an save it into a local list else { // Get Longitude if (double.TryParse(words[0], out Lon) == false) { throw Bad_States; } // Get Latitude if (double.TryParse(words[1], out Lat) == false) { throw Bad_States; } Sector_Points.Add((new GeoCordSystemDegMinSecUtilities.LatLongClass(Lat, Lon))); } } } // Now add the last processed sector SystemAdaptationDataSet.StateBorderDataSet.Add(new SystemAdaptationDataSet.StateBorder(StateName, Sector_Points)); } }
public static void Initialize() { ServerStarted = DateTime.Now; Console.WindowWidth = 110; Console.WindowHeight = 45; Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(@" Dual Server" + PrettyBuild + " " + VersionCloud + " / Créditos: Xjoao,Paulo!"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine( Console.LargestWindowWidth > 30 ? @"-------------------------------------------------------------------------------------------------------------" : @""); Console.WriteLine(""); _defaultEncoding = Encoding.Default; Console.Title = "Dual Server | Carregando..."; CultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); try { _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"Settings/config.ini")); var connectionString = new MySqlConnectionStringBuilder { ConnectionTimeout = 10, Database = GetConfig().data["db.name"], DefaultCommandTimeout = 30, Logging = false, MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]), MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]), Password = GetConfig().data["db.password"], Pooling = true, Port = uint.Parse(GetConfig().data["db.port"]), Server = GetConfig().data["db.hostname"], UserID = GetConfig().data["db.username"], AllowZeroDateTime = true, ConvertZeroDateTime = true, }; _manager = new DatabaseManager(connectionString.ToString()); if (!_manager.IsConnected()) { log.Warn("» Ya existe una conexión a la base de datos o hay un problema al conectarse con ella."); Console.ReadKey(true); Environment.Exit(1); return; } log.Info("» Conectado a la Base de datos!"); #region Add 2016 HotelName = Convert.ToString(GetConfig().data["hotel.name"]); Licenseto = Convert.ToString(GetConfig().data["license"]); #endregion Add 2016 //Reset our statistics first. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor()) { dbClient.runFastQuery("TRUNCATE `catalog_marketplace_data`"); dbClient.runFastQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0'"); dbClient.runFastQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'"); dbClient.runFastQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0', `status` = '1'"); } _game = new Game(); _game.ContinueLoading(); //Have our encryption ready. HabboEncryptionV2.Initialize(new RSAKeys()); //Make sure MUS is working. _rcon = new RCONSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";"))); //Accept connections. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); _connectionManager.Init(); //_game.StartGameLoop(); TimeSpan TimeUsed = DateTime.Now - ServerStarted; Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; log.Info("» CLOUD SERVER -> LISTO!! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)"); Console.ResetColor(); IsLive = true; } catch (KeyNotFoundException e) { log.ErrorFormat("Please check your configuration file - some values appear to be missing.", ConsoleColor.Red); log.Error("Press any key to shut down ..."); ExceptionLogger.LogException(e); Console.ReadKey(true); Environment.Exit(1); return; } catch (InvalidOperationException e) { log.Error("Failed to initialize CloudServer: " + e.Message); log.Error("Press any key to shut down ..."); Console.ReadKey(true); Environment.Exit(1); return; } catch (Exception e) { log.Error("Fatal error during startup: " + e); log.Error("Press a key to exit"); Console.ReadKey(); Environment.Exit(1); } }
private void NewProjectCallBack(ConfigurationData data) { if (data != null) { //新建工程 MyScreen.ElementCollection.Clear(); //更新发送卡信息 MyScreen.SenderConnectInfoList = new ObservableCollection<SenderConnectInfo>(); ObservableCollection<PortConnectInfo> portConnectInfoList = new ObservableCollection<PortConnectInfo>(); for (int i = 0; i < CurrentSenderConfigInfo.PortCount; i++) { PortConnectInfo portConnectInfo = new PortConnectInfo(i, 0, -1, null, null, new Rect()); portConnectInfoList.Add(portConnectInfo); } SenderConnectInfo senderConnectIinfo = new SenderConnectInfo(0, portConnectInfoList, new Rect()); MyScreen.SenderConnectInfoList.Add(senderConnectIinfo); RectLayer myRectLayer3 = new RectLayer(0, 0, SmartLCTViewModeBase.MaxScreenWidth + SmartLCTViewModeBase.ScrollWidth, SmartLCTViewModeBase.MaxScreenHeight + SmartLCTViewModeBase.ScrollWidth, MyScreen, 0, ElementType.baselayer, 0); RectLayer Layer3_sender1 = new RectLayer(0, 0, SmartLCTViewModeBase.MaxScreenWidth, SmartLCTViewModeBase.MaxScreenHeight, myRectLayer3, 3, ElementType.screen, 0); myRectLayer3.ElementSelectedState = SelectedState.None; myRectLayer3.ElementCollection.Add(Layer3_sender1); MyScreen.ElementCollection.Add(myRectLayer3); RectLayer newLayer = new RectLayer(0, 0, SmartLCTViewModeBase.MaxScreenWidth, SmartLCTViewModeBase.MaxScreenHeight, MyScreen, -1, ElementType.newLayer, -1); MyScreen.ElementCollection.Add(newLayer); MyConfigurationData = data; if (SelectedEnvironMentIndex == 1) { SelectedEnvironMentIndex = 1; } } }
/// <summary> /// Constructor /// </summary> /// <param name="itmWgs84MathTransfromFactory"></param> /// <param name="options"></param> public RouteDataSplitterService(IItmWgs84MathTransfromFactory itmWgs84MathTransfromFactory, IOptions <ConfigurationData> options) { _wgs84ItmMathTransform = itmWgs84MathTransfromFactory.CreateInverse(); _options = options.Value; }
protected override void Configure(ServiceLocatorRegistry registry, ConfigurationData configuration) { registry.RegisterService( typeof(ILogger).Name, locator => Task.FromResult<ILogger>(LogManager.GetLogger("Default"))); }
public ExceptionWithConfigData(string message, ConfigurationData data) : base(message) => ConfigData = data;
/// <summary> /// Open configuration editor. /// </summary> /// <param name="configuration">The configuration.</param> public virtual void EditConfiguration(ConfigurationData configuration) { throw new NotImplementedException("EditConfiguration is not implemented yet"); //MessageBox.Show("EditConfiguration is not implemented yet", "Library functionality", MessageBoxButton.OK, MessageBoxImage.Question); }
public static void Initialize() { string CurrentTime = DateTime.Now.ToString("HH:mm:ss" + " | "); ServerStarted = DateTime.Now; Console.WindowWidth = 120; Console.WindowHeight = 42; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(@" _ _ _ _ _ "); Console.WriteLine(@"| | | | __ _| |__ | |__ (_)___ "); Console.WriteLine(@"| |_| |/ _` | '_ \| '_ \| / __|"); Console.WriteLine(@"| _ | (_| | |_) | |_) | \__ \"); Console.WriteLine(@"|_| |_|\__,_|_.__/|_.__/|_|___/"); Console.WriteLine(@" "); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Emulator »"); Console.Title = "Loading Quasar Emulator"; _defaultEncoding = Encoding.Default; Console.WriteLine(""); Console.WriteLine(""); CultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); try { _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"config.ini")); var connectionString = new MySqlConnectionStringBuilder { ConnectionTimeout = 10, Database = GetConfig().data["db.name"], DefaultCommandTimeout = 30, Logging = false, MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]), MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]), Password = GetConfig().data["db.password"], Pooling = true, Port = uint.Parse(GetConfig().data["db.port"]), Server = GetConfig().data["db.hostname"], UserID = GetConfig().data["db.username"], AllowZeroDateTime = true, ConvertZeroDateTime = true, }; _manager = new DatabaseManager(connectionString.ToString()); if (!_manager.IsConnected()) { Console.WriteLine(CurrentTime + "» Kan geen verbinding maken met de database."); Console.ReadKey(true); Environment.Exit(1); return; } Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(CurrentTime + "» Heeft verbinding met de database."); Console.ResetColor(); //Reset our statistics first. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor()) { dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`"); dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';"); dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'"); dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'"); } //Get the configuration & Game set. ConfigData = new ConfigData(); _game = new Game(); //Have our encryption ready. HabboEncryptionV2.Initialize(new RSAKeys()); //Make sure MUS is working. MusSystem = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";")), 0); //Accept connections. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); _connectionManager.init(); _game.StartGameLoop(); TimeSpan TimeUsed = DateTime.Now - ServerStarted; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(CurrentTime + "» Emulator is opgestart! [" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms]"); Console.ResetColor(); } catch (KeyNotFoundException e) { Logging.WriteLine(CurrentTime + "Je configuratie is verkeerd ingesteld.", ConsoleColor.Red); Logging.WriteLine(CurrentTime + "Druk een toets in om af te sluiten.."); Logging.WriteLine(e.ToString()); Console.ReadKey(true); Environment.Exit(1); return; } catch (InvalidOperationException e) { Logging.WriteLine(CurrentTime + "Fout bij het vinden van de Emulator Key." + e.Message, ConsoleColor.Red); Logging.WriteLine(CurrentTime + "Druk een toets in om af te sluiten.."); Console.ReadKey(true); Environment.Exit(1); return; } catch (Exception e) { Logging.WriteLine(CurrentTime + "Relevante error tijdens het opstarten: " + e, ConsoleColor.Red); Logging.WriteLine(CurrentTime + "Druk een toets in om af te sluiten.."); Console.ReadKey(); Environment.Exit(1); } }
/// <summary> /// Seeds Configuration Data /// </summary> /// <param name="dataClientConfig"></param> /// <returns></returns> private async Task ConfigurationDataDemoAsync(Config.DataClientConfig dataClientConfig) { try { using (DataClient dataClient = new DataClient(dataClientConfig)) { if (dataClient.ConfigurationData != null) { ConfigurationData configurationData = dataClient.ConfigurationData; // Explicit loading. When the entity is first read, related data isn't retrieved. // Example code that retrieves the related data. It impacts retrieval performance hence only use if it's needed. await configurationData.Clients.Include(client => client.ClientSpots).LoadAsync(); await configurationData.ClientSpots.Include(clientSpot => clientSpot.Zones) .Include(clientSpot => clientSpot.LocationDevices) .Include(clientSpot => clientSpot.DisplayEndpoints) .Include(clientSpot => clientSpot.Notifications) .Include(clientSpot => clientSpot.Coupons).LoadAsync(); await configurationData.Zones.Include(zone => zone.LocationDevices) .Include(zone => zone.DisplayEndpoints).LoadAsync(); await configurationData.LocationDevices.Include(locationDevice => locationDevice.LocationDeviceNotifications).LoadAsync(); await configurationData.DisplayEndpoints.Include(displayEndpoint => displayEndpoint.DisplayEndpointNotifications).LoadAsync(); await configurationData.Notifications.Include(notification => notification.Coupons) .Include(notification => notification.LocationDeviceNotifications) .Include(notification => notification.DisplayEndpointNotifications).LoadAsync(); ///////// DB seeding with demo content ///////// // Look for any Clients if (configurationData.Clients.Any()) { string log = "Total Client found: " + configurationData.Clients.LongCount() + " | " + "Total ClientSpot found: " + configurationData.ClientSpots.LongCount() + " | " + "Total Zone found: " + configurationData.Zones.LongCount() + " | " + "Total LocationDevice found: " + configurationData.LocationDevices.LongCount() + " | " + "Total DisplayEndpoint found: " + configurationData.DisplayEndpoints.LongCount() + " | " + "Total Notification found: " + configurationData.Notifications.LongCount() + " | " + "Total Coupon found: " + configurationData.Coupons.LongCount() + " | " + "Total User found: " + configurationData.Users.LongCount(); Context.Logger.LogLine("[ConfigurationData Summary]"); Context.Logger.LogLine(log); return; // DB has been seeded already } // DB save operation Context.Logger.LogLine("[Adding contents for ConfigurationData]"); // Adding Clients var clients = new Client[] { new Client { Name = "Demo Mart", PhoneNumber = "001-123-4567", Address = "US" } }; foreach (Client client in clients) { configurationData.Clients.Add(client); } Context.Logger.LogLine("1 Client added"); // Adding ClientSpots var clientSpots = new ClientSpot[] { new ClientSpot { ClientID = clients[0].ClientID, Name = "DemoMart Seattle Store", PhoneNumber = "001-123-4567", Address = "Seattle, US" }, new ClientSpot { ClientID = clients[0].ClientID, Name = "DemoMart LA Store", PhoneNumber = "001-123-4567", Address = "LA, US" } }; foreach (ClientSpot clientSpot in clientSpots) { configurationData.ClientSpots.Add(clientSpot); } Context.Logger.LogLine("2 ClientSpots added"); // Adding Zones var zones = new Zone[] { new Zone { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Pseudo Zone" }, new Zone { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Entrance Zone (Scenario #1)" }, new Zone { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Bakery Zone (Scenario #2)" }, new Zone { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Electronics Zone (Scenario #3)" } }; foreach (Zone zone in zones) { configurationData.Zones.Add(zone); } Context.Logger.LogLine("4 Zones added"); // SAVING the changes into physical DB await configurationData.SaveChangesAsync(); // Adding LocationDevices var locationDevices = new LocationDevice[] { new LocationDevice { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[0].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "pseudo-uuid" }, new LocationDevice { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[1].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "11111111-1111-1111-1111-111111111111" }, new LocationDevice { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[2].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "22222222-2222-2222-2222-222222222222" }, new LocationDevice { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "33333333-3333-3333-3333-333333333333" }, new LocationDevice { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Type = LocationDeviceType.IBeacon, DeviceID = "44444444-4444-4444-4444-444444444444" } }; foreach (LocationDevice locationDevice in locationDevices) { configurationData.LocationDevices.Add(locationDevice); } Context.Logger.LogLine("5 LocationDevices added"); // Adding DisplayEndpoints var displayEndpoints = new DisplayEndpoint[] { new DisplayEndpoint { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[0].ZoneID, Name = "Pseudo Display" }, new DisplayEndpoint { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[1].ZoneID, Name = "Demo Display 1" }, new DisplayEndpoint { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[2].ZoneID, Name = "Demo Display 2" }, new DisplayEndpoint { ClientSpotID = clientSpots[0].ClientSpotID, ZoneID = zones[3].ZoneID, Name = "Demo Display 3" } }; foreach (DisplayEndpoint displayEndpoint in displayEndpoints) { configurationData.DisplayEndpoints.Add(displayEndpoint); } Context.Logger.LogLine("4 DisplayEndpoints added"); // Adding Notifications var notifications = new Notification[] { new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Pseduo Notification", Timeout = 10, ContentMimeType = MimeType.ImagePng, ContentSubject = "Pseduo Notification", ContentCaption = "Pseduo advertisement", ContentBody = "http://www.abc.com/images/img1.png" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 1 (Scenario #1)", SortOrder = 1, Timeout = 20, ShowProgressBar = false, ContentMimeType = MimeType.ImagePng, ContentSubject = "Welcome Greetings", ContentCaption = "Welcome to DemoMart Seattle Store!", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/welcome.png" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 2 (Scenario #2)", SortOrder = 1, Timeout = 10, ContentMimeType = MimeType.ImageJpg, ContentSubject = "Advertisement for Doughnut", ContentCaption = "4 Delicious Doughnuts", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/doughnut.jpg" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 3 (Scenario #2)", SortOrder = 2, Timeout = 10, ContentMimeType = MimeType.ImageJpg, ContentSubject = "Advertisement for Croissant", ContentCaption = "Croissant for breakfast needs", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/croissant.jpg" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 4 (Scenario #2)", SortOrder = 3, Timeout = 10, ContentMimeType = MimeType.VideoMp4, ContentSubject = "Advertisement for Coke", ContentCaption = "Taste the Feeling", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/coke.mp4" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 5 (Scenario #3)", Timeout = 10, ContentMimeType = MimeType.ImageJpeg, ContentSubject = "Advertisement for Iron", ContentCaption = "Steam Iron", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/iron.jpeg" }, new Notification { ClientSpotID = clientSpots[0].ClientSpotID, Name = "Demo Notification 6 (Scenario #3)", Timeout = 10, ContentMimeType = MimeType.ImageJpeg, ContentSubject = "Advertisement for Smartphone", ContentCaption = "Extraordinary performance", ContentBody = "https://s3.amazonaws.com/hwconscious/notifications/demo_mart/smart-phone.jpeg" } }; foreach (Notification notification in notifications) { configurationData.Notifications.Add(notification); } Context.Logger.LogLine("7 Notifications added"); // SAVING the changes into physical DB await configurationData.SaveChangesAsync(); // Adding LocationDeviceNotifications var displayEndpointNotifications = new DisplayEndpointNotification[] { new DisplayEndpointNotification { DisplayEndpointID = displayEndpoints[0].DisplayEndpointID, NotificationID = notifications[0].NotificationID }, new DisplayEndpointNotification { DisplayEndpointID = displayEndpoints[1].DisplayEndpointID, NotificationID = notifications[1].NotificationID }, new DisplayEndpointNotification { DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[2].NotificationID }, new DisplayEndpointNotification { DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[3].NotificationID }, new DisplayEndpointNotification { DisplayEndpointID = displayEndpoints[2].DisplayEndpointID, NotificationID = notifications[4].NotificationID } }; foreach (DisplayEndpointNotification displayEndpointNotification in displayEndpointNotifications) { configurationData.DisplayEndpointNotifications.Add(displayEndpointNotification); } Context.Logger.LogLine("5 DisplayEndpointNotifications added"); // Adding LocationDeviceNotifications var locationDeviceNotifications = new LocationDeviceNotification[] { new LocationDeviceNotification { LocationDeviceID = locationDevices[3].LocationDeviceID, NotificationID = notifications[5].NotificationID }, new LocationDeviceNotification { LocationDeviceID = locationDevices[4].LocationDeviceID, NotificationID = notifications[6].NotificationID } }; foreach (LocationDeviceNotification locationDeviceNotification in locationDeviceNotifications) { configurationData.LocationDeviceNotifications.Add(locationDeviceNotification); } Context.Logger.LogLine("2 LocationDeviceNotifications added"); // Adding Coupons var coupons = new Coupon[] { new Coupon { ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[0].NotificationID, Name = "Pseduo Coupon", CouponCode = "00000000000", Description = "Save $0.00", DiscountCents = 0.0 }, new Coupon { ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[2].NotificationID, Name = "Doughnut Coupon", CouponCode = "09876543210", Description = "SAVE $1.99", DiscountCents = 199.0 }, new Coupon { ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[3].NotificationID, Name = "Croissant Coupon", CouponCode = "92186293264", Description = "SAVE $0.49", DiscountCents = 49.0 }, new Coupon { ClientSpotID = clientSpots[0].ClientSpotID, NotificationID = notifications[4].NotificationID, Name = "Coke Coupon", CouponCode = "97294957293", Description = "SAVE $0.20", DiscountCents = 20.0 } }; foreach (Coupon coupon in coupons) { configurationData.Coupons.Add(coupon); } Context.Logger.LogLine("4 Coupons added"); // Adding Users var users = new User[] { new User { Type = UserType.Registered, Name = "Pseduo User", Email = "*****@*****.**" }, new User { Type = UserType.Registered, Name = "Demo User", Email = "*****@*****.**" }, new User { Type = UserType.Guest } }; foreach (User user in users) { configurationData.Users.Add(user); } Context.Logger.LogLine("3 Users added"); // SAVING the changes into physical DB await configurationData.SaveChangesAsync(); } } } catch (Exception ex) { Context.Logger.LogLine("ConfigurationData ERROR: " + ex.Message); } }
public static StringBuilder Export(string key, HashSet <Element> elements, ConfigurationData conf, Document doc) { var sbAccessories = new StringBuilder(); foreach (Element element in elements) { //Read the family and type of the element string fat = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString(); //Read element kind string kind = dw.ReadElementTypeFromDataTable(fat, conf.Elements, "KIND"); if (string.IsNullOrEmpty(kind)) { kind = dw.ReadElementTypeFromDataTable(fat, conf.Supports, "KIND"); } if (string.IsNullOrEmpty(kind)) { kind = dw.ReadElementTypeFromDataTable(fat, conf.Flexjoints, "KIND"); } if (string.IsNullOrEmpty(kind)) { throw new Exception($"{fat} is not defined in the configuration file!"); } //Support for steel frames and supports that interact with steel //For now TAG 4 parameter is used with string "FRAME" to denote steel frame support if (InputVars.IncludeSteelStructure) { if (dw.ParameterValue("", "TAG 4", element).Contains("FRAME")) { continue; } } //Write element kind sbAccessories.Append(kind); //Get the connectors var cons = Shared.MepUtils.GetConnectors(element); switch (kind) { case "ARM": case "ARMECK": sbAccessories.Append(dw.PointCoords("P1", cons.Primary)); sbAccessories.Append(dw.PointCoords("P2", cons.Secondary)); sbAccessories.Append(dw.PointCoords("PM", element)); sbAccessories.Append(dw.DnWriter("DN1", cons.Primary)); sbAccessories.Append(dw.DnWriter("DN2", cons.Secondary)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Elements, "GEW")); break; // Old SymbolicSupport cases //case "SH": //case "FH": // sbAccessories.Append(dw.PointCoords("PNAME", element)); // sbAccessories.Append(dw.ReadParameterFromDataTable(fat, conf.Supports, "L")); // sbAccessories.Append(dw.WriteElementId(element, "REF")); // sbAccessories.AppendLine(); // continue; case "SH": case "FH": sbAccessories.Append(dw.PointCoords("PNAME", element)); if (kind == "FH") { sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "CW")); } sbAccessories.Append(dw.HangerLength("L", element)); if (kind == "FH") { sbAccessories.Append(dw.ParameterValue("RF", "NTR_ELEM_RF", element)); //Installation load -- calculate beforehand } sbAccessories.Append(dw.ParameterValue("TEXT", new[] { "TAG 1", "TAG 2" }, element)); sbAccessories.Append(dw.WriteElementId(element, "REF")); sbAccessories.AppendLine(); continue; case "FP": sbAccessories.Append(dw.PointCoords("PNAME", element)); sbAccessories.Append(dw.ParameterValue("TEXT", new[] { "TAG 1", "TAG 2" }, element)); sbAccessories.Append(dw.WriteElementId(element, "REF")); sbAccessories.AppendLine(); continue; case "GL": case "FL": case "FGL": case "FFL": sbAccessories.Append(dw.PointCoords("PNAME", element)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SAV")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SAB")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MAQ")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MAV")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SQV")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SQB")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MQA")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MQV")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SVV")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "SVB")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MVA")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MVQ")); sbAccessories.Append(dw.ParameterValue("TEXT", new[] { "TAG 1", "TAG 2" }, element)); sbAccessories.Append(dw.WriteElementId(element, "REF")); sbAccessories.AppendLine(); continue; case "QS": case "QSV": case "QSVX": case "FLVXY": case "AX": case "FLAX": case "QSAX": sbAccessories.Append(dw.PointCoords("PNAME", element)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Supports, "MALL")); sbAccessories.Append(dw.ParameterValue("TEXT", new[] { "TAG 1", "TAG 2" }, element)); sbAccessories.Append(dw.WriteElementId(element, "REF")); sbAccessories.AppendLine(); continue; case "RO": //Added for preinsulated district heating pipes in Pipe Accessory category sbAccessories.Append(dw.PointCoords("P1", cons.Primary)); sbAccessories.Append(dw.PointCoords("P2", cons.Secondary)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Elements, "DN")); break; //Flexible joints hereafter case "KLAT": //Lateral kompensator sbAccessories.Append(dw.PointCoords("P1", cons.Primary)); sbAccessories.Append(dw.PointCoords("P2", cons.Secondary)); sbAccessories.Append(dw.DnWriter("DN", cons.Primary)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "GEW")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CR")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CL")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CP")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CT")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "L")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "LMAX")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "ANZRI")); break; case "KAX": //Axial kompensator sbAccessories.Append(dw.PointCoords("P1", cons.Primary)); sbAccessories.Append(dw.PointCoords("P2", cons.Secondary)); sbAccessories.Append(dw.DnWriter("DN", cons.Primary)); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "GEW")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CD")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CL")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CA")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "CT")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "A")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "L")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "D")); sbAccessories.Append(dw.ReadPropertyFromDataTable(fat, conf.Flexjoints, "DMAX")); break; default: throw new Exception($"In NTR_Accessories no switch handling for element kind: {kind}"); } sbAccessories.Append(dw.ReadPropertyFromDataTable(key, conf.Pipelines, "MAT")); //Is not required for FLABL? sbAccessories.Append(dw.ReadPropertyFromDataTable(key, conf.Pipelines, "LAST")); //Is not required for FLABL? sbAccessories.Append(dw.ParameterValue("TEXT", new[] { "TAG 1", "TAG 2" }, element)); sbAccessories.Append(dw.WriteElementId(element, "REF")); sbAccessories.Append(" LTG=" + key); sbAccessories.AppendLine(); } return(sbAccessories); }
protected BaseMetaIndexer(string name, string description, IFallbackStrategyProvider fallbackStrategyProvider, IResultFilterProvider resultFilterProvider, IIndexerConfigurationService configService, IWebClient webClient, Logger logger, ConfigurationData configData, IProtectionService p, Func <IIndexer, bool> filter) : base(name, "http://127.0.0.1/", description, configService, webClient, logger, configData, p, null, null) { filterFunc = filter; this.fallbackStrategyProvider = fallbackStrategyProvider; this.resultFilterProvider = resultFilterProvider; }
/// <summary> /// Initializes the configuration utils /// </summary> public static void Initialize() { Debug.Log("Initializing"); configurationData = new ConfigurationData(); }
// standard constructor used by most indexers public BaseIndexer(string name, string link, string description, IIndexerManagerService manager, IWebClient client, Logger logger, ConfigurationData configData, IProtectionService p, TorznabCapabilities caps = null, string downloadBase = null) : this(manager, client, logger, p) { if (!link.EndsWith("/")) { throw new Exception("Site link must end with a slash."); } DisplayName = name; DisplayDescription = description; SiteLink = link; DefaultSiteLink = link; this.downloadUrlBase = downloadBase; this.configData = configData; LoadValuesFromJson(null); if (caps == null) { caps = TorznabUtil.CreateDefaultTorznabTVCaps(); } TorznabCaps = caps; }
public void Initialize() { ServerStarted = DateTime.Now; TextManager.WritePhoenix(); try { Configuration = new ConfigurationData("config.conf"); DateTime now = DateTime.Now; Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; DatabaseServer server = new DatabaseServer(GetConfig().data["db.hostname"], uint.Parse(GetConfig().data["db.port"]), GetConfig().data["db.username"], GetConfig().data["db.password"]); Database database = new Database(GetConfig().data["db.name"], uint.Parse(GetConfig().data["db.pool.minsize"]), uint.Parse(GetConfig().data["db.pool.maxsize"])); DatabaseManager = new DatabaseManager(server, database); Game = new Game(int.Parse(GetConfig().data["game.tcp.conlimit"])); Messages = new MessageHandler(); Messages.RegisterHandshake(); Messages.RegisterMessenger(); Messages.RegisterNavigator(); Messages.RegisterRoomsAction(); Messages.RegisterRoomsAvatar(); Messages.RegisterRoomsChat(); Messages.RegisterRoomsEngine(); Messages.RegisterRoomsFurniture(); Messages.RegisterRoomsPets(); Messages.RegisterRoomsSession(); Messages.RegisterRoomsSettings(); Messages.RegisterCatalog(); Messages.RegisterMarketplace(); Messages.RegisterRecycler(); Messages.RegisterQuest(); Messages.RegisterInventoryAchievements(); Messages.RegisterInventoryAvatarFX(); Messages.RegisterInventoryBadges(); Messages.RegisterInventoryFurni(); Messages.RegisterInventoryPurse(); Messages.RegisterInventoryTrading(); Messages.RegisterAvatar(); Messages.RegisterUsers(); Messages.RegisterRegister(); Messages.RegisterHelp(); Messages.RegisterSound(); Messages.RegisterWired(); Messages.RegisterFriendStream(); //NEW! MusListener = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(new char[] { ';' }), 20); ConnectionManager = new TcpConnectionManager(GetConfig().data["game.tcp.bindip"], int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"])); ConnectionManager.GetListener().Start(); TimeSpan span = DateTime.Now - now; Logging.WriteLine(string.Concat(new object[] { "Server -> READY! (", span.Seconds, " s, ", span.Milliseconds, " ms)" })); Console.Beep(); } catch (KeyNotFoundException) { Logging.WriteLine("Failed to boot, key not found."); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); Destroy(); } catch (InvalidOperationException ex) { Logging.WriteLine("Failed to initialize PhoenixEmulator: " + ex.Message); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); Destroy(); } }
public static ConfigurationData ReadConfigurationFile( string filename ) { string[] lines = null; // Read file try { lines = System.IO.File.ReadAllLines( filename ); } catch ( FileNotFoundException fnfe ) { Console.WriteLine( "Configuration file not found." ); return null; } catch ( Exception e ) { Console.WriteLine( "Error while reading from configuration file." ); return null; } // Parse content //Puppet Master ip string pupIP = "localhost"; // Logging Level LoggingLevel level = LoggingLevel.Light; // Routing policy RoutingPolicy routing = RoutingPolicy.Flooding; // Ordering Ordering ordering = Ordering.Fifo; List<Site> sites = new List<Site>(); List<Process> processes = new List<Process>(); foreach ( string line in lines ) { if (line.StartsWith("LoggingLevel")) { Regex pattern = new Regex(@"LoggingLevel (?<type>(full|light))"); Match match = pattern.Match(line); if (match.Success) { string type = match.Groups["type"].Value; level = (type == "full" ? LoggingLevel.Full : LoggingLevel.Light); } } else if (line.StartsWith("RoutingPolicy")) { Regex pattern = new Regex(@"RoutingPolicy (?<type>(flooding|filter))"); Match match = pattern.Match(line); if (match.Success) { string type = match.Groups["type"].Value; routing = (type == "flooding" ? RoutingPolicy.Flooding : RoutingPolicy.Filter); } } else if (line.StartsWith("Ordering")) { Regex pattern = new Regex(@"Ordering (?<type>(NO|FIFO|TOTAL))"); Match match = pattern.Match(line); if (match.Success) { string type = match.Groups["type"].Value; if (type == "FIFO") { ordering = Ordering.Fifo; } else if (type == "TOTAL") { ordering = Ordering.Total; } else if (type == "NO") { ordering = Ordering.No; } } } else if (line.StartsWith("Site")) { Regex pattern = new Regex(@"Site (?<name>\w+) Parent (?<parent>(none|\w+))"); Match match = pattern.Match(line); if (match.Success) { string name = match.Groups["name"].Value; string parent = match.Groups["parent"].Value; Site parentSite = null; if (parent != "none") { parentSite = sites.Find(n => n.name == parent); } sites.Add(new Site(name, parentSite)); } } else if (line.StartsWith("Process")) { Regex pattern = new Regex(@"Process (?<name>\w+) [Ii][Ss] (?<type>(broker|publisher|subscriber)) On (?<site>\w+) URL (?<url>[\w.:/-]+)"); Match match = pattern.Match(line); if (match.Success) { string name = match.Groups["name"].Value; string type = match.Groups["type"].Value; string sitename = match.Groups["site"].Value; string url = match.Groups["url"].Value; ProcessType pType = ProcessType.Broker; if (type == "broker") { pType = ProcessType.Broker; } else if (type == "publisher") { pType = ProcessType.Publisher; } else if (type == "subscriber") { pType = ProcessType.Subscriber; } Site site = sites.Find(n => n.name == sitename); if (site == null) { return null; } Process process = new Process(name, url, site, pType); processes.Add(process); if (type == "broker") { site.broker = process; } else if (type == "publisher") { site.publishers.Add(process); } else if (type == "subscriber") { site.subscribers.Add(process); } } } else if (line.StartsWith("PMIP")) { Regex pattern = new Regex(@"PMIP (?<ip>.*)"); Match match = pattern.Match(line); if (match.Success) { pupIP = match.Groups["ip"].Value; } } } ConfigurationData data = new ConfigurationData( level, routing, ordering, pupIP ); foreach ( Site site in sites ) { data.AddSite( site ); } foreach ( Process process in processes ) { data.AddProcess( process ); } return data; }
private Configuration() : base() { _config = new ConfigurationData(); }
public void Initialize() { Essential.consoleWriter = new ConsoleWriter(Console.Out); Console.SetOut(Essential.consoleWriter); try { Console.WindowWidth = 130; Console.WindowHeight = 36; } catch { } Essential.ServerStarted = DateTime.Now; Console.Clear(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(); Console.WriteLine(@" ______ _ _ _ "); Console.WriteLine(@" | ____| | | (_) | |"); Console.WriteLine(@" | |__ ___ ___ ___ _ __ | |_ _ __ _| |"); Console.WriteLine(@" | __| / __/ __|/ _ \ '_ \| __| |/ _` | |"); Console.WriteLine(@" | |____\__ \__ \ __/ | | | |_| | (_| | |"); Console.WriteLine(@" |______|___/___/\___|_| |_|\__|_|\__,_|_|"); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(" Essential Emulator Build " + Build + " by " + Creator); Console.WriteLine(); Console.WriteLine(" Credits to: Meth0d (Uber), Sojobo (Phoenix), Juniori (GTE) & Rootkit (Essential)"); Console.WriteLine(); Console.ResetColor(); try { Essential.Configuration = new ConfigurationData("config.conf"); DateTime now = DateTime.Now; try { Essential.SWFDirectory = Essential.GetConfig().data["web.api.furni.hof_furni"]; } catch { } if (!Directory.Exists("API")) { Directory.CreateDirectory("API"); } DatabaseServer dbServer = new DatabaseServer(Essential.GetConfig().data["db.hostname"], uint.Parse(Essential.GetConfig().data["db.port"]), Essential.GetConfig().data["db.username"], Essential.GetConfig().data["db.password"]); Database database = new Database(Essential.GetConfig().data["db.name"], uint.Parse(Essential.GetConfig().data["db.pool.minsize"]), uint.Parse(Essential.GetConfig().data["db.pool.maxsize"])); Essential.DatabaseManager = new DatabaseManager(dbServer, database); GroupsPartsData.InitGroups(); try { using (DatabaseClient dbClient = Essential.GetDatabase().GetClient()) { dbClient.ExecuteQuery("SET @@global.sql_mode= '';"); dbClient.ExecuteQuery("UPDATE users SET online = '0'"); dbClient.ExecuteQuery("UPDATE rooms SET users_now = '0'"); } Essential.Internal_Game.ContinueLoading(); } catch { } Essential.Internal_Game = new Game(int.Parse(Essential.GetConfig().data["game.tcp.conlimit"])); Essential.PacketManager = new PacketManager(); Essential.PacketManager.Load(); Essential.mhandler = new MobileHandler(); Essential.mhandler.Load(); Console.WriteLine(Essential.PacketManager.Count + " Packets loaded!"); Essential.antiAdSystem = new AntiAd(); Essential.MusListener = new MusListener(Essential.GetConfig().data["mus.tcp.bindip"], int.Parse(Essential.GetConfig().data["mus.tcp.port"]), Essential.GetConfig().data["mus.tcp.allowedaddr"].Split(new char[] { ';' }), 20); Essential.SocketsManager = new SocketsManager(Essential.GetConfig().data["game.tcp.bindip"], int.Parse(Essential.GetConfig().data["game.tcp.port"]), int.Parse(Essential.GetConfig().data["game.tcp.conlimit"])); //ConnectionManage = new ConnectionHandeling(Essential.GetConfig().data["game.tcp.port"], int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]), int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]), true); Essential.HeadImagerURL = Essential.GetConfig().data["eventstream.imager.url"]; using (DatabaseClient dbClient = Essential.GetDatabase().GetClient()) { dbClient.ExecuteQuery("UPDATE server_status SET bannerdata='" + EssentialEnvironment.globalCrypto.Prime + ":" + EssentialEnvironment.globalCrypto.Generator + "';"); } Essential.SocketsManager.method_3().method_0(); webSocketServerManager = new WebSocketServerManager(Essential.GetConfig().data["websocket.url"]); Console.WriteLine("Server started at " + Essential.GetConfig().data["websocket.url"]); webManager = new WebManager(); TimeSpan timeSpan = DateTime.Now - now; Logging.WriteLine(string.Concat(new object[] { "Server -> READY! (", timeSpan.Seconds, " s, ", timeSpan.Milliseconds, " ms)" })); using (DatabaseClient dbClient = Essential.GetDatabase().GetClient()) { dbClient.ExecuteQuery("UPDATE server_status SET server_started='" + Convert.ToInt32(GetUnixTimestamp()) + "'"); } Console.Beep(); } catch (KeyNotFoundException KeyNotFoundException) { Logging.WriteLine("Failed to boot, key not found: " + KeyNotFoundException); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); Essential.Destroy(); } catch (InvalidOperationException ex) { Logging.WriteLine("Failed to initialize EssentialEmulator: " + ex.Message); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); Essential.Destroy(); } }
internal static void Initialize() { PrettyVersion = string.Format("Firewind {0}", Assembly.GetExecutingAssembly().GetName().Version); Console.Clear(); DateTime Start = DateTime.Now; SystemMute = false; ServerStarted = DateTime.Now; Console.Title = "Firewind: Loading environment."; Logging.WriteWithColor(" _______ __ __ __ ", ConsoleColor.Cyan); Logging.WriteWithColor(" | ___|__|.----.-----.--.--.--.|__|.-----.--| |", ConsoleColor.Cyan); Logging.WriteWithColor(" | ___| || _| -__| | | || || | _ |", ConsoleColor.Cyan); Logging.WriteWithColor(" |___| |__||__| |_____|________||__||__|__|_____|", ConsoleColor.Cyan); Logging.WriteLine(""); Logging.WriteLine("=============================================================="); DefaultEncoding = Encoding.Default; Logging.WriteLine(" " + PrettyVersion); Logging.WriteLine(string.Format(" Licenced to {0}", LicenseHolder)); Logging.WriteLine(string.Format(" Maximum players: {0}", MaxUsers == 0 ? "Unlimited!" : MaxUsers.ToString())); Logging.WriteLine(""); Logging.WriteLine(" Go to the GitHub repo for bug reporting/contributions!"); cultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); IsDebugging = IsDebugging ? System.Diagnostics.Debugger.IsAttached : false; try { LanguageLocale.Init(); ChatCommandRegister.Init(); PetCommandHandeler.Init(); PetLocale.Init(); if (IsDebugging) { Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings_test/configuration.ini")); } else { Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings/configuration.ini")); } DateTime Starts = DateTime.Now; Logging.WriteLine("Connecting to database..."); manager = new DatabaseManager(uint.Parse(FirewindEnvironment.GetConfig().data["db.pool.maxsize"]), int.Parse(FirewindEnvironment.GetConfig().data["db.pool.minsize"])); manager.setServerDetails( FirewindEnvironment.GetConfig().data["db.hostname"], uint.Parse(FirewindEnvironment.GetConfig().data["db.port"]), FirewindEnvironment.GetConfig().data["db.username"], FirewindEnvironment.GetConfig().data["db.password"], FirewindEnvironment.GetConfig().data["db.name"]); manager.init(); TimeSpan TimeUsed2 = DateTime.Now - Starts; Logging.WriteLine("Connected to database! (" + TimeUsed2.Seconds + " s, " + TimeUsed2.Milliseconds + " ms)"); LanguageLocale.InitSwearWord(); friendRequestLimit = (uint)(int.Parse(FirewindEnvironment.GetConfig().data["client.maxrequests"])); Game = new Game(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conlimit"])); Game.ContinueLoading(); ConnectionManager = new ConnectionHandling(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.port"]), MaxUsers, int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conperip"]), FirewindEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); ConnectionManager.init(); ConnectionManager.Start(); StaticClientMessageHandler.Initialize(); ClientMessageFactory.Init(); string[] arrayshit = FirewindEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(';'); MusSystem = new RConListener(FirewindEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(FirewindEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0); useSSO = true; if (Configuration.data.ContainsKey("auth.ssodisabled")) { if (Configuration.data["auth.ssodisabled"] == "false") { useSSO = false; } } if (Configuration.data.ContainsKey("spambans.enabled")) { if (Configuration.data["spambans.enabled"] == "true") { spamBans = true; spamBans_limit = Convert.ToInt32(Configuration.data["spambans.limit"]); Logging.WriteLine("Spam Bans enabled"); } } if (Configuration.data.ContainsKey("SeparatedTasksInMainLoops.enabled")) { if (Configuration.data["SeparatedTasksInMainLoops.enabled"] == "true") { SeparatedTasksInMainLoops = true; Logging.WriteLine("MultiTasking in MainLoop"); } } if (Configuration.data.ContainsKey("SeparatedTasksInGameClientManager.enabled")) { if (Configuration.data["SeparatedTasksInGameClientManager.enabled"] == "true") { SeparatedTasksInGameClientManager = true; Logging.WriteLine("MultiTasking in ClientManager"); } } TimeSpan TimeUsed = DateTime.Now - Start; Logging.WriteWithColor("Firewind -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)", ConsoleColor.Cyan); isLive = true; if (System.Diagnostics.Debugger.IsAttached) { Logging.WriteLine("Server is debugging: Console writing enabled", true); } else { Logging.WriteLine("Server is not debugging: Console writing disabled", false); Logging.DisablePrimaryWriting(false); } } catch (KeyNotFoundException e) { Logging.WriteLine("Please check your configuration file - some values appear to be missing."); Logging.WriteLine("Press any key to shut down ..."); Logging.WriteLine(e.ToString()); Console.ReadKey(true); FirewindEnvironment.Destroy(); return; } catch (InvalidOperationException e) { Logging.WriteLine("Failed to initialize Firewind Emulator: " + e.Message); Logging.WriteLine("Press any key to shut down ..."); Console.ReadKey(true); FirewindEnvironment.Destroy(); return; } catch (Exception e) { Logging.WriteLine("Fatal error during startup: " + e.ToString()); Logging.WriteLine("Press a key to exit"); Console.ReadKey(); Environment.Exit(1); } // Check if this is habin or not try { using (IQueryAdapter dbClient = manager.getQueryreactor()) { dbClient.setQuery("SELECT column_name FROM information_schema.columns WHERE table_schema = '" + FirewindEnvironment.GetConfig().data["db.name"] + "' AND table_name = 'users' AND column_name = 'hpo'"); IsHabin = dbClient.findsResult(); } } catch { } }
public static void Load() { string ConfigurationData; string FileName; char[] delimiterChars = { ',', '\t' }; StreamReader MyStreamReader; string ItemName; int LatDeg; int LatMin; double LatSec; GeoCordSystemDegMinSecUtilities.LatLongPrefix LatPrefix; int LonDeg; int LonMin; double LonSec; GeoCordSystemDegMinSecUtilities.LatLongPrefix LonPrefix; FileName = @"C:\ASTERIX\ADAPTATION\Waypoints.txt"; Exception Bad_Waypoints = new Exception("Bad Waypoints.txt file"); bool Is_COP; if (System.IO.File.Exists(FileName)) { MyStreamReader = System.IO.File.OpenText(FileName); while (MyStreamReader.Peek() >= 0) { ConfigurationData = MyStreamReader.ReadLine(); string[] words = ConfigurationData.Split(delimiterChars); if (words[0][0] != '#') { ItemName = words[0]; // Get Radar Name // Get Latitude if (int.TryParse(words[1], out LatDeg) == false) { throw Bad_Waypoints; } if (int.TryParse(words[2], out LatMin) == false) { throw Bad_Waypoints; } if (Double.TryParse(words[3], out LatSec) == false) { throw Bad_Waypoints; } switch (words[4]) { case "E": LatPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.E; break; case "W": LatPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.W; break; case "N": LatPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.N; break; case "S": LatPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.S; break; default: throw Bad_Waypoints; } // Get Longitude if (int.TryParse(words[5], out LonDeg) == false) { throw Bad_Waypoints; } if (int.TryParse(words[6], out LonMin) == false) { throw Bad_Waypoints; } if (Double.TryParse(words[7], out LonSec) == false) { throw Bad_Waypoints; } switch (words[8]) { case "E": LonPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.E; break; case "W": LonPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.W; break; case "N": LonPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.N; break; case "S": LonPrefix = GeoCordSystemDegMinSecUtilities.LatLongPrefix.S; break; default: throw Bad_Waypoints; } if (words[9] == "TRUE") { Is_COP = true; } else { Is_COP = false; } // Now add the radar SystemAdaptationDataSet.WaypointDataSet.Add(new SystemAdaptationDataSet.Waypoint(ItemName, new GeoCordSystemDegMinSecUtilities.LatLongClass(LatDeg, LatMin, LatSec, LatPrefix, LonDeg, LonMin, LonSec, LonPrefix), Is_COP)); } } } }
private void OnCreate() { //判断选择的路径下是否有同名文件 string filename = ProjectLocationPath + "\\" + ProjectName+".xml"; if (File.Exists(filename)) { string msg = ""; CommonStaticMethod.GetLanguageString("创建失败!目录下存在相同文件名的文件!", "Lang_ScanBoardConfigManager_SameFile", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Error); return; } if (IsCreateEmptyProject)//创建空工程 { ConfigurationData configurationData = new ConfigurationData(ProjectName, ProjectLocationPath, SelectedSenderConfigInfo, SelectedScannerConfigInfo, Rows, Cols, SelectedArrangeType, IsCreateEmptyProject, OperateType); ConfigData = configurationData; Messenger.Default.Send<object>(null, MsgToken.MSG_CLOSE_GUIDETWOFORM); return; } //判断是否超出带载(向导只支持单发送卡配置) Size portLoadPoint = Function.CalculatePortLoadSize(60,24); double portLoadSize = portLoadPoint.Width * portLoadPoint.Height; double senderLoadSize = portLoadSize * SelectedSenderConfigInfo.PortCount; ScanBoardProperty scanBdProp = SelectedScannerConfigInfo.ScanBdProp; int width = scanBdProp.Width; int height = scanBdProp.Height; double currentLoadSize = width * Cols * height * Rows; if (currentLoadSize > senderLoadSize) { string msg = ""; CommonStaticMethod.GetLanguageString("超出带载,请重新设置!", "Lang_ScanBoardConfigManager_OverLoad", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Warning); } else { //每个网口行的整数倍和列的整数倍 double rowIndex = -1; double colIndex = -1; //需要多少网口可以带载完 //1、需要几个网口 double portCount = Math.Ceiling(Rows * Cols / (portLoadSize / (height * width))); //2、计算每个网口的行列数(水平串线则是列的整数倍,垂直串线则是行的整数倍) while (true) { if (SelectedArrangeType == ArrangeType.LeftBottom_Hor || SelectedArrangeType == ArrangeType.LeftTop_Hor || SelectedArrangeType == ArrangeType.RightBottom_Hor || SelectedArrangeType == ArrangeType.RightTop_Hor)//水平串线 { rowIndex = Math.Ceiling(Rows * Cols / portCount / Cols); if (rowIndex * Cols * height * width > portLoadSize) { portCount += 1; if (portCount > SelectedSenderConfigInfo.PortCount) { string msg = ""; CommonStaticMethod.GetLanguageString("超出带载,请重新设置!", "Lang_ScanBoardConfigManager_OverLoad", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Warning); return; } } else { break; } } else { colIndex = Math.Ceiling(Rows * Cols / portCount / Rows); if (colIndex * Rows * height * width > portLoadSize) { portCount += 1; if (portCount > SelectedSenderConfigInfo.PortCount) { string msg = ""; CommonStaticMethod.GetLanguageString("超出带载,请重新设置!", "Lang_ScanBoardConfigManager_OverLoad", out msg); ShowGlobalDialogMessage(msg, MessageBoxImage.Warning); return; } } else { break; } } } //根据配置数据生成显示 ConfigurationData configurationData = new ConfigurationData(ProjectName, ProjectLocationPath, SelectedSenderConfigInfo, SelectedScannerConfigInfo, Rows, Cols, SelectedArrangeType, IsCreateEmptyProject,OperateType); ConfigData = configurationData; InsertImportCfgToDB(configurationData.SelectedScannerConfigInfo); Messenger.Default.Send<object>(null, MsgToken.MSG_CLOSE_GUIDETWOFORM); } }
public ExceptionWithConfigData(string message, ConfigurationData data) : base(message) { ConfigData = data; }
private void GetCommands() { while (!kill) { if (talker != null) { Command cmd = talker.GetCommand(); if (cmd != null) { lastMessage = DateTime.Now; ServiceActive = true; switch (cmd.CommandType) { case Commands.GetResultsResponse: Results results = (Results)cmd.Data; if (results != null) { counter++; if (results.Count > 0) UpdateDataGridViewWithResults(results.ToEnumerable()); } break; case Commands.GetConfigurationResponse: configurationData = (ConfigurationData)cmd.Data; configurationLoaded = true; if (serverMonitorList.InvokeRequired) { Invoke(new MethodInvoker(() => serverMonitorList.Rows.Clear())); } else serverMonitorList.Rows.Clear(); PopulateGridView(); configurationData.ExportToXml("configuration.xml"); //NOTE: may need to convert this to some sort of overlay window that isn't a modal dialog box so it doesn't block this thread MessageBox.Show("Configuration Retrived from the RemoteMon Service.", "Configuration Retrieved", MessageBoxButtons.OK); break; case Commands.UpdateConfigurationResponse: if ((Boolean)cmd.Data) MessageBox.Show("Configuration Updated successfully.", "Service Configuration Updated", MessageBoxButtons.OK); break; case Commands.ServiceStatus: //Boolean oldValue = serviceActive; ServiceActive = (Boolean)cmd.Data; statusBarLabelServiceStatus.Text = "Service Status: " + (ServiceActive ? "Running" : "Stopped"); if (ServiceActive && MonitorScheduler.Scheduler.Running) { Logger.Instance.Log(this.GetType(), LogType.Info, "Stopping Monitoring"); MonitorScheduler.Scheduler.Kill(); } break; case Commands.GetConfiguration: //if the service requests a configuration, then pop a dialog box asking whether or not to give it. if (!ignoreServiceConfigRequest) { DialogResult dr = MessageBox.Show( "The RemoteMon Service has requested your configuration, because it does not have any. \n\r\n\rDo you want to upload your configuration to the service?", "Service needs a configuration", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { talker.SendCommand(new Command { CommandType = Commands.GetConfigurationResponse, Data = configurationData, ToNamespace = cmd.FromNamespace, ToIp = cmd.FromIp }); synced = false; ignoreServiceConfigRequest = false; } else ignoreServiceConfigRequest = true; } break; case Commands.ResultsSyncResponse: if (cmd.Data != null && configurationLoaded) { SyncDatas servicedatas = (SyncDatas)cmd.Data; SyncDatas localdatas = new SyncDatas(); counter = servicedatas.Counter; foreach (IMonitor monitor in configurationData.ToEnumerable()) { localdatas.Add(new SyncData { FriendlyName = monitor.FriendlyName, GuidHash = monitor.Hash, IntHash = monitor.GetHashCode() }); } syncDict.Clear(); foreach (SyncData ld in localdatas) { //loop through each and create a dictionary of the guid from service to guid from local configuration SyncData local = ld; SyncData match = GetMatch(servicedatas, local); if (match != null) syncDict.Add(match.GuidHash, ld.GuidHash); //shouldn't be duplicates } //mark synced as true synced = true; } break; } } } Thread.Sleep(250); } }
private void OnCmdWizardProject() { //保存当前工程 string msg = ""; CommonStaticMethod.GetLanguageString("是否保存?", "Lang_SmartLCT_VM_IsSave", out msg); MessageBoxResult result = ShowQuestionMessage(msg, MessageBoxButton.YesNoCancel, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { //SaveSysConfigFile(MyConfigurationData.ProjectLocationPath + "\\" + MyConfigurationData.ProjectName + ".xml"); OnOtherSaveSysConfigFile(); } else if (result == MessageBoxResult.Cancel) { return; } //发送新建工程的消息,并返回新建的信息 ConfigurationData data = new ConfigurationData(); data.OperateType = OperateScreenType.UpdateScreen; NotificationMessageAction<ConfigurationData> nsa = new NotificationMessageAction<ConfigurationData>(this, data, MsgToken.MSG_SHOWGUIDETWO, NewProjectCallBack); Messenger.Default.Send(nsa, MsgToken.MSG_SHOWGUIDETWO); }
protected virtual void Configure(ServiceLocatorRegistry registry, ConfigurationData configuration) { }
/// <summary> /// Constructor /// </summary> /// <param name="optionsProvider"></param> public TagsHelper(IOptions <ConfigurationData> optionsProvider) { _iconsToTags = new Dictionary <string, IconTags>(); _options = optionsProvider.Value; // ORDER IS IMPORTNAT FOR UI, BOTH CATEGORIES AND FIRST ICON // // Water // var springIcon = new IconColorCategory { Category = Categories.WATER, Color = "blue", Icon = "icon-tint", Label = "Spring, Pond" }; _iconsToTags[springIcon.Icon] = new IconTags(springIcon, new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("natural", "spring"), new KeyValuePair <string, string>("water", "pond") }); var waterfallIcon = new IconColorCategory { Category = Categories.WATER, Color = "blue", Icon = "icon-waterfall", Label = "Waterfall" }; _iconsToTags[waterfallIcon.Icon] = new IconTags(waterfallIcon, CreateOne("waterway", "waterfall")); var waterHole = new IconColorCategory { Category = Categories.WATER, Color = "blue", Icon = "icon-waterhole", Label = "Waterhole" }; _iconsToTags[waterHole.Icon] = new IconTags(waterHole, CreateOne("natural", "waterhole")); var waterWell = new IconColorCategory { Category = Categories.WATER, Color = "blue", Icon = "icon-water-well", Label = "Water Well" }; _iconsToTags[waterWell.Icon] = new IconTags(waterWell, CreateOne("man_made", "water_well")); var cistern = new IconColorCategory { Category = Categories.WATER, Color = "blue", Icon = "icon-cistern", Label = "Cistern" }; _iconsToTags[cistern.Icon] = new IconTags(cistern, CreateOne("man_made", "cistern")); // Historic // var ruinsIcon = new IconColorCategory { Category = Categories.HISTORIC, Color = "brown", Icon = "icon-ruins", Label = "Ruins" }; _iconsToTags[ruinsIcon.Icon] = new IconTags(ruinsIcon, CreateOne("historic", "ruins")); var archaeologicalSiteIcon = new IconColorCategory { Category = Categories.HISTORIC, Color = "brown", Icon = "icon-archaeological", Label = "Archeological Site" }; _iconsToTags[archaeologicalSiteIcon.Icon] = new IconTags(archaeologicalSiteIcon, CreateOne("historic", "archaeological_site")); var memorialIcon = new IconColorCategory { Category = Categories.HISTORIC, Color = "brown", Icon = "icon-memorial", Label = "Memorial" }; _iconsToTags[memorialIcon.Icon] = new IconTags(memorialIcon, new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("historic", "memorial"), new KeyValuePair <string, string>("historic", "monument"), }); // View Point // var viewpointIcon = new IconColorCategory("icon-viewpoint", Categories.VIEWPOINT, "black", "Viewpoint"); _iconsToTags[viewpointIcon.Icon] = new IconTags(viewpointIcon, CreateOne("tourism", "viewpoint")); // Camping // var iconPicnic = new IconColorCategory { Icon = "icon-picnic", Color = "brown", Category = Categories.CAMPING, Label = "Picnic Area" }; _iconsToTags[iconPicnic.Icon] = new IconTags(iconPicnic, new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("tourism", "picnic_site"), new KeyValuePair <string, string>("leisure", "picnic"), new KeyValuePair <string, string>("leisure", "picnic_table"), }); var campsiteIcon = new IconColorCategory("icon-campsite", Categories.CAMPING, "black", "Campsite"); _iconsToTags[campsiteIcon.Icon] = new IconTags(campsiteIcon, CreateOne("tourism", "camp_site")); // Natual // var caveIcon = new IconColorCategory("icon-cave", Categories.NATURAL, "black", "Cave"); _iconsToTags[caveIcon.Icon] = new IconTags(caveIcon, CreateOne("natural", "cave_entrance")); var treeIcon = new IconColorCategory("icon-tree", Categories.NATURAL, "green", "Tree"); _iconsToTags[treeIcon.Icon] = new IconTags(treeIcon, CreateOne("natural", "tree")); var flowersIcon = new IconColorCategory("icon-flowers", Categories.NATURAL, "purple", "Flowers"); _iconsToTags[flowersIcon.Icon] = new IconTags(flowersIcon, CreateOne("natural", "flowers")); // Other // var attractionIcon = new IconColorCategory("icon-star", Categories.OTHER, "orange", "Attraction"); _iconsToTags[attractionIcon.Icon] = new IconTags(attractionIcon, CreateOne("tourism", "attraction")); var natureReserveIcon = new IconColorCategory { Icon = "icon-nature-reserve", Color = "green", Category = Categories.OTHER, Label = "Nature Reserve, National Park" }; _iconsToTags[natureReserveIcon.Icon] = new IconTags(natureReserveIcon, new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("leisure", "nature_reserve"), new KeyValuePair <string, string>("boundary", "national_park"), new KeyValuePair <string, string>("boundary", "protected_area") }); var hikingIcon = new IconColorCategory("icon-hike", Categories.ROUTE_HIKE); _iconsToTags[hikingIcon.Icon] = new IconTags(hikingIcon, CreateOne("route", "hiking")); var bicycleIcon = new IconColorCategory("icon-bike", Categories.ROUTE_BIKE); _iconsToTags[bicycleIcon.Icon] = new IconTags(bicycleIcon, new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("route", "bicycle"), new KeyValuePair <string, string>("route", "mtb") }); var fourWheelDriveIcon = new IconColorCategory("icon-four-by-four", Categories.ROUTE_4X4); _iconsToTags[fourWheelDriveIcon.Icon] = new IconTags(fourWheelDriveIcon, new List <KeyValuePair <string, string> >()); // For search but not as POI var peakIcon = new IconColorCategory("icon-peak"); _iconsToTags[peakIcon.Icon] = new IconTags(peakIcon, CreateOne("natural", "peak")); _iconsToTags[string.Empty] = new IconTags(new IconColorCategory(), new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("landuse", "farmyard"), new KeyValuePair <string, string>("waterway", "stream"), new KeyValuePair <string, string>("waterway", "river"), new KeyValuePair <string, string>("waterway", "wadi") }); }
protected virtual Task Configure(IServiceLocator locator, ConfigurationData configuration) { return Task.FromResult(0); }
private void PopulateConfigurationData(Boolean retry) { if (!File.Exists(_configPath)) { NoConfigurationFound noConfigurationFound = new NoConfigurationFound(); DialogResult dialogResult = noConfigurationFound.ShowDialog(); if (dialogResult == DialogResult.OK) { if (noConfigurationFound.File) { _configPath = noConfigurationFound.FileName; } else { if (Listener.IsLocal(noConfigurationFound.IpOrHostName)) talker = new MessageQueueTalker(Namespace.Client); else talker = new TcpTalker(noConfigurationFound.IpOrHostName, connectPort: noConfigurationFound.Port); talker.SendCommand(new Command { CommandType = Commands.GetConfiguration, Data = null, ToNamespace = Namespace.Service }); return; } } } try { if (!Directory.Exists(_path)) Directory.CreateDirectory(_path); if (!File.Exists(_configPath)) //NOTE: Create a blank configuration.xml file CreateConfigurationXml(); configurationData = ConfigurationData.LoadConfiguration(_configPath); configurationLoaded = true; if (configurationData.Settings.ClientLogPath != "") { _logPath = configurationData.Settings.ClientLogPath; Logger.Instance.SetFileName(_logPath); } } catch (Exception ex) { if (retry && (ex.InnerException != null && ex.InnerException.Message == "Root element is missing.")) { File.Delete(_configPath); //NOTE: should I be doing this? PopulateConfigurationData(false); } else { Logger.Instance.LogException(this.GetType(), ex); MessageBox.Show("Error loading configuration file - check log for details.", "Error"); } } }
public void Load( Form mainForm ) { var temp = (ConfigurationData)_config.Load( SaveFileName ); if ( temp != null ) { _config = temp; CheckUpdate( mainForm ); OnConfigurationChanged(); } else { MessageBox.Show( SoftwareInformation.SoftwareNameJapanese + " をご利用いただきありがとうございます。\r\n設定や使用方法については「ヘルプ」→「オンラインヘルプ」を参照してください。\r\nご使用の前に必ずご一読ください。", "初回起動メッセージ", MessageBoxButtons.OK, MessageBoxIcon.Information ); } }
protected BaseWebIndexer(string name, string link, string description, IIndexerConfigurationService configService, WebClient client, Logger logger, ConfigurationData configData, IProtectionService p, TorznabCapabilities caps = null, string downloadBase = null) : base(name, link, description, configService, logger, configData, p) { this.webclient = client; this.downloadUrlBase = downloadBase; if (caps == null) { caps = TorznabUtil.CreateDefaultTorznabTVCaps(); } TorznabCaps = caps; }
public XmlExport(string fileName, ConfigurationData data) { _fileName = fileName; _data = data; }
// standard constructor used by most indexers public BaseIndexer(string name, string link, string description, IIndexerConfigurationService configService, Logger logger, ConfigurationData configData, IProtectionService p) { this.logger = logger; configurationService = configService; protectionService = p; if (!link.EndsWith("/", StringComparison.Ordinal)) { throw new Exception("Site link must end with a slash."); } DisplayName = name; DisplayDescription = description; SiteLink = link; DefaultSiteLink = link; this.configData = configData; if (configData != null) { LoadValuesFromJson(null); } }
private void LoadConfigurationToolStripMenuItemClick(object sender, EventArgs e) { DialogResult dr = loadConfigurationFd.ShowDialog(); if (dr == DialogResult.OK) { try { configurationData = ConfigurationData.LoadConfiguration(loadConfigurationFd.FileName); configurationLoaded = true; } catch (Exception ex) { Logger.Instance.LogException(this.GetType(), ex); configurationLoaded = false; MessageBox.Show("Please confirm the file location and format, and try again.", "Load Configuration Failed", MessageBoxButtons.OK); } if (!ServiceActive) MonitorScheduler.Scheduler.SetMonitors(configurationData); } }
protected BaseCachingWebIndexer(string name, string link, string description, IIndexerConfigurationService configService, WebClient client, Logger logger, ConfigurationData configData, IProtectionService p, TorznabCapabilities caps = null, string downloadBase = null) : base(name, link, description, configService, client, logger, configData, p, caps, downloadBase) { }