forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScheduledJobSourceAdapter.cs
More file actions
1084 lines (957 loc) · 34.8 KB
/
ScheduledJobSourceAdapter.cs
File metadata and controls
1084 lines (957 loc) · 34.8 KB
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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization;
namespace Microsoft.PowerShell.ScheduledJob
{
/// <summary>
/// This class provides functionality for retrieving scheduled job run results
/// from the scheduled job store. An instance of this object will be registered
/// with the PowerShell JobManager so that GetJobs commands will retrieve schedule
/// job runs from the file based scheduled job store. This allows scheduled job
/// runs to be managed from PowerShell in the same way workflow jobs are managed.
/// </summary>
public sealed class ScheduledJobSourceAdapter : JobSourceAdapter
{
#region Private Members
private static FileSystemWatcher StoreWatcher;
private static object SyncObject = new object();
private static ScheduledJobRepository JobRepository = new ScheduledJobRepository();
internal const string AdapterTypeName = "PSScheduledJob";
#endregion
#region Public Strings
/// <summary>
/// BeforeFilter
/// </summary>
public const string BeforeFilter = "Before";
/// <summary>
/// AfterFilter
/// </summary>
public const string AfterFilter = "After";
/// <summary>
/// NewestFilter
/// </summary>
public const string NewestFilter = "Newest";
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public ScheduledJobSourceAdapter()
{
Name = AdapterTypeName;
}
#endregion
#region JobSourceAdapter Implementation
/// <summary>
/// Create a new Job2 results instance.
/// </summary>
/// <param name="specification">Job specification</param>
/// <returns>Job2</returns>
public override Job2 NewJob(JobInvocationInfo specification)
{
if (specification == null)
{
throw new PSArgumentNullException("specification");
}
ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition(
specification, null, null, null);
return new ScheduledJob(
specification.Command,
specification.Name,
scheduledJobDef);
}
/// <summary>
/// Creates a new Job2 object based on a definition name
/// that can be run manually. If the path parameter is
/// null then a default location will be used to find the
/// job definition by name.
/// </summary>
/// <param name="definitionName">ScheduledJob definition name</param>
/// <param name="definitionPath">ScheduledJob definition file path</param>
/// <returns>Job2 object</returns>
public override Job2 NewJob(string definitionName, string definitionPath)
{
if (string.IsNullOrEmpty(definitionName))
{
throw new PSArgumentException("definitionName");
}
Job2 rtnJob = null;
try
{
ScheduledJobDefinition scheduledJobDef =
ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath);
rtnJob = new ScheduledJob(
scheduledJobDef.Command,
scheduledJobDef.Name,
scheduledJobDef);
}
catch (FileNotFoundException)
{
// Return null if no job definition exists.
}
return rtnJob;
}
/// <summary>
/// Get the list of jobs that are currently available in this
/// store
/// </summary>
/// <returns>Collection of job objects</returns>
public override IList<Job2> GetJobs()
{
RefreshRepository();
List<Job2> rtnJobs = new List<Job2>();
foreach (var job in JobRepository.Jobs)
{
rtnJobs.Add(job);
}
return rtnJobs;
}
/// <summary>
/// Get list of jobs that matches the specified names
/// </summary>
/// <param name="name">names to match, can support
/// wildcard if the store supports</param>
/// <param name="recurse"></param>
/// <returns>collection of jobs that match the specified
/// criteria</returns>
public override IList<Job2> GetJobsByName(string name, bool recurse)
{
if (string.IsNullOrEmpty(name))
{
throw new PSArgumentException("name");
}
RefreshRepository();
WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
List<Job2> rtnJobs = new List<Job2>();
foreach (var job in JobRepository.Jobs)
{
if (namePattern.IsMatch(job.Name))
{
rtnJobs.Add(job);
}
}
return rtnJobs;
}
/// <summary>
/// Get list of jobs that run the specified command
/// </summary>
/// <param name="command">command to match</param>
/// <param name="recurse"></param>
/// <returns>collection of jobs that match the specified
/// criteria</returns>
public override IList<Job2> GetJobsByCommand(string command, bool recurse)
{
if (string.IsNullOrEmpty(command))
{
throw new PSArgumentException("command");
}
RefreshRepository();
WildcardPattern commandPattern = new WildcardPattern(command, WildcardOptions.IgnoreCase);
List<Job2> rtnJobs = new List<Job2>();
foreach (var job in JobRepository.Jobs)
{
if (commandPattern.IsMatch(job.Command))
{
rtnJobs.Add(job);
}
}
return rtnJobs;
}
/// <summary>
/// Get job that has the specified id
/// </summary>
/// <param name="instanceId">Guid to match</param>
/// <param name="recurse"></param>
/// <returns>job with the specified guid</returns>
public override Job2 GetJobByInstanceId(Guid instanceId, bool recurse)
{
RefreshRepository();
foreach (var job in JobRepository.Jobs)
{
if (Guid.Equals(job.InstanceId, instanceId))
{
return job;
}
}
return null;
}
/// <summary>
/// Get job that has specific session id
/// </summary>
/// <param name="id">Id to match</param>
/// <param name="recurse"></param>
/// <returns>Job with the specified id</returns>
public override Job2 GetJobBySessionId(int id, bool recurse)
{
RefreshRepository();
foreach (var job in JobRepository.Jobs)
{
if (id == job.Id)
{
return job;
}
}
return null;
}
/// <summary>
/// Get list of jobs that are in the specified state
/// </summary>
/// <param name="state">state to match</param>
/// <param name="recurse"></param>
/// <returns>collection of jobs with the specified
/// state</returns>
public override IList<Job2> GetJobsByState(JobState state, bool recurse)
{
RefreshRepository();
List<Job2> rtnJobs = new List<Job2>();
foreach (var job in JobRepository.Jobs)
{
if (state == job.JobStateInfo.State)
{
rtnJobs.Add(job);
}
}
return rtnJobs;
}
/// <summary>
/// Get list of jobs based on the adapter specific
/// filter parameters
/// </summary>
/// <param name="filter">dictionary containing name value
/// pairs for adapter specific filters</param>
/// <param name="recurse"></param>
/// <returns>collection of jobs that match the
/// specified criteria</returns>
public override IList<Job2> GetJobsByFilter(Dictionary<string, object> filter, bool recurse)
{
if (filter == null)
{
throw new PSArgumentNullException("filter");
}
List<Job2> rtnJobs = new List<Job2>();
foreach (var filterItem in filter)
{
switch (filterItem.Key)
{
case BeforeFilter:
GetJobsBefore((DateTime)filterItem.Value, ref rtnJobs);
break;
case AfterFilter:
GetJobsAfter((DateTime)filterItem.Value, ref rtnJobs);
break;
case NewestFilter:
GetNewestJobs((int)filterItem.Value, ref rtnJobs);
break;
}
}
return rtnJobs;
}
/// <summary>
/// Remove a job from the store
/// </summary>
/// <param name="job">job object to remove</param>
public override void RemoveJob(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
RefreshRepository();
try
{
JobRepository.Remove(job);
ScheduledJobStore.RemoveJobRun(
job.Name,
job.PSBeginTime ?? DateTime.MinValue);
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
}
/// <summary>
/// Saves job to scheduled job run store.
/// </summary>
/// <param name="job">ScheduledJob</param>
public override void PersistJob(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
SaveJobToStore(job as ScheduledJob);
}
#endregion
#region Save Job
/// <summary>
/// Serializes a ScheduledJob and saves it to store.
/// </summary>
/// <param name="job">ScheduledJob</param>
internal static void SaveJobToStore(ScheduledJob job)
{
string outputPath = job.Definition.OutputPath;
if (string.IsNullOrEmpty(outputPath))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified,
job.Name);
throw new ScheduledJobException(msg);
}
FileStream fsStatus = null;
FileStream fsResults = null;
try
{
// Check the job store results and if maximum number of results exist
// remove the oldest results folder to make room for these new results.
CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength);
fsStatus = ScheduledJobStore.CreateFileForJobRunItem(
outputPath,
job.PSBeginTime ?? DateTime.MinValue,
ScheduledJobStore.JobRunItem.Status);
// Save status only in status file stream.
SaveStatusToFile(job, fsStatus);
fsResults = ScheduledJobStore.CreateFileForJobRunItem(
outputPath,
job.PSBeginTime ?? DateTime.MinValue,
ScheduledJobStore.JobRunItem.Results);
// Save entire job in results file stream.
SaveResultsToFile(job, fsResults);
}
finally
{
if (fsStatus != null)
{
fsStatus.Close();
}
if (fsResults != null)
{
fsResults.Close();
}
}
}
/// <summary>
/// Writes the job status information to the provided
/// file stream.
/// </summary>
/// <param name="job">ScheduledJob job to save</param>
/// <param name="fs">FileStream</param>
private static void SaveStatusToFile(ScheduledJob job, FileStream fs)
{
StatusInfo statusInfo = new StatusInfo(
job.InstanceId,
job.Name,
job.Location,
job.Command,
job.StatusMessage,
job.JobStateInfo.State,
job.HasMoreData,
job.PSBeginTime,
job.PSEndTime,
job.Definition);
XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
serializer.WriteObject(fs, statusInfo);
fs.Flush();
}
/// <summary>
/// Writes the job (which implements ISerializable) to the provided
/// file stream.
/// </summary>
/// <param name="job">ScheduledJob job to save</param>
/// <param name="fs">FileStream</param>
private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
{
XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
serializer.WriteObject(fs, job);
fs.Flush();
}
/// <summary>
/// Check the job store results and if maximum number of results exist
/// remove the oldest results folder to make room for these new results.
/// </summary>
/// <param name="outputPath">Output path</param>
/// <param name="executionHistoryLength">Maximum size of stored job results</param>
private static void CheckJobStoreResults(string outputPath, int executionHistoryLength)
{
// Get current results for this job definition.
Collection<DateTime> jobRuns = ScheduledJobStore.GetJobRunsForDefinitionPath(outputPath);
if (jobRuns.Count <= executionHistoryLength)
{
// There is room for another job run in the store.
return;
}
// Remove the oldest job run from the store.
DateTime jobRunToRemove = DateTime.MaxValue;
foreach (DateTime jobRun in jobRuns)
{
jobRunToRemove = (jobRun < jobRunToRemove) ? jobRun : jobRunToRemove;
}
try
{
ScheduledJobStore.RemoveJobRunFromOutputPath(outputPath, jobRunToRemove);
}
catch (UnauthorizedAccessException)
{ }
}
#endregion
#region Retrieve Job
/// <summary>
/// Finds and load the Job associated with this ScheduledJobDefinition object
/// having the job run date time provided.
/// </summary>
/// <param name="jobRun">DateTime of job run to load</param>
/// <param name="definitionName">ScheduledJobDefinition name</param>
/// <returns>Job2 job loaded from store</returns>
internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun)
{
FileStream fsResults = null;
Exception ex = null;
bool corruptedFile = false;
Job2 job = null;
try
{
// Results
fsResults = ScheduledJobStore.GetFileForJobRunItem(
definitionName,
jobRun,
ScheduledJobStore.JobRunItem.Results,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
job = LoadResultsFromFile(fsResults);
}
catch (ArgumentException e)
{
ex = e;
}
catch (DirectoryNotFoundException e)
{
ex = e;
}
catch (FileNotFoundException e)
{
ex = e;
corruptedFile = true;
}
catch (UnauthorizedAccessException e)
{
ex = e;
}
catch (IOException e)
{
ex = e;
}
catch (System.Runtime.Serialization.SerializationException)
{
corruptedFile = true;
}
catch (System.Runtime.Serialization.InvalidDataContractException)
{
corruptedFile = true;
}
catch (System.Xml.XmlException)
{
corruptedFile = true;
}
catch (System.TypeInitializationException)
{
corruptedFile = true;
}
finally
{
if (fsResults != null)
{
fsResults.Close();
}
}
if (corruptedFile)
{
// Remove the corrupted job results file.
ScheduledJobStore.RemoveJobRun(definitionName, jobRun);
}
if (ex != null)
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun);
throw new ScheduledJobException(msg, ex);
}
return job;
}
/// <summary>
/// Loads the Job2 object from provided files stream.
/// </summary>
/// <param name="fs">FileStream from which to read job object</param>
/// <returns>Created Job2 from file stream</returns>
private static Job2 LoadResultsFromFile(FileStream fs)
{
XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
return (Job2)serializer.ReadObject(fs);
}
#endregion
#region Static Methods
/// <summary>
/// Adds a Job2 object to the repository.
/// </summary>
/// <param name="job">Job2</param>
internal static void AddToRepository(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
JobRepository.AddOrReplace(job);
}
/// <summary>
/// Clears all items in the repository.
/// </summary>
internal static void ClearRepository()
{
JobRepository.Clear();
}
/// <summary>
/// Clears all items for given job definition name in the
/// repository.
/// </summary>
/// <param name="definitionName">Scheduled job definition name.</param>
internal static void ClearRepositoryForDefinition(string definitionName)
{
if (string.IsNullOrEmpty(definitionName))
{
throw new PSArgumentException("definitionName");
}
// This returns a new list object of repository jobs.
List<Job2> jobList = JobRepository.Jobs;
foreach (var job in jobList)
{
if (string.Compare(definitionName, job.Name,
StringComparison.OrdinalIgnoreCase) == 0)
{
JobRepository.Remove(job);
}
}
}
#endregion
#region Private Methods
private void RefreshRepository()
{
ScheduledJobStore.CreateDirectoryIfNotExists();
CreateFileSystemWatcher();
IEnumerable<string> jobDefinitions = ScheduledJobStore.GetJobDefinitions();
foreach (string definitionName in jobDefinitions)
{
// Create Job2 objects for each job run in store.
Collection<DateTime> jobRuns = GetJobRuns(definitionName);
if (jobRuns == null)
{
continue;
}
ScheduledJobDefinition definition = null;
foreach (DateTime jobRun in jobRuns)
{
if (jobRun > JobRepository.GetLatestJobRun(definitionName))
{
Job2 job;
try
{
if (definition == null)
{
definition = ScheduledJobDefinition.LoadFromStore(definitionName, null);
}
job = LoadJobFromStore(definition.Name, jobRun);
}
catch (ScheduledJobException)
{
continue;
}
catch (DirectoryNotFoundException)
{
continue;
}
catch (FileNotFoundException)
{
continue;
}
catch (UnauthorizedAccessException)
{
continue;
}
catch (IOException)
{
continue;
}
JobRepository.AddOrReplace(job);
JobRepository.SetLatestJobRun(definitionName, jobRun);
}
}
}
}
private void CreateFileSystemWatcher()
{
// Lazily create the static file system watcher
// on first use.
if (StoreWatcher == null)
{
lock (SyncObject)
{
if (StoreWatcher == null)
{
StoreWatcher = new FileSystemWatcher(ScheduledJobStore.GetJobDefinitionLocation());
StoreWatcher.IncludeSubdirectories = true;
StoreWatcher.NotifyFilter = NotifyFilters.LastWrite;
StoreWatcher.Filter = "Results.xml";
StoreWatcher.EnableRaisingEvents = true;
StoreWatcher.Changed += (object sender, FileSystemEventArgs e) =>
{
UpdateRepositoryObjects(e);
};
}
}
}
}
private static void UpdateRepositoryObjects(FileSystemEventArgs e)
{
// Extract job run information from change file path.
string updateDefinitionName;
DateTime updateJobRun;
if (!GetJobRunInfo(e.Name, out updateDefinitionName, out updateJobRun))
{
System.Diagnostics.Debug.Assert(false, "All job run updates should have valid directory names.");
return;
}
// Find corresponding job in repository.
ScheduledJob updateJob = JobRepository.GetJob(updateDefinitionName, updateJobRun);
if (updateJob == null)
{
return;
}
// Load updated job information from store.
Job2 job = null;
try
{
job = LoadJobFromStore(updateDefinitionName, updateJobRun);
}
catch (ScheduledJobException)
{ }
catch (DirectoryNotFoundException)
{ }
catch (FileNotFoundException)
{ }
catch (UnauthorizedAccessException)
{ }
catch (IOException)
{ }
// Update job in repository based on new job store data.
if (job != null)
{
updateJob.Update(job as ScheduledJob);
}
}
/// <summary>
/// Parses job definition name and job run DateTime from provided path string.
/// Example:
/// path = "ScheduledJob1\\Output\\20111219-200921-369\\Results.xml"
/// 'ScheduledJob1' is the definition name.
/// '20111219-200921-369' is the jobRun DateTime.
/// </summary>
/// <param name="path"></param>
/// <param name="definitionName"></param>
/// <param name="jobRunReturn"></param>
/// <returns></returns>
private static bool GetJobRunInfo(
string path,
out string definitionName,
out DateTime jobRunReturn)
{
// Parse definition name from path.
string[] pathItems = path.Split(System.IO.Path.DirectorySeparatorChar);
if (pathItems.Length == 4)
{
definitionName = pathItems[0];
return ScheduledJobStore.ConvertJobRunNameToDateTime(pathItems[2], out jobRunReturn);
}
definitionName = null;
jobRunReturn = DateTime.MinValue;
return false;
}
internal static Collection<DateTime> GetJobRuns(string definitionName)
{
Collection<DateTime> jobRuns = null;
try
{
jobRuns = ScheduledJobStore.GetJobRunsForDefinition(definitionName);
}
catch (DirectoryNotFoundException)
{ }
catch (FileNotFoundException)
{ }
catch (UnauthorizedAccessException)
{ }
catch (IOException)
{ }
return jobRuns;
}
private void GetJobsBefore(
DateTime dateTime,
ref List<Job2> jobList)
{
foreach (var job in JobRepository.Jobs)
{
if (job.PSEndTime < dateTime &&
!jobList.Contains(job))
{
jobList.Add(job);
}
}
}
private void GetJobsAfter(
DateTime dateTime,
ref List<Job2> jobList)
{
foreach (var job in JobRepository.Jobs)
{
if (job.PSEndTime > dateTime &&
!jobList.Contains(job))
{
jobList.Add(job);
}
}
}
private void GetNewestJobs(
int maxNumber,
ref List<Job2> jobList)
{
List<Job2> allJobs = JobRepository.Jobs;
// Sort descending.
allJobs.Sort((firstJob, secondJob) =>
{
if (firstJob.PSEndTime > secondJob.PSEndTime)
{
return -1;
}
else if (firstJob.PSEndTime < secondJob.PSEndTime)
{
return 1;
}
else
{
return 0;
}
});
int count = 0;
foreach (var job in allJobs)
{
if (++count > maxNumber)
{
break;
}
if (!jobList.Contains(job))
{
jobList.Add(job);
}
}
}
#endregion
#region Private Repository Class
/// <summary>
/// Collection of Job2 objects.
/// </summary>
internal class ScheduledJobRepository
{
#region Private Members
private object _syncObject = new object();
private Dictionary<Guid, Job2> _jobs = new Dictionary<Guid, Job2>();
private Dictionary<string, DateTime> _latestJobRuns = new Dictionary<string, DateTime>();
#endregion
#region Public Properties
/// <summary>
/// Returns all job objects in the repository as a List.
/// </summary>
public List<Job2> Jobs
{
get
{
lock (_syncObject)
{
return new List<Job2>(_jobs.Values);
}
}
}
/// <summary>
/// Returns count of jobs in repository.
/// </summary>
public int Count
{
get
{
lock (_syncObject)
{
return _jobs.Count;
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Add Job2 to repository.
/// </summary>
/// <param name="job">Job2 to add</param>
public void Add(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
lock (_syncObject)
{
if (_jobs.ContainsKey(job.InstanceId))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobAlreadyExistsInLocal, job.Name, job.InstanceId);
throw new ScheduledJobException(msg);
}
_jobs.Add(job.InstanceId, job);
}
}
/// <summary>
/// Add or replace passed in Job2 object to repository.
/// </summary>
/// <param name="job">Job2 to add</param>
public void AddOrReplace(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
lock (_syncObject)
{
if (_jobs.ContainsKey(job.InstanceId))
{
_jobs.Remove(job.InstanceId);
}
_jobs.Add(job.InstanceId, job);
}
}
/// <summary>
/// Remove Job2 from repository.
/// </summary>
/// <param name="job"></param>
public void Remove(Job2 job)
{
if (job == null)
{
throw new PSArgumentNullException("job");
}
lock (_syncObject)
{
if (_jobs.ContainsKey(job.InstanceId) == false)
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobNotInRepository, job.Name);
throw new ScheduledJobException(msg);
}
_jobs.Remove(job.InstanceId);
}
}
/// <summary>
/// Clears all Job2 items from the repository.
/// </summary>
public void Clear()
{
lock (_syncObject)
{
_jobs.Clear();
}
}
/// <summary>
/// Gets the latest job run Date/Time for the given definition name.
/// </summary>
/// <param name="definitionName">ScheduledJobDefinition name</param>
/// <returns>Job Run DateTime</returns>
public DateTime GetLatestJobRun(string definitionName)
{
if (string.IsNullOrEmpty(definitionName))
{