Tuesday, August 19, 2025

Send emails using SendGrid using C#

 public static bool SendMail(EmailDTO emailDTO, bool showOEEFooter, bool isSCECHSponsor = false)
        {
            try
            {
                var apiKey = Utility.GetAppSettingsValue(MOECSAppSettings.SENDGRID_APIKEY);
                var sendGridClient = new SendGridClient(apiKey);

                var mailMessage = new SendGridMessage();

                string fromAddress = Utility.GetAppSettingsValue(MOECSAppSettings.SENDGRID_FROM_ADDRESS);
                mailMessage.From = new EmailAddress(fromAddress, fromAddress);

                string environment = Utility.GetAppSettingsValue(MOECSAppSettings.ENVIRONMENT)?.ToLower();

                if (isSCECHSponsor)
                {
                    mailMessage.AddReplyTo(Utility.GetAppSettingsValue(MOECSAppSettings.SCECH_FROM_ADDRESS));
                }

                List<EmailAddress> toEmails;
                if (environment == ApplicationSettings.MOECS_PRODUCTION)
                {
                    mailMessage.AddTo(new EmailAddress(emailDTO.ToAddress));
                    mailMessage.Subject = emailDTO.Subject;

                    toEmails = new List<EmailAddress> { new EmailAddress(emailDTO.ToAddress) };
                }
                else
                {
                    string fallbackToAddress = Utility.GetAppSettingsValue(MOECSAppSettings.TO_ADDRESS);

                    var fallbackEmails = new List<EmailAddress>();
                    if (emailDTO.ToAddress.Contains(";"))
                    {
                        fallbackEmails = emailDTO.ToAddress.Split(';').Select(_ => new EmailAddress(fallbackToAddress)).ToList();
                    }
                    else if (emailDTO.ToAddress.Contains(","))
                    {
                        fallbackEmails = emailDTO.ToAddress.Split(',').Select(_ => new EmailAddress(fallbackToAddress)).ToList();
                    }
                    else
                    {
                        fallbackEmails.Add(new EmailAddress(fallbackToAddress));
                    }

                    mailMessage.AddTos(fallbackEmails);
                    mailMessage.Subject = $"{environment.ToUpper()} - {emailDTO.Subject}";

                    toEmails = fallbackEmails;
                }

                //string bcc = Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS)?.Trim();
                //if (!string.IsNullOrEmpty(bcc))
                //{
                //    mailMessage.AddBcc(new EmailAddress(bcc));
                //}

                var ccEmails = !string.IsNullOrEmpty(emailDTO.CCAddress)
                   ? emailDTO.CCAddress.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)
                   .Select(e => new EmailAddress(e.Trim())).ToList() : new List<EmailAddress>();

                var bccEmails = !string.IsNullOrEmpty(Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS))
                    ? Utility.GetAppSettingsValue(MOECSAppSettings.BCC_ADDRESS)
                    .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(e => new EmailAddress(e.Trim())).ToList() : new List<EmailAddress>();

                ccEmails = ccEmails.Where(cc => !toEmails.Any(to => to.Email.Equals(cc.Email, StringComparison.OrdinalIgnoreCase))).ToList();

                bccEmails = bccEmails.Where(bcc => !toEmails.Any(to => to.Email.Equals(bcc.Email, StringComparison.OrdinalIgnoreCase)) &&
                                                   !ccEmails.Any(cc => cc.Email.Equals(bcc.Email, StringComparison.OrdinalIgnoreCase))).ToList();

                if (ccEmails.Any())
                {
                    mailMessage.AddCcs(ccEmails);
                }

                if (bccEmails.Any())
                {
                    mailMessage.AddBccs(bccEmails);
                }

                string bodyContent = formatMessage(emailDTO.FullName, emailDTO.Body, showOEEFooter, emailDTO.TemplateID, isSCECHSponsor);
                mailMessage.PlainTextContent = bodyContent;
                mailMessage.HtmlContent = bodyContent;

                if (emailDTO.Attachment != null)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        emailDTO.Attachment.CopyTo(memoryStream);
                        byte[] fileBytes = memoryStream.ToArray();
                        string base64File = Convert.ToBase64String(fileBytes);

                        mailMessage.AddAttachment(new Attachment
                        {
                            Content = base64File,
                            Filename = emailDTO.AttachmentFileName,
                            Type = MediaTypeNames.Application.Octet,
                            Disposition = "attachment"
                        });
                    }
                }

                var response = sendGridClient.SendEmailAsync(mailMessage).GetAwaiter().GetResult();

                if (!response.IsSuccessStatusCode)
                {
                    string errorBody = response.Body.ReadAsStringAsync().GetAwaiter().GetResult();
                    LoggerUtility.WriteLog($"SendGrid Error: {response.StatusCode} - {errorBody}", System.Diagnostics.TraceEventType.Error);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                LoggerUtility.WriteLog($"Exception: {ex.Message}", System.Diagnostics.TraceEventType.Error);
                return false;
            }
        }


  public static bool SendMail(EmailDTO emailDTO)
        {
            return SendMail(emailDTO, true);
        }

  private static string formatMessage(string fullName, string messageBody, bool showOEEFooter, int templateID, bool isSCECHSponsor)
        {
            string content = string.Empty;
            TextInfo txtInfo = new CultureInfo("en-US", false).TextInfo;

            string footer = string.Empty;

            if (showOEEFooter == true)
            {
                footer = CacheUtil.GetMessageDescription(MOECSMessage.OEE_ADDRESS_CONTACT_HTML);
            }

            if (isSCECHSponsor)
            {
                footer = CacheUtil.GetMessageDescription(MOECSMessage.SCECH_EMAIL_FOOTER);
            }
            else
            {
                //attach no reply message to the footer
                footer = footer + CacheUtil.GetMessageDescription(MOECSMessage.NOREPLY_EMAIL_FOOTER);
            }

            if (templateID > 0)
            {
                footer = footer + "<br/><br/>EmailID: " + templateID;
            }

            if (!string.IsNullOrEmpty(fullName))
            { content = string.Format("Dear {0}<br/><br/>{1}", txtInfo.ToTitleCase(fullName.ToLower()+":"), messageBody); }
            else
            { content = messageBody; }

            content = string.Format("{0} {1}", content, footer);

            return content;
        }

 public static string GetAppSettingsValue(String key)
        {
            return ConfigurationManager.AppSettings.Get(key);
        }

