Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
inga-lovinde committed Dec 4, 2019
1 parent 0fc4127 commit b259322
Show file tree
Hide file tree
Showing 21 changed files with 228 additions and 154 deletions.
7 changes: 7 additions & 0 deletions RadeonResetBugFixService/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[*.cs]

# CA1303: Do not pass literals as localized parameters
dotnet_diagnostic.CA1303.severity = suggestion

# CA1031: Do not catch general exception types
dotnet_diagnostic.CA1031.severity = suggestion
4 changes: 0 additions & 4 deletions RadeonResetBugFixService/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,5 @@
static class Constants
{
public static TimeSpan ServiceTimeout { get; } = TimeSpan.FromMinutes(5);

public static string RegistryKeyBasicDisplay { get; } = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\BasicDisplay";

public static string RegistryKeySystemControl { get; } = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control";
}
}
27 changes: 7 additions & 20 deletions RadeonResetBugFixService/Devices/DeviceHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System;
using System.Collections.Generic;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
using Contracts;

Expand All @@ -23,8 +22,12 @@ private static T GetProperty<T>(PropertyDataCollection properties, string key)

private static Guid GuidTryParse(string input)
{
Guid.TryParse(input, out var result);
return result;
if (Guid.TryParse(input, out var result))
{
return result;
}

return default;
}

private static DeviceInfo ConvertDeviceInfo(PropertyDataCollection deviceProperties)
Expand Down Expand Up @@ -93,25 +96,9 @@ public static void EnableDevice(DeviceInfo deviceInfo)

private static void RunWithTimeout(Action action, TimeSpan timeout)
{
Exception localException = null;
Task.WaitAny(
Task.Run(() =>
{
try
{
action();
}
catch (Exception e)
{
localException = new Exception("Exception from action", e);
}
}),
Task.Run(action),
Task.Delay(timeout));

if (localException != null)
{
throw localException;
}
}
}
}
7 changes: 4 additions & 3 deletions RadeonResetBugFixService/Devices/KnownDevices.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
namespace RadeonResetBugFixService.Devices
{
using System;
using Contracts;

static class KnownDevices
{
public static bool IsAmdVideo(DeviceInfo device)
{
return (device.Manufacturer.ToLowerInvariant() == "amd" || device.Manufacturer.ToLowerInvariant().Contains("advanced micro devices")) &&
(device.Service.ToLowerInvariant() == "hdaudbus" || device.ClassName.ToLowerInvariant() == "display");
return ((device.Manufacturer.Equals("AMD", StringComparison.OrdinalIgnoreCase) || device.Manufacturer.IndexOf("Advanced Micro Devices", StringComparison.OrdinalIgnoreCase) >= 0) &&
(device.Service.Equals("hdaudbus", StringComparison.OrdinalIgnoreCase) || device.ClassName.Equals("display", StringComparison.OrdinalIgnoreCase)));
}

public static bool IsVirtualVideo(DeviceInfo device)
{
return device.Service.ToLowerInvariant() == "hypervideo";
return device.Service.Equals("hypervideo", StringComparison.OrdinalIgnoreCase);
}
}
}
4 changes: 2 additions & 2 deletions RadeonResetBugFixService/MainHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ public void HandleStartup(string reason)
new ITask[]
{
new EnableBasicDisplayStartupTask(),
new SleepTask(TimeSpan.FromSeconds(20)),
new SleepTask(TimeSpan.FromSeconds(40)),
new EnableAmdVideoTask(this.StartupDevicesStatus),
new DisableVirtualVideoTask(this.StartupDevicesStatus),
new SleepTask(TimeSpan.FromSeconds(40)),
new SleepTask(TimeSpan.FromSeconds(20)),
new FixMonitorTask(),
new DisableVirtualVideoTask(this.StartupDevicesStatus),
new FixMonitorTask(),
Expand Down
49 changes: 21 additions & 28 deletions RadeonResetBugFixService/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
namespace RadeonResetBugFixService
{
using Microsoft.Win32;
using System;
using System.Security.Principal;
using System.ServiceProcess;
Expand All @@ -13,6 +12,11 @@ public static class Program
/// </summary>
public static int Main(string[] args)
{
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}

if (Environment.UserInteractive)
{
if (!HasAdministratorPrivileges())
Expand Down Expand Up @@ -52,23 +56,21 @@ private static void MainConsole(string[] args)
return;
}

switch (args[0].ToLowerInvariant())
var command = args[0];
if (command.Equals("install", StringComparison.OrdinalIgnoreCase)) {
DoInstall();
}
else if (command.Equals("uninstall", StringComparison.OrdinalIgnoreCase))
{
DoUninstall();
}
else if (command.Equals("startup", StringComparison.OrdinalIgnoreCase))
{
case "install":
DoInstall();
return;
case "uninstall":
DoUninstall();
return;
case "startup":
DoStartup();
return;
case "shutdown":
DoShutdown();
return;
default:
ShowHelp();
return;
DoStartup();
}
else if (command.Equals("shutdown", StringComparison.OrdinalIgnoreCase))
{
DoShutdown();
}
}

Expand All @@ -90,26 +92,17 @@ private static void DoInstall()
{
Console.WriteLine("Setting registry values...");

// Prevent Windows from killing services that take up to 300 seconds to shutdown
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "WaitToKillServiceTimeout", (int)Constants.ServiceTimeout.TotalMilliseconds, RegistryValueKind.String);

// Disable fast restart
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power", "HiberbootEnabled", 0, RegistryValueKind.DWord);

// Allow interactive services (FixMonitorTask only works correctly in interactive mode)
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows", "NoInteractiveServices", 0, RegistryValueKind.DWord);

Console.WriteLine("Installing service...");
ServiceHelpers.InstallService(nameof(RadeonResetBugFixService), typeof(RadeonResetBugFixService));
Console.WriteLine("Starting service...");
ServiceHelpers.StartService(nameof(RadeonResetBugFixService), typeof(RadeonResetBugFixService));
ServiceHelpers.StartService(nameof(RadeonResetBugFixService));
Console.WriteLine("Started service");
}

