public void Invoke()
        {
            LogMessage("Starting execution of daily consolidated CS task");

            if (NeedsExecution())
            {
                LogMessage("Valid day for execution of consolidated CS task");

                LogMessage($"Date range is { GetExecutionDateRange()}");

                var tasksCreatedFromDateRange =
                    _reportingService.GetNotificationsForCollectiveCSTasks(
                        GetExecutionDateRange());

                if (tasksCreatedFromDateRange == null)
                {
                    LogMessage("No records found for date range");
                    return;
                }

                LogMessage($"Tasks created for date range is {tasksCreatedFromDateRange?.Count()}");

                var notifications = GetNotificationsFromTasks(tasksCreatedFromDateRange);

                LogMessage($"Notifications created for date range is {notifications?.Count()}");

                if (notifications == null)
                {
                    LogMessage("No notifications found");
                    return;
                }

                LogMessage("Sending emails");

                _emailService.SendBulkEmail(notifications);

                foreach (var notification in notifications)
                {
                    var emailTracker = new EmailTracker
                    {
                        Subject      = notification.Subject,
                        ToAddresses  = notification.ToAddresses,
                        Body         = notification.Body,
                        CcAddresses  = notification.CcAddresses,
                        BccAddresses = notification.BccAddresses,
                        Source       = ApplicationSource.Notification.ToString()
                    };

                    _emailTrackerService.InsertEmail(emailTracker);
                }

                LogMessage("Emails sent");
            }
        }
        public void Invoke()
        {
            try
            {
                Console.WriteLine($"Application Started at {DateTime.Now.ToString()}");
                LogMessage($"Application Started at {DateTime.Now.ToString()}");

                var skills
                    = _reportingService.GetSkillsForNewTasksAddeddYesterday();

                if (skills == null ||
                    skills.Count() == 0)
                {
                    Console.WriteLine($"No skills fetched from DB. Process Ended");
                    LogMessage($"No skills fetched from DB. Process Ended");

                    return;
                }

                Console.WriteLine($"Number skills fetched from DB = {skills.Count()}");
                LogMessage($"Number skills fetched from DB = {skills.Count()}");

                var notifications = GetNotificationsFromSkills(skills);

                Console.WriteLine($"Sending bulk emails");
                LogMessage($"Sending bulk emails");

                _emailService.SendBulkEmail(notifications);

                foreach (var notification in notifications)
                {
                    var emailTracker = new EmailTracker
                    {
                        Subject      = notification.Subject,
                        ToAddresses  = notification.ToAddresses,
                        Body         = notification.Body,
                        CcAddresses  = notification.CcAddresses,
                        BccAddresses = notification.BccAddresses,
                        Source       = ApplicationSource.Notification.ToString()
                    };

                    _emailTrackerService.InsertEmail(emailTracker);
                }

                Console.WriteLine($"Sending bulk emails completed");
                LogMessage($"Sending bulk emails completed");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while executing :: {ex.StackTrace}");
                LogMessage($"An error occurred while executing :: {ex.StackTrace}");
            }
        }
Exemplo n.º 3
0
        public IEnumerable <TModel> CreateModelList <TModel>(IEnumerable <email_tracker> inputList) where TModel : class
        {
            var modelList = new List <EmailTracker>();

            foreach (var dbTask in inputList)
            {
                var emailTracker = new EmailTracker();
                emailTracker = CreateModel <EmailTracker>(dbTask);
                modelList.Add(emailTracker);
            }
            return(modelList as IEnumerable <TModel>);
        }
        public void Invoke()
        {
            try
            {
                var firmInitiatives = _reportingService.GetFirmInitiativeTasksCreatedYesterday();

                if (firmInitiatives == null || firmInitiatives?.Count() == 0)
                {
                    Console.WriteLine($"No firm initiatives from yesterday. Ending execution");
                    LogMessage($"No firm initiatives from yesterday. Ending execution");

                    return;
                }

                Console.WriteLine($"Number of firm initiatives ={firmInitiatives.Count()}");
                LogMessage($"Number of firm initiatives  ={firmInitiatives.Count()}");

                var notifications = GetNotificationsForNewFirmInitiatives(firmInitiatives);

                Console.WriteLine($"Number of notifications ={notifications.Count()}");
                LogMessage($"Number of notifications  ={notifications.Count()}");

                Console.WriteLine($"Sending bulk emails");
                LogMessage($"Sending bulk emails");

                _emailService.SendBulkEmail(notifications);

                foreach (var notification in notifications)
                {
                    var emailTracker = new EmailTracker
                    {
                        Subject      = notification.Subject,
                        ToAddresses  = notification.ToAddresses,
                        Body         = notification.Body,
                        CcAddresses  = notification.CcAddresses,
                        BccAddresses = notification.BccAddresses,
                        Source       = ApplicationSource.Notification.ToString()
                    };

                    _emailTrackerService.InsertEmail(emailTracker);
                }

                Console.WriteLine($"Sending bulk emails completed");
                LogMessage($"Sending bulk emails completed");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while executing :: {ex.StackTrace}");
                LogMessage($"An error occurred while executing :: {ex.StackTrace}");
            }
        }
