public void Save(string location, bool saveDatabases = true) { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(dec); XmlElement conf = doc.CreateElement("Configuration"); doc.AppendChild(conf); XmlAttribute wh = doc.CreateAttribute("WindowHeight"); wh.Value = WindowHeight.ToString(); conf.Attributes.Append(wh); XmlAttribute em = doc.CreateAttribute("ExitMode"); em.Value = ExitMode.ToString(); conf.Attributes.Append(em); XmlAttribute cul = doc.CreateAttribute("Culture"); cul.Value = Thread.CurrentThread.CurrentCulture.Name; conf.Attributes.Append(cul); foreach (Database item in Databases) { if (saveDatabases) { item.Save(); } if (item.Location == null) { continue; } XmlElement db = doc.CreateElement("Database"); conf.AppendChild(db); XmlAttribute loc = doc.CreateAttribute("Location"); loc.Value = Path.GetFullPath(item.Location); db.Attributes.Append(loc); if (item.SavePassword) { XmlAttribute pass = doc.CreateAttribute("Password"); string password; if (CryptoHelper.Encrypt(item.Password, ManagerFactory.PasswordCrypto, out password)) { pass.Value = password; db.Attributes.Append(pass); } } } doc.Save(location); }
public void SaveSettings() { new XDocument( new XElement(Tag_Root, new XElement(Tag_NamedPipeAddress, NamedPipeAddress), new XElement(Tag_AutoConnect, AutoConnect.ToString()), new XElement(Tag_TimePaddingForLoop, TimePaddingForLoop.ToString()), new XElement(Tag_LoopSelection, LoopSelection.ToString()), new XElement(Tag_LoopNumber, LoopNumber.ToString()), new XElement(Tag_PlayMode, PlayMode.ToString()), new XElement(Tag_Volume, new XElement(Tag_VolumeValue, VolumeValue.ToString()), new XElement(Tag_VolumeMute, VolumeMute.ToString())), new XElement(Tag_Documents, DocumentByDocumentGuid.Select(x => new XElement(Tag_Document, new XAttribute(Att_Document_Id, x.Key), new XElement(Tag_Document_Name, x.Value.Name), new XElement(Tag_Media, x.Value.Media)))), new XElement(Tag_MinimalSeverityToShowInLog, MinimalSeverityToShowInLog.ToString()), new XElement(Tag_Window, new XElement(Tag_Top, WindowTop.ToString()), new XElement(Tag_Left, WindowLeft.ToString()), new XElement(Tag_Width, WindowWidth.ToString()), new XElement(Tag_Height, WindowHeight.ToString()), new XElement(Tag_Maximized, WindowMaximized.ToString()), new XElement(Tag_AlwaysOnTop, AlwaysOnTop.ToString())), new XElement(Tag_VlcLibPath, VlcLibPath), new XElement(Tag_DoNotAskAgain, FontMissingWindowDoNotAskAgain.ToString())) ).Save(SettingsPath); }
public void RewriteConfig() { SetConfigField("CertificateStore", CertificateStore.ToString()); SetConfigField("CertificateItem", CertificateItem.ToString()); SetConfigField("WindowHeight", WindowHeight.ToString()); SetConfigField("WindowWidth", WindowWidth.ToString()); SetConfigField("WindowLeft", WindowLeft.ToString()); SetConfigField("WindowTop", WindowTop.ToString()); saveChangesToConfig(); }
private void Save_Settings(object sender, RoutedEventArgs e) { var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfg.AppSettings.Settings["listboxitemwidth"].Value = ListBoxItemWidth.ToString(); cfg.AppSettings.Settings["listboxitemheight"].Value = ListBoxItemHeight.ToString(); cfg.AppSettings.Settings["listboxitemimageheight"].Value = ListBoxItemImageHeight.ToString(); cfg.AppSettings.Settings["windowwidth"].Value = WindowWidth.ToString(); cfg.AppSettings.Settings["windowheight"].Value = WindowHeight.ToString(); cfg.Save(); }
public string ConfigDump() { StringBuilder configBuilder = new StringBuilder(); configBuilder.AppendLine(String.Empty); configBuilder.AppendLine("Configuration Dump"); configBuilder.AppendLine("WaitTimeToKillOrigin = " + WaitTimeToKillOrigin.ToString()); configBuilder.AppendLine("FullscreenMode = " + FullscreenMode.ToString()); configBuilder.AppendLine("WindowHeight = " + WindowHeight.ToString()); configBuilder.AppendLine("WindowWidth = " + WindowWidth.ToString()); configBuilder.AppendLine("ManageOrigin = " + ManageOrigin.ToString()); configBuilder.AppendLine("DisableHardwareAccel = " + DisableHardwareAccel.ToString()); return(configBuilder.ToString()); }
public void SaveSettings(object sender, RoutedEventArgs e) { DataBase.SetSetting("WIDTH", WindowWidth.ToString()); DataBase.SetSetting("HEIGHT", WindowHeight.ToString()); DataBase.SetSetting("COLS", ColumnCount.ToString()); DataBase.SetSetting("ROWS", RowCount.ToString()); DataBase.SetSetting("TOPMOST", IsTopMost ? "TRUE" : "FALSE"); DataBase.SetSetting("STARTUP", StartUp ? "TRUE" : "FALSE"); InstallStartUp(StartUp); DataBase.SetTabs(Tabs); // 재시작 System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); }
public void SaveSettings() { new XDocument( new XElement(Tag_Root, new XElement(Tag_NamedPipeAddress, NamedPipeAddress), new XElement(Tag_AutoConnect, AutoConnect.ToString()), new XElement(Tag_MinimalSeverityToShowInLog, MinimalSeverityToShowInLog.ToString()), new XElement(Tag_Window, new XElement(Tag_Top, WindowTop.ToString()), new XElement(Tag_Left, WindowLeft.ToString()), new XElement(Tag_Width, WindowWidth.ToString()), new XElement(Tag_Height, WindowHeight.ToString()), new XElement(Tag_Maximized, WindowMaximized.ToString()), new XElement(Tag_AlwaysOnTop, AlwaysOnTop.ToString()))) ).Save(SettingsPath); }
public string ConfigDump() { StringBuilder configBuilder = new StringBuilder(); configBuilder.AppendLine(String.Empty); configBuilder.AppendLine("Configuration Dump"); configBuilder.AppendLine("DirectToCampaign = " + DirectToCampaign.ToString()); configBuilder.AppendLine("CustomJsEnabled = " + CustomJsEnabled.ToString()); configBuilder.AppendLine("WaitTimeToKillOrigin = " + WaitTimeToKillOrigin.ToString()); configBuilder.AppendLine("WindowedMode = " + WindowedMode.ToString()); configBuilder.AppendLine("StatMaximized = " + StartMaximized.ToString()); configBuilder.AppendLine("WindowHeight = " + WindowHeight.ToString()); configBuilder.AppendLine("WindowWidth = " + WindowWidth.ToString()); configBuilder.AppendLine("HandleOrigin = " + HandleOrigin.ToString()); return(configBuilder.ToString()); }
public override void Update() { SettingNode root = new SettingNode(Xml_SettingRootName); root.SetAttribute(Xml_ActiveUserNodeName, ActiveUser); root.SetAttribute(Xml_ExportFolder, exportworkFolder); root.SetAttribute(Xml_SimpleMode, SimpleMode.ToString()); SettingNode window = new SettingNode(Xml_WindowSettingRoot); window.SetAttribute(Xml_WindowLocX, WindowLeft.ToString()); window.SetAttribute(Xml_WindowLocY, WindowTop.ToString()); window.SetAttribute(Xml_WindowWidth, WindowWidth.ToString()); window.SetAttribute(Xml_WindowHeight, WindowHeight.ToString()); window.SetAttribute(Xml_APPName, AppName); root.AppendChild(window); SaveSettingXML(SettingFile, root); }
public override void Process(TagHelperContext context, TagHelperOutput output) { BaseVM vm = null; string formid = ""; if (context.Items.ContainsKey("model") == true) { vm = context.Items["model"] as BaseVM; } if (context.Items.ContainsKey("formid")) { formid = context.Items["formid"].ToString(); } if (IsLink == false) { output.Attributes.SetAttribute("type", "button"); } else { output.TagName = "a"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.SetAttribute("href", "#"); } if (Target == null || Target == ButtonTargetEnum.Layer) { string windowid = Guid.NewGuid().ToString(); if (PostCurrentForm == true && context.Items.ContainsKey("formid")) { Click = $@" try{{ {formid}validate = false; $('#{formid}hidesubmit').trigger('click'); }} catch(e){{ {formid}validate = true;}} if({formid}validate == true){{ ff.OpenDialog('{Url}', '{windowid}', '{WindowTitle ?? ""}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "null"}, ff.GetPostData('{context.Items["formid"]}'),{Max.ToString().ToLower()}) }} "; } else { Click = $"ff.OpenDialog('{Url}', '{windowid}', '{WindowTitle ?? ""}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "null"},undefined,{Max.ToString().ToLower()})"; } } else if (Target == ButtonTargetEnum.self) { if (PostCurrentForm == true && context.Items.ContainsKey("formid")) { Click = $@" try{{ {formid}validate = false; $('#{formid}hidesubmit').trigger('click'); }} catch(e){{ {formid}validate = true;}} if({formid}validate == true){{ ff.BgRequest('{Url}',ff.GetPostData('{context.Items["formid"]}'),'{vm?.ViewDivId}') }} "; } else { Click = $"ff.BgRequest('{Url}')"; } } else if (Target == ButtonTargetEnum.newwindow) { if (Url.StartsWith("~")) { Url = Url.TrimStart('~'); Click = $"ff.SetCookie('#{Url}','{WindowTitle ?? ""}',true);window.open('{Url}')"; } else { Click = $"ff.SetCookie('#{Url}','{WindowTitle ?? ""}',true);window.open('/Home/PIndex#{Url}')"; } } base.Process(context, output); }
public override void Process(TagHelperContext context, TagHelperOutput output) { #region Display Value var modelType = Field.Metadata.ModelType; var list = new List <Guid>(); if (Field.Model != null) { // 数组 or 泛型集合 if (modelType.IsArray || (modelType.IsGenericType && typeof(List <>).IsAssignableFrom(modelType.GetGenericTypeDefinition()))) { foreach (var item in Field.Model as dynamic) { list.Add(item); } } else { list.Add(Guid.Parse(Field.Model.ToString())); } } var value = new List <string>(); if (list.Count > 0) { if (ListVM == null || ListVM.Model == null) { throw new Exception("Selector 组件指定的 ListVM 必须要实例化"); } var listVM = ListVM.Model as IBasePagedListVM <TopBasePoco, ISearcher>; if (context.Items.ContainsKey("model") == true) { listVM.CopyContext(context.Items["model"] as BaseVM); } listVM.Ids = list; listVM.NeedPage = false; listVM.IsSearched = false; listVM.SearcherMode = ListVMSearchModeEnum.Batch; var entityList = listVM.GetEntityList().ToList(); foreach (var item in entityList) { value.Add(item.GetType().GetProperty(TextBind?.Metadata.PropertyName)?.GetValue(item).ToString()); } } #endregion if (Display) { output.TagName = "label"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.Add("class", "layui-form-label"); output.Attributes.Add("style", "text-align:left;padding:9px 0;"); var val = string.Empty; if (Field.Model != null) { if (Field.Model.GetType().IsEnumOrNullableEnum()) { val = PropertyHelper.GetEnumDisplayName(Field.Model.GetType(), Field.Model.ToString()); } else { val = Field.Model.ToString(); } } output.Content.AppendHtml(string.Join(",", value)); base.Process(context, output); } else { var windowid = Guid.NewGuid().ToString(); if (MultiSelect == null) { MultiSelect = false; var type = Field.Metadata.ModelType; if (type.IsArray || (type.IsGenericType && typeof(List <>).IsAssignableFrom(type.GetGenericTypeDefinition())))// Array or List { MultiSelect = true; } } if (WindowWidth == null) { WindowWidth = 800; } output.TagName = "input"; output.TagMode = TagMode.StartTagOnly; output.Attributes.Add("type", "text"); output.Attributes.Add("id", Id + "_Display"); output.Attributes.Add("name", Field.Name + "_Display"); var content = output.GetChildContentAsync().Result.GetContent().Trim(); #region 移除因 RowTagHelper 生成的外层 div 即 <div class="layui-col-xs6"></div> var regStart = new Regex(@"^<div\s+class=""layui-col-xs[0-9]+"">"); var regEnd = new Regex("</div>$"); content = regStart.Replace(content, string.Empty); content = regEnd.Replace(content, string.Empty); #endregion var reg = new Regex("(name=\")([0-9a-zA-z]{0,}[.]?)(Searcher[.]?[0-9a-zA-z]{0,}\")", RegexOptions.Multiline | RegexOptions.IgnoreCase); content = reg.Replace(content, "$1$3"); content = content.Replace("<script>", "$$script$$").Replace("</script>", "$$#script$$"); var searchPanelTemplate = $@"<script type=""text/template"" id=""Temp{Id}"">{content}</script>"; output.Attributes.Add("value", string.Join(",", value)); output.Attributes.Add("placeholder", EmptyText ?? "请选择"); output.Attributes.Add("class", "layui-input"); this.Disabled = true; var vmQualifiedName = ListVM.Metadata.ModelType.AssemblyQualifiedName; vmQualifiedName = vmQualifiedName.Substring(0, vmQualifiedName.LastIndexOf(", Version=")); var Filter = new Dictionary <string, object> { { "_DONOT_USE_VMNAME", vmQualifiedName }, { "_DONOT_USE_KFIELD", TextBind?.Metadata.PropertyName }, { "_DONOT_USE_VFIELD", ValBind == null ? "ID" : ValBind?.Metadata.PropertyName }, { "_DONOT_USE_FIELD", Field.Name }, { "_DONOT_USE_MULTI_SEL", MultiSelect }, { "_DONOT_USE_SEL_ID", Id }, { "Ids", list } }; if (!string.IsNullOrEmpty(SubmitFunc)) { Filter.Add("_DONOT_USE_SUBMIT", SubmitFunc); } var hiddenStr = string.Empty; var sb = new StringBuilder(); foreach (var item in list) { sb.Append($"<input type='hidden' name='{Field.Name}' value='{item.ToString()}' />"); } hiddenStr = sb.ToString(); output.PreElement.AppendHtml($@"<div id=""{Id}_Container"" style=""position:absolute;right:50px;left:0px;width:auto"">"); output.PostElement.AppendHtml($@" {hiddenStr} </div> <button class='layui-btn layui-btn-sm layui-btn-warm' type='button' id='{Id}_Select' style='color:white;position:absolute;right:0px'>{SelectButtonText ?? "选择"}</button> <hidden id='{Id}' name='{Field.Name}' /> <script> $('#{Id}_Select').on('click',function(){{ var filter = {JsonConvert.SerializeObject(Filter)}; var vals = $('#{Id}_Container input[type=hidden]'); filter.Ids = [] for(var i=0;i<vals.length;i++){{ filter.Ids.push(vals[i].value); }} ff.OpenDialog2('/_Framework/Selector', '{windowid}', '{WindowTitle ?? string.Empty}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "null"},'#Temp{Id}', filter); }}); </script> {searchPanelTemplate} "); base.Process(context, output); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (IsLink == false) { output.Attributes.SetAttribute("type", "button"); } else { output.TagName = "a"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.SetAttribute("href", "#"); } if (Target == null || Target == ButtonTargetEnum.Layer) { string windowid = Guid.NewGuid().ToString(); if (PostCurrentForm == true && context.Items.ContainsKey("formid")) { Click = $"ff.OpenDialog('{Url}', '{windowid}', '{WindowTitle ?? ""}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "null"}, ff.GetFormData('{context.Items["formid"]}'))"; } else { Click = $"ff.OpenDialog('{Url}', '{windowid}', '{WindowTitle ?? ""}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "null"})"; } } else if (Target == ButtonTargetEnum.self) { if (PostCurrentForm == true && context.Items.ContainsKey("formid")) { Click = $"ff.BgRequest('{Url}',ff.GetFormData('{context.Items["formid"]}'))"; } else { Click = $"ff.BgRequest('{Url}')"; } } else if (Target == ButtonTargetEnum.newwindow) { if (Url.StartsWith("~")) { Url = Url.TrimStart('~'); Click = $"ff.SetCookie('#{Url}','{WindowTitle ?? ""}',true);window.open('{Url}')"; } else { Click = $"ff.SetCookie('#{Url}','{WindowTitle ?? ""}',true);window.open('/Home/PIndex#{Url}')"; } } base.Process(context, output); }
private void RegisterScript() { string selectClientID = WebControlUtilities.FindControlRecursive(Page, EntitySelectControlID).ClientID; string url = CreateNavigateUrl(); StringBuilder builder = new StringBuilder(); NameValueCollection transferData = ParseTransferData(); builder.Append("<script language='javascript' defer>\n"); builder.Append("function GetData_" + ClientID + "(key){\n"); foreach (string key in transferData.Keys) { Control control = WebControlUtilities.FindControlRecursive(Page, transferData[key]); if (control == null) { throw new Exception("No control found with ID of '" + transferData[key] + "'."); } string clientID = control.ClientID; builder.Append("if (key == '" + WebUtilities.EncodeJsString(key) + "'){\n"); builder.Append(" return document.getElementById('"+ clientID + "').value;\n"); builder.Append("}\n"); } builder.Append("}\n"); string height = WindowHeight.ToString().Replace("px", ""); string width = WindowWidth.ToString().Replace("px", ""); builder.Append("\n"); builder.Append("function NewItem_" + ClientID + "(){\n"); builder.Append(" var url = '"+ WebUtilities.EncodeJsString(CreateNavigateUrl()) + "';\n"); builder.Append(" var settings = 'Location=0,Scrollbars=1,Height="+ height + ",Width=" + width + "';\n"); builder.Append(" var win = window.open(url, 'AddItem_"+ Guid.NewGuid().ToString().Replace("-", "_") + "', settings);\n"); // TODO: Check if the following line should be used instead of the one above. The one above makes every window // title unique so that new windows aren't prevented from opening (by ID being in use) // The following line uses a predictable title which is good for integration testing but means windows could be blocked from opening //builder.Append(" var win = window.open(url, 'AddItemTo" + EntityType + "', settings);\n"); //builder.Append(" var url = " + CreateNavigateUrl() + "\n"); builder.Append("}\n"); builder.Append("\n"); builder.Append(@"function AddItem_" + ClientID + @"(id, text){ if (id == '" + Guid.Empty.ToString() + @"') alert('Cannot add item with Guid.Empty value.'); var newOption = document.createElement('option'); newOption.value = id; newOption.text = text; newOption.selected = true; // Only used while debugging. Leave commented out //alert(id + ' - ' + text); var field = document.getElementById('" + selectClientID + @"') if (field == null) alert('" + selectClientID + @" field not found.'); //field.appendChild(newOption) try { field.add(newOption, null); // standards compliant; doesn't work in IE } catch(ex) { field.add(newOption); // IE only } } " ); builder.Append("</script>\n"); //if (!Page.ClientScript.IsClientScriptBlockRegistered("EntitySelectRequesterScript")) Page.ClientScript.RegisterClientScriptBlock(typeof(EntitySelectRequester), "EntitySelectRequesterScript", builder.ToString()); }
public override void GameLogic() { // This runs every frame and handles game logic Player player = (Player)GetObjectByName("Player"); SpriteComponent playerSpriteComp = (SpriteComponent)player.GetComponent("SpriteComponent"); GameObject GameResTextObj = GetUIObjectByName("GameRenderTextObj"); TextComponent GameResTextObjComp = (TextComponent)GameResTextObj.GetComponent("TextComponent"); GameResTextObjComp.SetText("Render Width: " + GameResolutionWidth.ToString() + ", Render Height: " + GameResolutionHeight.ToString()); GameObject WindowSizeTextObj = GetUIObjectByName("WindowSizeTextObj"); TextComponent WindowSizeTextObjComp = (TextComponent)WindowSizeTextObj.GetComponent("TextComponent"); WindowSizeTextObjComp.SetText("Window Width: " + WindowWidth.ToString() + ", Render Height: " + WindowHeight.ToString()); // Handle Key Presses if (PressedKeys.Count > 0) { for (int i = 0; i < PressedKeys.Count; i++) { //Keys currentKeyCode = PressedKeys[i]; //printText(EngineClass.debugType.Debug, PressedKeys[i].ToString()); if (PressedKeys[i] == Keys.W) { player.moveUp(60); //playerSpriteComp.SetImageRotation(Rotation.Up); } // REMOVED S to go down because gravity pulls the player down //else if (PressedKeys[i] == Keys.S || PressedKeys[i] == Keys.Down) //{ // player.moveDown(playerSpeed); // //playerSpriteComp.SetImageRotation(Rotation.Down); //} if (PressedKeys[i] == Keys.A) { player.moveLeft(playerSpeed); playerSpriteComp.SetImageRotation(HRotation.Left, VRotation.Up); } else if (PressedKeys[i] == Keys.D) { player.moveRight(playerSpeed); playerSpriteComp.SetImageRotation(HRotation.Right, VRotation.Up); } if (PressedKeys[i] == Keys.Up) { GlobalCoords[1] += 10; } if (PressedKeys[i] == Keys.Down) { GlobalCoords[1] -= 10; } if (PressedKeys[i] == Keys.Left) { GlobalCoords[0] += 10; } if (PressedKeys[i] == Keys.Right) { GlobalCoords[0] -= 10; } if (PressedKeys[i] == Keys.O) { GlobalScale[0] += (float)0.25; GlobalScale[1] += (float)0.25; //PrintText(debugType.Error, "GlobalScale X = " + GlobalScale[0].ToString() + ", Y = " + GlobalScale[1].ToString()); } else if (PressedKeys[i] == Keys.P) { GlobalScale[0] -= (float)0.25; GlobalScale[1] -= (float)0.25; //PrintText(debugType.Error, "GlobalScale X = " + GlobalScale[0].ToString() + ", Y = " + GlobalScale[1].ToString()); } //printText(debugType.Debug, player.x.ToString()); //printText(debugType.Debug, player.y.ToString()); } PressedKeys.Clear(); // Handle Collision //if (player.GetX() + player.GetWidth() > GetCanvasWidth()) //{ // player.x = GetCanvasWidth() - player.width; //} //else if (player.x < 0) //{ // player.x = 0; //} //if (player.y + player.height > GetCanvasHeight()) //{ // player.y = GetCanvasHeight() - player.height; //} //else if (player.y < 0) //{ // player.y = 0; //} } }
private bool checkConfig(XDocument cfg) { string binConfigPath = cfg.Root?.Element("CfgBinPath")?.Value; string certFilePath = cfg.Root?.Element("CertificateFilePath")?.Value; StoreLocation storeLocation; StoreLocation.TryParse(cfg.Root?.Element("CertificateStore")?.Value, true, out storeLocation); if(storeLocation != 0) { CertificateStore = storeLocation; } else { CertificateStore = StoreLocation.CurrentUser; SetConfigField("CertificateStore", CertificateStore.ToString()); } #region [set window position and size] string lastHeightStr = cfg.Root?.Element("WindowHeight")?.Value; string lastWidthStr = cfg.Root?.Element("WindowWidth")?.Value; string lastLeftStr = cfg.Root?.Element("WindowLeft")?.Value; string lastTopStr = cfg.Root?.Element("WindowTop")?.Value; if(!string.IsNullOrEmpty(lastHeightStr)) { WindowHeight = Int32.Parse(lastHeightStr); } else { WindowHeight = 780; SetConfigField("WindowHeight", WindowHeight.ToString()); } if(!string.IsNullOrEmpty(lastWidthStr)) { WindowWidth = Int32.Parse(lastWidthStr); } else { WindowWidth = 590; SetConfigField("WindowWidth", WindowWidth.ToString()); } if(!string.IsNullOrEmpty(lastLeftStr)) { WindowLeft = Int32.Parse(lastLeftStr); } else { WindowLeft = 100; SetConfigField("WindowLeft", WindowLeft.ToString()); } if(!string.IsNullOrEmpty(lastTopStr)) { WindowTop = Int32.Parse(lastTopStr); } else { WindowTop = 20; SetConfigField("WindowTop", WindowTop.ToString()); } #endregion string lastCertificateStr = cfg.Root?.Element("CertificateItem")?.Value; if(!string.IsNullOrEmpty(lastCertificateStr)) { CertificateItem = Int32.Parse(lastCertificateStr); } else { CertificateItem = 0; SetConfigField("CertificateItem", CertificateItem.ToString()); } string interopCertificateThumb = cfg.Root?.Element("InteropCertificateThumbprint")?.Value; if (string.IsNullOrEmpty(interopCertificateThumb)) { // Thread.Sleep(1000); SetErrorMessage("Не указан сертификат подписи для взаимодействия"); bool certSelected = SelectInteropCertificate(); if (!certSelected) { MessageBox.Show( "Не указан сертификат подписи для взаимодействия.\nУкажите сертификат подписи, используя соответствующий пункт меню «Настройка» программы.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); return false; } else { StoreLocation.TryParse(cfg.Root?.Element("InteropCertificateStore")?.Value, true, out _interopCertificateStoreLocation); } } else { _interopCertificateThumbprint = interopCertificateThumb; StoreLocation.TryParse(cfg.Root?.Element("InteropCertificateStore")?.Value, true, out _interopCertificateStoreLocation); } saveChangesToConfig(); //signed (and siphered) binary config if(string.IsNullOrEmpty(binConfigPath)) { SetErrorMessage("Личный конфигурационный файл не найден"); bool privateConfigSelected = LoadPrivateConfig(); if (!privateConfigSelected) { MessageBox.Show("Личный конфигурационный файл не найден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); return false; } } else { //means htere is a config //check it's signature, but first load our certificate if(string.IsNullOrEmpty(certFilePath)) { MessageBox.Show("Файл сертификата сервера не найден.\nСкачайте файл сертификата сервера с корпоративного портала.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Файл сертификата сервера не найден"); bool serverCertifcateSelected = LoadServerCertificate(); if (!serverCertifcateSelected) { return false; } } else { //means certificate && config present //check cert expiration date X509Certificate2 cert = new X509Certificate2(); try { cert.Import(certFilePath); if (cert.NotAfter > DateTime.Now) { //cert ok //check config signature string configContents = Util.DecryptConfig(binConfigPath,ProgramFolder); if (string.IsNullOrEmpty(configContents)) { MessageBox.Show("Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Личный конфигурационный файл поврежден"); return false; } XmlDocument xdocConfig = new XmlDocument(); // this stuff is for try { xdocConfig.LoadXml(configContents); // check signature further } catch (Exception e) { MessageBox.Show( $"Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.\n\n{e.Message}", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Личный конфигурационный файл поврежден"); return false; } XDocument privateConfig = XDocument.Parse(configContents); try { #if !DEBUG if (SignatureProcessor.VerifySignature(SignatureProcessor.SignatureType.Smev3SidebysideDetached, xdocConfig, cert)) { #endif #if DEBUG if(SignatureProcessor.VerifySignature(SignatureProcessor.SignatureType.Smev3SidebysideDetached, xdocConfig)) { #endif //config signature OK - loading contents if (privateConfig.Root?.Attribute("version").Value == ProgramVersion) { //means config version corresponds to a program version _ourCertificate = cert; _serverUri = new Uri(privateConfig.Root?.Element("Server").Element("GetFileUri")?.Value ?? ""); _serverSignatureCertificateThumbprint = privateConfig.Root?.Element("Server").Element("CertificateThumbprint")?.Value ?? ""; _serverHttpsCertificateThumbprint = privateConfig.Root?.Element("Server").Element("SSLCertificateThumbprint")?.Value ?? ""; ClearError("Конфигурационный файл успешно загружен"); } else { //means version in config is not right one MessageBox.Show( $"Текущая версия программы <{ProgramVersion}> устарела.\nСкачайте новую версию с корпоративного портала.", "Программа устарела.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage($"Установленная версия программы <{ProgramVersion}> устарела"); return false; } } else { //signature incorrect Debug.WriteLine("Invalid Signature"); MessageBox.Show( "Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Личный конфигурационный файл поврежден"); return false; } } catch (Exception e) { MessageBox.Show( $"Личный конфигурационный файл поврежден.\nСкачайте новый личный конфигурационный файл с корпоративного портала.\n\n{e.Message}", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Личный конфигурационный файл поврежден"); return false; } } else { //cert expired MessageBox.Show("Файл сертификата сервера просрочен.\nСкачайте новый файл сертификата сервера с корпоративного портала.", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Файл сертификата сервера просрочен"); return false; } } catch (Exception e) { //certificate corrupted MessageBox.Show($"Ошибка загрузки сертификата сервера. Файл поврежден.\nСкачайте новый файл сертификата сервера с корпоративного портала.\n\n{e.Message}", "Ошибка загрузки начальной конфигурации.", MessageBoxButton.OK, MessageBoxImage.Error); SetErrorMessage("Ошибка загрузки сертификата сервера"); return false; } } } return true; }
static public void VideoPr() { MenuMethods.Clear(); MenuMethods.Add(new Acts("Screen width (max - " + (Console.LargestWindowWidth - 2).ToString() + ") = " + WindowWidth.ToString(), del = () => { WindowWidth = WindowWidth < Console.LargestWindowWidth - 2 ? WindowWidth += 1 : 30; SetProperties(); VideoPr(); })); MenuMethods.Add(new Acts("Screen height (max - " + (Console.LargestWindowHeight - InfoHeight - LogHeight).ToString() + ") = " + WindowHeight.ToString(), del = () => { WindowHeight = WindowHeight < Console.LargestWindowHeight - InfoHeight - LogHeight ? WindowHeight += 1 : 17; SetProperties(); VideoPr(); })); MenuMethods.Add(new Acts("Logbar height = " + (LogHeight - 5).ToString(), del = () => { LogHeight = LogHeight < 20 ? LogHeight += 1 : 8; SetProperties(); VideoPr(); })); Program.mainDialog.SetDialog("Changes will take effect after reboot", MenuMethods); }