private static void DoUninstall()
{
Console.WriteLine("Stopping service...");
ServiceHelpers.StopService(nameof(RadeonResetBugFixService), typeof(RadeonResetBugFixService));
ServiceHelpers.StopService(nameof(RadeonResetBugFixService));
Console.WriteLine("Uninstalling service...");
ServiceHelpers.UninstallService(nameof(RadeonResetBugFixService), typeof(RadeonResetBugFixService));
Console.WriteLine("Uninstalled");
Expand Down
1 change: 0 additions & 1 deletion RadeonResetBugFixService/ProjectInstaller.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 24 additions & 34 deletions RadeonResetBugFixService/ProjectInstaller.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
namespace RadeonResetBugFixService
{
using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Management;
using Microsoft.Win32;

[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
Expand All @@ -16,54 +16,44 @@ public ProjectInstaller()

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
ManagementObject wmiService = null;
ManagementBaseObject InParam = null;
try
{
wmiService = new ManagementObject($"Win32_Service.Name='{this.serviceInstaller1.ServiceName}'");
InParam = wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"] = true;
wmiService.InvokeMethod("Change", InParam, null);
}
finally
Console.WriteLine("Preventing Windows from killing services that take up to 300 seconds to shutdown");
RegistryHelper.SetWaitToKillServiceTimeout((int)Constants.ServiceTimeout.TotalMilliseconds);

Console.WriteLine("Disabling fast reboot");
RegistryHelper.SetFastRebootStatus(false);

Console.WriteLine("Allowing interactive services");
RegistryHelper.SetInteractiveServicesStatus(true);

Console.WriteLine("Configuring service as interactive");
using (var wmiService = new ManagementObject($"Win32_Service.Name='{this.serviceInstaller1.ServiceName}'"))
{
if (InParam != null)
InParam.Dispose();
if (wmiService != null)
wmiService.Dispose();
using (var InParam = wmiService.GetMethodParameters("Change"))
{
InParam["DesktopInteract"] = true;
wmiService.InvokeMethod("Change", InParam, null);
}
}

Console.WriteLine("Setting preshutdown timeout for service");
ThirdParty.ServicePreshutdownHelpers.ServicePreshutdownHelpers.SetPreShutdownTimeOut(this.serviceInstaller1.ServiceName, (uint)Constants.ServiceTimeout.TotalMilliseconds);

var preshutdownOrder = GetPreshutdownOrder();
Console.WriteLine("Adding service to preshutdown order");
var preshutdownOrder = RegistryHelper.GetPreshutdownOrder();
if (!preshutdownOrder.Contains(this.serviceInstaller1.ServiceName))
{
SetPreshutdownOrder(new[] { this.serviceInstaller1.ServiceName }.Concat(preshutdownOrder).ToArray());
RegistryHelper.SetPreshutdownOrder(new[] { this.serviceInstaller1.ServiceName }.Concat(preshutdownOrder).ToArray());
}
}

private void serviceInstaller1_AfterUninstall(object sender, InstallEventArgs e)
{
var preshutdownOrder = GetPreshutdownOrder();
Console.WriteLine("Removing service from preshutdown order");
var preshutdownOrder = RegistryHelper.GetPreshutdownOrder();
if (preshutdownOrder.Contains(this.serviceInstaller1.ServiceName))
{
SetPreshutdownOrder(preshutdownOrder.Where((name) => name != this.serviceInstaller1.ServiceName).ToArray());
RegistryHelper.SetPreshutdownOrder(preshutdownOrder.Where((name) => name != this.serviceInstaller1.ServiceName).ToArray());
}
}

private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
{

}

private string[] GetPreshutdownOrder()
{
return (string[])Registry.GetValue(Constants.RegistryKeySystemControl, "PreshutdownOrder", new string[0]);
}

private void SetPreshutdownOrder(string[] data)
{
Registry.SetValue(Constants.RegistryKeySystemControl, "PreshutdownOrder", data, RegistryValueKind.MultiString);
}
}
}
31 changes: 31 additions & 0 deletions RadeonResetBugFixService/RadeonResetBugFixService.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Microsoft.CodeAnalysis.FxCopAnalyzers.2.9.8\build\Microsoft.CodeAnalysis.FxCopAnalyzers.props" Condition="Exists('..\packages\Microsoft.CodeAnalysis.FxCopAnalyzers.2.9.8\build\Microsoft.CodeAnalysis.FxCopAnalyzers.props')" />
<Import Project="..\packages\Microsoft.NetFramework.Analyzers.2.9.8\build\Microsoft.NetFramework.Analyzers.props" Condition="Exists('..\packages\Microsoft.NetFramework.Analyzers.2.9.8\build\Microsoft.NetFramework.Analyzers.props')" />
<Import Project="..\packages\Microsoft.NetCore.Analyzers.2.9.8\build\Microsoft.NetCore.Analyzers.props" Condition="Exists('..\packages\Microsoft.NetCore.Analyzers.2.9.8\build\Microsoft.NetCore.Analyzers.props')" />
<Import Project="..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\build\Microsoft.CodeQuality.Analyzers.props" Condition="Exists('..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\build\Microsoft.CodeQuality.Analyzers.props')" />
<Import Project="..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\build\Microsoft.CodeAnalysis.VersionCheckAnalyzer.props" Condition="Exists('..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\build\Microsoft.CodeAnalysis.VersionCheckAnalyzer.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand All @@ -12,6 +17,8 @@
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<Platform_target>AnyCPU</Platform_target>
Expand Down Expand Up @@ -73,6 +80,7 @@
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Logging\TaskLoggerWrapper.cs" />
<Compile Include="RegistryHelper.cs" />
<Compile Include="Tasks\DisableBasicDisplayStartupTask.cs" />
<Compile Include="Tasks\EnableBasicDisplayStartupTask.cs" />
<Compile Include="Tasks\FixMonitorTask.cs" />
Expand All @@ -94,7 +102,9 @@
<Compile Include="ThirdParty\ServicePreshutdownHelpers.cs" />
</ItemGroup>
<ItemGroup>
<None Include=".editorconfig" />
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="ProjectInstaller.resx">
Expand All @@ -104,5 +114,26 @@
<DependentUpon>RadeonResetBugFixService.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\analyzers\dotnet\cs\Microsoft.CodeAnalysis.VersionCheckAnalyzer.resources.dll" />
<Analyzer Include="..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\analyzers\dotnet\Microsoft.CodeAnalysis.VersionCheckAnalyzer.dll" />
<Analyzer Include="..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Humanizer.dll" />
<Analyzer Include="..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.Analyzers.dll" />
<Analyzer Include="..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.CSharp.Analyzers.dll" />
<Analyzer Include="..\packages\Microsoft.NetCore.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.NetCore.Analyzers.dll" />
<Analyzer Include="..\packages\Microsoft.NetCore.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.NetCore.CSharp.Analyzers.dll" />
<Analyzer Include="..\packages\Microsoft.NetFramework.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.NetFramework.Analyzers.dll" />
<Analyzer Include="..\packages\Microsoft.NetFramework.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.NetFramework.CSharp.Analyzers.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp._targets" />
<_target Name="EnsureNuGetPackageBuildImports" Before_targets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\build\Microsoft.CodeAnalysis.VersionCheckAnalyzer.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\build\Microsoft.CodeAnalysis.VersionCheckAnalyzer.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\build\Microsoft.CodeQuality.Analyzers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeQuality.Analyzers.2.9.8\build\Microsoft.CodeQuality.Analyzers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.NetCore.Analyzers.2.9.8\build\Microsoft.NetCore.Analyzers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NetCore.Analyzers.2.9.8\build\Microsoft.NetCore.Analyzers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.NetFramework.Analyzers.2.9.8\build\Microsoft.NetFramework.Analyzers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NetFramework.Analyzers.2.9.8\build\Microsoft.NetFramework.Analyzers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeAnalysis.FxCopAnalyzers.2.9.8\build\Microsoft.CodeAnalysis.FxCopAnalyzers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeAnalysis.FxCopAnalyzers.2.9.8\build\Microsoft.CodeAnalysis.FxCopAnalyzers.props'))" />
</_target>
</Project>
Loading

0 comments on commit b259322

Please sign in to comment.
  NODES
admin 1
COMMUNITY 1
Note 1
Project 22
USERS 1