Exemplo n.º 5
0
        private void SendEmail(string sender, string recipient)
        {
            using (MailMessage message = new MailMessage(sender, recipient))
            {
                message.Subject      = "Email from: " + sender;
                message.BodyEncoding = System.Text.Encoding.ASCII;
                message.Body         = "Trying to get the Exchange Server to break.";
                //Add Tracker info to the email header
                EmailTracker.Tag(message);

                // Send the Email.
                _emailController.Send(message);
                _operationLog.Append("Sent email from: ").Append(sender);
                _operationLog.Append(" to: ").AppendLine(recipient);
            }
        }
Exemplo n.º 6
0
        //private List<TaskApproval> ProcessApplicantForTaskApprovals(IList<taskapplicant> taskApplicants)
        //{

        //}

        public int AssignTask(AssignTaskRequest taskRequest)
        {
            var userContext         = _commonService.GetCurrentUserContext();
            var dbApprovedApplicant = new approvedapplicant();

            dbApprovedApplicant.ID           = taskRequest.TaskApplicantId;
            dbApprovedApplicant.TASK_ID      = taskRequest.TaskId;
            dbApprovedApplicant.APPLICANT_ID = taskRequest.ApplicantId;
            MapAuditFields <approvedapplicant>(ActionType.Insert, dbApprovedApplicant);
            var result = _requestorRepository.AssignTask(dbApprovedApplicant);

            if (result > 0)
            {
                var task                 = _taskRepository.GetTaskById(taskRequest.TaskId);
                var offering             = _commonService.GetOfferings().Where(x => x.Id == task.OFFERING_ID).Select(x => x.Description).FirstOrDefault();
                var applicant            = _requestorRepository.GetTaskApplicantByApplicantId(taskRequest.TaskApplicantId);
                var applicantUserContext = _commonService.MapDetailsFromDeloitteNetworkWithoutUserContextObject(applicant.user.EMAIL_ID.Split('@')[0]);
                var RMGroupEmailAddress  = _commonService.GetRMGroupEmailAddress(applicantUserContext.Department);

                var ccEmailAddress = taskRequest.TaskTypeId == 1
                    ? $"{userContext.EmailId};{applicant.user.MANAGER_EMAIL_ID};{RMGroupEmailAddress}"
                    : userContext.EmailId;

                var mailMessage  = EmailHelper.AssignNotification(applicant.user.FIRST_NAME + Constants.Space + applicant.user.LAST_NAME, applicant.task.TASK_NAME, applicant.task.PROJECT_NAME, applicant.task.PROJECT_WBS_Code, applicant.user.EMAIL_ID, ccEmailAddress, offering);
                var emailTracker = new EmailTracker
                {
                    ToAddresses = applicant.user.EMAIL_ID,
                    Subject     = mailMessage.Subject,
                    Body        = mailMessage.Body,
                    TaskId      = taskRequest.TaskId,
                    Source      = ApplicationSource.WebApp.ToString()
                };

                if (ccEmailAddress != null)
                {
                    emailTracker.CcAddresses.Add(ccEmailAddress);
                }

                _emailTrackerService.InsertEmail(emailTracker);
            }
            return(result);
        }
        public static void SendEmail(string ToEmailId, string Subject, string BodyMessage, string MailFrom)
        {
            EmailTracker _emailTracker = new EmailTracker()
            {
                ToEmailId   = ToEmailId,
                MailSubject = Subject,
                MailBody    = BodyMessage,
                MailFrom    = MailFrom,
                Status      = eEmailStatus.Success.ToString(),
                Result      = "Email Sent Successfull to the given emailId",
                DateCreated = DateTime.Now
            };

            try
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(MailAddressFrom, MailFrom);
                string[] emailList = ToEmailId.Split(',');
                foreach (var item in emailList)
                {
                    mailMessage.To.Add(new MailAddress(item));
                }
                mailMessage.IsBodyHtml = true;
                mailMessage.Subject    = Subject;
                mailMessage.Body       = BodyMessage;
                mailMessage.IsBodyHtml = true;
                mailMessage.Priority   = MailPriority.High;
                SmtpClient smtpClient = new SmtpClient(SmtpClient);
                smtpClient.Port = Convert.ToInt32(SmtpPort);
                System.Net.NetworkCredential MyCache = new System.Net.NetworkCredential(NetworkCredentialEmail, NetworkCredentialPwd);
                smtpClient.Credentials = MyCache;
                smtpClient.EnableSsl   = false;
                smtpClient.Send(mailMessage);
                bAdministrator.CreateEmailTracker(_emailTracker);
            }
            catch (Exception ex)
            {
                _emailTracker.Status = eEmailStatus.Fail.ToString();
                _emailTracker.Result = "Failed: " + ex.Message;
                bAdministrator.CreateEmailTracker(_emailTracker);
            }
        }
