protected void CheckPreviousBackup() { string backupFilePath = GetSystemSettingsBackupPath(); if (File.Exists(backupFilePath)) { // backup file exists DateTime date = File.GetLastWriteTime(backupFilePath); string message = string.Format(Resources.CommandBase_Message_SystemSettingsAreNotRestored, date); bool? answer = Prompt(message, threeState: true); // process depending on answer // true (Yes): restore the backup // false (No): do not restore the backup, but delete it // null (Cancel): do nothing if (answer.HasValue) { if (answer.Value) { // restore the backup JsonObjectData data = JsonObjectData.Load(backupFilePath, createIfNotExist: false); if (data != null) { SystemSettingsSwitcher switcher = this.ComponentFactory.CreateSystemSettingsSwitcher(this, null); switcher.Restore(data, systemSessionEnding: false); } } // delete backup file File.Delete(backupFilePath); } } return; }
public SetupContext(CommandSettings settings, SystemSettingsSwitcher switcher) { // argument checks if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (switcher == null) { throw new ArgumentNullException(nameof(switcher)); } // initialize members this.Settings = settings; // ActualProxy this.DefaultActualProxyHostName = SystemSettingsSwitcher.GetDefaultActualProxyHostName(); this.DefaultActualProxyPort = SystemSettingsSwitcher.GetDefaultActualProxyPort(); this.DefaultActualProxyConfigurationScript = SystemSettingsSwitcher.GetDefaultActualProxyConfigurationScript(); IActualProxy actualProxy = switcher.DetectSystemActualProxy(); if (actualProxy != null) { this.ProxyDetected = true; DisposableUtil.ClearDisposableObject(ref actualProxy); } if (this.ProxyDetected == false && settings.SystemSettingsSwitcher.ActualProxy == null) { // The authentication proxy cannot be detected automatically. // User must set its information explicitly. this.NeedActualProxy = true; } return; }
public virtual bool TestWebProxy(IActualProxy actualProxy) { // get test url specified in application config file // (not in the settings file because this information is supposed to be set for site) string targetUrl = SystemSettingsSwitcher.GetProxyTestUrl(); Debug.Assert(string.IsNullOrEmpty(targetUrl) == false); Uri target = new Uri(targetUrl); DnsEndPoint targetEndPoint = new DnsEndPoint(target.Host, target.Port); WebClientForTest webClient = new WebClientForTest(); webClient.Timeout = 10 * 1000; // 10 seconds // test each proxy candidate CommandBase owner = this.Owner; bool result = false; IReadOnlyCollection <DnsEndPoint> endPoints = actualProxy.GetProxyEndPoints(target); if (endPoints != null) { foreach (DnsEndPoint endPoint in endPoints) { owner.LogVerbose($"ActualProxy check: to {endPoint.Host}:{endPoint.Port}"); try { webClient.Proxy = new WebProxy(endPoint.Host, endPoint.Port); webClient.DownloadData(targetUrl); // an exception is thrown on error result = true; } catch (WebException exception) { // Note that a protocol error indicates that the end point exists result = (exception.Status == WebExceptionStatus.ProtocolError); if (result) { owner.LogVerbose($"ActualProxy check: {exception.Status} -> OK"); } else { owner.LogError($"ActualProxy check: {exception.Status} -> NG"); } } if (result) { // a valid proxy is found break; } } } if (result) { owner.LogVerbose("ActualProxy check: OK - there is a valid actual proxy."); } else { owner.LogError("ActualProxy check: NG - no valid proxy."); } return(result); }
public bool Stop(bool systemSessionEnding, int millisecondsTimeout = 0) { // restore the system settings SystemSettingsSwitcher switcher = this.switcher; this.switcher = null; SystemSettings backup = this.backup; this.backup = null; if (backup != null) { Debug.Assert(switcher != null); try { switcher.Restore(backup, systemSessionEnding); this.Owner.DeleteSystemSettingsBackup(); } catch (Exception exception) { this.Owner.ShowRestoreSystemSettingsErrorMessage(exception.Message); // continue } } // stop and dispose the proxy Proxy proxy = this.proxy; this.proxy = null; bool stopConfirmed = false; if (proxy == null) { stopConfirmed = true; } else { try { stopConfirmed = proxy.Stop(millisecondsTimeout); } finally { DisposableUtil.DisposeSuppressingErrors(proxy); } } // update credentials if necessary IEnumerable <CredentialSettings> credentials = null; lock (this.credentialsLocker) { if (this.isCredentialsDirty) { this.isCredentialsDirty = false; credentials = this.dictionary.Select(pair => CloneSettings(pair.Value)).ToArray(); } this.dictionary = null; } if (credentials != null) { if (this.commandSettings != null) { this.commandSettings.Credentials = credentials; } if (this.saveCredentials) { Action saveTask = () => { try { this.Owner.UpdateSettingsFile((s) => { s.Credentials = credentials; }, null); } catch (Exception exception) { string message = string.Format(Resources.CommandBase_Message_FailToSaveCredentials, exception.Message); this.Owner.ShowErrorMessage(message); } }; // launch save task Task.Run(saveTask); } } this.saveCredentials = false; // checks Debug.Assert(this.proxy == null); Debug.Assert(this.switcher == null); Debug.Assert(this.backup == null); Debug.Assert(this.saveCredentials == false); return(stopConfirmed); }
public void Start(CommandSettings commandSettings, bool saveCredentials, bool checkPreviousBackup) { // argument checks if (commandSettings == null) { throw new ArgumentNullException(nameof(commandSettings)); } SystemSettingsSwitcherSettings systemSettingsSwitcherSettings = commandSettings.SystemSettingsSwitcher; if (systemSettingsSwitcherSettings == null) { throw new ArgumentNullException(nameof(commandSettings.SystemSettingsSwitcher)); } ProxySettings proxySettings = commandSettings.Proxy; if (proxySettings == null) { throw new ArgumentNullException(nameof(commandSettings.Proxy)); } // state checks if (this.proxy != null) { throw new InvalidOperationException("The proxy is already started."); } Debug.Assert(this.switcher == null); Debug.Assert(this.backup == null); try { ComponentFactory componentFactory = this.Owner.ComponentFactory; // check the state of previous backup if (checkPreviousBackup) { this.Owner.CheckPreviousBackup(); } // create a system settings swither SystemSettingsSwitcher switcher = componentFactory.CreateSystemSettingsSwitcher(this.Owner, systemSettingsSwitcherSettings); this.switcher = switcher; // setup credential dictionary lock (this.credentialsLocker) { IEnumerable <CredentialSettings> credentials = commandSettings.Credentials; this.dictionary = (credentials == null)? new Dictionary <string, CredentialSettings>(): credentials.ToDictionary(c => c.EndPoint); this.isCredentialsDirty = false; } // create a proxy Proxy proxy = componentFactory.CreateProxy(proxySettings); this.proxy = proxy; // detect the current proxy IActualProxy actualProxy = switcher.GetActualProxy(); if (actualProxy == null) { // no actual proxy to which it connects throw new Exception(Resources.CommandBase_Message_NoActualProxy); } try { // log CommandBase owner = this.Owner; if (owner.ShouldLog(TraceEventType.Verbose)) { // log the actual proxy owner.LogVerbose($"ActualProxy is '{actualProxy.Description}'"); // log whether system settings is being switched string label = switcher.Enabled ? "enabled" : "disabled"; owner.LogVerbose($"SystemSettingsSwitch: {label}"); } // test actual proxy if (switcher.TestWebProxy(actualProxy) == false) { string message = string.Format(Resources.SystemSettingsSwitcher_Message_ProxyIsNotConnectable, actualProxy.Description); throw new Exception(message); } // start the proxy proxy.ActualProxy = actualProxy; actualProxy = null; // its ownership has been moved to the proxy object. proxy.Start(this); this.saveCredentials = saveCredentials; // switch system settings this.backup = switcher.Switch(proxy); if (this.backup != null) { // save backup settings owner.SaveSystemSettingsBackup(this.backup); } this.commandSettings = commandSettings; } catch { DisposableUtil.ClearDisposableObject(ref actualProxy); throw; } } catch { Stop(systemSessionEnding: false); throw; } return; }