Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable .NET IL trimming to reduce app size #54

Merged
merged 5 commits into from
Mar 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/Build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ jobs:
/p:GenerateAppxPackageOnBuild=true `
/p:WindowsAppSDKSelfContained=true `
/p:SelfContained=true `
/p:PublishReadyToRun=false `
/p:RuntimeIdentifier=win10-${{ matrix.platform }}
env:
Appx_Bundle: Never
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ publish/
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
# *.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
Expand Down
19 changes: 13 additions & 6 deletions EnergyStarX/EnergyStarX.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
<Platforms>x86;x64;arm64</Platforms>
<RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
<PublishProfile>Properties\PublishProfiles\win10-$(Platform).pubxml</PublishProfile>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseWinUI>true</UseWinUI>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseWinUI>true</UseWinUI>
<EnableMsixTooling>true</EnableMsixTooling>
<GenerateTemporaryStoreCertificate>True</GenerateTemporaryStoreCertificate>
<GenerateAppInstallerFile>False</GenerateAppInstallerFile>
Expand All @@ -24,6 +24,14 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<!-- Enable .NET IL trimming in release mode to reduce app size -->
<!-- We need COM support to get hardware info with WmiLight -->
<PropertyGroup Condition="'$(Configuration)' != 'Debug'">
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>partial</TrimMode>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
</PropertyGroup>

<ItemGroup>
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>
Expand All @@ -33,20 +41,19 @@
<PackageReference Include="CommunityToolkit.WinUI" Version="7.1.2" />
<PackageReference Include="CommunityToolkit.WinUI.UI.Controls.Markdown" Version="7.1.2" />
<PackageReference Include="H.NotifyIcon" Version="2.0.94" />
<PackageReference Include="Hardware.Info" Version="10.1.1" />
<PackageReference Include="Microsoft.AppCenter.Analytics" Version="5.0.1" />
<PackageReference Include="Microsoft.AppCenter.Crashes" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.2.230217.4" />
<PackageReference Include="Microsoft.Xaml.Behaviors.WinUI.Managed" Version="2.0.9" />
<PackageReference Include="NLog" Version="5.1.2" />
<PackageReference Include="TaskScheduler" Version="2.10.1" />
<PackageReference Include="WinUICommunity.SettingsUI" Version="3.1.1" />
<PackageReference Include="WinUIEx" Version="2.1.0" />
<PackageReference Include="DependencyPropertyGenerator" Version="1.2.2" PrivateAssets="all" ExcludeAssets="runtime">
<IncludeAssets>compile; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Flurl" Version="3.0.7" />
<PackageReference Include="WmiLight" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
Expand Down Expand Up @@ -110,7 +117,7 @@
<DependentUpon>SettingsHelper.tt</DependentUpon>
</Compile>
</ItemGroup>

<PropertyGroup Condition="'$(DisableHasPackageAndPublishMenuAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">
<HasPackageAndPublishMenu>true</HasPackageAndPublishMenu>
</PropertyGroup>
Expand Down
16 changes: 16 additions & 0 deletions EnergyStarX/Properties/PublishProfiles/win10-arm64.pubxml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishProtocol>FileSystem</PublishProtocol>
<Platform>arm64</Platform>
<RuntimeIdentifier>win10-arm64</RuntimeIdentifier>
<PublishDir>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\</PublishDir>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun Condition="'$(Configuration)' == 'Debug'">False</PublishReadyToRun>
<PublishReadyToRun Condition="'$(Configuration)' != 'Debug'">True</PublishReadyToRun>
</PropertyGroup>
</Project>
16 changes: 16 additions & 0 deletions EnergyStarX/Properties/PublishProfiles/win10-x64.pubxml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishProtocol>FileSystem</PublishProtocol>
<Platform>x64</Platform>
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
<PublishDir>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\</PublishDir>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun Condition="'$(Configuration)' == 'Debug'">False</PublishReadyToRun>
<PublishReadyToRun Condition="'$(Configuration)' != 'Debug'">True</PublishReadyToRun>
</PropertyGroup>
</Project>
31 changes: 25 additions & 6 deletions EnergyStarX/Services/StartupService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ public async Task Initialize()