Saturday, January 6, 2024

Query to get the Employee name and their Manager name from the same table in SQL Server

Query to get the Employee name and their manager's name from the same table in SQL Server
 
Below is Employee Table 

SELECT e.employeename, m.employeename AS ManagerName FROM Employee e JOIN Employee m ON e.ManagerId = m.EmployeeId 





Tuesday, December 13, 2022

Angular - ng.ps1 cannot be loaded because running scripts is disabled on this system. ng server is not working, ng is not recognized.

 ng server is not working (ng is not recognized):


If ng serve is not recognized or not worked in out angular application we will get below error message in Terminal window.

Execute below command in Terminal.

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted


Thursday, December 1, 2022

How to move item in an array to last position in javascript.

const arrayList = ['1', '2', '3', '5', '0'];
const moveThreeToEnd = (arrayList) => {
return arrayList.filter(item => item !== '3').concat(arrayList.filter(item => item === '3'))

}

console.log(array list); //['1', '2', '3', '5', '0' ];
console.log(moveThreeToEnd(array list)); // ['1', '2', '5', '0', '3'];

Monday, January 24, 2022

How to disable mat text box filed in angular

 How to disable mat form filed in angular.


isDisableField: boolean = true;

In html need add [readonly] = "isDisableField"

in CSS: 

.disable-field {

pointer-events: none;

.mat-form-field-flex {
background--color: gray;
}
.mat-form-field-outline {
display : none;
}

}

Get Local Date format without time in angular.

Get Local Date format without time in angular. 


getLocalDateWithOutTime(dateValue: string | Date): string {
        const localDateTime = dateValue instanceof Date ? dateValue : new Date(dateValue);
        const dateString = localDateTime.getFullYear() + '-' +
            (localDateTime.getMonth() > 8 ? localDateTime.getMonth() + 1 :
             '0' + (localDateTime.getMonth() + 1)) + '-' +
            (localDateTime.getDate() > 9 ? localDateTime.getDate() :
             '0' + localDateTime.getDate());
        return dateString;
    }