Exemplo n.º 8
0
        public static async Task ProcessDeliveryStatusQueue(
            [QueueTrigger(DELIVERY_STATUS_QUEUE)] string deliveryStatusQueue,
            [Table(EMAIL_BLOCKED)] IAsyncCollector <EmailBlocked> tbEmailBlocked,
            [Table(EMAIL_TRACK)] CloudTable tbEmailTrack,
            int dequeueCount,
            ILogger log)
        {
            try
            {
                log.LogInformation($"New status to update. Dequeue count for this item: {dequeueCount}.");
                var deliveryStatusList = JsonConvert.DeserializeObject <List <DeliveryWebHook> >(deliveryStatusQueue);

                foreach (var status in deliveryStatusList)
                {
                    if (DeliveryEvents.Contains(status.Event))
                    {
                        if (BlockerEvents.Contains(status.Event))
                        {
                            log.LogInformation($"Blocking email {status.Email}...");
                            await EmailBlocker.Create(tbEmailBlocked, status.Email, JsonConvert.SerializeObject(status), status.Event);
                        }
                        //TODO: Add to a list of Delivery Events
                        await EmailTracker.Update(tbEmailTrack, status.Email, status.TrackerId, status.Event, log, status.SgMessageId);
                    }
                    else if (EngagementEvents.Contains(status.Event))
                    {
                        //TODO: Add to a list of Engagement Events
                        await EmailTracker.Update(tbEmailTrack, status.Email, status.TrackerId, status.Event, log, status.SgMessageId);
                    }
                    else
                    {
                        throw new Exception($"Event not mapped {status.Event}.");
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError("An error has occurred: {0}", ex);
                throw;
            }
        }
Exemplo n.º 9
0
        public static async Task ProcessEmailQueue(
            [QueueTrigger(EMAIL_QUEUE)] OutgoingEmail emailQueue,
            [Table(EMAIL_TRACK)] CloudTable tbEmailTrack,
            [Table(EMAIL_BLOCKED)] CloudTable tbEmailBlocked,
            int dequeueCount,
            ILogger log)
        {
            log.LogInformation($"New email to send. Dequeue count for this message: {dequeueCount}.");

            try
            {
                var toEmail = emailQueue.ToAddress.Email;

                //Check whether the recipient of the message is blocked
                //TODO: Change this method to check if the email is blocked calling a SendGrid Api
                var recipientIsBlocked = await EmailBlocker.CheckIfBlocked(toEmail, tbEmailBlocked);

                if (recipientIsBlocked)
                {
                    log.LogInformation($"Can't send email to {toEmail} because it has been blocked");
                    await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.Blocked, log);

                    return;
                }

                var response = await SendMail.SendSingleEmail(emailQueue.FromAddress, emailQueue.ToAddress, emailQueue.Subject, emailQueue.Body,
                                                              emailQueue.TrackerId, log);

                if (!SuccessStatusCodes.Contains(response.StatusCode))
                {
                    throw new Exception($"Error sending mail. SendGrid response {response.StatusCode}");
                }
                //Track that email request was sent
                await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.SendRequested, log, response.MessageId);
            }
            catch (Exception ex)
            {
                log.LogError("An error has occurred: {0}", ex);
                throw;
            }
        }
Exemplo n.º 10
0
        public static async Task <IActionResult> SendEmail(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Queue(EMAIL_QUEUE, Connection = "AzureWebJobsStorage")]  IAsyncCollector <OutgoingEmail> emailQueue,
            [Table(EMAIL_TRACK)] IAsyncCollector <SendEmailTrack> tbEmailTrack,
            ILogger log)
        {
            try
            {
                var body = await req.GetBodyAsync <OutgoingEmail>();

                if (!body.IsValid)
                {
                    log.LogInformation($"Invalid model: {JsonConvert.SerializeObject(body.ValidationResults)}");
                    return(new BadRequestObjectResult(body.ValidationResults));
                }

                log.LogInformation($"Request received from {body.Value.Origin}, message type {body.Value.Type}.");

                //Setting the tracker id for this message.
                body.Value.TrackerId = Guid.NewGuid().ToString();
                //Queue email request
                await emailQueue.AddAsync(body.Value);

                //Track that email request was queued
                await EmailTracker.Create(tbEmailTrack, body.Value, Event.Queued);

                return(new OkObjectResult(new SendMailResponse(body.Value.TrackerId)));
            }
            catch (JsonReaderException jrEx)
            {
                log.LogError("Json request error: {0}", jrEx);
                return(new BadRequestObjectResult("Json format error."));
            }
            catch (Exception ex)
            {
                log.LogError("An error has occurred: {0}", ex);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }
        }
