public static async Task <JObject> SendEmailSASUri(HttpRequest req, Logging logging) { string requestBody = new StreamReader(req.Body).ReadToEndAsync().Result; dynamic taskInformation = JsonConvert.DeserializeObject(requestBody); string _TaskInstanceId = taskInformation["TaskInstanceId"].ToString(); string _ExecutionUid = taskInformation["ExecutionUid"].ToString(); try { //Get SAS URI string _blobStorageAccountName = taskInformation["Source"]["StorageAccountName"].ToString(); string _blobStorageContainerName = taskInformation["Source"]["StorageAccountContainer"].ToString(); string _blobStorageFolderPath = taskInformation["Source"]["RelativePath"].ToString(); string _dataFileName = taskInformation["Source"]["DataFileName"].ToString(); int _accessDuration = (int)taskInformation["Source"]["SasURIDaysValid"]; string _targetSystemUidInPHI = taskInformation["Source"]["TargetSystemUidInPHI"]; string _FileUploaderWebAppURL = taskInformation["Source"]["FileUploaderWebAppURL"]; string SASUri = Storage.CreateSASToken(_blobStorageAccountName, _blobStorageContainerName, _blobStorageFolderPath, _dataFileName, _accessDuration); //Send Email string _emailRecipient = taskInformation["Target"]["EmailRecipient"].ToString(); string _emailRecipientName = taskInformation["Target"]["EmailRecipientName"].ToString(); string _emailTemplateFileName = taskInformation["Target"]["EmailTemplateFileName"].ToString(); string _senderEmail = taskInformation["Target"]["SenderEmail"].ToString(); string _senderDescription = taskInformation["Target"]["SenderDescription"].ToString(); string _subject = taskInformation["Target"]["EmailSubject"].ToString(); //Get Plain Text and Email Subject from Template Files Dictionary <string, string> Params = new Dictionary <string, string> { { "NAME", _emailRecipientName }, { "SASTOKEN", SASUri }, { "FileUploaderUrl", _FileUploaderWebAppURL }, { "TargetSystemUidInPHI", _targetSystemUidInPHI }, }; string _plainTextContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".txt"); _plainTextContent = _plainTextContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}'); string _htmlContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".html"); _htmlContent = _htmlContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}'); var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); var client = new SendGridClient(new SendGridClientOptions { ApiKey = apiKey, HttpErrorAsException = true }); var msg = new SendGridMessage() { From = new EmailAddress(_senderEmail, _senderDescription), Subject = _subject, PlainTextContent = _plainTextContent, HtmlContent = _htmlContent }; msg.AddTo(new EmailAddress(_emailRecipient, _emailRecipientName)); try { var response = await client.SendEmailAsync(msg).ConfigureAwait(false); logging.LogInformation($"SendGrid Response StatusCode - {response.StatusCode}"); } catch (Exception ex) { SendGridErrorResponse errorResponse = JsonConvert.DeserializeObject <SendGridErrorResponse>(ex.Message); logging.LogInformation($"Error Message - {ex.Message}"); throw new Exception("Could not send email"); } //Update Task Instace TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, Guid.Empty, ""); JObject Root = new JObject { ["Result"] = "Complete" }; return(Root); } catch (Exception TaskException) { logging.LogErrors(TaskException); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, Guid.Empty, "Failed when trying to Generate Sas URI and Send Email"); JObject Root = new JObject { ["Result"] = "Failed" }; return(Root); } }
/// <summary> /// Get error based on Response from SendGrid API /// Method taken from the StrongGrid project (https://github.com/Jericho/StrongGrid) with some minor changes. Thanks Jericho (https://github.com/Jericho) /// </summary> /// <param name="message">Response Message from API</param> /// <returns>Return string with the error Status Code and the Message</returns> private static async Task <string> GetErrorMessage(HttpResponseMessage message) { var errorStatusCode = (int)message.StatusCode; var errorReasonPhrase = message.ReasonPhrase; string errorValue = null; string fieldValue = null; string helpValue = null; if (message.Content != null) { var responseContent = await message.Content.ReadAsStringAsync().ConfigureAwait(false); if (!string.IsNullOrEmpty(responseContent)) { try { // Check for the presence of property called 'errors' var jObject = JObject.Parse(responseContent); var errorsArray = (JArray)jObject["errors"]; if (errorsArray != null && errorsArray.Count > 0) { // Get the first error message errorValue = errorsArray[0]["message"].Value <string>(); // Check for the presence of property called 'field' if (errorsArray[0]["field"] != null) { fieldValue = errorsArray[0]["field"].Value <string>(); } // Check for the presence of property called 'help' if (errorsArray[0]["help"] != null) { helpValue = errorsArray[0]["help"].Value <string>(); } } else { // Check for the presence of property called 'error' var errorProperty = jObject["error"]; if (errorProperty != null) { errorValue = errorProperty.Value <string>(); } } } catch { // Intentionally ignore parsing errors to return default error message } } } SendGridErrorResponse errorResponse = new SendGridErrorResponse { ErrorHttpStatusCode = errorStatusCode, ErrorReasonPhrase = errorReasonPhrase, SendGridErrorMessage = errorValue, FieldWithError = fieldValue, HelpLink = helpValue }; return(Newtonsoft.Json.JsonConvert.SerializeObject(errorResponse)); }