public async Task <DeployStrategyResult> DeployAsync(BuildResult buildResult, CustomLogger customLogger) { var info = buildResult.Target.DeploymentExtraInfo as IISDeployTargetExtraInfo; if (IISDeployTargetExtraInfo.Validate(info) == false) { return(new DeployStrategyResult(string.Empty, true)); } return(await Task.Run(() => { try { using (var manager = new ServerManager()) { customLogger.Information("Current sites installed:"); var currentSites = manager.Sites; foreach (var item in currentSites) { customLogger.Information(item.Name); } customLogger.Information(string.Empty); // Find out if the site exists already. var site = manager.Sites.FirstOrDefault(x => x.Name == info.SiteName); if (site == null) { site = manager.Sites.Add(info.SiteName, buildResult.OutputPath, info.Port); manager.CommitChanges(); } else { site.Stop(); site.Applications["/"].VirtualDirectories["/"].PhysicalPath = buildResult.OutputPath; manager.CommitChanges(); site.Start(); } } return new DeployStrategyResult(string.Empty, false); } catch (Exception exp) { customLogger.Error(exp); return new DeployStrategyResult(string.Empty, true); } })); }
public Task <RepositoryImportResult> ImportAsync(Project entity, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, CustomLogger runnerLogger, string commitId = null) { return(Task.Run(() => { var folderName = $"{entity.Name}_{DateTime.UtcNow.Ticks}"; var path = Path.Combine(appConfiguration.BaseDirectory, folderName); var info = authInfo as AuthInfo; if (info == null) { return new RepositoryImportResult(string.Empty, true); } try { Directory.CreateDirectory(path); using (var client = new SharpSvn.SvnClient()) { client.Authentication.DefaultCredentials = new NetworkCredential(info.Username, info.Password); runnerLogger.Information("Checking out..."); bool result = false; if (commitId == null) { result = client.CheckOut(new SharpSvn.SvnUriTarget(entity.RepositoryUrl), path); } else { result = client.CheckOut(new SharpSvn.SvnUriTarget(entity.RepositoryUrl), path, new SharpSvn.SvnCheckOutArgs { Revision = new SharpSvn.SvnRevision(int.Parse(commitId)) }); } runnerLogger.Information($"Check out complete. Result = {result}"); } runnerLogger.Information(string.Empty); return new RepositoryImportResult(path, false); } catch (Exception exp) { runnerLogger.Error(exp); return new RepositoryImportResult(string.Empty, true); } })); }
public bool Execute(IDictionary <string, object> parameters) { CustomLogger.Information("Get Fruits Step start"); CustomLogger.Information("Get Fruits Step Complete"); return(true); }
public IActionResult SendFeedbackPost(FeedbackViewModel viewModel) { viewModel.ParseAndValidateParameters(Request, m => m.HowEasyIsThisServiceToUse); viewModel.ParseAndValidateParameters(Request, m => m.HowDidYouHearAboutGpg); viewModel.ParseAndValidateParameters(Request, m => m.OtherSourceText); viewModel.ParseAndValidateParameters(Request, m => m.WhyVisitGpgSite); viewModel.ParseAndValidateParameters(Request, m => m.OtherReasonText); viewModel.ParseAndValidateParameters(Request, m => m.WhoAreYou); viewModel.ParseAndValidateParameters(Request, m => m.OtherPersonText); viewModel.ParseAndValidateParameters(Request, m => m.Details); if (viewModel.HasAnyErrors()) { // If there are any errors, return the user back to the same page to correct the mistakes return(View("SendFeedback", viewModel)); } CustomLogger.Information("Feedback has been received", viewModel); Feedback feedbackDatabaseModel = ConvertFeedbackViewModelIntoFeedbackDatabaseModel(viewModel); dataRepository.Insert(feedbackDatabaseModel); dataRepository.SaveChanges(); return(View("FeedbackSent")); }
static void Main(string[] args) { try { string configFileName = args[0]; CustomLogger.Information("Execution start"); CustomLogger.Information($"Loading Unity from File:{configFileName}"); IDictionary <string, object> parameters = new Dictionary <string, object> { { "CallCarrier", "false" }, { "PackageFruits", "false" } }; var container = _Bootstrapper(configFileName); IWorkflowManager mgr = container.Resolve <IWorkflowManager>("SimpleWorkflowManager"); bool returnValue = mgr.Initiate(parameters); } catch (Exception ex) { CustomLogger.Exception(ex, "MAIN"); } finally { Console.ReadKey(); CustomLogger.Information("Execution complete"); } }
public bool Execute(IDictionary <string, object> parameters) { CustomLogger.Information("Verify Fruit Count start"); CustomLogger.Information("Verify Fruit Count Complete"); return(true); }
private void SendReminderEmailsForSectorType(SectorTypes sector, string runId, DateTime startTime) { if (IsAfterEarliestReminder(sector)) { DateTime latestReminderEmailDate = GetLatestReminderEmailDate(sector); IEnumerable <User> usersUncheckedSinceLatestReminderDate = dataRepository.GetAll <User>() .Where(user => !user.ReminderEmails .Where(re => re.SectorType == sector) .Where(re => re.DateChecked > latestReminderEmailDate) .Any()); foreach (User user in usersUncheckedSinceLatestReminderDate) { if (VirtualDateTime.Now > startTime.AddMinutes(59)) { var endTime = VirtualDateTime.Now; CustomLogger.Information($"Function finished: {nameof(SendReminderEmails)}. Hit timeout break.", new { runId, environment = Config.EnvironmentName, endTime, TimeTakenInSeconds = (endTime - startTime).TotalSeconds }); break; } CheckUserAndSendReminderEmailsForSectorType(user, sector); } } }
public IActionResult CookieSettingsPost(CookieSettingsViewModel cookieSettingsViewModel) { var cookieSettings = new CookieSettings { GoogleAnalyticsGpg = cookieSettingsViewModel != null && cookieSettingsViewModel.GoogleAnalyticsGpg == "On", GoogleAnalyticsGovUk = cookieSettingsViewModel != null && cookieSettingsViewModel.GoogleAnalyticsGovUk == "On", RememberSettings = cookieSettingsViewModel != null && cookieSettingsViewModel.RememberSettings == "On" }; CookieHelper.SetCookieSettingsCookie(Response, cookieSettings); CookieHelper.SetSeenCookieMessageCookie(Response); cookieSettingsViewModel.ChangesHaveBeenSaved = true; CustomLogger.Information( "Updated cookie settings", new { CookieSettings = cookieSettings, HttpRequestMethod = HttpContext.Request.Method, HttpRequestPath = HttpContext.Request.Path.Value }); return(View("CookieSettings", cookieSettingsViewModel)); }
public bool Execute(IDictionary <string, object> parameters) { CustomLogger.Information("Update Stock start"); CustomLogger.Information("Update Stock Complete"); return(true); }
private static void LogFunctionEnd(string runId, string functionName, DateTime startTime) { DateTime endTime = VirtualDateTime.Now; CustomLogger.Information( $"Function finished: {functionName}", new { runId, Environment = Config.EnvironmentName, endTime, TimeTakenInSeconds = (endTime - startTime).TotalSeconds }); }
public Task StopAsync(CancellationToken stoppingToken) { CustomLogger.Information("Timed Hosted Service is stopping."); timer?.Change(Timeout.Infinite, 0); return(Task.CompletedTask); }
public static async Task <ReadOnlyCollection <BuildResult> > BuildTargetsAsync(string checkOutDirectory, BuildTarget[] targets, ReadOnlyCollection <ISourceCodeBuilderStrategy> strategies, CustomLogger customLogger) { var result = new List <BuildResult>(); foreach (var t in targets) { var sourcePath = Path.Combine(checkOutDirectory, t.TargetRelativePath); var outPath = Path.Combine(checkOutDirectory, t.Name); customLogger.Information($"Building Target: {t.Type} {t.Name} {t.TargetRelativePath}"); BuildStrategyResult currentResult = default; var strategy = strategies.FirstOrDefault(x => x.Type == t.Type); if (strategy == null) { customLogger.Error($"Unknown build target type: {t.Type}"); continue; } currentResult = await strategy.BuildAsync(t, sourcePath, outPath, customLogger); if (currentResult.IsError) { customLogger.Error($"Output: IsError: {currentResult.IsError}"); customLogger.Error(currentResult.Output); } else { customLogger.Information($"Output: IsError: {currentResult.IsError}"); customLogger.Information(currentResult.Output); } customLogger.Information(string.Empty); result.Add(new BuildResult(t, outPath, currentResult.IsError)); } return(result.AsReadOnly()); }
public bool Execute(IDictionary <string, object> parameters) { CustomLogger.Information("Call Carrier start"); if (parameters["CallCarrier"].ToString().ToLower() == "false") { CustomLogger.Information("Call Carrier is not needed. Skipping this step"); } CustomLogger.Information("Call Carrier Complete"); return(true); }
public async Task <BuildStrategyResult> BuildAsync(BuildTarget target, string sourcePath, string outPath, CustomLogger customLogger) { try { var cmd = $"dotnet publish {sourcePath} -c Release --self-contained -r win-x64 -o {outPath}"; customLogger.Information(string.Empty); customLogger.Information(cmd); customLogger.Information(string.Empty); var output = await Shell.Execute(cmd); var isError = string.IsNullOrEmpty(output) || output.Contains(": error"); return(new BuildStrategyResult(output, isError)); } catch (Exception exp) { customLogger.Error(exp); return(new BuildStrategyResult(string.Empty, true)); } }
private void UpdateDownloadFilesAction() { CustomLogger.Information($"UpdateDownloadFiles: Loading Organisations"); // IMPORTANT: This variable isn't used, but running this query makes the next query much faster List <Organisation> activeOrganisations = dataRepository.GetAll <Organisation>() .Where(o => o.Status == OrganisationStatuses.Active) .Include(o => o.OrganisationNames) .Include(o => o.OrganisationAddresses) .Include(o => o.OrganisationSicCodes) .ToList(); CustomLogger.Information($"UpdateDownloadFiles: Loading Returns"); List <Return> allReturns = dataRepository.GetAll <Return>() .Where(r => r.Organisation.Status == OrganisationStatuses.Active) .Include(r => r.Organisation) .ToList(); CustomLogger.Information($"UpdateDownloadFiles: Creating downloads for each year"); foreach (int year in ReportingYearsHelper.GetReportingYears()) { CustomLogger.Information($"UpdateDownloadFiles: Creating download for year {year}"); CustomLogger.Information($"UpdateDownloadFiles: - Filtering Returns"); List <Return> returns = allReturns .Where(r => r.AccountingDate.Year == year) .Where(r => r.Status == ReturnStatuses.Submitted) .ToList(); CustomLogger.Information($"UpdateDownloadFiles: - Converting Returns into results"); List <DownloadResult> downloadData = returns.ToList() .Select(r => r.ToDownloadResult()) .OrderBy(d => d.EmployerName) .ToList(); CustomLogger.Information($"UpdateDownloadFiles: - Saving results to file"); string filePath = Path.Combine(Global.DownloadsLocation, $"GPGData_{year}-{year + 1}.csv"); try { SaveCsvFile(downloadData, filePath); } catch (Exception ex) { CustomLogger.Error(ex.Message, new { Error = ex }); } CustomLogger.Information($"UpdateDownloadFiles: Done for year {year}"); } CustomLogger.Information($"UpdateDownloadFiles: Done"); }
public static async Task <ReadOnlyCollection <DeployResult> > DeployTargetsAsync(BuildResult[] targets, IReadOnlyCollection <IDeployStrategy> strategies, CustomLogger customLogger) { var result = new List <DeployResult>(); foreach (var t in targets) { customLogger.Information($"Deploying Target: {t.Target.Type} {t.Target.Name} {t.Target.TargetRelativePath}"); DeployStrategyResult currentResult = default; var strategy = strategies.FirstOrDefault(x => x.Type == t.Target.DeploymentType); if (strategy == null) { customLogger.Error($"Unknown deploy target type: {t.Target.Type}"); continue; } currentResult = await strategy.DeployAsync(t, customLogger); if (currentResult.IsError) { customLogger.Error($"Output: IsError: {currentResult.IsError}"); customLogger.Error(currentResult.Output); } else { customLogger.Information($"Output: IsError: {currentResult.IsError}"); customLogger.Information(currentResult.Output); } customLogger.Information(string.Empty); result.Add(new DeployResult(t, currentResult.Output, currentResult.IsError)); } return(result.AsReadOnly()); }
private void DoWork(object state) { CustomLogger.Information("Starting cache update (SearchRepository.StartCacheUpdateThread)"); try { SearchRepository.LoadSearchDataIntoCache(); } catch (Exception ex) { CustomLogger.Error($"Error during cache update (SearchRepository.StartCacheUpdateThread): {ex.Message} {ex.StackTrace}", ex); } CustomLogger.Information("Finished cache update (SearchRepository.StartCacheUpdateThread)"); }
private void AddEmailToQueue(NotifyEmail notifyEmail) { AddEnvironmentDetailsToEmail(notifyEmail); try { backgroundJobsApi.AddEmailToQueue(notifyEmail); CustomLogger.Information("Successfully queued Notify email", new { notifyEmail }); } catch (Exception ex) { CustomLogger.Error("Failed to queue Notify email", new { Exception = ex }); } }
private async Task <bool> AddEmailToQueue(SendEmailRequest notifyEmail) { try { await SendNotifyEmailQueue.AddMessageAsync(notifyEmail); CustomLogger.Information("Successfully added message to SendNotifyEmail Queue", new { notifyEmail }); return(true); } catch (Exception ex) { CustomLogger.Error("Failed to add message to SendNotifyEmail Queue", new { Exception = ex }); } return(false); }
public Task StartAsync(CancellationToken stoppingToken) { CustomLogger.Information("Starting timer (SearchRepository.StartCacheUpdateThread)"); if (!Global.DisableSearchCache) { timer = new Timer( DoWork, null, dueTime: TimeSpan.FromSeconds(0), // How long to wait before the cache is first updated period: TimeSpan.FromMinutes(1)); // How often is the cache updated } CustomLogger.Information("Started timer (SearchRepository.StartCacheUpdateThread)"); return(Task.CompletedTask); }
private void PurgeOrganisationsAction() { DateTime deadline = VirtualDateTime.Now.AddDays(0 - Global.PurgeUnusedOrganisationDays); List <Organisation> organisationsToPurge = GetOrganisationsToPurge(deadline); foreach (Organisation org in organisationsToPurge) { PurgeOrganisation(org); } if (organisationsToPurge.Count > 0) { CustomLogger.Information( $"Executed {nameof(PurgeOrganisations)} successfully: {organisationsToPurge.Count} organisations deleted", new { Environment = Config.EnvironmentName }); } }
// Generates and stores a string to act as a password reset code private void SendPasswordResetEmail(User userForPasswordReset) { // Generate a random string as a unique identifier for the password reset string resetCode = Convert.ToBase64String(Crypto.GetSalt()); // Store the reset code on the user entity for verification userForPasswordReset.PasswordResetCode = resetCode; userForPasswordReset.ResetSendDate = VirtualDateTime.Now; dataRepository.SaveChanges(); string resetUrl = Url.Action("ChooseNewPasswordGet", "PasswordReset", new { code = resetCode }, "https"); emailSendingService.SendResetPasswordVerificationEmail(userForPasswordReset.EmailAddress, resetUrl); CustomLogger.Information( "Password reset sent", $"User ID: {userForPasswordReset.UserId}, Email:{userForPasswordReset.EmailAddress}"); }
private void SendReminderEmailsAction(string runId) { DateTime startTime = VirtualDateTime.Now; List <int> reminderDays = GetReminderEmailDays(); if (reminderDays.Count != 0) { SendReminderEmailsForSectorType(SectorTypes.Private, runId, startTime); SendReminderEmailsForSectorType(SectorTypes.Public, runId, startTime); } else { var endTime = VirtualDateTime.Now; CustomLogger.Information( $"Function finished: {nameof(SendReminderEmails)}. No ReminderEmailDays set.", new { runId, environment = Config.EnvironmentName, endTime, TimeTakenInSeconds = (endTime - startTime).TotalSeconds }); } }
private static List <SearchCachedUser> LoadAllUsers(IDataRepository repository) { DateTime start = VirtualDateTime.Now; var allUsers = repository .GetAll <User>() .Select( u => new SearchCachedUser { UserId = u.UserId, FullName = new SearchReadyValue(u.Fullname), EmailAddress = new SearchReadyValue(u.EmailAddress), Status = u.Status }) .ToList(); CustomLogger.Information($"Search Repository: Time taken to load Users: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); return(allUsers); }
private void UpdateFromCompaniesHouse(string runId) { int maxNumCallCompaniesHouseApi = Global.MaxNumCallsCompaniesHouseApiPerFiveMins; for (var i = 0; i < maxNumCallCompaniesHouseApi; i++) { long organisationId = dataRepository.GetAll <Organisation>() .Where(org => !org.OptedOutFromCompaniesHouseUpdate && org.CompanyNumber != null && org.CompanyNumber != "") .OrderByDescending(org => org.LastCheckedAgainstCompaniesHouse == null) .ThenBy(org => org.LastCheckedAgainstCompaniesHouse) .Select(org => org.OrganisationId) .FirstOrDefault(); if (organisationId != 0) { CustomLogger.Information($"Start update companies house data organisation id: {organisationId}. Run id: {runId}"); updateFromCompaniesHouseService.UpdateOrganisationDetails(organisationId); CustomLogger.Information($"End update companies house data organisation id: {organisationId}. Run id: {runId}"); } } }
public static async Task <RepositoryImportResult> ImportAsync(Project project, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, ReadOnlyCollection <IRepositoryImportStrategy> strategies, CustomLogger runnerLogger, string commitId = null) { if (authInfo != null) { if (await authInfo.Validate() == false) { runnerLogger.Information($"Validation for {nameof(authInfo)} did not pass."); return(new RepositoryImportResult(string.Empty, true)); } } var strategy = strategies.FirstOrDefault(x => x.Type == project.RepositoryType); if (strategy == null) { runnerLogger.Error($"Unknown Source Code Import type: {project.RepositoryType}"); return(default);
private void SendReminderEmailForSectorTypeAndYear(SectorTypes sector, int year, string runId, DateTime startTime) { DateTime latestReminderEmailDate = GetLatestReminderEmailDateForReportingYear(sector, year); IEnumerable <User> usersUncheckedSinceLatestReminderDate = dataRepository.GetAll <User>() .Where(user => !user.HasBeenAnonymised) .Where(UserHasNotBeenEmailedYet(sector, latestReminderEmailDate)); foreach (User user in usersUncheckedSinceLatestReminderDate) { if (VirtualDateTime.Now > startTime.AddMinutes(45)) { var endTime = VirtualDateTime.Now; CustomLogger.Information( $"Function finished: {nameof(SendReminderEmails)}. Hit timeout break.", new { runId, environment = Config.EnvironmentName, endTime, TimeTakenInSeconds = (endTime - startTime).TotalSeconds }); break; } try { SendReminderEmailRecordIfNotInProgress(user, sector, latestReminderEmailDate, year); } catch (Exception ex) { CustomLogger.Information( "Failed whilst saving or sending reminder email", new { user.UserId, SectorType = sector, Exception = ex.Message }); } } }
private static List <SearchCachedOrganisation> LoadAllOrganisations(IDataRepository repository) { DateTime start = VirtualDateTime.Now; // IMPORTANT: This variable isn't used, but running this query makes the next query much faster var allOrgsWithNames = repository.GetAll <Organisation>() .Include(o => o.OrganisationNames) .ToList(); CustomLogger.Information($"Search Repository: Time taken to load Names: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); // IMPORTANT: This variable isn't used, but running this query makes the next query much faster var allOrgsWithReturns = repository.GetAll <Organisation>() .Include(o => o.Returns) .ToList(); CustomLogger.Information($"Search Repository: Time taken to load Returns: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); // IMPORTANT: This variable isn't used, but running this query makes the next query much faster var allOrgsWithScopes = repository.GetAll <Organisation>() .Include(o => o.OrganisationScopes) .ToList(); CustomLogger.Information($"Search Repository: Time taken to load Scopes: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); List <Organisation> allOrganisations = repository .GetAll <Organisation>() //.Include(o => o.OrganisationNames) // Moved into separate pre-load query //.Include(o => o.Returns) // Moved into separate pre-load query //.Include(o => o.OrganisationScopes) // Moved into separate pre-load query .Include(o => o.OrganisationSicCodes) .ThenInclude(osc => osc.SicCode) .ThenInclude(sc => sc.SicSection) .ToList(); CustomLogger.Information($"Search Repository: Time taken to load Organisations: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); List <SearchCachedOrganisation> searchCachedOrganisations = allOrganisations .Select( o => { var sicCodeSynonyms = o.OrganisationSicCodes.Select(osc => osc.SicCode.Synonyms) .Where(s => s != null) .Select(s => new SearchReadyValue(s)) .ToList(); foreach (var osc in o.OrganisationSicCodes) { sicCodeSynonyms.Add(new SearchReadyValue(osc.SicCode.Description)); } var submittedReports = o.Returns.Where(r => r.Status == ReturnStatuses.Submitted).ToList(); return(new SearchCachedOrganisation { OrganisationId = o.OrganisationId, EncryptedId = o.GetEncryptedId(), OrganisationName = new SearchReadyValue(o.OrganisationName), CompanyNumber = o.CompanyNumber?.Trim(), EmployerReference = o.EmployerReference?.Trim(), OrganisationNames = o.OrganisationNames.OrderByDescending(n => n.Created) .Select(on => new SearchReadyValue(on.Name)) .ToList(), MinEmployees = o.GetLatestReturn()?.MinEmployees ?? 0, Status = o.Status, ReportingYearToOrganisationSizesMap = submittedReports .GroupBy(r => r.AccountingDate.Year) .ToDictionary( g => g.Key, g => g.ToList().Select(r => r.OrganisationSize).Distinct().ToList()), SicSectionIds = o.OrganisationSicCodes.Select(osc => Convert.ToChar(osc.SicCode.SicSection.SicSectionId)).ToList(), ReportingYears = submittedReports.Select(r => r.AccountingDate.Year).ToList(), ReportingYearToDateOfLatestReportMap = ReportingYearsHelper.GetReportingYears() .ToDictionary( y => y, y => o.GetReturn(y) != null ? o.GetReturn(y).StatusDate.Date : new DateTime(1999, 1, 1)), ReportedWithCompanyLinkYears = submittedReports.Where(r => !r.CompanyLinkToGPGInfo.IsNullOrEmpty()) .Select(r => r.AccountingDate.Year) .ToList(), ReportedLateYears = submittedReports.Where(r => r.IsLateSubmission).Select(r => r.AccountingDate.Year).ToList(), SicCodeIds = o.OrganisationSicCodes.Select(osc => osc.SicCode.SicCodeId.ToString()).ToList(), SicCodeSynonyms = sicCodeSynonyms, IncludeInViewingService = GetIncludeInViewingService(o), Sector = o.SectorType }); }) .ToList(); CustomLogger.Information($"Search Repository: Time taken to convert Organisations into SearchCachedOrganisations: {VirtualDateTime.Now.Subtract(start).TotalSeconds} seconds"); return(searchCachedOrganisations); }
public async Task <IActionResult> ConfirmCancellation(OrganisationViewModel model, string command) { //Ensure user has completed the registration process User currentUser; IActionResult checkResult = CheckUserRegisteredOk(out currentUser); if (checkResult != null) { return(checkResult); } // Validate cancellation reason model.ParseAndValidateParameters(Request, m => m.CancellationReason); if (model.HasAnyErrors()) { View("ConfirmCancellation", model); } //If cancel button clicked the n return to review page if (command.EqualsI("Cancel")) { return(RedirectToAction("ReviewRequest")); } //Unwrap code UserOrganisation userOrg; ActionResult result = UnwrapRegistrationRequest(model, out userOrg); if (result != null) { return(result); } //Log the rejection auditLogger.AuditChangeToOrganisation( AuditedAction.RegistrationLog, userOrg.Organisation, new { Status = "Manually Rejected", Sector = userOrg.Organisation.SectorType, Organisation = userOrg.Organisation.OrganisationName, CompanyNo = userOrg.Organisation.CompanyNumber, Address = userOrg?.Address.GetAddressString(), SicCodes = userOrg.Organisation.GetSicCodeIdsString(), UserFirstname = userOrg.User.Firstname, UserLastname = userOrg.User.Lastname, UserJobtitle = userOrg.User.JobTitle, UserEmail = userOrg.User.EmailAddress, userOrg.User.ContactFirstName, userOrg.User.ContactLastName, userOrg.User.ContactJobTitle, userOrg.User.ContactOrganisation, userOrg.User.ContactPhoneNumber }, User); //Delete address for this user and organisation if (userOrg.Address.Status != AddressStatuses.Active && userOrg.Address.CreatedByUserId == userOrg.UserId) { DataRepository.Delete(userOrg.Address); } //Delete the org user long orgId = userOrg.OrganisationId; string emailAddress = userOrg.User.ContactEmailAddress.Coalesce(userOrg.User.EmailAddress); //Delete the organisation if it has no returns, is not in scopes table, and is not registered to another user if (userOrg.Organisation != null && !userOrg.Organisation.Returns.Any() && !userOrg.Organisation.OrganisationScopes.Any() && !await DataRepository.GetAll <UserOrganisation>() .AnyAsync(uo => uo.OrganisationId == userOrg.Organisation.OrganisationId && uo.UserId != userOrg.UserId)) { CustomLogger.Information( $"Unused organisation {userOrg.OrganisationId}:'{userOrg.Organisation.OrganisationName}' deleted by {(OriginalUser == null ? currentUser.EmailAddress : OriginalUser.EmailAddress)} when declining manual registration for {userOrg.User.EmailAddress}"); DataRepository.Delete(userOrg.Organisation); } EmployerSearchModel searchRecord = userOrg.Organisation.ToEmployerSearchResult(true); DataRepository.Delete(userOrg); //Send the declined email to the applicant SendRegistrationDeclined( emailAddress, string.IsNullOrWhiteSpace(model.CancellationReason) ? "We haven't been able to verify your employer's identity. So we have declined your application." : model.CancellationReason); //Save the changes and redirect DataRepository.SaveChanges(); //Save the model for the redirect this.StashModel(model); //If private sector then send the pin return(RedirectToAction("RequestCancelled")); }
public Task <RepositoryImportResult> ImportAsync(Project project, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, CustomLogger runnerLogger, string commitId = null) { return(Task.Run(() => { // Try to get the auth data. var info = authInfo as AuthInfo; if (info == null) { return new RepositoryImportResult(string.Empty, true); } // Setup storage directory. var folderName = $"{project.Name}_{DateTime.UtcNow.Ticks}"; var path = Path.Combine(appConfiguration.BaseDirectory, folderName); try { // Create the path before we start. Directory.CreateDirectory(path); // Clone the repository first. var cloneOptions = new CloneOptions { CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = info.Username, Password = info.Password } }; var cloneResult = Repository.Clone(project.RepositoryUrl, path, cloneOptions); if (string.IsNullOrEmpty(cloneResult)) { return new RepositoryImportResult(string.Empty, true); } // Checkout the branch. using (var repo = new Repository(path)) { var branch = repo.Branches[project.BranchName ?? "main"]; if (branch == null) { new RepositoryImportResult(string.Empty, true); } runnerLogger.Information("Checking out..."); Branch currentBranch; if (commitId != null) { var localCommit = repo.Lookup <Commit>(new ObjectId(commitId)); if (localCommit == null) { runnerLogger.Error("Could not find branch."); return new RepositoryImportResult(null, true); } currentBranch = Commands.Checkout(repo, localCommit); } else { currentBranch = Commands.Checkout(repo, branch); } runnerLogger.Information($"Check out complete. Result = {currentBranch != null}"); if (currentBranch != null) { return new RepositoryImportResult(path, false); } else { return new RepositoryImportResult(path, true); } } } catch (Exception exp) { runnerLogger.Error(exp); return new RepositoryImportResult(string.Empty, true); } })); }