public HttpResponseMessage Get(int id) { using (var session = NHibernateHelper.CreateSessionFactory()) { using (var transaction = session.BeginTransaction()) { Renewal entity; if (id == 0) { entity = new Renewal(); } else { // collect objects var data = new List <Renewal>(session.CreateCriteria(typeof(Renewal)).List <Renewal>()); // collect single object entity = data.FirstOrDefault(x => x.Id == id); } // trim excess if (entity != null) { entity.Transactions.Clear(); entity.RenewalType = null; } // return as HttpResponseMessage return(WebApiHelper.ObjectToHttpResponseMessage(entity)); } } }
public async Task <ActionResult> Details(int?id) { #region USERVALIDATION token = (string)(Session["accessToken"]); string userID = (string)(Session["UserID"]); #endregion if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } List <Renewal> renewal = new List <Renewal>(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage Res = await client.GetAsync($"api/Renewals/{id}"); if (Res.IsSuccessStatusCode) { var RenewalResponse = Res.Content.ReadAsStringAsync().Result; Renewal myRenewal = JsonConvert.DeserializeObject <Renewal>(RenewalResponse); return(View(myRenewal)); } else { this.AddNotification("Unable to display Renewals information,please contact Administrator" + Res, NotificationType.ERROR); return(View()); } } }
/// <summary> /// Process a single renewal /// </summary> /// <param name="renewal"></param> internal async Task<bool?> ProcessRenewal(Renewal renewal, RunLevel runLevel) { var notification = _container.Resolve<NotificationService>(); try { var result = await _renewalExecutor.HandleRenewal(renewal, runLevel); if (!result.Abort) { _renewalStore.Save(renewal, result); if (result.Success) { await notification.NotifySuccess(renewal, _log.Lines); return true; } else { await notification.NotifyFailure(runLevel, renewal, result.ErrorMessages, _log.Lines); return false; } } else { return null; } } catch (Exception ex) { _exceptionHandler.HandleException(ex); await notification.NotifyFailure(runLevel, renewal, new List<string> { ex.Message }, _log.Lines); return false; } }
public async Task <ActionResult> Edit([Bind(Include = "ID,RenewalCode,RenewalName,RenewalEmail,RenewalPassword,OrganizationID,CreatedDate,isDeleted,TimeStamp")] Renewal renewal) { if (ModelState.IsValid) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage Res = await client.PutAsJsonAsync($"api/Renewals/{renewal.ID}", renewal); if (Res.IsSuccessStatusCode) { this.AddNotification("Renewals information modified successfully", NotificationType.SUCCESS); return(RedirectToAction("Index")); } else { this.AddNotification("Renewals information cannot be modified at this time. Please contact Administrator", NotificationType.ERROR); return(View()); } } } ViewBag.OrganizationID = await OrganizationSelectListByModel(token, renewal.OrganizationID); ViewBag.SubscriptionID = await SubscriptionSelectListByModel(token, renewal.SubscriptionID); return(View(renewal)); }
/// <summary> /// Process a single renewal /// </summary> /// <param name="renewal"></param> private void ProcessRenewal(Renewal renewal, RunLevel runLevel) { var notification = _container.Resolve <NotificationService>(); try { var result = Renew(renewal, runLevel); if (result != null) { _renewalService.Save(renewal, result); if (result.Success) { notification.NotifySuccess(runLevel, renewal); } else { notification.NotifyFailure(runLevel, renewal, result.ErrorMessage); } } } catch (Exception ex) { HandleException(ex); notification.NotifyFailure(runLevel, renewal, ex.Message); } }
/// <summary> /// For renewal and creating scheduled task /// </summary> /// <param name="target"></param> /// <param name="renewal"></param> /// <param name="runLevel"></param> /// <returns></returns> internal ILifetimeScope Execution(ILifetimeScope target, Renewal renewal, RunLevel runLevel) { return(target.BeginLifetimeScope(builder => { builder.Register(c => runLevel).As <RunLevel>(); // Used to configure TaskScheduler without renewal if (renewal != null) { builder.RegisterInstance(renewal); builder.RegisterInstance(renewal.StorePluginOptions).As(renewal.StorePluginOptions.GetType()); builder.RegisterInstance(renewal.CsrPluginOptions).As(renewal.CsrPluginOptions.GetType()); builder.RegisterInstance(renewal.ValidationPluginOptions).As(renewal.ValidationPluginOptions.GetType()); builder.RegisterInstance(renewal.TargetPluginOptions).As(renewal.TargetPluginOptions.GetType()); // Find factory based on options builder.Register(x => { var plugin = x.Resolve <PluginService>(); var match = plugin.ValidationPluginFactories(target).FirstOrDefault(vp => vp.OptionsType.PluginId() == renewal.ValidationPluginOptions.Plugin); return match; }).As <IValidationPluginOptionsFactory>().SingleInstance(); builder.RegisterType(renewal.CsrPluginOptions.Instance).As <ICsrPlugin>().SingleInstance(); builder.RegisterType(renewal.StorePluginOptions.Instance).As <IStorePlugin>().SingleInstance(); builder.RegisterType(renewal.ValidationPluginOptions.Instance).As <IValidationPlugin>().SingleInstance(); builder.RegisterType(renewal.TargetPluginOptions.Instance).As <ITargetPlugin>().SingleInstance(); foreach (var i in renewal.InstallationPluginOptions) { builder.RegisterInstance(i).As(i.GetType()); } } })); }
/// <summary> /// Show certificate details /// </summary> private async Task ShowRenewal(Renewal renewal) { try { _input.Show("Id", renewal.Id, true); _input.Show("File", $"{renewal.Id}.renewal.json"); _input.Show("FriendlyName", string.IsNullOrEmpty(renewal.FriendlyName) ? $"[Auto] {renewal.LastFriendlyName}" : renewal.FriendlyName); _input.Show(".pfx password", renewal.PfxPassword?.Value); _input.Show("Renewal due", renewal.GetDueDate()?.ToString() ?? "now"); _input.Show("Renewed", $"{renewal.History.Where(x => x.Success).Count()} times"); renewal.TargetPluginOptions.Show(_input); renewal.ValidationPluginOptions.Show(_input); if (renewal.CsrPluginOptions != null) { renewal.CsrPluginOptions.Show(_input); } foreach (var ipo in renewal.StorePluginOptions) { ipo.Show(_input); } foreach (var ipo in renewal.InstallationPluginOptions) { ipo.Show(_input); } _input.Show("History"); await _input.WritePagedList(renewal.History.Select(x => Choice.Create(x))); } catch (Exception ex) { _log.Error(ex, "Unable to list details for target"); } }
public void Save(Renewal renewal, RenewResult result) { var renewals = Renewals.ToList(); if (renewal.New) { renewal.History = new List <RenewResult>(); renewals.Add(renewal); _log.Information(true, "Adding renewal for {target}", renewal.FriendlyName); } else if (result.Success) { _log.Information(true, "Renewal for {host} succeeded", renewal.FriendlyName); } else { _log.Error("Renewal for {host} failed, will retry on next run", renewal.FriendlyName); } // Set next date renewal.History.Add(result); if (result.Success) { _log.Information(true, "Next renewal scheduled at {date}", renewal.Date.ToUserString()); } renewal.Updated = true; Renewals = renewals; }
internal ILifetimeScope Execution(ILifetimeScope target, Renewal renewal, RunLevel runLevel) { return(target.BeginLifetimeScope(builder => { builder.RegisterType <AcmeClient>().SingleInstance(); builder.RegisterType <CertificateService>().SingleInstance(); builder.RegisterType <TaskSchedulerService>().SingleInstance(); builder.Register(c => runLevel).As <RunLevel>(); // Used to configure TaskScheduler without renewal if (renewal != null) { builder.RegisterInstance(renewal); builder.RegisterInstance(renewal.StorePluginOptions).As(renewal.StorePluginOptions.GetType()); builder.RegisterInstance(renewal.CsrPluginOptions).As(renewal.CsrPluginOptions.GetType()); builder.RegisterInstance(renewal.ValidationPluginOptions).As(renewal.ValidationPluginOptions.GetType()); builder.RegisterInstance(renewal.TargetPluginOptions).As(renewal.TargetPluginOptions.GetType()); builder.RegisterType(renewal.CsrPluginOptions.Instance).As <ICsrPlugin>().SingleInstance(); builder.RegisterType(renewal.StorePluginOptions.Instance).As <IStorePlugin>().SingleInstance(); builder.RegisterType(renewal.ValidationPluginOptions.Instance).As <IValidationPlugin>().SingleInstance(); builder.RegisterType(renewal.TargetPluginOptions.Instance).As <ITargetPlugin>().SingleInstance(); foreach (var i in renewal.InstallationPluginOptions) { builder.RegisterInstance(i).As(i.GetType()); } } })); }
public async Task <IHttpActionResult> PutRenewal(int id, Renewal renewal) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != renewal.ID) { return(BadRequest()); } db.Entry(renewal).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RenewalExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
/// <summary> /// If renewal is already Scheduled, replace it with the new options /// </summary> /// <param name="target"></param> /// <returns></returns> private Renewal CreateRenewal(Renewal temp, RunLevel runLevel) { var renewal = _renewalService.FindByFriendlyName(temp.LastFriendlyName).FirstOrDefault(); if (renewal == null) { return(temp); } var overwrite = false; if (runLevel.HasFlag(RunLevel.Interactive)) { overwrite = _input.PromptYesNo($"Renewal with FriendlyName {temp.LastFriendlyName} already exists, overwrite?", true); } else { overwrite = true; } if (overwrite) { _log.Warning("Overwriting previously created renewal"); renewal.Updated = true; renewal.TargetPluginOptions = temp.TargetPluginOptions; renewal.CsrPluginOptions = temp.CsrPluginOptions; renewal.StorePluginOptions = temp.StorePluginOptions; renewal.ValidationPluginOptions = temp.ValidationPluginOptions; renewal.InstallationPluginOptions = temp.InstallationPluginOptions; return(renewal); } else { return(temp); } }
public void ConvertStore(LegacyScheduledRenewal legacy, Renewal ret) { // Configure store if (!string.IsNullOrEmpty(legacy.CentralSslStore)) { ret.StorePluginOptions.Add(new store.CentralSslOptions() { Path = legacy.CentralSslStore, KeepExisting = legacy.KeepExisting == true }); } else { ret.StorePluginOptions.Add(new store.CertificateStoreOptions() { StoreName = legacy.CertificateStore, KeepExisting = legacy.KeepExisting == true }); } ret.StorePluginOptions.Add(new store.PemFilesOptions() { Path = _settings.Cache.Path }); ret.StorePluginOptions.Add(new store.PfxFileOptions() { Path = _settings.Cache.Path }); }
private void TestScript(string script, string parameters) { log = new Mock.Services.LogService(true); var renewal = new Renewal(); var storeOptions = new CertificateStoreOptions(); var store = new CertificateStore(log, iis, storeOptions); var oldCert = cs.RequestCertificate(null, RunLevel.Unattended, renewal, new Target() { CommonName = "test.local" }, null); var newCert = cs.RequestCertificate(null, RunLevel.Unattended, renewal, new Target() { CommonName = "test.local" }, null); newCert.StoreInfo.Add(typeof(CertificateStore), new StoreInfo() { }); var options = new ScriptOptions { Script = script, ScriptParameters = parameters }; var installer = new Script(renewal, options, log); installer.Install(new[] { store }, newCert, oldCert); }
private void TestScript(string script, string parameters) { var renewal = new Renewal(); var storeOptions = new CertificateStoreOptions(); var settings = new MockSettingsService(); var iisClient = new Mock.Clients.MockIISClient(log); var userRoleService = new UserRoleService(iisClient); var store = new CertificateStore(log, iis, settings, userRoleService, storeOptions); var oldCert = cs.RequestCertificate(null, RunLevel.Unattended, renewal, new Target() { CommonName = "test.local" }, null).Result; var newCert = cs.RequestCertificate(null, RunLevel.Unattended, renewal, new Target() { CommonName = "test.local" }, null).Result; newCert.StoreInfo.Add(typeof(CertificateStore), new StoreInfo() { }); var options = new ScriptOptions { Script = script, ScriptParameters = parameters }; var installer = new Script(renewal, options, new Clients.ScriptClient(log, settings)); installer.Install(new[] { store }, newCert, oldCert).Wait(); }
/// <summary> /// Process a single renewal /// </summary> /// <param name="renewal"></param> private void ProcessRenewal(Renewal renewal, RunLevel runLevel) { try { // Let the plugin run var result = Renew(renewal, runLevel); if (result != null) { _renewalService.Save(renewal, result); if (result.Success) { NotifySuccess(runLevel, renewal); } else { NotifyFailure(runLevel, renewal, result.ErrorMessage); } } } catch (Exception ex) { HandleException(ex); NotifyFailure(runLevel, renewal, ex.Message); } }
/// <summary> /// Process a single renewal /// </summary> /// <param name="renewal"></param> internal async Task ProcessRenewal(Renewal renewal, RunLevel runLevel) { var notification = _container.Resolve <NotificationService>(); try { var result = await _renewalExecutor.Execute(renewal, runLevel); if (result != null) { _renewalStore.Save(renewal, result); if (result.Success) { notification.NotifySuccess(runLevel, renewal); } else { notification.NotifyFailure(runLevel, renewal, result.ErrorMessage); } } } catch (Exception ex) { _exceptionHandler.HandleException(ex); notification.NotifyFailure(runLevel, renewal, ex.Message); } }
private RenewResult Renew(Renewal renewal, RunLevel runLevel) { using (var ts = _scopeBuilder.Target(_container, renewal, runLevel)) using (var es = _scopeBuilder.Execution(ts, renewal, runLevel)) { var targetPlugin = es.Resolve <ITargetPlugin>(); var client = es.Resolve <AcmeClient>(); var target = targetPlugin.Generate(); if (target == null) { throw new Exception($"Target plugin did not generate a target"); } if (!target.IsValid(_log)) { throw new Exception($"Target plugin generated an invalid target"); } var identifiers = target.GetHosts(false); // Create the order var order = client.CreateOrder(identifiers); // Check if the order is valid if (order.Payload.Status != _orderReady && order.Payload.Status != _orderPending) { return(OnRenewFail(new Challenge() { Error = order.Payload.Error })); } // Answer the challenges foreach (var authUrl in order.Payload.Authorizations) { // Get authorization details var authorization = client.GetAuthorizationDetails(authUrl); // Find a targetPart that matches the challenge var targetPart = target.Parts. FirstOrDefault(tp => tp.GetHosts(false). Any(h => authorization.Identifier.Value == h.Replace("*.", ""))); if (targetPart == null) { return(OnRenewFail(new Challenge() { Error = "Unable to match challenge to target" })); } // Run the validation plugin var challenge = Authorize(es, runLevel, order, renewal.ValidationPluginOptions, targetPart, authorization); if (challenge.Status != _authorizationValid) { return(OnRenewFail(challenge)); } } return(OnRenewSuccess(es, renewal, target, order, runLevel)); } }
public void ConvertInstallation(LegacyScheduledRenewal legacy, Renewal ret) { if (legacy.InstallationPluginNames == null) { legacy.InstallationPluginNames = new List <string>(); // Based on chosen target if (legacy.Binding.TargetPluginName == "IISSite" || legacy.Binding.TargetPluginName == "IISSites" || legacy.Binding.TargetPluginName == "IISBinding") { legacy.InstallationPluginNames.Add("IIS"); } // Based on command line if (!string.IsNullOrEmpty(legacy.Script) || !string.IsNullOrEmpty(legacy.ScriptParameters)) { legacy.InstallationPluginNames.Add("Manual"); } // Cannot find anything, then it's no installation steps if (legacy.InstallationPluginNames.Count == 0) { legacy.InstallationPluginNames.Add("None"); } } foreach (var legacyName in legacy.InstallationPluginNames) { switch (legacyName.ToLower()) { case "iis": ret.InstallationPluginOptions.Add(new install.IISWebOptions() { SiteId = legacy.Binding.InstallationSiteId, NewBindingIp = legacy.Binding.SSLIPAddress, NewBindingPort = legacy.Binding.SSLPort }); break; case "iisftp": ret.InstallationPluginOptions.Add(new install.IISFtpOptions() { SiteId = legacy.Binding.FtpSiteId.Value }); break; case "manual": ret.InstallationPluginOptions.Add(new install.ScriptOptions() { Script = legacy.Script, ScriptParameters = legacy.ScriptParameters }); break; case "none": ret.InstallationPluginOptions.Add(new NullInstallationOptions()); break; } } }
public void Import(Renewal renewal) { var renewals = Renewals.ToList(); renewals.Add(renewal); _log.Information(true, "Importing renewal for {target}", renewal.FriendlyName); Renewals = renewals; }
/// <summary> /// Delete cached files related to a specific renewal /// </summary> /// <param name="renewal"></param> private void ClearCache(Renewal renewal, string prefix = "*", string postfix = "*") { foreach (var f in _cache.GetFiles($"{prefix}{renewal.Id}{postfix}")) { _log.Verbose("Deleting {file} from certificate cache @ {folder}", f.Name, _cache.FullName); f.Delete(); } }
/// <summary> /// Delete cached files related to a specific renewal /// </summary> /// <param name="renewal"></param> private void ClearCache(Renewal renewal) { foreach (var f in _cache.GetFiles($"*{renewal.Id}*")) { _log.Verbose("Deleting {file} from cache", f.Name); f.Delete(); } }
public void Import(Renewal renewal) { var renewals = Renewals.ToList(); renewals.Add(renewal); _log.Information(LogType.All, "Importing renewal for {friendlyName}", renewal.LastFriendlyName); Renewals = renewals; }
// This method has been replaced by RenewMembership (above), to handle the entire membership type, instead of just the amount public void Renew(Renewal renewal) { this._tracer.Trace("Method: MembershipService.Renew: MembershipNumber={0}, Amount={1}", renewal.MembershipNumber, renewal.Amount); try { if (!string.IsNullOrEmpty(renewal.MembershipNumber)) { var sdk = ConnectionController.ConnectToCrm(this._tracer); if (sdk != null) { MembershipController mc = new MembershipController(sdk, this._tracer); bool renewed = mc.RenewMembership(renewal); this._tracer.Trace("mc.RenewMembership={0}", renewed); if (!renewed) { throw new Exception("Unable to renew the membership, this might be because the membership is in an invalid state."); } } else { string message = "Unable to connect to CRM. Check web.config"; this._tracer.Trace(message); throw new Exception(message); } } else { throw new Exception("Invalid input. The Member cannot be null for a Membership"); } } catch (FaultException <OrganizationServiceFault> fe) { if (fe.Detail != null) { this._tracer.Trace(fe.Detail.ToString()); } this._tracer.Trace(fe.ToString()); string reference = renewal.MembershipNumber; throw new WebFaultException <Error>(ConvertToError(fe, reference), HttpStatusCode.InternalServerError); } catch (Exception ex) { this._tracer.Trace(ex.ToString()); string reference = renewal.MembershipNumber; throw new WebFaultException <Error>(ConvertToError(ex, reference), HttpStatusCode.InternalServerError); } finally { // write to the log file this._tracer.WriteToLog(this._logPath); } }
public async Task <ActionResult> DeleteConfirmed(int id) { Renewal renewal = await db.Renewals.FindAsync(id); db.Renewals.Remove(renewal); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
/// <summary> /// Constructor /// </summary> /// <param name="log"></param> /// <param name="input"></param> /// <param name="options"></param> /// <param name="proxy"></param> /// <param name="renewal"></param> /// <param name="target"></param> /// <param name="runLevel"></param> /// <param name="identifier"></param> public HttpValidation(TOptions options, HttpValidationParameters pars) : base(pars.LogService, options, pars.Identifier) { _input = pars.InputService; _proxy = pars.ProxyService; _renewal = pars.Renewal; _targetPart = pars.TargetPart; _path = options.Path; }
/// <summary> /// Get the most recent thumbprint /// </summary> /// <returns></returns> public static string Thumbprint(this Renewal renewal) { return(renewal. History?. OrderByDescending(x => x.Date). Where(x => x.Success). Select(x => x.Thumbprint). FirstOrDefault()); }
public void ConvertTarget(LegacyScheduledRenewal legacy, Renewal ret) { if (string.IsNullOrEmpty(legacy.Binding.TargetPluginName)) { switch (legacy.Binding.PluginName) { case "IIS": legacy.Binding.TargetPluginName = legacy.Binding.HostIsDns == false ? "IISSite" : "IISBinding"; break; case "IISSiteServer": legacy.Binding.TargetPluginName = "IISSites"; break; case "Manual": legacy.Binding.TargetPluginName = "Manual"; break; } } switch (legacy.Binding.TargetPluginName.ToLower()) { case "iissite": ret.TargetPluginOptions = new target.IISSiteOptions() { CommonName = string.IsNullOrEmpty(legacy.Binding.CommonName) ? null : legacy.Binding.CommonName, ExcludeBindings = legacy.Binding.ExcludeBindings.ParseCsv(), SiteId = legacy.Binding.TargetSiteId ?? legacy.Binding.SiteId ?? 0 }; break; case "iissites": ret.TargetPluginOptions = new target.IISSitesOptions() { CommonName = string.IsNullOrEmpty(legacy.Binding.CommonName) ? null : legacy.Binding.CommonName, ExcludeBindings = legacy.Binding.ExcludeBindings.ParseCsv(), SiteIds = legacy.Binding.Host.ParseCsv().Select(x => long.Parse(x)).ToList() }; break; case "manual": ret.TargetPluginOptions = new target.ManualOptions() { CommonName = string.IsNullOrEmpty(legacy.Binding.CommonName) ? legacy.Binding.Host : legacy.Binding.CommonName, AlternativeNames = legacy.Binding.AlternativeNames }; break; case "iisbinding": ret.TargetPluginOptions = new target.IISBindingOptions() { Host = legacy.Binding.Host, SiteId = (long)(legacy.Binding.TargetSiteId ?? legacy.Binding.SiteId) }; break; } }
private RenewResult Renew(Renewal renewal, RunLevel runLevel) { using (var ts = _scopeBuilder.Target(_container, renewal, runLevel)) using (var es = _scopeBuilder.Execution(ts, renewal, runLevel)) { var targetPlugin = es.Resolve <ITargetPlugin>(); var client = es.Resolve <AcmeClient>(); var target = targetPlugin.Generate(); if (target == null) { throw new Exception($"Target plugin did not generate a target"); } if (!target.IsValid(_log)) { throw new Exception($"Target plugin generated an invalid target"); } var identifiers = target.GetHosts(false); // Create the order var order = client.CreateOrder(identifiers); // Check if the order is valid if (order.Payload.Status != _orderReady && order.Payload.Status != _orderPending) { return(OnRenewFail(new Challenge() { Error = order.Payload.Error })); } var authorizations = new List <Authorization>(); foreach (var authUrl in order.Payload.Authorizations) { authorizations.Add(client.GetAuthorizationDetails(authUrl)); } foreach (var targetPart in target.Parts) { foreach (var identifier in targetPart.GetHosts(false)) { var rootIdentifier = identifier; if (identifier.StartsWith("*.")) { rootIdentifier = identifier.Substring(2); } var authorization = authorizations.FirstOrDefault(a => a.Identifier.Value == rootIdentifier); var challenge = Authorize(es, runLevel, order, renewal.ValidationPluginOptions, targetPart, authorization); if (challenge.Status != _authorizationValid) { return(OnRenewFail(challenge)); } } } return(OnRenewSuccess(es, renewal, target, order, runLevel)); } }
/// <summary> /// Read from the disk cache /// </summary> /// <param name="renewal"></param> /// <returns></returns> public CertificateInfo?CachedInfo(Renewal renewal, Target?target = null) { var nameAll = GetPath(renewal, $"*{PfxPostFix}"); var directory = new DirectoryInfo(Path.GetDirectoryName(nameAll)); var allPattern = Path.GetFileName(nameAll); var allFiles = directory.GetFiles(allPattern); if (!allFiles.Any()) { return(null); } FileInfo?fileCache = null; if (target != null) { var key = CacheKey(renewal, target); var keyName = Path.GetFileName(GetPath(renewal, $"-{key}{PfxPostFix}")); var keyFile = allFiles.Where(x => x.Name == keyName).FirstOrDefault(); if (keyFile != null) { fileCache = keyFile; } else { var legacyName = Path.GetFileName(GetPath(renewal, PfxPostFix)); var legacyFile = allFiles.Where(x => x.Name == legacyName).FirstOrDefault(); if (legacyFile != null) { var legacyInfo = FromCache(legacyFile, renewal.PfxPassword?.Value); if (Match(legacyInfo, target)) { fileCache = legacyFile; } } } } else { fileCache = allFiles.OrderByDescending(x => x.LastWriteTime).FirstOrDefault(); } if (fileCache != null) { try { return(FromCache(fileCache, renewal.PfxPassword?.Value)); } catch { // File corrupt or invalid password? _log.Warning("Unable to read from certificate cache"); } } return(null); }
public void DomainSplit() { var parts = new TargetPart[] { new TargetPart(new[] { new DnsIdentifier("x.com") }) }; var target = new Target("x.com", "x.com", parts); var renewal = new Renewal(); var container = new MockContainer().TestScope(); var domain = container.Resolve <Domain>(); var split = domain.Split(renewal, target); Assert.IsNotNull(split); }