public async Task<StartupType> GetStartupType()
{
bool msixStartupTaskEnabled = await GetMsixStartupTaskEnabled();
bool adminScheduleTaskExists = GetAdminScheduleTaskExists();
// Run in parallel to save time
Task<bool> GetMsixStartupTaskEnabledTask = GetMsixStartupTaskEnabled();
Task<bool> GetAdminScheduleTaskExistsTask = GetAdminScheduleTaskExists();

bool msixStartupTaskEnabled = await GetMsixStartupTaskEnabledTask;
bool adminScheduleTaskExists = await GetAdminScheduleTaskExistsTask;

StartupType startupType = (msixStartupTaskEnabled, adminScheduleTaskExists) switch
{
Expand Down Expand Up @@ -122,9 +126,24 @@ private async Task<bool> DisableMsixStartupTask()

private const string AdminScheduleTaskName = "EnergyStarXAdminStartupTask";

private bool GetAdminScheduleTaskExists()
private async Task<bool> GetAdminScheduleTaskExists()
{
return Microsoft.Win32.TaskScheduler.TaskService.Instance.RootFolder.Tasks.Exists(AdminScheduleTaskName);
using Process process = new()
{
StartInfo = new ProcessStartInfo()
{
FileName = "schtasks",
ArgumentList = { "/query", "/tn", AdminScheduleTaskName },

UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Hidden
}
};

process.Start();
await process.WaitForExitAsync();

return process.ExitCode == 0;
}

/// <summary>
Expand Down Expand Up @@ -212,7 +231,7 @@ private async Task<bool> CreateAdminScheduleTask()
await scheduleTaskXmlFile.DeleteAsync();
}

return GetAdminScheduleTaskExists();
return await GetAdminScheduleTaskExists();
}

/// <summary>
Expand Down Expand Up @@ -246,7 +265,7 @@ private async Task<bool> DeleteAdminScheduleTask()
return false;
}

return !GetAdminScheduleTaskExists();
return !await GetAdminScheduleTaskExists();
}

private string GetExecutablePath()
Expand Down
37 changes: 25 additions & 12 deletions EnergyStarX/ViewModels/SettingsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
using CommunityToolkit.Mvvm.Input;
using EnergyStarX.Helpers;
using EnergyStarX.Services;
using Hardware.Info;
using Windows.ApplicationModel;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Windows.System;
using WmiLight;

namespace EnergyStarX.ViewModels;

Expand Down Expand Up @@ -201,13 +201,30 @@ private async Task ContactTheDeveloper()

private readonly Lazy<string> feedbackMailBody = new(() =>
{
HardwareInfo hardware = new();
hardware.RefreshCPUList(false);
hardware.RefreshMemoryList();
hardware.RefreshVideoControllerList();
hardware.RefreshBatteryList();
string hardwareInfo = string.Empty;

string JoinItems<T>(IEnumerable<T> items, Func<T, string> selector) => items.Any() ? string.Join(" + ", items.Select(selector)) : "N/A";
try
{
using WmiConnection wmiConnection = new();

string JoinItems<T>(IEnumerable<T> items) => items.Any() ? string.Join(" + ", items) : "N/A";

string cpuName = JoinItems(wmiConnection.CreateQuery("SELECT Name FROM Win32_Processor").Select(cpu => cpu["Name"]));
string gpuName = JoinItems(wmiConnection.CreateQuery("SELECT Name FROM Win32_VideoController").Select(gpu => gpu["Name"]));
bool batteryExists = wmiConnection.CreateQuery("SELECT Name FROM Win32_Battery").Any();
long ramCapacity = wmiConnection.CreateQuery("SELECT Capacity FROM Win32_PhysicalMemory")
.Select(ram => long.TryParse(ram["Capacity"] as string, out long capacity) ? capacity : 0)
.Sum();

hardwareInfo = $"""
CPU: {cpuName}
RAM: {ramCapacity / 1024 / 1024} MB
GPU: {gpuName}
Battery: {(batteryExists ? "Yes" : "No")}

""";
}
catch { }

return $"""

Expand All @@ -216,11 +233,7 @@ private async Task ContactTheDeveloper()
----------
Windows: {Environment.OSVersion.Version}
Device: {new EasClientDeviceInformation().SystemProductName}
CPU: {JoinItems(hardware.CpuList, c => c.Name)}
RAM: {hardware.MemoryList.Select(m => m.Capacity).Aggregate((a, b) => a + b) / 1024 / 1024} MB
GPU: {JoinItems(hardware.VideoControllerList, v => v.Name)}
Battery: {(hardware.BatteryList.Count > 0 ? "Yes" : "No")}

{hardwareInfo}
""";
});

Expand Down