Exemplo n.º 11
0
        public int AllowTask(ApproveTaskRequest taskRequest)
        {
            var userContext = _commonService.GetCurrentUserContext();
            var dbApplicant = new taskapplicant();

            dbApplicant.ID           = taskRequest.TaskApplicantId;
            dbApplicant.APPLICANT_ID = taskRequest.ApplicantId;
            dbApplicant.TASK_ID      = taskRequest.TaskId;
            MapAuditFields <taskapplicant>(ActionType.Update, dbApplicant);
            var result = _requestorRepository.AllowTask(dbApplicant);

            if (result > 0)
            {
                var task          = _taskRepository.GetTaskById(taskRequest.TaskId);
                var offering      = _commonService.GetOfferings().Where(x => x.Id == task.OFFERING_ID).Select(x => x.Description).FirstOrDefault();
                var applicant     = _requestorRepository.GetTaskApplicantByApplicantId(taskRequest.TaskApplicantId);
                var ccMailAddress = applicant.task.CREATED_BY.ToString() + ";" + userContext.EmailId.ToString();
                var mailMessage   = EmailHelper.SendApproveRejectNotification(applicant.user.FIRST_NAME + Constants.Space + applicant.user.LAST_NAME, applicant.task.TASK_NAME, applicant.task.PROJECT_NAME, EmailType.Approved, applicant.user.EMAIL_ID, ccMailAddress, offering);
                var emailTracker  = new EmailTracker
                {
                    ToAddresses = applicant.user.EMAIL_ID,
                    Subject     = mailMessage.Subject,
                    Body        = mailMessage.Body,
                    TaskId      = taskRequest.TaskId,
                    Source      = ApplicationSource.WebApp.ToString()
                };
                foreach (var address in emailTracker.CcAddresses)
                {
                    if (ccMailAddress != null)
                    {
                        emailTracker.CcAddresses.Add(ccMailAddress);
                    }
                }
                _emailTrackerService.InsertEmail(emailTracker);
            }

            return(result);
        }
Exemplo n.º 12
0
 public bool AnalyzeMessage(EmailMessage email)
 {
     return(EmailTracker.IsTagged(email));
 }
Exemplo n.º 13
0
 public EmailTracker CreateEmailTracker(EmailTracker EmailTracker)
 {
     return(_administrator.CreateEmailTracker(EmailTracker));
 }
        public static EmailTracker CreateEmailTracker(EmailTracker EmailTracker)
        {
            dAdministrator _dAdministrator = new dAdministrator();

            return(_dAdministrator.CreateEmailTracker(EmailTracker));
        }
Exemplo n.º 15
0
 public int GetNumberOfTodaysEmail(EmailTracker emailTracker)
 {
     return(GetNumberOfTodaysEmail(emailTracker.Subject, emailTracker.Body, emailTracker.ReferenceId));
 }
Exemplo n.º 16
0
        public int ApplyFITask(int taskId, string requestor)
        {
            try
            {
                var user = _commonService.GetCurrentUserContext();

                var taskApplicant = new taskapplicant
                {
                    APPLICANT_ID         = user.UserId,
                    TASK_ID              = taskId,
                    STATUS               = ApplicantStatus.ManagerApproved.ToString(),
                    STATUS_DATE          = DateTime.Now,
                    STATEMENT_OF_PURPOSE = "Interested for Firm Initiative"
                };

                MapAuditFields(ActionType.Insert, taskApplicant);

                var result = _contributorRepository.ApplyForTask(taskApplicant);

                if (result > 0)
                {
                    var requestorName = _commonService.GetNameFromEmailId(requestor);

                    var task = _taskRepository.GetTaskById(taskId);

                    var offering = _commonService.GetOfferings()
                                   .Where(x => x.Id == task.OFFERING_ID)
                                   .Select(x => x.Description)
                                   .FirstOrDefault();

                    var mailMessage = EmailHelper.ApplyFINotification(
                        requestorName,
                        $"{user.FirstName}{Constants.Space}{user.LastName}",
                        task.TASK_NAME,
                        task.DETAILS,
                        task.HOURS.ToString(),
                        task.ONBOARDING_DATE.Value.ToShortDateString(),
                        requestor,
                        user.EmailId,
                        offering);

                    var emailTracker = new EmailTracker
                    {
                        ToAddresses = requestor,
                        Subject     = mailMessage.Subject,
                        Body        = mailMessage.Body,
                        TaskId      = taskId,
                        Source      = ApplicationSource.WebApp.ToString()
                    };

                    if (user.EmailId != null)
                    {
                        emailTracker.CcAddresses.Add(user.EmailId);
                    }

                    _emailTrackerService.InsertEmail(emailTracker);
                }

                return(result);
            }
            catch (Exception ex)
            {
                var logDetails = new DCode.Models.Common.Log {
                    Description = ex.Message, Details = ex.ToString()
                };
                _commonService.LogToDatabase(logDetails);
                return(-1);
            }
        }
