public void Constructor_CreateNewProjectFromBundle_BundleHasNoLdmlFile_WsIsoIsSet_ProjectIsCreatedSuccessfully() { Sldr.Initialize(); try { var bundle = GetGlyssenBundleToBeUsedForProject(false); bundle.Metadata.Language.Ldml = ""; bundle.Metadata.Language.Iso = "ach"; bundle.Metadata.Language.Name = "Acholi"; // see messages in Assert.AreEqual lines below var project = new Project(bundle); m_tempProjectFolders.Add(Path.GetDirectoryName(Path.GetDirectoryName(project.ProjectFilePath))); WaitForProjectInitializationToFinish(project, ProjectState.ReadyForUserInteraction); Assert.IsNotNull(project); Assert.IsNotEmpty(project.QuoteSystem.AllLevels); Assert.AreEqual("ach", project.WritingSystem.Id); Assert.AreEqual("Acoli", project.WritingSystem.Language.Name, "This name should be coming from the \"global\" cache, not from the metadata above - note spelling difference."); Assert.AreEqual("ach", project.WritingSystem.Language.Iso3Code, "If \"ach\" is not found in the global cache, the lnaguage subtag will be considered \"private-use\" and the " + "ISO code will be null"); Assert.AreEqual("ach", project.WritingSystem.Language.Code); } finally { Sldr.Cleanup(); } }
public void TestFixtureTearDown() { Sldr.Cleanup(); var ntBooks = SilBooks.Codes_3Letter.Skip(39).ToArray(); if (m_results.Count == 27 || m_results.Count == 1) { foreach (var bookCode in ntBooks) { CastSizeRowValues validCast; if (m_results.TryGetValue(bookCode, out validCast)) { Debug.WriteLine("[TestCase(\"" + bookCode + "\", " + (validCast.Male - 1) + ")]"); } } Debug.WriteLine("****************"); } else { Debug.WriteLine("WARNING: not all NT books are included in these results!!!!!!!!!!!"); } Debug.WriteLine("Copy and paste the following into the CastSizePlanningViewModel constructor:"); Debug.WriteLine(""); foreach (var bookCode in ntBooks) { CastSizeRowValues validCast; if (m_results.TryGetValue(bookCode, out validCast)) { Debug.WriteLine("case \"" + bookCode + "\":"); if (bookCode == "HEB") { Debug.WriteLine("switch (m_project.DramatizationPreferences.ScriptureQuotationsShouldBeSpokenBy)"); Debug.WriteLine("{"); Debug.WriteLine("\tcase DramatizationOption.DedicatedCharacter:"); Debug.WriteLine("\t\tsmallCast.Male = Math.Max(smallCast.Male, 1);"); Debug.WriteLine("\t\tbreak;"); Debug.WriteLine("\tcase DramatizationOption.DefaultCharacter:"); Debug.WriteLine("\t\tsmallCast.Male = Math.Max(smallCast.Male, 4);"); Debug.WriteLine("\t\tbreak;"); Debug.WriteLine("\tcase DramatizationOption.Narrator:"); Debug.WriteLine("\t\tsmallCast.Male = Math.Max(smallCast.Male, 0);"); Debug.WriteLine("\t\tbreak;"); Debug.WriteLine("}"); } else { Debug.WriteLine("smallCast.Male = Math.Max(smallCast.Male, " + (validCast.Male - 2) + ");"); } if (validCast.Female != 2) { Debug.WriteLine("smallCast.Female = " + validCast.Female + ";"); } Debug.WriteLine("break;"); } } }
public static void Main(string[] args) { ExceptionLogging.Initialize("17a42e4a67dd2e42d4aa40d8bf2d23ee", Assembly.GetExecutingAssembly().GetName().Name); var options = AuxToolOptions.ParseCommandLineArgs(args); if (options == null) { return; } if (!File.Exists(options.Project)) { Console.WriteLine("Can't find project file '{0}'", options.Project); return; } Icu.Wrapper.Init(); // initialize the SLDR Sldr.Initialize(); try { var projectFileInfo = new FileInfo(options.Project); options.Project = projectFileInfo.FullName; if (options.InfoOnly) { DisplayInfo(options); } ExceptionLogging.Client.AddInfo(options.Project, FwProject.GetModelVersion(options.Project)); if (options.Migrate) { MigrateData(options); } if (options.Commit) { CommitData(options); } } finally { if (Sldr.IsInitialized) { Sldr.Cleanup(); } Icu.Wrapper.Cleanup(); } }
public void Dispose() { if (Sldr.IsInitialized) { Sldr.Cleanup(); } if (Directory.Exists(_ldmlFolder)) { Directory.Delete(_ldmlFolder, true); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); FwRegistryHelper.Initialize(); FwUtils.InitializeIcu(); Sldr.Initialize(); using (var form = new LCMBrowserForm()) { Application.Run(form); } Sldr.Cleanup(); }
public void Dispose() { FolderContainingLdml.Dispose(); string sldrCachePath = Sldr.SldrCachePath; Sldr.Cleanup(); // clear out SLDR cache DirectoryInfo di = new DirectoryInfo(sldrCachePath); foreach (FileInfo fi in di.GetFiles()) { fi.Delete(); } // The OfflineSldrAttribute has been assigned to the entire test assembly, so we reinitialize // the SLDR back to what it was Sldr.Initialize(true, sldrCachePath); }
public TestEnvironment(bool sldrOffline = true, DateTime?embeddedAllTagsTime = null) { string sldrCachePath = Sldr.SldrCachePath; Sldr.Cleanup(); if (embeddedAllTagsTime == null) { Sldr.Initialize(sldrOffline, sldrCachePath); } else { Sldr.Initialize(sldrOffline, sldrCachePath, embeddedAllTagsTime.Value); } FolderContainingLdml = new TemporaryFolder("SldrTests"); NamespaceManager = new XmlNamespaceManager(new NameTable()); NamespaceManager.AddNamespace("sil", "urn://www.sil.org/ldml/0.1"); }
public void Constructor_CreateNewProjectFromBundle_BundleHasNoLdmlFile_WsLdmlIsSet_ProjectIsCreatedSuccessfully() { Sldr.Initialize(); try { var bundle = GetGlyssenBundleToBeUsedForProject(false); bundle.Metadata.Language.Ldml = "ach"; var project = new Project(bundle); WaitForProjectInitializationToFinish(project, ProjectState.ReadyForUserInteraction); Assert.IsNotNull(project); Assert.IsNotEmpty(project.QuoteSystem.AllLevels); Assert.AreEqual("ach", project.WritingSystem.Id); } finally { Sldr.Cleanup(); } }
/// <summary> /// Override to dispose managed resources. /// </summary> protected override void DisposeManagedResources() { lock (m_syncRoot) { foreach (FdoLexicon lexicon in m_lexiconCache) { lexicon.Dispose(); } m_lexiconCache.Clear(); foreach (LcmCache fdoCache in m_cacheCache) { fdoCache.ServiceLocator.GetInstance <IUndoStackManager>().Save(); fdoCache.Dispose(); } m_cacheCache.Clear(); } Sldr.Cleanup(); }
public void Constructor_CreateNewProjectFromBundle_BundleHasNoLdmlFile_WsIsoCodeNotInLanguageRepo_ProjectIsCreatedUsingPrivateUseWritingSystem() { Sldr.Initialize(); try { var bundle = GetGlyssenBundleToBeUsedForProject(false); bundle.Metadata.Language.Iso = "zyt"; bundle.Metadata.Language.Ldml = ""; var project = new Project(bundle); WaitForProjectInitializationToFinish(project, ProjectState.ReadyForUserInteraction); Assert.IsNotNull(project); Assert.IsNotEmpty(project.QuoteSystem.AllLevels); Assert.AreEqual("zyt", project.WritingSystem.Id); Assert.IsTrue(project.WritingSystem.Language.IsPrivateUse); } finally { Sldr.Cleanup(); } }
public void TestFixtureTearDown() { Sldr.Cleanup(); var otBooks = SilBooks.Codes_3Letter.Take(39).ToArray(); if (m_results.Count == 39 || m_results.Count == 1) { foreach (var bookCode in otBooks) { CastSizeRowValues validCast; if (m_results.TryGetValue(bookCode, out validCast)) { Debug.WriteLine("[TestCase(\"" + bookCode + "\", " + (validCast.Male - 1) + ")]"); } } Debug.WriteLine("****************"); } else { Debug.WriteLine("WARNING: not all OT books are included in these results!!!!!!!!!!!"); } Debug.WriteLine("Copy and paste the following into the CastSizePlanningViewModel constructor:"); Debug.WriteLine(""); foreach (var bookCode in otBooks) { CastSizeRowValues validCast; if (m_results.TryGetValue(bookCode, out validCast)) { Debug.WriteLine("case \"" + bookCode + "\":"); Debug.WriteLine("smallCast.Male = Math.Max(smallCast.Male, " + (validCast.Male - 2) + ");"); if (validCast.Female != 2) { Debug.WriteLine("smallCast.Female = " + validCast.Female + ";"); } Debug.WriteLine("break;"); } } }
public void TestFixtureSetUp() { // Use the real version of the file because we want the results to be based on the production control file. ControlCharacterVerseData.TabDelimitedCharacterVerseData = null; CharacterDetailData.TabDelimitedCharacterDetailData = null; Sldr.Initialize(); try { m_project = Project.Load(@"C:\ProgramData\FCBH-SIL\Glyssen\ach\3b9fdc679b9319c3\Acholi New Test 1985 Audio\ach.glyssen"); TestProject.SimulateDisambiguationForAllBooks(m_project); m_project.CharacterGroupGenerationPreferences.NarratorsOption = NarratorsOption.SingleNarrator; } catch { // If we have an exception here, TestFixtureTearDown doesn't get called which means we need to call Sldr.Cleanup() now Sldr.Cleanup(); throw; } }
/// <summary> Exports main character set from a project to an ldml file </summary> private void LdmlExport(string filePath, string langTag) { // SLDR is the SIL Locale Data repository, it is necessary for reading/writing ldml // It is being initialized in offline mode here to only pull local data Sldr.Initialize(true); try { var wsr = LdmlInFolderWritingSystemRepository.Initialize(filePath); var wsf = new LdmlInFolderWritingSystemFactory(wsr); wsf.Create(langTag, out var wsDef); var proj = _projService.GetProject(_projectId).Result; // If there isn't already a main character set defined, make one and add it to the writing system // definition if (!wsDef.CharacterSets.TryGet("main", out var chars)) { chars = new CharacterSetDefinition("main"); wsDef.CharacterSets.Add(chars); } // Replace all the characters found with our copy of the character set chars.Characters.Clear(); foreach (var character in proj.ValidCharacters) { chars.Characters.Add(character); } // Write out the new definition wsr.Set(wsDef); wsr.Save(); } finally { // If there was somehow an error above, we still want to cleanup to prevent unhelpful errors later Sldr.Cleanup(); } }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Sldr.Initialize(); var localizationFolder = Path.GetDirectoryName(FileLocationUtilities.GetFileDistributedWithApplication("Palaso.en.tmx")); LocalizationManager.Create("fr", "Palaso", "Palaso", "1.0.0", localizationFolder, "SIL/Palaso", null, ""); if (args.Length > 0) //for testing commandlinerunner { for (int i = 0; i < 10; i++) { Console.WriteLine(i); Thread.Sleep(1000); } return; } Application.Run(new TestAppForm()); Sldr.Cleanup(); }
/// <summary> Imports main character set for a project from an ldml file </summary> public void LdmlImport(string filePath, string langTag) { // SLDR is the SIL locale data repository, it is necessary for reading/writing ldml // It is being initialized in offline mode here to only pull local data Sldr.Initialize(true); try { var wsr = LdmlInFolderWritingSystemRepository.Initialize(filePath); var wsf = new LdmlInFolderWritingSystemFactory(wsr); wsf.Create(langTag, out var wsDef); //if there is a main character set, import it to the project if (wsDef.CharacterSets.Contains("main")) { var newProj = _projService.GetProject(_projectId).Result; newProj.ValidCharacters = wsDef.CharacterSets["main"].Characters.ToList(); _projService.Update(_projectId, newProj); } } finally //if there was somehow an error above, we still want to cleanup to prevent unhelpful errors later { Sldr.Cleanup(); } }
public void TestFixtureSetUp() { // Use the real version of the file because we want the results to be based on the production control file. ControlCharacterVerseData.TabDelimitedCharacterVerseData = null; CharacterDetailData.TabDelimitedCharacterDetailData = null; Sldr.Initialize(); try { //Change this to Kuna and finish tests for OT books m_project = Project.Load( @"C:\ProgramData\FCBH-SIL\Glyssen\cuk\5a6b88fafe1c8f2b\The Bible in Kuna, San Blas Audio\cuk.glyssen"); TestProject.SimulateDisambiguationForAllBooks(m_project); m_project.CharacterGroupGenerationPreferences.NarratorsOption = NarratorsOption.SingleNarrator; } catch { // If we have an exception here, TestFixtureTearDown doesn't get called which means we need to call Sldr.Cleanup() now. // This can affect other tests, otherwise. Sldr.Cleanup(); throw; } }
public static void Main(string[] args) { ExceptionLogging.Initialize("17a42e4a67dd2e42d4aa40d8bf2d23ee", Assembly.GetExecutingAssembly().GetName().Name); var options = QueueManagerOptions.ParseCommandLineArgs(args); if (options == null) { return; } MainClass.Logger.Notice("LfMergeQueueManager starting with args: {0}", string.Join(" ", args)); // initialize the SLDR Sldr.Initialize(); var settings = MainClass.Container.Resolve <LfMergeSettings>(); settings.Initialize(); var fileLock = SimpleFileLock.CreateFromFilePath(settings.LockFile); try { if (!fileLock.TryAcquireLock()) { MainClass.Logger.Error("Can't acquire file lock - is another instance running?"); return; } MainClass.Logger.Notice("Lock acquired"); if (!CheckSetup(settings)) { return; } // Cleanup any hang projects new Janitor(settings, MainClass.Logger).CleanupAndRescheduleJobs(); for (var queue = Queue.FirstQueueWithWork; queue != null; queue = queue.NextQueueWithWork) { var clonedQueue = queue.QueuedProjects.ToList(); foreach (var projectCode in clonedQueue) { var projectPath = Path.Combine(settings.LcmDirectorySettings.ProjectsDirectory, projectCode, $"{projectCode}{LcmFileHelper.ksFwDataXmlFileExtension}"); var modelVersion = FwProject.GetModelVersion(projectPath); queue.DequeueProject(projectCode); int retCode = MainClass.StartLfMerge(projectCode, queue.CurrentActionName, modelVersion, true); // TODO: If LfMerge fails, should we re-queue the project, or not? if (retCode != 0) { // queue.EnqueueProject(projectCode); } } } } catch (Exception e) { MainClass.Logger.Error("Unhandled Exception:\n{0}", e); throw; } finally { if (fileLock != null) { fileLock.ReleaseLock(); } if (Sldr.IsInitialized) { Sldr.Cleanup(); } MainClass.Container.Dispose(); } MainClass.Logger.Notice("LfMergeQueueManager finished"); }
public void TearDownFixture() { Sldr.Cleanup(); }
protected override void DisposeManagedResources() { Sldr.Cleanup(); _sldrCacheFolder.Dispose(); }
public static int Main(string[] args) { ExceptionLogging.Initialize("17a42e4a67dd2e42d4aa40d8bf2d23ee", Assembly.GetExecutingAssembly().GetName().Name); int result = (int)ErrorCode.NoError; var options = Options.ParseCommandLineArgs(args); if (options == null) { return((int)ErrorCode.InvalidOptions); } // initialize the SLDR Sldr.Initialize(); // Username and Password will usually be "x" because it's dealt with on Language Forge site. // However, when debugging LfMerge we want to be able to set it to a real name ChorusHelper.Username = options.User; ChorusHelper.Password = System.Environment.GetEnvironmentVariable("LANGUAGE_DEPOT_TRUST_TOKEN") ?? options.Password; ExceptionLogging.Client.AddInfo(options.ProjectCode, MainClass.ModelVersion); MainClass.Logger.Notice("LfMerge {2} (database {0}) starting with args: {1}", MainClass.ModelVersion, string.Join(" ", args), MainClass.GetVersionInfo("SemVer")); if (string.IsNullOrEmpty(options.ProjectCode)) { MainClass.Logger.Error("Command line doesn't contain project code - exiting."); return(-1); } FwProject.AllowDataMigration = options.AllowDataMigration; string differentModelVersion = null; try { if (!MainClass.CheckSetup()) { return((int)ErrorCode.GeneralError); } MongoConnection.Initialize(); differentModelVersion = RunAction(options.ProjectCode, options.CurrentAction); } catch (Exception e) { MainClass.Logger.Error("Unhandled Exception: \n{0}", e); throw; } finally { if (Sldr.IsInitialized) { Sldr.Cleanup(); } MainClass.Container.Dispose(); Cleanup(); } if (!string.IsNullOrEmpty(differentModelVersion)) { result = MainClass.StartLfMerge(options.ProjectCode, options.CurrentAction, differentModelVersion, false); } MainClass.Logger.Notice("LfMerge-{0} finished", MainClass.ModelVersion); return(result); }
static void Main(string[] args) { IsRunning = true; if (GetRunningGlyssenProcessCount() > 1) { ErrorReport.NotifyUserOfProblem("There is another copy of Glyssen already running. This instance of Glyssen will now shut down."); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //bring in settings from any previous version if (Settings.Default.NeedUpgrade) { //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load Settings.Default.Upgrade(); Settings.Default.Reload(); Settings.Default.NeedUpgrade = false; Settings.Default.Save(); } SetUpErrorHandling(); UserInfo userInfo = new UserInfo { UILanguageCode = Settings.Default.UserInterfaceLanguage }; bool sldrIsInitialized = false; Logger.Init(); Trace.Listeners.Add(new LogFileTraceListener()); Alert.Implementation = new AlertImpl(); // Do this before calling Initialize, just in case Initialize tries to display an alert. if (ParatextInfo.IsParatextInstalled) { string userName = null; try { ParatextData.Initialize(); sldrIsInitialized = true; userName = RegistrationInfo.UserName; userInfo.Email = RegistrationInfo.EmailAddress; foreach (var errMsgInfo in CompatibleParatextProjectLoadErrors.Where(e => e.Reason == UnsupportedReason.Unspecified)) { _pendingExceptionsToReportToAnalytics.Add(errMsgInfo.Exception); } } catch (Exception fatalEx) when(fatalEx is FileLoadException || fatalEx is TypeInitializationException) { ErrorReport.ReportFatalException(fatalEx); } catch (Exception ex) { _pendingExceptionsToReportToAnalytics.Add(ex); } if (userName != null) { var split = userName.LastIndexOf(" ", StringComparison.Ordinal); if (split > 0) { userInfo.FirstName = userName.Substring(0, split); userInfo.LastName = userName.Substring(split + 1); } else { userInfo.LastName = userName; } } } // ENHANCE (PG-63): Implement something like this if we decide to give the user the option of manually // specifying the location of Paratext data files if the program isn’t actually installed. //else //{ // RegistrationInfo.Implementation = new GlyssenAnonymousRegistrationInfo(); // if (!String.IsNullOrWhiteSpace(Settings.Default.UserSpecifiedParatext8ProjectsDir) && // Directory.Exists(Settings.Default.UserSpecifiedParatext8ProjectsDir)) // { // try // { // ParatextData.Initialize(Settings.Default.UserSpecifiedParatext8ProjectsDir); // sldrIsInitialized = true; // } // catch (Exception ex) // { // _pendingExceptionsToReportToAnalytics.Add(ex); // Settings.Default.UserSpecifiedParatext8ProjectsDir = null; // } // } //} #if DEBUG using (new Analytics("jBh7Qg4jw2nRFE8j8EY1FDipzin3RFIP", userInfo)) #else //default is to allow tracking if this isn't set string feedbackSetting = Environment.GetEnvironmentVariable("FEEDBACK")?.ToLower(); var allowTracking = string.IsNullOrEmpty(feedbackSetting) || feedbackSetting == "yes" || feedbackSetting == "true"; using (new Analytics("WEyYj2BOnZAP9kplKmo2BDPvfyofbMZy", userInfo, allowTracking)) #endif { foreach (var exception in _pendingExceptionsToReportToAnalytics) { Analytics.ReportException(exception); } _pendingExceptionsToReportToAnalytics.Clear(); var oldPgBaseFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), GlyssenInfo.kCompany, kOldProductName); var baseDataFolder = GlyssenInfo.BaseDataFolder; if (Directory.Exists(oldPgBaseFolder) && !Directory.Exists(baseDataFolder)) { Directory.Move(oldPgBaseFolder, baseDataFolder); } if (!Directory.Exists(baseDataFolder)) { // create the directory Directory.CreateDirectory(baseDataFolder); } // PG-433, 07 JAN 2016, PH: Set the permissions so everyone can read and write to this directory DirectoryUtilities.SetFullControl(baseDataFolder, false); SetUpLocalization(); DataMigrator.UpgradeToCurrentDataFormatVersion(); SampleProject.CreateSampleProjectIfNeeded(); // The following not only gets the location of the settings file; // it also detects corruption and deletes it if needed so we don't crash. string userConfigSettingsPath = GetUserConfigFilePath(); if ((Control.ModifierKeys & Keys.Shift) > 0 && !string.IsNullOrEmpty(userConfigSettingsPath)) { HandleDeleteUserSettings(userConfigSettingsPath); } // This might also be needed if Glyssen and ParatextData use different versions of SIL.WritingSystems.dll if (!sldrIsInitialized) { Sldr.Initialize(); } try { Application.Run(new MainForm(args)); } finally { Sldr.Cleanup(); } } }
static int Main(string[] args) { var options = new Options(); var isValid = CommandLine.Parser.Default.ParseArgumentsStrict(args, options); if (isValid) { if (options.ShowHelp) { Console.WriteLine(options.GetUsage()); return(0); } if (String.IsNullOrEmpty(options.InputDir)) { options.InputDir = Path.Combine("..", "..", "SIL.WritingSystems", "Resources"); } if (!Directory.Exists(options.InputDir)) { Console.WriteLine("Input directory does not exist"); return(1); } else if (!File.Exists(Path.Combine(options.InputDir, "LanguageIndex.txt")) || !File.Exists(Path.Combine(options.InputDir, "ianaSubtagRegistry.txt")) || !File.Exists(Path.Combine(options.InputDir, "TwoToThreeCodes.txt"))) { Console.WriteLine("Input directory does not contain all of the source files LanguageIndex.txt, ianaSubtagRegistry.txt and TwoToThreeCodes.txt"); return(1); } if ((options.OutputFile != "LanguageDataIndex.txt") && File.Exists(options.OutputFile)) { Console.WriteLine("The file {0} already exists.", options.OutputFile); return(1); } if (options.Verbose) { Console.WriteLine("Input directory: {0}", options.InputDir); Console.WriteLine("Output file: {0}", options.OutputFile); Console.WriteLine("Getting new files: {0}", options.GetFresh); } } else { // Display the default usage information Console.WriteLine("command line parsing failed"); Console.WriteLine(options.GetUsage()); return(1); } GetAndCheckSources getcheck = new GetAndCheckSources(); getcheck.GetOldSources(options.InputDir); if (options.GetFresh || options.CheckFresh) { if (!getcheck.GetNewSources()) { Console.WriteLine("Failed to download files - aborting"); return(2); } bool newfiles = getcheck.CheckSourcesAreDifferent(); if (newfiles) { getcheck.WriteNewFiles("."); if (options.CheckFresh) { return(99); } } } if (!options.CheckFresh) { Sldr.Initialize(true); LanguageDataIndex langIndex = new LanguageDataIndex(getcheck.GetFileStrings(options.GetFresh)); langIndex.WriteIndex(options.OutputFile); if (options.Json) { string basename = Path.GetFileNameWithoutExtension(options.OutputFile); string json_file = basename + ".json"; langIndex.WriteJson(json_file); } Sldr.Cleanup(); } return(0); }
static void Main(string[] args) { IsRunning = true; if (GetRunningGlyssenProcessCount() > 1) { ErrorReport.NotifyUserOfProblem("There is another copy of Glyssen already running. This instance of Glyssen will now shut down."); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //bring in settings from any previous version if (Settings.Default.NeedUpgrade) { //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load Settings.Default.Upgrade(); Settings.Default.Reload(); Settings.Default.NeedUpgrade = false; Settings.Default.Save(); } SetUpErrorHandling(); #if DEBUG using (new Analytics("jBh7Qg4jw2nRFE8j8EY1FDipzin3RFIP", new UserInfo { UILanguageCode = Settings.Default.UserInterfaceLanguage })) #else string feedbackSetting = Environment.GetEnvironmentVariable("FEEDBACK"); //default is to allow tracking var allowTracking = string.IsNullOrEmpty(feedbackSetting) || feedbackSetting.ToLower() == "yes" || feedbackSetting.ToLower() == "true"; using (new Analytics("WEyYj2BOnZAP9kplKmo2BDPvfyofbMZy", new UserInfo { UILanguageCode = Settings.Default.UserInterfaceLanguage }, allowTracking)) #endif { Logger.Init(); var oldPgBaseFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), GlyssenInfo.kCompany, kOldProductName); var baseDataFolder = GlyssenInfo.BaseDataFolder; if (Directory.Exists(oldPgBaseFolder) && !Directory.Exists(baseDataFolder)) { Directory.Move(oldPgBaseFolder, baseDataFolder); } if (!Directory.Exists(baseDataFolder)) { // create the directory Directory.CreateDirectory(baseDataFolder); } // PG-433, 07 JAN 2016, PH: Set the permissions so everyone can read and write to this directory DirectoryUtilities.SetFullControl(baseDataFolder, false); DataMigrator.UpgradeToCurrentDataFormatVersion(); SampleProject.CreateSampleProjectIfNeeded(); SetUpLocalization(); // The following not only gets the location of the settings file; // it also detects corruption and deletes it if needed so we don't crash. string userConfigSettingsPath = GetUserConfigFilePath(); if ((Control.ModifierKeys & Keys.Shift) > 0 && !string.IsNullOrEmpty(userConfigSettingsPath)) { HandleDeleteUserSettings(userConfigSettingsPath); } Sldr.Initialize(); try { Application.Run(new MainForm(args)); } finally { Sldr.Cleanup(); } } }
static void Main() { // I had put the following line of code in to fix a SP-436 after reading this article: // http://stackoverflow.com/questions/4077822/net-4-0-and-the-dreaded-onuserpreferencechanged-hang // Microsoft.Win32.SystemEvents.UserPreferenceChanged += delegate { }; // But then I found this page: http://www.aaronlerch.com/blog/2008/12/15/debugging-ui/ // which describes how to find out where the actual problem is. Thread.CurrentThread.Name = "UI"; // This is pretty annoying: When, because .Net doesn't have a font style of SemiBold // (e.g. Segoe UI SemiBold), fonts having that style are assumed to be bold, but // when some controls (e.g. Label) are set to a SemiBold font, they are displayed as // bold, so we'll create our own, forcing the style to regular, which seems to work. // Don't use SystemFonts.DefaultFont because that always returns "Microsoft Sans Serif" // and SystemFonts.DialogFont always returns "Tahoma", regardless of OS. // See: http://benhollis.net/blog/2007/04/11/setting-the-correct-default-font-in-net-windows-forms-apps/ _dialogFont = new Font(SystemFonts.MessageBoxFont, FontStyle.Regular); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // The following not only get the location of the settings file used for the analytics stuff. It also // detects corruption and deletes it if needed so SayMore doesn't crash. var analyticsConfigFilePath = GetAnalyticsConfigFilePath(); // Analytics settings. if ((Control.ModifierKeys & Keys.Shift) > 0 && !IsNullOrEmpty(analyticsConfigFilePath)) { var confirmationString = LocalizationManager.GetString("MainWindow.ConfirmDeleteUserSettingsFile", "Do you want to delete your user settings? (This will clear your most-recently-used project list, window positions, UI language settings, etc. It will not affect your SayMore project data.)"); if (DialogResult.Yes == MessageBox.Show(confirmationString, ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning)) { File.Delete(analyticsConfigFilePath); File.Delete(new PortableSettingsProvider().GetFullSettingsFilePath()); } } //bring in settings from any previous version //NB: this code doesn't actually work, because for some reason Saymore uses its own settings code, //(which emits a "settings" file rather than "user.config"), //and which apparently doesn't use the application version to trigger the following technique: // Insight from Tom: Looks like ALL user settings in SayMore use the PortableSettingsProvider. I think the // idea of this was to facilitate installing SayMore to a thumb drive or whatever, so it could be totally // portable. This provider does not attach version numbers to the settings files (or the cryptic GUIDs or // whatever to their containing folders), so once NeedUpgrade gets set to false (the very first time SayMore // is run), it will never again be true. It's easy enough to store NeedUpgrade in the normal // user.config file by removing the attribute in Settings.Designer.cs that causes it to be handled by the // custom provider. But PortableSettingsProvider would need to implement IApplicationSettingsProvider and // implement Upgrade in an appropriate way to handle this. if (Settings.Default.NeedUpgrade) //TODO: this doesn't get triggered with David's custom settings { //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load Settings.Default.Upgrade(); //TODO: and this doesn't seem to actually do anything with David's custom settings Settings.Default.NeedUpgrade = false; Settings.Default.Save(); } //so, as a hack because this is biting our users *now*. //this hack begins the damage control started above, when from 1.6.52 to 1.6.53, we changed the namespace //of the grid settings. It removes the old settings, talks to the user, and waits for the user to restart. else { try { // ReSharper disable once NotAccessedVariable var x = Settings.Default.SessionsListGrid; //we want this to throw if the last version used the SILGrid, and this one uses the BetterGrid // ReSharper disable once RedundantAssignment x = Settings.Default.PersonListGrid; } catch (Exception) { string path = ""; try { ErrorReport.NotifyUserOfProblem("We apologize for the inconvenience, but to complete this upgrade, SayMore needs to exit. Please run it again to complete the upgrade."); var s = Application.LocalUserAppDataPath; s = s.Substring(0, s.IndexOf("Local", StringComparison.InvariantCultureIgnoreCase) + 5); path = s.CombineForPath("SayMore", "SayMore.Settings"); File.Delete(path); Settings.Default.MRUList = MruFiles.Initialize(Settings.Default.MRUList, 4); //leave this reminder to our post-restart self if (MruFiles.Latest != null) { File.WriteAllText(MRULatestReminderFilePath, MruFiles.Latest); } //Application.Restart(); won't work, because the settings will still get saved Environment.FailFast("SayMore quitting hard to prevent old settings from being saved again."); } catch (Exception error) { ErrorReport.NotifyUserOfProblem(error, "SayMore was unable to find or delete the settings file from the old version of SayMore. Normally, this would be found at " + path); Application.Exit(); } } } //this hack is a continuation of the damage control started above, when from 1.6.52 to 1.6.53, we changed the namespace //of the grid settings. if (File.Exists(MRULatestReminderFilePath)) { var path = File.ReadAllText(MRULatestReminderFilePath).Trim(); if (File.Exists(path)) { Settings.Default.MRUList = new StringCollection(); Settings.Default.MRUList.Add(path); } File.Delete(MRULatestReminderFilePath); } Settings.Default.MRUList = MruFiles.Initialize(Settings.Default.MRUList, 4); _applicationContainer = new ApplicationContainer(false); Logger.Init(); AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler; Logger.WriteEvent(ApplicationContainer.GetVersionInfo("SayMore version {0}.{1}.{2} {3} Built on {4}", BuildType.Current)); Logger.WriteEvent("Visual Styles State: {0}", Application.VisualStyleState); SetUpErrorHandling(); var userInfo = new UserInfo(); #if DEBUG // Always track if this is a debug build, but track to a different segment.io project using (new Analytics("twa75xkko9", userInfo)) #else // If this is a release build, then allow an environment variable to be set to false // so that testers aren't generating false analytics string feedbackSetting = System.Environment.GetEnvironmentVariable("FEEDBACK"); var allowTracking = IsNullOrEmpty(feedbackSetting) || feedbackSetting.ToLower() == "yes" || feedbackSetting.ToLower() == "true"; using (new Analytics("jtfe7dyef3", userInfo, allowTracking)) #endif { foreach (var exception in _pendingExceptionsToReportToAnalytics) { Analytics.ReportException(exception); } bool startedWithCommandLineProject = false; var args = Environment.GetCommandLineArgs(); if (args.Length > 1) { var possibleProjFile = args[1]; startedWithCommandLineProject = possibleProjFile.EndsWith(Settings.Default.ProjectFileExtension) && File.Exists(possibleProjFile) && OpenProjectWindow(possibleProjFile); } if (!startedWithCommandLineProject) { StartUpShellBasedOnMostRecentUsedIfPossible(); } Sldr.Initialize(); try { Application.Run(); Settings.Default.Save(); Logger.WriteEvent("SayMore shutting down"); if (s_countOfContiguousFirstChanceOutOfMemoryExceptions > 1) { Logger.WriteEvent("Total number of contiguous OutOfMemoryExceptions: {0}", s_countOfContiguousFirstChanceOutOfMemoryExceptions); } Logger.ShutDown(); SafelyDisposeProjectContext(); } finally { ReleaseMutexForThisProject(); Sldr.Cleanup(); } } }