public void Save() { ProtectedSettings toSave = new ProtectedSettings(Settings); toSave.Proxy = new ProxySetting(App.Kernel.Get <ProxyManager>().Settings); IProfileManager ProfileManager = App.Kernel.Get <IProfileManager>(); if (ProfileManager.DefaultProfile != null) { toSave.DefaultProfile = ProfileManager.DefaultProfile.Id; } if (ProfileManager.Profiles != null) { LoginManager loginManager = App.Kernel.Get <LoginManager>(); foreach (Profile profile in ProfileManager.Profiles) { ProtectedProfile protectedProfile = new ProtectedProfile(profile); LoginData login = loginManager.GetCredentials(profile); if (login != null) { protectedProfile.Login = new LoginData(login); } toSave.Profiles.Add(protectedProfile); } } new FileIOPermission(FileIOPermissionAccess.Write, SettingsFile).Assert(); XmlSerializer writer = new XmlSerializer(typeof(ProtectedSettings)); using (var file = new StreamWriter(SettingsFile)) { writer.Serialize(file, toSave); } }
private void ApplyAppTheme(ProtectedSettings ProtectedSettings) { Tuple <AppTheme, Accent> currentTheme = ThemeManager.DetectAppStyle(Application.Current); if (currentTheme == null) { return; } AppTheme appTheme = null; Accent themeAccent = null; if (ProtectedSettings.AppTheme != null) { appTheme = ThemeManager.GetAppTheme(ProtectedSettings.AppTheme); } if (appTheme == null) { appTheme = currentTheme.Item1; } if (ProtectedSettings.ThemeAccent != null) { themeAccent = ThemeManager.GetAccent(ProtectedSettings.ThemeAccent); } if (themeAccent == null) { themeAccent = currentTheme.Item2; } ProtectedSettings.AppTheme = appTheme.Name; ProtectedSettings.ThemeAccent = themeAccent.Name; ThemeManager.ChangeAppStyle(Application.Current, themeAccent, appTheme); }
private void InitializeSafeSettings(ProtectedSettings settings) { _Settings = new Settings(); _Settings.AppTheme = settings.AppTheme; _Settings.LanguageFile = settings.Language; _Settings.ThemeAccent = settings.ThemeAccent; _Settings.CheckForUpdates = settings.CheckForUpdates; _Settings.Profiles = new List <Profile>(); LoginManager loginManager = App.Kernel.Get <LoginManager>(); if (settings.Profiles != null) { foreach (ProtectedProfile protectedProfile in settings.Profiles) { Profile safeProfile = new Profile(); safeProfile.Id = protectedProfile.Id; safeProfile.Name = protectedProfile.Name; safeProfile.ImagePath = protectedProfile.ImagePath; safeProfile.KBLCServiceEnabled = protectedProfile.KBLCServiceEnabled; safeProfile.UpdateEngineEnabled = protectedProfile.UpdateEngineEnabled; safeProfile.LaunchMode = protectedProfile.LaunchMode; safeProfile.GameModel = new GameModel(protectedProfile.GameModel); safeProfile.News = new NewsData(protectedProfile.News); safeProfile.Rotation = new RotationData(protectedProfile.Rotation); _Settings.Profiles.Add(safeProfile); if (safeProfile.Id == settings.DefaultProfile) { _Settings.DefaultProfile = safeProfile; } loginManager.UpdateCredentials(safeProfile, new LoginData(protectedProfile.Login)); } } }
private void ApplyProxySettings(ProtectedSettings settings) { ProxyManager pManager = App.Kernel.Get <ProxyManager>(); if (settings.Proxy == null) { settings.Proxy = new ProxySetting(); } pManager.Initialize(settings.Proxy); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); writer.WritePropertyName("extensionParameters"); writer.WriteStartObject(); if (Optional.IsDefined(ForceUpdateTag)) { writer.WritePropertyName("forceUpdateTag"); writer.WriteStringValue(ForceUpdateTag); } if (Optional.IsDefined(Publisher)) { writer.WritePropertyName("publisher"); writer.WriteStringValue(Publisher); } if (Optional.IsDefined(TypePropertiesExtensionParametersType)) { writer.WritePropertyName("type"); writer.WriteStringValue(TypePropertiesExtensionParametersType); } if (Optional.IsDefined(TypeHandlerVersion)) { writer.WritePropertyName("typeHandlerVersion"); writer.WriteStringValue(TypeHandlerVersion); } if (Optional.IsDefined(AutoUpgradeMinorVersion)) { writer.WritePropertyName("autoUpgradeMinorVersion"); writer.WriteBooleanValue(AutoUpgradeMinorVersion.Value); } if (Optional.IsDefined(Settings)) { writer.WritePropertyName("settings"); #if NET6_0_OR_GREATER writer.WriteRawValue(Settings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(Settings.ToString()).RootElement); #endif } if (Optional.IsDefined(ProtectedSettings)) { writer.WritePropertyName("protectedSettings"); #if NET6_0_OR_GREATER writer.WriteRawValue(ProtectedSettings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(ProtectedSettings.ToString()).RootElement); #endif } writer.WriteEndObject(); writer.WriteEndObject(); writer.WriteEndObject(); }
private void ValidateSettings(ProtectedSettings settings) { if (settings.Proxy == null) { settings.Proxy = new ProxySetting(); } ProxySetting proxy = settings.Proxy; if (Uri.CheckHostName(proxy.Host) == UriHostNameType.Unknown) { proxy.Host = string.Empty; } if (proxy.Port < 0 || proxy.Port > 65535) { proxy.Port = 8080; } if (settings.Profiles != null) { TwitterNameValidation twitterValidator = new TwitterNameValidation(); GuildNameValidationRule guildNameValidator = new GuildNameValidationRule(); foreach (var profile in settings.Profiles) { if (profile.News == null) { profile.News = new NewsData(); } if (profile.Login == null) { profile.Login = new LoginData(); } if (profile.Rotation == null) { profile.Rotation = new RotationData(); } if (profile.GameModel == null) { profile.GameModel = new GameModel(); } if (!twitterValidator.Validate(profile.News.TwitterUser, null).IsValid) { profile.News.TwitterUser = Utils.GetDefaultTwitter(); } if (profile.Rotation.Guild != null) { if (!guildNameValidator.Validate(profile.Rotation.Guild, null).IsValid) { profile.Rotation.Guild = string.Empty; } } } } }
private static ProtectedSettings DeSerializeSettings(string filepath) { ProtectedSettings settings = new ProtectedSettings(); if (File.Exists(filepath)) { XmlSerializer reader = new XmlSerializer(typeof(ProtectedSettings)); using (var file = new StreamReader(filepath)) { settings = (ProtectedSettings)reader.Deserialize(file); } } return(settings); }
public void Initialize() { AppPath = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory); AppDataPath = InitFolder(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), Path.Combine("GoldRenard", "AdvancedLauncher")); LanguagesPath = InitFolder(AppPath, LOCALE_DIR); Resources3rdPath = InitFolder(AppDataPath, RESOURCE_DIR); ResourcesPath = InitFolder(AppPath, RESOURCE_DIR); PluginsPath = InitFolder(AppPath, PLUGINS_DIR); AppDomain.CurrentDomain.SetData("DataDirectory", AppDataPath); // Initialize ProtectedSettings entity ProtectedSettings ProtectedSettings = null; if (File.Exists(SettingsFile)) { try { ProtectedSettings = DeSerializeSettings(SettingsFile); } catch (Exception) { // fall down and recreate settings file } } bool createSettingsFile = ProtectedSettings == null; if (createSettingsFile) { ProtectedSettings = new ProtectedSettings(); } ValidateSettings(ProtectedSettings); ApplyAppTheme(ProtectedSettings); ApplyProxySettings(ProtectedSettings); InitializeSafeSettings(ProtectedSettings); LanguageManager LM = LanguageManager as LanguageManager; if (LM != null) { Settings.LanguageFile = LM.Initialize(InitFolder(AppPath, LOCALE_DIR), _Settings.LanguageFile); } if (createSettingsFile) { Save(); } }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(ForceUpdateTag)) { writer.WritePropertyName("forceUpdateTag"); writer.WriteStringValue(ForceUpdateTag); } if (Optional.IsDefined(Publisher)) { writer.WritePropertyName("publisher"); writer.WriteStringValue(Publisher); } if (Optional.IsDefined(TypePropertiesType)) { writer.WritePropertyName("type"); writer.WriteStringValue(TypePropertiesType); } if (Optional.IsDefined(TypeHandlerVersion)) { writer.WritePropertyName("typeHandlerVersion"); writer.WriteStringValue(TypeHandlerVersion); } if (Optional.IsDefined(AutoUpgradeMinorVersion)) { writer.WritePropertyName("autoUpgradeMinorVersion"); writer.WriteBooleanValue(AutoUpgradeMinorVersion.Value); } if (Optional.IsDefined(EnableAutomaticUpgrade)) { writer.WritePropertyName("enableAutomaticUpgrade"); writer.WriteBooleanValue(EnableAutomaticUpgrade.Value); } if (Optional.IsDefined(Settings)) { writer.WritePropertyName("settings"); #if NET6_0_OR_GREATER writer.WriteRawValue(Settings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(Settings.ToString()).RootElement); #endif } if (Optional.IsDefined(ProtectedSettings)) { writer.WritePropertyName("protectedSettings"); #if NET6_0_OR_GREATER writer.WriteRawValue(ProtectedSettings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(ProtectedSettings.ToString()).RootElement); #endif } if (Optional.IsCollectionDefined(ProvisionAfterExtensions)) { writer.WritePropertyName("provisionAfterExtensions"); writer.WriteStartArray(); foreach (var item in ProvisionAfterExtensions) { writer.WriteStringValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(SuppressFailures)) { writer.WritePropertyName("suppressFailures"); writer.WriteBooleanValue(SuppressFailures.Value); } writer.WriteEndObject(); writer.WriteEndObject(); }
static void Main(string[] args) { var random = new Random(); // ********* Builder(Fluent) Pattern Usage: START ********* // creating dummy data for products simulation int capacity = 3; var products = new List <Product>(capacity); for (int i = 1; i <= capacity; i++) { products.Add( new Product { Id = Guid.NewGuid(), Name = $"Product {i}", Price = Math.Round(random.NextDouble() * 100, 2), NumberInStock = random.Next(100) }); } // creation of builder is mandatory. because we use it when we create manager for report builder var builder = new ProductStockReportBuilder(products); var manager = new ProductStockReportManager(builder); // report is generated by manager manager.BuildReport(); var productsReport = builder.GetReport(); Console.WriteLine(productsReport); // ********* Builder(Fluent) Pattern Usage: END ********* // ------------------------------------------------------------------------- // ********* Fluent Builder Interface with Recursive Generics Pattern Usage: START ********* var emp = EmployeeBuilderManager.NewEmployee .WithFirstName("Nuran").WithLastName("Tarlan").WithAge(18) .WithEMail("*****@*****.**") .WithMainPhone("xxx-xxx-xx-xx").WithBackupPhone("xxx-xxx-xx-xx") .AtPosition(Positions.FullStackDeveloper).WithSalary(500).Build(); Console.WriteLine(emp); // ********* Fluent Builder Interface with Recursive Generics Pattern Usage: END ********* // ------------------------------------------------------------------------- // ********* Faceted Builder Pattern Usage: START var car = new CarBuilderFacade() .Info.WithBrand(CarBrands.Subaru).WithModel("Impreza").CreatedAt(2003).WithDistance(186522.5) .Engine.WithEngine(1800).WithHorsePower(422).WithTorque(600) .Trade.WithPrice(18000.0m).IsSecondHand(true) .Address.InCity("Baku").InDealer("Subaru XXXXX-XX") .Build(); Console.WriteLine(car); // ********* Faceted Builder Pattern Usage: END // ------------------------------------------------------------------------- // ********* Factory Method Pattern Usage: START AirConditioner.InitializeFactories() .ExecuteCreation(Actions.Cooling, 20.2) .Operate(); // ********* Factory Method Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Singleton Pattern Usage: START var db1 = SingletonDataContainer.GetInstance; Console.WriteLine($"Population of Sumqayit: {db1.GetPopulation("Sumqayit")}"); var db2 = SingletonDataContainer.GetInstance; Console.WriteLine($"Baku: {db2.GetPopulation("Baku")} people"); // ********* Singleton Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Adapter Pattern Usage: START var xmlConverter = new CustomXmlConverter(); var adapter = new XmlToJsonAdapter(xmlConverter); adapter.ConvertXmlToJson(); // ********* Adapter Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Composite Pattern Usage: START // single gift var phone = new SingleGift("Phone", 500); phone.CalculateTotalPrice(); Console.WriteLine(); // composite many gifts together var rootBox = new CompositeGift("Surprise Box for Teenagers", true); var truckToy = new SingleGift("Truck Toy", 220); var plainToy = new SingleGift("Plain Toy", 89); rootBox.Add(truckToy); rootBox.Add(plainToy); var childBox = new CompositeGift("Surprise Box for Children", false); var soldierToy = new SingleGift("Soldier Toy", 15); childBox.Add(soldierToy); rootBox.Add(childBox); rootBox.CalculateTotalPrice(); // ********* Composite Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Decorator Pattern Usage: START var regularOrder = new RegularOrder(); Console.WriteLine(regularOrder.CalculateTotalOrderPrice() + "\n"); var preOrder = new PreOrder(); Console.WriteLine(preOrder.CalculateTotalOrderPrice() + "\n"); var premiumPreOrder = new PremiumPreOrder(preOrder); Console.WriteLine(premiumPreOrder.CalculateTotalOrderPrice()); // ********* Decorator Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Command Pattern Usage: START var modifyPrice = new ModifyPrice(); var product = new Product2("Phone", 500); modifyPrice.Execute(new ProductCommand(product, PriceAction.Increase, 100)); modifyPrice.Execute(new ProductCommand(product, PriceAction.Decrease, 700)); modifyPrice.Execute(new ProductCommand(product, PriceAction.Decrease, 20)); Console.WriteLine(product); modifyPrice.UndoActions(); Console.WriteLine(product); // ********* Command Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Strategy Pattern Usage: START var reports = new List <DeveloperReport> { new DeveloperReport { Id = 1, Name = "Dev1", Level = DeveloperLevel.Senior, HourlyRate = 30.5, WorkingHours = 160 }, new DeveloperReport { Id = 2, Name = "Dev2", Level = DeveloperLevel.Junior, HourlyRate = 20, WorkingHours = 120 }, new DeveloperReport { Id = 3, Name = "Dev3", Level = DeveloperLevel.Senior, HourlyRate = 32.5, WorkingHours = 130 }, new DeveloperReport { Id = 4, Name = "Dev4", Level = DeveloperLevel.Junior, HourlyRate = 24.5, WorkingHours = 140 } }; var calculatorContext = new SalaryCalculator(new JuniorDeveloperSalaryCalculator()); var juniorTotal = calculatorContext.Calculate(reports); Console.WriteLine($"Total amount for junior salaries is: {juniorTotal}"); calculatorContext.SetCalculator(new SeniorDeveloperSalaryCalculator()); var seniorTotal = calculatorContext.Calculate(reports); Console.WriteLine($"Total amount for senior salaries is: {seniorTotal}"); Console.WriteLine($"Total cost for all the salaries is: {juniorTotal + seniorTotal}"); // ********* Strategy Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Facade Pattern Usage: START var facade = new Facade.Facade(); var chickenOrder = new Order() { DishName = "Chicken with rice", DishPrice = 20.0, User = "******", ShippingAddress = "Random street 123" }; var sushiOrder = new Order() { DishName = "Sushi", DishPrice = 52.0, User = "******", ShippingAddress = "More random street 321" }; facade.OrderFood(new List <Order> { chickenOrder, sushiOrder }); // ********* Facade Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Prototype Pattern Usage: START var grid = new List <IBlock>(); grid.AddRange(new List <IBlock> { BlockFactory.Create("Hello, world!"), BlockFactory.Create("3"), BlockFactory.Create("16/05/2002"), // datetime BlockFactory.Create("08/22/2021") // string, because 12 month exist in calendar }); foreach (var block in grid) { Console.WriteLine(block); } var block5 = (DateTimeBlock)grid[2].Clone(); block5.Format = "MM/dd/yyyy"; grid.Add(block5); Console.WriteLine("\nblock5 is added..."); Console.WriteLine(block5); var block6 = (DateTimeBlock)grid[4].Clone(); block6.DateTime = DateTime.UtcNow; grid.Add(block6); Console.WriteLine("\nblock6 is added..."); Console.WriteLine(block6); // ********* Prototype Pattern Usage: END // ------------------------------------------------------------------------- Console.WriteLine("\n-------------------------------\n"); // ********* Protection-Proxy Pattern Usage: START var settings = new Settings("settings config"); Console.WriteLine(settings.GetConfig()); var authService = new AuthService(); var protectedSettings = new ProtectedSettings(authService); Console.WriteLine(protectedSettings.GetConfig()); // ********* Protection-Proxy Pattern Usage: END // ********* Iterator Pattern Usage: START var numbers = new CustomLinkedList <int>(1); for (int i = 2; i < 8; i++) { numbers.Add(i); } var iterator = numbers.Iterator; while (!iterator.Complete) { Console.WriteLine(iterator.Next()); } // Exception will be thrown // Console.WriteLine(iterator.Next()); // ********* Iterator Pattern Usage: END }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("tags"); writer.WriteStartObject(); foreach (var item in Tags) { writer.WritePropertyName(item.Key); writer.WriteStringValue(item.Value); } writer.WriteEndObject(); writer.WritePropertyName("location"); writer.WriteStringValue(Location); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(ForceUpdateTag)) { writer.WritePropertyName("forceUpdateTag"); writer.WriteStringValue(ForceUpdateTag); } if (Optional.IsDefined(Publisher)) { writer.WritePropertyName("publisher"); writer.WriteStringValue(Publisher); } if (Optional.IsDefined(MachineExtensionType)) { writer.WritePropertyName("type"); writer.WriteStringValue(MachineExtensionType); } if (Optional.IsDefined(TypeHandlerVersion)) { writer.WritePropertyName("typeHandlerVersion"); writer.WriteStringValue(TypeHandlerVersion); } if (Optional.IsDefined(AutoUpgradeMinorVersion)) { writer.WritePropertyName("autoUpgradeMinorVersion"); writer.WriteBooleanValue(AutoUpgradeMinorVersion.Value); } if (Optional.IsDefined(Settings)) { writer.WritePropertyName("settings"); #if NET6_0_OR_GREATER writer.WriteRawValue(Settings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(Settings.ToString()).RootElement); #endif } if (Optional.IsDefined(ProtectedSettings)) { writer.WritePropertyName("protectedSettings"); #if NET6_0_OR_GREATER writer.WriteRawValue(ProtectedSettings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(ProtectedSettings.ToString()).RootElement); #endif } if (Optional.IsDefined(InstanceView)) { writer.WritePropertyName("instanceView"); writer.WriteObjectValue(InstanceView); } writer.WriteEndObject(); writer.WriteEndObject(); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(ForceUpdateTag)) { writer.WritePropertyName("forceUpdateTag"); writer.WriteStringValue(ForceUpdateTag); } if (Optional.IsDefined(Publisher)) { writer.WritePropertyName("publisher"); writer.WriteStringValue(Publisher); } if (Optional.IsDefined(ExtensionType)) { writer.WritePropertyName("type"); writer.WriteStringValue(ExtensionType); } if (Optional.IsDefined(TypeHandlerVersion)) { writer.WritePropertyName("typeHandlerVersion"); writer.WriteStringValue(TypeHandlerVersion); } if (Optional.IsDefined(AutoUpgradeMinorVersion)) { writer.WritePropertyName("autoUpgradeMinorVersion"); writer.WriteBooleanValue(AutoUpgradeMinorVersion.Value); } if (Optional.IsDefined(EnableAutomaticUpgrade)) { writer.WritePropertyName("enableAutomaticUpgrade"); writer.WriteBooleanValue(EnableAutomaticUpgrade.Value); } if (Optional.IsDefined(Settings)) { writer.WritePropertyName("settings"); #if NET6_0_OR_GREATER writer.WriteRawValue(Settings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(Settings.ToString()).RootElement); #endif } if (Optional.IsDefined(ProtectedSettings)) { writer.WritePropertyName("protectedSettings"); #if NET6_0_OR_GREATER writer.WriteRawValue(ProtectedSettings); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(ProtectedSettings.ToString()).RootElement); #endif } if (Optional.IsDefined(InstanceView)) { writer.WritePropertyName("instanceView"); writer.WriteObjectValue(InstanceView); } if (Optional.IsDefined(SuppressFailures)) { writer.WritePropertyName("suppressFailures"); writer.WriteBooleanValue(SuppressFailures.Value); } if (Optional.IsDefined(ProtectedSettingsFromKeyVault)) { writer.WritePropertyName("protectedSettingsFromKeyVault"); #if NET6_0_OR_GREATER writer.WriteRawValue(ProtectedSettingsFromKeyVault); #else JsonSerializer.Serialize(writer, JsonDocument.Parse(ProtectedSettingsFromKeyVault.ToString()).RootElement); #endif } writer.WriteEndObject(); writer.WriteEndObject(); }