22// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33
44using System ;
5- using System . Collections . Concurrent ;
65using System . Collections . Generic ;
76using System . ComponentModel . Design ;
8- using System . Data . SqlClient ;
97using System . Linq ;
108using System . Net ;
119using System . Net . Mail ;
1210using System . Threading ;
1311using System . Threading . Tasks ;
12+ using Autofac ;
1413using Gallery . CredentialExpiration . Models ;
14+ using Microsoft . Extensions . Configuration ;
15+ using Microsoft . Extensions . DependencyInjection ;
1516using Microsoft . Extensions . Logging ;
17+ using Microsoft . Extensions . Options ;
1618using Microsoft . WindowsAzure . Storage ;
1719using Newtonsoft . Json ;
18- using Newtonsoft . Json . Linq ;
1920using NuGet . Jobs ;
20- using NuGet . Services . KeyVault ;
21- using NuGet . Services . Sql ;
2221using NuGet . Services . Storage ;
2322
2423namespace Gallery . CredentialExpiration
2524{
26- public class Job : JobBase
25+ public class Job : JsonConfigurationJob
2726 {
2827 private readonly TimeSpan _defaultCommandTimeout = TimeSpan . FromMinutes ( 30 ) ;
2928
3029 private readonly string _cursorFile = "cursorv2.json" ;
3130
32- private bool _whatIf = false ;
31+ private InitializationConfiguration Configuration { get ; set ; }
3332
34- private string _galleryBrand ;
35- private string _galleryAccountUrl ;
33+ private Storage Storage { get ; set ; }
3634
37- private ISqlConnectionFactory _galleryDatabase ;
38-
39- private string _mailFrom ;
40- private SmtpClient _smtpClient ;
41-
42- private int _warnDaysBeforeExpiration = 10 ;
43-
44- private Storage _storage ;
35+ private SmtpClient SmtpClient { get ; set ; }
4536
4637 public override void Init ( IServiceContainer serviceContainer , IDictionary < string , string > jobArgsDictionary )
4738 {
48- _whatIf = JobConfigurationManager . TryGetBoolArgument ( jobArgsDictionary , JobArgumentNames . WhatIf ) ;
49-
50- var secretInjector = ( ISecretInjector ) serviceContainer . GetService ( typeof ( ISecretInjector ) ) ;
51- var databaseConnectionString = JobConfigurationManager . GetArgument ( jobArgsDictionary , JobArgumentNames . GalleryDatabase ) ;
52- _galleryDatabase = new AzureSqlConnectionFactory ( databaseConnectionString , secretInjector ) ;
53-
54- _galleryBrand = JobConfigurationManager . GetArgument ( jobArgsDictionary , MyJobArgumentNames . GalleryBrand ) ;
55- _galleryAccountUrl = JobConfigurationManager . GetArgument ( jobArgsDictionary , MyJobArgumentNames . GalleryAccountUrl ) ;
39+ base . Init ( serviceContainer , jobArgsDictionary ) ;
5640
57- _mailFrom = JobConfigurationManager . GetArgument ( jobArgsDictionary , JobArgumentNames . MailFrom ) ;
41+ Configuration = _serviceProvider . GetRequiredService < IOptionsSnapshot < InitializationConfiguration > > ( ) . Value ;
5842
59- var smtpConnectionString = JobConfigurationManager . GetArgument ( jobArgsDictionary , JobArgumentNames . SmtpUri ) ;
60- var smtpUri = new SmtpUri ( new Uri ( smtpConnectionString ) ) ;
61- _smtpClient = CreateSmtpClient ( smtpUri ) ;
62-
63- _warnDaysBeforeExpiration = JobConfigurationManager . TryGetIntArgument ( jobArgsDictionary , MyJobArgumentNames . WarnDaysBeforeExpiration )
64- ?? _warnDaysBeforeExpiration ;
65-
66- var storageConnectionString = JobConfigurationManager . GetArgument ( jobArgsDictionary , JobArgumentNames . DataStorageAccount ) ;
67- var storageContainerName = JobConfigurationManager . GetArgument ( jobArgsDictionary , JobArgumentNames . ContainerName ) ;
68-
69- var storageAccount = CloudStorageAccount . Parse ( storageConnectionString ) ;
70- var storageFactory = new AzureStorageFactory ( storageAccount , storageContainerName , LoggerFactory ) ;
71- _storage = storageFactory . Create ( ) ;
43+ SmtpClient = CreateSmtpClient ( Configuration . SmtpUri ) ;
44+
45+ var storageAccount = CloudStorageAccount . Parse ( Configuration . DataStorageAccount ) ;
46+ var storageFactory = new AzureStorageFactory ( storageAccount , Configuration . ContainerName , LoggerFactory ) ;
47+ Storage = storageFactory . Create ( ) ;
7248 }
7349
7450 public override async Task Run ( )
7551 {
7652 var jobRunTime = DateTimeOffset . UtcNow ;
7753 // Default values
7854 var jobCursor = new JobRunTimeCursor ( jobCursorTime : jobRunTime , maxProcessedCredentialsTime : jobRunTime ) ;
79- var galleryCredentialExpiration = new GalleryCredentialExpiration ( new CredentialExpirationJobMetadata ( jobRunTime , _warnDaysBeforeExpiration , jobCursor ) , _galleryDatabase ) ;
55+ var galleryCredentialExpiration = new GalleryCredentialExpiration ( this ,
56+ new CredentialExpirationJobMetadata ( jobRunTime , Configuration . WarnDaysBeforeExpiration , jobCursor ) ) ;
8057
8158 try
8259 {
8360 List < ExpiredCredentialData > credentialsInRange = null ;
8461
8562 // Get the most recent date for the emails being sent
86- if ( _storage . Exists ( _cursorFile ) )
63+ if ( Storage . Exists ( _cursorFile ) )
8764 {
88- string content = await _storage . LoadString ( _storage . ResolveUri ( _cursorFile ) , CancellationToken . None ) ;
65+ string content = await Storage . LoadString ( Storage . ResolveUri ( _cursorFile ) , CancellationToken . None ) ;
8966 // Load from cursor
9067 // Throw if the schema is not correct to ensure that not-intended emails are sent.
91- jobCursor = JsonConvert . DeserializeObject < JobRunTimeCursor > ( content , new JsonSerializerSettings ( ) { MissingMemberHandling = MissingMemberHandling . Error } ) ;
92- galleryCredentialExpiration = new GalleryCredentialExpiration ( new CredentialExpirationJobMetadata ( jobRunTime , _warnDaysBeforeExpiration , jobCursor ) , _galleryDatabase ) ;
68+ jobCursor = JsonConvert . DeserializeObject < JobRunTimeCursor > (
69+ content ,
70+ new JsonSerializerSettings ( ) { MissingMemberHandling = MissingMemberHandling . Error } ) ;
71+
72+ galleryCredentialExpiration = new GalleryCredentialExpiration ( this ,
73+ new CredentialExpirationJobMetadata ( jobRunTime , Configuration . WarnDaysBeforeExpiration , jobCursor ) ) ;
9374 }
9475
9576 // Connect to database
@@ -126,10 +107,13 @@ public override async Task Run()
126107 }
127108 finally
128109 {
129- JobRunTimeCursor newCursor = new JobRunTimeCursor ( jobCursorTime : jobRunTime , maxProcessedCredentialsTime : galleryCredentialExpiration . GetMaxNotificationDate ( ) ) ;
110+ JobRunTimeCursor newCursor = new JobRunTimeCursor (
111+ jobCursorTime : jobRunTime ,
112+ maxProcessedCredentialsTime : galleryCredentialExpiration . GetMaxNotificationDate ( ) ) ;
113+
130114 string json = JsonConvert . SerializeObject ( newCursor ) ;
131115 var content = new StringStorageContent ( json , "application/json" ) ;
132- await _storage . Save ( _storage . ResolveUri ( _cursorFile ) , content , CancellationToken . None ) ;
116+ await Storage . Save ( Storage . ResolveUri ( _cursorFile ) , content , CancellationToken . None ) ;
133117 }
134118 }
135119
@@ -146,7 +130,7 @@ private async Task HandleExpiredCredentialEmail(string username, List<ExpiredCre
146130
147131 // Build message
148132 var userEmail = credentialList . FirstOrDefault ( ) . EmailAddress ;
149- var mailMessage = new MailMessage ( _mailFrom , userEmail ) ;
133+ var mailMessage = new MailMessage ( Configuration . MailFrom , userEmail ) ;
150134
151135 var apiKeyExpiryMessageList = credentialList
152136 . Select ( x => BuildApiKeyExpiryMessage ( x . Description , x . Expires , jobRunTime ) )
@@ -156,21 +140,21 @@ private async Task HandleExpiredCredentialEmail(string username, List<ExpiredCre
156140 // Build email body
157141 if ( expired )
158142 {
159- mailMessage . Subject = string . Format ( Strings . ExpiredEmailSubject , _galleryBrand ) ;
160- mailMessage . Body = string . Format ( Strings . ExpiredEmailBody , username , _galleryBrand , apiKeyExpiryMessage , _galleryAccountUrl ) ;
143+ mailMessage . Subject = string . Format ( Strings . ExpiredEmailSubject , Configuration . GalleryBrand ) ;
144+ mailMessage . Body = string . Format ( Strings . ExpiredEmailBody , username , Configuration . GalleryBrand , apiKeyExpiryMessage , Configuration . GalleryAccountUrl ) ;
161145 }
162146 else
163147 {
164- mailMessage . Subject = string . Format ( Strings . ExpiringEmailSubject , _galleryBrand ) ;
165- mailMessage . Body = string . Format ( Strings . ExpiringEmailBody , username , _galleryBrand , apiKeyExpiryMessage , _galleryAccountUrl ) ;
148+ mailMessage . Subject = string . Format ( Strings . ExpiringEmailSubject , Configuration . GalleryBrand ) ;
149+ mailMessage . Body = string . Format ( Strings . ExpiringEmailBody , username , Configuration . GalleryBrand , apiKeyExpiryMessage , Configuration . GalleryAccountUrl ) ;
166150 }
167151
168152 // Send email
169153 try
170154 {
171- if ( ! _whatIf ) // if WhatIf is passed, we will not send e-mails (e.g. dev/int don't have to annoy users)
155+ if ( ! Configuration . WhatIf ) // if WhatIf is passed, we will not send e-mails (e.g. dev/int don't have to annoy users)
172156 {
173- await _smtpClient . SendMailAsync ( mailMessage ) ;
157+ await SmtpClient . SendMailAsync ( mailMessage ) ;
174158 }
175159
176160 Logger . LogInformation ( "Handled {Expired} credential ." ,
@@ -200,9 +184,10 @@ private static string BuildApiKeyExpiryMessage(string description, DateTimeOffse
200184 // \u2022 - Unicode for bullet point.
201185 return "\u2022 " + message + Environment . NewLine ;
202186 }
203-
204- private SmtpClient CreateSmtpClient ( SmtpUri smtpUri )
187+
188+ private SmtpClient CreateSmtpClient ( string smtpUriString )
205189 {
190+ var smtpUri = new SmtpUri ( new Uri ( smtpUriString ) ) ;
206191 var smtpClient = new SmtpClient ( smtpUri . Host , smtpUri . Port )
207192 {
208193 EnableSsl = smtpUri . Secure
@@ -218,5 +203,14 @@ private SmtpClient CreateSmtpClient(SmtpUri smtpUri)
218203
219204 return smtpClient ;
220205 }
206+
207+ protected override void ConfigureAutofacServices ( ContainerBuilder containerBuilder )
208+ {
209+ }
210+
211+ protected override void ConfigureJobServices ( IServiceCollection services , IConfigurationRoot configurationRoot )
212+ {
213+ ConfigureInitializationSection < InitializationConfiguration > ( services , configurationRoot ) ;
214+ }
221215 }
222216}
0 commit comments