Exemplo n.º 17
0
 public EmailTracker CreateEmailTracker(EmailTracker EmailTracker)
 {
     context.EmailTracker.Add(EmailTracker);
     context.SaveChanges();
     return(EmailTracker);
 }
Exemplo n.º 18
0
        public int UpsertTask(TaskRequest taskRequest)
        {
            var result = 0;

            if (taskRequest.ActionType == ActionType.Insert)
            {
                taskRequest.WBSCode = string.IsNullOrWhiteSpace(taskRequest.WBSCode)
                    ? "WBS00000-00-00-00-0000"
                    : taskRequest.WBSCode;

                var dbTask = _taskModelFactory.CreateModel <TaskRequest>(taskRequest);
                MapAuditFields <task>(ActionType.Insert, dbTask);
                if (taskRequest.SelectedTaskType == "2" ||
                    taskRequest.SelectedTaskType == "3")
                {
                    if (taskRequest.SkillSet == null ||
                        !taskRequest.SkillSet.Any())
                    {
                        var listOfSkills = new List <int>();

                        var skillName = taskRequest.SelectedTaskType == "2"
                            ? Constants.FirmInitiativeSkillRecord
                            : Constants.IndustryInitiativeSkillRecord;

                        var matchedSkill = _taskRepository.GetSkillByName(skillName);

                        listOfSkills.Add(matchedSkill != null
                            ? matchedSkill.ID
                            : default(int));

                        taskRequest.SkillSet = listOfSkills;
                    }
                }
                var dbTaskSkills = _taskSkillModelFactory.CreateModelList(taskRequest.SkillSet);
                foreach (var dbTaskSkill in dbTaskSkills)
                {
                    MapAuditFields <taskskill>(ActionType.Insert, dbTaskSkill);
                }
                result = _taskRepository.InsertTask(dbTask, dbTaskSkills);

                if (taskRequest.SelectedTaskType == "2" &&
                    result == 2)
                {
                    var currentUser = _commonService.GetCurrentUserContext();

                    var offeringRecipients = _commonService.GetFINotificationRecipientsForOffering(
                        Convert.ToInt32(taskRequest.SelectedOffering));

                    offeringRecipients = offeringRecipients != null && offeringRecipients.Any()
                        ? offeringRecipients
                        : _commonService.GetDefaultConsultingMailboxes();

                    var offering = _commonService.GetOfferings()
                                   .Where(x => x.Id == Convert.ToInt32(taskRequest.SelectedOffering))
                                   .Select(x => x.Description)
                                   .FirstOrDefault();

                    var mailMessage = EmailHelper.PostNewFINotification(taskRequest.ProjectName,
                                                                        taskRequest.Hours.ToString(),
                                                                        taskRequest.Description,
                                                                        taskRequest.OnBoardingDate,
                                                                        currentUser.EmailId,
                                                                        offeringRecipients,
                                                                        offering);
                    var emailTracker = new EmailTracker
                    {
                        ToAddresses = ConfigurationManager.AppSettings["DcodeEmailId"],
                        Subject     = mailMessage.Subject,
                        Body        = mailMessage.Body,
                        TaskId      = taskRequest.Id,
                        Source      = ApplicationSource.WebApp.ToString()
                    };

                    if (currentUser.EmailId != null)
                    {
                        emailTracker.CcAddresses.Add(currentUser.EmailId);
                    }


                    if (offeringRecipients != null && offeringRecipients.Any())
                    {
                        emailTracker.BccAddresses.AddRange(offeringRecipients);
                    }

                    _emailTrackerService.InsertEmail(emailTracker);
                }
            }
            else if (taskRequest.ActionType == ActionType.Update)
            {
                var dbTask = _taskModelFactory.CreateModel <TaskRequest>(taskRequest);
                MapAuditFields <task>(ActionType.Update, dbTask);
                result = _taskRepository.UpdateTask(dbTask);
            }
            return(result);
        }
