public MainViewModel(IWindowManager windowManager, IEventAggregator events) { Instance = this; _windowManager = windowManager; _events = events; _events.Subscribe(this); _windowTitle = $"{Global.ApplicationName} {VersionHelper.PublishVersion} {VersionHelper.PublishBuild} [dnscrypt-proxy {DnsCryptProxyManager.GetVersion()}]"; SelectedTab = Tabs.MainTab; _isSavingConfiguration = false; _isWorkingOnService = false; _settingsViewModel = new SettingsViewModel(_windowManager, _events) { WindowTitle = LocalizationEx.GetUiString("settings", Thread.CurrentThread.CurrentCulture) }; _settingsViewModel.PropertyChanged += SettingsViewModelOnPropertyChanged; _listenAddressesViewModel = new ListenAddressesViewModel(_windowManager, _events); _proxiesViewModel = new ProxiesViewModel(_windowManager, _events); _queryLogViewModel = new QueryLogViewModel(_windowManager, _events); _domainBlockLogViewModel = new DomainBlockLogViewModel(_windowManager, _events); _domainBlacklistViewModel = new DomainBlacklistViewModel(_windowManager, _events); _addressBlockLogViewModel = new AddressBlockLogViewModel(_windowManager, _events); _addressBlacklistViewModel = new AddressBlacklistViewModel(_windowManager, _events); _resolvers = new BindableCollection <AvailableResolver>(); }
public void BuildAddressBlacklist() { try { if (IsWorking) { return; } IsWorking = true; DomainBlacklistPathInfoString = LocalizationEx.GetUiString("blacklist_building_list", Thread.CurrentThread.CurrentCulture); var addressBlacklist = GenerateAddressBlacklist(AddressBlacklist); File.WriteAllLines(Path.Combine("data", Global.AddressBlacklistFile), addressBlacklist); AddressBlacklistPath = Path.Combine(Directory.GetCurrentDirectory(), "data", Global.AddressBlacklistFile); UpdateAddressBlacklistPathInfoString(); if (AddressBlacklistPlugin) { SavePlugin(); } IsWorking = false; } catch (Exception) { IsWorking = false; } }
public void AddAddressBlockRule() { try { var metroWindow = Application.Current.MainWindow as MetroWindow; var metroDialogSettings = new MetroDialogSettings { AffirmativeButtonText = LocalizationEx.GetUiString("ok", Thread.CurrentThread.CurrentCulture), NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture) }; var result = metroWindow.ShowModalInputExternal( LocalizationEx.GetUiString("blacklist_modal_new_address_rule_header", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("blacklist_modal_new_address_rule_text", Thread.CurrentThread.CurrentCulture), metroDialogSettings); if (result == null) { return; } var newRule = result.ToLower().Trim(); if (!ValidateAddressInput(newRule)) { return; } if (AddressBlacklist.Rules.FirstOrDefault(l => l.Equals(newRule)) != null) { return; } AddressBlacklist.Rules.Add(newRule); SaveAddressBlacklist(); } catch (Exception) { } }
private async void HandleGlobalResolver(bool actAsGlobalGateway) { IsWorkingOnPrimaryService = true; if (actAsGlobalGateway) { PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalAddress = Global.GlobalGatewayAddress; PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalPort = Global.PrimaryResolverPort; PrimaryDnsCryptProxyManager.WriteRegistry(DnsCryptProxyType.Primary); await Task.Run(() => { PrimaryDnsCryptProxyManager.Restart(); }).ConfigureAwait(false); Thread.Sleep(Global.ServiceRestartTime); _isPrimaryResolverRunning = PrimaryDnsCryptProxyManager.IsDnsCryptProxyRunning(); NotifyOfPropertyChange(() => IsPrimaryResolverRunning); PrimaryResolverTitle = string.Format("{0} ({1}:{2})", LocalizationEx.GetUiString("default_settings_primary_header", Thread.CurrentThread.CurrentCulture), Global.GlobalGatewayAddress, Global.PrimaryResolverPort); } else { PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalAddress = Global.PrimaryResolverAddress; PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalPort = Global.PrimaryResolverPort; PrimaryDnsCryptProxyManager.WriteRegistry(DnsCryptProxyType.Primary); await Task.Run(() => { PrimaryDnsCryptProxyManager.Restart(); }).ConfigureAwait(false); Thread.Sleep(Global.ServiceRestartTime); _isPrimaryResolverRunning = PrimaryDnsCryptProxyManager.IsDnsCryptProxyRunning(); NotifyOfPropertyChange(() => IsPrimaryResolverRunning); PrimaryResolver.LocalPort = Global.PrimaryResolverPort; // reset the resolver port PrimaryResolverTitle = string.Format("{0}", LocalizationEx.GetUiString("default_settings_primary_header", Thread.CurrentThread.CurrentCulture)); } IsWorkingOnPrimaryService = false; }
public async void BuildDomainBlacklist() { try { if (IsWorking) { return; } IsWorking = true; DomainBlacklistPathInfoString = LocalizationEx.GetUiString("blacklist_building_list", Thread.CurrentThread.CurrentCulture); var domainBlacklist = await GenerateDomainBlacklist(DomainBlacklist).ConfigureAwait(false); if (domainBlacklist != null) { File.WriteAllLines(Path.Combine("data", Global.DomainBlacklistFile), domainBlacklist); DomainBlacklistPath = Path.Combine(Directory.GetCurrentDirectory(), "data", Global.DomainBlacklistFile); UpdateDomainBlacklistPathInfoString(); if (DomainBlacklistPlugin) { SavePlugin(); } } IsWorking = false; } catch (Exception exception) { IsWorking = false; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) { return(LocalizationEx.GetUiString("yes", Thread.CurrentThread.CurrentCulture)); } return(LocalizationEx.GetUiString("no", Thread.CurrentThread.CurrentCulture)); }
/// <summary> /// Method to check if there is a new application version available. /// </summary> private async void UpdateAsync() { try { var update = await ApplicationUpdater.CheckForRemoteUpdateAsync().ConfigureAwait(true); if (update.CanUpdate) { var boxType = update.Update.Type == UpdateType.Standard ? BoxType.Default : BoxType.Warning; var boxText = update.Update.Type == UpdateType.Standard ? LocalizationEx.GetUiString("dialog_message_update_standard_text", Thread.CurrentThread.CurrentCulture) : LocalizationEx.GetUiString("dialog_message_update_critical_text", Thread.CurrentThread.CurrentCulture); var boxTitle = update.Update.Type == UpdateType.Standard ? LocalizationEx.GetUiString("dialog_message_update_standard_title", Thread.CurrentThread.CurrentCulture) : LocalizationEx.GetUiString("dialog_message_update_critical_title", Thread.CurrentThread.CurrentCulture); var userResult = _windowManager.ShowMetroMessageBox( string.Format(boxText, update.Update.Version), boxTitle, MessageBoxButton.YesNo, boxType); if (userResult != MessageBoxResult.Yes) { return; } var updateViewModel = new UpdateViewModel(update.Update) { DisplayName = LocalizationEx.GetUiString("window_update_title", Thread.CurrentThread.CurrentCulture) }; dynamic settings = new ExpandoObject(); settings.WindowStartupLocation = WindowStartupLocation.CenterOwner; settings.Owner = GetView(); var result = _windowManager.ShowDialog(updateViewModel, null, settings); if (!result) { return; } if (!File.Exists(updateViewModel.InstallerPath)) { return; } // start the installer Process.Start(updateViewModel.InstallerPath); // kill running application Process.GetCurrentProcess().Kill(); } } catch (Exception) { } }
/// <summary> /// Refresh the resolver list from the newest csv file. /// </summary> /// <exception cref="UnauthorizedAccessException"></exception> /// <exception cref="NotSupportedException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> public async void RefreshResolverListAsync() { IsRefreshingResolverList = true; var state = await DnsCryptProxyListManager.UpdateResolverListAsync().ConfigureAwait(false); await Task.Run(() => { // we do this, to prevent excessive usage Thread.Sleep(2000); }).ConfigureAwait(false); if (state) { var proxyList = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptProxyResolverListName); var proxyListSignature = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptProxySignatureFileName); var dnsProxyList = DnsCryptProxyListManager.ReadProxyList(proxyList, proxyListSignature, _userData.UseIpv6); if (dnsProxyList != null && dnsProxyList.Any()) { Resolvers.Clear(); foreach (var dnsProxy in dnsProxyList) { if ( dnsProxy.ProviderPublicKey.Equals( PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.ProviderKey)) { _primaryResolver = dnsProxy; // restore the local port _primaryResolver.LocalPort = PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalPort; } if ( dnsProxy.ProviderPublicKey.Equals( SecondaryDnsCryptProxyManager.DnsCryptProxy.Parameter.ProviderKey)) { _secondaryResolver = dnsProxy; } Resolvers.Add(dnsProxy); } } } else { _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("dialog_message_refresh_failed", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("dialog_warning_title", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Warning); } IsRefreshingResolverList = false; }
public void Block() { try { if (SelectedLogLine == null) { return; } var newRule = SelectedLogLine.Remote.ToLower().Trim(); var metroWindow = Application.Current.MainWindow as MetroWindow; var metroDialogSettings = new MetroDialogSettings { AffirmativeButtonText = LocalizationEx.GetUiString("ok", Thread.CurrentThread.CurrentCulture), NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture), DefaultText = newRule }; var result = metroWindow.ShowModalInputExternal( LocalizationEx.GetUiString("log_modal_add_rule_header", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("log_modal_add_rule_text", Thread.CurrentThread.CurrentCulture), metroDialogSettings); if (result == null) { return; } var newCustomRule = result.ToLower().Trim(); var response = MainViewModel.Instance.BlockViewModel.ParseBlacklist(newCustomRule, true); if (response.Count() != 1) { return; } if ( MainViewModel.Instance.BlockViewModel.DomainBlacklist.LocalRules.FirstOrDefault(l => l.Rule.Equals(newCustomRule)) != null) { return; } MainViewModel.Instance.BlockViewModel.DomainBlacklist.LocalRules.Add(new LocaleRule { Rule = newCustomRule }); MainViewModel.Instance.BlockViewModel.SaveDomainBlacklist(); } catch (Exception) { } }
public async void BlockQueryLogEntry() { try { if (_selectedQueryLogLine == null) { return; } if (MainViewModel.Instance.DomainBlacklistViewModel == null) { return; } var dialogSettings = new MetroDialogSettings { DefaultText = _selectedQueryLogLine.Remote.ToLower(), AffirmativeButtonText = LocalizationEx.GetUiString("add", Thread.CurrentThread.CurrentCulture), NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture), ColorScheme = MetroDialogColorScheme.Theme }; var metroWindow = Application.Current.Windows.OfType <MetroWindow>().FirstOrDefault(); //TODO: translate var dialogResult = await metroWindow.ShowInputAsync(LocalizationEx.GetUiString("message_title_new_blacklist_rule", Thread.CurrentThread.CurrentCulture), "Rule:", dialogSettings); if (string.IsNullOrEmpty(dialogResult)) { return; } var newCustomRule = dialogResult.ToLower().Trim(); var parsed = DomainBlacklist.ParseBlacklist(newCustomRule, true); var enumerable = parsed as string[] ?? parsed.ToArray(); if (enumerable.Length != 1) { return; } MainViewModel.Instance.DomainBlacklistViewModel.DomainBlacklistRules.Add(enumerable[0]); MainViewModel.Instance.DomainBlacklistViewModel.SaveBlacklistRulesToFile(); } catch (Exception exception) { Log.Error(exception); } }
public void OpenPluginManager() { var win = new PluginManagerViewModel { DisplayName = LocalizationEx.GetUiString("window_plugin_title", Thread.CurrentThread.CurrentCulture) }; win.SetPlugins(Plugins); dynamic settings = new ExpandoObject(); settings.WindowStartupLocation = WindowStartupLocation.CenterOwner; settings.Owner = GetView(); var inputOk = _windowManager.ShowDialog(win, null, settings); if (inputOk == true) { Plugins = win.Plugins; ReloadResolver(DnsCryptProxyType.Primary); ReloadResolver(DnsCryptProxyType.Secondary); } }
/// <summary> /// Uninstall all installed dnscrypt-proxy services. /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="NetworkInformationException"></exception> /// <exception cref="ArgumentNullException"></exception> public async void UninstallServices() { var result = _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("dialog_message_uninstall", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("dialog_uninstall_title", Thread.CurrentThread.CurrentCulture), MessageBoxButton.YesNo, BoxType.Default); if (result == MessageBoxResult.Yes) { IsUninstallingServices = true; await Task.Run(() => { PrimaryDnsCryptProxyManager.Uninstall(); SecondaryDnsCryptProxyManager.Uninstall(); }).ConfigureAwait(false); Thread.Sleep(Global.ServiceUninstallTime); IsUninstallingServices = false; } _isPrimaryResolverRunning = PrimaryDnsCryptProxyManager.IsDnsCryptProxyRunning(); NotifyOfPropertyChange(() => IsPrimaryResolverRunning); _isSecondaryResolverRunning = SecondaryDnsCryptProxyManager.IsDnsCryptProxyRunning(); NotifyOfPropertyChange(() => IsSecondaryResolverRunning); // recover the network interfaces (also the hidden and down cards) foreach (var nic in LocalNetworkInterfaceManager.GetLocalNetworkInterfaces(true, false)) { if (!nic.UseDnsCrypt) { continue; } var status = LocalNetworkInterfaceManager.SetNameservers(nic, new List <string>(), NetworkInterfaceComponent.IPv4); var card = _localNetworkInterfaces.SingleOrDefault(n => n.Description.Equals(nic.Description)); if (card != null) { card.UseDnsCrypt = !status; } } }
public AddRuleWindow(RuleWindowType ruleWindowType) { InitializeComponent(); if (ruleWindowType == RuleWindowType.Cloaking) { Title = LocalizationEx.GetUiString("cloaking", Thread.CurrentThread.CurrentCulture); RuleHeaderIcon.Kind = PackIconMaterialKind.AccountConvert; RuleHeader.Text = LocalizationEx.GetUiString("rule_window_cloaking_header", Thread.CurrentThread.CurrentCulture); RuleKeyDescription.Text = LocalizationEx.GetUiString("rule_window_cloaking_key_text", Thread.CurrentThread.CurrentCulture); RuleValueDescription.Text = LocalizationEx.GetUiString("rule_window_cloaking_value_text", Thread.CurrentThread.CurrentCulture); } else { Title = LocalizationEx.GetUiString("forwarding", Thread.CurrentThread.CurrentCulture); RuleHeaderIcon.Kind = PackIconMaterialKind.Radar; RuleHeader.Text = LocalizationEx.GetUiString("rule_window_forwarding_header", Thread.CurrentThread.CurrentCulture); RuleKeyDescription.Text = LocalizationEx.GetUiString("rule_window_forwarding_key_text", Thread.CurrentThread.CurrentCulture); RuleValueDescription.Text = LocalizationEx.GetUiString("rule_window_forwarding_value_text", Thread.CurrentThread.CurrentCulture); } AddRule.Content = LocalizationEx.GetUiString("rule_window_add", Thread.CurrentThread.CurrentCulture); Abort.Content = LocalizationEx.GetUiString("rule_window_abort", Thread.CurrentThread.CurrentCulture); }
public void AddLocalDomainBlockRule() { try { var metroWindow = Application.Current.MainWindow as MetroWindow; var metroDialogSettings = new MetroDialogSettings { AffirmativeButtonText = LocalizationEx.GetUiString("ok", Thread.CurrentThread.CurrentCulture), NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture) }; var result = metroWindow.ShowModalInputExternal( LocalizationEx.GetUiString("blacklist_modal_new_local_domain_rule_header", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("blacklist_modal_new_local_domain_rule_text", Thread.CurrentThread.CurrentCulture), metroDialogSettings); if (result == null) { return; } var newRule = result.ToLower().Trim(); var response = ParseBlacklist(newRule, true); if (response.Count() != 1) { return; } if (DomainBlacklist.LocalRules.FirstOrDefault(l => l.Rule.Equals(newRule)) != null) { return; } DomainBlacklist.LocalRules.Add(new LocaleRule { Rule = newRule }); SaveDomainBlacklist(); } catch (Exception) { } }
public void AddRemoteDomainBlockRule() { try { var metroWindow = Application.Current.MainWindow as MetroWindow; var metroDialogSettings = new MetroDialogSettings { AffirmativeButtonText = LocalizationEx.GetUiString("ok", Thread.CurrentThread.CurrentCulture), NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture) }; var result = metroWindow.ShowModalInputExternal( LocalizationEx.GetUiString("blacklist_modal_new_remote_domain_rule_header", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("blacklist_modal_new_remote_domain_rule_text", Thread.CurrentThread.CurrentCulture), metroDialogSettings); if (result == null) { return; } var newRule = result.ToLower().Trim(); if (!Uri.IsWellFormedUriString(newRule, UriKind.Absolute)) { return; } if (DomainBlacklist.RemoteRules.FirstOrDefault(l => l.Rule.Equals(newRule)) != null) { return; } DomainBlacklist.RemoteRules.Add(new RemoteRule { Rule = newRule }); SaveDomainBlacklist(); } catch (Exception) { } }
/// <summary> /// Add the license of the libraries and software we use. /// </summary> private async void AddLicenses() { try { var tmpList = new List <License> { new License { LicenseHeaderText = "Simple DNSCrypt", LicenseText = await LoadLicense("SimpleDNSCrypt.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "simplednscrypt.org", LinkUri = new Uri("https://simplednscrypt.org/") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/bitbeans/SimpleDnsCrypt") } }, new License { LicenseHeaderText = "dnscrypt-proxy", LicenseText = await LoadLicense("dnscrypt-proxy.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "dnscrypt.info", LinkUri = new Uri("https://dnscrypt.info/") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/jedisct1/dnscrypt-proxy") } }, new License { LicenseHeaderText = "Caliburn.Micro", LicenseText = await LoadLicense("Caliburn.Micro.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "caliburnmicro.com", LinkUri = new Uri("https://caliburnmicro.com/") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/Caliburn-Micro/Caliburn.Micro") } }, new License { LicenseHeaderText = "MahApps.Metro", LicenseText = await LoadLicense("MahApps.Metro.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "mahapps.com [http]", LinkUri = new Uri("http://mahapps.com/") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/MahApps/MahApps.Metro") } }, new License { LicenseHeaderText = "Hardcodet NotifyIcon", LicenseText = await LoadLicense("Hardcodet.NotifyIcon.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "http://www.hardcodet.net/projects/wpf-notifyicon [http]", LinkUri = new Uri("http://www.hardcodet.net/projects/wpf-notifyicon") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://bitbucket.org/hardcodet/notifyicon-wpf/src") } }, new License { LicenseHeaderText = "YamlDotNet", LicenseText = await LoadLicense("YamlDotNet.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/aaubry/YamlDotNet") } }, new License { LicenseHeaderText = "Nett", LicenseText = await LoadLicense("Nett.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/paiden/Nett") } }, new License { LicenseHeaderText = "Newtonsoft.Json", LicenseText = await LoadLicense("Newtonsoft.Json.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "www.newtonsoft.com", LinkUri = new Uri("https://www.newtonsoft.com/json") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/JamesNK/Newtonsoft.Json") } }, new License { LicenseHeaderText = "WPFLocalizationExtension", LicenseText = await LoadLicense("WPFLocalizationExtension.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/SeriousM/WPFLocalizationExtension") } }, new License { LicenseHeaderText = "XAMLMarkupExtensions", LicenseText = await LoadLicense("XAMLMarkupExtensions.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/MrCircuit/XAMLMarkupExtensions") } }, new License { LicenseHeaderText = "minisign-net", LicenseText = await LoadLicense("minisign-net.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/bitbeans/minisign-net") } }, new License { LicenseHeaderText = "libsodium-net", LicenseText = await LoadLicense("libsodium-net.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/adamcaudill/libsodium-net") } }, new License { LicenseHeaderText = "Costura.Fody", LicenseText = await LoadLicense("Costura.Fody.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/Fody/Costura") } }, new License { LicenseHeaderText = "Fody", LicenseText = await LoadLicense("Fody.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/Fody/Fody") } }, new License { LicenseHeaderText = "helper-net", LicenseText = await LoadLicense("helper-net.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/bitbeans/helper-net") } }, new License { LicenseHeaderText = "ControlzEx", LicenseText = await LoadLicense("ControlzEx.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/ControlzEx/ControlzEx") } }, new License { LicenseHeaderText = "Baseclass.Contrib.Nuget.Output", LicenseText = await LoadLicense("Baseclass.Contrib.Nuget.Output.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/baseclass/Contrib.Nuget") } }, new License { LicenseHeaderText = "NLog", LicenseText = await LoadLicense("NLog.txt").ConfigureAwait(false), LicenseRegularLink = new LicenseLink { LinkText = "nlog-project.org [http]", LinkUri = new Uri("http://nlog-project.org/") }, LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/nlog/NLog") } }, new License { LicenseHeaderText = "MahApps.Metro.SimpleChildWindow", LicenseText = await LoadLicense("MahApps.Metro.SimpleChildWindow.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/punker76/MahApps.Metro.SimpleChildWindow") } }, new License { LicenseHeaderText = "gong-wpf-dragdrop", LicenseText = await LoadLicense("gong-wpf-dragdrop.txt").ConfigureAwait(false), LicenseCodeLink = new LicenseLink { LinkText = LocalizationEx.GetUiString("about_view_on_github", Thread.CurrentThread.CurrentCulture), LinkUri = new Uri("https://github.com/punker76/gong-wpf-dragdrop") } } }; var orderedList = tmpList.OrderBy(l => l.LicenseHeaderText); _licenses = new BindableCollection <License>(orderedList); } catch (Exception) { } }
/// <summary> /// Handle the given file. /// </summary> /// <param name="activationDataMessage"></param> public async void Handle(ActivationDataMessage activationDataMessage) { try { // validate the inputFile if (string.IsNullOrEmpty(activationDataMessage.AbsolutePath)) { throw new ArgumentOutOfRangeException( string.Format(LocalizationEx.GetUiString("error_filename_invalid_size", Thread.CurrentThread.CurrentCulture), 0)); } if (!File.Exists(activationDataMessage.AbsolutePath)) { throw new FileNotFoundException(LocalizationEx.GetUiString("error_file_not_found", Thread.CurrentThread.CurrentCulture)); } InputFilePath = activationDataMessage.AbsolutePath; var outputFolder = Path.GetDirectoryName(InputFilePath); // validate the outputFolder if (string.IsNullOrEmpty(outputFolder) || !Directory.Exists(outputFolder)) { throw new DirectoryNotFoundException(LocalizationEx.GetUiString("error_directory_not_found", Thread.CurrentThread.CurrentCulture)); } if (outputFolder.IndexOfAny(Path.GetInvalidPathChars()) > -1) { throw new ArgumentException(LocalizationEx.GetUiString("error_bad_character_input", Thread.CurrentThread.CurrentCulture)); } var decryptionProgress = new Progress <StreamCryptorTaskAsyncProgress>(); decryptionProgress.ProgressChanged += (s, e) => { ProgressBarValue = e.ProgressPercentage; }; var identityWindow = new IdentityViewModel { DisplayName = ApplicationName }; dynamic settings = new ExpandoObject(); settings.WindowStartupLocation = WindowStartupLocation.CenterOwner; settings.Owner = GetView(); var calculation = _windowManager.ShowDialog(identityWindow, null, settings); if (calculation == true) { if (identityWindow.KeyPair != null) { //TODO: maybe allow cancellation on large files var cancellationToken = new CancellationToken(); var outputFile = await Cryptor.DecryptFileWithStreamAsync(identityWindow.KeyPair, InputFilePath, outputFolder, decryptionProgress, true, cancellationToken).ConfigureAwait(false); identityWindow.KeyPair = null; var outputFileFullPath = Path.Combine(outputFolder, outputFile); if (File.Exists(outputFileFullPath)) { ProgressBarValue = 0; OutputFilePath = outputFileFullPath; } else { throw new FileNotFoundException(LocalizationEx.GetUiString("error_decrypted_file_not_found", Thread.CurrentThread.CurrentCulture)); } } else { throw new CryptographicException(LocalizationEx.GetUiString("error_failed_to_calculate", Thread.CurrentThread.CurrentCulture)); } } else { Environment.Exit(0); } } catch (Exception exception) when( exception is ArgumentOutOfRangeException || exception is ArgumentException || exception is CryptographicException || exception is FileNotFoundException || exception is DirectoryNotFoundException) { _windowManager.ShowMetroMessageBox( exception.Message, LocalizationEx.GetUiString("error_header_handled", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Warning); TryClose(); } catch (Exception unhandledException) { _windowManager.ShowMetroMessageBox( unhandledException.Message, LocalizationEx.GetUiString("error_header_unhandled", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Error); TryClose(); } }
private async void InitializeApplication() { try { if (IsAdministrator()) { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_available", Thread.CurrentThread.CurrentCulture); } else { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_missing", Thread.CurrentThread.CurrentCulture); await Task.Delay(3000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_check", Thread.CurrentThread.CurrentCulture); if (PrerequisiteHelper.IsRedistributablePackageInstalled()) { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_already_installed", Thread.CurrentThread.CurrentCulture); } else { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_installing", Thread.CurrentThread.CurrentCulture); //minisign needs this (to verify the installer with libsodium) await PrerequisiteHelper.DownloadAndInstallRedistributablePackage(); if (PrerequisiteHelper.IsRedistributablePackageInstalled()) { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_ready", Thread.CurrentThread.CurrentCulture); await Task.Delay(1000).ConfigureAwait(false); } } if (Properties.Settings.Default.AutoUpdate) { ProgressText = LocalizationEx.GetUiString("loader_checking_version", Thread.CurrentThread.CurrentCulture); //TODO: remove in future version (for now we only have one channel) Properties.Settings.Default.MinUpdateType = 2; Properties.Settings.Default.Save(); var minUpdateType = (UpdateType)Properties.Settings.Default.MinUpdateType; var update = await ApplicationUpdater.CheckForRemoteUpdateAsync(minUpdateType).ConfigureAwait(false); if (update.CanUpdate) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_new_version_found", Thread.CurrentThread.CurrentCulture), update.Update.Version); await Task.Delay(200).ConfigureAwait(false); var installer = await StartRemoteUpdateDownload(update).ConfigureAwait(false); if (!string.IsNullOrEmpty(installer) && File.Exists(installer)) { ProgressText = LocalizationEx.GetUiString("loader_starting_update", Thread.CurrentThread.CurrentCulture); await Task.Delay(200).ConfigureAwait(false); Process.Start(installer); Process.GetCurrentProcess().Kill(); } else { await Task.Delay(500).ConfigureAwait(false); ProgressText = LocalizationEx.GetUiString("loader_update_failed", Thread.CurrentThread.CurrentCulture); } } else { ProgressText = LocalizationEx.GetUiString("loader_latest_version", Thread.CurrentThread.CurrentCulture); } } else { await Task.Delay(500).ConfigureAwait(false); } ProgressText = string.Format(LocalizationEx.GetUiString("loader_validate_folder", Thread.CurrentThread.CurrentCulture), Global.DnsCryptProxyFolder); var validatedFolder = ValidateDnsCryptProxyFolder(); if (validatedFolder.Count == 0) { ProgressText = LocalizationEx.GetUiString("loader_all_files_available", Thread.CurrentThread.CurrentCulture); } else { var fileErrors = ""; foreach (var pair in validatedFolder) { fileErrors += $"{pair.Key}: {pair.Value}\n"; } ProgressText = string.Format( LocalizationEx.GetUiString("loader_missing_files", Thread.CurrentThread.CurrentCulture).Replace("\\n", "\n"), Global.DnsCryptProxyFolder, fileErrors, Global.ApplicationName); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = string.Format(LocalizationEx.GetUiString("loader_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); if (DnscryptProxyConfigurationManager.LoadConfiguration()) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_successfully_loaded", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); _mainViewModel.DnscryptProxyConfiguration = DnscryptProxyConfigurationManager.DnscryptProxyConfiguration; } else { ProgressText = string.Format(LocalizationEx.GetUiString("loader_failed_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_loading_network_cards", Thread.CurrentThread.CurrentCulture); List <LocalNetworkInterface> localNetworkInterfaces; if (DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.listen_addresses.Contains(Global.GlobalResolver)) { var dnsServer = new List <string> { Global.DefaultResolverIpv4, Global.DefaultResolverIpv6 }; localNetworkInterfaces = LocalNetworkInterfaceManager.GetLocalNetworkInterfaces(dnsServer); } else { localNetworkInterfaces = LocalNetworkInterfaceManager.GetLocalNetworkInterfaces( DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.listen_addresses.ToList()); } _mainViewModel.LocalNetworkInterfaces = new BindableCollection <LocalNetworkInterface>(); _mainViewModel.LocalNetworkInterfaces.AddRange(localNetworkInterfaces); _mainViewModel.Initialize(); ProgressText = LocalizationEx.GetUiString("loader_starting", Thread.CurrentThread.CurrentCulture); if (Properties.Settings.Default.TrayMode) { Execute.OnUIThread(() => _windowManager.ShowWindow(_systemTrayViewModel)); Execute.OnUIThread(() => _systemTrayViewModel.ShowWindow()); } else { Execute.OnUIThread(() => _windowManager.ShowWindow(_mainViewModel)); } TryClose(true); } catch (Exception exception) { Log.Error(exception); } }
private MainViewModel(IWindowManager windowManager, IEventAggregator eventAggregator) { _windowManager = windowManager; eventAggregator.Subscribe(this); _userData = new UserData(Path.Combine(Directory.GetCurrentDirectory(), Global.UserConfigurationFile)); // fill the language combobox _languages = LocalizationEx.GetSupportedLanguages(); // automatically use the correct translations if available (fallback: en) LocalizeDictionary.Instance.SetCurrentThreadCulture = true; // overwrite language detection LocalizeDictionary.Instance.Culture = _userData.Language.Equals("auto") ? Thread.CurrentThread.CurrentCulture : new CultureInfo(_userData.Language); // select the current language in the combobox _selectedLanguage = _languages.SingleOrDefault(l => l.ShortCode.Equals(LocalizeDictionary.Instance.Culture.TwoLetterISOLanguageName)); // this is already defined in the app.manifest, but to be sure check it again if (!IsAdministrator()) { _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("dialog_message_bad_privileges", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("dialog_error_title", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Error); Environment.Exit(1); } // do a simple check, if all needed files are available if (!ValidateDnsCryptProxyFolder()) { _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("dialog_message_missing_proxy_files", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("dialog_error_title", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Error); Environment.Exit(1); } if (_userData.UseIpv6) { DisplayName = string.Format("{0} {1}", Global.ApplicationName, VersionUtilities.PublishVersion); } else { DisplayName = string.Format("{0} {1} ({2})", Global.ApplicationName, VersionUtilities.PublishVersion, LocalizationEx.GetUiString("global_ipv6_disabled", Thread.CurrentThread.CurrentCulture)); } _resolvers = new List <DnsCryptProxyEntry>(); _updateResolverListOnStart = _userData.UpdateResolverListOnStart; _isWorkingOnPrimaryService = false; _isWorkingOnSecondaryService = false; LocalNetworkInterfaces = new CollectionViewSource { Source = _localNetworkInterfaces }; PrimaryDnsCryptProxyManager = new DnsCryptProxyManager(DnsCryptProxyType.Primary); SecondaryDnsCryptProxyManager = new DnsCryptProxyManager(DnsCryptProxyType.Secondary); ShowHiddenCards = false; if (PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.TcpOnly || SecondaryDnsCryptProxyManager.DnsCryptProxy.Parameter.TcpOnly) { _useTcpOnly = true; } // check the primary resolver for plugins if (PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.Plugins.Any()) { _plugins = PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.Plugins.ToList(); } else { if (SecondaryDnsCryptProxyManager.DnsCryptProxy.Parameter.Plugins.Any()) { _plugins = SecondaryDnsCryptProxyManager.DnsCryptProxy.Parameter.Plugins.ToList(); } else { // no stored plugins _plugins = new List <string>(); } } var proxyList = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptProxyResolverListName); var proxyListSignature = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptProxySignatureFileName); if (!File.Exists(proxyList) || !File.Exists(proxyListSignature) || UpdateResolverListOnStart) { // download and verify the proxy list if there is no one. AsyncHelpers.RunSync(DnsCryptProxyListManager.UpdateResolverListAsync); } var dnsProxyList = DnsCryptProxyListManager.ReadProxyList(proxyList, proxyListSignature, _userData.UseIpv6); if (dnsProxyList != null && dnsProxyList.Any()) { foreach (var dnsProxy in dnsProxyList) { if ( dnsProxy.Name.Equals( PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.ResolverName)) { _primaryResolver = dnsProxy; // restore the local port _primaryResolver.LocalPort = PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalPort; } if ( dnsProxy.Name.Equals( SecondaryDnsCryptProxyManager.DnsCryptProxy.Parameter.ResolverName)) { _secondaryResolver = dnsProxy; } _resolvers.Add(dnsProxy); } } else { _windowManager.ShowMetroMessageBox( string.Format( LocalizationEx.GetUiString("dialog_message_missing_file", Thread.CurrentThread.CurrentCulture), proxyList, proxyListSignature), LocalizationEx.GetUiString("dialog_error_title", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Error); Environment.Exit(1); } // if there is no selected primary resolver, add a default resolver if (PrimaryResolver == null) { DnsCryptProxyEntry defaultResolver; // first check the config file if (_userData.PrimaryResolver.Equals("auto")) { // automatic, so choose the DefaultPrimaryResolver defaultResolver = dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultPrimaryResolverName)) ?? dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultPrimaryBackupResolverName)); } else { defaultResolver = dnsProxyList.SingleOrDefault(d => d.Name.Equals(_userData.PrimaryResolver)) ?? (dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultPrimaryResolverName)) ?? dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultPrimaryBackupResolverName))); } PrimaryResolver = defaultResolver; } // if there is no selected secondary resolver, add a default resolver if (SecondaryResolver == null) { DnsCryptProxyEntry defaultResolver; // first check the config file if (_userData.SecondaryResolver.Equals("auto")) { // automatic, so choose the DefaultPrimaryResolver defaultResolver = dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultSecondaryResolverName)) ?? dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultSecondaryBackupResolverName)); } else { defaultResolver = dnsProxyList.SingleOrDefault(d => d.Name.Equals(_userData.SecondaryResolver)) ?? (dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultSecondaryResolverName)) ?? dnsProxyList.SingleOrDefault(d => d.Name.Equals(Global.DefaultSecondaryBackupResolverName))); } SecondaryResolver = defaultResolver; } if (PrimaryDnsCryptProxyManager.IsDnsCryptProxyInstalled()) { if (PrimaryDnsCryptProxyManager.IsDnsCryptProxyRunning()) { _isPrimaryResolverRunning = true; } } if (SecondaryDnsCryptProxyManager.IsDnsCryptProxyInstalled()) { if (SecondaryDnsCryptProxyManager.IsDnsCryptProxyRunning()) { _isSecondaryResolverRunning = true; } } if ( PrimaryDnsCryptProxyManager.DnsCryptProxy.Parameter.LocalAddress.Equals( Global.GlobalGatewayAddress)) { _actAsGlobalGateway = true; _primaryResolverTitle = string.Format("{0} ({1}:{2})", LocalizationEx.GetUiString("default_settings_primary_header", Thread.CurrentThread.CurrentCulture), Global.GlobalGatewayAddress, Global.PrimaryResolverPort); } else { _actAsGlobalGateway = false; _primaryResolverTitle = string.Format("{0}", LocalizationEx.GetUiString("default_settings_primary_header", Thread.CurrentThread.CurrentCulture)); } _secondaryResolverTitle = string.Format("{0} ({1}:{2})", LocalizationEx.GetUiString("default_settings_secondary_header", Thread.CurrentThread.CurrentCulture), Global.SecondaryResolverAddress, Global.SecondaryResolverPort); // check for new version on every application start UpdateAsync(); }
private async void InitializeApplication() { try { if (IsAdministrator()) { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_available", Thread.CurrentThread.CurrentCulture); } else { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_missing", Thread.CurrentThread.CurrentCulture); await Task.Delay(3000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_checking_version", Thread.CurrentThread.CurrentCulture); var update = await ApplicationUpdater.CheckForRemoteUpdateAsync().ConfigureAwait(false); if (update.CanUpdate) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_new_version_found", Thread.CurrentThread.CurrentCulture), update.Update.Version); await Task.Delay(200).ConfigureAwait(false); var installer = await StartRemoteUpdateDownload(update).ConfigureAwait(false); if (!string.IsNullOrEmpty(installer) && File.Exists(installer)) { ProgressText = LocalizationEx.GetUiString("loader_starting_update", Thread.CurrentThread.CurrentCulture); await Task.Delay(200).ConfigureAwait(false); Process.Start(installer); Process.GetCurrentProcess().Kill(); } else { await Task.Delay(500).ConfigureAwait(false); ProgressText = LocalizationEx.GetUiString("loader_update_failed", Thread.CurrentThread.CurrentCulture); } } else { ProgressText = LocalizationEx.GetUiString("loader_latest_version", Thread.CurrentThread.CurrentCulture); } ProgressText = string.Format(LocalizationEx.GetUiString("loader_validate_folder", Thread.CurrentThread.CurrentCulture), Global.DnsCryptProxyFolder); var validatedFolder = ValidateDnsCryptProxyFolder(); if (validatedFolder.Count == 0) { ProgressText = LocalizationEx.GetUiString("loader_all_files_available", Thread.CurrentThread.CurrentCulture); } else { var fileErrors = ""; foreach (var pair in validatedFolder) { fileErrors += $"{pair.Key}: {pair.Value}\n"; } ProgressText = string.Format( LocalizationEx.GetUiString("loader_missing_files", Thread.CurrentThread.CurrentCulture).Replace("\\n", "\n"), Global.DnsCryptProxyFolder, fileErrors, Global.ApplicationName); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = string.Format(LocalizationEx.GetUiString("loader_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); if (DnscryptProxyConfigurationManager.LoadConfiguration()) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_successfully_loaded", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); _mainViewModel.DnscryptProxyConfiguration = DnscryptProxyConfigurationManager.DnscryptProxyConfiguration; } else { ProgressText = string.Format(LocalizationEx.GetUiString("loader_failed_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_loading_network_cards", Thread.CurrentThread.CurrentCulture); var localNetworkInterfaces = LocalNetworkInterfaceManager.GetLocalNetworkInterfaces( DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.listen_addresses.ToList()); _mainViewModel.LocalNetworkInterfaces = new BindableCollection <LocalNetworkInterface>(); _mainViewModel.LocalNetworkInterfaces.AddRange(localNetworkInterfaces); _mainViewModel.Initialize(); ProgressText = LocalizationEx.GetUiString("loader_starting", Thread.CurrentThread.CurrentCulture); Execute.OnUIThread(() => _windowManager.ShowWindow(_mainViewModel)); TryClose(true); } catch (Exception exception) { Log.Error(exception); } }
private async void InitializeApplication() { try { if (IsAdministrator()) { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_available", Thread.CurrentThread.CurrentCulture); } else { ProgressText = LocalizationEx.GetUiString("loader_administrative_rights_missing", Thread.CurrentThread.CurrentCulture); await Task.Delay(3000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_check", Thread.CurrentThread.CurrentCulture); if (PrerequisiteHelper.IsRedistributablePackageInstalled()) { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_already_installed", Thread.CurrentThread.CurrentCulture); } else { //Note: if this is disabled, the auto update may not work if (Properties.Settings.Default.InstallRedistributablePackage) { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_installing", Thread.CurrentThread.CurrentCulture); //minisign needs this (to verify the installer with libsodium) await PrerequisiteHelper.DownloadAndInstallRedistributablePackage(); if (PrerequisiteHelper.IsRedistributablePackageInstalled()) { ProgressText = LocalizationEx.GetUiString("loader_redistributable_package_ready", Thread.CurrentThread.CurrentCulture); await Task.Delay(1000).ConfigureAwait(false); } } } ProgressText = string.Format(LocalizationEx.GetUiString("loader_validate_folder", Thread.CurrentThread.CurrentCulture), Global.DnsCryptProxyFolder); var validatedFolder = ValidateDnsCryptProxyFolder(); if (validatedFolder.Count == 0) { ProgressText = LocalizationEx.GetUiString("loader_all_files_available", Thread.CurrentThread.CurrentCulture); } else if (validatedFolder.Count == 1 && validatedFolder.Single().Key == Global.DnsCryptConfigurationFile) { File.Copy( Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptExampleConfigurationFile), Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptConfigurationFile), false); } else { var fileErrors = ""; foreach (var pair in validatedFolder) { fileErrors += $"{pair.Key}: {pair.Value}\n"; } ProgressText = string.Format( LocalizationEx.GetUiString("loader_missing_files", Thread.CurrentThread.CurrentCulture).Replace("\\n", "\n"), Global.DnsCryptProxyFolder, fileErrors, Global.ApplicationName); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } if (Properties.Settings.Default.BackupAndRestoreConfigOnUpdate) { var tmpConfigPath = Path.Combine(Path.GetTempPath(), Global.DnsCryptConfigurationFile + ".bak"); if (File.Exists(tmpConfigPath)) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_restore_config", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); var configFile = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder, Global.DnsCryptConfigurationFile); if (File.Exists(configFile)) { if (File.Exists(configFile + ".bak")) { File.Delete(configFile + ".bak"); } File.Move(configFile, configFile + ".bak"); } File.Move(tmpConfigPath, configFile); // update the configuration file if (PatchHelper.Patch()) { await Task.Delay(500).ConfigureAwait(false); } } } ProgressText = string.Format(LocalizationEx.GetUiString("loader_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); if (DnscryptProxyConfigurationManager.LoadConfiguration()) { ProgressText = string.Format(LocalizationEx.GetUiString("loader_successfully_loaded", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); _mainViewModel.DnscryptProxyConfiguration = DnscryptProxyConfigurationManager.DnscryptProxyConfiguration; } else { ProgressText = string.Format(LocalizationEx.GetUiString("loader_failed_loading", Thread.CurrentThread.CurrentCulture), Global.DnsCryptConfigurationFile); await Task.Delay(5000).ConfigureAwait(false); Process.GetCurrentProcess().Kill(); } ProgressText = LocalizationEx.GetUiString("loader_loading_network_cards", Thread.CurrentThread.CurrentCulture); List <LocalNetworkInterface> localNetworkInterfaces; if (DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.listen_addresses.Contains(Global.GlobalResolver)) { var dnsServer = new List <string> { Global.DefaultResolverIpv4, Global.DefaultResolverIpv6 }; localNetworkInterfaces = LocalNetworkInterfaceManager.GetLocalNetworkInterfaces(dnsServer); } else { localNetworkInterfaces = LocalNetworkInterfaceManager.GetLocalNetworkInterfaces( DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.listen_addresses.ToList()); } _mainViewModel.LocalNetworkInterfaces = new BindableCollection <LocalNetworkInterface>(); _mainViewModel.LocalNetworkInterfaces.AddRange(localNetworkInterfaces); _mainViewModel.Initialize(); ProgressText = LocalizationEx.GetUiString("loader_starting", Thread.CurrentThread.CurrentCulture); if (Properties.Settings.Default.TrayMode) { await Execute.OnUIThreadAsync(() => _windowManager.ShowWindowAsync(_systemTrayViewModel)); if (Properties.Settings.Default.StartInTray) { Execute.OnUIThread(() => _systemTrayViewModel.HideWindow()); } else { await Execute.OnUIThreadAsync(() => _windowManager.ShowWindowAsync(_mainViewModel)); } } else { await Execute.OnUIThreadAsync(() => _windowManager.ShowWindowAsync(_mainViewModel)); } await TryCloseAsync(true); } catch (Exception exception) { Log.Error(exception); throw; } }
private async void Log() { try { if (_isLogging) { if (!string.IsNullOrEmpty(_logFile)) { if (File.Exists(_logFile)) { await Task.Run(() => { using (var reader = new StreamReader(new FileStream(_logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { //start at the end of the file var lastMaxOffset = reader.BaseStream.Length; while (_isLogging) { Thread.Sleep(100); //if the file size has not changed, idle if (reader.BaseStream.Length == lastMaxOffset) { continue; } //seek to the last max offset reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin); //read out of the file until the EOF string line; while ((line = reader.ReadLine()) != null) { var logLine = new LogLine(line); AddLogLine(logLine); } //update the last max offset lastMaxOffset = reader.BaseStream.Position; } } }); } else { IsLogging = false; _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("log_modal_no_log_file_text", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("log_modal_no_log_file_header", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Warning); } } else { IsLogging = false; _windowManager.ShowMetroMessageBox( LocalizationEx.GetUiString("log_modal_no_log_file_text", Thread.CurrentThread.CurrentCulture), LocalizationEx.GetUiString("log_modal_no_log_file_header", Thread.CurrentThread.CurrentCulture), MessageBoxButton.OK, BoxType.Warning); } } else { Execute.OnUIThread(() => { LogLines.Clear(); }); } } catch (Exception) { } }
private void UpdateAddressBlacklistPathInfoString() { AddressBlacklistPathInfoString = string.Format("({0} {1}; {2})", File.ReadLines(_addressBlacklistPath).Count(), LocalizationEx.GetUiString("blacklist_entries", Thread.CurrentThread.CurrentCulture), new FileInfo(_addressBlacklistPath).LastWriteTime); }