Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Configuration;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Automating_Approval_of_Registration.Models;
- using log4net;
- using Microsoft.Crm.Sdk.Messages;
- using Microsoft.Xrm.Sdk;
- using UOP.Portal.Gateway.Services.DAL;
- namespace Automating_Approval_of_Registration.Helpers
- {
- public class TaskHelper
- {
- private const string TableStyle =
- "<table style='width:100%; border-top: 1px solid black;border-left:1px solid black; border-collapse: collapse;'>";
- private const string TableRowStyle =
- "<th style='border-right: 1px solid black;border-bottom:1px solid black;text-align: left; padding: 5px;'>";
- private const string Subject = "Automating Approval of Registration - Summary";
- private readonly string _crmAccountUrl = ConfigurationManager.AppSettings["CRM_ACCOUNT_BASE_URL"];
- private readonly ILog _logger;
- private readonly bool _forceMode;
- private readonly CrmConnection _connection;
- private readonly DGuidsHelper _guidsHelper;
- private readonly CrmHelper _helper;
- private List<RegistrationData> _registrations;
- private List<RegistrationData> _successes;
- private List<RegistrationData> _failures;
- private readonly StringBuilder _totalIds = new StringBuilder();
- private readonly StringBuilder _successIds = new StringBuilder();
- private readonly StringBuilder _failedIds = new StringBuilder();
- public DateTime ServerDate = DateTime.Now;
- public New_timeperiod NextTerm;
- public TaskHelper(ILog logger, bool forceMode)
- {
- this._forceMode = forceMode;
- this._logger = logger;
- this._connection = new CrmConnection(logger);
- this._guidsHelper = new DGuidsHelper(_connection, logger);
- this._helper = new CrmHelper(_connection, logger);
- this._registrations = new List<RegistrationData>();
- this._successes = new List<RegistrationData>();
- this._failures = new List<RegistrationData>();
- }
- public void Execute()
- {
- //1. Task triggers:
- bool trigger = CheckTaskTriggers();
- if (trigger)
- {
- try
- {
- //3.1. Reporting compliance:
- //3.2. Create UoPeople process record with the following attributes:
- Guid uopProcessId = _helper.CreateUopProcess();
- // Getting required lookup values section
- if (!_helper.InitializingRequiredGuids())
- {
- UpdateUopProcess(uopProcessId, (int)PortalEnums.UopeopleProcessRequeststatus.Faild, _totalIds.ToString(),
- "Issue in getting required guids", _successIds.ToString());
- _logger.Error($"Error in retrieving the required guids. Aborting task {nameof(Automating_Approval_of_Registration)}");
- _guidsHelper.SendEmailToSupport($"Error in task {nameof(Automating_Approval_of_Registration)}", "Error in retrieving the required guids.");
- return;
- }
- //3.4. Search for registrations that:
- //3.4.1. Term = next term.
- //3.4.2. Registration status = “open”.
- //3.4.3. Registration sub - status = “processing request”.
- //3.4.4. In associated student: program funding = “on my own” OR “scholarships”.
- _registrations = _helper.RetrieveNextTermRegistrations(NextTerm);
- if (_registrations.Count == 0)
- {
- _logger.Error($"No registrations meeting the criteria found for term {NextTerm.New_name}. " +
- $"Aborting {nameof(Automating_Approval_of_Registration)} execution.");
- return;
- }
- //// QA Test
- //var testRegistrationIds = new []
- //{
- // "Reg1042585",
- // "Reg1042614",
- // "Reg1042618",
- // "Reg1042611",
- // "Reg1042613",
- // "Reg1042620",
- // "Reg1042326",
- // "Reg1042612",
- // "Reg1042619"
- //};
- //_registrations = _registrations.Where(r => testRegistrationIds.Contains(r.RegistrationName)).ToList();
- //// End of QA Test
- foreach (var currentRegistration in _registrations)
- {
- try
- {
- //3.5. For each record found:
- //3.5.1. Set “registration sub-status” = “registered”.
- //3.5.2. Set “registration sub status reason” = “your request has been approved”.
- //3.5.3. Set “payment creation status” = “requires payment creation”.
- //3.5.4. Save relevant registration.
- _logger.Info($"Updating registration {currentRegistration.RegistrationName} with id {currentRegistration.RegistrationId}...");
- New_enrollment registrationToUpdate = new New_enrollment
- {
- Id = currentRegistration.RegistrationId,
- New_RegistrationSubStatusId = new EntityReference(
- New_registrationsubstatus.EntityLogicalName,
- _helper.RegistrationSubStatusRegistered),
- New_RegistrationSubStatusReasonId = new EntityReference(
- New_registrationsubstatusreason.EntityLogicalName,
- _helper.RegistrationSubStatusReasonApproved),
- new_PaymentCreationStatus =
- new OptionSetValue((int)PortalEnums.PaymentCreationStatus.RequiresPayemntCreation)
- };
- _connection.Service.Update(registrationToUpdate);
- _logger.Info($"Successfully updated registration {currentRegistration.RegistrationName} with id {currentRegistration.RegistrationId}");
- _successes.Add(currentRegistration);
- _successIds.AppendLine(currentRegistration.RegistrationId.ToString());
- }
- catch (Exception e)
- {
- _logger.Error($"Exception while updating registration with id {currentRegistration.RegistrationId}. Details: {e}");
- currentRegistration.IssueDescription = e.Message;
- _failures.Add(currentRegistration);
- _failedIds.AppendLine(currentRegistration.RegistrationId.ToString());
- }
- finally
- {
- _totalIds.AppendLine(currentRegistration.RegistrationId.ToString());
- }
- }
- //3.6. Send email to task owners stored in (university rule: student services – approving registrations – task owners)
- List<string> taskOwners = _helper.RetrieveTaskOwners();
- bool emailsSent = SendEmailToTaskOwners(taskOwners, uopProcessId);
- if (emailsSent)
- {
- _logger.Info($"Email to task owners sent successfully.");
- }
- else
- {
- _logger.Error("Unable to send email to task owners.");
- _guidsHelper.SendEmailToSupport($"Error in task {nameof(Automating_Approval_of_Registration)}",
- $"Unable to send email to task owners: {string.Join(",", taskOwners)}.");
- }
- //3.7. Reporting compliance:
- //3.8. If any system failure occurred during the execution:
- //3.8.1. Update UoPeople process record
- if (_failures.Count > 0)
- {
- UpdateUopProcess(uopProcessId, (int)PortalEnums.UopeopleProcessRequeststatus.Faild, _totalIds.ToString(),
- _failedIds.ToString(), _successIds.ToString());
- }
- else
- {
- UpdateUopProcess(uopProcessId, (int)PortalEnums.UopeopleProcessRequeststatus.Completed, _totalIds.ToString(),
- _failedIds.ToString(), _successIds.ToString());
- }
- }
- catch (Exception ex)
- {
- _logger.Error($"An error occurred while executing {nameof(Automating_Approval_of_Registration)}. Details: {ex}");
- _guidsHelper.SendEmailToSupport($"Error in task {nameof(Automating_Approval_of_Registration)}", "Error details: " + ex);
- }
- }
- }
- #region Private Methods
- private bool CheckTaskTriggers()
- {
- //1.1.1. The task shall execute the logic if:
- //1.1.1.1. Current date = “date to approve registrations” for next term.
- NextTerm = _helper.GetNextTerm(ServerDate);
- if (NextTerm != null)
- {
- _logger.Info($"{nameof(CheckTaskTriggers)} returned term {NextTerm.New_name} with date to approve registrations {NextTerm.new_datetoapproveregistrations}");
- if (NextTerm.new_datetoapproveregistrations != null && ServerDate.Date == NextTerm.new_datetoapproveregistrations.Value.Date)
- {
- _logger.Info($"Date to approve registration in {NextTerm.New_name} matches the current date {ServerDate.Date}. The scheduled task begins execution...");
- return true;
- }
- else
- {
- _logger.Info($"Date to approve registration in {NextTerm.New_name} is different that current date {ServerDate.Date}. Aborting scheduled task execution.");
- return false;
- }
- }
- return false;
- }
- private void UpdateUopProcess(Guid uopProcessId, int uopProcessStatus, string totalRecordIds, string failIds, string successIds)
- {
- if (uopProcessId != Guid.Empty)
- {
- _logger.Info("Updating UOP Process....");
- try
- {
- new_crmisvrequest uopProcessToUpdate = new new_crmisvrequest
- {
- Id = uopProcessId,
- new_successes = _successes.Count,
- new_failures = _failures.Count,
- new_total = _registrations.Count,
- new_requeststatus = new OptionSetValue(uopProcessStatus),
- new_failedrecordsids = failIds,
- new_totalrecordids = totalRecordIds,
- new_succeededrecordsids = successIds,
- new_Datecompleted = DateTime.Now,
- new_Datefailed = _failures.Count != 0 ? DateTime.Now : (DateTime?)null
- };
- _connection.Service.Update(uopProcessToUpdate);
- _logger.Info($"UOP Process with id {uopProcessId} updated successfully");
- }
- catch (Exception ex)
- {
- _logger.Error($"Error in {nameof(UpdateUopProcess)}. Details: {ex}");
- }
- }
- else
- {
- _logger.Info("Can't update UOP Process, record id is null");
- }
- }
- private bool SendEmailToTaskOwners(List<string> taskOwners, Guid uopProcessId)
- {
- string description = BuildEmailDescription();
- _logger.Debug($"Executing {nameof(SendEmailToTaskOwners)}, subject: {Subject}, description: {description}");
- try
- {
- var service = _connection.Service;
- // Create the 'From:' activity party for the email
- ActivityParty fromParty = new ActivityParty
- {
- PartyId = new EntityReference(Queue.EntityLogicalName, _helper.StudentServicesQueueId)
- };
- // Create the 'To:' activity party for the email
- List<ActivityParty> toParties = new List<ActivityParty>();
- foreach (string emailAddress in taskOwners)
- {
- ActivityParty toParty = new ActivityParty
- {
- AddressUsed = emailAddress
- };
- toParties.Add(toParty);
- }
- // Create an email message entity
- Email email = new Email
- {
- To = toParties,
- From = new[] { fromParty },
- Subject = Subject,
- Description = description,
- DirectionCode = true,
- RegardingObjectId = new EntityReference(new_crmisvrequest.EntityLogicalName, uopProcessId)
- };
- Guid emailId = service.Create(email);
- if (emailId == Guid.Empty)
- {
- _logger.Error("Email to task owners not created successfully");
- return false;
- }
- _logger.Info($"Created email message with id {emailId} with the following information: " +
- $"Subject: {email.Subject}, Description: {email.Description}");
- SendEmailRequest sendEmailRequest = new SendEmailRequest
- {
- EmailId = emailId,
- TrackingToken = string.Empty,
- IssueSend = true
- };
- SendEmailResponse sendEmailResponse = (SendEmailResponse)service.Execute(sendEmailRequest);
- return sendEmailResponse != null;
- }
- catch (Exception ex)
- {
- _logger.FatalFormat($"Error in {nameof(SendEmailToTaskOwners)}. Details: {ex}");
- return false;
- }
- }
- private string BuildEmailDescription()
- {
- string description = @"Automating approval of registration started at: " + ServerDate + "<br>";
- description += @"Automating approval of registration finished at: " + DateTime.Now + "<br>";
- description += @"Total number of registrations found: " + _registrations.Count + "<br>";
- description += @"Number of registrations successfully processed: " + _successes.Count + "<br>";
- description += @"Number of registrations failed to be processed: " + _failures.Count + "<br> <br>";
- description += "List of registrations processed successfully (related data was updated):";
- description += TableStyle +
- TableRowStyle + "#</th>" +
- TableRowStyle + "Registration ID</th>" +
- TableRowStyle + "Student ID</th>";
- //3.6.3. List of registrations processed.
- for (int i = 0; i < _successes.Count; i++)
- {
- string studentId = _successes[i].Student.StudentId.ToString();
- string accountUrl = _crmAccountUrl.Replace("ENTITY_NAME", Account.EntityLogicalName)
- .Replace("ENTITY_ID", studentId);
- string registrationId = _successes[i].RegistrationId.ToString();
- string registrationUrl = _crmAccountUrl.Replace("ENTITY_NAME", New_enrollment.EntityLogicalName)
- .Replace("ENTITY_ID", registrationId);
- description += @"<tr>" +
- TableRowStyle + (i + 1) + " </td>" +
- TableRowStyle + "<a href='" + registrationUrl + "'>" + _successes[i].RegistrationName + "</a></td>" +
- TableRowStyle + "<a href='" + accountUrl + "'>" + _successes[i].Student.StudentNumber + "</a></td>" +
- "</tr>";
- }
- description += "</table> <br>";
- if (_failures.Count > 0)
- {
- //3.6.4. List of registrations failed to be processed.
- description += "List of students with issues (data was not updated):";
- description += TableStyle +
- TableRowStyle + "#</th>" +
- TableRowStyle + "Registration ID</th>" +
- TableRowStyle + "Student ID</th>" +
- TableRowStyle + "Issue Description</th>";
- for (int i = 0; i < _failures.Count; i++)
- {
- string studentId = _failures[i].Student.StudentId.ToString();
- string accountUrl = _crmAccountUrl.Replace("ENTITY_NAME", Account.EntityLogicalName)
- .Replace("ENTITY_ID", studentId);
- string registrationId = _failures[i].RegistrationId.ToString();
- string registrationUrl = _crmAccountUrl.Replace("ENTITY_NAME", New_enrollment.EntityLogicalName)
- .Replace("ENTITY_ID", registrationId);
- description += @"<tr>" +
- TableRowStyle + (i + 1) + " </td>" +
- TableRowStyle + "<a href='" + registrationUrl + "'>" + _failures[i].RegistrationName + "</a></td>" +
- TableRowStyle + "<a href='" + accountUrl + "'>" + _failures[i].Student.StudentNumber + "</a></td>" +
- TableRowStyle + _failures[i].IssueDescription + "</a></td>" +
- "</tr>";
- }
- description += "</table> <br>";
- }
- description +=
- "<div style ='font-size: 10px; float: left;'>Related version: v15.9 Automating Approval of Registration</div>";
- return description;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment