Ejemplo n.º 1
0
        /// <summary>
        /// This function adds/update the job application and creates the candidate if couldn't find one
        /// </summary> 
        /// <param name="jApplication"></param>
        /// <returns></returns>
        // ReSharper disable once FunctionComplexityOverflow
        public JobApplicationPostResponse AddUpdateJobApplication(JobApplication jApplication)
        {
            var response = new JobApplicationPostResponse
            {
                ContactId = -1,
                JobApplicationId = -1
            };
            var context = new dbDataContext();
            // check candidate - create or update candidate details
            if (jApplication.JobApplicationId <= 0)
            {
                var contactId = new Contacts().AddUpdateCandidate(jApplication.Candidate);
                if (contactId > 0)
                    jApplication.ContactId = contactId;
                else
                    return response;
            }
            response.ContactId = jApplication.ContactId;
            // check for job Application - create or update job application details
            var jobApplication = context.tbl_JobApplications.FirstOrDefault(t => t.JobApplicationId == jApplication.JobApplicationId) ?? new tbl_JobApplication();
            jobApplication.CandidateId = jApplication.ContactId;
            jobApplication.JobId = jApplication.JobId;
            jobApplication.AgentId = jApplication.AgentId;
            jobApplication.InternalCandidate = jApplication.InternalCandidate;
            //check for application status changing
            var isAppStatusChanged = (jobApplication.ApplicationStatusId != jApplication.ApplicationStatusId);
            jobApplication.ApplicationStatusId = jApplication.ApplicationStatusId;
            jobApplication.LastUpdatedDate = DateTime.Now;
            jobApplication.ReferrerId = jApplication.ReferrerId;
            jobApplication.ReferredBy = jApplication.ReferredBy;
            jobApplication.ReferringEmpNo = jApplication.ReferringEmpNo;
            jobApplication.UrlReferrer = jApplication.UrlReferrer;

            try
            {
                var isAdd = false;
                // Add/Update candidate
                if (jobApplication.JobApplicationId <= 0)
                {
                    isAdd = true;
                    jobApplication.CreatedDate = DateTime.Now;
                    jobApplication.ApplicationStatusId = jobApplication.ApplicationStatusId < 1 ? 1 : jobApplication.ApplicationStatusId;
                    context.tbl_JobApplications.InsertOnSubmit(jobApplication);
                }
                context.SubmitChanges();

                // Add Application status changed record


                if (isAdd && jobApplication.ApplicationStatusId != 1)
                {
                    //add the new candidates status first
                    new ApplicationStatuses().ChangeApplicationStatuses(jobApplication.JobApplicationId.ToString(), 1);
                }
                if (isAppStatusChanged)
                    new ApplicationStatuses().ChangeApplicationStatuses(jobApplication.JobApplicationId.ToString(), jobApplication.ApplicationStatusId);

                //send notification email 
                if (isAdd && jApplication.SendConfirmationEmail)
                {
                    var contact = new Contacts().GetCandidate(jApplication.ContactId);
                    if (contact != null && !string.IsNullOrEmpty(contact.Email))
                    {
                        try
                        {
                            var template = new Templates().GetTemplates(new TemplateFilter { Title = "Job Application Successful" }).FirstOrDefault();
                            if (template != null)
                            {
                                var emailBody = Utils.GetFullEmailReplacingMainTemplateTags(-1, template.TemplateBody);
                                emailBody = new Utils().GetOriginalBody(emailBody, jApplication.ContactId, jApplication.JobId, 0, 0, 0, contact);
                                //send email
                                var email = new Email
                                {
                                    Body = emailBody,
                                    FromAddress = new Recipient { DisplayName = "Resonate Search", MailAddress = "*****@*****.**" },
                                    Subject = template.Subject,
                                    ToAddress = new Recipient { DisplayName = contact.Forename + " " + contact.Surname, MailAddress = contact.Email }
                                };
                                new Emails().SendEmail(email);
                            }
                        }
                        catch (Exception)
                        {
                            //ignore
                        }
                    }
                }
                if (isAdd)
                    // Add History Record 
                    new Histories().AddHistory(new History
                    {
                        RefId = jApplication.ContactId,
                        RefType = "Contact",
                        ClientUserId = jApplication.UpdatedBy,
                        TypeId = 4,
                        SubRefType = "JobApplication",
                        SubRefId = jobApplication.JobApplicationId
                    });

                response.JobApplicationId = jobApplication.JobApplicationId;
                return response;
            }
            catch (Exception)
            {
                return response;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This function sends copies
        /// </summary>
        /// <param name="emailRequest"></param>
        /// <param name="appendToAddresses"></param>
        /// <param name="fromUser"></param>
        private void SendEmailCopy(PostEmailRequest emailRequest, string appendToAddresses, User fromUser)
        {
            emailRequest.RawBody = appendToAddresses + "<br/>" + emailRequest.RawBody;

            foreach (var ccEmail in emailRequest.CcAddresses)
            {
                try
                {
                    var email = new Email
                    {
                        Subject = emailRequest.Subject,
                        ToAddress = new Recipient { MailAddress = ccEmail },
                        FromAddress = new Recipient
                        {
                            MailAddress = fromUser.Email,
                            DisplayName = fromUser.Forename + " " + fromUser.Surname
                        },
                        Body = emailRequest.RawBody,
                        Attachments = emailRequest.Attachments
                    };
                    // set the from email address with display name
                    SendEmail(email);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// This function sends the email using smtp or mandril
        /// </summary>
        /// <param name="email"></param>
        public void SendEmail(Email email)
        {
            //populate MailMessage object
            var mailObj = new MailMessage
            {
                From = new MailAddress(email.FromAddress.MailAddress, email.FromAddress.DisplayName),
                Subject = email.Subject,
                Body = email.Body,
                IsBodyHtml = true
            };

            // Add to addresses
            mailObj.To.Add(new MailAddress("*****@*****.**", email.ToAddress.DisplayName));
            //mailObj.To.Add(new MailAddress(email.ToAddress.MailAddress, email.ToAddress.DisplayName));

            // attach documents
            if (email.Attachments != null)
            {
                foreach (var att in email.Attachments)
                {
                    if (!string.IsNullOrEmpty(att.UploadUrl))
                    {
                        // upload location
                        var uploadDirPath = HttpContext.Current.Server.MapPath("/system/temp/" + email.Guid + "/");
                        if (!Directory.Exists(uploadDirPath))
                            Directory.CreateDirectory(uploadDirPath);
                        if (!att.UploadUrl.StartsWith("http"))
                        {
                            var docPath = uploadDirPath + Path.GetFileName(att.UploadUrl);
                            //original location
                            var originalDocPath = HttpContext.Current.Server.MapPath(att.UploadUrl);
                            //if not the same location copy to the temp location
                            if (originalDocPath != docPath && !File.Exists(docPath))
                                File.Copy(originalDocPath, docPath);
                            if (File.Exists(docPath))
                                mailObj.Attachments.Add(new Attachment(docPath, MediaTypeNames.Application.Octet));
                        }
                        else
                        {
                            var docPath = uploadDirPath + Path.GetFileName(att.UploadUrl);
                            // copy file to temp location with a guid 
                            if (!File.Exists(docPath))
                                using (var wc = new WebClient())
                                {
                                    wc.DownloadFile(att.UploadUrl, docPath);
                                }
                            // if file exists in the doc path then add that to attachment list
                            if (File.Exists(docPath))
                                mailObj.Attachments.Add(new Attachment(docPath, MediaTypeNames.Application.Octet));
                        }
                    }
                    else if (!string.IsNullOrEmpty(att.Base64String))
                    {
                        // base64string, so create the temp file
                        var path = "/system/temp/" + email.Guid + "/" + att.FileName;
                        var docPath = HttpContext.Current.Server.MapPath(path);
                        // copy file to temp location with a guid 
                        if (!File.Exists(docPath))
                            File.WriteAllBytes(docPath, Convert.FromBase64String(att.Base64String));

                        // if file exists in the doc path then add that to attachment list
                        if (File.Exists(docPath))
                            mailObj.Attachments.Add(new Attachment(docPath, MediaTypeNames.Application.Octet));
                    }
                }
            }

            //send using mandrill
            Mandrill.SendEmail(mailObj);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// This function sends the email and save a record to the database
        /// </summary>
        /// <param name="emailRequest"></param>
        /// <returns></returns>
        // ReSharper disable once FunctionComplexityOverflow
        public PostEmailResponse SendContactEmails(PostEmailRequest emailRequest)
        {
            // init the response object
            var response = new PostEmailResponse { IsSuccess = true, ErrorContacts = new List<EmailSmsError>() };
            try
            {
                User fromUser = null;
                User consultant = null;
                Job job = null;
                User sendUser = null;

                // Retrieve objects if an id passed
                if (emailRequest.JobId > 0)
                    job = new Jobs().GetJob(emailRequest.JobId);
                // get the user if user id passed- who is sending
                if (emailRequest.SentBy > 0)
                    sendUser = new Users().GetUser(emailRequest.SentBy);
                //get the from address
                if (emailRequest.FromUserId > 0)
                    fromUser = new Users().GetUser(emailRequest.FromUserId);

                //Get the consultant/user object
                if (emailRequest.ConsultantId > 0 || (fromUser != null && fromUser.UserType.UserTypeId == 1))
                {
                    consultant = emailRequest.ConsultantId > 0 ? new Users().GetUser(emailRequest.ConsultantId) : fromUser;
                }

                emailRequest.RawBody = Utils.GetFullEmailReplacingMainTemplateTags(emailRequest.FromUserId, emailRequest.RawBody, true, true, false);
                var toAddressesToAppend = "This email has been sent to following contacts, <br />";

                // Get contacts for the filters or sent ids)
                var contactsAndClients = new ClientsAndContacts().GetClientContactsForEmailAndSms(emailRequest.SelectedContactIds, emailRequest.SelectedClientIds);


                //iterate through the contacts and send the sms
                foreach (var obj in contactsAndClients)
                {
                    var contact = obj.ClientOrContact as Candidate;
                    var client = obj.ClientOrContact as Client;
                    EmailSmsError errorContact = null;
                    var email = new Email();

                    // consultant id (if consultant id passed the use that else check whether the from user is a consultant and use that for tags )
                    var consultantId = emailRequest.ConsultantId > 0 ? emailRequest.ConsultantId : ((fromUser != null && fromUser.UserType.UserTypeId == 1) ? fromUser.UserId : 0);

                    // check for the contact email
                    if (contact != null && contact.DoNotEmail)
                    {
                        errorContact = new EmailSmsError { ContactId = contact != null ? contact.CandidateId : (client != null ? client.ClientId : -1), Error = "Contact prefence is not to send emails." };
                        response.ErrorContacts.Add(errorContact);
                    }
                    else if ((contact != null && !string.IsNullOrEmpty(contact.Email)) || (client != null && !string.IsNullOrEmpty(client.Email)))
                    {
                        var intRequestId = 0;
                        // set the interview request
                        if (emailRequest.InterviewRequestId > 0)
                        {
                            intRequestId = emailRequest.InterviewRequestId;
                        }
                        else if (emailRequest.InterviewId > 0)
                        {
                            // interview request email
                            var request = new InterviewRequest
                            {
                                InterviewId = emailRequest.InterviewId,
                                ContactId = contact.CandidateId
                            };
                            intRequestId = new Interviews().AddInterviewRequest(request);
                        }

                        // get the original message 
                        emailRequest.Body = new Utils().GetOriginalBody(emailRequest.RawBody, (contact != null ? contact.CandidateId : -1),
                            emailRequest.JobId, emailRequest.SentBy, consultantId, (client != null ? client.ClientId : -1), contact, job, sendUser, consultant, client, intRequestId, emailRequest.TimeSlotId);

                        //set the to address
                        email.ToAddress = new Recipient
                        {
                            MailAddress = contact != null ? contact.Email : (client != null ? client.Email : ""),
                            DisplayName = contact != null ? (contact.Forename + " " + contact.Surname) : (client != null ? client.ClientName : "")
                        };


                        if (contact != null)
                            toAddressesToAppend += ("&nbsp;&nbsp; - ") + ("\t" + contact.Forename + " " + contact.Surname);
                        else if (client != null)
                            toAddressesToAppend += ("&nbsp;&nbsp; - ") + ("\t" + client.ClientName);
                        toAddressesToAppend += "<br />";

                        // set the from email address with display name
                        if (fromUser != null)
                        {
                            email.FromAddress = new Recipient
                            {
                                MailAddress = fromUser.Email,
                                DisplayName = fromUser.Forename + " " + fromUser.Surname
                            };
                        }
                        else
                        {
                            email.FromAddress = new Recipient
                            {
                                MailAddress = "*****@*****.**",
                                DisplayName = "Resonate Search and Selection"
                            };
                        }

                        email.Subject = emailRequest.Subject;
                        email.Body = emailRequest.Body;
                        email.Attachments = emailRequest.Attachments;
                        // set the guid of not passed
                        email.Guid = string.IsNullOrEmpty(emailRequest.Guid) ? Guid.NewGuid().ToString() : emailRequest.Guid;
                        // send Email
                        try
                        {
                            SendEmail(email);
                        }
                        catch (Exception ex)
                        {
                            //error sending the sms 
                            errorContact = new EmailSmsError { ContactId = contact != null ? contact.CandidateId : (client != null ? client.ClientId : -1), Error = ex.ToString() };
                            response.ErrorContacts.Add(errorContact);
                        }
                    }
                    else
                    {
                        errorContact = new EmailSmsError { ContactId = contact != null ? contact.CandidateId : (client != null ? client.ClientId : -1), Error = "Email Address not found for the " + contact != null ? "contact" : "client" + "!" };
                        response.ErrorContacts.Add(errorContact);
                    }

                    // On success save Email into the database
                    var context = new dbDataContext();
                    var objEmail = new tbl_Email
                    {
                        Body = email.Body,
                        FromAddress = (email != null && email.FromAddress != null) ? email.FromAddress.MailAddress : "",
                        RefId = contact != null ? contact.CandidateId : (client != null ? client.ClientId : -1),
                        RefType = emailRequest.Type,
                        Subject = emailRequest.Subject,
                        SentBy = emailRequest.SentBy,
                        SentDate = DateTime.Now,
                        UserId = emailRequest.FromUserId,
                        Consultant = consultantId,
                        RawBody = emailRequest.RawBody,
                        HasAttachments = (emailRequest.Attachments != null && emailRequest.Attachments.Count > 0),
                        Error = errorContact != null ? errorContact.Error : "",
                        IsError = errorContact != null,
                        Guid = string.IsNullOrEmpty(email.Guid) ? Guid.NewGuid().ToString() : email.Guid,
                        ToAddress = (email != null && email.ToAddress != null) ? email.ToAddress.MailAddress : "",
                        EmailType = "OUT",
                        CcAddresses =
                            emailRequest.CcAddresses != null
                                ? (emailRequest.CcAddresses.Aggregate("", (current, to) => current + (to + ";")))
                                : ""
                    };
                    context.tbl_Emails.InsertOnSubmit(objEmail);
                    context.SubmitChanges();

                    if (errorContact == null)
                    {
                        // Add History 
                        new Histories().AddHistory(new History
                        {
                            RefId = contact != null ? contact.CandidateId : (client != null ? client.ClientId : -1),
                            RefType = contact != null ? "Contact" : "Client",
                            ClientUserId = emailRequest.FromUserId,
                            TypeId = 8,
                            SubRefType = "Email",
                            SubRefId = objEmail.EmailId
                        });
                    }

                    // save attachments into the email location
                    try
                    {
                        var sourcePath = HttpContext.Current.Server.MapPath("/system/temp/" + email.Guid + "/");
                        var destLocation =
                            HttpContext.Current.Server.MapPath("/system/email/" + objEmail.EmailId + "/");
                        if (!Directory.Exists(destLocation))
                            Directory.CreateDirectory(destLocation);
                        if (Directory.Exists(destLocation) && Directory.Exists(sourcePath))
                            Directory.GetFiles(sourcePath)
                                .ToList()
                                .ForEach(f => File.Copy(f, destLocation + "/" + Path.GetFileName(f)));
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
                //Send Copies
                if (emailRequest.CcAddresses != null)
                    SendEmailCopy(emailRequest, toAddressesToAppend, fromUser);
            }
            catch (Exception e)
            {
                response.IsSuccess = false;
                response.Error = e.ToString();
            }
            return response;

        }