-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundCopyManager.cs
420 lines (354 loc) · 16.3 KB
/
BackgroundCopyManager.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
//
// @(#) BackgroundCopyManager.cs
//
// Project: usis.Net.Bits
// System: Microsoft Visual Studio 2022
// Author: Udo Schäfer
//
// Copyright (c) 2017-2023 usis GmbH. All rights reserved.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using usis.Net.Bits.Interop;
namespace usis.Net.Bits
{
// ---------------------------
// BackgroundCopyManager class
// ---------------------------
/// <summary>
/// Provides methods to create transfer jobs,
/// to enumerate the jobs in the queue, and to retrieve individual jobs from the queue.
/// </summary>
/// <seealso cref="IDisposable" />
public sealed class BackgroundCopyManager : IDisposable
{
#region fields
private IBackgroundCopyManager? manager;
private Version? version;
#endregion
#region construction
// ------------
// construction
// ------------
private BackgroundCopyManager() => manager = CreateComObject<IBackgroundCopyManager>(new Guid(CLSID.BackgroundCopyManager));
#endregion
#region IDisposable implementation
// --------------
// Dispose method
// --------------
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (manager != null)
{
// free unmanaged resources
_ = Marshal.ReleaseComObject(manager);
manager = null;
}
GC.SuppressFinalize(this);
}
// ---------
// finalizer
// ---------
/// <summary>
/// Finalizes an instance of the <see cref="BackgroundCopyManager"/> class.
/// </summary>
~BackgroundCopyManager() { Dispose(); }
#endregion
#region properties
// ----------------
// Version property
// ----------------
/// <summary>
/// Gets the version of BITS on the client computer.
/// </summary>
/// <value>
/// The version of BITS on the client computer.
/// </value>
public Version? Version => version ??= DetermineVersion();
// -----------------------
// LibraryVersion property
// -----------------------
/// <summary>
/// Gets the file version of the Windows <c>QMgr.dll</c> file.
/// </summary>
/// <value>
/// The QMgr.dll file version number.
/// </value>
public static Version? LibraryVersion => DetermineQMgrVersion();
#endregion
#region methods
// --------------
// Connect method
// --------------
/// <summary>
/// Connects to the BITS service and returns an instance of the <see cref="BackgroundCopyManager" /> class.
/// </summary>
/// <returns>
/// An instance of the <see cref="BackgroundCopyManager" /> class.
/// </returns>
/// <exception cref="COMException">The connection attempt to the BITS service failed.</exception>
/// <remarks>
/// The returned <see cref="BackgroundCopyManager"/> object implements the <see cref="IDisposable"/> interface.
/// Therefore you have to call <see cref="IDisposable.Dispose"/> to disconnect from the BITS service and to free all resources.
/// </remarks>
public static BackgroundCopyManager Connect() => new();
// ----------------
// CreateJob method
// ----------------
/// <summary>
/// Creates a transfer job.
/// </summary>
/// <param name="displayName">A string that contains a display name for the job.
/// Typically, the display name is used to identify the job in a user interface.
/// Note that more than one job may have the same display name.
/// Must not be <c>null</c>. The name is limited to 256 characters.</param>
/// <param name="type">The type of transfer job.</param>
/// <returns>
/// An instance of the <see cref="BackgroundCopyJob" /> class
/// that represent the newly created job.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="displayName" /> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
/// <exception cref="ObjectDisposedException">The method was called after the object was disposed.</exception>
/// <exception cref="BackgroundCopyException">An error occured during a BITS method call.</exception>
public BackgroundCopyJob CreateJob(string displayName, BackgroundCopyJobType type)
{
return displayName == null
? throw new ArgumentNullException(nameof(displayName))
: manager == null
? throw new ObjectDisposedException(nameof(BackgroundCopyManager))
: InvokeComMethod(() => new BackgroundCopyJob(this, manager.CreateJob(displayName, type, out var jobId)));
}
// --------------------
// EnumerateJobs method
// --------------------
/// <summary>
/// Enumerates the jobs in the transfer queue.
/// The order of the jobs in the enumerator is arbitrary.
/// </summary>
/// <param name="forAllUsers">
/// A value that indicates whether to include all jobs in the transfer queue
/// - those owned by the user and those owned by others.
/// The user must be an administrator when this flag is <c>true</c>.
/// </param>
/// <returns>
/// An enumerator to iterate through the list of
/// <see cref="BackgroundCopyJob" /> objects that represent the jobs in the queue.
/// </returns>
/// <exception cref="ObjectDisposedException">The method was called after the object was disposed.</exception>
/// <remarks>
/// <para>
/// The enumerator provides a snapshot of the jobs in the transfer queue
/// at the time you call the <c>EnumerateJobs</c> method.
/// If you retrieve property values from a job in the list, however,
/// the values reflect the current property values of the job.
/// </para>
/// <para>
/// Each <see cref="BackgroundCopyJob"/> object that is returned by the enumerator holds a reference to a COM interface
/// and implements the <see cref="IDisposable"/> intrface. Therefore you should call <see cref="IDisposable.Dispose"/>
/// when your are finished with it.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs">
/// using System;
/// using usis.Net.Bits;
///
/// namespace BitsTest
/// {
/// internal static class Sample
/// {
/// internal static void Main()
/// {
/// using (var manager = BackgroundCopyManager.Connect())
/// {
/// Console.WriteLine("BITS Version {0}", manager.Version);
/// Console.WriteLine();
///
/// // list all BITS jobs of the current user
/// foreach (var job in manager.EnumerateJobs(false))
/// {
/// Console.WriteLine("{0} '{1}' {2}", job.Id.ToString("B"), job.DisplayName, job.State.ToString());
/// job.Dispose();
/// }
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public IEnumerable<BackgroundCopyJob> EnumerateJobs(bool forAllUsers)
{
if (manager == null) throw new ObjectDisposedException(nameof(BackgroundCopyManager));
IEnumBackgroundCopyJobs? jobs = null;
try
{
jobs = manager.EnumJobs(forAllUsers ? Interop.Constants.BG_JOB_ENUM_ALL_USERS : 0);
while (jobs.Next(1, out var job, IntPtr.Zero) == HResult.Ok)
{
yield return new BackgroundCopyJob(this, job);
}
}
finally { if (jobs != null) _ = Marshal.ReleaseComObject(jobs); }
}
/// <summary>
/// Enumerates the jobs in the transfer queue for the current user.
/// </summary>
/// <returns>
/// An enumerator to iterate through the list of
/// <see cref="BackgroundCopyJob" /> objects that represent the jobs in the queue.
/// </returns>
/// <seealso cref="EnumerateJobs(bool)"/>
public IEnumerable<BackgroundCopyJob> EnumerateJobs() => EnumerateJobs(false);
// -------------
// GetJob method
// -------------
/// <summary>
/// Retrieves a given job from the transfer queue.
/// </summary>
/// <param name="jobId">A <see cref="Guid" /> that identifies the job to retrieve from the transfer queue.</param>
/// <param name="throwNotFoundException">If set to <c>true</c> an exception is thrown when the job was not found.</param>
/// <returns>
/// A <see cref="BackgroundCopyJob" /> object that represents the job specified by <paramref name="jobId" />.
/// </returns>
/// <exception cref="ObjectDisposedException">The method was called after the object was disposed.</exception>
/// <exception cref="BackgroundCopyException">An error occured during a BITS method call.</exception>
/// <remarks>
/// Typically, your application persists the job identifier,
/// so you can later retrieve the job from the queue.
/// </remarks>
public BackgroundCopyJob? GetJob(Guid jobId, bool throwNotFoundException)
{
if (manager == null) throw new ObjectDisposedException(nameof(BackgroundCopyManager));
var result = manager.GetJob(jobId, out var job);
return result == HResult.Ok
? new BackgroundCopyJob(this, job)
: result == HResult.BG_E_NOT_FOUND && !throwNotFoundException
? null
: throw new BackgroundCopyException(this, result);
}
/// <summary>
/// Retrieves a given job from the transfer queue.
/// </summary>
/// <param name="jobId">A <see cref="Guid" /> that identifies the job to retrieve from the transfer queue.</param>
/// <returns>
/// A <see cref="BackgroundCopyJob" /> object that represents the job specified by <paramref name="jobId" />.
/// </returns>
/// <exception cref="ObjectDisposedException">The method was called after the object was disposed.</exception>
/// <exception cref="BackgroundCopyException">An error occured during a BITS method call.</exception>
public BackgroundCopyJob? GetJob(Guid jobId) => GetJob(jobId, true);
// --------------------------
// GetErrorDescription method
// --------------------------
internal string GetErrorDescription(COMException exception) => (exception.ErrorCode & 0xFFFF0000) == 0x80200000 ? GetErrorDescription((uint)exception.ErrorCode) : exception.Message;
internal string GetErrorDescription(uint hResult) => GetErrorDescription(hResult, Thread.CurrentThread.CurrentCulture.LCID);
// ----------------------
// InvokeComMethod method
// ----------------------
internal T InvokeComMethod<T>(Func<T> method)
{
try { return method(); }
catch (COMException exception) { throw new BackgroundCopyException(this, exception); }
}
internal void InvokeComMethod(Action method)
{
try { method(); }
catch (COMException exception) { throw new BackgroundCopyException(this, exception); }
}
#endregion
#region private methods
// --------------------------
// GetErrorDescription method
// --------------------------
private string GetErrorDescription(uint hResult, int languageId)
{
if (manager == null) throw new ObjectDisposedException(nameof(BackgroundCopyManager));
var result = manager.GetErrorDescription(hResult, languageId, out var description);
return result == HResult.Ok
? description
: result == Win32Error.ERROR_MUI_FILE_NOT_LOADED
? GetErrorDescription(hResult, 0x0C00)
: throw new BackgroundCopyException(Strings.FailedErrorDescription, result);
}
// ---------------------------
// DetermineQMgrVersion method
// ---------------------------
private static Version? DetermineQMgrVersion()
{
const string QMgrFileName = "QMgr.dll";
var path = Path.Combine(Environment.SystemDirectory, QMgrFileName);
if (File.Exists(path))
{
var info = FileVersionInfo.GetVersionInfo(path);
return new Version(info.FileMajorPart, info.FileMinorPart);
}
return null;
}
// -----------------------
// DetermineVersion method
// -----------------------
private static Version? DetermineVersion()
{
var dictionary = new SortedDictionary<Version, Guid>
{
[new Version(10, 1)] = new Guid(CLSID.BackgroundCopyManager10_1),
[new Version(10, 0)] = new Guid(CLSID.BackgroundCopyManager10_0),
[new Version(5, 0)] = new Guid(CLSID.BackgroundCopyManager5_0),
[new Version(4, 0)] = new Guid(CLSID.BackgroundCopyManager4_0),
[new Version(3, 0)] = new Guid(CLSID.BackgroundCopyManager3_0),
[new Version(2, 5)] = new Guid(CLSID.BackgroundCopyManager2_5),
[new Version(2, 0)] = new Guid(CLSID.BackgroundCopyManager2_0),
[new Version(1, 5)] = new Guid(CLSID.BackgroundCopyManager1_5),
[new Version(1, 0)] = new Guid(CLSID.BackgroundCopyManager),
};
return dictionary.Keys.Reverse().FirstOrDefault(v => IsCLSIDRegistered(dictionary[v]));
}
// ------------------------
// IsCLSIDRegistered method
// ------------------------
private static bool IsCLSIDRegistered(Guid clsid)
{
var name = string.Format(CultureInfo.InvariantCulture, @"CLSID\{0}", clsid.ToString("B", CultureInfo.InvariantCulture));
using var registryKey = Registry.ClassesRoot.OpenSubKey(name);
return registryKey != null;
}
// ----------------------
// CreateComObject method
// ----------------------
private static TInterface CreateComObject<TInterface>(Guid clsid) where TInterface : class
{
var o = CreateComObject(clsid);
if (o is not TInterface i)
{
if (o is not null) _ = Marshal.FinalReleaseComObject(o);
throw new InvalidCastException();
}
else return i;
}
private static object? CreateComObject(Guid clsid) => CreateComObject(Type.GetTypeFromCLSID(clsid));
private static object? CreateComObject(Type? type)
{
object? @object = null;
try
{
if (type is not null) @object = Activator.CreateInstance(type);
}
catch (Exception)
{
if (@object != null) _ = Marshal.FinalReleaseComObject(@object);
throw;
}
return @object;
}
#endregion
}
}
// eof "BackgroundCopyManager.cs"