-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
SystemInformation.cs
423 lines (350 loc) · 16.3 KB
/
SystemInformation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Toolkit.Helpers;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Windows.System;
using Windows.System.Profile;
using Windows.System.UserProfile;
using Windows.UI.Core;
using Windows.UI.Xaml;
namespace Microsoft.Toolkit.Uwp.Helpers
{
/// <summary>
/// This class provides info about the app and the system.
/// </summary>
public sealed class SystemInformation
{
/// <summary>
/// The <see cref="ApplicationDataStorageHelper"/> instance used to save and retrieve application settings.
/// </summary>
private readonly ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent();
/// <summary>
/// The starting time of the current application session (since app launch or last move to foreground).
/// </summary>
private DateTime _sessionStart;
/// <summary>
/// Initializes a new instance of the <see cref="SystemInformation"/> class.
/// </summary>
private SystemInformation()
{
ApplicationName = Package.Current.DisplayName;
ApplicationVersion = Package.Current.Id.Version;
try
{
Culture = GlobalizationPreferences.Languages.Count > 0 ? new CultureInfo(GlobalizationPreferences.Languages.First()) : null;
}
catch
{
Culture = null;
}
DeviceFamily = AnalyticsInfo.VersionInfo.DeviceFamily;
ulong version = ulong.Parse(AnalyticsInfo.VersionInfo.DeviceFamilyVersion);
OperatingSystemVersion = new OSVersion
{
Major = (ushort)((version & 0xFFFF000000000000L) >> 48),
Minor = (ushort)((version & 0x0000FFFF00000000L) >> 32),
Build = (ushort)((version & 0x00000000FFFF0000L) >> 16),
Revision = (ushort)(version & 0x000000000000FFFFL)
};
OperatingSystemArchitecture = Package.Current.Id.Architecture;
EasClientDeviceInformation deviceInfo = new();
OperatingSystem = deviceInfo.OperatingSystem;
DeviceManufacturer = deviceInfo.SystemManufacturer;
DeviceModel = deviceInfo.SystemProductName;
IsFirstRun = DetectIfFirstUse();
(IsAppUpdated, PreviousVersionInstalled) = DetectIfAppUpdated();
FirstUseTime = DetectFirstUseTime();
FirstVersionInstalled = DetectFirstVersionInstalled();
InitializeValuesSetWithTrackAppUse();
}
/// <summary>
/// Gets the unique instance of <see cref="SystemInformation"/>.
/// </summary>
public static SystemInformation Instance { get; } = new();
/// <summary>
/// Gets the application's name.
/// </summary>
public string ApplicationName { get; }
/// <summary>
/// Gets the application's version.
/// </summary>
public PackageVersion ApplicationVersion { get; }
/// <summary>
/// Gets the user's most preferred culture.
/// </summary>
public CultureInfo Culture { get; }
/// <summary>
/// Gets the device's family.
/// <para></para>
/// Common values include:
/// <list type="bullet">
/// <item><term>"Windows.Desktop"</term></item>
/// <item><term>"Windows.Mobile"</term></item>
/// <item><term>"Windows.Xbox"</term></item>
/// <item><term>"Windows.Holographic"</term></item>
/// <item><term>"Windows.Team"</term></item>
/// <item><term>"Windows.IoT"</term></item>
/// </list>
/// <para></para>
/// Prepare your code for other values.
/// </summary>
public string DeviceFamily { get; }
/// <summary>
/// Gets the operating system's name.
/// </summary>
public string OperatingSystem { get; }
/// <summary>
/// Gets the operating system's version.
/// </summary>
public OSVersion OperatingSystemVersion { get; }
/// <summary>
/// Gets the processor architecture.
/// </summary>
public ProcessorArchitecture OperatingSystemArchitecture { get; }
/// <summary>
/// Gets the available memory.
/// </summary>
public float AvailableMemory => (float)MemoryManager.AppMemoryUsageLimit / 1024 / 1024;
/// <summary>
/// Gets the device's model.
/// Will be empty if the model couldn't be determined (For example: when running in a virtual machine).
/// </summary>
public string DeviceModel { get; }
/// <summary>
/// Gets the device's manufacturer.
/// Will be empty if the manufacturer couldn't be determined (For example: when running in a virtual machine).
/// </summary>
public string DeviceManufacturer { get; }
/// <summary>
/// Gets a value indicating whether the app is being used for the first time since it was installed.
/// Use this to tell if you should do or display something different for the app's first use.
/// </summary>
public bool IsFirstRun { get; }
/// <summary>
/// Gets a value indicating whether the app is being used for the first time since being upgraded from an older version.
/// Use this to tell if you should display details about what has changed.
/// </summary>
public bool IsAppUpdated { get; }
/// <summary>
/// Gets the first version of the app that was installed.
/// This will be the current version if a previous version of the app was installed before accessing this property.
/// </summary>
public PackageVersion FirstVersionInstalled { get; }
/// <summary>
/// Gets the previous version of the app that was installed.
/// This will be the current version if a previous version of the app was installed
/// before using <see cref="SystemInformation"/> or if the app is not updated.
/// </summary>
public PackageVersion PreviousVersionInstalled { get; }
/// <summary>
/// Gets the DateTime (in UTC) when the app was launched for the first time.
/// </summary>
public DateTime FirstUseTime { get; }
/// <summary>
/// Gets the DateTime (in UTC) when the app was last launched, not including this instance.
/// Will be <see cref="DateTime.MinValue"/> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public DateTime LastLaunchTime { get; private set; }
/// <summary>
/// Gets the number of times the app has been launched.
/// Will be <c>0</c> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public long LaunchCount { get; private set; }
/// <summary>
/// Gets the number of times the app has been launched.
/// Will be <c>0</c> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public long TotalLaunchCount { get; private set; }
/// <summary>
/// Gets the DateTime (in UTC) that this instance of the app was launched.
/// Will be <see cref="DateTime.MinValue"/> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public DateTime LaunchTime { get; private set; }
/// <summary>
/// Gets the DateTime (in UTC) when the launch count was last reset.
/// Will be <see cref="DateTime.MinValue"/> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public DateTime LastResetTime { get; private set; }
/// <summary>
/// Gets the length of time this instance of the app has been running.
/// Will be <see cref="TimeSpan.MinValue"/> if <see cref="TrackAppUse"/> has not been called yet.
/// </summary>
public TimeSpan AppUptime
{
get
{
if (LaunchCount > 0)
{
var subSessionLength = DateTime.UtcNow.Subtract(_sessionStart).Ticks;
var uptimeSoFar = _settingsStorage.Read<long>(nameof(AppUptime));
return new(uptimeSoFar + subSessionLength);
}
return TimeSpan.MinValue;
}
}
/// <summary>
/// Adds to the record of how long the app has been running.
/// Use this to optionally include time spent in background tasks or extended execution.
/// </summary>
/// <param name="duration">The amount to time to add</param>
public void AddToAppUptime(TimeSpan duration)
{
var uptimeSoFar = _settingsStorage.Read<long>(nameof(AppUptime));
_settingsStorage.Save(nameof(AppUptime), uptimeSoFar + duration.Ticks);
}
/// <summary>
/// Resets the launch count.
/// </summary>
public void ResetLaunchCount()
{
LastResetTime = DateTime.UtcNow;
LaunchCount = 0;
_settingsStorage.Save(nameof(LastResetTime), LastResetTime.ToFileTimeUtc());
_settingsStorage.Save(nameof(LaunchCount), LaunchCount);
}
/// <summary>
/// Tracks information about the app's launch.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
/// <param name="xamlRoot">The XamlRoot object from your visual tree.</param>
public void TrackAppUse(IActivatedEventArgs args, XamlRoot xamlRoot = null)
{
if (args.PreviousExecutionState is ApplicationExecutionState.ClosedByUser or ApplicationExecutionState.NotRunning)
{
LaunchCount = _settingsStorage.Read<long>(nameof(LaunchCount)) + 1;
TotalLaunchCount = _settingsStorage.Read<long>(nameof(TotalLaunchCount)) + 1;
// In case we upgraded the properties, make TotalLaunchCount is correct
if (TotalLaunchCount < LaunchCount)
{
TotalLaunchCount = LaunchCount;
}
_settingsStorage.Save(nameof(LaunchCount), LaunchCount);
_settingsStorage.Save(nameof(TotalLaunchCount), TotalLaunchCount);
LaunchTime = DateTime.UtcNow;
var lastLaunch = _settingsStorage.Read<long>(nameof(LastLaunchTime));
LastLaunchTime = lastLaunch != 0
? DateTime.FromFileTimeUtc(lastLaunch)
: LaunchTime;
_settingsStorage.Save(nameof(LastLaunchTime), LaunchTime.ToFileTimeUtc());
_settingsStorage.Save(nameof(AppUptime), 0L);
var lastResetTime = _settingsStorage.Read<long>(nameof(LastResetTime));
LastResetTime = lastResetTime != 0
? DateTime.FromFileTimeUtc(lastResetTime)
: DateTime.MinValue;
}
if (xamlRoot != null)
{
void XamlRoot_Changed(XamlRoot sender, XamlRootChangedEventArgs e)
{
UpdateVisibility(sender.IsHostVisible);
}
xamlRoot.Changed -= XamlRoot_Changed;
xamlRoot.Changed += XamlRoot_Changed;
}
else
{
void App_VisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs e)
{
UpdateVisibility(e.Visible);
}
CoreWindow windowForCurrentThread = CoreWindow.GetForCurrentThread();
windowForCurrentThread.VisibilityChanged -= App_VisibilityChanged;
windowForCurrentThread.VisibilityChanged += App_VisibilityChanged;
}
}
private void UpdateVisibility(bool visible)
{
if (visible)
{
_sessionStart = DateTime.UtcNow;
}
else
{
var subSessionLength = DateTime.UtcNow.Subtract(_sessionStart).Ticks;
var uptimeSoFar = _settingsStorage.Read<long>(nameof(AppUptime));
_settingsStorage.Save(nameof(AppUptime), uptimeSoFar + subSessionLength);
}
}
private bool DetectIfFirstUse()
{
if (_settingsStorage.KeyExists(nameof(IsFirstRun)))
{
return false;
}
_settingsStorage.Save(nameof(IsFirstRun), true);
return true;
}
private (bool IsUpdated, PackageVersion PreviousVersion) DetectIfAppUpdated()
{
var currentVersion = ApplicationVersion.ToFormattedString();
// If the "currentVersion" key does not exist, it means that this is the first time this method
// is ever called. That is, this is either the first time the app has been launched, or the first
// time a previously existing app has run this method (or has run it after a new update of the app).
// In this case, save the current version and report the same version as previous version installed.
if (!_settingsStorage.KeyExists(nameof(currentVersion)))
{
_settingsStorage.Save(nameof(currentVersion), currentVersion);
}
else
{
var previousVersion = _settingsStorage.Read<string>(nameof(currentVersion));
// There are two possible cases if the "currentVersion" key exists:
// 1) The previous version is different than the current one. This means that the application
// has been updated since the last time this method was called. We can overwrite the saved
// setting for "currentVersion" to bring that value up to date, and return its old value.
// 2) The previous version matches the current one: the app has just been reopened without updates.
// In this case we have nothing to do and just return the previous version installed to be the same.
if (currentVersion != previousVersion)
{
_settingsStorage.Save(nameof(currentVersion), currentVersion);
return (true, previousVersion.ToPackageVersion());
}
}
return (false, currentVersion.ToPackageVersion());
}
private DateTime DetectFirstUseTime()
{
if (_settingsStorage.KeyExists(nameof(FirstUseTime)))
{
var firstUse = _settingsStorage.Read<long>(nameof(FirstUseTime));
return DateTime.FromFileTimeUtc(firstUse);
}
DateTime utcNow = DateTime.UtcNow;
_settingsStorage.Save(nameof(FirstUseTime), utcNow.ToFileTimeUtc());
return utcNow;
}
private PackageVersion DetectFirstVersionInstalled()
{
if (_settingsStorage.KeyExists(nameof(FirstVersionInstalled)))
{
return _settingsStorage.Read<string>(nameof(FirstVersionInstalled)).ToPackageVersion();
}
_settingsStorage.Save(nameof(FirstVersionInstalled), ApplicationVersion.ToFormattedString());
return ApplicationVersion;
}
private void InitializeValuesSetWithTrackAppUse()
{
LaunchTime = DateTime.MinValue;
LaunchCount = 0;
TotalLaunchCount = 0;
LastLaunchTime = DateTime.MinValue;
LastResetTime = DateTime.MinValue;
}
/// <summary>
/// Launches the store app so the user can leave a review.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <remarks>This method needs to be called from your UI thread.</remarks>
public static Task LaunchStoreForReviewAsync()
{
return Launcher.LaunchUriAsync(new Uri(string.Format("ms-windows-store://review/?PFN={0}", Package.Current.Id.FamilyName))).AsTask();
}
}
}