public SettingsForm(IAudioDeviceLister audioDeviceLister) { _audioDeviceLister = audioDeviceLister; // Form itself InitializeComponent(); Icon = RessourceSettingsIcon; Text = AssemblyUtils.GetReleaseState() == AssemblyUtils.ReleaseState.Beta ? $"{SettingsStrings.settings} {AssemblyUtils.GetReleaseState()}" : SettingsStrings.settings; LocalizeForm(); var closeToolTip = new ToolTip(); closeToolTip.SetToolTip(closeButton, SettingsStrings.closeTooltip); hotKeyControl.HotKey = AppConfigs.Configuration.PlaybackHotKey; hotKeyControl.Tag = new Tuple <DataFlow, HotKey>(DataFlow.Render, AppConfigs.Configuration.PlaybackHotKey); hotKeyControl.Enabled = hotkeysCheckBox.Checked = AppConfigs.Configuration.PlaybackHotKey.Enabled; var hotkeysToolTip = new ToolTip(); hotkeysToolTip.SetToolTip(hotkeysCheckBox, SettingsStrings.hotkeysTooltip); // Settings - Basic startWithWindowsCheckBox.Checked = AppModel.Instance.RunAtStartup; new IconChangerFactory().ConfigureListControl(iconChangeChoicesComboBox); iconChangeChoicesComboBox.SelectedValue = AppConfigs.Configuration.SwitchIcon; var iconChangeToolTip = new ToolTip(); iconChangeToolTip.SetToolTip(iconChangeLabel, SettingsStrings.iconChange_tooltip); // Settings - Audio switchCommunicationDeviceCheckBox.Checked = AppModel.Instance.SetCommunications; var switchCommunicationsDeviceToolTip = new ToolTip(); switchCommunicationsDeviceToolTip.SetToolTip(switchCommunicationDeviceCheckBox, SettingsStrings.communicationsDeviceTooltip); var notificationToolTip = new ToolTip(); notificationToolTip.SetToolTip(notificationComboBox, SettingsStrings.notificationTooltip); var notificationFactory = new NotificationFactory(); notificationFactory.ConfigureListControl(notificationComboBox); notificationComboBox.SelectedValue = AppModel.Instance.NotificationSettings; selectSoundFileDialog.Filter = SettingsStrings.audioFiles + @" (*.wav;*.mp3)|*.wav;*.mp3;*.aiff"; selectSoundFileDialog.FileOk += SelectSoundFileDialogOnFileOk; selectSoundFileDialog.CheckFileExists = true; selectSoundFileDialog.CheckPathExists = true; var soundSupported = notificationFactory.Get(AppModel.Instance.NotificationSettings).SupportCustomSound() != NotificationCustomSoundEnum.NotSupported; selectSoundButton.Visible = soundSupported; var removeCustomSoundToolTip = new ToolTip(); removeCustomSoundToolTip.SetToolTip(deleteSoundButton, SettingsStrings.disableCustomSoundTooltip); try { deleteSoundButton.Visible = soundSupported && AppModel.Instance.CustomNotificationSound != null; } catch (CachedSoundFileNotExistsException) { } var selectSoundButtonToolTip = new ToolTip(); selectSoundButtonToolTip.SetToolTip(selectSoundButton, SettingsStrings.selectSoundButtonTooltip); new TooltipInfoFactory().ConfigureListControl(tooltipInfoComboBox); tooltipInfoComboBox.SelectedValue = TooltipInfoManager.CurrentTooltipInfo; new DeviceCyclerFactory().ConfigureListControl(cycleThroughComboBox); cycleThroughComboBox.SelectedValue = DeviceCyclerManager.CurrentCycler; var cycleThroughToolTip = new ToolTip(); cycleThroughToolTip.SetToolTip(cycleThroughComboBox, SettingsStrings.cycleThroughTooltip); foregroundAppCheckbox.Checked = AppModel.Instance.SwitchForegroundProgram; usePrimaryScreenCheckbox.Checked = AppModel.Instance.NotifyUsingPrimaryScreen; usePrimaryScreenCheckbox.Visible = AppModel.Instance.NotificationSettings == NotificationTypeEnum.BannerNotification; var foregroundAppToolTip = new ToolTip(); foregroundAppToolTip.SetToolTip(foregroundAppCheckbox, SettingsStrings.foregroundAppTooltip); var usePrimaryScreenTooltip = new ToolTip(); usePrimaryScreenTooltip.SetToolTip(usePrimaryScreenCheckbox, SettingsStrings.usePrimaryScreenTooltip); // Settings - Update includeBetaVersionsCheckBox.Checked = AppModel.Instance.IncludeBetaVersions; switch (AppModel.Instance.UpdateMode) { case UpdateMode.Silent: updateSilentRadioButton.Checked = true; break; case UpdateMode.Notify: updateNotifyRadioButton.Checked = true; break; case UpdateMode.Never: updateNeverRadioButton.Checked = true; break; default: throw new ArgumentOutOfRangeException(); } var updateSilentToolTip = new ToolTip(); updateSilentToolTip.SetToolTip(updateSilentRadioButton, SettingsStrings.updateInstallAutomaticallyTooltip); var updateNotifyToolTip = new ToolTip(); updateNotifyToolTip.SetToolTip(updateNotifyRadioButton, SettingsStrings.updateNotifyTooltip); var updateNeverToolTip = new ToolTip(); updateNeverToolTip.SetToolTip(updateNeverRadioButton, SettingsStrings.updateNeverTooltip); var includeBetaVersionsToolTip = new ToolTip(); includeBetaVersionsToolTip.SetToolTip(includeBetaVersionsCheckBox, SettingsStrings.updateIncludeBetaVersionsTooltip); // Settings - Language new LanguageFactory().ConfigureListControl(languageComboBox); languageComboBox.SelectedValue = AppModel.Instance.Language; PopulateSettings(); _loaded = true; }
public SettingsForm() { // Form itself InitializeComponent(); Icon = Resources.SettingsIcon; Text = AssemblyUtils.GetReleaseState() == AssemblyUtils.ReleaseState.Beta ? $"{SettingsStrings.settings} {AssemblyUtils.GetReleaseState()}" : SettingsStrings.settings; LocalizeForm(); var closeToolTip = new ToolTip(); closeToolTip.SetToolTip(closeButton, SettingsStrings.closeTooltip); hotkeysTextBox.Text = AppConfigs.Configuration.PlaybackHotKeys.Display(); hotkeysTextBox.Tag = new Tuple <AudioDeviceType, HotKeys>(AudioDeviceType.Playback, AppConfigs.Configuration.PlaybackHotKeys); hotkeysTextBox.Enabled = hotkeysCheckBox.Checked = AppConfigs.Configuration.PlaybackHotKeys.Enabled; hotkeysTextBox.KeyDown += (sender, args) => SetHotkey(args); var hotkeysToolTip = new ToolTip(); hotkeysToolTip.SetToolTip(hotkeysCheckBox, SettingsStrings.hotkeysTooltip); // Settings - Basic startWithWindowsCheckBox.Checked = AppModel.Instance.RunAtStartup; keepSystemTrayIconCheckBox.Checked = AppConfigs.Configuration.KeepSystrayIcon; var keepSystemTrayIconToolTip = new ToolTip(); keepSystemTrayIconToolTip.SetToolTip(keepSystemTrayIconCheckBox, SettingsStrings.keepSystemTrayIconTooltip); // Settings - Audio switchCommunicationDeviceCheckBox.Checked = AppModel.Instance.SetCommunications; var switchCommunicationsDeviceToolTip = new ToolTip(); switchCommunicationsDeviceToolTip.SetToolTip(switchCommunicationDeviceCheckBox, SettingsStrings.communicationsDeviceTooltip); var notificationToolTip = new ToolTip(); notificationToolTip.SetToolTip(notificationComboBox, SettingsStrings.notificationTooltip); var notificationFactory = new NotificationFactory(); notificationFactory.ConfigureListControl(notificationComboBox); notificationComboBox.SelectedValue = AppModel.Instance.NotificationSettings; selectSoundFileDialog.Filter = SettingsStrings.audioFiles + @" (*.wav;*.mp3)|*.wav;*.mp3;*.aiff"; selectSoundFileDialog.FileOk += SelectSoundFileDialogOnFileOk; selectSoundFileDialog.CheckFileExists = true; selectSoundFileDialog.CheckPathExists = true; selectSoundButton.Visible = notificationFactory.Get(AppModel.Instance.NotificationSettings).SupportCustomSound() != NotificationCustomSoundEnum.NotSupported; var selectSoundButtonToolTip = new ToolTip(); selectSoundButtonToolTip.SetToolTip(selectSoundButton, SettingsStrings.selectSoundButtonTooltip); new TooltipInfoFactory().ConfigureListControl(tooltipInfoComboBox); tooltipInfoComboBox.SelectedValue = TooltipInfoManager.CurrentTooltipInfo; new DeviceCyclerFactory().ConfigureListControl(cycleThroughComboBox); cycleThroughComboBox.SelectedValue = DeviceCyclerManager.CurrentCycler; var cycleThroughToolTip = new ToolTip(); cycleThroughToolTip.SetToolTip(cycleThroughComboBox, SettingsStrings.cycleThroughTooltip); // Settings - Update includeBetaVersionsCheckBox.Checked = AppModel.Instance.IncludeBetaVersions; switch (AppModel.Instance.UpdateMode) { case UpdateMode.Silent: updateSilentRadioButton.Checked = true; break; case UpdateMode.Notify: updateNotifyRadioButton.Checked = true; break; case UpdateMode.Never: updateNeverRadioButton.Checked = true; break; default: throw new ArgumentOutOfRangeException(); } var updateSilentToolTip = new ToolTip(); updateSilentToolTip.SetToolTip(updateSilentRadioButton, SettingsStrings.updateInstallAutomaticallyTooltip); var updateNotifyToolTip = new ToolTip(); updateNotifyToolTip.SetToolTip(updateNotifyRadioButton, SettingsStrings.updateNotifyTooltip); var updateNeverToolTip = new ToolTip(); updateNeverToolTip.SetToolTip(updateNeverRadioButton, SettingsStrings.updateNeverTooltip); var includeBetaVersionsToolTip = new ToolTip(); includeBetaVersionsToolTip.SetToolTip(includeBetaVersionsCheckBox, SettingsStrings.updateIncludeBetaVersionsTooltip); // Settings - Language languageComboBox.SelectedIndex = (int)AppConfigs.Configuration.Language; // Playback and Recording var audioDeviceLister = new AudioDeviceLister(DeviceState.All); PopulateAudioList(playbackListView, AppModel.Instance.SelectedPlaybackDevicesList, audioDeviceLister.GetPlaybackDevices()); PopulateAudioList(recordingListView, AppModel.Instance.SelectedRecordingDevicesList, audioDeviceLister.GetRecordingDevices()); _loaded = true; }
internal static void GatherMods() { YamlFile <GuuMod>[] modFiles = YamlUtils.GetModFiles(); SortedSet <GuuMod> loadOrder = new SortedSet <GuuMod>(new ModComparer()); // Filter what is valid and invalid for load foreach (YamlFile <GuuMod> modFile in modFiles) { GuuMod mod = modFile.Read(); // Check for mod ID if (mod.ID == null || mod.ID.Equals(string.Empty)) { GuuCore.LOGGER?.LogWarning($"Missing 'modID' key on file '{modFile.Info.FullName}' or the value is blank. Skipping mod!"); continue; } // Check if it is not example mod if (mod.ID.Equals(EXAMPLE_MOD_ID)) { GuuCore.LOGGER?.LogWarning($"Found example mod ID on file '{modFile.Info.FullName}', please change the ID of the mod. Skipping mod!"); continue; } // Check for assembly to load if (mod.AssemblyName == null || mod.AssemblyName.Equals(string.Empty)) { GuuCore.LOGGER?.LogWarning($"Missing 'assembly' key on file {modFile.Info.FullName}' or the value is blank. Skipping mod!"); continue; } // Check for guu version to see if it can be loaded if (mod.GuuVersion != null && !mod.GuuVersion.Equals(string.Empty)) { if (!ValidateVersion(mod.GuuVersion, GuuCore.GUU_VERSION)) { GuuCore.LOGGER?.LogWarning($"Guu version is outdated. Requires at least '{mod.GuuVersion}' but has '{GuuCore.GUU_VERSION}'. Skipping mod!"); continue; } } mod.Info = modFile.Info; MODS.Add(mod.ID, null); loadOrder.Add(mod); } // Loads the mods and generates their mod information foreach (GuuMod mod in loadOrder) { string modid = mod.ID; string mainAssembly = mod.AssemblyName; string version = mod.Version ?? ASSEMBLY_VERSION_TAG; bool unsafeCheck = mod.IsUnsafe; HashSet <string> required = new HashSet <string>(mod.RequiredMods); EdenHarmony harmony = new EdenHarmony(modid); // Checks if all required mods are available foreach (string req in required) { if (!MODS.ContainsKey(req)) { throw new Exception($"Missing required mod '{req}' when loading '{modid}'"); } } // Checks and loads the main assembly FileInfo assembly = new FileInfo(Path.Combine(mod.Info.Directory.FullName, mainAssembly + GuuCore.DLL_EXTENSION)); if (!assembly.Exists) { throw new Exception($"Cannot load the main assembly '{mainAssembly}' for mod '{modid}'"); } Assembly modAssembly = AssemblyUtils.LoadWithSymbols(assembly.FullName); harmony.LatePatchAll(modAssembly, !unsafeCheck ? AllowedPatchType.ALL : SAFE_PATCH); // Checks if version as {assemblyVersion} tag, and replaces it if (version.Equals(ASSEMBLY_VERSION_TAG)) { mod.Version = modAssembly.GetRuntimeVersion(); } // Obtains the ModMain Type mainType = modAssembly.GetTypes().Single(t => t.IsSubclassOf(typeof(ModMain))); ModMain main = Activator.CreateInstance(mainType) as ModMain; main.Assembly = modAssembly; main.Mod = mod; main.Logger = new ModLogger(modid); main.HarmonyInst = harmony; MOD_CONTEXTS.Add(modAssembly, new ModContext(main.Mod, main)); // Finalizes the load process MODS[modid] = main; } // Loads all modules and registers them foreach (string modid in MODS.Keys) { ModMain main = MODS[modid]; List <IModLoad> moduleMains = new List <IModLoad> { main }; foreach (ModModuleAttribute module in main.GetType().GetCustomAttributes <ModModuleAttribute>()) { string name = module.moduleName; string depID = module.dependentID; string depVer = module.dependentVersion; // Checks if dependent is available, and if so if the version matches if (!MODS.ContainsKey(depID)) { continue; } if (!ValidateVersion(depVer, MODS[depID].Mod.Version)) { continue; } // Checks and loads the assembly FileInfo assembly = new FileInfo(Path.Combine(main.Mod.Info.Directory.FullName, name + GuuCore.DLL_EXTENSION)); if (!assembly.Exists) { throw new Exception($"Trying to load module '{name}' for mod '{modid}', but it wasn't found!"); } Assembly moduleAssembly = AssemblyUtils.LoadWithSymbols(assembly.FullName); main.HarmonyInst?.LatePatchAll(moduleAssembly, !main.Mod.IsUnsafe ? AllowedPatchType.ALL : SAFE_PATCH); // Obtains the ModuleMain Type mainType = moduleAssembly.GetTypes().Single(t => t.IsSubclassOf(typeof(ModuleMain))); ModuleMain moduleMain = Activator.CreateInstance(mainType) as ModuleMain; moduleMain.Assembly = moduleAssembly; moduleMain.Main = main; MOD_CONTEXTS.Add(moduleAssembly, MOD_CONTEXTS[main.Assembly]); // Finalizes the load process for this mod's modules moduleMains.Add(moduleMain); } // Finalizes the load process for all modules main.Mod.Modules = moduleMains.ToArray(); } // Executes all late patches foreach (ModMain main in MODS.Values) { main.HarmonyInst?.ExecuteLatePatches(); } // Initializes the mods Init(); // Preloads the mods PreLoad(); // Triggers registration for all mods Register(); }
internal static object StringToType( Type type, string strType, EmptyCtorDelegate ctorFn, Dictionary <string, TypeAccessor> typeAccessorMap) { var index = 0; if (strType == null) { return(null); } //if (!Serializer.EatMapStartChar(strType, ref index)) for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (strType[index++] != JsWriter.MapStartChar) { throw DeserializeTypeRef.CreateSerializationError(type, strType); } if (JsonTypeSerializer.IsEmptyMap(strType, index)) { return(ctorFn()); } object instance = null; var strTypeLength = strType.Length; while (index < strTypeLength) { var propertyName = JsonTypeSerializer.ParseJsonString(strType, ref index); //Serializer.EatMapKeySeperator(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (strType.Length != index) { index++; } var propertyValueStr = Serializer.EatValue(strType, ref index); var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1; //if we already have an instance don't check type info, because then we will have a half deserialized object //we could throw here or just use the existing instance. if (instance == null && possibleTypeInfo && propertyName == JsWriter.TypeAttr) { var explicitTypeName = Serializer.ParseString(propertyValueStr); var explicitType = AssemblyUtils.FindType(explicitTypeName); if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract()) { instance = explicitType.CreateInstance(); } if (instance == null) { Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr); } else { //If __type info doesn't match, ignore it. if (!type.InstanceOfType(instance)) { instance = null; } else { var derivedType = instance.GetType(); if (derivedType != type) { var derivedTypeConfig = new TypeConfig(derivedType); var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer); if (map != null) { typeAccessorMap = map; } } } } Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); continue; } if (instance == null) { instance = ctorFn(); } var typeAccessor = PropertyNameResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap); var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null; if (propType != null) { try { if (typeAccessor != null) { //var parseFn = Serializer.GetParseFn(propType); var parseFn = JsonReader.GetParseFn(propType); var propertyValue = parseFn(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) { for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline } } continue; } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) { throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e); } else { Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr); } } } if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null) { try { var propertyValue = typeAccessor.GetProperty(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) { throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, typeAccessor.PropertyType, e); } else { Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr); } } } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) { for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline } } } return(instance); }
public void Can_connect_to_Buffered_SslStream() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = -1, ReceiveTimeout = -1, }; socket.Connect(Host, Port); if (!socket.Connected) { socket.Close(); throw new Exception("Could not connect"); } Stream networkStream = new NetworkStream(socket); SslStream sslStream; if (Env.IsMono) { //Mono doesn't support EncryptionPolicy sslStream = new SslStream(networkStream, leaveInnerStreamOpen: false, userCertificateValidationCallback: RedisConfig.CertificateValidationCallback, userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback); } else { var ctor = typeof(SslStream).GetConstructors() .First(x => x.GetParameters().Length == 5); var policyType = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy"); var policyValue = Enum.Parse(policyType, "RequireEncryption"); sslStream = (SslStream)ctor.Invoke(new[] { networkStream, false, RedisConfig.CertificateValidationCallback, RedisConfig.CertificateSelectionCallback, policyValue, }); //sslStream = new SslStream(networkStream, // leaveInnerStreamOpen: false, // userCertificateValidationCallback: null, // userCertificateSelectionCallback: null, // encryptionPolicy: EncryptionPolicy.RequireEncryption); } #if NETCORE sslStream.AuthenticateAsClientAsync(Host).Wait(); #else sslStream.AuthenticateAsClient(Host); #endif if (!sslStream.IsEncrypted) { throw new Exception("Could not establish an encrypted connection to " + Host); } var bstream = new BufferedStream(sslStream, 16 * 1024); SendAuth(bstream); }
protected void ResolveAdditionalOutput() { ResolveAdditionalOutput(AssemblyUtils.GetCachedReflectionAssembly(GetFullPath(TargetPath))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { var builder = _servicesManager.InitContainer(); services.AddSingleton(typeof(ILogger <>), typeof(LoggerEx <>)); services.AddAutoMapper(AssemblyUtils.GetAppAssemblies()); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddWebSocketManager(); // if (_neonConfig.EnableMetrics) // services.AddMetrics(); services.AddHttpClient(); var key = Encoding.ASCII.GetBytes(Configuration.Get <NeonConfig>().JwtToken); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); services.AddDbContextPool <NeonDbContext>(options => { //var config = Configuration.Get<NeonConfig>(); var dbFullPath = $"Data Source={_neonConfig.FileSystem.RootDirectory}{_neonConfig.DatabaseDirectory}{Path.DirectorySeparatorChar}{_neonConfig.Database.ConnectionString}"; options.UseSqlite(dbFullPath); }); services.AddTransient <DbContext, NeonDbContext>(); services.AddResponseCompression(); if (_neonConfig.EnableSwagger) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Leon Home control", Version = "v1.0" }); }); } builder.Populate(services); _container = _servicesManager.Build(); var cont = new AutofacServiceProvider(_container); return(cont); }
/// <summary>String to type.</summary> /// <exception cref="CreateSerializationError"> Thrown when a create serialization error error /// condition occurs.</exception> /// <exception cref="GetSerializationException">Thrown when a Get Serialization error condition /// occurs.</exception> /// <param name="type"> The type.</param> /// <param name="strType"> The type.</param> /// <param name="ctorFn"> The constructor function.</param> /// <param name="typeAccessorMap">The type accessor map.</param> /// <returns>An object.</returns> internal static object StringToType( Type type, string strType, EmptyCtorDelegate ctorFn, Dictionary <string, TypeAccessor> typeAccessorMap) { var index = 0; if (strType == null) { return(null); } //if (!Serializer.EatMapStartChar(strType, ref index)) if (strType[index++] != JsWriter.MapStartChar) { throw DeserializeTypeRef.CreateSerializationError(type, strType); } if (JsonTypeSerializer.IsEmptyMap(strType)) { return(ctorFn()); } object instance = null; var strTypeLength = strType.Length; while (index < strTypeLength) { var propertyName = Serializer.EatMapKey(strType, ref index); //Serializer.EatMapKeySeperator(strType, ref index); index++; var propertyValueStr = Serializer.EatValue(strType, ref index); var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1; if (possibleTypeInfo && propertyName == JsWriter.TypeAttr) { var explicitTypeName = Serializer.ParseString(propertyValueStr); var explicitType = AssemblyUtils.FindType(explicitTypeName); if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract()) { instance = explicitType.CreateInstance(); } if (instance == null) { Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr); } else { //If __type info doesn't match, ignore it. if (!type.InstanceOfType(instance)) { instance = null; } else { var derivedType = instance.GetType(); if (derivedType != type) { var derivedTypeConfig = new TypeConfig(derivedType); var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer); if (map != null) { typeAccessorMap = map; } } } } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); if (index != strType.Length) { index++; } continue; } if (instance == null) { instance = ctorFn(); } TypeAccessor typeAccessor; typeAccessorMap.TryGetValue(propertyName, out typeAccessor); var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null; if (propType != null) { try { if (typeAccessor != null) { var parseFn = Serializer.GetParseFn(propType); var propertyValue = parseFn(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); if (index != strType.Length) { index++; } continue; } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) { throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e); } else { Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr); } } } if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null) { try { var propertyValue = typeAccessor.GetProperty(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) { throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e); } else { Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr); } } } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); if (index != strType.Length) { index++; } } return(instance); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); #if WIN32 if (Environment.Is64BitOperatingSystem) { var resourceName = "SmartSystemMenu.SmartSystemMenu64.exe"; var fileName = "SmartSystemMenu64.exe"; var directoryName = Path.GetDirectoryName(AssemblyUtils.AssemblyLocation); var filePath = Path.Combine(directoryName, fileName); try { if (!File.Exists(filePath)) { AssemblyUtils.ExtractFileFromAssembly(resourceName, filePath); } _64BitProcess = Process.Start(filePath); } catch { string message = string.Format("Failed to load {0} process!", fileName); MessageBox.Show(message, AssemblyUtils.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } } if (_settings.ShowSystemTrayIcon) { _systemTrayMenu = new SystemTrayMenu(_settings.Language); _systemTrayMenu.MenuItemAutoStartClick += MenuItemAutoStartClick; _systemTrayMenu.MenuItemSettingsClick += MenuItemSettingsClick; _systemTrayMenu.MenuItemAboutClick += MenuItemAboutClick; _systemTrayMenu.MenuItemExitClick += MenuItemExitClick; _systemTrayMenu.Create(); _systemTrayMenu.CheckMenuItemAutoStart(AutoStarter.IsAutoStartByRegisterEnabled(AssemblyUtils.AssemblyProductName, AssemblyUtils.AssemblyLocation)); } var moduleName = Process.GetCurrentProcess().MainModule.ModuleName; _hotKeyHook = new HotKeyHook(); _hotKeyHook.Hooked += HotKeyHooked; if (_settings.MenuItems.Items.Flatten(x => x.Items).Any(x => x.Type == MenuItemType.Item && x.Key3 != VirtualKey.None && x.Show) || _settings.MenuItems.WindowSizeItems.Any(x => x.Key3 != VirtualKey.None)) { _hotKeyHook.Start(moduleName, _settings.MenuItems); } _hotKeyMouseHook = new HotKeys.MouseHook(); _hotKeyMouseHook.Hooked += HotKeyMouseHooked; if (_settings.Closer.MouseButton != MouseButton.None) { _hotKeyMouseHook.Start(moduleName, _settings.Closer.Key1, _settings.Closer.Key2, _settings.Closer.MouseButton); } #endif _windows = EnumWindows.EnumAllWindows(_settings, _windowSettings, new string[] { SHELL_WINDOW_NAME }).ToList(); foreach (var window in _windows) { var processPath = window.Process?.GetMainModuleFileName() ?? string.Empty; var fileName = Path.GetFileName(processPath); if (!string.IsNullOrEmpty(fileName) && _settings.ProcessExclusions.Contains(fileName.ToLower())) { continue; } var isAdded = window.Menu.Create(); if (isAdded) { window.Menu.CheckMenuItem(window.ProcessPriority.GetMenuItemId(), true); if (window.AlwaysOnTop) { window.Menu.CheckMenuItem(MenuItemId.SC_TOPMOST, true); } if (window.IsExToolWindow) { window.Menu.CheckMenuItem(MenuItemId.SC_HIDE_FOR_ALT_TAB, true); } var windowClassName = window.GetClassName(); var states = _windowSettings.Find(windowClassName, processPath); if (states.Any()) { window.ApplyState(states[0], _settings.SaveSelectedItems, _settings.MenuItems.WindowSizeItems); window.Menu.CheckMenuItem(MenuItemId.SC_SAVE_SELECTED_ITEMS, true); } } } _callWndProcHook = new CallWndProcHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _callWndProcHook.CallWndProc += WindowProc; _callWndProcHook.Start(); _getMsgHook = new GetMsgHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _getMsgHook.GetMsg += WindowGetMsg; _getMsgHook.Start(); _shellHook = new ShellHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _shellHook.WindowCreated += WindowCreated; _shellHook.WindowDestroyed += WindowDestroyed; _shellHook.Start(); _cbtHook = new CBTHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _cbtHook.WindowCreated += WindowCreated; _cbtHook.WindowDestroyed += WindowDestroyed; _cbtHook.MoveSize += WindowMoveSize; _cbtHook.MinMax += WindowMinMax; _cbtHook.Start(); _mouseHook = new Hooks.MouseHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); var dragByMouseItemName = MenuItemId.GetName(MenuItemId.SC_DRAG_BY_MOUSE); if (_settings.MenuItems.Items.Flatten(x => x.Items).Any(x => x.Type == MenuItemType.Item && x.Name == dragByMouseItemName && x.Show)) { _mouseHook.Start(); } Hide(); }
public void CreateAssemblyTest() { Assert.IsNotNull(AssemblyUtils.CreateAssembly("LeonReader.Common.dll")); Assert.ThrowsException <System.IO.FileNotFoundException>(() => AssemblyUtils.CreateAssembly("LeonReader.xxx.dll")); }
public bool Initialize() { Debug.LogError(string.Format("Scripting define symbol \"{0}\" not set for {1}.", AssemblyUtils.GetProviderCompilerFlag(this), this.GetType().Name)); return(false); }
private void RunEndpoint(ILogger logger) { AppDomain appDomain = null; try { appDomain = AppDomainUtils.CreateAppDomain(@"Host", Arguments.ApplicationBaseDirectory, Arguments.ConfigurationFile, Arguments.ShadowCopy); Type endpointType = typeof(HostEndpoint); using (HostEndpoint endpoint = (HostEndpoint)appDomain.CreateInstanceFromAndUnwrap( AssemblyUtils.GetAssemblyLocalPath(endpointType.Assembly), endpointType.FullName)) { foreach (string hintDirectory in Arguments.HintDirectories) { endpoint.AddHintDirectory(hintDirectory); } if (Arguments.OwnerProcessId >= 0) { if (!endpoint.SetOwnerProcess(Arguments.OwnerProcessId)) { logger.Log(LogSeverity.Warning, String.Format("The owner process with PID {0} does not appear to be running!", Arguments.OwnerProcessId)); return; } } if (Arguments.IpcPortName != null) { logger.Log(LogSeverity.Debug, String.Format("Listening for connections on IPC port: '{0}'", Arguments.IpcPortName)); endpoint.InitializeIpcChannel(Arguments.IpcPortName); } else { logger.Log(LogSeverity.Debug, String.Format("Listening for connections on TCP port: '{0}'", Arguments.TcpPortNumber)); endpoint.InitializeTcpChannel(Arguments.TcpPortNumber); } TimeSpan?watchdogTimeout = Arguments.TimeoutSeconds <= 0 ? (TimeSpan?)null : TimeSpan.FromSeconds(Arguments.TimeoutSeconds); HostTerminationReason reason = endpoint.Run(watchdogTimeout); switch (reason) { case HostTerminationReason.WatchdogTimeout: logger.Log(LogSeverity.Warning, "Watchdog timer expired!"); break; case HostTerminationReason.Disowned: logger.Log(LogSeverity.Warning, "Owner process terminated abruptly!"); break; case HostTerminationReason.Disposed: break; } } } finally { // For some reason this is throwing CannotUnloadAppDomainException on Mono 1.9.1. // After that happens, the process refuses to shut down normally. // -- Jeff. if (appDomain != null) { AppDomain.Unload(appDomain); } } }
public static int Main(string[] Arguments) { // Ensure UTF8Output flag is respected, since we are initializing logging early in the program. if (CommandUtils.ParseParam(Arguments, "-Utf8output")) { Console.OutputEncoding = new System.Text.UTF8Encoding(false, false); } // Parse the log level argument if (CommandUtils.ParseParam(Arguments, "-Verbose")) { Log.OutputLevel = LogEventType.Verbose; } if (CommandUtils.ParseParam(Arguments, "-VeryVerbose")) { Log.OutputLevel = LogEventType.VeryVerbose; } // Initialize the log system, buffering the output until we can create the log file StartupTraceListener StartupListener = new StartupTraceListener(); Trace.Listeners.Add(StartupListener); // Configure log timestamps Log.IncludeTimestamps = CommandUtils.ParseParam(Arguments, "-Timestamps"); // Enter the main program section ExitCode ReturnCode = ExitCode.Success; try { // Set the working directory to the UE4 root Environment.CurrentDirectory = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetOriginalLocation()), "..", "..", "..")); // Ensure we can resolve any external assemblies as necessary. string PathToBinariesDotNET = Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation()); AssemblyUtils.InstallAssemblyResolver(PathToBinariesDotNET); AssemblyUtils.InstallRecursiveAssemblyResolver(PathToBinariesDotNET); // Initialize the host platform layer HostPlatform.Initialize(); // Log the operating environment. Since we usually compile to AnyCPU, we may be executed using different system paths under WOW64. Log.TraceVerbose("{2}: Running on {0} as a {1}-bit process.", HostPlatform.Current.GetType().Name, Environment.Is64BitProcess ? 64 : 32, DateTime.UtcNow.ToString("o")); // Log if we're running from the launcher string ExecutingAssemblyLocation = Assembly.GetExecutingAssembly().Location; if (string.Compare(ExecutingAssemblyLocation, Assembly.GetEntryAssembly().GetOriginalLocation(), StringComparison.OrdinalIgnoreCase) != 0) { Log.TraceVerbose("Executed from AutomationToolLauncher ({0})", ExecutingAssemblyLocation); } Log.TraceVerbose("CWD={0}", Environment.CurrentDirectory); // Hook up exit callbacks AppDomain Domain = AppDomain.CurrentDomain; Domain.ProcessExit += Domain_ProcessExit; Domain.DomainUnload += Domain_ProcessExit; HostPlatform.Current.SetConsoleCtrlHandler(CtrlHandlerDelegateInstance); // Log the application version FileVersionInfo Version = AssemblyUtils.ExecutableVersion; Log.TraceVerbose("{0} ver. {1}", Version.ProductName, Version.ProductVersion); // Don't allow simultaneous execution of AT (in the same branch) ReturnCode = InternalUtils.RunSingleInstance(() => MainProc(Arguments, StartupListener)); } catch (AutomationException Ex) { // Output the message in the desired format if (Ex.OutputFormat == AutomationExceptionOutputFormat.Silent) { Log.TraceLog("{0}", ExceptionUtils.FormatExceptionDetails(Ex)); } else if (Ex.OutputFormat == AutomationExceptionOutputFormat.Minimal) { Log.TraceInformation("{0}", Ex.ToString().Replace("\n", "\n ")); Log.TraceLog("{0}", ExceptionUtils.FormatExceptionDetails(Ex)); } else { Log.WriteException(Ex, LogUtils.FinalLogFileName); } // Take the exit code from the exception ReturnCode = Ex.ErrorCode; } catch (Exception Ex) { // Use a default exit code Log.WriteException(Ex, LogUtils.FinalLogFileName); ReturnCode = ExitCode.Error_Unknown; } finally { // In all cases, do necessary shut down stuff, but don't let any additional exceptions leak out while trying to shut down. // Make sure there's no directories on the stack. NoThrow(() => CommandUtils.ClearDirStack(), "Clear Dir Stack"); // Try to kill process before app domain exits to leave the other KillAll call to extreme edge cases NoThrow(() => { if (ShouldKillProcesses && !Utils.IsRunningOnMono) { ProcessManager.KillAll(); } }, "Kill All Processes"); // Write the exit code Log.TraceInformation("AutomationTool exiting with ExitCode={0} ({1})", (int)ReturnCode, ReturnCode); // Can't use NoThrow here because the code logs exceptions. We're shutting down logging! Trace.Close(); } return((int)ReturnCode); }
/// <summary> /// Main entry point. Parses any global options and initializes the logging system, then invokes the appropriate command. /// </summary> /// <param name="ArgumentsArray">Command line arguments</param> /// <returns>Zero on success, non-zero on error</returns> private static int Main(string[] ArgumentsArray) { SingleInstanceMutex Mutex = null; try { // Start capturing performance info Timeline.Start(); // Parse the command line arguments CommandLineArguments Arguments = new CommandLineArguments(ArgumentsArray); // Parse the global options GlobalOptions Options = new GlobalOptions(Arguments); // Configure the log system Log.OutputLevel = Options.LogOutputLevel; Log.IncludeTimestamps = Options.bLogTimestamps; Log.IncludeProgramNameWithSeverityPrefix = Options.bLogFromMsBuild; // Configure the progress writer ProgressWriter.bWriteMarkup = Options.bWriteProgressMarkup; // Add the log writer if requested. When building a target, we'll create the writer for the default log file later. if (Options.LogFileName != null) { Log.AddFileWriter("LogTraceListener", Options.LogFileName); } // Ensure we can resolve any external assemblies that are not in the same folder as our assembly. AssemblyUtils.InstallAssemblyResolver(Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation())); // Change the working directory to be the Engine/Source folder. We are likely running from Engine/Binaries/DotNET // This is critical to be done early so any code that relies on the current directory being Engine/Source will work. DirectoryReference.SetCurrentDirectory(UnrealBuildTool.EngineSourceDirectory); // Get the type of the mode to execute, using a fast-path for the build mode. Type ModeType = typeof(BuildMode); if (Options.Mode != null) { // Find all the valid modes Dictionary <string, Type> ModeNameToType = new Dictionary <string, Type>(StringComparer.OrdinalIgnoreCase); foreach (Type Type in Assembly.GetExecutingAssembly().GetTypes()) { if (Type.IsClass && !Type.IsAbstract && Type.IsSubclassOf(typeof(ToolMode))) { ToolModeAttribute Attribute = Type.GetCustomAttribute <ToolModeAttribute>(); if (Attribute == null) { throw new BuildException("Class '{0}' should have a ToolModeAttribute", Type.Name); } ModeNameToType.Add(Attribute.Name, Type); } } // Try to get the correct mode if (!ModeNameToType.TryGetValue(Options.Mode, out ModeType)) { Log.TraceError("No mode named '{0}'. Available modes are:\n {1}", Options.Mode, String.Join("\n ", ModeNameToType.Keys)); return(1); } } // Get the options for which systems have to be initialized for this mode ToolModeOptions ModeOptions = ModeType.GetCustomAttribute <ToolModeAttribute>().Options; // Start prefetching the contents of the engine folder if ((ModeOptions & ToolModeOptions.StartPrefetchingEngine) != 0) { using (Timeline.ScopeEvent("FileMetadataPrefetch.QueueEngineDirectory()")) { FileMetadataPrefetch.QueueEngineDirectory(); } } // Read the XML configuration files if ((ModeOptions & ToolModeOptions.XmlConfig) != 0) { using (Timeline.ScopeEvent("XmlConfig.ReadConfigFiles()")) { string XmlConfigMutexName = SingleInstanceMutex.GetUniqueMutexForPath("UnrealBuildTool_Mutex_XmlConfig", Assembly.GetExecutingAssembly().CodeBase); using (SingleInstanceMutex XmlConfigMutex = new SingleInstanceMutex(XmlConfigMutexName, true)) { FileReference XmlConfigCache = Arguments.GetFileReferenceOrDefault("-XmlConfigCache=", null); XmlConfig.ReadConfigFiles(XmlConfigCache); } } } // Acquire a lock for this branch if ((ModeOptions & ToolModeOptions.SingleInstance) != 0 && !Options.bNoMutex) { using (Timeline.ScopeEvent("SingleInstanceMutex.Acquire()")) { string MutexName = SingleInstanceMutex.GetUniqueMutexForPath("UnrealBuildTool_Mutex", Assembly.GetExecutingAssembly().CodeBase); Mutex = new SingleInstanceMutex(MutexName, Options.bWaitMutex); } } // Register all the build platforms if ((ModeOptions & ToolModeOptions.BuildPlatforms) != 0) { using (Timeline.ScopeEvent("UEBuildPlatform.RegisterPlatforms()")) { UEBuildPlatform.RegisterPlatforms(false); } } if ((ModeOptions & ToolModeOptions.BuildPlatformsForValidation) != 0) { using (Timeline.ScopeEvent("UEBuildPlatform.RegisterPlatforms()")) { UEBuildPlatform.RegisterPlatforms(true); } } // Create the appropriate handler ToolMode Mode = (ToolMode)Activator.CreateInstance(ModeType); // Execute the mode int Result = Mode.Execute(Arguments); if ((ModeOptions & ToolModeOptions.ShowExecutionTime) != 0) { Log.TraceInformation("Total execution time: {0:0.00} seconds", Timeline.Elapsed.TotalSeconds); } return(Result); } catch (CompilationResultException Ex) { // Used to return a propagate a specific exit code after an error has occurred. Does not log any message. Log.TraceLog(ExceptionUtils.FormatExceptionDetails(Ex)); return((int)Ex.Result); } catch (BuildException Ex) { // BuildExceptions should have nicely formatted messages. We can log these directly. Log.TraceError(Ex.Message.ToString()); Log.TraceLog(ExceptionUtils.FormatExceptionDetails(Ex)); return((int)CompilationResult.OtherCompilationError); } catch (Exception Ex) { // Unhandled exception. Log.TraceError("Unhandled exception: {0}", Ex); Log.TraceLog(ExceptionUtils.FormatExceptionDetails(Ex)); return((int)CompilationResult.OtherCompilationError); } finally { // Cancel the prefetcher using (Timeline.ScopeEvent("FileMetadataPrefetch.Stop()")) { FileMetadataPrefetch.Stop(); } // Print out all the performance info Timeline.Print(TimeSpan.FromMilliseconds(20.0), LogEventType.Log); // Make sure we flush the logs however we exit Trace.Close(); // Dispose of the mutex. Must be done last to ensure that another process does not startup and start trying to write to the same log file. if (Mutex != null) { Mutex.Dispose(); } } }
internal static string GetWASSufix() { return($"WAS/{AssemblyUtils.GetVersion()}"); }
private async Task SendVersion(ChatId chat) { await _telegramBotClient.SendTextMessageAsync(chat, $"Neon v{AssemblyUtils.GetVersion()}"); }
private static void ShowVersion() { Console.Error.WriteLine("{0} v{1} - compiled {2}", AssemblyUtils.GetAssemblyName(), AssemblyUtils.GetAssemblyVersion(), AssemblyUtils.GetLinkerTimestamp()); }
private void SetExePath() { var exeDir = AssemblyUtils.GetInstallDir(GetType()); ExePath = Path.Combine(exeDir, MkvPropEditFileName); }
public void GeneratesNCoverCoverageWithCorrectOptionsAndMergesIfNecessary(string factoryName, NCoverVersion version, string ncoverCoverageFile, bool includeLogArgument, bool runMultipleAssemblies) { string tempPath = SpecialPathPolicy.For <NCoverTestIsolationProviderIntegrationTest>().GetTempDirectory().FullName; string coverageFilePath = Path.Combine(tempPath, ncoverCoverageFile ?? "Coverage.xml"); string coverageLogFilePath = Path.Combine(tempPath, "CoverageLog.txt"); string ncoverArguments = includeLogArgument ? "//l \"" + coverageLogFilePath + "\"" + (version == NCoverVersion.V1 ? "" : " //ll Normal") : null; if (File.Exists(coverageFilePath)) { File.Delete(coverageFilePath); } if (File.Exists(coverageLogFilePath)) { File.Delete(coverageLogFilePath); } Type firstTestType = typeof(SimpleTest); Type secondTestType = typeof(DummyTest); TestLauncher launcher = new TestLauncher(); launcher.Logger = new MarkupStreamLogger(TestLog.Default); launcher.TestProject.TestPackage.AddFile(new FileInfo(AssemblyUtils.GetAssemblyLocalPath(firstTestType.Assembly))); if (runMultipleAssemblies) { launcher.TestProject.TestPackage.AddFile(new FileInfo(AssemblyUtils.GetAssemblyLocalPath(secondTestType.Assembly))); } launcher.TestProject.TestRunnerFactoryName = factoryName; launcher.TestExecutionOptions.FilterSet = new FilterSet <ITestDescriptor>( new OrFilter <ITestDescriptor>(new[] { new TypeFilter <ITestDescriptor>(new EqualityFilter <string>(firstTestType.FullName), false), new TypeFilter <ITestDescriptor>(new EqualityFilter <string>(secondTestType.FullName), false), })); if (ncoverArguments != null) { launcher.TestRunnerOptions.AddProperty("NCoverArguments", ncoverArguments); } if (ncoverCoverageFile != null) { launcher.TestRunnerOptions.AddProperty("NCoverCoverageFile", ncoverCoverageFile); } TestLauncherResult result; using (new CurrentDirectorySwitcher(tempPath)) result = launcher.Run(); NCoverTool tool = NCoverTool.GetInstance(version, ProcessorArchitecture.MSIL); if (!tool.IsInstalled()) { Assert.AreEqual(ResultCode.Failure, result.ResultCode); var logEntries = result.Report.LogEntries; Assert.AreEqual(1, logEntries.Count, "Expected to find a log entry."); Assert.AreEqual(LogSeverity.Error, logEntries[0].Severity); Assert.Contains(logEntries[0].Details, tool.Name + " does not appear to be installed."); } else { int passed = runMultipleAssemblies ? 2 : 1; int failed = 1; Assert.AreEqual(passed + failed, result.Statistics.RunCount); Assert.AreEqual(passed, result.Statistics.PassedCount); Assert.AreEqual(failed, result.Statistics.FailedCount); Assert.AreEqual(0, result.Statistics.InconclusiveCount); Assert.AreEqual(0, result.Statistics.SkippedCount); Assert.IsTrue(File.Exists(coverageFilePath), "The NCover runner should have written its coverage log to '{0}'.", coverageFilePath); string coverageXml = File.ReadAllText(coverageFilePath); File.Delete(coverageFilePath); Assert.Contains(coverageXml, firstTestType.Name, "Expected the coverage log to include information about the test method that we actually ran.\n" + "In NCover v3, there is now a list of excluded 'system assemblies' in NCover.Console.exe.config which " + "specifies MbUnit and Gallio by default. For this test to run, the file must be edited such that " + "these entries are removed."); if (runMultipleAssemblies) { Assert.Contains(coverageXml, secondTestType.Name, "Expected the coverage log to include information about the test method that we actually ran.\n" + "In NCover v3, there is now a list of excluded 'system assemblies' in NCover.Console.exe.config which " + "specifies MbUnit and Gallio by default. For this test to run, the file must be edited such that " + "these entries are removed."); } if (ncoverArguments != null && ncoverArguments.Contains("/l")) { Assert.IsTrue(File.Exists(coverageLogFilePath), "Should have created a coverage log file since the /l argument was specified."); File.Delete(coverageLogFilePath); } } }
/// <summary> /// Returns Type from type name syntax of .NET's typeof() /// </summary> public Type @typeof(string typeName) { var key = "type:" + typeName; Type cookGenericType(Type type, List <string> genericArgs) { if (type.IsGenericType) { var isGenericDefinition = genericArgs != null && genericArgs.All(x => x == ""); if (!isGenericDefinition) { var genericTypes = typeGenericTypes(genericArgs); var cookedType = type.MakeGenericType(genericTypes); return(cookedType); } } return(type); } var resolvedType = (Type)Context.Cache.GetOrAdd(key, k => { var isGeneric = typeName.IndexOf('<') >= 0; List <string> genericArgs = null; if (isGeneric) { genericArgs = typeGenericArgs(typeName); typeName = typeName.LeftPart('<') + '`' + Math.Max(genericArgs.Count, 1); } if (typeName.IndexOf('.') >= 0) { if (Context.ScriptTypeQualifiedNameMap.TryGetValue(typeName, out var type)) { return(cookGenericType(type, genericArgs)); } if (Context.AllowScriptingOfAllTypes) { type = AssemblyUtils.FindType(typeName); if (type != null) { return(cookGenericType(type, genericArgs)); } } } else { switch (typeName) { case "bool": return(typeof(bool)); case "byte": return(typeof(byte)); case "sbyte": return(typeof(sbyte)); case "char": return(typeof(char)); case "decimal": return(typeof(decimal)); case "double": return(typeof(double)); case "float": return(typeof(float)); case "int": return(typeof(int)); case "uint": return(typeof(uint)); case "long": return(typeof(long)); case "ulong": return(typeof(ulong)); case "object": return(typeof(object)); case "short": return(typeof(short)); case "ushort": return(typeof(ushort)); case "string": return(typeof(string)); } if (Context.ScriptTypeNameMap.TryGetValue(typeName, out var type)) { return(cookGenericType(type, genericArgs)); } } foreach (var ns in Context.ScriptNamespaces) { var lookupType = ns + "." + typeName; if (Context.ScriptTypeQualifiedNameMap.TryGetValue(lookupType, out var type)) { return(cookGenericType(type, genericArgs)); } if (Context.AllowScriptingOfAllTypes) { type = AssemblyUtils.FindType(lookupType); if (type != null) { return(cookGenericType(type, genericArgs)); } } } return(null); }); return(resolvedType); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); var settingsFileName = Path.Combine(AssemblyUtils.AssemblyDirectory, "SmartSystemMenu.xml"); var languageFileName = Path.Combine(AssemblyUtils.AssemblyDirectory, "Language.xml"); if (File.Exists(settingsFileName) && File.Exists(languageFileName)) { _settings = SmartSystemMenuSettings.Read(settingsFileName, languageFileName); } #if WIN32 if (Environment.Is64BitOperatingSystem) { string resourceName = "SmartSystemMenu.SmartSystemMenu64.exe"; string fileName = "SmartSystemMenu64.exe"; string directoryName = Path.GetDirectoryName(AssemblyUtils.AssemblyLocation); string filePath = Path.Combine(directoryName, fileName); try { if (!File.Exists(filePath)) { AssemblyUtils.ExtractFileFromAssembly(resourceName, filePath); } _64BitProcess = Process.Start(filePath); } catch { string message = string.Format("Failed to load {0} process!", fileName); MessageBox.Show(message, AssemblyUtils.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } } _systemTrayMenu = new SystemTrayMenu(_settings.ShowSystemTrayIcon, _settings.LanguageSettings); _systemTrayMenu.MenuItemAutoStart.Click += MenuItemAutoStartClick; _systemTrayMenu.MenuItemSettings.Click += MenuItemSettingsClick; _systemTrayMenu.MenuItemAbout.Click += MenuItemAboutClick; _systemTrayMenu.MenuItemExit.Click += MenuItemExitClick; _systemTrayMenu.MenuItemAutoStart.Checked = AutoStarter.IsAutoStartByRegisterEnabled(AssemblyUtils.AssemblyProductName, AssemblyUtils.AssemblyLocation); _hotKeyHook = new HotKeyHook(); _hotKeyHook.Hooked += HotKeyHooked; _hotKeyHook.Start(Process.GetCurrentProcess().MainModule.ModuleName, _settings.MenuItems.Items); #endif _windows = EnumWindows.EnumAllWindows(_settings.MenuItems, _settings.LanguageSettings, new string[] { SHELL_WINDOW_NAME }).ToList(); foreach (var window in _windows) { var processName = ""; try { processName = Path.GetFileName(window.Process.GetMainModuleFileName()); } catch { } if (string.IsNullOrEmpty(processName) || _settings.ProcessExclusions.Contains(processName.ToLower())) { continue; } window.Menu.Create(); int menuItemId = window.ProcessPriority.GetMenuItemId(); window.Menu.CheckMenuItem(menuItemId, true); if (window.AlwaysOnTop) { window.Menu.CheckMenuItem(MenuItemId.SC_TOPMOST, true); } } _getMsgHook = new GetMsgHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _getMsgHook.GetMsg += WindowGetMsg; _getMsgHook.Start(); _shellHook = new ShellHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _shellHook.WindowCreated += WindowCreated; _shellHook.WindowDestroyed += WindowDestroyed; _shellHook.Start(); _cbtHook = new CBTHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _cbtHook.WindowCreated += WindowCreated; _cbtHook.WindowDestroyed += WindowDestroyed; _cbtHook.MoveSize += WindowMoveSize; _cbtHook.MinMax += WindowMinMax; _cbtHook.Start(); _mouseHook = new MouseHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE); _mouseHook.Start(); Hide(); }
public static int Main() { var CommandLine = SharedUtils.ParseCommandLine(); LogUtils.InitLogging(CommandLine); ExitCode ReturnCode = ExitCode.Success; try { // ensure we can resolve any external assemblies as necessary. AssemblyUtils.InstallAssemblyResolver(Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation())); HostPlatform.Initialize(); Log.TraceVerbose("{2}: Running on {0} as a {1}-bit process.", HostPlatform.Current.GetType().Name, Environment.Is64BitProcess ? 64 : 32, DateTime.UtcNow.ToString("o")); XmlConfigLoader.Init(); // Log if we're running from the launcher var ExecutingAssemblyLocation = Assembly.GetExecutingAssembly().Location; if (string.Compare(ExecutingAssemblyLocation, Assembly.GetEntryAssembly().GetOriginalLocation(), StringComparison.OrdinalIgnoreCase) != 0) { Log.TraceVerbose("Executed from AutomationToolLauncher ({0})", ExecutingAssemblyLocation); } Log.TraceVerbose("CWD={0}", Environment.CurrentDirectory); // Hook up exit callbacks var Domain = AppDomain.CurrentDomain; Domain.ProcessExit += Domain_ProcessExit; Domain.DomainUnload += Domain_ProcessExit; HostPlatform.Current.SetConsoleCtrlHandler(CtrlHandlerDelegateInstance); var Version = AssemblyUtils.ExecutableVersion; Log.TraceVerbose("{0} ver. {1}", Version.ProductName, Version.ProductVersion); // Don't allow simultaneous execution of AT (in the same branch) ReturnCode = InternalUtils.RunSingleInstance(MainProc, CommandLine); } catch (AutomationException Ex) { Log.TraceError("AutomationTool terminated with exception: {0}", Ex); ReturnCode = Ex.ErrorCode; } catch (Exception Ex) { // Catch all exceptions and propagate the ErrorCode if we are given one. Log.TraceError("AutomationTool terminated with exception: {0}", Ex); ReturnCode = ExitCode.Error_Unknown; } finally { // In all cases, do necessary shut down stuff, but don't let any additional exceptions leak out while trying to shut down. // Make sure there's no directories on the stack. NoThrow(() => CommandUtils.ClearDirStack(), "Clear Dir Stack"); // Try to kill process before app domain exits to leave the other KillAll call to extreme edge cases NoThrow(() => { if (ShouldKillProcesses && !Utils.IsRunningOnMono) { ProcessManager.KillAll(); } }, "Kill All Processes"); Log.TraceInformation("AutomationTool exiting with ExitCode={0} ({1})", (int)ReturnCode, ReturnCode); // Can't use NoThrow here because the code logs exceptions. We're shutting down logging! LogUtils.ShutdownLogging(); } // STOP: No code beyond the return statement should go beyond this point! // Nothing should happen after the finally block above is finished. return((int)ReturnCode); }
private void Connect() { if (UsageTimer == null) { //Save Timer Resource for licensed usage if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis)) { UsageTimer = new Timer(delegate { __requestsPerHour = 0; }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1)); } } socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = SendTimeout, ReceiveTimeout = ReceiveTimeout }; try { #if NETSTANDARD2_0 var addresses = Dns.GetHostAddressesAsync(Host).Result; socket.Connect(addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork), Port); #else if (ConnectTimeout <= 0) { socket.Connect(Host, Port); } else { var connectResult = socket.BeginConnect(Host, Port, null, null); connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true); } #endif if (!socket.Connected) { socket.Close(); socket = null; DeactivatedAt = DateTime.UtcNow; return; } Stream networkStream = new NetworkStream(socket); if (Ssl) { if (Env.IsMono) { //Mono doesn't support EncryptionPolicy sslStream = new SslStream(networkStream, leaveInnerStreamOpen: false, userCertificateValidationCallback: RedisConfig.CertificateValidationCallback, userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback); } else { #if NETSTANDARD2_0 sslStream = new SslStream(networkStream, leaveInnerStreamOpen: false, userCertificateValidationCallback: RedisConfig.CertificateValidationCallback, userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback, encryptionPolicy: EncryptionPolicy.RequireEncryption); #else var ctor = typeof(SslStream).GetConstructors() .First(x => x.GetParameters().Length == 5); var policyType = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy"); var policyValue = Enum.Parse(policyType, "RequireEncryption"); sslStream = (SslStream)ctor.Invoke(new[] { networkStream, false, RedisConfig.CertificateValidationCallback, RedisConfig.CertificateSelectionCallback, policyValue, }); #endif } #if NETSTANDARD2_0 sslStream.AuthenticateAsClientAsync(Host).Wait(); #else sslStream.AuthenticateAsClient(Host); #endif if (!sslStream.IsEncrypted) { throw new Exception("Could not establish an encrypted connection to " + Host); } networkStream = sslStream; } Bstream = new BufferedStream(networkStream, 16 * 1024); if (!string.IsNullOrEmpty(Password)) { SendUnmanagedExpectSuccess(Commands.Auth, Password.ToUtf8Bytes()); } if (db != 0) { SendUnmanagedExpectSuccess(Commands.Select, db.ToUtf8Bytes()); } if (Client != null) { SendUnmanagedExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes()); } try { if (ServerVersionNumber == 0) { ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0); if (ServerVersionNumber <= 0) { var parts = ServerVersion.Split('.'); var version = int.Parse(parts[0]) * 1000; if (parts.Length > 1) { version += int.Parse(parts[1]) * 100; } if (parts.Length > 2) { version += int.Parse(parts[2]); } ServerVersionNumber = version; } } } catch (Exception) { //Twemproxy doesn't support the INFO command so automatically closes the socket //Fallback to ServerVersionNumber=Unknown then try re-connecting ServerVersionNumber = Unknown; Connect(); return; } clientPort = socket.LocalEndPoint is IPEndPoint ipEndpoint ? ipEndpoint.Port : -1; lastCommand = null; lastSocketException = null; LastConnectedAtTimestamp = Stopwatch.GetTimestamp(); OnConnected(); if (ConnectionFilter != null) { ConnectionFilter(this); } } catch (SocketException) { log.Error(ErrorConnect.Fmt(Host, Port)); throw; } }
/// <summary> /// Creates an instance of <see cref="CliApplication"/> using configured parameters. /// Default values are used in place of parameters that were not specified. /// A scope is defined as a lifetime of a command execution pipeline that includes directives handling. /// </summary> public CliApplication Build() { if (_cliApplicationBuilt) { throw new InvalidOperationException("Build can only be called once."); } _cliApplicationBuilt = true; // Set default values _title ??= AssemblyUtils.TryGetDefaultTitle() ?? "App"; _executableName ??= AssemblyUtils.TryGetDefaultExecutableName() ?? "app"; _versionText ??= AssemblyUtils.TryGetDefaultVersionText() ?? "v1.0"; _console ??= new SystemConsole(); if (_startupMode is null || _modeTypes.Count == 0) { this.UseDirectMode(true); } // Add core middlewares to the end of the pipeline this.AddAfterUserMiddlewares(); // Create context var _serviceCollection = new ServiceCollection(); var metadata = new ApplicationMetadata(_title, _executableName, _versionText, _description); var configuration = new ApplicationConfiguration(_modeTypes, _commandTypes, _directivesTypes, _middlewareTypes, _startupMode !, _serviceCollection); var environmentVariablesAccessor = new EnvironmentVariablesAccessor(); // Add core services _serviceCollection.AddOptions(); _serviceCollection.AddSingleton(typeof(ApplicationMetadata), metadata); _serviceCollection.AddSingleton(typeof(ApplicationConfiguration), configuration); _serviceCollection.AddSingleton(typeof(IConsole), _console); _serviceCollection.AddSingleton(typeof(IEnvironmentVariablesAccessor), environmentVariablesAccessor); _serviceCollection.AddSingleton <IRootSchemaAccessor, RootSchemaAccessor>(); _serviceCollection.AddSingleton <ICliCommandExecutor, CliCommandExecutor>(); _serviceCollection.AddSingleton <ICliApplicationLifetime, CliApplicationLifetime>(); _serviceCollection.AddScoped(typeof(ICliContext), (provider) => { IRootSchemaAccessor rootSchemaAccessor = provider.GetRequiredService <IRootSchemaAccessor>(); return(new CliContext(metadata, configuration, rootSchemaAccessor.RootSchema, environmentVariablesAccessor.EnvironmentVariables, _console)); }); _serviceCollection.AddLogging(cfg => { cfg.ClearProviders(); cfg.AddDebug(); cfg.SetMinimumLevel(LogLevel.Information); }); IServiceProvider serviceProvider = CreateServiceProvider(_serviceCollection); return(new CliApplication(serviceProvider, _console, environmentVariablesAccessor, metadata, _startupMessage)); }
protected virtual void BuildCache() { System.Type v_safeFilterType = m_filterType == null ? (m_acceptAbstract ? typeof(object) : null) : m_filterType; string v_safeTypeNameInAssembly = GetSafeTypedNameInAssembly(v_safeFilterType); ArrayDict <Assembly, System.Type[]> v_assemblyTypesDict = AssemblyUtils.GetAssemblyTypesDict(false); List <Assembly> v_assemblies = new List <Assembly>(); m_currentAssembly = m_currentType == null || m_currentType.CastedType == null ? null : m_currentType.CastedType.Assembly; //Filter Assemblies foreach (KVPair <Assembly, System.Type[]> v_pair in v_assemblyTypesDict) { if (v_pair != null && v_pair.Key != null) { if (AssemblyContainsFilteredType(v_pair.Key, m_filterType, m_acceptGeneric, m_acceptAbstract)) { v_assemblies.Add(v_pair.Key); } try { if (m_currentAssembly == null && m_currentType != null && ((SerializableType)m_currentType).StringType.Contains(v_pair.Key.FullName)) { m_currentAssembly = v_pair.Key; } } catch { } } } if (m_acceptNull) { v_assemblies.Insert(0, null); } if (m_currentAssembly == null && !m_acceptNull) { m_currentAssembly = v_safeFilterType.Assembly; } //Draw Popup Select Assembly m_possibleAssemblies = v_assemblies.ToArray(); m_possibleAssembliesString = v_assemblies.GetStringList().ToArray(); m_selectedAssemblyIndex = v_assemblies.Contains(m_currentAssembly) ? v_assemblies.IndexOf(m_currentAssembly) : -1; //Pick All Types if dont use Assembly Filter List <System.Type> v_assemblyTypes = new List <System.Type>(); foreach (var v_assembly in v_assemblies) { try { var v_types = v_assemblyTypesDict.GetValueWithKey(v_assembly); if (v_types != null) { foreach (System.Type v_type in v_types) { if (v_type != null && (!v_type.IsGenericTypeDefinition || m_acceptGeneric) && (!v_type.IsAbstract || m_acceptAbstract) && (m_filterType == null || TypeExtension.IsSameOrSubClassOrImplementInterface(v_type, m_filterType) || v_type.FullName.Contains(v_safeTypeNameInAssembly))) { v_assemblyTypes.Add(v_type); } } } } catch { } } if (m_acceptNull) { v_assemblyTypes.Insert(0, null); } m_possibleTypesInAllAssemblies = v_assemblyTypes.ToArray(); m_possibleTypesInAllAssembliesString = v_assemblyTypes.GetStringList().ToArray(); if (m_currentType == null && !m_acceptNull) { m_selectedTypeIndexInAllAssemblies = v_assemblyTypes.Contains(v_safeFilterType) ? v_assemblyTypes.IndexOf(v_safeFilterType) : -1; } else { m_selectedTypeIndexInAllAssemblies = v_assemblyTypes.Contains(m_currentType) ? v_assemblyTypes.IndexOf(m_currentType) : -1; } //Filter Types in Assembly Current Assembly v_assemblyTypes.Clear(); if (m_currentAssembly != null) { try { var v_types = v_assemblyTypesDict.GetValueWithKey(m_currentAssembly); if (v_types != null) { foreach (System.Type v_type in v_types) { if (v_type != null && (!v_type.IsGenericTypeDefinition || m_acceptGeneric) && (!v_type.IsAbstract || m_acceptAbstract) && (m_filterType == null || TypeExtension.IsSameOrSubClassOrImplementInterface(v_type, m_filterType) || v_type.FullName.Contains(v_safeTypeNameInAssembly))) { v_assemblyTypes.Add(v_type); } } } } catch { } } if (m_acceptNull) { v_assemblyTypes.Insert(0, null); } m_possibleTypesInCurrentAssembly = v_assemblyTypes.ToArray(); m_possibleTypesInCurrentAssemblyString = v_assemblyTypes.GetStringList().ToArray(); if (m_currentType == null && !m_acceptNull) { m_selectedTypeIndexInCurrentAssembly = v_assemblyTypes.Contains(v_safeFilterType) ? v_assemblyTypes.IndexOf(v_safeFilterType) : -1; } else { m_selectedTypeIndexInCurrentAssembly = v_assemblyTypes.Contains(m_currentType) ? v_assemblyTypes.IndexOf(m_currentType) : -1; } }
private void linkLabelContact_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start(String.Format("mailto:{0}?subject=About {1} v{2}", this.linkLabelContact.Text, QuickConnectPluginExt.Title, AssemblyUtils.GetVersion())); }
public static string ToJson <T>(this T obj) { return(JsConfig.PreferInterfaces ? JsonSerializer.SerializeToString(obj, AssemblyUtils.MainInterface <T>()) : JsonSerializer.SerializeToString(obj)); }
public FormAbout() { InitializeComponent(); var version = AssemblyUtils.GetProductVersion(); this.labelPluginName.Text += String.Format(" ({0})", Info.PluginType); this.labelVersion.Text = this.labelVersion.Text.Replace("{version}", version); this.KeyDown += new KeyEventHandler(formAbout_KeyPress); this.richTextBoxCopyright.LinkClicked += new LinkClickedEventHandler(richTextBoxCopyright_LinkClicked); this.linkLabelContact.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelContact_LinkClicked); this.linkLabelSource.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelSource_LinkClicked); this.richTextBoxCopyright.Text = this.richTextBoxCopyright.Text.Replace("{sshNetLibVersion}", AssemblyUtils.GetVersion("Renci.SshNet").ToString()); }
public static Type ParseType(string assemblyQualifiedName) { return(AssemblyUtils.FindType(assemblyQualifiedName.FromCsvField())); }
public Settings() { InitializeComponent(); Name = SettingsString.settings; Text = SettingsString.settings; if (AssemblyUtils.GetReleaseState() == AssemblyUtils.ReleaseState.Beta) { Name = SettingsString.settings + ' ' + AssemblyUtils.GetReleaseState(); Text = SettingsString.settings + ' ' + AssemblyUtils.GetReleaseState(); } Icon = Resources.SettingsIcon; var toolTip = new ToolTip(); toolTip.SetToolTip(closeButton, SettingsString.closeTooltip); var toolTipComm = new ToolTip(); toolTipComm.SetToolTip(communicationCheckbox, SettingsString.commTooltip); hotkeyTextBox.KeyDown += (sender, args) => SetHotkey(args); hotkeyTextBox.Text = AppConfigs.Configuration.PlaybackHotKeys.Display(); hotkeyTextBox.Tag = new Tuple <AudioDeviceType, HotKeys>(AudioDeviceType.Playback, AppConfigs.Configuration.PlaybackHotKeys); hotkeyTextBox.Enabled = hotkeysCheckbox.Checked = AppConfigs.Configuration.PlaybackHotKeys.Enabled; var toolTipHotkeys = new ToolTip(); toolTipHotkeys.SetToolTip(hotkeysCheckbox, SettingsString.hotkeyUncheckExplanation); RunAtStartup.Checked = AppModel.Instance.RunAtStartup; communicationCheckbox.Checked = AppModel.Instance.SetCommunications; var audioDeviceLister = new AudioDeviceLister(DeviceState.All); PopulateAudioList(playbackListView, AppModel.Instance.SelectedPlaybackDevicesList, audioDeviceLister.GetPlaybackDevices()); PopulateAudioList(recordingListView, AppModel.Instance.SelectedRecordingDevicesList, audioDeviceLister.GetRecordingDevices()); notifLabel.Text = SettingsString.notification; var toolTipNotification = new ToolTip(); toolTipNotification.SetToolTip(notificationComboBox, Notifications.explanation); new NotificationFactory().ConfigureListControl(notificationComboBox); notificationComboBox.SelectedValue = AppModel.Instance.NotificationSettings; betaVersionCheckbox.Checked = AppModel.Instance.SubscribedBetaVersions; var toolTipBeta = new ToolTip(); toolTipBeta.SetToolTip(betaVersionCheckbox, SettingsString.betaExplanation); selectSoundFileDialog.Filter = SettingsString.supportedAudio + @" (*.wav;*.mp3)|*.wav;*.mp3;*.aiff"; selectSoundFileDialog.FileOk += SelectSoundFileDialogOnFileOk; selectSoundFileDialog.CheckFileExists = true; var toolTipSoundButton = new ToolTip(); toolTipSoundButton.SetToolTip(selectSoundButton, SettingsString.selectSoundButtonTooltip); selectSoundButton.Visible = AppModel.Instance.NotificationSettings == NotificationTypeEnum.CustomNotification; stealthUpdateCheckbox.Checked = AppModel.Instance.StealthUpdate; var toolTipStealthUpdate = new ToolTip(); toolTipStealthUpdate.SetToolTip(stealthUpdateCheckbox, SettingsString.stealthUpdateExplanation); new TooltipInfoFactory().ConfigureListControl(tooltipInfoComboBox); tooltipInfoComboBox.SelectedValue = TooltipInfoManager.CurrentTooltipInfo; var toolTipCycler = new ToolTip(); toolTipCycler.SetToolTip(cyclerComboBox, AudioCycler.tooltipExplanation); new DeviceCyclerFactory().ConfigureListControl(cyclerComboBox); cyclerComboBox.SelectedValue = DeviceCyclerManager.CurrentCycler; _loaded = true; }