Exemplo n.º 19
0
    public static void CLRSendMail([SqlFacet(MaxSize = 20)] SqlString profileName,
                                   SqlString mailTo,
                                   [SqlFacet(IsNullable = true, MaxSize = 255)] SqlString mailSubject,
                                   SqlString mailBody,
                                   [SqlFacet(IsNullable = true, MaxSize = 500)] SqlString fromAddress,
                                   [SqlFacet(IsNullable = true, MaxSize = 400)] SqlString displayName,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)] SqlString mailCc,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)] SqlString blindCopyRec,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)] SqlString replyAddress,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)] SqlString fileAttachments,
                                   [SqlFacet(IsNullable = true)] SqlBoolean requestReadReceipt,
                                   [SqlFacet(IsNullable = true)] SqlInt16 deliveryNotification,
                                   [SqlFacet(IsNullable = true)] SqlInt16 sensitivity,
                                   [SqlFacet(IsNullable = true)] SqlInt16 mailPriorty,
                                   [SqlFacet(IsNullable = true)] SqlBoolean bodyHtml,
                                   [SqlFacet(IsNullable = true, MaxSize = 20)] SqlString configName)
    {
        SysProfile  MailCLRClient   = null;
        MailMessage eMail           = null;
        SysConfig   sc              = null;
        string      validAttachment = string.Empty;

        try
        {
            //Check parameters
            if (profileName.IsNull || profileName.Value.Trim() == string.Empty)
            {
                SqlContext.Pipe.Send("Parameter @profileName must be specified !");
                return;
            }
            if (mailTo.IsNull || mailTo.Value.Trim() == string.Empty)
            {
                SqlContext.Pipe.Send("Parametar @mailTo must be specified !");
                return;
            }
            if (mailBody.IsNull || mailBody.Value.Trim() == string.Empty)
            {
                SqlContext.Pipe.Send("Parametar @mailBody must be specified !");
                return;
            }
            string error = "";

            if (configName.IsNull || configName.Value.Trim() == string.Empty)
            {
                sc = new SysConfig();
            }
            else
            {
                sc = GetConfig(configName.Value, ref error);
                if (sc == null)
                {
                    LogEntry.LogItem("Configuration is not defined !", "Warning", "There is an error when trying to determine config : " + error, "Config name : " + configName.Value);
                    SqlContext.Pipe.Send("Configuration is not defined !" + error != "" ? "There is an error when trying to determine config : " + error : "");
                    return;
                }
            }

            MailCLRClient = GetClient(profileName.Value, ref error);
            if (MailCLRClient == null)
            {
                LogEntry.LogItem("Profile is not defined !", "Warning", "There is an error when trying to determine profile : " + error, "Profile name : " + profileName.Value);
                SqlContext.Pipe.Send("Profile is not defined !" + error != "" ? "There is an error when trying to determine profile : " + error : "");
                return;
            }


            eMail = ConstructEmailMessage(
                sc,
                mailTo.Value.ToString(),
                mailSubject.IsNull ? "SQLCLR Server Message" : mailSubject.Value.ToString(),
                mailBody.IsNull ? String.Empty : mailBody.Value.ToString(),
                DetermineFromAddress(fromAddress.IsNull ? string.Empty : fromAddress.Value.ToString(), displayName.IsNull ? string.Empty : displayName.Value.ToString(), MailCLRClient),
                mailCc.IsNull ? string.Empty : (string)mailCc.Value,
                blindCopyRec.IsNull ? string.Empty : (string)blindCopyRec.Value,
                replyAddress.IsNull ? string.Empty : (string)replyAddress.Value,
                fileAttachments.IsNull ? string.Empty : (string)fileAttachments.Value,
                ref validAttachment,
                requestReadReceipt.IsNull ? false : (bool)requestReadReceipt.Value,
                sensitivity.IsNull ? -1 : (int)sensitivity.Value,
                deliveryNotification.IsNull ? DeliveryNotificationOptions.None : (DeliveryNotificationOptions)Enum.Parse(typeof(DeliveryNotificationOptions), deliveryNotification.Value.ToString()),
                mailPriorty.IsNull ? MailPriority.Normal : (MailPriority)Enum.Parse(typeof(MailPriority), mailPriorty.Value.ToString()),
                bodyHtml.IsNull ? false : (bool)bodyHtml.Value);



            if (MailCLRClient.client.EnableSsl)
            {
                ServicePointManager.ServerCertificateValidationCallback = (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true;
            }


            if (sc.sendAsync)
            {
                MailCLRClient.client.SendAsync(eMail, null);
            }
            else
            {
                MailCLRClient.client.Send(eMail);
            }

            if (sc.noPiping == false)
            {
                SqlContext.Pipe.Send("Sent successfully!");
            }

            if (sc.loggingLevel == eLoggingLevel.Maximum)
            {
                LogEntry.LogItem("SQLCLR sent e-mail", "Information", "E-mail successfully sent!", eMail.HeaderInformation());
            }

            if (sc.saveEmails)
            {
                EmailTracker.SaveEmail(eMail, MailCLRClient.name == null ? null : MailCLRClient.name, sc.name == null ? null : sc.name, validAttachment, sc.saveAttachments);
            }
        }
        catch (Exception ex)
        {
            //if (sc.noPiping == false)
            SqlContext.Pipe.Send("There is an error in sending e-mail : " + ex.Message + "\r\n" + ex.InnerException == null ? "" : ex.InnerException.Message);

            LogEntry.LogItem("SQLCLR sent e-mail", "Error", "E-mail was not sent!", ex.Message + "\r\n" + ex.InnerException == null ? "" : ex.InnerException.Message);
        }
        finally
        {
            eMail         = null;
            sc            = null;
            MailCLRClient = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
Exemplo n.º 20
0
        public int ApplyTask(int taskId, string emailAddress, string statementOfPurpose)
        {
            try
            {
                var user = _commonService.GetCurrentUserContext();

                var taskApplicant = new taskapplicant
                {
                    APPLICANT_ID         = user.UserId,
                    TASK_ID              = taskId,
                    STATUS               = ApplicantStatus.Active.ToString(),
                    STATUS_DATE          = DateTime.Now,
                    STATEMENT_OF_PURPOSE = statementOfPurpose
                };

                MapAuditFields(ActionType.Insert, taskApplicant);

                var result = _contributorRepository.ApplyForTask(taskApplicant);

                if (result > 0)
                {
                    var task = _taskRepository.GetTaskById(taskId);

                    if (string.IsNullOrWhiteSpace(emailAddress))
                    {
                        emailAddress = user.ManagerEmailId;
                    }

                    var managerName = _commonService.GetNameFromEmailId(emailAddress);

                    _userRepository.UpdateManager(user.UserId, managerName, emailAddress);

                    var RMGroupEmailAddress = _commonService.GetRMGroupEmailAddress(user.Department);

                    var offering = _commonService.GetOfferings().Where(x => x.Id == task.OFFERING_ID).Select(x => x.Description).FirstOrDefault();

                    var mailMessage = EmailHelper.ApplyNotification(
                        managerName,
                        $"{user.FirstName}{Constants.Space}{user.LastName}",
                        task.TASK_NAME,
                        task.PROJECT_NAME,
                        $"{task.HOURS.ToString()}h",
                        task.ONBOARDING_DATE.Value.ToShortDateString(),
                        emailAddress,
                        $"{user.EmailId};{RMGroupEmailAddress}",
                        offering);

                    var emailTracker = new EmailTracker
                    {
                        ToAddresses = emailAddress,
                        Subject     = mailMessage.Subject,
                        Body        = mailMessage.Body,
                        TaskId      = taskId,
                        Source      = ApplicationSource.WebApp.ToString()
                    };

                    if (RMGroupEmailAddress != null)
                    {
                        emailTracker.CcAddresses.Add(RMGroupEmailAddress);
                    }

                    _emailTrackerService.InsertEmail(emailTracker);
                }
                return(result);
            }
            catch (Exception ex)
            {
                var logDetails = new DCode.Models.Common.Log {
                    Description = ex.Message, Details = ex.ToString()
                };
                _commonService.LogToDatabase(logDetails);
                return(-1);
            }
        }
Exemplo n.º 21
0
// ReSharper disable once UnusedMember.Global
    // ReSharper disable once InconsistentNaming
    public static void CLRSendMail([SqlFacet(MaxSize = 20)] SqlString profileName,
                                   SqlString mailTo,
                                   [SqlFacet(IsNullable = true, MaxSize = 255)]
                                   SqlString mailSubject,
                                   SqlString mailBody,
                                   [SqlFacet(IsNullable = true, MaxSize = 500)]
                                   SqlString fromAddress,
                                   [SqlFacet(IsNullable = true, MaxSize = 400)]
                                   SqlString displayName,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)]
                                   SqlString mailCc,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)]
                                   SqlString blindCopyRec,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)]
                                   SqlString replyAddress,
                                   [SqlFacet(IsNullable = true, MaxSize = 4000)]
                                   SqlString fileAttachments,
                                   [SqlFacet(IsNullable = true)] SqlBoolean requestReadReceipt,
                                   [SqlFacet(IsNullable = true)] SqlInt16 deliveryNotification,
                                   [SqlFacet(IsNullable = true)] SqlInt16 sensitivity,
                                   [SqlFacet(IsNullable = true)] SqlInt16 mailPriorty,
                                   [SqlFacet(IsNullable = true)] SqlBoolean bodyHtml,
                                   [SqlFacet(IsNullable = true, MaxSize = 20)]
                                   SqlString configName)
    {
        SysProfile  mailClrClient;
        MailMessage eMail = null;
        SysConfig   sc;
        var         validAttachment = string.Empty;
        var         pipe            = SqlContext.Pipe;

        try
        {
            // Check parameters
            if (profileName.IsNull || profileName.Value.Trim() == string.Empty)
            {
                pipe?.Send("Parameter @profileName must be specified !");
                return;
            }

            if (mailTo.IsNull || mailTo.Value.Trim() == string.Empty)
            {
                pipe?.Send("Parametar @mailTo must be specified !");
                return;
            }

            if (mailBody.IsNull || mailBody.Value.Trim() == string.Empty)
            {
                pipe?.Send("Parametar @mailBody must be specified !");
                return;
            }

            var error = string.Empty;

            if (configName.IsNull || configName.Value.Trim() == string.Empty)
            {
                sc = new SysConfig();
            }
            else
            {
                sc = GetConfig(configName.Value, ref error);
                if (sc == null)
                {
                    LogEntry.LogItem($"Configuration is not defined !", "Warning",
                                     $"There is an error when trying to determine config : {error}",
                                     $"Config name : {configName.Value}");
                    pipe?.Send($"Configuration is not defined !{error}" != string.Empty
                        ? $"There is an error when trying to determine config : {error}"
                        : string.Empty);
                    return;
                }
            }

            mailClrClient = GetClient(profileName.Value, ref error);
            if (mailClrClient == null)
            {
                LogEntry.LogItem("Profile is not defined !", "Warning",
                                 $"There is an error when trying to determine profile : {error}",
                                 $"Profile name : {profileName.Value}");
                pipe?.Send($"Profile is not defined !{error}" != string.Empty
                    ? $"There is an error when trying to determine profile : {error}"
                    : string.Empty);
                return;
            }


            eMail = ConstructEmailMessage(
                sc,
                mailTo.Value,
                mailSubject.IsNull ? "SQLCLR Server Message" : mailSubject.Value,
                mailBody.IsNull ? string.Empty : mailBody.Value,
                DetermineFromAddress(fromAddress.IsNull ? string.Empty : fromAddress.Value,
                                     displayName.IsNull ? string.Empty : displayName.Value, mailClrClient),
                mailCc.IsNull ? string.Empty : mailCc.Value,
                blindCopyRec.IsNull ? string.Empty : blindCopyRec.Value,
                replyAddress.IsNull ? string.Empty : replyAddress.Value,
                fileAttachments.IsNull ? string.Empty : fileAttachments.Value,
                ref validAttachment,
                !requestReadReceipt.IsNull && requestReadReceipt.Value,
                sensitivity.IsNull ? -1 : sensitivity.Value,
                deliveryNotification.IsNull
                    ? DeliveryNotificationOptions.None
                    : (DeliveryNotificationOptions)Enum.Parse(typeof(DeliveryNotificationOptions),
                                                              deliveryNotification.Value.ToString()),
                mailPriorty.IsNull
                    ? MailPriority.Normal
                    : (MailPriority)Enum.Parse(typeof(MailPriority), mailPriorty.Value.ToString()),
                !bodyHtml.IsNull && bodyHtml.Value);


            if (mailClrClient.Client.EnableSsl)
            {
                // ReSharper disable once RedundantLambdaParameterType
                ServicePointManager.ServerCertificateValidationCallback = (object s, X509Certificate certificate,
                                                                           X509Chain chain, SslPolicyErrors sslPolicyErrors) => true;
            }


            if (sc.SendAsync)
            {
                // mailClrClient.Client.SendCompleted += new
                // SendCompletedEventHandler(SendCompletedCallback);
                // The userState can be any object that allows your callback
                // method to identify this send operation.
                // For this example, the userToken is a string constant.
                // string userState = "SQLCLR does not fire this event";
                // mailClrClient.Client.SendAsync(eMail, userState);
                mailClrClient.Client.SendAsync(eMail, null);
            }
            else
            {
                mailClrClient.Client.Send(eMail);
            }

            if (sc.NoPiping == false)
            {
                pipe.Send("Sent successfully!");
            }

            if (sc.LoggingLevel == ELoggingLevel.Maximum)
            {
                LogEntry.LogItem("SQLCLR sent e-mail", "Information", "E-mail successfully sent!",
                                 eMail.HeaderInformation());
            }

            if (sc.SaveEmails)
            {
                EmailTracker.SaveEmail(eMail, mailClrClient.Name, sc.Name, validAttachment, sc.SaveAttachments);
            }

            // Dispose
            if (sc.SendAsync == false)
            {
                eMail.Dispose();
            }
        }
        catch (Exception ex)
        {
            // if (sc.noPiping == false)
            pipe.Send($"There is an error in sending e-mail : {ex.Message}\r\n{ex.InnerException}" == null
                ? string.Empty
                : ex.InnerException.Message);

            LogEntry.LogItem("SQLCLR sent e-mail", "Error", $"E-mail was not sent!",
                             ex.Message + "\r\n" + ex.InnerException == null ? string.Empty : ex.InnerException.Message);
        }
        finally
        {
            // ReSharper disable once RedundantCheckBeforeAssignment
            if (eMail != null)
            {
                // ReSharper disable once RedundantAssignment
                eMail = null;
            }

            sc            = null;
            mailClrClient = null;
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }