-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundCopyJob.cs
1200 lines (950 loc) · 44.1 KB
/
BackgroundCopyJob.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// @(#) BackgroundCopyJob.cs
//
// Project: usis.Net.Bits
// System: Microsoft Visual Studio 2022
// Author: Udo Schäfer
//
// Copyright (c) 2017-2023 usis GmbH. All rights reserved.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using usis.Net.Bits.Interop;
namespace usis.Net.Bits
{
// -----------------------
// BackgroundCopyJob class
// -----------------------
/// <summary>
/// Provides methods and properties to add files to the job,
/// set the priority level of the job,
/// determine the state of the job, and to start and stop the job.
/// </summary>
/// <seealso cref="IDisposable" />
public sealed class BackgroundCopyJob : IDisposable, INotifyPropertyChanged
{
#region fields
private IBackgroundCopyJob? interop;
private Callback? callback;
#endregion
#region construction
// ------------
// construction
// ------------
internal BackgroundCopyJob(BackgroundCopyManager manager, IBackgroundCopyJob i)
{
Manager = manager;
interop = i ?? throw new ArgumentNullException(nameof(i));
HttpOptions = new BackgroundCopyJobHttpOptions(this);
}
#endregion
#region IDisposable implementation
// --------------
// Dispose method
// --------------
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (interop != null)
{
// free unmanaged resources
if (callback != null)
{
var hr = interop.SetNotifyInterface(null);
if (HResult.Succeeded(hr) || hr == HResult.RPC_E_DISCONNECTED) callback = null;
}
_ = Marshal.ReleaseComObject(interop);
interop = null;
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizes an instance of the <see cref="BackgroundCopyJob"/> class.
/// </summary>
~BackgroundCopyJob() { Dispose(); } // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
#endregion
#region properties
#region public properties
// -----------
// Id property
// -----------
/// <summary>
/// Gets the identifier of the job in the queue.
/// </summary>
/// <value>
/// The identifier of the job in the queue.
/// </value>
public Guid Id => Manager.InvokeComMethod(Interface.GetId);
// --------------------
// DisplayName property
// --------------------
/// <summary>
/// Gets or sets the display name that identifies the job.
/// </summary>
/// <value>
/// The display name that identifies the job.
/// </value>
public string DisplayName
{
get => Manager.InvokeComMethod(Interface.GetDisplayName);
set => Manager.InvokeComMethod(() => Interface.SetDisplayName(value));
}
// --------------------
// Description property
// --------------------
/// <summary>
/// Gets or sets the description of the job.
/// </summary>
/// <value>
/// The description of the job.
/// </value>
public string Description
{
get => Manager.InvokeComMethod(Interface.GetDescription);
set => Manager.InvokeComMethod(() => Interface.SetDescription(value));
}
// ----------------
// JobType property
// ----------------
/// <summary>
/// Gets the type of transfer being performed, such as a file download or upload.
/// </summary>
/// <value>
/// The type of transfer being performed, such as a file download or upload.
/// </value>
public BackgroundCopyJobType JobType => Manager.InvokeComMethod(Interface.GetType);
// -----------------
// Priority property
// -----------------
/// <summary>
/// Gets or sets the priority level for the job.
/// </summary>
/// <value>
/// The priority level for the job.
/// </value>
/// <remarks>
/// The priority level determines when the job is processed relative to other jobs in the transfer queue.
/// </remarks>
public BackgroundCopyJobPriority Priority
{
get => Manager.InvokeComMethod(Interface.GetPriority);
set => Manager.InvokeComMethod(() => Interface.SetPriority(value));
}
// --------------
// State property
// --------------
/// <summary>
/// Gets the state of the job.
/// </summary>
/// <value>
/// The state of the job.
/// </value>
public BackgroundCopyJobState State => Manager.InvokeComMethod(Interface.GetState);
// --------------
// Owner property
// --------------
/// <summary>
/// Gets the identity of the job's owner.
/// </summary>
/// <value>
/// The identity of the job's owner.
/// </value>
public string Owner => Manager.InvokeComMethod(Interface.GetOwner);
// --------------------------
// MinimumRetryDelay property
// --------------------------
/// <summary>
/// Gets or sets the minimum length of time that BITS waits after encountering
/// a transient error condition before trying to transfer the file.
/// </summary>
/// <value>
/// Length of time, in seconds, that the service waits after encountering
/// a transient error before trying to transfer the file.
/// </value>
/// <remarks>
/// The default retry delay is 600 seconds (10 minutes).
/// The minimum retry delay that you can specify is 5 seconds.
/// If you specify a value less than 5 seconds, BITS changes the value to 5 seconds.
/// If the value exceeds the no-progress-timeout value set by the <see cref="NoProgressTimeout"/> property,
/// BITS will not retry the transfer and moves the job to the <see cref="BackgroundCopyJobState.Error"/> state.
/// </remarks>
public int MinimumRetryDelay
{
get => Manager.InvokeComMethod(Interface.GetMinimumRetryDelay);
set => Manager.InvokeComMethod(() => Interface.SetMinimumRetryDelay(value));
}
// --------------------------
// NoProgressTimeout property
// --------------------------
/// <summary>
/// Gets or sets the length of time that BITS tries to transfer the file
/// after a transient error condition occurs. If there is progress, the timer is reset.
/// </summary>
/// <value>
/// Length of time, in seconds, that the service tries to transfer the file after a transient error occurs.
/// </value>
public int NoProgressTimeout
{
get => Manager.InvokeComMethod(Interface.GetNoProgressTimeout);
set => Manager.InvokeComMethod(() => Interface.SetNoProgressTimeout(value));
}
// ----------------------
// Notifications property
// ----------------------
/// <summary>
/// Gets the event notification flags for your application.
/// </summary>
/// <value>
/// The event notification flags for your application.
/// </value>
public BackgroundCopyJobNotifications Notifications
{
get => Manager.InvokeComMethod(GetNotifyFlags);
private set => Manager.InvokeComMethod(() => Interface.SetNotifyFlags(value));
}
// -------------------
// ErrorCount property
// -------------------
/// <summary>
/// Gets the number of times BITS tried to transfer the job and an error occurred.
/// </summary>
/// <value>
/// The number of times BITS tried to transfer the job and an error occurred.
/// </value>
public int ErrorCount => Manager.InvokeComMethod(Interface.GetErrorCount);
// ----------------------
// ProxySettings property
// ----------------------
/// <summary>
/// Gets or sets the proxy information that the job uses to transfer the files.
/// </summary>
/// <value>
/// The proxy information that the job uses to transfer the files.
/// </value>
public BackgroundCopyJobProxySettings ProxySettings
{
get => RetrieveProxySettings();
set => SetProxySettings(value);
}
// --------------------------
// NotifyCommandLine property
// --------------------------
/// <summary>
/// Gets or sets the program to execute when the job enters the error or transferred state.
/// </summary>
/// <value>
/// The program to execute when the job enters the error or transferred state.
/// </value>
public BackgroundCopyNotifyCommandLine NotifyCommandLine
{
get => Manager.InvokeComMethod(() =>
{
Interface2.GetNotifyCmdLine(out var program, out var parameters);
return new BackgroundCopyNotifyCommandLine(program, parameters);
});
set => Manager.InvokeComMethod(() =>
{
if (value == null) Interface2.SetNotifyCmdLine(null, null);
else Interface2.SetNotifyCmdLine(value.Program, value.Parameters);
});
}
// ----------------------
// ReplyFileName property
// ----------------------
/// <summary>
/// Gets or sets the name of the file to contain the reply data of an upload-reply job.
/// </summary>
/// <value>
/// The name of the file to contain the reply data of an upload-reply job.
/// </value>
public string? ReplyFileName
{
get
{
var hr = Interface2.GetReplyFileName(out var replyFileName);
return hr == HResult.Ok ? replyFileName : null;
}
set => Manager.InvokeComMethod(() => Interface2.SetReplyFileName(value));
}
// ----------------
// FileAcl property
// ----------------
/// <summary>
/// Gets or sets the flags that identify the owner and ACL information to maintain when transferring a file using SMB.
/// </summary>
/// <value>
/// The flags that identify the owner and ACL information to maintain when transferring a file using SMB.
/// </value>
public BackgroundCopyJobFileAclOptions FileAcl
{
get => (BackgroundCopyJobFileAclOptions)Interface3.GetFileACLFlags();
set => Interface3.SetFileACLFlags(Convert.ToUInt32(value, CultureInfo.InvariantCulture));
}
// --------------------
// HttpOptions property
// --------------------
/// <summary>
/// Gets the HTTP options to specify client certificates for certificate-based client authentication
/// and custom headers for HTTP requests.
/// </summary>
/// <value>
/// The HTTP options.
/// </value>
public BackgroundCopyJobHttpOptions HttpOptions { get; }
// -----------------------------
// PeerCachingOptions properties
// -----------------------------
/// <summary>
/// Gets or sets options that determine if the files of the job can be cached
/// and served to peers and if BITS can download content for the job from peers.
/// </summary>
/// <value>
/// Options that determine if the files of the job can be cached and served to peers
/// and if BITS can download content for the job from peers.
/// </value>
public BackgroundCopyJobPeerCachingOptions PeerCachingOptions
{
get => Manager.InvokeComMethod(Interface4.GetPeerCachingFlags);
set => Manager.InvokeComMethod(() => Interface4.SetPeerCachingFlags(value));
}
// ----------------------------
// MaximumDownloadTime property
// ----------------------------
/// <summary>
/// Gets or sets the maximum time that BITS will spend transferring the files in the job.
/// </summary>
/// <value>
/// The maximum time that BITS will spend transferring the files in the job.
/// </value>
public int MaximumDownloadTime
{
get => Manager.InvokeComMethod(() => Convert.ToInt32(Interface4.GetMaximumDownloadTime()));
set => Manager.InvokeComMethod(() => Interface4.SetMaximumDownloadTime(Convert.ToUInt32(value)));
}
// ----------------------------
// OwnerElevationState property
// ----------------------------
/// <summary>
/// Gets a value that determines if the token of the owner was elevated at the time they created or took ownership of the job.
/// </summary>
/// <value>
/// <c>true</c> if the token of the owner was elevated at the time they created or took ownership of the job; otherwise, <c>false</c>.
/// </value>
public bool OwnerElevationState => Manager.InvokeComMethod(Interface4.GetOwnerElevationState);
// ----------------------------
// OwnerIntegrityLevel property
// ----------------------------
/// <summary>
/// Gets the integrity level of the token of the owner that created or took ownership of the job.
/// </summary>
/// <value>
/// The integrity level of the token of the owner that created or took ownership of the job.
/// </value>
public int OwnerIntegrityLevel => Convert.ToInt32(Manager.InvokeComMethod(Interface4.GetOwnerIntegrityLevel));
#endregion
#region private properties
// ----------------
// Manager property
// ----------------
internal BackgroundCopyManager Manager { get; }
// ------------------
// Interface property
// ------------------
private IBackgroundCopyJob Interface => interop ?? throw new ObjectDisposedException(nameof(BackgroundCopyJob));
// -------------------
// Interface2 property
// -------------------
private IBackgroundCopyJob2 Interface2 => Extensions.QueryInterface<IBackgroundCopyJob2>(Interface);
// -------------------
// Interface3 property
// -------------------
private IBackgroundCopyJob3 Interface3 => Extensions.QueryInterface<IBackgroundCopyJob3>(Interface);
// -------------------
// Interface4 property
// -------------------
private IBackgroundCopyJob4 Interface4 => Extensions.QueryInterface<IBackgroundCopyJob4>(Interface);
// -----------------------------
// HttpOptionsInterface property
// -----------------------------
internal IBackgroundCopyJobHttpOptions HttpOptionsInterface => Extensions.QueryInterface<IBackgroundCopyJobHttpOptions>(Interface);
#endregion
#endregion
#region events
#region Failed event
// ------------
// Failed event
// ------------
private EventHandler<BackgroundCopyErrorEventArgs>? failedHandler;
/// <summary>
/// Occurs when the state of the job changes to <see cref="BackgroundCopyJobState.Error"/>.
/// </summary>
/// <remarks>
/// BITS implements job notifications by callbacks.
/// When an event handler is added or removed a corresponding callback interface is set.
/// If the access to set a notification callback is denied an exception is <b>not</b> thrown
/// and the event handler is added anyway.
/// Use the <see cref="Notifications"/> property to check what notifications you receive.
/// </remarks>
public event EventHandler<BackgroundCopyErrorEventArgs> Failed
{
add
{
if (CheckCallback()) Notifications |= BackgroundCopyJobNotifications.Error;
failedHandler += value;
}
remove => RemoveEvent(failedHandler, BackgroundCopyJobNotifications.Error, value);
}
// ---------------
// OnFailed method
// ---------------
private uint OnFailed(IBackgroundCopyError error)
{
using var e = new BackgroundCopyError(Manager, error);
return InvokeHandler(failedHandler, new BackgroundCopyErrorEventArgs(e));
}
#endregion
#region Modified event
// --------------
// Modified event
// --------------
private EventHandler<EventArgs>? modifiedHandler;
/// <summary>
/// Occurs when a job is modified.
/// </summary>
/// <remarks>
/// BITS implements job notifications by callbacks.
/// When an event handler is added or removed a corresponding callback interface is set.
/// If the access to set a notification callback is denied an exception is <b>not</b> thrown
/// and the event handler is added anyway.
/// Use the <see cref="Notifications"/> property to check what notifications you receive.
/// </remarks>
public event EventHandler<EventArgs> Modified
{
add
{
if (CheckCallback()) Notifications |= BackgroundCopyJobNotifications.Modification;
modifiedHandler += value;
}
remove => RemoveEvent(modifiedHandler, BackgroundCopyJobNotifications.Modification, value);
}
private uint OnModified() => InvokeHandler(modifiedHandler, EventArgs.Empty);
#endregion
#region Transferred event
// -----------------
// Transferred event
// -----------------
private EventHandler<EventArgs>? transferredHandler;
/// <summary>
/// Occurs when all of the files in the job have successfully transferred.
/// </summary>
/// <remarks>
/// BITS implements job notifications by callbacks.
/// When an event handler is added or removed a corresponding callback interface is set.
/// If the access to set a notification callback is denied an exception is <b>not</b> thrown
/// and the event handler is added anyway.
/// Use the <see cref="Notifications"/> property to check what notifications you receive.
/// </remarks>
public event EventHandler<EventArgs> Transferred
{
add
{
if (CheckCallback()) Notifications |= BackgroundCopyJobNotifications.Transferred;
transferredHandler += value;
}
remove => RemoveEvent(transferredHandler, BackgroundCopyJobNotifications.Transferred, value);
}
private uint OnTransferred() => InvokeHandler(transferredHandler, EventArgs.Empty);
#endregion
#region FileTransferred event
// ---------------------
// FileTransferred event
// ---------------------
private EventHandler<BackgroundCopyFileEventArgs>? fileTransferredHandler;
/// <summary>
/// Occurs when BITS successfully finishes transferring a file.
/// </summary>
public event EventHandler<BackgroundCopyFileEventArgs> FileTransferred
{
add
{
if (CheckCallback()) Notifications |= BackgroundCopyJobNotifications.FileTransferred;
fileTransferredHandler += value;
}
remove => RemoveEvent(fileTransferredHandler, BackgroundCopyJobNotifications.FileTransferred, value);
}
// ------------------------
// OnFileTransferred method
// ------------------------
private uint OnFileTransferred(IBackgroundCopyFile file)
{
using var f = new BackgroundCopyFile(Manager, file);
return InvokeHandler(fileTransferredHandler, new BackgroundCopyFileEventArgs(f));
}
#endregion
#region PropertyChanged event
// ---------------------
// PropertyChanged event
// ---------------------
private PropertyChangedEventHandler? propertyChangedHandler;
event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged
{
add
{
propertyChangedHandler += value;
Modified += OnPropertyChanged;
}
remove
{
Modified -= OnPropertyChanged;
propertyChangedHandler -= value;
}
}
// ------------------------
// OnPropertyChanged method
// ------------------------
private void OnPropertyChanged(object? sender, EventArgs e)
=> propertyChangedHandler?.Invoke(sender, new PropertyChangedEventArgs(string.Empty));
#endregion
#endregion
#region methods
#region public methods
// -------------
// Cancel method
// -------------
/// <summary>
/// Deletes the job from the transfer queue and removes related temporary files
/// from the client (downloads) and server (uploads).
/// </summary>
public void Cancel() => Manager.InvokeComMethod(Interface.Cancel);
// ---------------
// Complete method
// ---------------
/// <summary>
/// Ends the job and saves the transferred files on the client.
/// </summary>
public void Complete() => Manager.InvokeComMethod(Interface.Complete);
// --------------
// Suspend method
// --------------
/// <summary>
/// Suspends a job. New jobs, jobs that are in error,
/// and jobs that have finished transferring files are automatically suspended.
/// </summary>
public void Suspend() => Manager.InvokeComMethod(Interface.Suspend);
// -------------
// Resume method
// -------------
/// <summary>
/// Activates a new job or restarts a job that has been suspended.
/// </summary>
public void Resume() => Manager.InvokeComMethod(Interface.Resume);
// ---------------------
// EnumerateFiles method
// ---------------------
/// <summary>
/// Enumerates the files in the job.
/// </summary>
/// <returns>
/// An enumerator that is used to iterate the files in the job.
/// </returns>
/// <exception cref="ObjectDisposedException">The method was called after the object was disposed.</exception>
public IEnumerable<BackgroundCopyFile> EnumerateFiles()
{
if (interop == null) throw new ObjectDisposedException(nameof(BackgroundCopyJob));
IEnumBackgroundCopyFiles? files = null;
try
{
files = interop.EnumFiles();
while (files.Next(1, out var file, IntPtr.Zero) == HResult.Ok)
{
try { yield return new BackgroundCopyFile(Manager, file); }
finally { _ = Marshal.ReleaseComObject(file); }
}
}
finally { if (files != null) _ = Marshal.ReleaseComObject(files); }
}
// -----------------------
// RetrieveProgress method
// -----------------------
/// <summary>
/// Retrieves job-related progress information, such as the number of bytes and files transferred.
/// </summary>
/// <returns>
/// A <see cref="BackgroundCopyJobProgress"/> object that contains data that you can use
/// to calculate the percentage of the job that is complete.
/// </returns>
public BackgroundCopyJobProgress RetrieveProgress() => new(Interface.GetProgress());
// ----------------------------
// RetrieveReplyProgress method
// ----------------------------
/// <summary>
/// Retrieves progress information that indicates how many bytes of the reply file have been downloaded to the client.
/// </summary>
/// <returns>
/// A <see cref="BackgroundCopyJobReplyProgress"/> object that contains information that you use
/// to calculate the percentage of the reply file transfer that is complete.
/// </returns>
public BackgroundCopyJobReplyProgress RetrieveReplyProgress() => new(Manager.InvokeComMethod(Interface2.GetReplyProgress));
// --------------------
// RetrieveTimes method
// --------------------
/// <summary>
/// Retrieves job-related time stamps, such as the time that the job was created or last modified.
/// </summary>
/// <returns>
/// A <c>BackgroundCopyJobTimes</c> structure that contains job-related time stamps.
/// </returns>
public BackgroundCopyJobTimes RetrieveTimes() => new(Interface.GetTimes());
// --------------
// AddFile method
// --------------
/// <summary>
/// Adds a single file to the job.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
public void AddFile(string remoteUrl, string localName) => AddFile(new Uri(remoteUrl), localName);
/// <summary>
/// Adds a single file to the job.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
public void AddFile(Uri remoteUrl, string localName) => Manager.InvokeComMethod(() => Interface.AddFile(remoteUrl.ToString(), localName));
/// <summary>
/// Adds a file to a download job and specifies the range of the file you want to download.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
/// <param name="offset">Zero-based offset to the beginning of the range of bytes to download from a file.</param>
/// <param name="length">The length of the range, in bytes. Do not specify a zero byte length.
/// To indicate that the range extends to the end of the file, specify <see cref="Constants.LengthToEndOfFile" />.</param>
public void AddFile(string remoteUrl, string localName, long offset, long length) => AddFile(new Uri(remoteUrl), localName, offset, length);
/// <summary>
/// Adds a file to a download job and specifies the range of the file you want to download.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
/// <param name="offset">Zero-based offset to the beginning of the range of bytes to download from a file.</param>
/// <param name="length">The length of the range, in bytes. Do not specify a zero byte length.
/// To indicate that the range extends to the end of the file, specify <see cref="Constants.LengthToEndOfFile" />.</param>
public void AddFile(Uri remoteUrl, string localName, long offset, long length) => AddFile(remoteUrl, localName, new BackgroundCopyFileRange(offset, length));
/// <summary>
/// Adds a file to a download job and specifies the ranges of the file you want to download.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
/// <param name="ranges">An array of one or more <see cref="BackgroundCopyFileRange" /> structures that specify the ranges to download.
/// Do not specify duplicate or overlapping ranges.</param>
public void AddFile(string remoteUrl, string localName, params BackgroundCopyFileRange[] ranges) => AddFile(new Uri(remoteUrl), localName, ranges);
/// <summary>
/// Adds a file to a download job and specifies the ranges of the file you want to download.
/// </summary>
/// <param name="remoteUrl">The URL of the file on the server.</param>
/// <param name="localName">The name of the file on the client.</param>
/// <param name="ranges">An array of one or more <see cref="BackgroundCopyFileRange" /> structures that specify the ranges to download.
/// Do not specify duplicate or overlapping ranges.</param>
public void AddFile(Uri remoteUrl, string localName, params BackgroundCopyFileRange[] ranges)
{
var fileRanges = ranges.Select(r => r.ToFileRange()).ToArray();
Manager.InvokeComMethod(() => Interface3.AddFileWithRanges(remoteUrl.ToString(), localName, Convert.ToUInt32(fileRanges.Length), fileRanges));
}
// ---------------
// AddFiles method
// ---------------
/// <summary>
/// Adds multiple files to the job.
/// </summary>
/// <param name="files">The files to add to the job.</param>
/// <example>
/// The following sample creates a job and adds three files to it.
/// <code language="cs">
/// using usis.Net.Bits;
///
/// namespace BitsTest
/// {
/// internal static class Sample
/// {
/// internal static void Main()
/// {
/// using (var manager = BackgroundCopyManager.Connect())
/// {
/// using (var job = manager.CreateJob("Test", BackgroundCopyJobType.Download))
/// {
/// job.AddFiles(
/// new BackgroundCopyFileInfo { RemoteName = "http://localhost/bits1", LocalName = @"C:\tmp\test1.dat" },
/// new BackgroundCopyFileInfo { RemoteName = "http://localhost/bits2", LocalName = @"C:\tmp\test2.dat" },
/// new BackgroundCopyFileInfo { RemoteName = "http://localhost/bits3", LocalName = @"C:\tmp\test3.dat" });
/// job.Resume();
/// }
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public void AddFiles(params BackgroundCopyFileInfo[] files) => Manager.InvokeComMethod(() => Interface.AddFileSet(files.Length, [.. files.Select(e => e.fileInfo)]));
// --------------------
// TakeOwnership method
// --------------------
/// <summary>
/// Changes ownership of the job to the current user.
/// </summary>
public void TakeOwnership() => Manager.InvokeComMethod(Interface.TakeOwnership);
// --------------------
// RetrieveError method
// --------------------
/// <summary>
/// Retrieves error informations after an error occurs.
/// </summary>
/// <returns>
/// An object that provides error informations.
/// </returns>
public BackgroundCopyError? RetrieveError() => RetrieveError(false);
// ------------------------
// RetrieveReplyData method
// ------------------------
/// <summary>
/// Retrieves the reply data from the server application.
/// </summary>
/// <returns>
/// The reply data from the server application.
/// </returns>
/// <exception cref="BackgroundCopyException">Failed to retrieve reply data.</exception>
public byte[] RetrieveReplyData()
{
var hr = Interface2.GetReplyData(out var buffer, out var lenght);
if (HResult.Succeeded(hr))
{
var data = new byte[lenght];
Marshal.Copy(buffer, data, 0, (int)lenght);
Marshal.FreeCoTaskMem(buffer);
return data;
}
else throw new BackgroundCopyException(Manager, hr);
}
// ---------------------
// SetCredentials method
// ---------------------
/// <summary>
/// Specifies the credentials to use for a proxy or remote server user authentication request.
/// </summary>
/// <param name="target">Identifies whether to use the credentials for a proxy or server authentication request.</param>
/// <param name="scheme">Identifies the scheme to use for authentication (for example, Basic or NTLM).</param>
/// <param name="userName">
/// The user name to authenticate. The user name is limited to 300 characters, not including the null terminator.
/// The format of the user name depends on the authentication scheme requested.
/// For example, for Basic, NTLM, and Negotiate authentication, the user name is of the form <i>DomainName\UserName</i>.
/// For Passport authentication, the user name is an email address.
/// </param>
/// <param name="password">
/// The password in plaintext. The password is limited to 65536 characters,
/// not including the null terminator. The password can be blank. Set it to <c>null</c> if <b>UserName</b> is <c>null</c>.
/// BITS encrypts the password before persisting the job if a network disconnect occurs or the user logs off.
/// </param>
public void SetCredentials(BackgroundCopyAuthenticationTarget target, BackgroundCopyAuthenticationScheme scheme, string userName, string password)
{
Manager.InvokeComMethod(() => Interface2.SetCredentials(new BG_AUTH_CREDENTIALS()
{
Target = target,
Scheme = scheme,
UserName = userName,
Password = password
}));
}
// ------------------------
// RemoveCredentials method
// ------------------------
/// <summary>
/// Removes credentials set by the <see cref="SetCredentials"/> method.
/// </summary>
/// <param name="target">Identifies whether to use the credentials for proxy or server authentication.</param>
/// <param name="scheme">Identifies the authentication scheme to use (basic or one of several challenge-response schemes).</param>
public void RemoveCredentials(BackgroundCopyAuthenticationTarget target, BackgroundCopyAuthenticationScheme scheme) => Manager.InvokeComMethod(() => Interface2.RemoveCredentials(target, scheme));
// --------------------------
// ReplaceRemotePrefix method
// --------------------------
/// <summary>
/// Replaces the beginning text of all remote names in the download job with the specified string.
/// </summary>
/// <param name="oldPrefix">Identifies the text to replace in the remote name. The text must start at the beginning of the remote name.</param>
/// <param name="newPrefix">The replacement text.</param>
public void ReplaceRemotePrefix(string oldPrefix, string newPrefix) => Manager.InvokeComMethod(() => Interface3.ReplaceRemotePrefix(oldPrefix, newPrefix));
#endregion
#region private methods
// ----------------------------
// RetrieveProxySettings method
// ----------------------------
/// <summary>
/// Retrieves the proxy information that the job uses to transfer the files.
/// </summary>
/// <returns>
/// A <c>BackgroundCopyJobProxySettings</c> class with the proxy settings.
/// </returns>
private BackgroundCopyJobProxySettings RetrieveProxySettings()
{
Interface.GetProxySettings(out var usage, out var list, out var bypassList);
return new BackgroundCopyJobProxySettings(usage, list, bypassList);
}
// -----------------------
// SetProxySettings method
// -----------------------
/// <summary>
/// Specifies which proxy to use to transfer files.
/// </summary>