internal override void UnloadDictionary(object token) { if (_isDisposed) { return; } var data = (Tuple <string, string>)token; string ietfLanguageTag = data.Item1; string filePath = data.Item2; new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); _customDictionaryFilesLock.WaitOne(); try { _customDictionaryFiles[ietfLanguageTag].RemoveAll((str) => str == filePath); } finally { _customDictionaryFilesLock.Release(); } using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(filePath, ietfLanguageTag); } File.Delete(filePath); }
internal override void UnloadDictionary(object token) { if (_isDisposed) { return; } var data = (Tuple <string, string>)token; string ietfLanguageTag = data.Item1; string filePath = data.Item2; try { new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(filePath, ietfLanguageTag); } FileHelper.DeleteTemporaryFile(filePath); } catch (SecurityException) { } }
private void ClearDictionaries(bool disposing = false) { if (this._isDisposed) { return; } if (this._customDictionaryFiles != null) { foreach (KeyValuePair <string, List <string> > keyValuePair in this._customDictionaryFiles) { string key = keyValuePair.Key; foreach (string text in keyValuePair.Value) { try { new FileIOPermission(FileIOPermissionAccess.AllAccess, text).Demand(); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(text, key, true); } FileHelper.DeleteTemporaryFile(text); } catch { } } } this._customDictionaryFiles.Clear(); } if (disposing) { this._customDictionaryFiles = null; } }
internal override void UnloadDictionary(object token) { if (_isDisposed) { return; } var data = (Tuple <CultureInfo, String>)token; CultureInfo culture = data.Item1; string filePath = data.Item2; new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); _customDictionaryFilesLock.WaitOne(); try { _customDictionaryFiles[culture].RemoveAll((str) => str == filePath); } finally { _customDictionaryFilesLock.Release(); } SpellCheckerFactory.UnregisterUserDictionary(filePath, culture.IetfLanguageTag); File.Delete(filePath); }
internal WinRTSpellerInterop() { // When the CLR consumes an unmanaged COM object, it invokes // System.ComponentModel.LicenseManager.LicenseInteropHelper.GetCurrentContextInfo // which in turn calls Assembly.GetName. Assembly.GetName requires FileIOPermission for // access to the path of the assembly. FileIOPermission fiop = new FileIOPermission(PermissionState.None); fiop.AllLocalFiles = FileIOPermissionAccess.PathDiscovery; fiop.Assert(); try { SpellCheckerFactory.Create(shouldSuppressCOMExceptions: false); } catch (Exception ex) // Sometimes, InvalidCastException is thrown when SpellCheckerFactory fails to instantiate correctly when(ex is InvalidCastException || ex is COMException) { Dispose(); throw new PlatformNotSupportedException(string.Empty, ex); } finally { CodeAccessPermission.RevertAssert(); } _spellCheckers = new Dictionary <CultureInfo, Tuple <WordsSegmenter, SpellChecker> >(); _customDictionaryFiles = new Dictionary <string, List <string> >(); _defaultCulture = InputLanguageManager.Current?.CurrentInputLanguage ?? Thread.CurrentThread.CurrentCulture; _culture = null; try { EnsureWordBreakerAndSpellCheckerForCulture(_defaultCulture, throwOnError: true); } catch (Exception ex) when(ex is ArgumentException || ex is NotSupportedException || ex is PlatformNotSupportedException) { _spellCheckers = null; Dispose(); if ((ex is PlatformNotSupportedException) || (ex is NotSupportedException)) { throw; } else { throw new NotSupportedException(string.Empty, ex); } } // This class is only instantiated from the UI thread, so it is safe to // obtain the Dispatcher this way. _dispatcher = new WeakReference <Dispatcher>(Dispatcher.CurrentDispatcher); WeakEventManager <AppDomain, UnhandledExceptionEventArgs> .AddHandler(AppDomain.CurrentDomain, "UnhandledException", ProcessUnhandledException); }
/// <summary> /// Determines if the specified language is supported by a registered spell checker. /// </summary> /// <param name="languageTag">A BCP47 language tag that identifies the language for the requested spell checker.</param> /// <returns>True if supported; false otherwise.</returns> public static bool IsLanguageSupported(string languageTag) { var factory = new SpellCheckerFactory(); try { return(factory.IsSupported(languageTag) != 0); } finally { Marshal.ReleaseComObject(factory); } }
/// <summary> /// Creates a spell checker that supports the specified language. /// </summary> /// <exception cref="ArgumentException">languageTag is an empty string, or there is no spell checker available for languageTag.</exception> /// <param name="languageTag">A BCP47 language tag that identifies the language for the requested spell checker.</param> public SpellChecker(string languageTag) { var factory = new SpellCheckerFactory(); try { spellChecker = factory.CreateSpellChecker(languageTag); } finally { Marshal.ReleaseComObject(factory); } }
/// <summary> /// Creates a spell checker that supports the current UI language. /// </summary> public SpellChecker() { var factory = new SpellCheckerFactory(); try { spellChecker = factory.CreateSpellChecker(CultureInfo.CurrentCulture.Name); } finally { Marshal.ReleaseComObject(factory); } }
/// <summary> /// Unloads a given custom dictionary /// </summary> /// <param name="token"></param> internal override void UnloadDictionary(object token) { if (_isDisposed) return; var data = (Tuple<string, string>)token; string ietfLanguageTag = data.Item1; string filePath = data.Item2; using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(filePath, ietfLanguageTag); } FileHelper.DeleteTemporaryFile(filePath); }
private void ClearDictionaries(bool isDisposeOrFinalize = false) { if (_isDisposed || (_customDictionaryFilesLock == null)) { // Locks are not initialized => Dispose called from within the constructor. // Likely this platform is not supported - do not process further. return; } _customDictionaryFilesLock.WaitOne(); try { if (_customDictionaryFiles != null) { foreach (KeyValuePair <CultureInfo, List <string> > items in _customDictionaryFiles) { CultureInfo culture = items.Key; foreach (string filePath in items.Value) { try { new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); SpellCheckerFactory.UnregisterUserDictionary(filePath, culture.IetfLanguageTag); File.Delete(filePath); } catch { // Do nothing - Continue to make a best effort // attempt at unregistering custom dictionaries } } } _customDictionaryFiles.Clear(); } } finally { if (isDisposeOrFinalize) { _customDictionaryFiles = null; } _customDictionaryFilesLock.Release(); } }
/// <exception cref="PlatformNotSupportedException"> /// The OS platform is not supported /// </exception> /// <exception cref="NotSupportedException"> /// The OS platform is supportable, but spellchecking services are currently unavailable /// </exception> internal WinRTSpellerInterop() { try { SpellCheckerFactory.Create(shouldSuppressCOMExceptions: false); } catch (Exception ex) // Sometimes, InvalidCastException is thrown when SpellCheckerFactory fails to instantiate correctly when (ex is InvalidCastException || ex is COMException ) { Dispose(); throw new PlatformNotSupportedException(string.Empty, ex); } _spellCheckers = new Dictionary<CultureInfo, Tuple<WordsSegmenter, SpellChecker>>(); _customDictionaryFiles = new Dictionary<string, List<string>>(); _defaultCulture = InputLanguageManager.Current?.CurrentInputLanguage ?? Thread.CurrentThread.CurrentCulture; _culture = null; try { EnsureWordBreakerAndSpellCheckerForCulture(_defaultCulture, throwOnError: true); } catch (Exception ex) when (ex is ArgumentException || ex is NotSupportedException || ex is PlatformNotSupportedException) { _spellCheckers = null; Dispose(); if ((ex is PlatformNotSupportedException) || (ex is NotSupportedException)) { throw; } else { throw new NotSupportedException(string.Empty, ex); } } // This class is only instantiated from the UI thread, so it is safe to // obtain the Dispatcher this way. _dispatcher = new WeakReference<Dispatcher>(Dispatcher.CurrentDispatcher); WeakEventManager<AppDomain, UnhandledExceptionEventArgs> .AddHandler(AppDomain.CurrentDomain, "UnhandledException", ProcessUnhandledException); }
private void ClearDictionaries(bool disposing = false) { if (_isDisposed) { // Likely this platform is not supported - do not process further. return; } if (_customDictionaryFiles != null) { foreach (KeyValuePair <string, List <string> > items in _customDictionaryFiles) { string ietfLanguageTag = items.Key; foreach (string filePath in items.Value) { try { new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(filePath, ietfLanguageTag); } FileHelper.DeleteTemporaryFile(filePath); } catch { // Do nothing - Continue to make a best effort // attempt at unregistering custom dictionaries } } } _customDictionaryFiles.Clear(); } if (disposing) { _customDictionaryFiles = null; } }
internal WinRTSpellerInterop() { new FileIOPermission(PermissionState.None) { AllLocalFiles = FileIOPermissionAccess.PathDiscovery }.Assert(); try { SpellCheckerFactory.Create(false); } catch (Exception ex) when(ex is InvalidCastException || ex is COMException) { this.Dispose(); throw new PlatformNotSupportedException(string.Empty, ex); } finally { CodeAccessPermission.RevertAssert(); } this._spellCheckers = new Dictionary <CultureInfo, Tuple <WordsSegmenter, SpellChecker> >(); this._customDictionaryFiles = new Dictionary <string, List <string> >(); InputLanguageManager inputLanguageManager = InputLanguageManager.Current; this._defaultCulture = (((inputLanguageManager != null) ? inputLanguageManager.CurrentInputLanguage : null) ?? Thread.CurrentThread.CurrentCulture); this._culture = null; try { this.EnsureWordBreakerAndSpellCheckerForCulture(this._defaultCulture, true); } catch (Exception ex2) when(ex2 is ArgumentException || ex2 is NotSupportedException || ex2 is PlatformNotSupportedException) { this._spellCheckers = null; this.Dispose(); if (ex2 is PlatformNotSupportedException || ex2 is NotSupportedException) { throw; } throw new NotSupportedException(string.Empty, ex2); } this._dispatcher = new WeakReference <Dispatcher>(Dispatcher.CurrentDispatcher); WeakEventManager <AppDomain, UnhandledExceptionEventArgs> .AddHandler(AppDomain.CurrentDomain, "UnhandledException", new EventHandler <UnhandledExceptionEventArgs>(this.ProcessUnhandledException)); }
internal override void UnloadDictionary(object token) { if (this._isDisposed) { return; } Tuple <string, string> tuple = (Tuple <string, string>)token; string item = tuple.Item1; string item2 = tuple.Item2; try { new FileIOPermission(FileIOPermissionAccess.AllAccess, item2).Demand(); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(item2, item, true); } FileHelper.DeleteTemporaryFile(item2); } catch (SecurityException) { } }
/// <summary> /// Actual implementation of loading a dictionary /// </summary> /// <param name="lexiconFilePath"></param> /// <param name="dictionaryLoadedCallback"></param> /// <param name="callbackParam"></param> /// <returns> /// A tuple of cultureinfo detected from <paramref name="lexiconFilePath"/> and /// a temp file path which holds a copy of <paramref name="lexiconFilePath"/> /// /// If no culture is specified in the first line of <paramref name="lexiconFilePath"/> /// in the format #LID nnnn (where nnnn = decimal LCID of the culture), then invariant /// culture is returned. /// </returns> /// <remarks> /// At the end of this method, we guarantee that <paramref name="lexiconFilePath"/> /// can be reclaimed (i.e., potentially deleted) by the caller. /// </remarks> private Tuple<string, string> LoadDictionaryImpl(string lexiconFilePath) { if (_isDisposed) { return new Tuple<string, string>(null, null); } if (!File.Exists(lexiconFilePath)) { throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath)); } bool fileCopied = false; string lexiconPrivateCopyPath = null; try { CultureInfo culture = null; // Read the first line of the file and detect culture, if specified using (FileStream stream = new FileStream(lexiconFilePath, FileMode.Open, FileAccess.Read)) { string line = null; using (StreamReader reader = new StreamReader(stream)) { line = reader.ReadLine(); culture = WinRTSpellerInterop.TryParseLexiconCulture(line); } } string ietfLanguageTag = culture.IetfLanguageTag; // Make a temp file and copy the original file over. // Ensure that the copy has Unicode (UTF16-LE) encoding using (FileStream lexiconPrivateCopyStream = FileHelper.CreateAndOpenTemporaryFile(out lexiconPrivateCopyPath, extension: "dic")) { WinRTSpellerInterop.CopyToUnicodeFile(lexiconFilePath, lexiconPrivateCopyStream); fileCopied = true; } // Add the temp file (with .dic extension) just created to a cache, // then pass it along to IUserDictionariesRegistrar if (!_customDictionaryFiles.ContainsKey(ietfLanguageTag)) { _customDictionaryFiles[ietfLanguageTag] = new List<string>(); } _customDictionaryFiles[ietfLanguageTag].Add(lexiconPrivateCopyPath); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.RegisterUserDictionary)) { SpellCheckerFactory.RegisterUserDictionary(lexiconPrivateCopyPath, ietfLanguageTag); } return new Tuple<string, string>(ietfLanguageTag, lexiconPrivateCopyPath); } catch (Exception e) when ((e is ArgumentException) || !fileCopied) { // IUserDictionariesRegistrar.RegisterUserDictionary can // throw ArgumentException on failure. Cleanup the temp file if // we successfully created one. if (lexiconPrivateCopyPath != null) { FileHelper.DeleteTemporaryFile(lexiconPrivateCopyPath); } throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath), e); } }
private void ClearDictionaries(bool isDisposeOrFinalize = false) { if (_isDisposed || (_customDictionaryFilesLock == null)) { // Locks are not initialized => Dispose called from within the constructor. // Likely this platform is not supported - do not process further. return; } try { _customDictionaryFilesLock.WaitOne(); if (_customDictionaryFiles != null) { foreach (KeyValuePair <string, List <string> > items in _customDictionaryFiles) { string ietfLanguageTag = items.Key; foreach (string filePath in items.Value) { try { new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath).Demand(); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.UnregisterUserDictionary)) { SpellCheckerFactory.UnregisterUserDictionary(filePath, ietfLanguageTag); } File.Delete(filePath); } catch { // Do nothing - Continue to make a best effort // attempt at unregistering custom dictionaries } } } _customDictionaryFiles.Clear(); } } catch (ObjectDisposedException) { // _customeDictionaryFilesLock might throw ObjectDisposedException // if it has been disposed before reaching ClearDictionaries. // We will simply handle the exception and abort gracefully. // // Setting _customDictionaryFilesLock to null here would // ensure that the call into Release() in the finally block would // not throw again. _customDictionaryFilesLock = null; } finally { if (isDisposeOrFinalize) { _customDictionaryFiles = null; } try { _customDictionaryFilesLock?.Release(); } catch (ObjectDisposedException) { // do nothing } finally { _customDictionaryFilesLock = null; } } }
private Tuple <string, string> LoadDictionaryImpl(string lexiconFilePath) { if (this._isDisposed) { return(new Tuple <string, string>(null, null)); } try { new FileIOPermission(FileIOPermissionAccess.Read, lexiconFilePath).Demand(); } catch (SecurityException innerException) { throw new ArgumentException(SR.Get("CustomDictionaryFailedToLoadDictionaryUri", new object[] { lexiconFilePath }), innerException); } if (!File.Exists(lexiconFilePath)) { throw new ArgumentException(SR.Get("CustomDictionaryFailedToLoadDictionaryUri", new object[] { lexiconFilePath })); } bool flag = false; string text = null; Tuple <string, string> result; try { CultureInfo cultureInfo = null; using (FileStream fileStream = new FileStream(lexiconFilePath, FileMode.Open, FileAccess.Read)) { using (StreamReader streamReader = new StreamReader(fileStream)) { string line = streamReader.ReadLine(); cultureInfo = WinRTSpellerInterop.TryParseLexiconCulture(line); } } string ietfLanguageTag = cultureInfo.IetfLanguageTag; using (FileStream fileStream2 = FileHelper.CreateAndOpenTemporaryFile(out text, FileAccess.Write, FileOptions.None, "dic", "WPF")) { WinRTSpellerInterop.CopyToUnicodeFile(lexiconFilePath, fileStream2); flag = true; } if (!this._customDictionaryFiles.ContainsKey(ietfLanguageTag)) { this._customDictionaryFiles[ietfLanguageTag] = new List <string>(); } this._customDictionaryFiles[ietfLanguageTag].Add(text); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.RegisterUserDictionary)) { SpellCheckerFactory.RegisterUserDictionary(text, ietfLanguageTag, true); } result = new Tuple <string, string>(ietfLanguageTag, text); } catch (Exception ex) when(ex is SecurityException || ex is ArgumentException || !flag) { if (text != null) { FileHelper.DeleteTemporaryFile(text); } throw new ArgumentException(SR.Get("CustomDictionaryFailedToLoadDictionaryUri", new object[] { lexiconFilePath }), ex); } return(result); }
private Tuple <CultureInfo, String> LoadDictionaryImpl(string lexiconFilePath) { if (_isDisposed) { return(new Tuple <CultureInfo, string>(null, null)); } try { new FileIOPermission(FileIOPermissionAccess.Read, lexiconFilePath).Demand(); } catch (SecurityException se) { throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath), se); } if (!File.Exists(lexiconFilePath)) { throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath)); } bool fileCopied = false; string lexiconPrivateCopyPath = null; try { CultureInfo culture = null; // Read the first line of the file and detect culture, if specified using (FileStream stream = new FileStream(lexiconFilePath, FileMode.Open, FileAccess.Read)) { string line = null; using (StreamReader reader = new StreamReader(stream)) { line = reader.ReadLine(); culture = WinRTSpellerInterop.TryParseLexiconCulture(line); } } // Make a temp file and copy the original file over. // Ensure that the copy has Unicode (UTF16-LE) encoding lexiconPrivateCopyPath = WinRTSpellerInterop.GetTempFileName(extension: "dic"); new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, lexiconPrivateCopyPath).Assert(); try { WinRTSpellerInterop.CopyToUnicodeFile(lexiconFilePath, lexiconPrivateCopyPath); fileCopied = true; } finally { CodeAccessPermission.RevertAssert(); } // Add the temp file (with .dic extension) just created to a cache, // then pass it along to IUserDictionariesRegistrar _customDictionaryFilesLock.WaitOne(); try { if (!_customDictionaryFiles.ContainsKey(culture)) { _customDictionaryFiles[culture] = new List <string>(); } _customDictionaryFiles[culture].Add(lexiconPrivateCopyPath); } finally { _customDictionaryFilesLock.Release(); } SpellCheckerFactory.RegisterUserDictionary(lexiconPrivateCopyPath, culture.IetfLanguageTag); return(new Tuple <CultureInfo, string>(culture, lexiconPrivateCopyPath)); } catch (Exception e) when((e is SecurityException) || (e is ArgumentException) || !fileCopied) { // IUserDictionariesRegistrar.RegisterUserDictionary can // throw ArgumentException on failure. Cleanup the temp file if // we successfully created one. if (lexiconPrivateCopyPath != null) { File.Delete(lexiconPrivateCopyPath); } throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath), e); } }