//muiBtnUndo_Click private void muiBtnUndo_Click(object sender, RoutedEventArgs e) { if (current_folder_undo != "") { ModernDialog md = new ModernDialog(); md.Buttons = new Button[] { md.YesButton, md.CloseButton, }; md.Title = FindResource("notification").ToString(); md.Content = FindResource("are_you_sure").ToString(); md.YesButton.Content = FindResource("yes").ToString(); md.CloseButton.Content = FindResource("no").ToString(); md.YesButton.Focus(); bool result = md.ShowDialog().Value; if (result == true) { //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { //close connect ConnectionDB.CloseConnect(); if (System.IO.File.Exists(current_directory + @"\DBRES_Local\" + current_folder_undo + @"\CheckOut.db") == true) { System.IO.File.Copy(current_directory + @"\DBRES_Local\" + current_folder_undo + @"\CheckOut.db", current_directory + @"\Databases\CheckOut.db", true); //restart app System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } //open connect ConnectionDB.OpenConnect(); } //if database type is sql server else { //System.IO.Directory.CreateDirectory(current_directory + @"\DBRESSer_Local\" + __current_time); string _restoreFile = current_directory + @"\DBRESSer_Local\" + current_folder_undo.Replace("/", ".").Replace(":", "..") + @"\CheckOut.bak"; if (System.IO.File.Exists(_restoreFile)) { System.Diagnostics.Debug.WriteLine(_restoreFile); SqlConnection sqlConnect = ConnectionDB.getSQLConnection(); var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}' WITH NOFORMAT, NOINIT, NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10", ConnectionDB.getSqlServerDataBaseName(), current_directory + @"\DBRESSer_Local\" + current_folder_undo.Replace("/", ".").Replace(":", "..") + @"\" + ConnectionDB.getSqlServerDataBaseName() + ".bak"); using (var command = new SqlCommand(query, sqlConnect)) { //command.ExecuteNonQuery(); command.CommandText = "Use Master"; command.ExecuteNonQuery(); command.CommandText = "ALTER DATABASE " + ConnectionDB.getSqlServerDataBaseName() + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"; command.ExecuteNonQuery(); command.CommandText = "RESTORE DATABASE " + ConnectionDB.getSqlServerDataBaseName() + " FROM DISK = '" + @_restoreFile + "' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10; "; command.ExecuteNonQuery(); command.CommandText = "Use Master"; command.ExecuteNonQuery(); command.CommandText = "ALTER DATABASE " + ConnectionDB.getSqlServerDataBaseName() + " SET MULTI_USER;"; command.ExecuteNonQuery(); command.CommandText = "Use " + ConnectionDB.getSqlServerDataBaseName(); command.ExecuteNonQuery(); } } else if (System.IO.File.Exists(current_directory + @"\DBRESSer_Local\" + current_folder_undo + @"\CheckOut.sql") == true) { //get connection info System.IO.StreamReader stream_reader = StaticClass.GeneralClass.DecryptFileGD(current_directory + @"\sqltype", StaticClass.GeneralClass.key_register_general); stream_reader.ReadLine(); server = stream_reader.ReadLine().Split(':')[1].ToString(); id = stream_reader.ReadLine().Split(':')[1].ToString(); password = stream_reader.ReadLine().Split(':')[1].ToString(); stream_reader.Close(); //connection to server string connection_string = "server = " + server + "; user id = " + id + "; password = "******"; integrated security = true"; SqlConnection sql_connection = new SqlConnection(); sql_connection.ConnectionString = connection_string; sql_connection.Open(); //insert data System.IO.StreamReader stream_reader_insert = StaticClass.GeneralClass.DecryptFileGD(current_directory + @"\DBRESSer_Local\" + current_folder_undo + @"\CheckOut.sql", StaticClass.GeneralClass.key_register_general); string _line; StringBuilder _strImport = new StringBuilder(); while ((_line = stream_reader_insert.ReadLine()) != null) { if (!string.IsNullOrEmpty(_line) && _line.Substring(0, 3) != "-- ") { if (_line.Contains("INSERT INTO")) { string _strTemp = _line.Substring(0, _line.IndexOf("(")); _strTemp = _strTemp.Substring("insert into ".Length).Trim().Replace("[", "").Replace("]", ""); _line = _line.Replace("')", @"\u0066").Replace("''", @"\u0055").Replace("','", @"\u0022").Replace("', '", @"\u0099").Replace(",'", @"\u0033").Replace(", '", @"\u0077").Replace("',", @"\u0044").Replace("' ,", @"\u0088").Replace("'", "''"); _line = _line.Replace(@"\u0066", "')").Replace(@"\u0055", "''").Replace(@"\u0022", "',N'").Replace(@"\u0099", "', N'").Replace(@"\u0033", ",N'").Replace(@"\u0077", ", N'").Replace(@"\u0044", "',").Replace(@"\u0088", "' ,"); _line = "if exists (select column_id from sys.columns where object_id = OBJECT_ID('" + _strTemp + "', 'U') and is_identity = 1) begin SET IDENTITY_INSERT " + _strTemp + " ON; " + _line + " SET IDENTITY_INSERT " + _strTemp + " OFF; end else " + _line; } _strImport.AppendLine(_line); } } if (!string.IsNullOrEmpty(_strImport.ToString())) { SqlTransaction tr = null; SqlCommand sql_command = null; try { using (tr = sql_connection.BeginTransaction()) { using (sql_command = sql_connection.CreateCommand()) { sql_command.Transaction = tr; sql_command.CommandText = _strImport.ToString(); sql_command.ExecuteNonQuery(); } tr.Commit(); } tr.Dispose(); sql_command.Dispose(); } catch (SqlException ex) { if (tr != null) { try { tr.Rollback(); } catch (ObjectDisposedException ex2) { } finally { tr.Dispose(); } } } } sql_connection.Close(); //restart app System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } } } } }
private static void onRunAction(object obj) { var result = ModernDialog.ShowMessage("Din q3config är nu uppdaterad.", "Klart!", MessageBoxButton.OK); }
private async void BackgroundInitialization() { try { await Task.Delay(1000); if (AppArguments.Has(AppFlag.TestIfAcdAvailable) && !Acd.IsAvailable()) { NonfatalError.NotifyBackground(@"This build can’t work with encrypted ACD-files"); } if (AppUpdater.JustUpdated && SettingsHolder.Common.ShowDetailedChangelog) { List <ChangelogEntry> changelog; try { changelog = await Task.Run(() => AppUpdater.LoadChangelog().Where(x => x.Version.IsVersionNewerThan(AppUpdater.PreviousVersion)).ToList()); } catch (WebException e) { NonfatalError.NotifyBackground(AppStrings.Changelog_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks, e); return; } catch (Exception e) { NonfatalError.NotifyBackground(AppStrings.Changelog_CannotLoad, e); return; } Logging.Debug("Changelog entries: " + changelog.Count); if (changelog.Any()) { Toast.Show(AppStrings.App_AppUpdated, AppStrings.App_AppUpdated_Details, () => { ModernDialog.ShowMessage(changelog.Select(x => $@"[b]{x.Version}[/b]{Environment.NewLine}{x.Changes}") .JoinToString(Environment.NewLine.RepeatString(2)), AppStrings.Changelog_RecentChanges_Title, MessageBoxButton.OK); }); } } await Task.Delay(1500); PresetsPerModeBackup.Revert(); WeatherSpecificCloudsHelper.Revert(); WeatherSpecificTyreSmokeHelper.Revert(); WeatherSpecificVideoSettingsHelper.Revert(); CarSpecificControlsPresetHelper.Revert(); CopyFilterToSystemForOculusHelper.Revert(); await Task.Delay(1500); CustomUriSchemeHelper.EnsureRegistered(); await Task.Delay(5000); await Task.Run(() => { foreach (var f in from file in Directory.GetFiles(FilesStorage.Instance.GetDirectory("Logs")) where file.EndsWith(@".txt") || file.EndsWith(@".log") || file.EndsWith(@".json") let info = new FileInfo(file) where info.LastWriteTime < DateTime.Now - TimeSpan.FromDays(3) select info) { f.Delete(); } }); } catch (Exception e) { Logging.Error(e); } }
private void btnMessage_ScrapeUserPhotoUrl_Start_Click(object sender, RoutedEventArgs e) { try { if (IGGlobals.listAccounts.Count > 0) { try { GlobalDeclration.objScrapeUser.isStopScrapeUser = false; GlobalDeclration.objScrapeUser.lstofThreadScrapeUser.Clear(); Regex checkNo = new Regex("^[0-9]*$"); int processorCount = objUtils.GetProcessor(); int threads = 25; if (chkBox_Scraper_ScrapeUserPhotoUrl_SingleUsername.IsChecked == true) { GlobalDeclration.objScrapeUser.listOfPhotoUrl.Clear(); GlobalDeclration.objScrapeUser.usernmeToScrape = Txt_UsernameToScrapeUserPhotoUrl.Text; GlobalDeclration.objScrapeUser.listOfPhotoUrl.Add(Txt_UsernameToScrapeUserPhotoUrl.Text); } int maxThread = 25 * processorCount; try { GlobalDeclration.objScrapeUser.minDelayScrapeUser = Convert.ToInt32(txt_ScrapeUsers_DelayMin.Text); GlobalDeclration.objScrapeUser.maxDelayScrapeUser = Convert.ToInt32(txt_ScrapeUsers_DelayMax.Text); GlobalDeclration.objScrapeUser.NoOfThreadsScarpeUser = Convert.ToInt32(txt_Tweet_ScrapeUsers_NoOfThreads.Text); GlobalDeclration.objScrapeUser.noOfPhotoToScrape = Convert.ToInt32(Txt_ScrapeUser_ScrapeUser_NoOfPhotoToScrape.Text); GlobalDeclration.objScrapeUser.noOfUserToScrape = Convert.ToInt32(Txt_ScrapeUser_ScrapeFollowing_NoOfUserToScrape.Text); try { List <CheckBox> tempListOfAccount = new List <CheckBox>(); foreach (CheckBox item in cmb_Select_To_Account.Items) { tempListOfAccount.Add(item); } if (tempListOfAccount.Count > 0) { tempListOfAccount = tempListOfAccount.Where(x => x.IsChecked == true).ToList(); if (tempListOfAccount.Count == 0) { GlobusLogHelper.log.Info("Please Select Account From List"); ModernDialog.ShowMessage("Please Select Account From List", "Select Account", MessageBoxButton.OK); cmb_Select_To_Account.Focus(); return; } else { foreach (CheckBox checkedItem in tempListOfAccount) { if (checkedItem.IsChecked == true) { GlobalDeclration.objScrapeUser.selectedAccountToScrape.Add(checkedItem.Content.ToString()); } } GlobusLogHelper.log.Info(GlobalDeclration.objScrapeUser.selectedAccountToScrape.Count + " Account Selected"); } } } catch (Exception ex) { GlobusLogHelper.log.Error("Error ==> " + ex.Message); } } catch (Exception ex) { GlobusLogHelper.log.Info("Enter in Correct Formate/Fill all Field"); ModernDialog.ShowMessage("Enter in Correct Formate/Fill all Field", "Error", MessageBoxButton.OK); return; } if (threads > maxThread) { threads = 25; } GlobalDeclration.objScrapeUser.isScrapePhotoURL = true; Thread CommentPosterThread = new Thread(GlobalDeclration.objScrapeUser.StartScrapUser); CommentPosterThread.Start(); GlobusLogHelper.log.Info("------ ScrapeFollower Proccess Started ------"); } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } } else { GlobusLogHelper.log.Info("Please Load Accounts !"); GlobusLogHelper.log.Debug("Please Load Accounts !"); } } catch (Exception ex) { GlobusLogHelper.log.Error("Error ==> " + ex.StackTrace); } }
/// <summary> /// Executes the command. /// </summary> /// <param name="parameter">The parameter.</param> protected override void OnExecute(object parameter) { ModernDialog.ShowMessage("A messagebox triggered by selecting a hyperlink", "Messagebox", MessageBoxButton.OK); }
public void startInviteEmail() { try { if (PDGlobals.listAccounts.Count > 0) { try { if (objInviteManagers.rdbSingleUserInvite == true || objInviteManagers.rdbMultipleUserInvite == true) { if (objInviteManagers.rdbSingleUserInvite == true) { try { } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } }//end of single User if (objInviteManagers.rdbMultipleUserInvite == true) { try { if (string.IsNullOrEmpty(txtInviteEmail.Text)) { GlobusLogHelper.log.Info("Please Upload Email "); ModernDialog.ShowMessage("Please Upload Email", "Upload Email", MessageBoxButton.OK); return; } } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } }//end of Multiple user } else { GlobusLogHelper.log.Info("Please Select Use Single User or Use Multiple User"); ModernDialog.ShowMessage("Please Select Use Single User or Use Multiple User", "Select Use Single User or Use Multiple User", MessageBoxButton.OK); return; } objInviteManagers.isStopInvite = false; objInviteManagers.lstThreadsInvite.Clear(); if (objInviteManagers._IsfevoriteInvite) { objInviteManagers._IsfevoriteInvite = false; } Regex checkNo = new Regex("^[0-9]*$"); int processorCount = objUtils.GetProcessor(); int threads = 25; int maxThread = 25 * processorCount; try { try { objInviteManagers.minDelayInvite = Convert.ToInt32(txtInviteEmail_DelayMin.Text); objInviteManagers.maxDelayInvite = Convert.ToInt32(txtInviteEmail_DelayMax.Text); objInviteManagers.Nothread_Invite = Convert.ToInt32(txtInviteEmail_NoOfThreads.Text); } catch (Exception ex) { GlobusLogHelper.log.Info("Enter in Correct Format"); return; } if (!string.IsNullOrEmpty(txtInviteEmail_NoOfThreads.Text) && checkNo.IsMatch(txtInviteEmail_NoOfThreads.Text)) { threads = Convert.ToInt32(txtInviteEmail_NoOfThreads.Text); } if (threads > maxThread) { threads = 25; } GlobusLogHelper.log.Info(" => [ Process Starting ] "); objInviteManagers.NoOfThreadsInvite = threads; Thread InviteThread = new Thread(objInviteManagers.StartInvite); InviteThread.Start(); } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } } else { GlobusLogHelper.log.Info("Please Load Accounts !"); GlobusLogHelper.log.Debug("Please Load Accounts !"); } } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } }
public void ExportAccReportInvite() { try { if (dgvInvite_AccountsReport.Items.Count == 1) { GlobusLogHelper.log.Info("=> [ Data Is Not Found In Account Report ]"); ModernDialog.ShowMessage("Data Is Not Found In Account Report", "Data Is Not Found", MessageBoxButton.OK); return; } else if (dgvInvite_AccountsReport.Items.Count > 1) { try { string CSV_Header = string.Join(",", "AccountName", "ModuleName", "UserName", "Status", "Date&Time"); string CSV_Content = ""; var result = ModernDialog.ShowMessage("Are you want to Export Report Data ", " Export Report Data ", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { try { string FilePath = string.Empty; FilePath = Utils.Utils.UploadFolderData(PDGlobals.Pindominator_Folder_Path); FilePath = FilePath + "\\Invite.csv"; GlobusLogHelper.log.Info("Export Data File Path :" + FilePath); GlobusLogHelper.log.Debug("Export Data File Path :" + FilePath); string ExportDataLocation = FilePath; PDGlobals.Pindominator_Folder_Path = FilePath; DataSet ds = QM.SelectAddReport("Invite"); foreach (DataRow item in ds.Tables[0].Rows) { try { string AccountName = item.ItemArray[1].ToString(); string ModuleName = item.ItemArray[2].ToString(); string UserName = item.ItemArray[5].ToString(); string Status = item.ItemArray[9].ToString(); string DateAndTime = item.ItemArray[12].ToString(); CSV_Content = string.Join(",", AccountName.Replace("'", ""), ModuleName.Replace("'", ""), UserName.Replace("'", ""), Status.Replace("'", ""), DateAndTime.Replace("'", "")); PDGlobals.ExportDataCSVFile(CSV_Header, CSV_Content, ExportDataLocation); } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } } } catch (Exception ex) { GlobusLogHelper.log.Error("Error : " + ex.StackTrace); } } } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } } } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } }
//btnSaveInvoice_Click private void btnSaveInvoice_Click(object sender, RoutedEventArgs e) { ModernDialog mdd = new ModernDialog(); mdd.Buttons = new Button[] { mdd.OkButton, mdd.CancelButton, }; mdd.OkButton.TabIndex = 0; mdd.OkButton.Content = FindResource("ok").ToString(); mdd.CancelButton.TabIndex = 1; mdd.CancelButton.Content = FindResource("cancel").ToString(); mdd.TabIndex = -1; mdd.Height = 200; mdd.Title = FindResource("save_invoice").ToString(); mdd.Content = FindResource("really_want_save_invoice").ToString(); mdd.OkButton.Focus(); mdd.ShowDialog(); if (mdd.MessageBoxResult == System.Windows.MessageBoxResult.OK) { if (thread_saveinvoice != null && thread_saveinvoice.ThreadState == ThreadState.Running) { } else { thread_saveinvoice = new Thread(() => { try { this.btnSaveInvoice.Dispatcher.Invoke((Action)(() => { this.btnSaveInvoice.Visibility = System.Windows.Visibility.Hidden; })); this.btnSaveSendEmail.Dispatcher.Invoke((Action)(() => { this.btnSaveSendEmail.IsEnabled = false; })); this.btnClose.Dispatcher.Invoke((Action)(() => { this.btnClose.IsEnabled = false; })); this.mprSaveInvoice.Dispatcher.Invoke((Action)(() => { this.mprSaveInvoice.Visibility = System.Windows.Visibility.Visible; this.mprSaveInvoice.IsActive = true; })); if (PayOrder() == true) { StaticClass.GeneralClass.flag_paycash = true; btnpayother_delegate(true); this.Dispatcher.Invoke((Action)(() => { this.Close(); })); } else { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.CloseButton.Content = FindResource("close").ToString(); md.Content = FindResource("error_insert").ToString(); md.Title = FindResource("notification").ToString(); md.ShowDialog(); })); } this.mprSaveInvoice.Dispatcher.Invoke((Action)(() => { this.mprSaveInvoice.Visibility = System.Windows.Visibility.Hidden; this.mprSaveInvoice.IsActive = false; this.btnSaveInvoice.Visibility = System.Windows.Visibility.Visible; this.btnSaveSendEmail.IsEnabled = true; this.btnClose.IsEnabled = true; })); } catch (Exception ex) { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.CloseButton.Content = FindResource("close").ToString(); md.Content = ex.Message; md.Title = FindResource("notification").ToString(); md.ShowDialog(); })); } }); thread_saveinvoice.Start(); } } }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.WeatherExtMode, ref WeatherProceduralHelper.Option24HourMode); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled); AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold); AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode); AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect); AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing); AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading); AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality); AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial); Acd.Factory = new AcdFactory(); #if !DEBUG Kn5.Factory = Kn5New.GetFactoryInstance(); #endif Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync; KeyboardListenerFactory.Register <KeyboardListener>(); LimitedSpace.Initialize(); DataProvider.Initialize(); SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); TestKey(); AppDomain.CurrentDomain.ProcessExit += OnProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => { if (b) { NonfatalError.NotifyBackground(s, c, e); } else { NonfatalError.Notify(s, c, e); } }; AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles); AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging); FancyBackgroundManager.Initialize(); if (AppArguments.Has(AppFlag.UiScale)) { AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); } if (AppArguments.Has(AppFlag.WindowsLocationManagement)) { AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true); } if (!InternalUtils.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode); AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay); AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode); AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode); AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays); AppArguments.Set(AppFlag.HideRaceCancelButton, ref GameDialog.OptionHideCancelButton); AppArguments.Set(AppFlag.PatchSupport, ref PatchHelper.OptionPatchSupport); // Shared memory, now as an app flag SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory); /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, * !Equals(DpiAwareWindow.OptionScale, 1d));*/ NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative); AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative); AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries()); VisualExtension.RegisterInput <WebBlock>(); ContentUtils.Register("AppStrings", AppStrings.ResourceManager); ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager); ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager); ContentUtils.Register("UiStrings", UiStrings.ResourceManager); LocalizationHelper.Use12HrFormat = SettingsHolder.Common.Use12HrTimeFormat; AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); RaceResultsStorage.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver), new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver)); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } Storage.TemporaryBackupsDirectory = FilesStorage.Instance.GetTemporaryDirectory("Storages Backups"); CupClient.Initialize(); CupViewModel.Initialize(); Superintendent.Initialize(); ModsWebBrowser.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); WebBlock.DefaultDownloadListener = new WebDownloadListener(); FlexibleLoader.CmRequestHandler = new CmRequestHandler(); ContextMenus.ContextMenusProvider = new ContextMenusProvider(); PrepareUi(); AppShortcut.Initialize("Content Manager", "Content Manager"); // If shortcut exists, make sure it has a proper app ID set for notifications if (File.Exists(AppShortcut.ShortcutLocation)) { AppShortcut.CreateShortcut(); } AppIconService.Initialize(new AppIconProvider()); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += OnBbImageClick; BbCodeBlock.OptionEmojiProvider = new EmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"), new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16)))); BbCodeBlock.AddLinkCommand(new Uri("cmd://findSrsServers"), new DelegateCommand(() => new ModernDialog { ShowTitle = false, ShowTopBlob = false, Title = "Connect to SimRacingSystem", Content = new ModernFrame { Source = new Uri("/Pages/Drive/Online.xaml?Filter=SimRacingSystem", UriKind.Relative) }, MinHeight = 400, MinWidth = 800, MaxHeight = DpiAwareWindow.UnlimitedSize, MaxWidth = DpiAwareWindow.UnlimitedSize, Padding = new Thickness(0), ButtonsMargin = new Thickness(8, -32, 8, 8), SizeToContent = SizeToContent.Manual, ResizeMode = ResizeMode.CanResizeWithGrip, LocationAndSizeKey = @".SrsJoinDialog" }.ShowDialog())); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager") { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget(); args.Cancel = true; } }; AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); BetterImage.RemoteUserAgent = CmApiProvider.UserAgent; BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory; GameWrapper.Started += (sender, args) => { BetterImage.CleanUpCache(); GCHelper.CleanUp(); }; AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = true; GameResultExtension.RegisterNameProvider(new GameSessionNameProvider()); CarBlock.CustomShowroomWrapper = new CustomShowroomWrapper(); CarBlock.CarSetupsView = new CarSetupsView(); SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout); var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded(); if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value)) { if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType; Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM"); } } else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType; Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => { ModernDialog.ShowMessage( "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.", "Steam Starter is unavailable", MessageBoxButton.OK); }); } InitializeUpdatableStuff(); BackgroundInitialization(); ExtraProgressRings.Initialize(); FatalErrorMessage.Register(new AppRestartHelper()); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); RhmService.Instance.SetListener(); WheelOptionsBase.SetStorage(new WheelAnglesStorage()); _hibernator = new AppHibernator(); _hibernator.SetListener(); VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs")); try { SetRenderersOptions(); } catch (Exception e) { VisualCppTool.OnException(e, null); } CommonFixes.Initialize(); CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); // Paint shop+livery generator? LiteShowroomTools.LiveryGenerator = new LiveryGenerator(); // Discord if (AppArguments.Has(AppFlag.DiscordCmd)) { // Do not show main window and wait for futher instructions? } if (SettingsHolder.Integrated.DiscordIntegration) { AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode); DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler()); DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch"; GameWrapper.Started += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode)); } // Reshade? var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade); if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), @"kn5only", StringComparison.OrdinalIgnoreCase)) { loadReShade = AppArguments.Values.Any(x => x.EndsWith(@".kn5", StringComparison.OrdinalIgnoreCase)); } if (loadReShade) { var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll"); if (File.Exists(reshade)) { Kernel32.LoadLibrary(reshade); } } // Auto-show that thing InstallAdditionalContentDialog.Initialize(); // Make sure Steam is running if (SettingsHolder.Common.LaunchSteamAtStart) { LaunchSteam().Ignore(); } // Let’s roll ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(() => { if (PatchHelper.OptionPatchSupport) { PatchUpdater.Initialize(); PatchUpdater.Instance.Updated += OnPatchUpdated; } }); }
private new void Activate() { string Username = (txtUserName.Text).Trim(); string Password = (txtPassword.Password); string TransactionID = (txtTransactionID).Text.Trim(); string Email = (txtEmail.Text).Trim(); //string Email = try { Globals.licType = cmb_LicType.Text; } catch (Exception ex) { } if (Username.ToLower().Contains("pdfreetrial") || Password.ToLower().Contains("pdfreetrial") || TransactionID.ToLower().Contains("pdfreetrial") || Email.ToLower().Contains("pdfreetrial")) { GlobusLogHelper.log.Info("pdfreetrial is not valid input !"); MessageBox.Show("pdfreetrial is not valid input !"); return; } // AddToLogs("Sending Details for Registration"); if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(TransactionID) && !string.IsNullOrEmpty(Email)) { string response_Registration = licensemanager.RegisterUser(Username, Password, cpuID, TransactionID, Email, server2); if (string.IsNullOrEmpty(response_Registration)) { var result = ModernDialog.ShowMessage("Unable to Register your License", " Message Box ", btnC); if (result == MessageBoxResult.Yes) { // MessageBox.Show("Unable to Register your License"); this.Close(); } } else { response_Registration = response_Registration.Trim(); if (response_Registration == "Sucessfully Inserted") { StartLicenseValidation(); } else { var result = ModernDialog.ShowMessage("Unable to Register your License", " Message Box ", btnC); if (result == MessageBoxResult.Yes) { // MessageBox.Show("Unable to Register your License"); } } } } else { var result = ModernDialog.ShowMessage("No Fields can be blank", " Message Box ", btnC); // MessageBox.Show("No Fields can be blank"); } }
//btnSaveSendEmail_Click private void btnSaveSendEmail_Click(object sender, RoutedEventArgs e) { ModernDialog mdd = new ModernDialog(); mdd.Buttons = new Button[] { mdd.OkButton, mdd.CancelButton, }; mdd.OkButton.TabIndex = 0; mdd.OkButton.Content = FindResource("ok").ToString(); mdd.CancelButton.TabIndex = 1; mdd.CancelButton.Content = FindResource("cancel").ToString(); mdd.TabIndex = -1; mdd.Height = 200; mdd.Title = FindResource("save_invoice").ToString(); mdd.Content = FindResource("really_want_save_invoice").ToString(); mdd.OkButton.Focus(); mdd.ShowDialog(); if (mdd.MessageBoxResult == System.Windows.MessageBoxResult.OK) { if (thread_savesendemail != null && thread_savesendemail.ThreadState == ThreadState.Running) { } else { thread_savesendemail = new Thread(() => { try { this.btnSaveSendEmail.Dispatcher.Invoke((Action)(() => { this.btnSaveSendEmail.Visibility = System.Windows.Visibility.Hidden; })); this.btnSaveInvoice.Dispatcher.Invoke((Action)(() => { this.btnSaveInvoice.IsEnabled = false; })); this.btnClose.Dispatcher.Invoke((Action)(() => { this.btnClose.IsEnabled = false; })); this.mprSaveSendEmail.Dispatcher.Invoke((Action)(() => { this.mprSaveSendEmail.Visibility = System.Windows.Visibility.Visible; this.mprSaveSendEmail.IsActive = true; })); if (PayOrder() == true) { StaticClass.GeneralClass.flag_paycash = true; btnpayother_delegate(true); this.Dispatcher.Invoke((Action)(() => { SendEmail page = new SendEmail(); page.ShowInTaskbar = false; var m = Application.Current.MainWindow; page.Owner = m; if (m.RenderSize.Width > StaticClass.GeneralClass.width_screen_general) { page.Width = StaticClass.GeneralClass.width_screen_general * 90 / 100; } if (m.RenderSize.Height > System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Bottom) { page.Height = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Bottom; } else { page.Height = m.RenderSize.Height; page.Width = m.RenderSize.Width * 90 / 100; } page.orderid = bus_tb_order.GetMaxOrderID(""); page.WindowStartupLocation = WindowStartupLocation.CenterOwner; page.ShowDialog(); })); this.Dispatcher.Invoke((Action)(() => { this.Close(); })); } else { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.CloseButton.Content = FindResource("close").ToString(); md.Content = FindResource("error_insert").ToString(); md.Title = FindResource("notification").ToString(); md.ShowDialog(); })); } this.mprSaveSendEmail.Dispatcher.Invoke((Action)(() => { this.mprSaveSendEmail.Visibility = System.Windows.Visibility.Hidden; this.mprSaveSendEmail.IsActive = false; })); this.btnSaveSendEmail.Dispatcher.Invoke((Action)(() => { this.btnSaveInvoice.Visibility = System.Windows.Visibility.Visible; })); this.btnSaveInvoice.Dispatcher.Invoke((Action)(() => { this.btnSaveInvoice.IsEnabled = true; })); this.btnClose.Dispatcher.Invoke((Action)(() => { this.btnClose.IsEnabled = true; })); } catch (Exception ex) { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.CloseButton.Content = FindResource("close").ToString(); md.Content = ex.Message; md.Title = FindResource("notification").ToString(); md.ShowDialog(); })); } }); thread_savesendemail.Start(); } } }
/// <summary> /// Shows dialog with all information about shared entry and offers a choise to user what to do with it. /// </summary> /// <param name="shared">Shared entry.</param> /// <param name="additionalButton">Label of additional button.</param> /// <param name="saveable">Can be saved.</param> /// <param name="applyable">Can be applied.</param> /// <param name="appliableWithoutSaving">Can be applied without saving.</param> /// <returns>User choise.</returns> private Choise ShowDialog(SharedEntry shared, string additionalButton = null, bool saveable = true, bool applyable = true, bool appliableWithoutSaving = true) { var description = string.Format(AppStrings.Arguments_SharedMessage, shared.Name ?? AppStrings.Arguments_SharedMessage_EmptyValue, shared.EntryType == SharedEntryType.Weather ? AppStrings.Arguments_SharedMessage_Id : AppStrings.Arguments_SharedMessage_For, shared.Target ?? AppStrings.Arguments_SharedMessage_EmptyValue, shared.Author ?? AppStrings.Arguments_SharedMessage_EmptyValue); var dlg = new ModernDialog { Title = shared.EntryType.GetDescription().ToTitle(), Content = new ScrollViewer { Content = new BbCodeBlock { BbCode = description + '\n' + '\n' + ( saveable ? AppStrings.Arguments_Shared_ShouldApplyOrSave : AppStrings.Arguments_Shared_ShouldApply), Margin = new Thickness(0, 0, 0, 8) }, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }, MinHeight = 0, MinWidth = 0, MaxHeight = 480, MaxWidth = 640 }; dlg.Buttons = new[] { applyable&& saveable?dlg.CreateCloseDialogButton( appliableWithoutSaving?AppStrings.Arguments_Shared_ApplyAndSave : AppStrings.Arguments_Shared_SaveAndApply, true, false, MessageBoxResult.Yes) : null, appliableWithoutSaving&& applyable ? dlg.CreateCloseDialogButton(saveable ? AppStrings.Arguments_Shared_ApplyOnly : AppStrings.Arguments_Shared_Apply, true, false, MessageBoxResult.OK) : null, saveable ? dlg.CreateCloseDialogButton( applyable && appliableWithoutSaving ? AppStrings.Arguments_Shared_SaveOnly : AppStrings.Toolbar_Save, true, false, MessageBoxResult.No) : null, additionalButton == null ? null : dlg.CreateCloseDialogButton(additionalButton, true, false, MessageBoxResult.None), dlg.CancelButton }.NonNull(); dlg.ShowDialog(); switch (dlg.MessageBoxResult) { case MessageBoxResult.None: return(Choise.Extra); case MessageBoxResult.OK: return(Choise.Apply); case MessageBoxResult.Cancel: return(Choise.Cancel); case MessageBoxResult.Yes: return(Choise.ApplyAndSave); case MessageBoxResult.No: return(Choise.Save); default: throw new ArgumentOutOfRangeException(); } }
public static async Task ShareAsync(SharedEntryType type, [CanBeNull] string defaultName, [CanBeNull] string target, [NotNull] byte[] data) { if (_sharingInProcess) { return; } _sharingInProcess = true; try { var contentName = defaultName; if (!SettingsHolder.Sharing.ShareWithoutName && type != SharedEntryType.Results) { contentName = Prompt.Show(ControlsStrings.Share_EnterName, ControlsStrings.Share_EnterNameHeader, defaultName, ToolsStrings.Common_None, maxLength: 60); if (contentName == null) { return; // cancelled } if (string.IsNullOrWhiteSpace(contentName)) { contentName = null; } } string id = null; if (SettingsHolder.Sharing.CustomIds && type != SharedEntryType.Results) { id = Prompt.Show(ControlsStrings.Share_EnterCustomId, ControlsStrings.Share_EnterCustomIdHeader, "", ToolsStrings.Common_None, maxLength: 200)?.Trim(); if (id == null) { return; // cancelled } if (string.IsNullOrWhiteSpace(id)) { id = null; } } var authorName = SettingsHolder.Sharing.ShareAnonymously ? null : SettingsHolder.Sharing.SharingName; if (SettingsHolder.Sharing.VerifyBeforeSharing && ModernDialog.ShowMessage( string.Format(ControlsStrings.Share_VerifyMessage, authorName ?? @"?", contentName ?? @"?", type.GetDescription()), ControlsStrings.Share_VerifyMessageHeader, MessageBoxButton.YesNo) != MessageBoxResult.Yes && type != SharedEntryType.Results) { return; } string link; using (var waiting = new WaitingDialog()) { waiting.Report(ControlsStrings.Share_InProgress); link = await SharingHelper.ShareAsync(type, contentName, target, data, id, waiting.CancellationToken); if (link == null) { return; } } ShowShared(type, link); await Task.Delay(2000); } catch (Exception e) { NonfatalError.Notify(string.Format(ControlsStrings.Share_CannotShare, type.GetDescription()), ToolsStrings.Common_CannotDownloadFile_Commentary, e); } finally { _sharingInProcess = false; } }
//GetDatabase private void GetDatabase() { try { if (thread_getdatabase != null && thread_getdatabase.ThreadState == ThreadState.Running) { } else { thread_getdatabase = new Thread(() => { try { this.mpr.Dispatcher.Invoke((Action)(() => { mpr.IsActive = true; dtgDatabase.ItemsSource = null; })); list_tb_database.Clear(); //UserCredential user_credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = client_id, ClientSecret = client_secret, }, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None, new FileDataStore("TuanNguyen.GoogleDrive.Auth.Store")).Result; UserCredential user_credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = GeneralClass.client_id, ClientSecret = GeneralClass.client_secret, }, new[] { DriveService.Scope.DriveFile }, "user", CancellationToken.None, new FileDataStore("TuanNguyen.GoogleDrive.Auth.Store")).Result; //create the drive service var driveservice = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = user_credential, ApplicationName = "Get database backup" }); this.Dispatcher.Invoke((Action)(() => { this.muiBtnBackup.Visibility = System.Windows.Visibility.Visible; })); //get file from gdrive string str_condition = "Backup_CashierRegister_"; try { FileList file_list = driveservice.Files.List().Execute(); string client_folderid_lc = ""; string client_folderid_gd = ""; string client_foldername_gd = ""; //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { client_foldername_gd = "CashierRegister_Backup"; } else { client_foldername_gd = "CashierRegister_Ser_Backup"; } //if ClientFolderInfo file isn't existed if (!System.IO.File.Exists("ClientFolderInfo")) { bool flag_exist_client_folderid = false; for (int i = 0; i < file_list.Items.Count; i++) { //if local ClientFolderInfo file is't exist and CashierRegister_Backup is existed if ((file_list.Items[i].Title == client_foldername_gd) && (file_list.Items[i].MimeType == "application/vnd.google-apps.folder") && (file_list.Items[i].ExplicitlyTrashed == false)) { //create ClientFolderInfo file System.IO.StreamWriter streamwriter = new System.IO.StreamWriter("ClientFolder"); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { streamwriter.WriteLine("FolderID:" + file_list.Items[i].Id.ToString()); streamwriter.WriteLine("FolderID:"); } //if database tupe is sqlserver else { streamwriter.WriteLine("FolderID:"); streamwriter.WriteLine("FolderID:" + file_list.Items[i].Id.ToString()); } streamwriter.Close(); StaticClass.GeneralClass.EncryptFileGD("ClientFolder", "ClientFolderInfo", StaticClass.GeneralClass.key_register_general); client_folderid_lc = file_list.Items[i].Id; client_folderid_gd = file_list.Items[i].Id; flag_exist_client_folderid = true; break; } } //if local ClientFolderInfo file isn't existed and drive ClientFolderInfo isn't existed if (flag_exist_client_folderid == false) { File folder_client = new File(); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { folder_client.Title = "CashierRegister_Backup"; } //if database type is sqlserver else { folder_client.Title = "CashierRegister_Ser_Backup"; } folder_client.Description = "This folder using for backup database"; folder_client.MimeType = "application/vnd.google-apps.folder"; //insert folder File response_folder = driveservice.Files.Insert(folder_client).Execute(); if (response_folder != null) { System.IO.StreamWriter streamwriter = new System.IO.StreamWriter("ClientFolder"); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString()); streamwriter.WriteLine("FolderID:"); } //if database tupe is sqlserver else { streamwriter.WriteLine("FolderID:"); streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString()); } streamwriter.Close(); StaticClass.GeneralClass.EncryptFileGD("ClientFolder", "ClientFolderInfo", StaticClass.GeneralClass.key_register_general); client_folderid_gd = response_folder.Id; client_folderid_lc = response_folder.Id; } } } //if local ClientFolderInfo file is existed else { bool flag_exist_client_folderid = false; System.IO.StreamReader streamreader_folder = StaticClass.GeneralClass.DecryptFileGD("ClientFolderInfo", StaticClass.GeneralClass.key_register_general); if (streamreader_folder != null) { //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { client_folderid_lc = streamreader_folder.ReadLine().Split(':')[1]; } //if database type is sqlserver else { streamreader_folder.ReadLine(); client_folderid_lc = streamreader_folder.ReadLine().Split(':')[1]; } streamreader_folder.Close(); } //if client_folderid_lc isn't null if (!String.IsNullOrWhiteSpace(client_folderid_lc)) { for (int i = 0; i < file_list.Items.Count; i++) { //if local ClientFolderInfo file is exist and drive ClientFolderInfo is existed if ((file_list.Items[i].MimeType == "application/vnd.google-apps.folder") && (file_list.Items[i].ExplicitlyTrashed == false) && (file_list.Items[i].Id == client_folderid_lc)) { client_folderid_gd = file_list.Items[i].Id; flag_exist_client_folderid = true; break; } } } else { for (int i = 0; i < file_list.Items.Count; i++) { if ((file_list.Items[i].Title == client_foldername_gd) && (file_list.Items[i].MimeType == "application/vnd.google-apps.folder") && (file_list.Items[i].ExplicitlyTrashed == false)) { client_folderid_gd = file_list.Items[i].Id; flag_exist_client_folderid = true; System.IO.StreamWriter streamwriter = new System.IO.StreamWriter("ClientFolder"); //get FolderID System.IO.StreamReader stream_reader_temp = StaticClass.GeneralClass.DecryptFileGD(current_directory + @"\ClientFolderInfo", StaticClass.GeneralClass.key_register_general); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { streamwriter.WriteLine("FolderID:" + file_list.Items[i].Id); stream_reader_temp.ReadLine(); streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString()); } //if database tupe is sqlserver else { streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString()); streamwriter.WriteLine("FolderID:" + file_list.Items[i].Id); } //close stream_reader_temp if (stream_reader_temp != null) { stream_reader_temp.Close(); } streamwriter.Close(); StaticClass.GeneralClass.EncryptFileGD("ClientFolder", "ClientFolderInfo", StaticClass.GeneralClass.key_register_general); client_folderid_gd = file_list.Items[i].Id; client_folderid_lc = file_list.Items[i].Id; break; } } } //if local ClientFolderInfo file is existed and drive ClientFolderInfo isn't existed if (flag_exist_client_folderid == false) { File folder_client = new File(); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { folder_client.Title = "CashierRegister_Backup"; } //if database type is sqlserver else { folder_client.Title = "CashierRegister_Ser_Backup"; } folder_client.Description = "This folder using for backup database"; folder_client.MimeType = "application/vnd.google-apps.folder"; //insert folder File response_folder = driveservice.Files.Insert(folder_client).Execute(); if (response_folder != null) { System.IO.StreamWriter streamwriter = new System.IO.StreamWriter("ClientFolder"); //get FolderID System.IO.StreamReader stream_reader_temp = StaticClass.GeneralClass.DecryptFileGD(current_directory + @"\ClientFolderInfo", StaticClass.GeneralClass.key_register_general); //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString()); stream_reader_temp.ReadLine(); streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString()); } //if database tupe is sqlserver else { streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString()); streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString()); } //close stream_reader_temp if (stream_reader_temp != null) { stream_reader_temp.Close(); } streamwriter.Close(); StaticClass.GeneralClass.EncryptFileGD("ClientFolder", "ClientFolderInfo", StaticClass.GeneralClass.key_register_general); client_folderid_gd = response_folder.Id; client_folderid_lc = response_folder.Id; } } } int no = 0; for (int i = 0; i < file_list.Items.Count; i++) { if (file_list.Items[i].Title.Length > 23) { if (file_list.Items[i].Parents.Count > 0) { if ((file_list.Items[i].Parents[0].Id == client_folderid_lc) && (file_list.Items[i].MimeType == "application/octet-stream") && (file_list.Items[i].Title.Substring(0, 23) == str_condition) && (file_list.Items[i].ExplicitlyTrashed == false)) { EC_tb_Database ec_tb_database = new EC_tb_Database(); ec_tb_database.Id = ++no; ec_tb_database.IdDatabase = file_list.Items[i].Id.ToString(); ec_tb_database.DownloadUrl = file_list.Items[i].DownloadUrl; ec_tb_database.BackupDate = file_list.Items[i].CreatedDate.ToString(); ec_tb_database.FileSize = (file_list.Items[i].FileSize / 1000).ToString() + "KB"; ec_tb_database.BitmapImage_Restore = bitmapimage_restore; ec_tb_database.BitmapImage_Delete = bitmapimage_delete; _lstExt.Add(file_list.Items[i].FileExtension.ToString()); list_tb_database.Add(ec_tb_database); } } } } } catch (System.Net.Http.HttpRequestException) { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.Title = FindResource("notification").ToString(); md.Content = FindResource("internet_problem").ToString(); md.CloseButton.Content = FindResource("close").ToString(); md.ShowDialog(); })); } this.Dispatcher.Invoke((Action)(() => { tblTotal.Text = FindResource("checkout").ToString() + "(" + list_tb_database.Count.ToString() + ")"; dtgDatabase.ItemsSource = list_tb_database; mpr.IsActive = false; dtgDatabase.Visibility = System.Windows.Visibility.Visible; })); //get email address string email_address = driveservice.About.Get().Execute().User.EmailAddress.ToString(); this.Dispatcher.Invoke((Action)(() => { this.tblEmailAddress.Visibility = System.Windows.Visibility.Visible; this.tblEmailAddress.Text = driveservice.About.Get().Execute().User.EmailAddress; //set login logout this.tblLogout.Visibility = System.Windows.Visibility.Visible; this.tblLogin.Visibility = System.Windows.Visibility.Hidden; })); } catch (AggregateException) { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); md.Title = FindResource("notification").ToString(); md.Content = FindResource("have_not_access").ToString(); md.ShowDialog(); })); } }); thread_getdatabase.Start(); } } catch (Exception ex) { this.Dispatcher.Invoke((Action)(() => { ModernDialog md = new ModernDialog(); FindResource("notification").ToString(); md.Content = ex.Message; md.ShowDialog(); })); } }
//串口数据处理 private void DataHandlerThread(object data) { //形参data为串口接收的数据 int minusLocation = -1; byte[] receiveData = data as byte[]; //用于将byte[]数组解析成字符串 ASCIIEncoding asciiEncoding = new ASCIIEncoding(); //更新数据 switch (Flag.nFunc) { case 1: //设置电机转速 break; case 2: //电机转速 Data.MotoSpeed = receiveData[3] * 256 + receiveData[4]; Data.PlatSpeed = (int)(Data.MotoSpeed / 3.0 * 10) / 10.0; Data.FricSpeed = (int)(Data.PlatSpeed / 60 * SysParam.FricRadius * 100) / 100.0; RTDatas.uiDataRT.MotoSpeed = Data.MotoSpeed.ToString(); RTDatas.uiDataRT.PlatSpeed = Data.PlatSpeed.ToString(); RTDatas.uiDataRT.FricSpeed = Data.FricSpeed.ToString(); //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "PlateSpeed", new PlotPoint(Flag.SysTime, Data.PlatSpeed)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "MotoSpeed", new PlotPoint(Flag.SysTime, Data.MotoSpeed)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "FricSpeed", new PlotPoint(Flag.SysTime, Data.FricSpeed)); break; case 3: //电机扭矩 Data.MotoTorque = receiveData[3] * 256 + receiveData[4]; RTDatas.uiDataRT.MotoTorque = Data.MotoTorque.ToString(); //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "MotoTor", new PlotPoint(Flag.SysTime, Data.MotoTorque)); break; case 4: //查询温湿度及压力 string s = asciiEncoding.GetString(receiveData); s = s.Substring(0, s.Length - 2); //判断是否出现负号 minusLocation = s.IndexOf("-"); if (minusLocation >= 0) { s = s.Insert(minusLocation, "+"); } string[] strs = s.Split('+'); try { Data.Pressure1 = double.Parse(strs[1]) + SysParam.ExtraPress_1; Data.Pressure2 = double.Parse(strs[2]) + SysParam.ExtraPress_2; Data.Temperature = double.Parse(strs[3]); Data.Humidity = double.Parse(strs[4]); } catch (Exception e) { ModernDialog.ShowMessage("预计:" + Flag.nFlag.ToString() + "\n实际:" + receiveData.GetLength(0).ToString() + "\n解析:" + strs.Length.ToString() + "\n" + e.ToString(), "Message:", MessageBoxButton.OK); } RTDatas.uiDataRT.Pressure = Data.Pressure1.ToString(); RTDatas.uiDataRT.FricForce = (Data.Pressure2 * SysParam.ArmRatio).ToString(); RTDatas.uiDataRT.Temperature = Data.Temperature.ToString(); RTDatas.uiDataRT.Humidity = Data.Humidity.ToString(); //将系统参数写出到文件 if (MotoData.StartMoto == true) { string str = MotoData.MotoTime.ToString() + "\t" + DateTime.Now.ToString("yyyy-MM-dd") + "\t" + DateTime.Now.ToString("HH:mm:ss") + "\t"; str = str + RTDatas.uiDataRT.Pressure + "\t" + RTDatas.uiDataRT.Temperature + "\t" + RTDatas.uiDataRT.Humidity + "\t"; str = str + RTDatas.uiDataRT.PlatSpeed + "\t" + RTDatas.uiDataRT.MotoSpeed + "\t" + RTDatas.uiDataRT.MotoTorque + "\t"; str = str + RTDatas.uiDataRT.FricForce + "\t" + RTDatas.uiDataRT.FricSpeed; SetParam.dataFile.WriteLine(str); //写出数据 if (Flag.RecData == true) { RTDatas.mydataFile.WriteLine(str); } } //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Pressure", new PlotPoint(Flag.SysTime, Data.Pressure1)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Temperature", new PlotPoint(Flag.SysTime, Data.Temperature)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Humidity", new PlotPoint(Flag.SysTime, Data.Humidity)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "FricForce", new PlotPoint(Flag.SysTime, Data.Pressure2 * SysParam.ArmRatio)); break; } }
private static async void BackgroundInitialization() { try { #if DEBUG CupClient.Instance?.LoadRegistries().Forget(); #endif await Task.Delay(500); AppArguments.Set(AppFlag.SimilarThreshold, ref CarAnalyzer.OptionSimilarThreshold); if (SettingsHolder.Drive.ScanControllersAutomatically) { try { InitializeDirectInputScanner(); } catch (Exception e) { VisualCppTool.OnException(e, null); } } string additional = null; AppArguments.Set(AppFlag.SimilarAdditionalSourceIds, ref additional); if (!string.IsNullOrWhiteSpace(additional)) { CarAnalyzer.OptionSimilarAdditionalSourceIds = additional.Split(';', ',').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray(); } await Task.Delay(500); if (AppArguments.Has(AppFlag.TestIfAcdAvailable) && !Acd.IsAvailable) { NonfatalError.NotifyBackground(@"This build can’t work with encrypted ACD-files"); } if (AppUpdater.JustUpdated && SettingsHolder.Common.ShowDetailedChangelog) { List <ChangelogEntry> changelog; try { changelog = await Task.Run(() => AppUpdater.LoadChangelog().Where(x => x.Version.IsVersionNewerThan(AppUpdater.PreviousVersion)).ToList()); } catch (WebException e) { NonfatalError.NotifyBackground(AppStrings.Changelog_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks, e); return; } catch (Exception e) { NonfatalError.NotifyBackground(AppStrings.Changelog_CannotLoad, e); return; } Logging.Write("Changelog entries: " + changelog.Count); if (changelog.Any()) { Toast.Show(AppStrings.App_AppUpdated, AppStrings.App_AppUpdated_Details, () => { ModernDialog.ShowMessage(changelog.Select(x => $@"[b]{x.Version}[/b]{Environment.NewLine}{x.Changes}") .JoinToString(Environment.NewLine.RepeatString(2)), AppStrings.Changelog_RecentChanges_Title, MessageBoxButton.OK); }); } } await Task.Delay(1500); RevertFileChanges(); await Task.Delay(1500); CustomUriSchemeHelper.Initialize(); #if !DEBUG CupClient.Instance?.LoadRegistries().Forget(); #endif await Task.Delay(5000); await Task.Run(() => { foreach (var f in from file in Directory.GetFiles(FilesStorage.Instance.GetDirectory("Logs")) where file.EndsWith(@".txt") || file.EndsWith(@".log") || file.EndsWith(@".json") let info = new FileInfo(file) where info.LastWriteTime < DateTime.Now - TimeSpan.FromDays(3) select info) { f.Delete(); } }); } catch (Exception e) { Logging.Error(e); } }
//初始化函数 void IniSystem() { //创建数据文件目录 if (!Directory.Exists("D:\\Program Files\\TRIBOLOGY")) { Directory.CreateDirectory("D:\\Program Files\\TRIBOLOGY"); } //读取力臂比值 if (File.Exists("D:\\Program Files\\TRIBOLOGY\\SysParam.txt")) { StreamReader paramReader = new StreamReader("D:\\Program Files\\TRIBOLOGY\\SysParam.txt"); string line = null; string[] strs = null; while ((line = paramReader.ReadLine()) != null) { try { //解析数据 strs = line.Split('\t'); switch (strs[0]) { case "串口号:": SysParam.PortName = int.Parse(strs[1]); break; case "波特率:": SysParam.BaudRate = int.Parse(strs[1]); break; case "校验位:": SysParam.Parity = strs[1]; break; case "停止位:": SysParam.StopBit = strs[1]; break; case "力臂-1:": if (strs[1] != "") { SysParam.Arm_1 = double.Parse(strs[1]); } break; case "力臂-2:": if (strs[1] != "") { SysParam.Arm_2 = double.Parse(strs[1]); } break; case "力臂比值:": SysParam.ArmRatio = double.Parse(strs[1]); break; case "压力-1零点附加值:": SysParam.ExtraPress_1 = double.Parse(strs[1]); break; case "压力-2零点附加值:": SysParam.ExtraPress_2 = double.Parse(strs[1]); break; } } catch (Exception e) { MessageBox.Show("解析数据出现问题\n" + e.ToString()); return; } } paramReader.Close(); } else { StreamWriter paramFile = new StreamWriter("D:\\Program Files\\TRIBOLOGY\\SysParam.txt"); paramFile.Close(); ModernDialog.ShowMessage("首次运行,未找到系统配置文件,将使用默认参数,请及时设置……", "Message:", MessageBoxButton.OK); } //使用事件方式处理串口接收到的数据 serPort.DataReceived += new SerialDataReceivedEventHandler(seriReceive); //定时器,计时周期250 ms timer.Interval = TimeSpan.FromMilliseconds(250); timer.Tick += new EventHandler(Timer_Tick); }
private static async Task <ArgumentHandleResult> ProcessSharedEntry(SharedEntry shared, bool justGo) { var data = shared?.Data; if (data == null) { return(ArgumentHandleResult.Failed); } switch (shared.EntryType) { case SharedEntryType.PpFilter: return(ProcessSharedPpFilter(shared, data, justGo)); case SharedEntryType.CarSetup: return(ProcessSharedCarSetup(shared, data, justGo)); case SharedEntryType.ControlsPreset: return(ProcessSharedControlsPreset(shared, data, justGo)); case SharedEntryType.ForceFeedbackPreset: return(ProcessSharedForceFeedbackPreset(shared, data, justGo)); case SharedEntryType.VideoSettingsPreset: return(ProcessSharedSettingsPreset(AcSettingsHolder.VideoPresets, shared, data, justGo)); case SharedEntryType.AudioSettingsPreset: return(ProcessSharedSettingsPreset(AcSettingsHolder.AudioPresets, shared, data, justGo)); case SharedEntryType.AssistsSetupPreset: return(ProcessSharedAssistsSetupPreset(shared, data, justGo)); case SharedEntryType.TrackStatePreset: return(ProcessSharedTrackStatePreset(shared, data, justGo)); case SharedEntryType.QuickDrivePreset: return(await ProcessSharedQuickDrivePreset(shared, data, justGo)); case SharedEntryType.RaceGridPreset: return(ProcessSharedRaceGridPreset(shared, data, justGo)); case SharedEntryType.RhmPreset: return(ProcessSharedRhmPreset(shared, data, justGo)); case SharedEntryType.UserChampionship: return(OptionUserChampionshipExtMode ? ProcessSharedUserChampionshipExt(shared, data, justGo) : ProcessSharedUserChampionship(shared, data, justGo)); case SharedEntryType.Weather: return(ProcessSharedWeather(shared, data, justGo)); case SharedEntryType.CustomShowroomPreset: return(ProcessSharedCustomShowroomPreset(shared, data, justGo)); case SharedEntryType.CustomPreviewsPreset: return(ProcessSharedCustomPreviewsPreset(shared, data, justGo)); case SharedEntryType.CspSettings: return(ProcessSharedCspSettings(shared, data, justGo)); case SharedEntryType.CarLodsGenerationPreset: return(ProcessSharedCarLodsGenerationPreset(shared, data, justGo)); case SharedEntryType.BakedShadowsPreset: return(ProcessSharedBakedShadowsPreset(shared, data, justGo)); case SharedEntryType.Replay: throw new NotSupportedException(); case SharedEntryType.Results: ModernDialog.ShowMessage(Encoding.UTF8.GetString(data)); return(ArgumentHandleResult.Successful); default: throw new Exception(string.Format(AppStrings.Arguments_SharedUnsupported, shared.EntryType)); } }
public void rdbSingleUserInvite() { try { objInviteManagers.rdbSingleUserInvite = true; objInviteManagers.rdbMultipleUserInvite = false; btnInviteEmail_Browse.Visibility = Visibility.Hidden; txtInviteEmail.Visibility = Visibility.Hidden; lbInviteEmail.Visibility = Visibility.Hidden; ClGlobul.lstEmailInvites.Clear(); try { UserControl_SingleUser obj = new UserControl_SingleUser(); obj.UserControlHeader.Text = "Enter Email Here "; obj.txtEnterSingleMessages.ToolTip = "Format :- [email protected]"; var window = new ModernDialog { Content = obj }; window.ShowInTaskbar = true; window.MinWidth = 100; window.MinHeight = 300; Button customButton = new Button() { Content = "SAVE" }; customButton.Click += (ss, ee) => { closeEvent(); window.Close(); }; window.Buttons = new Button[] { customButton }; window.ShowDialog(); MessageBoxButton btnC = MessageBoxButton.YesNo; var result = ModernDialog.ShowMessage("Are you sure want to save ?", "Message Box", btnC); if (result == MessageBoxResult.Yes) { TextRange textRange = new TextRange(obj.txtEnterSingleMessages.Document.ContentStart, obj.txtEnterSingleMessages.Document.ContentEnd); if (!string.IsNullOrEmpty(textRange.Text)) { string enterText = textRange.Text; string[] arr = Regex.Split(enterText, "\r\n"); foreach (var arr_item in arr) { if (!string.IsNullOrEmpty(arr_item) || !arr_item.Contains("")) { ClGlobul.lstEmailInvites.Add(arr_item); } } } GlobusLogHelper.log.Info(" => [ Email Loaded : " + ClGlobul.lstEmailInvites.Count + " ]"); GlobusLogHelper.log.Debug("Email : " + ClGlobul.lstEmailInvites.Count); } } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } } catch (Exception ex) { GlobusLogHelper.log.Error(" Error :" + ex.StackTrace); } }
private void SplitButton_Click(object sender, System.Windows.RoutedEventArgs e) { ModernDialog.ShowMessage("Thanks for clicking me!", "SplitButton Click", MessageBoxButton.OK); }
/// <summary> /// Displays the non selection warning. /// </summary> private void DisplayNonSelectionWarning() { ModernDialog.ShowMessage("No selected test plan.", "Warning", MessageBoxButton.OK); }
protected override void OnExecute(object parameter) { ModernDialog.ShowMessage(string.Format(CultureInfo.CurrentUICulture, "被超连接触发的带参数的对话框\r\n参数是:{0}", parameter), "带参数的对话框", System.Windows.MessageBoxButton.OK); }
private void DecryptViewModel_Completed(string caption, string message) { ModernDialog.ShowMessage(message, caption, MessageBoxButton.OK); }
private void Th_Click(object sender, RoutedEventArgs e) { ///批量替换文本中的值 string FilePath = Path.GetDirectoryName(FileRoute.Text) + "\\程序串联"; string WcsPath = WCS.Text; //文件中的坐标值 string AWcsPath = AWCS.Text; //输入的坐标值 string[] pathFile = Directory.GetFiles(FileRoute.Text); string Th = null; foreach (string str in pathFile) { FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.Default); Th = sr.ReadToEnd(); ///查找文本中的WcsPath,替换为AWcsPath Th = Th.Replace(WcsPath, AWcsPath); sr.Close(); fs.Close(); FileStream fs2 = new FileStream(str, FileMode.Open, FileAccess.Write); ///Encoding.Default 参照电脑默认编码保存文件 StreamWriter sw = new StreamWriter(fs2, Encoding.Default); sw.WriteLine(Th); sw.Close(); fs2.Close(); } this.Dk.IsEnabled = true; ModernDialog.ShowMessage("替换坐标成功 ", "提示", MessageBoxButton.OK); //判断是否修改完坐标后打开文件所在目录 if (true == this.op.IsChecked) { if (true == this.copy.IsChecked) { string SPath1 = (System.IO.Path.GetDirectoryName(FileRoute.Text)) + "\\程序串联"; Process.Start("Explorer.exe", SPath1); } else { string Path2 = FileRoute.Text; Process.Start("Explorer.exe", Path2); } } ///重新检测坐标 ///清空listView listView.Items.Clear(); string XZPath = Cap.NCFileRoute; string FullName = null; string FileName = null; string Tools = null; string WCS_A = null; DirectoryInfo d = new DirectoryInfo(XZPath); FileInfo[] Files = d.GetFiles("*.nc"); List <string> lstr = new List <string>(); ///获取WCS坐标添加到listView foreach (FileInfo file in Files) { ///获取文件夹下文件名 FullName = file.FullName; FileName = file.Name; ///获取文件夹下所有程序的坐标系 StreamReader Wcs_objReader = new StreamReader(FullName); int j = 0; while ((WCS_A = Wcs_objReader.ReadLine()) != null) { j++; ///第二行 if (j == Int32.Parse(Cap.WCS_Line)) { ///截取字符中两个指定字符间的字符 WCS_A = InterceptStr(WCS_A, Cap.WCS_Start, Cap.WCS_End); WCS_A = WCS_A.Trim(); //去除首尾空格 break; } } Wcs_objReader.Close();//关闭流 ///获取文件夹下所有程序的刀具尺寸 StreamReader Tools_objReader = new StreamReader(FullName); int i = 0; while ((Tools = Tools_objReader.ReadLine()) != null) { i++; ///第七行 if (i == Int32.Parse(Cap.T_Line)) { ///截取字符中两个指定字符间的字符 Tools = InterceptStr(Tools, Cap.T_Start, Cap.T_End); Tools = Tools.Trim(); //去除首尾空格 break; } } Tools_objReader.Close(); //关闭流 ///将文件名,坐标系,刀具名称添加到ListView listView.Items.Add(new { A = FileName, B = WCS_A, C = Tools }); ///重新检测坐标系添加到ListView WCS.Text = WCS_A; //判断是否复制串联好的文件到上级目录 if (true == this.copy.IsChecked) { //将刀具名称和坐标系加入到文件名中 string NewFile = FilePath + "\\" + "[" + Tools + "]" + "[" + WCS_A + "]-" + FileName; Directory.CreateDirectory(FilePath); File.Copy(FullName, NewFile, true); } } }
private void Button_Click_1(object sender, RoutedEventArgs e) { var rows = GetDataGridRows(DG1); foreach (DataGridRow row in rows) { ProductFieldModel rowView = (ProductFieldModel)row.Item; } String script = "<? php $node = menu_get_object(); if ($node &&"; KalkulatorWidok.NewScript.Products.ForEach(p => { script += "$node->nid == '" + p.ProductNode + "' " + "|| "; }); script = script.Substring(script.Length - 3); script += "): ?>"; script += "<script>"; script += "var product_rules = {"; KalkulatorWidok.NewScript.Fields.ForEach(f => { script += f.IdValue + ":"; }); // < script > // var product_rules = { // field_swiatlo: // { // operator: '+', // values: [0, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100] // }, // field_powieszchnia: // { // operator: '*', // values: [1, 1, 1.1] // }, // field_mocowanie: // { // related_fields: // { // field_swiatlo: // { // operator: '+', // values: // { // 0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] // } //} // } // }, // field_zestaw_montazowy: { // operator: '+', // values: [0, 0, 200] // } // }; // </script> // <? php endif; ?> try { bbCodeBlock.LinkNavigator.Navigate(new Uri("/Pages/NewScript/NewScriptFieldSettings.xaml", UriKind.Relative), this); } catch (Exception error) { ModernDialog.ShowMessage(error.Message, FirstFloor.ModernUI.Resources.NavigationFailed, MessageBoxButton.OK); } }
private void Xz_Click(object sender, RoutedEventArgs e) { ///打开选择文件夹对话框 CommonOpenFileDialog dialog = new CommonOpenFileDialog { IsFolderPicker = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { Cap.NCFileRoute = dialog.FileName; string XZPath = Cap.NCFileRoute; ///判断选择的文件夹中是否含有后缀名为NC的文件 if (Directory.GetFiles(XZPath, "*.nc").Length > 0) { FileRoute.Text = XZPath; ///如果存在,将替换按钮显示 this.Th.IsEnabled = true; this.Dk.IsEnabled = false; ///读取选择的文件夹中NC文件 ///清空listView listView.Items.Clear(); string FullName = null; string FileName = null; string Tools = null; string WCS = null; ///读取ini文件数据 string inifilePath = AppDomain.CurrentDomain.BaseDirectory + "NC Config\\" + Cap.IniFileName + ".ini"; //设置路径 IniFile iniFile = new IniFile(inifilePath); if (File.Exists(inifilePath)) { ///读取ini文件数据 Cap.WCS_Line = iniFile.ReadIni("WCS_Config", "WCS_Line"); Cap.WCS_Start = iniFile.ReadIni("WCS_Config", "WCS_Start"); Cap.WCS_End = iniFile.ReadIni("WCS_Config", "WCS_End"); Cap.T_Line = iniFile.ReadIni("T_Config", "T_Line"); Cap.T_Start = iniFile.ReadIni("T_Config", "T_Start"); Cap.T_End = iniFile.ReadIni("T_Config", "T_End"); } else { ModernDialog.ShowMessage(Cap.IniFileName + " 配置文件不存在,请检查", "警告", MessageBoxButton.OK); } DirectoryInfo d = new DirectoryInfo(XZPath); FileInfo[] Files = d.GetFiles("*.nc"); List <string> lstr = new List <string>(); ///获取文件夹下文件名,将路径显示到listView foreach (FileInfo file in Files) { ///获取文件夹下文件名 FullName = file.FullName; FileName = file.Name; ///获取文件夹下所有程序的坐标系 StreamReader Wcs_objReader = new StreamReader(FullName); int j = 0; while ((WCS = Wcs_objReader.ReadLine()) != null) { j++; ///第二行 if (j == Int32.Parse(Cap.WCS_Line)) { ///截取字符中两个指定字符间的字符 WCS = InterceptStr(WCS, Cap.WCS_Start, Cap.WCS_End); WCS = WCS.Trim(); //去除首尾空格 break; } } Wcs_objReader.Close();//关闭流 ///获取文件夹下所有程序的刀具尺寸 StreamReader Tools_objReader = new StreamReader(FullName); int i = 0; while ((Tools = Tools_objReader.ReadLine()) != null) { i++; ///第七行 if (i == Int32.Parse(Cap.T_Line)) { ///截取字符中两个指定字符间的字符 Tools = InterceptStr(Tools, Cap.T_Start, Cap.T_End); Tools = Tools.Trim(); //去除首尾空格 break; } } Tools_objReader.Close(); //关闭流 ///将文件名,坐标系,刀具名称添加到ListView listView.Items.Add(new { A = FileName, B = WCS, C = Tools }); this.WCS.Text = WCS; } ///判断程序是否有坐标系 if (WCS.Contains("G5")) { ///包含坐标系 } else { ModernDialog.ShowMessage("程序中不存在坐标系,请检查程序或者配置文件", "警告", MessageBoxButton.OK); ///不存在 this.Th.IsEnabled = false; } } else { ///不存在 this.Th.IsEnabled = false; ///清空ListBox listView.Items.Clear(); ModernDialog.ShowMessage("您选择的文件夹不存在.NC文件程序", "警告", MessageBoxButton.OK); } } }
/// <summary> /// Function to control the first launch install. /// </summary> public async void FirstInstall() { VersionCheck.GetLatestGameVersionName(); await VersionCheck.UpdateLatestVersions(); //Get the current root path and prepare the installation var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchPath = VersionCheck.GamePatchPath; var patchVersion = VersionCheck.GetLatestGameVersionName(); //Create an empty var containing the progress report from the patcher var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); Task task = null; try { task = RxPatcher.Instance.ApplyPatchFromWeb(patchPath, targetDir, applicationDir, progress, cancellationTokenSource.Token, VersionCheck.InstructionsHash); //Create the update window var window = new ApplyUpdateWindow(task, RxPatcher.Instance, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Install); window.Owner = this; //Show the dialog and wait for completion window.Show(); while (!task.IsCompleted) { await Task.Delay(1000); if (cancellationTokenSource.IsCancellationRequested) { task.Dispose(); } } RxLogger.Logger.Instance.Write($"Install complete, task state isCompleted = {task.IsCompleted}"); } catch (Exception) { } if (task?.IsCompleted == true && task?.Status != TaskStatus.Canceled) { VersionCheck.UpdateGameVersion(); //Create the UE3 redist dialog RxLogger.Logger.Instance.Write("Creating the UE3 Redist package dialog"); ModernDialog ueRedistDialog = new ModernDialog(); ueRedistDialog.Title = "UE3 Redistributable"; ueRedistDialog.Content = MessageRedistInstall; ueRedistDialog.Buttons = new Button[] { ueRedistDialog.OkButton, ueRedistDialog.CancelButton }; ueRedistDialog.ShowDialog(); RxLogger.Logger.Instance.Write($"Did the user want to install the UE3 Redist? - {ueRedistDialog.DialogResult.Value}"); if (ueRedistDialog.DialogResult.Value == true) { bool downloadSuccess = false; var bestPatchServer = RxPatcher.Instance.UpdateServerHandler.SelectBestPatchServer(); Uri RedistServer = bestPatchServer.Uri; //Create new URL based on the patch url (Without the patch part) String redistUrl = RedistServer + "redists/UE3Redist.exe"; string systemPath = GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"; //Create canceltokens to stop the downloaderthread if neccesary CancellationTokenSource downloaderTokenSource = new CancellationTokenSource(); CancellationToken downloaderToken = downloaderTokenSource.Token; //Redist downloader statuswindow GeneralDownloadWindow redistWindow = new GeneralDownloadWindow(downloaderTokenSource, "UE3Redist download"); redistWindow.Show(); //Start downloading redist RxLogger.Logger.Instance.Write($"Downloading UE3 Redist from {RedistServer.AbsoluteUri}"); downloadSuccess = await DownloadRedist(redistUrl, systemPath, downloaderToken, (received, size) => { redistWindow.UpdateProgressBar(received, size); }); RxLogger.Logger.Instance.Write("UE3 Redist Download Complete"); redistWindow.Close(); if (downloadSuccess) { //When done, execute the UE3Redist here try { using (Process ue3Redist = Process.Start(systemPath)) { ue3Redist.WaitForExit(); if (ue3Redist.ExitCode != 0)//If redist install fails, notify the user { MessageBox.Show("Error while installing the UE3 Redist."); } else//Everything done! save installed flag and restart { Properties.Settings.Default.Installed = true; Properties.Settings.Default.Save(); try { System.IO.File.Delete(systemPath); System.IO.Directory.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\"); } catch (Exception) { MessageBox.Show("Could not cleanup the redist file. This won't hinder the game."); } } } } catch { MessageBox.Show("Error while executing the UE3 Redist."); } finally { //Restart launcher System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } } if (downloadSuccess == false) { MessageBox.Show("Unable to download the UE3 Redist (corrupt download)"); } } else { ModernDialog notInstalledDialog = new ModernDialog(); notInstalledDialog.Title = "UE3 Redistributable"; notInstalledDialog.Content = MessageNotInstalled; notInstalledDialog.Buttons = new Button[] { notInstalledDialog.OkButton }; notInstalledDialog.ShowDialog(); //Shutdown launcher Application.Current.Shutdown(); } } else { Application.Current.Shutdown(); } }
//定时器事件响应(轮询查询) void Timer_Tick(object sender, EventArgs e) { //查询功能标志 flag++; if (flag > 4) { flag = 1; } Flag.SysTime += 0.25; //以轮询方式查询系统参数 switch (flag) { case 1: if (MotoData.StartMoto == true) //电机是否启动 { MotoData.MotoTime++; if (MotoData.MotoTime <= MotoData.N) //未到达运行总时间 { Flag.nFunc = 1; //功能标志 Flag.nFlag = 8; //接收字节数标志 dataRec.Clear(); //***********************待验证************************************** serPort.DiscardInBuffer(); //******************************************************************** sendData.setMotoSpeed(MotoData.SpeedData[MotoData.MotoTime], serPort); //进度条 RTDatas.uiDataRT.LeftTime = "剩余时间:" + (MotoData.N - MotoData.MotoTime).ToString() + "s"; RTDatas.uiDataRT.ProBar = (double)(MotoData.MotoTime) / MotoData.N; RTDatas.uiDataRT.ProBarTex = ((int)(RTDatas.uiDataRT.ProBar * 1000) / 10.0).ToString() + "%"; RTDatas.uiDataRT.ProBarVisible = Visibility.Visible; } else { // 发布事件 if (OnStopMoto != null) { OnStopMoto(this, new EventArgs()); } if (Flag.RecData == true) { if (OnSaveFile != null) { OnSaveFile(this, new EventArgs()); } } Flag.nFunc = 1; //功能标志 Flag.nFlag = 8; //接收字节数标志 sendData.setMotoSpeed(0, serPort); ModernDialog.ShowMessage("电机运行结束!", "Message:", MessageBoxButton.OK); MotoData.MotoTime = 0; RTDatas.uiDataRT.ProBarVisible = Visibility.Hidden; } } break; //查询电机转速 case 2: Flag.nFunc = 2; //功能标志 Flag.nFlag = 7; //接收字节数标志 dataRec.Clear(); //***********************待验证************************************** serPort.DiscardInBuffer(); //******************************************************************** sendData.qurMotoSpeed(serPort); break; //查询电机扭矩 case 3: Flag.nFunc = 3; Flag.nFlag = 7; dataRec.Clear(); //***********************待验证************************************** serPort.DiscardInBuffer(); //******************************************************************** sendData.qurMotoTorque(serPort); break; //查询温湿度及压力 case 4: Flag.nFunc = 4; Flag.nFlag = 27; dataRec.Clear(); //***********************待验证************************************** serPort.DiscardInBuffer(); //******************************************************************** sendData.qurHumTemPre(serPort); break; } }
private void EncryptViewModel_ShowMessageBox(string caption, string message) { ModernDialog.ShowMessage(message, caption, MessageBoxButton.OK); }
/// <summary> /// Executes the command. /// </summary> /// <param name="parameter">The parameter.</param> protected override void OnExecute(object parameter) { ModernDialog.ShowMessage(string.Format(CultureInfo.CurrentUICulture, "Executing command, command parameter = '{0}'", parameter), "SampleCommand", MessageBoxButton.OK); }