Ejemplo n.º 1
0
        private static MailData RenderTemplateInternal(MailTemplate template, IEnumerable<KeyValuePair<string, object>> data)
        {
            var engine = new VelocityEngine();
            engine.Init();

            var context = GetContext(data);

            var result = new MailData
                {
                    Subject = EvaluateTemplate(engine, context, template.Subject),
                    Body = EvaluateTemplate(engine, context, template.Content)
                };
            return result;
        }
Ejemplo n.º 2
0
    protected void btnForgotPwd_Click(object sender, EventArgs e)
    {
        DataTable dt;

        SqlParameter[] sqlparams = new SqlParameter[1];
        sqlparams[0]       = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
        sqlparams[0].Value = txtUserName.Text.Trim();

        try
        {
            dt = SqlHelper.ExecuteDataset(connString, "sp_GetUserPasswordAndEmail", sqlparams).Tables[0];

            string Pwd      = dt.Rows[0]["Password"].ToString();
            string EmailAdd = dt.Rows[0]["EmailAddress"].ToString();

            if (Pwd.Equals("NONE") || EmailAdd.Equals("NONE"))
            {
                txtNote.Text = "Username not found.";
            }
            else
            {
                string from = MailHelper.ChangeToFriendlyName(ConfigurationManager.AppSettings["AdminEmailName"], ConfigurationManager.AppSettings["AdminEmailAddress"]);
                string to   = EmailAdd;

                string subject = "Globe Telecom Vendor Accreditation : Password Request";
                try
                {
                    if (MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(), from, to, subject, MailTemplate.IntegrateBodyIntoTemplate(CreateRequestPasswordBody(Pwd)), MailTemplate.GetTemplateLinkedResources(this)))
                    {
                        txtNote.Text = "Password sent!";
                    }
                    else
                    {
                        txtNote.Text = "Password not sent this time.";
                    }
                }
                catch
                {
                    txtNote.Text = "Password not sent this time.";
                }
                txtUserName.Text = "";
            }
        }
        catch (Exception ex)
        {
            txtNote.Text = ex.Message.ToString();
        }
    }
Ejemplo n.º 3
0
        public MailTemplateModel(MailTemplate template)
        {
            _mailTemplate = template;

            LoadedTime = DateTime.Now;
        }
Ejemplo n.º 4
0
    //############################################################
    //############################################################
    private bool SendEmailNotification()
    {
        bool success = false;

        string fromName     = "";
        string fromEmail    = "";
        string from         = "";
        string toName       = "";
        string toEmail      = "";
        string to           = "";
        string subject      = "";
        string oProjectName = "";
        string oVSFId       = "";

        query = "SELECT t1.VSFId, t1.ProjectName, t2.BuyerFirstName + ' ' + t2.BuyerMidName + ' ' + t2.BuyerLastName AS BuyerName, t2.EmailAdd as BuyerEmail, t3.FirstName + ' ' + t3.MiddleName + ' ' + t3.LastName AS PurchasingName, t3.EmailAdd as PurchasingEmail FROM tblVendorShortlistingForm t1, tblBuyers t2, tblPurchasing t3 WHERE t1.VSFId=@VSFId AND t2.BuyerId = t1.BuyerId AND t3.PurchasingId = t1.PurchasingId";
        //query = "sp_GetVendorInformation"; //##storedProcedure
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                cmd.Parameters.AddWithValue("@VSFId", Convert.ToInt32(Session["VSFId"]));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        oVSFId       = oReader["VSFId"].ToString();
                        oProjectName = oReader["ProjectName"].ToString();

                        fromName  = oReader["PurchasingName"].ToString();
                        fromEmail = oReader["PurchasingEmail"].ToString();
                        from      = '"' + oReader["PurchasingName"].ToString() + '"' + " <" + oReader["BuyerEmail"].ToString() + ">";

                        toName  = oReader["BuyerName"].ToString();
                        toEmail = oReader["BuyerEmail"].ToString();
                        to      = '"' + oReader["BuyerName"].ToString() + '"' + " <" + oReader["PurchasingEmail"].ToString() + ">";
                    }
                }
            }
        }

        //Response.Write(from + "<br>");
        //Response.Write(to + "<br>");
        //Response.Write(subject + "<br>");
        //Response.Write(CreateNotificationBody() + "<br>");
        //Response.Write(MailTemplate.GetTemplateLinkedResources(this) + "<br>");

        try
        {
            if (Request.Form["__EVENTTARGET"] == "Approve")
            {
                subject = "VSF Approved";
                if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                          from,
                                          to,
                                          subject,
                                          CreateNotificationBody(oVSFId, oProjectName, fromName, toName),
                                          MailTemplate.GetTemplateLinkedResources(this)))
                {       //if sending failed
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Sending Failed to " + from, System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {       //if sending successful
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Email Sent to " + from, System.Diagnostics.EventLogEntryType.Information);
                }
            }
            if (Request.Form["__EVENTTARGET"] == "Clarify")
            {
                subject = "VSF for Clarification";
                if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                          from,
                                          to,
                                          subject,
                                          CreateNotificationBodyClarify(oVSFId, oProjectName, fromName, toName),
                                          MailTemplate.GetTemplateLinkedResources(this)))
                {       //if sending failed
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Sending Failed to " + from, System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {       //if sending successful
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Email Sent to " + from, System.Diagnostics.EventLogEntryType.Information);
                }
            }
            if (Request.Form["__EVENTTARGET"] == "Reject")
            {
                subject = "VSF Rejected";
                if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                          from,
                                          to,
                                          subject,
                                          CreateNotificationBodyReject(oVSFId, oProjectName, fromName, toName),
                                          MailTemplate.GetTemplateLinkedResources(this)))
                {       //if sending failed
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Sending Failed to " + from, System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {       //if sending successful
                    LogHelper.EventLogHelper.Log("Bid > Send Notification : Email Sent to " + from, System.Diagnostics.EventLogEntryType.Information);
                }
            }
            success = true;
        }
        catch (Exception ex)
        {
            success = false;
            LogHelper.EventLogHelper.Log("Bid > Send Notification : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
        }
        return(success);
    }
        public MailTemplate ReplaceHolderTemplate <T>(MailTemplate template, T value)
        {
            try
            {
                MailTemplate currentTemplate = new MailTemplate();
                MergeObjects(template, currentTemplate);

                //assign basic value to return model

                // regEx to find replaceHolder
                string pattern = @"\" + "[" + @"\w+\" + "]";

                #region Replace properties of supporter
                var matchBody    = Regex.Match(currentTemplate.Body, pattern);
                var matchSubject = Regex.Match(currentTemplate.Subject, pattern);
                //contain all placeholder of title and body
                List <string> placeHolders = new List <string>();

                //while has placeholder
                while (matchBody.Value != "")
                {
                    placeHolders.Add(matchBody.Value.Replace("[", "").Replace("]", ""));
                    matchBody = matchBody.NextMatch();
                }
                while (matchSubject.Value != "")
                {
                    placeHolders.Add(matchSubject.Value.Replace("[", "").Replace("]", ""));
                    matchSubject = matchSubject.NextMatch();
                }
                //distinct placeholders for optimized loop
                placeHolders = placeHolders.Distinct().ToList();

                //loop all received placeholders and replace it with real value
                string propertyName = null;
                foreach (var item in placeHolders)
                {
                    string replaceTo   = "";
                    string placeHolder = "[" + item + "]";
                    try
                    {
                        propertyName = item;

                        dynamic propValue = GetValueOfProperty <T>(propertyName, value);


                        if (propValue is double || propValue is int || propValue is long)
                        {
                            replaceTo = String.Format("{0:### ### ### ###}", propValue);
                        }
                        else
                        {
                            replaceTo = propValue.ToString();
                        }
                    }
                    catch (Exception)
                    {
                        replaceTo = "";
                    }
                    currentTemplate.Body    = currentTemplate.Body.Replace(placeHolder, replaceTo);
                    currentTemplate.Subject = currentTemplate.Subject.Replace(placeHolder, replaceTo);
                }
                #endregion
                return(currentTemplate);
            }
            catch
            {
                throw new CustomException("Errors.ERROR_REPLACE_PLACEHOLDERS");
            }
        }
        // This method can be used for testing purposes, to save an email to disk instead of sending it.
        public static bool Save(MailTemplate template, string filename)
        {
            // make sure extension is .eml
            filename = Path.ChangeExtension(filename, ".eml");

            string errorMessage;
            var message = GetMessage(template, out errorMessage);
            if (message == null)
                return false;

            var assembly = typeof(SmtpClient).Assembly;
            var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

            using (var fileStream = new FileStream(filename, FileMode.Create))
            {
                var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
                var mailWriter = mailWriterContructor.Invoke(new object[] { fileStream });
                var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
                sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { mailWriter, true }, null);
                var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
                closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
            }

            if (template.StoreHistory)
            {
                long? mailId = StoreMailHistory(message, template.TypeName, true, errorMessage);
                template.MailId = mailId;
            }

            return true;
        }
Ejemplo n.º 7
0
        private  string GetEmailTemplate(CreateCouponViewModel createCouponVm,IMyMentorRepository repository)
        {
            var currenctUserFullName = Session.GetLoggedInUser().GetFullName(Language.CurrentLanguageCode);
            var teacherFullName = createCouponVm.TeacherData.TeacherFullName;

            var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);

            var itemType = repository.FindEntities().Single(x => x.EntityCode == EntityKeys.Coupons.ToString());
            var mailTemplate = new MailTemplate(Language.CurrentCulture);
          
            var emailData = new CouponEmailData();
            emailData.TeacherFullName =currenctUserFullName == teacherFullName ? createCouponVm.TeacherData.TeacherFullName:currenctUserFullName;
            emailData.CouponNumber = createCouponVm.CouponId;
            emailData.Event = createCouponVm.EventId;
            emailData.ItemNamePart1 = createCouponVm.ContentItemDetails.NamePart1;
            emailData.ItemNamePart2 = createCouponVm.ContentItemDetails.NamePart2;
            emailData.ItemType = itemType.GetLocalizedField("EntityName");
            emailData.OriginalPriceWithCurrency = createCouponVm.ContentItemDetails.FormattedOriginalPrice;
            emailData.StudentPriceWithCurrency = createCouponVm.CouponDiscountPrice.ToCurrency(currencyRetriever.GetCurrent());
            emailData.ValidUntil = createCouponVm.CouponValidUntil;
            emailData.PurchaseDate = DateTime.Now.ToString("dd/MM/yyyy");
            if (!string.IsNullOrEmpty(createCouponVm.EventId))
            {
                emailData.Event = string.Format(MyMentorResources.couponLetterEventPlaceholder, createCouponVm.EventId);
            }            
           
            var mailForStudent = mailTemplate.GetCouponEmail(emailData);
            return mailForStudent;
        }
Ejemplo n.º 8
0
 private void CreateMailTemplate()
 {
     _mailTemplate = new MailTemplate();
 }
Ejemplo n.º 9
0
    //====================================================================================
    private string CreateCongratsEmailBody(DataRow drVendor, DataTable dtBidItems)
    {
        StringBuilder sb = new StringBuilder();

        ArrayList Awarded       = new ArrayList();
        ArrayList notAwarded    = new ArrayList();
        string    vendorName    = drVendor["VendorName"].ToString();
        string    officialRep   = drVendor["KeyPersonnel"].ToString();
        string    orDesignation = drVendor["KpPosition"].ToString();
        string    bidEvent      = drVendor["ItemDesc"].ToString();
        string    buyerName     = drVendor["BuyerName"].ToString();

        if (dtBidItems.Rows.Count > 0)
        {
            for (int i = 0; i < dtBidItems.Rows.Count; i++)
            {
                DataRow drBidItem = dtBidItems.Rows[i];

                string itemDesc    = drBidItem["ItemDesc"].ToString();
                string awardStatus = drBidItem["AwardStatus"].ToString();

                if (awardStatus == "WonItem")
                {
                    Awarded.Add(itemDesc);
                }
                else
                {
                    notAwarded.Add(itemDesc);
                }
            }
        }

        sb.Append("<tr><td style='width: 5%; height: 13px;'></td><td style='width: 90%; height: 13px;' colspan=''></td><td style='width: 5%; height: 13px;'></td></tr><tr><td style='width: 5%; height: 635px'></td><td style='width: 90%'><br />");
        sb.Append(DateTime.Now.ToLongDateString());
        sb.Append("<br /><br />");
        sb.Append(officialRep);
        sb.Append("<br />");
        sb.Append(orDesignation);
        sb.Append("<br /><strong>");
        sb.Append(vendorName);
        sb.Append("</strong><br />");
        sb.Append("<br /><br />");
        sb.Append("Dear Mr/Madame,");
        sb.Append("<br /><br />");
        sb.Append("Re: Letter of Award - " + bidEvent);
        sb.Append("<br /><br />");
        sb.Append("Trans-Asia / Commnunications is pleased to inform you that your bid tender for the following item:");
        sb.Append("<br />");
        sb.Append("<ol>");
        for (int i = 0; i < Awarded.Count; i++)
        {
            sb.Append("<li>" + Awarded[i] + "</li>");
        }
        sb.Append("</ol>");
        sb.Append("<br /><br />");
        sb.Append("Was approved for awarding. Below are the items not awarded to you:");
        sb.Append("<br />");
        sb.Append("<ol>");
        for (int i = 0; i < notAwarded.Count; i++)
        {
            sb.Append("<li>" + notAwarded[i] + "</li>");
        }
        sb.Append("</ol>");
        sb.Append("<br /><br />");
        sb.Append("Kindly get in touch with " + buyerName + " for further details");
        sb.Append("<br /><br />");
        sb.Append("We sincerely appreciate the time and effort you have dedicated to conform with our requirements and we look forward to working with you on the fulfillment of " + bidEvent + ".");
        sb.Append("<br /><br />");
        sb.Append("Please do not reply.");
        sb.Append("<br /><br />");
        sb.Append("Very truly yours,");
        sb.Append("<br /><br />");
        sb.Append("T. Jefferson M. de Leon");
        sb.Append("<br />");
        sb.Append("<i>Head-Logistics</i>");
        sb.Append("<br /><br />");
        sb.Append("Cc:&nbsp; EC Santiago");
        sb.Append("</td><td style='width: 5%; height: auto'></td></tr><tr><td style='width: 5%'></td><td style='width: 90%'></td><td style='width: 5%'></td></tr>");
        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
 public EMailSourceHandlerException(string message, string subject, string body) : base(message)
 {
     MailTemplate = new MailTemplate(ResponseTemplate.MiniMailOnEmptyRecipients, subject, body);
 }
Ejemplo n.º 11
0
    private string CreateBody(
        int status,
        string vendorname,
        string vendorAddress,
        string vendorAddress1,
        string vendorAddress2,
        string vendorAddress3,
        string vendorcontactperson,
        string vendorphone,
        string vendorfax
        )
    {
        BidDetails details = GetBidItemDetails(int.Parse(((HiddenField)dvEventDetails.Rows[5].Cells[1].FindControl("hdn_bidrefno")).Value.ToString()));
        String     b_Event = ((HiddenField)dvEventDetails.Rows[5].Cells[1].FindControl("hdn_bidevent")).Value.ToString();
        String     b_Item  = dvEventDetails.Rows[2].Cells[1].Text.ToString();

        StringBuilder sb = new StringBuilder();

        if (status == 3) //FOR RENEGOTIATION
        {
            #region CLARIFY BODY

            sb.Append("<tr><td style='width: 5%; height: 13px;'></td><td style='width: 90%; height: 13px;' colspan=''></td><td style='width: 5%; height: 13px;'></td></tr><tr><td style='width: 5%; height: 635px'></td><td style='width: 90%'><br />");
            sb.Append(DateTime.Now.ToLongDateString());
            sb.Append("<br />");
            sb.Append("<br />");
            sb.Append("<br /><strong>");
            sb.Append(vendorname);
            sb.Append("</strong><br />");
            sb.Append("<br /><br />");
            sb.Append("Attention:");
            sb.Append("<br />");
            sb.Append("Re: Request for Clarification: " + b_Item + "</p>");
            sb.Append("<br /><br />");
            sb.Append("Dear Mr/Madame,");
            sb.Append("<br /><br />");
            sb.Append("We would like to request for a clarification on your commercial tender and technical response for Bid Invitation: " + b_Item + ".<br />");
            sb.Append("Kindly refer to this item posted under <strong>Bid Tenders for Clarification</strong> on the e-Sourcing Portal for the details.");
            sb.Append("<br /><br /><br />");
            sb.Append("Very truly yours,<br /><br />");
            sb.Append(details.Sender);
            sb.Append("<br />    ");
            sb.Append("</p></td><td style='width: 5%; height: auto'></td></tr><tr><td style='width: 5%'></td><td style='width: 90%'></td><td style='width: 5%'></td></tr>");

            #endregion
        }
        else if (status == 4) //AWARDED
        {
            #region AWARDED BODY

            sb.Append("<tr><td style='width: 5%; height: 13px;'></td><td style='width: 90%; height: 13px;' colspan=''></td><td style='width: 5%; height: 13px;'></td></tr><tr><td style='width: 5%; height: 635px'></td><td style='width: 90%'><br />");
            sb.Append(DateTime.Now.ToLongDateString());
            sb.Append("<br /><br />");
            sb.Append("Managing Director");
            sb.Append("<br /><strong>");
            sb.Append(vendorname);
            sb.Append("</strong><br />");
            sb.Append("<br /><br />");
            sb.Append("Dear Mr/Madame " + vendorcontactperson + ",");
            sb.Append("<br /><br />");
            sb.Append("Re: Letter of Award - " + b_Item + "");
            sb.Append("<br /><br />");
            sb.Append("Trans-Asia / Commnunications is pleased to inform you that your bid tender has been chosen for " + b_Item + ".");
            sb.Append("Kindly get in touch with " + details.Creator + " for further details");
            sb.Append("<br /><br />");
            sb.Append("We sincerely appreciate the time and effort you have dedicated to conform with our requirements and we look forward to working with you on the fulfillment of " + b_Item + ".");
            sb.Append("<br /><br />");
            sb.Append("Very truly yours,");
            sb.Append("<br /><br />");
            sb.Append("T. Jefferson M. de Leon");
            sb.Append("<br />");
            sb.Append("<i>Head-Logistics</i>");
            sb.Append("<br /><br />");
            sb.Append("Cc:&nbsp; EC Santiago");
            sb.Append("</td><td style='width: 5%; height: auto'></td></tr><tr><td style='width: 5%'></td><td style='width: 90%'></td><td style='width: 5%'></td></tr>");

            #endregion
        }
        else if (status == 5) //NOT AWARDED
        {
            #region NOT AWARDED BODY
            sb.Append("<tr><td style='width: 1px'></td><td style='width: auto' colspan=''></td><td style='width: 1px'></td></tr>");
            sb.Append("<tr><td style='width: auto; height: 635px'></td>");
            sb.Append("<td style='width: 100%; height: auto; text-align: justify;'>");
            sb.Append("<br /><br /><br />");
            sb.Append("" + DateTime.Now.ToLongDateString() + "");
            sb.Append("<br /><br /><br /><strong>");
            sb.Append(vendorname.Trim());
            sb.Append("<br /></strong>");
            sb.Append(vendorAddress.Trim());
            sb.Append("<br />");
            sb.Append(vendorAddress1.Trim());
            sb.Append("<br />");
            sb.Append(vendorAddress2.Trim());
            sb.Append("<br />");
            sb.Append(vendorAddress3.Trim());
            sb.Append("<br /><br />");
            sb.Append("<table style='width: 100%'><tr><td style='width: 1px; height: 8px'>Attention&nbsp; :</td><td style='width: 548px; height: 8px'><strong>");
            sb.Append(vendorcontactperson.Trim());
            sb.Append("</strong></td><td style='width: 1px; height: 8px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
            sb.Append(vendorAddress.Trim());
            sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
            sb.Append(vendorAddress1.Trim());
            sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
            sb.Append(vendorAddress2.Trim());
            sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
            sb.Append(vendorAddress3.Trim());
            sb.Append("</td><td style='width: 1px'></td></tr></table>");
            sb.Append("<br /><br />");
            sb.Append("<table style='width: 100%'><tr><td style='width: 12px'>");
            sb.Append("Bid Event:");
            sb.Append("</td><td style='width: auto'>");
            sb.Append("RFP Results for " + b_Event);
            sb.Append("</td></tr><tr><td style='width: 12px'>");
            sb.Append("Bid Item:");
            sb.Append("</td><td style='width: auto'>");
            sb.Append(b_Item);
            sb.Append("</td></tr></table>");
            sb.Append("<br /><br />");
            sb.Append("Dear Sir:");
            sb.Append("<br /><br />");
            sb.Append("Thank you for your interest to help Trans-Asia  in finding a solution for ");
            sb.Append("" + b_Event + ". It certainly was a pleasure to ");
            sb.Append("have worked with your company during the RFP and the succeeding clarificatory discussions.");
            sb.Append("<br /><br />");
            sb.Append("After careful evaluation of your solution, we regret to inform you that we are unable ");
            sb.Append("to award the project to " + vendorname + ". We will, however, keep in mind your cooperation ");
            sb.Append("and commitment when we have the opportunity to implement other projects.");
            sb.Append("<br /><br />");
            sb.Append("We sincerely appreciate the time and effort you dedicated for the completion of ");
            sb.Append("this RFP and we look forward to working with you again in the future.");
            sb.Append("<br /><br /><br />");
            sb.Append("Sincerely,");
            sb.Append("<br /><br /><br /><br />");
            sb.Append("Ma. Corazon V. Martin");
            sb.Append("<br />");
            sb.Append("Head, Corporate Procurement Department");
            sb.Append("<br /><br /><br /><br /></td><td style='width: auto; height: auto'></td></tr><tr><td style='width: auto'></td><td style='width: auto'></td><td style='width: auto'></td></tr>");
            #endregion
        }
        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 12
0
    private bool SendEmail(string From, string To, string Cc, string Bcc, string Subject, string Body)
    {
        bool success = false;

        if (MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(), From, To, Subject, Body, MailTemplate.GetTemplateLinkedResources(this)))
        {
            success = true;
        }
        return(success);
    }
Ejemplo n.º 13
0
        protected void SendMailFromDb(Project project, dynamic model, ProjectWorkflow.Trigger trigger, UserType userType)
        {
            var template = Repository.GetOne <MailTemplate>(t => t.Trigger == trigger && t.UserType == userType);

            if (template == null)
            {
                template = new MailTemplate
                {
                    UserType = userType,
                    Trigger  = trigger,
                    Title    = "Шаблон письма отсутствует",
                    Body     =
                        string.Format("Необходимо добавить шаблон письма для {0} пользователя на {1} событие", userType,
                                      trigger)
                };
            }

            if (template.UserType == UserType.Admin)
            {
                string[] users = RoleProvider.GetUsersInRole("Admin");

                foreach (var userName in users)
                {
                    Users user = Repository.GetOne <Users>(u => u.Username == userName);
                    if (user != null && user.NotificationTypeList.Contains(project.GetType().Name))
                    {
                        Email
                        .From("*****@*****.**")
                        .UsingClient(Client)
                        .To(user.Email)
                        .Subject(template.Title)
                        .UsingTemplate(template.Body, model)
                        .Send();
                        _protalNotification.PushNotificate(new NotificationQueue
                        {
                            IsRead            = false,
                            NotificationTime  = DateTime.Now,
                            NotificationTitle = template.Title,
                            NotigicationBody  = template.Body,
                            UserName          = user.Username
                        });
                    }
                }
            }

            if (template.UserType == UserType.Investor)
            {
                string investorMail = project.InvestorUser;
                if (string.IsNullOrEmpty(investorMail))
                {
                    investorMail = project.Responses.Last().InvestorEmail;
                }
                Email
                .From("*****@*****.**")
                .UsingClient(Client)
                .To(investorMail)
                .Subject(template.Title)
                .UsingTemplate(template.Body, model)
                .Send();

                _protalNotification.PushNotificate(new NotificationQueue
                {
                    IsRead            = false,
                    NotificationTime  = DateTime.Now,
                    NotificationTitle = template.Title,
                    NotigicationBody  = template.Body,
                    UserName          = project.Responses.Last().InvestorEmail
                });
            }

            if (template.UserType == UserType.User)
            {
                string[] users = RoleProvider.GetUsersInRole("User");

                foreach (var userName in users)
                {
                    MembershipUser user = Membership.GetUser(userName, false);
                    if (user != null)
                    {
                        Email
                        .From("*****@*****.**")
                        .UsingClient(Client)
                        .To(user.Email)
                        .Subject(template.Title)
                        .UsingTemplate(template.Body, model)
                        .Send();
                        _protalNotification.PushNotificate(new NotificationQueue
                        {
                            IsRead            = false,
                            NotificationTime  = DateTime.Now,
                            NotificationTitle = template.Title,
                            NotigicationBody  = template.Body,
                            UserName          = user.UserName
                        });
                    }
                }
            }
        }
Ejemplo n.º 14
0
    private string CreateInvitationBody(BidDetails biddetails, BidParticipant participant)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("<tr><td align='left'><h5>" + DateTime.Now.ToLongDateString() + "</h5></td></tr>");
        sb.Append("<tr><td align='left'><h3>INVITATION TO BID</h3></td></tr>");
        sb.Append("<tr>");
        sb.Append("<td valign='top'>");
        sb.Append("<p>");
        sb.Append("<b>TO: &nbsp;&nbsp;<u>" + participant.Name + "</u></b>");
        sb.Append("<br /><br />");
        sb.Append("Good Day!");
        sb.Append("<br /><br />");
        sb.Append("We are glad to inform you that you have been invited to participate in an online bidding event which was initiated by Trans-Asia");
        sb.Append("</p>");

        sb.Append("<table style='font-size: 12px;width:100%;'>");
        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>1.</td>");
        sb.Append("<td style='font-weight:bold;'>Bid Description</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>" + biddetails.Description + "</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>2.</td>");
        sb.Append("<td style='font-weight:bold;'>Schedule of Bid</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("Submission Deadline : " + biddetails.SubmissionDeadline + "<br />");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>3.</td>");
        sb.Append("<td style='font-weight:bold;'>Payment Details</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("<ul>");
        sb.Append("<li>Payment Terms - indicate applicable terms.</li>");
        // Commented by Angel 10/22/2008 ::  requested by Sir Seth
        //sb.Append("<br />");
        //sb.Append("<li>Billing Details</li>");
        //sb.Append("<ul>");
        //sb.Append("<li>Contact Person: Rose Soteco T# 730 2413</li>");
        //sb.Append("<li>Contact Details: 2F GT Plaza Tower 1, Pioneer cor Madison Sts., Mandaluyong City</li>");
        //sb.Append("</ul>");
        sb.Append("</ul>");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>4.</td>");
        sb.Append("<td style='font-weight:bold;'>Bid Price Details</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>The bid price submitted by the supplier shall be exclusive of VAT.</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>5.</td>");
        sb.Append("<td style='font-weight:bold;'>Price Validity</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("The price quoted must be valid and firm for a period of 90 days.");
        sb.Append("No change in price quoted shall be allowed after bid submission unless negotiated by Trans-Asia");
        sb.Append("</td.");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>6.</td>");
        sb.Append("<td style='font-weight:bold;'>Price Confirmation</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("Responses to the Invitation to Bid/Tender shall be sent by the vendors using the e-Sourcing Portal.");
        sb.Append("Price schedules (details) and other attachments shall be in Acrobat Format(i.e. PDF),");;
        sb.Append("or in any password-protected file (e.g. MS Word, Excel)");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>7.</td>");
        sb.Append("<td style='font-weight:bold;'>Grounds for Invalidating Bids</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("A supplier's bid may be invalidated under any of the following circumstances:");
        sb.Append("<ul>");
        sb.Append("<li>Incomplete bid documents</li>");
        sb.Append("<li>Scanned Summary documents without bidder's signature</li>");
        sb.Append("</ul>");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>8.</td>");
        sb.Append("<td style='font-weight:bold;'>Awarding of Bid</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("The lowest/highest bidder is not necessarily the winning bidder. Trans-Asia shall not be bound to assign any reason for not accepting any bid or accepting it in part.");
        sb.Append("Bids are still subject to further ecaluation. Trans-Asia shall award the winning supplier through a Purchase Order.");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>9.</td>");
        sb.Append("<td style='font-weight:bold;'>Penalties (depends on the items to be purchased)</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");
        sb.Append("</table>");

        sb.Append("<p>");
        sb.Append("<br /><br />");
        sb.Append("######################################################################################<br />");
        sb.Append("&nbsp;Credentials:<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Username: "******"<br /><br />");
        sb.Append("&nbsp;Notes:<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Password is for login.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Username is NOT CASE SENSITIVE.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If you don't know or forgot your password, go to eBid login page and click forgot password.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Use the username provided. Click Send. Your password will be sent to this email address.<br />");
        sb.Append("######################################################################################<br />");
        sb.Append("<br /><br /><br />");
        sb.Append("Sincerely Yours,");
        sb.Append("<br /><br />");
        sb.Append(biddetails.Creator);
        sb.Append("<br /><br />");
        sb.Append("</p>");
        sb.Append("</td>");
        sb.Append("</tr>");

        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 15
0
    private string CreateNotificationBody(string cfromName, string ctoName, string cAuthenticationNumber, string cVendorName, string VendorIdx)
    {
        SqlDataReader oReader;
        string        connstring = ConfigurationManager.ConnectionStrings["AVAConnectionString"].ConnectionString;
        string        cCeo = "", cCeoEmail = "", cAddress = "", cServices = "", cAccreDuration = "";

        query = "SELECT * FROM tblVendorInformation WHERE VendorId = @VendorId";
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cCeo      = oReader["conBidName"].ToString();
                        cCeoEmail = oReader["conBidEmail"].ToString();
                        cAddress  = oReader["regBldgCode"].ToString() != "" ? cAddress + "Bldg. " + oReader["regBldgCode"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgRoom"].ToString() != "" ? cAddress + "Rm. " + oReader["regBldgRoom"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgFloor"].ToString() != "" ? cAddress + oReader["regBldgFloor"].ToString() + " Fr, " : cAddress + "";
                        cAddress  = oReader["regBldgHouseNo"].ToString() != "" ? cAddress + "No. " + oReader["regBldgHouseNo"].ToString() + " " : cAddress + "";
                        cAddress  = oReader["regStreetName"].ToString() != "" ? cAddress + oReader["regStreetName"].ToString() + ", " : cAddress + "";
                        cAddress  = cAddress + "<br>";
                        cAddress  = oReader["regCity"].ToString() != "" ? cAddress + oReader["regCity"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regProvince"].ToString() != "" ? cAddress + oReader["regProvince"].ToString() + ", " : cAddress + "";
                        cAddress  = cAddress + "<br>";
                        cAddress  = oReader["regCountry"].ToString() != "" ? cAddress + oReader["regCountry"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regPostal"].ToString() != "" ? cAddress + oReader["regPostal"].ToString() + " " : cAddress + "";
                    }
                }
            }
        }
        query = "SELECT t1.*, t2.CategoryName, t3.SubCategoryName FROM tblVendorProductsAndServices t1, rfcProductCategory t2, rfcProductSubcategory t3 WHERE t2.CategoryId = t1.CategoryId AND t3.SubCategoryId = t1.SubCategoryId AND t1.VendorId = @VendorId";
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cServices = cServices + "&bull; " + oReader["CategoryName"].ToString() + " - " + oReader["SubCategoryName"].ToString() + "<br>";
                    }
                }
            }
        }

        query = "SELECT * FROM tblVendorApprovalbyVmReco  WHERE VendorId = @VendorId";
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cAccreDuration = oReader["AccreDuration"].ToString();
                    }
                }
            }
        }

        StringBuilder sb   = new StringBuilder();
        string        sTxt = "<table border='1' style='font-size:12px'>";

        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Vendor ID</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + VendorIdx + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Company Name</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + cVendorName + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "</table>";

        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Date: " + DateTime.Now.ToLongDateString() + "<br><br>");
        sb.Append(cCeo + "<br>");
        sb.Append("<b>" + cVendorName + "</b><br>");
        sb.Append(cAddress + "<br><br>");
        sb.Append("</p>");
        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Dear " + cCeo + ":<br><br>");
        sb.Append("Please consider this email as reminders to renew/update your accreditation status with Trans-Asia.<br><br>");
        sb.Append("Looking forward for your compliance on this request before your accreditation expired. Failure to comply will temporarily suspend your company to participate on any upcoming bid events.<br><br>");

        sb.Append("We encourage you to renew your accreditation and continue to be a business partner of Trans-Asia.<br><br>");
        sb.Append("Hope to receive positive response from your end.<br><br>");
        sb.Append("Please get in touch with Marife Pablo of Vendor Management for any clarifications.<br><br>");
        sb.Append(sTxt);
        sb.Append("</p>");
        sb.Append("<br><br><br>");
        sb.Append("Sincerely,<br><br>");
        sb.Append("Trans-Asia<br><br>");
        sb.Append("</td></tr>");
        sb.Append("<tr><td>");
        sb.Append("<p>&nbsp;</p><span style='font-size:10px; font-style:italic;'>Please do not reply to this auto-generated  message.&nbsp;</span>");
        sb.Append("</td></tr>");
        //Response.Write(sb.ToString());
        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 16
0
 public IActionResult EditMessageTemplate(MailTemplate model)
 {
     EmailLogic.EditMailTemplate(model);
     return(Redirect("/Admin/MessageTemplates"));
 }
Ejemplo n.º 17
0
    private void ShowTemplate (MailTemplate currentTemplate)
    {
        this.LabelCountryName.Text = Country.FromCode(currentTemplate.CountryCode).Name;
        this.LabelOrgName.Text = "";
        if (currentTemplate.OrganizationId != 0)
        {
            this.LabelOrgName.Text = Organization.FromIdentity(currentTemplate.OrganizationId).Name;
            ButtonSave.Visible = _authority.HasPermission(Permission.CanEditMailTemplates, currentTemplate.OrganizationId, -1, Authorization.Flag.Default);
        }
        else
        {
            ButtonSave.Visible = _authority.HasPermission(Permission.CanEditMailTemplates, Organization.RootIdentity, -1, Authorization.Flag.Default);
        }

        this.LabelTemplateName.Text = currentTemplate.TemplateName;
        CurrentTemplateNameViewState = currentTemplate.TemplateName;
        CurrentTemplateIdViewState = currentTemplate.TemplateId;
        currentTemplate.NormalizeHtml();

        TypedMailTemplate typedTemplate = TypedMailTemplate.FromName(currentTemplate.TemplateName);
        Dictionary<string, string> placeholders = new Dictionary<string, string>();
        foreach (string ph in typedTemplate.Placeholders.Keys)
        {
            placeholders.Add(ph.ToLower(), ph);
        }

        currentTemplate.MarkPlaceholderSpans(placeholders);

        RadEditor1.Content = currentTemplate.TemplateBody;
        TextBoxSubject.Text = currentTemplate.TemplateTitle;
        SetEditorToolbar();
    }
Ejemplo n.º 18
0
        public static void SendMessage(string sendTo, string subject, string body, string replyTo = "", string sendCc = "", bool sendAsHtml = true)
        {
            var    staticbody    = body;
            string formattedBody = "";

            if (sendAsHtml)
            {
                body          = body.Replace("  ", "&nbsp;&nbsp;");
                body          = body.Replace(Environment.NewLine, "<br>");
                formattedBody = MailTemplate.Replace("{{subject}}", subject);
                formattedBody = formattedBody.Replace("{{body}}", body);
            }

            try
            {
                var msg = new MailMessage
                {
                    From       = new MailAddress(MailFrom),
                    Body       = ((sendAsHtml) ? formattedBody : staticbody),
                    IsBodyHtml = sendAsHtml,
                    Subject    = subject
                };

                bool isAddressed = false;
                if (sendTo.Length > 0)
                {
                    isAddressed = true;
                    msg.To.Add(sendTo);
                }
                if (sendCc.Length > 0)
                {
                    isAddressed = true;
                    msg.CC.Add(sendCc);
                }
                if (!isAddressed)
                {
                    return;
                }

                if (replyTo.Length > 0)
                {
                    msg.ReplyToList.Add(replyTo);
                }
                if (sendAsHtml)
                {
                    if (LogoPath.Length > 0 && formattedBody.IndexOf("cid:") > 0)
                    {
                        var oRes  = new LinkedResource(LogoPath, System.Web.MimeMapping.GetMimeMapping(LogoPath));
                        var iname = System.IO.Path.GetFileName(LogoPath);
                        oRes.ContentId = iname;
                        formattedBody  = formattedBody.Replace("cid:", "cid:" + iname);
                        var oView = AlternateView.CreateAlternateViewFromString(formattedBody, new System.Net.Mime.ContentType("text/html"));
                        oView.LinkedResources.Add(oRes);
                        msg.AlternateViews.Add(oView);
                    }
                }
                SendMessage(msg);
            }
            catch (Exception ex)
            {
                throw new Exception("SendMessage failed: " + ex.Message, ex);
            }
        }
Ejemplo n.º 19
0
    private string CreateNotificationBody(string cfromName, string ctoName, string cAuthenticationNumber, string cVendorName, string VendorIdx, string Username, string Password)
    {
        SqlDataReader oReader;
        string        connstring = ConfigurationManager.ConnectionStrings["AVAConnectionString"].ConnectionString;
        string        cCeo = "", cCeoEmail = "", cAddress = "", cServices = "", cAccreDuration = "";

        query = "SELECT * FROM tblVendorInformation WHERE VendorId = @VendorId";
        //query = "sp_GetVendorInformation"; //##storedProcedure
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cCeo      = oReader["conBidName"].ToString();
                        cCeoEmail = oReader["conBidEmail"].ToString();
                        cAddress  = oReader["regBldgBldg"].ToString() != "" ? cAddress + "Bldg. " + oReader["regBldgBldg"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgUnit"].ToString() != "" ? cAddress + "Rm. " + oReader["regBldgUnit"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgLotNo"].ToString() != "" ? cAddress + oReader["regBldgLotNo"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgBlock"].ToString() != "" ? cAddress + oReader["regBldgBlock"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgPhase"].ToString() != "" ? cAddress + oReader["regBldgPhase"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgHouseNo"].ToString() != "" ? cAddress + "No. " + oReader["regBldgHouseNo"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgStreet"].ToString() != "" ? cAddress + oReader["regBldgStreet"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBldgSubd"].ToString() != "" ? cAddress + oReader["regBldgSubd"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regBrgy"].ToString() != "" ? cAddress + oReader["regBrgy"].ToString() + ", " : cAddress + "";
                        cAddress  = cAddress + "<br>";
                        cAddress  = oReader["regCity"].ToString() != "" ? cAddress + oReader["regCity"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regProvince"].ToString() != "" ? cAddress + oReader["regProvince"].ToString() + ", " : cAddress + "";
                        cAddress  = cAddress + "<br>";
                        cAddress  = oReader["regCountry"].ToString() != "" ? cAddress + oReader["regCountry"].ToString() + ", " : cAddress + "";
                        cAddress  = oReader["regPostal"].ToString() != "" ? cAddress + oReader["regPostal"].ToString() + " " : cAddress + "";
                    }
                }
            }
        }
        conn.Close();

        //Response.Write(VendorIdx);
        //query = "SELECT t1.*, t2.CategoryName FROM tblVendorProductsAndServices t1, rfcProductCategory t2 WHERE t2.CategoryId = t1.CategoryId AND t1.VendorId = @VendorId";
        query = "SELECT t1.*, t2.CategoryName, t3.SubCategoryName FROM tblVendorProductsAndServices t1, rfcProductCategory t2, rfcProductSubcategory t3 WHERE t2.CategoryId = t1.CategoryId AND t3.SubCategoryId = t1.SubCategoryId AND t1.VendorId = @VendorId";
        //query = "sp_GetVendorInformation"; //##storedProcedure
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        //cServices = cServices + "&bull; " + oReader["CategoryName"].ToString() + "<br>";
                        cServices = cServices + "&bull; " + oReader["CategoryName"].ToString() + " - " + oReader["SubCategoryName"].ToString() + "<br>";
                    }
                }
            }
        }
        conn.Close();

        query = "SELECT * FROM tblVendorApprovalbyVmReco  WHERE VendorId = @VendorId";
        //query = "sp_GetVendorInformation"; //##storedProcedure
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(VendorIdx));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cAccreDuration = oReader["AccreDuration"].ToString();
                        //Response.Write(cAccreDuration);
                    }
                }
            }
        }
        conn.Close();



        StringBuilder sb   = new StringBuilder();
        string        sTxt = "<table border='1' style='font-size:12px'>";

        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;UserName</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + Username + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Temporary Password</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + Password + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        //sTxt = sTxt + "<tr>";
        //sTxt = sTxt + "<td><strong>&nbsp;Authentication Ticket</strong></td>";
        //sTxt = sTxt + "<td>&nbsp;" + cAuthenticationNumber + "&nbsp;</td>";
        //sTxt = sTxt + "</tr>";
        sTxt = sTxt + "</table>";

        //sb.Append("<tr><td><p>Sent: " + DateTime.Now.ToLongDateString() + "<br>From: " + cfromName + "<br> To: " + ctoName + "<br><br> Congratulations!<br><br> This is to inform you that application for vendor accreditation has been approved.<br></p><br>" + sTxt + "<p>Very truly yours,<br><br><br> <strong>" + cfromName + "</strong></p><p>&nbsp;</p> <span style='font-size:10px; font-style:italic;'>Please do not reply to this auto-generated  message.&nbsp;</span></td></tr>");
        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Date: " + DateTime.Now.ToLongDateString() + "<br><br>");
        sb.Append(cCeo + "<br>");
        sb.Append("<b>" + cVendorName + "</b><br>");
        sb.Append(cAddress + "<br><br>");
        sb.Append("</p>");
        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Dear " + cCeo + ":<br><br>");
        sb.Append("We are pleased to inform you that Trans-Asia Vendor Management has approved your accreditation.<br><br>");
        //sb.Append("We are pleased to inform you that Trans-Asia Vendor Management has approved your accreditation for the following:<br><br>");
        //sb.Append("<b>PRODUCTS/SERVICES OFFERED   :  </b><br>");
        //sb.Append(cServices + "<br><br><br>");
        sb.Append("Please inform us immediately should there be any change in your products and services, organization, management, ownership, contact numbers, address and other material information which will affect our business relationship.<br><br>");
        sb.Append("This certification is valid for " + cAccreDuration + " from date of issuance. Trans-Asia reserves the right to invite and select suppliers, determine allocation and volume of orders in accordance with the company's procurement policies and objectives. Trans-Asia is also not committed to place an order upon accreditation. <br><br>");
        sb.Append("Your continuing status as an accredited supplier of Trans-Asia depends on your performance as a vendor/service provider subject to regular review and your compliance to company requirements. Consequently, Trans-Asia reserves the right to invite and require you to undergo an accreditation renewal process 60 days prior to the lapse of the " + cAccreDuration + " period.<br><br>");
        sb.Append("As part of Trans-Asia's program for good governance, we would like to take this opportunity to remind you, our business partner, of Trans-Asia's Gifts and Inducement Policy.  Our policy strongly prohibits Trans-Asia employees from soliciting gifts from business partners; and conversely prohibits business partners from giving Trans-Asia employees gifts of any kind in consideration of business, or as an inducement for the award of business.  <br><br>");
        sb.Append("We congratulate you and we look forward to a mutually beneficial and long-lasting business relationship with you. <br><br>");
        sb.Append("Please click the link below and login using the provided username and password for Trans-Asia e-Sourcing System. <br><br>");
        sb.Append("<a href='http://vm2008:300/'>http://vm2008:300/</a><br><br>");
        sb.Append(sTxt);
        sb.Append("</p>");
        sb.Append("<br><br><br><br>");
        sb.Append("Very truly yours,<br><br>");
        sb.Append("<b>Honesto P. Oliva</b><br>");
        sb.Append("Head - Vendor Management<br><br>");
        //sb.Append("<b>Trans-Asia Admin<br><br>");
        sb.Append("</td></tr>");
        sb.Append("<tr><td>");
        sb.Append("<p>&nbsp;</p><span style='font-size:10px; font-style:italic;'>Please do not reply to this auto-generated  message.&nbsp;</span>");
        sb.Append("</td></tr>");
        //Response.Write(sb.ToString());
        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 20
0
        private static MailMessage GetMessage(MailTemplate template, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                var mailMessage = new MailMessage();
                mailMessage.IsBodyHtml = true;

                var body = ProcessBodyHtml(template.GetBody());
                if (template.PerformCssInlineProcessing)
                    body = new CssInliner().Process(body);

                mailMessage.Body = body;
                mailMessage.Subject = template.GetSubject();
                mailMessage.Sender = template.GetSender();
                mailMessage.From = template.GetSender();

                foreach (var recipient in template.GetRecipients())
                    mailMessage.To.Add(recipient);

                foreach (var recipient in template.GetBccRecipients())
                    mailMessage.Bcc.Add(recipient);

                foreach (var attachment in template.GetAttachments())
                    mailMessage.Attachments.Add(attachment);

                return mailMessage;
            }
            catch (Exception exc)
            {
                errorMessage = exc.ToString();
                return null;
            }
        }
    protected virtual MailTemplate GetMailTemplate([NotNull] string templateName, string language)
    {
      Assert.ArgumentNotNull(templateName, "templateName");
      Assert.IsNotNull(this.shopContext, "Unable to build report. ShopContext is not set.");
      Assert.IsNotNull(this.shopContext.Database, "Database must be set.");

      GeneralSettings generalSettings = this.shopContext.GeneralSettings;
      if (!string.IsNullOrEmpty(generalSettings.MailTemplatesLink))
      {
        Item templateItemContainer = this.shopContext.Database.GetItem(generalSettings.MailTemplatesLink, Language.Parse(language));

        if (templateItemContainer != null)
        {
          Item templateItem = templateItemContainer.Children[templateName];

          if (templateItem != null)
          {
            ItemToEntityMapper entityMapper = Context.Entity.Resolve<ItemToEntityMapper>();
            MailTemplate mailTemplate = new MailTemplate();
            entityMapper.Map(templateItem, mailTemplate);
            return mailTemplate;
          }
        }
      }

      return null;
    }
Ejemplo n.º 22
0
        public DummyContext()
        {
            gebruikers   = new List <Gebruiker>();
            materialen   = new List <Materiaal>();
            doelgroepen  = new List <Doelgroep>();
            leergebieden = new List <Leergebied>();

            mailStudent = new MailNaReservatie()
            {
                Body    = "reservatie geslaagd",
                Subject = "Bevestiging reservatie"
            };
            Toon = new Student()
            {
                Email = "*****@*****.**",
                //GebruikersId = "1000000",
                Naam         = "Toon",
                Verlanglijst = new Verlanglijst(),
                Reservaties  = new List <Reservatie>()
            };

            Manu = new Student()
            {
                Email = "*****@*****.**",
                //GebruikersId = "1000000",
                Naam         = "Toon",
                Verlanglijst = new Verlanglijst(),
                Reservaties  = new List <Reservatie>()
            };

            LectorGebruiker = new Lector()
            {
                Email = "*****@*****.**",
                //GebruikersId = "1000000",
                Naam         = "lector",
                Verlanglijst = new Verlanglijst(),
                Reservaties  = new List <Reservatie>()
            };

            LectorGebruiker2 = new Lector()
            {
                Email = "*****@*****.**",
                //GebruikersId = "1000000",
                Naam         = "lector",
                Verlanglijst = new Verlanglijst(),
                Reservaties  = new List <Reservatie>()
            };

            Bol = new Materiaal("Wereldbol", 456, 10)
            {
                IsReserveerBaar = true,
                MateriaalId     = 1
            };
            Kaart = new Materiaal("Kaart", 4587, 5)
            {
                IsReserveerBaar = true,
                MateriaalId     = 2
            };
            Encyclopedie = new Materiaal("Encyclopedie", 111, 80)
            {
                IsReserveerBaar = true,
                MateriaalId     = 3
            };
            GeoDriehoek = new Materiaal("GeoDriehoek", 111, 2)
            {
                IsReserveerBaar = true,
                MateriaalId     = 4
            };

            Bok = new Materiaal("Bok", 20, 1)
            {
                IsReserveerBaar = true,
                MateriaalId     = 2
            };
            StartDatum = "14/03/2016";
            ReservatieWeek1Aantal2Student = new ReservatieStudent(Toon, Bol, StartDatum, 2);
            ReservatieWeek1Aantal8Student = new ReservatieStudent(Toon, Bol, StartDatum, 8);
            ReservatieWeek1Aantal5Student = new ReservatieStudent(Toon, Bol, StartDatum, 5);
            //Reservatie = new Reservatie();
            Student = new Student();
            materialen.Add(Bol);
            materialen.Add(Kaart);
            materialen.Add(Encyclopedie);
        }
Ejemplo n.º 23
0
    private bool SendEmail_ChangeDeadline(BidDetails biddetails, ArrayList recipients)
    {
        //String b_Company = ((Label)((DetailsView)Biddetails_details1.FindControl("dvEventDetails")).Rows[5].Cells[1].FindControl("lblCompany")).Text;

        bool   success      = false;
        string subject      = "Trans-Asia / Commnunications : Changed Submission Deadline Notification";
        int    failedcount  = 0;
        int    successcount = 0;

        try
        {
            #region NOTIFY VENDORS

            for (int i = 0; i < recipients.Count; i++)
            {
                BidParticipant p = (BidParticipant)recipients[i];

                if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                          MailHelper.ChangeToFriendlyName(Session[Constant.SESSION_USERFULLNAME].ToString(), Session[Constant.SESSION_USEREMAIL].ToString()),
                                          MailHelper.ChangeToFriendlyName(p.Name, p.EmailAddress),
                                          subject,
                                          CreateNotificationBody(biddetails, p),
                                          MailTemplate.GetTemplateLinkedResources(this)))
                {       // if sending failed
                    failedcount++;
                    LogHelper.EventLogHelper.Log("Bids > Send Notification : Sending Failed to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {       // if sending successful
                    successcount++;
                    LogHelper.EventLogHelper.Log("Bids > Send Notification : Email Sent to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Information);

                    #region add 1 to emailsent field based on vendorID and BidRefNo

                    //SqlParameter[] sqlparams = new SqlParameter[2];
                    //sqlparams[0] = new SqlParameter("@Vendorid", SqlDbType.Int);
                    //sqlparams[0].Value = p.ID;
                    //sqlparams[1] = new SqlParameter("@BidRefNo", SqlDbType.VarChar);
                    //sqlparams[1].Value = Int32.Parse(Session["BidRefNo"].ToString());
                    //SqlHelper.ExecuteNonQuery(connstring, CommandType.StoredProcedure, "sp_BidInvitationAddEmailSent", sqlparams);
                    #endregion
                }
            }

            #region SMS SENDER
            try
            {
                for (int j = 0; j < recipients.Count; j++)
                {
                    BidParticipant BP = (BidParticipant)recipients[j];

                    if (SMSHelper.AreValidMobileNumbers(BP.MobileNo.Trim()))
                    {
                        SMSHelper.SendSMS(new SMSMessage(CreateInvitationSmsBody(biddetails, BP).Trim(), BP.MobileNo.Trim())).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.EventLogHelper.Log("Bid Event > Send SMS Invitation : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
            #endregion

            #endregion

            #region NOTIFY BUYER

            if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                      MailHelper.ChangeToFriendlyName(Session[Constant.SESSION_USERFULLNAME].ToString(), Session[Constant.SESSION_USEREMAIL].ToString()),
                                      MailHelper.ChangeToFriendlyName(biddetails.Creator, biddetails.CreatorEmail),
                                      subject,
                                      CreateNotificationBody(biddetails),
                                      MailTemplate.GetTemplateLinkedResources(this)))
            {
                failedcount++;
                LogHelper.EventLogHelper.Log("Bids > Send Notification : Sending Failed to " + Session[Constant.SESSION_USEREMAIL].ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            else
            {
                successcount++;
                LogHelper.EventLogHelper.Log("Bids > Send Notification : Email Sent to " + Session[Constant.SESSION_USEREMAIL].ToString(), System.Diagnostics.EventLogEntryType.Information);
            }

            #endregion

            success = true;
        }
        catch (Exception ex)
        {
            success = false;
            LogHelper.EventLogHelper.Log("Bid Item > Send ??? Change Notice : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
        }

        return(success);
    }
Ejemplo n.º 24
0
        /// <summary>
        /// Initialization for all Email Manager Tests.
        /// </summary>
        protected void SetupTestBase()
        {
            this.MsGraphProvider             = new Mock <IMSGraphProvider>();
            this.CloudStorageClient          = new Mock <ICloudStorageClient>();
            this.TokenHelper                 = new Mock <ITokenHelper>();
            this.EmailNotificationRepository = new Mock <IRepositoryFactory>();
            this.MsGraphSetting              = Options.Create(new MSGraphSetting()
            {
                EnableBatching = false, SendMailUrl = this.sendEmailUrl, BatchRequestLimit = 4
            });
            this.Logger                      = new Mock <ILogger>().Object;
            this.EncryptionService           = new Mock <IEncryptionService>();
            this.EmailAccountManager         = new Mock <IEmailAccountManager>();
            this.TemplateManager             = new Mock <IMailTemplateManager>();
            this.TemplateMerge               = new Mock <ITemplateMerge>();
            this.NotificationProviderFactory = new Mock <INotificationProviderFactory>();
            this.NotificationRepo            = new Mock <IEmailNotificationRepository>();
            this.NotificationProvider        = new MockNotificationProvider();

            var notificationId = Guid.NewGuid().ToString();
            IList <NotificationBatchItemResponse> responses = new List <NotificationBatchItemResponse>();

            responses.Add(new NotificationBatchItemResponse()
            {
                NotificationId = notificationId, Status = System.Net.HttpStatusCode.Accepted
            });
            var applicationAccounts = new List <ApplicationAccounts>()
            {
                new ApplicationAccounts()
                {
                    ApplicationName = this.ApplicationName,
                    ValidAppIds     = Guid.NewGuid().ToString(),
                    Accounts        = new List <AccountCredential>()
                    {
                        new AccountCredential()
                        {
                            AccountName = "Test", IsEnabled = true, PrimaryPassword = "******",
                        },
                    },
                },
            };

            var retrySetting = new RetrySetting
            {
                MaxRetries          = 10,
                TransientRetryCount = 3,
            };

            IList <EmailNotificationItemEntity> emailNotificationItemEntities = new List <EmailNotificationItemEntity>()
            {
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = notificationId,
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = notificationId,
                },
            };
            var mailSettings = new List <MailSettings>()
            {
                new MailSettings()
                {
                    ApplicationName = this.ApplicationName,
                    MailOn          = true,
                    SendForReal     = false,
                    ToOverride      = "*****@*****.**",
                    SaveToSent      = true,
                },
            };
            Dictionary <string, string> testConfigValues = new Dictionary <string, string>()
            {
                { "ApplicationAccounts", JsonConvert.SerializeObject(applicationAccounts) },
                { "RetrySetting:MaxRetries", "10" },
                { "RetrySetting:TransientRetryCount", "3" },
                { Constants.StorageType, StorageType.StorageAccount.ToString() },
                { "MailSettings", JsonConvert.SerializeObject(mailSettings) },
                { Constants.NotificationProviderType, NotificationProviderType.Graph.ToString() },
            };

            string mergedTemplate = "Testing Html template";

            MailTemplate template = new MailTemplate()
            {
                TemplateName = "TestTemplate",
                Description  = "Test template",
                Content      = "Testing {{Key}} template",
                TemplateType = "Text",
            };

            this.Configuration = new ConfigurationBuilder()
                                 .AddInMemoryCollection(testConfigValues)
                                 .Build();

            _ = this.TokenHelper
                .Setup(th => th.GetAccessTokenForSelectedAccount(It.IsAny <AccountCredential>()))
                .Returns(Task.FromResult(this.TestToken));

            _ = this.TokenHelper
                .Setup(th => th.GetAuthenticationHeaderFromToken(It.IsAny <string>()))
                .Returns(Task.FromResult(new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", this.TestToken)));

            _ = this.MsGraphProvider
                .Setup(gp => gp.ProcessEmailRequestBatch(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <GraphBatchRequest>()))
                .Returns(Task.FromResult(responses));

            _ = this.MsGraphProvider
                .Setup(gp => gp.SendEmailNotification(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <EmailMessagePayload>(), It.IsAny <string>()))
                .Returns(Task.FromResult(It.IsAny <bool>()));

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).CreateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >(), It.IsAny <string>()))
                .Returns(Task.CompletedTask);

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()))
                .Returns(Task.CompletedTask);

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).GetEmailNotificationItemEntities(It.IsAny <IList <string> >(), It.IsAny <string>()))
                .Returns(Task.FromResult(emailNotificationItemEntities));

            _ = this.CloudStorageClient
                .Setup(csa => csa.GetCloudQueue(It.IsAny <string>()))
                .Returns(new CloudQueue(new Uri(this.cloudQueueUri)));

            _ = this.CloudStorageClient
                .Setup(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null))
                .Returns(Task.CompletedTask);

            _ = this.EmailAccountManager
                .Setup(ema => ema.FetchAccountToBeUsedForApplication(It.IsAny <string>(), It.IsAny <List <ApplicationAccounts> >()))
                .Returns(applicationAccounts[0].Accounts[0]);

            _ = this.TemplateManager
                .Setup(tmgr => tmgr.GetMailTemplate(It.IsAny <string>(), It.IsAny <string>()))
                .Returns(Task.FromResult(template));

            _ = this.TemplateMerge
                .Setup(tmr => tmr.CreateMailBodyUsingTemplate(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
                .Returns(mergedTemplate);
            this.EmailManager = new EmailManager(this.Configuration, this.EmailNotificationRepository.Object, this.Logger, this.TemplateManager.Object, this.TemplateMerge.Object);

            this.MSGraphNotificationProvider = new MSGraphNotificationProvider(
                this.Configuration,
                this.EmailAccountManager.Object,
                this.Logger,
                this.MsGraphSetting,
                Options.Create(retrySetting),
                this.TokenHelper.Object,
                this.MsGraphProvider.Object,
                this.EmailManager);

            _ = this.NotificationProviderFactory
                .Setup(provider => provider.GetNotificationProvider(NotificationProviderType.Graph))
                .Returns(this.MSGraphNotificationProvider);

            this.EmailHandlerManager = new EmailHandlerManager(this.Configuration, this.MsGraphSetting, this.CloudStorageClient.Object, this.Logger, this.EmailManager);
            this.EmailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);
        }
Ejemplo n.º 25
0
    private string CreateBodyWithdrawn(
        string vendorname,
        string vendorAddress,
        string vendorAddress1,
        string vendorAddress2,
        string vendorAddress3,
        string vendorcontactperson,
        string vendorphone,
        string vendorfax
        )
    {
        String b_Event = ((Label)((DetailsView)Biddetails_details1.FindControl("dvEventDetails")).Rows[1].Cells[1].FindControl("lblItemDesc")).Text;
        String b_Item  = ((Label)(gvBidItemDetails.Rows[0].Cells[0].FindControl("lblDescription"))).Text;

        StringBuilder sb = new StringBuilder();

        #region WITHDRAWN EMAIL BODY
        sb.Append("<tr><td style='width: 1px'></td><td style='width: auto' colspan=''></td><td style='width: 1px'></td></tr>");
        sb.Append("<tr><td style='width: auto; height: 635px'></td>");
        sb.Append("<td style='width: 100%; height: auto; text-align: justify;'>");
        sb.Append("<br /><br /><br />");
        sb.Append("" + DateTime.Now.ToLongDateString() + "");
        sb.Append("<br /><br /><br /><strong>");
        sb.Append(vendorname.Trim());
        sb.Append("<br /></strong>");
        sb.Append(vendorAddress.Trim());
        sb.Append("<br />");
        sb.Append(vendorAddress1.Trim());
        sb.Append("<br />");
        sb.Append(vendorAddress2.Trim());
        sb.Append("<br />");
        sb.Append(vendorAddress3.Trim());
        sb.Append("<br /><br />");
        sb.Append("<table style='width: 100%'><tr><td style='width: 1px; height: 8px'>Attention&nbsp; :</td><td style='width: 548px; height: 8px'><strong>");
        sb.Append(vendorcontactperson.Trim());
        sb.Append("</strong></td><td style='width: 1px; height: 8px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
        sb.Append(vendorAddress.Trim());
        sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
        sb.Append(vendorAddress1.Trim());
        sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
        sb.Append(vendorAddress2.Trim());
        sb.Append("</td><td style='width: 1px'></td></tr><tr><td style='width: 1px'></td><td style='width: 548px'>");
        sb.Append(vendorAddress3.Trim());
        sb.Append("</td><td style='width: 1px'></td></tr></table>");
        sb.Append("<br /><br />");
        sb.Append("<table style='width: 100%'><tr><td style='width: 12px'>");
        sb.Append("Bid Event:");
        sb.Append("</td><td style='width: auto'>");
        sb.Append(b_Event);
        sb.Append("</td></tr><tr><td style='width: 12px'>");
        sb.Append("Bid Item:");
        sb.Append("</td><td style='width: auto'>");
        sb.Append(b_Item);
        sb.Append("</td></tr></table>");
        sb.Append("<br /><br />");
        sb.Append("Dear Sir:");
        sb.Append("<br /><br />");
        sb.Append("Thank you for your interest to help Trans-Asia / Commnunications in finding a solution for ");
        sb.Append("" + b_Event + ". It certainly was a pleasure to ");
        sb.Append("have worked with your company during the RFP and the succeeding clarificatory discussions.");
        sb.Append("<br /><br />");
        sb.Append("We regret to inform you that " + b_Item + " has been withdrawn. We will, however, keep in mind your cooperation ");
        sb.Append("and commitment when we have the opportunity to implement other projects. ");
        sb.Append("<br /><br />");
        sb.Append("We sincerely appreciate the time and effort you dedicated for the completion of ");
        sb.Append("this RFP and we look forward to working with you again in the future.");
        sb.Append("<br /><br /><br />");
        sb.Append("Sincerely,");
        sb.Append("<br /><br /><br /><br />");
        sb.Append(Session[Constant.SESSION_USERFULLNAME].ToString());
        sb.Append("<br />");
        sb.Append("Head, Corporate Procurement Department");
        sb.Append("<br /><br /><br /><br /></td><td style='width: auto; height: auto'></td></tr><tr><td style='width: auto'></td><td style='width: auto'></td><td style='width: auto'></td></tr>");
        #endregion

        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 26
0
        /// <summary>
        /// sends invite using template
        /// </summary>
        /// <param name="mailTemplate"> template .</param>
        /// <param name="TemplateData">template  data params .</param>
        private async Task SendMeetingInviteTemplateTest(MailTemplate mailTemplate, string TemplateData)
        {
            var date = DateTime.UtcNow;
            var meetingInviteItems = new MeetingNotificationItem[]
            {
                new MeetingNotificationItem()
                {
                    From = this.Configuration[FunctionalConstants.ToAddress],
                    RequiredAttendees = this.Configuration[FunctionalConstants.ToAddress],
                    Subject           = "Meeting Invite Functional Testing of Template through send endpoint",
                    Start             = date,
                    End          = date.AddHours(1),
                    Priority     = NotificationPriority.Low,
                    TemplateId   = mailTemplate.TemplateId,
                    TemplateData = TemplateData
                }
            };

            var    stringContent = new StringContent(JsonConvert.SerializeObject(meetingInviteItems), Encoding.UTF8, FunctionalConstants.ContentType);
            string notificationServiceEndpoint = $"{this.Configuration[FunctionalConstants.NotificationServiceUrl]}/v1/meetinginvite/send/{this.Configuration[FunctionalConstants.Application]}";

            using (HttpClient httpClient = new HttpClient())
            {
                string bearerToken = await this.tokenUtility.GetTokenAsync();

                if (bearerToken != null)
                {
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(FunctionalConstants.Bearer, bearerToken);

                    var response = await httpClient.PostAsync(notificationServiceEndpoint, stringContent).ConfigureAwait(false);

                    if (!response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        Assert.Fail();
                    }
                    else
                    {
                        var Result = response.Content.ReadAsStringAsync().Result;
                        var notificationResponses = JsonConvert.DeserializeObject <List <NotificationResponse> >(Result);
                        var notificationResponse  = notificationResponses.FirstOrDefault();
                        Assert.IsTrue(notificationResponse.Status == NotificationItemStatus.Sent);
                        MeetingInviteMessage inviteMessage = await GetMeetingNotificationMessage(notificationResponse.NotificationId, httpClient);

                        if (inviteMessage != null)
                        {
                            var templateBody = ConvertText(mailTemplate.Content, TemplateData);
                            Assert.IsTrue(meetingInviteItems[0].Subject == inviteMessage.Subject);
                            Assert.IsTrue(templateBody == inviteMessage.Body);
                        }
                        else
                        {
                            Assert.Fail();
                        }
                    }
                }
                else
                {
                    Assert.Fail();
                }
            }
        }
Ejemplo n.º 27
0
        public void GetNotificationMessageTest()
        {
            Dictionary <string, string> testConfigValues = new Dictionary <string, string>()
            {
                { "RetrySetting:MaxRetries", "10" },
                { "RetrySetting:TransientRetryCount", "3" },
                { ConfigConstants.StorageType, StorageType.StorageAccount.ToString() },
            };

            this.Configuration = new ConfigurationBuilder()
                                 .AddInMemoryCollection(testConfigValues)
                                 .Build();

            EmailNotificationItemEntity notificationItemEntity = new EmailNotificationItemEntity()
            {
                Application = "TestApp",
                To          = "*****@*****.**",
                Subject     = "Test",
                Body        = "Test Body",
            };

            MessageBody body = new MessageBody
            {
                Content     = "Test Body",
                ContentType = "Text",
            };
            MailTemplate mailTemplate = new MailTemplate
            {
                Content      = "Test Body",
                Description  = "Test Description",
                TemplateId   = "TestTemplate-01",
                TemplateType = "Text",
            };
            string applicationName = "TestApp";
            string notificationId  = Guid.NewGuid().ToString();

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetEmailNotificationItemEntity(notificationId, notificationItemEntity.Application))
                .ReturnsAsync(notificationItemEntity);

            _ = this.EmailNotificationRepositoryFactory
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount))
                .Returns(this.EmailNotificationRepository.Object);

            _ = this.TemplateManager
                .Setup(c => c.GetMailTemplate(It.IsAny <string>(), It.IsAny <string>()))
                .ReturnsAsync(mailTemplate);

            _ = this.TemplateMerge
                .Setup(c => c.CreateMailBodyUsingTemplate(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
                .Returns("Test Message");

            this.NotificationReportManager = new NotificationReportManager(this.Logger, this.EmailNotificationRepositoryFactory.Object, this.Configuration, this.MailTemplateRepository.Object, this.TemplateManager.Object, this.TemplateMerge.Object);

            var managerResult = this.NotificationReportManager.GetNotificationMessage(applicationName, notificationId);

            Assert.AreEqual(managerResult.Status.ToString(), "RanToCompletion");
            Assert.AreEqual(managerResult.Result.Body.Content, body.Content);

            this.EmailNotificationRepositoryFactory.Verify(repo => repo.GetRepository(StorageType.StorageAccount).GetEmailNotificationItemEntity(notificationId, applicationName));
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Get Notification Message Body Async.
        /// </summary>
        /// <param name="applicationName">Application sourcing the email notification.</param>
        /// <param name="notification">email notification item entity.</param>
        /// <returns>
        /// A <see cref="Task{TResult}" /> representing the result of the asynchronous operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// applicationName - applicationName cannot be null or empty.
        /// or
        /// notification - notification cannot be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// TemplateData cannot be null or empty.
        /// or
        /// Template cannot be found, please provide a valid template and application name.
        /// </exception>
        private async Task <MessageBody> GetNotificationMessageBodyAsync(string applicationName, NotificationItemBaseEntity notification)
        {
            string body         = string.Empty;
            string templateId   = string.Empty;
            string templateData = string.Empty;

            if (notification is EmailNotificationItemEntity)
            {
                var notifEntity = (EmailNotificationItemEntity)notification;
                body         = notifEntity.Body;
                templateId   = notifEntity.TemplateId;
                templateData = notifEntity.TemplateData;
            }
            else
            {
                var notifEntity = (MeetingNotificationItemEntity)notification;
                body         = notifEntity.Body;
                templateId   = notifEntity.TemplateId;
                templateData = notifEntity.TemplateData;
            }

            this.logger.TraceInformation($"Started {nameof(this.GetNotificationMessageBodyAsync)} method of {nameof(EmailManager)}.");
            string notificationBody = null;

            try
            {
                if (string.IsNullOrEmpty(applicationName))
                {
                    throw new ArgumentNullException(nameof(applicationName), "applicationName cannot be null or empty.");
                }

                if (notification is null)
                {
                    throw new ArgumentNullException(nameof(notification), "notification cannot be null.");
                }

                if (string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(templateId))
                {
                    MailTemplate template = await this.templateManager.GetMailTemplate(applicationName, templateId).ConfigureAwait(false);

                    if (template == null)
                    {
                        throw new ArgumentException("Template cannot be found, please provide a valid template and application name");
                    }

                    notificationBody = this.templateMerge.CreateMailBodyUsingTemplate(template.TemplateType, template.Content, templateData);
                }
                else
                {
                    if (!string.IsNullOrEmpty(body))
                    {
                        notificationBody = body;
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.WriteException(ex);
                throw;
            }

            MessageBody messageBody = new MessageBody {
                Content = notificationBody, ContentType = Common.ApplicationConstants.EmailBodyContentType
            };

            this.logger.TraceInformation($"Finished {nameof(this.GetNotificationMessageBodyAsync)} method of {nameof(EmailManager)}.");
            return(messageBody);
        }
Ejemplo n.º 29
0
    private string CreateInvitationBody(AuctionDetails auctiondetails, AuctionParticipant participant)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("<tr><td align='right'><h5>" + DateTime.Now.ToLongDateString() + "</h5></td></tr>");
        sb.Append("<tr><td align='center'><h3>INVITATION TO AUCTION</h3></td></tr>");
        sb.Append("<tr>");
        sb.Append("<td valign='top'>");
        sb.Append("<p>");
        sb.Append("<b>TO&nbsp&nbsp;:&nbsp&nbsp;<u>" + participant.Name + "</u></b>");
        sb.Append("<br /><br />");
        sb.Append("Good Day!");
        sb.Append("<br /><br />");
        sb.Append("We are glad to inform you that you have been invited to participate in an online auction event which was initiated by Trans-Asia / Commnunications.");
        sb.Append("</p>");

        sb.Append("<table style='font-size: 12px;width:100%;'>");
        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>1.</td>");
        sb.Append("<td style='font-weight:bold;'>Auction Description</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>" + auctiondetails.Description + "</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>2.</td>");
        sb.Append("<td style='font-weight:bold;'>Schedule of Auction Event</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("Confirmation Deadline : " + FormattingHelper.FormatDateToString(auctiondetails.ConfirmationDeadline) + "<br />");
        sb.Append("Start Date & Time : " + FormattingHelper.FormatDateToLongString(auctiondetails.StartDateTime) + "<br />");
        sb.Append("End Date & Time : " + FormattingHelper.FormatDateToLongString(auctiondetails.EndDateTime) + "<br />");
        sb.Append("Duration : " + auctiondetails.Duration + "<br />");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>3.</td>");
        sb.Append("<td style='font-weight:bold;'>Payment Details</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("<ul>");
        sb.Append("<li>Payment Terms - depends on the item to be purchased</li>");
        sb.Append("<br />");
        sb.Append("<li>Billing Details</li>");
        sb.Append("<ul>");
        sb.Append("<li>Contact Person: Rose Soteco T# 730 2413</li>");
        sb.Append("<li>Contact Details: 2F GT Plaza Tower 1, Pioneer cor Madison Sts., Mandaluyong City</li>");
        sb.Append("</ul>");
        sb.Append("</ul>");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>4.</td>");
        sb.Append("<td style='font-weight:bold;'>Bid Price Details</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>The bid price submitted by the supplier shall be exclusive of VAT.</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>5.</td>");
        sb.Append("<td style='font-weight:bold;'>Price Validity</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("The price quoted must be valid and firm for a period of 90 days.");
        sb.Append("No change in price quoted shall be allowed after bid submission unless negotiated by Trans-Asia / Commnunications.");
        sb.Append("</td.");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>6.</td>");
        sb.Append("<td style='font-weight:bold;'>Price Confirmation</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("All bidders shall e-mail the price breakdown in Acrobat Format (i.e. PDF) according to");
        sb.Append("the final bid price submitted during the auction event not later than 24 hours after the");
        sb.Append("event has ended.  The sum of the breakdown must be equal to the supplier’s final bid");
        sb.Append("price submitted during the actual auction event.  Any attempt to submit a breakdown");
        sb.Append("which totals significantly higher, or lower than the final bid price during the event");
        sb.Append("may incur sanctions from Trans-Asia / Commnunications.");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>7.</td>");
        sb.Append("<td style='font-weight:bold;'>Grounds for Invalidating Bids</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("A supplier's bid may be invalidated under any of the following circumstances:");
        sb.Append("<ul>");
        sb.Append("<li>Incomplete bid documents</li>");
        sb.Append("<li>Late or non-transmittal of the price breakdown of the final auction tender</li>");
        sb.Append("</ul>");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>8.</td>");
        sb.Append("<td style='font-weight:bold;'>Awarding of Bid</td>");
        sb.Append("</tr>");
        sb.Append("<tr>");
        sb.Append("<td width='30px' colspan='2'></td>");
        sb.Append("<td>");
        sb.Append("The lowest/highest bidder is not necessarily the winning bidder. Trans-Asia / Commnunications shall not be bound to assign any reason for not accepting any bid or accepting it in part.");
        sb.Append("Bids are still subject to further ecaluation. Trans-Asia / Commnunications shall award the winning supplier through a Purchase Order/Sales Order.");
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td width='10px'></td>");
        sb.Append("<td style='font-weight:bold;width:20px;'>9.</td>");
        sb.Append("<td style='font-weight:bold;'>Penalties (depends on the items to be purchased)</td>");
        sb.Append("</tr>");
        sb.Append("<tr><td height='10px' colspan='3'></td></tr>");
        sb.Append("</table>");

        sb.Append("<p>");
        sb.Append("To know more about this auction, click <a href='" + ConfigurationManager.AppSettings["ServerUrl"] + "web/auctions/auctiondetails.aspx?aid=" + HttpUtility.UrlEncode(EncryptionHelper.Encrypt(auctiondetails.ID.ToString())) + "' target='_blank'>here</a>. ");
        sb.Append("<br />");
        sb.Append("To confirm/decline your invitation, click <a href='" + ConfigurationManager.AppSettings["ServerUrl"] + "web/auctions/confirmauctionevent.aspx?aid=" + HttpUtility.UrlEncode(EncryptionHelper.Encrypt(auctiondetails.ID.ToString())) + "' target='_blank'>here</a>.");
        sb.Append("<br />");
        sb.Append("<a href='" + ConfigurationManager.AppSettings["ServerUrl"] + "rules.htm' target='_blank' title='Click here or copy the link'>Rules and Regulations</a> : " + ConfigurationManager.AppSettings["ServerUrl"] + "rules.htm");
        sb.Append("<br /><br />");
        sb.Append("######################################################################################<br />");
        sb.Append("&nbsp;Credentials:<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Username: "******"<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Ticket: " + EncryptionHelper.Decrypt(participant.EncryptedTicket) + "<br /><br />");
        sb.Append("&nbsp;Notes:<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Ticket and password are CASE SENSITIVE.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ticket is for confirming/declining/participating an auction.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ticket is different for each supplier for each auction event.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Password is for login.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;Username is NOT CASE SENSITIVE.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If you don't know or forgot your password, go to eBid login page and click forgot password.<br />");
        sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Use the username provided. Click Send. Your password will be sent to this email address.<br />");
        sb.Append("######################################################################################<br />");
        sb.Append("<br /><br /><br />");
        sb.Append("Sincerely Yours,");
        sb.Append("<br /><br />");
        sb.Append(auctiondetails.Creator);
        sb.Append("<br /><br />");
        sb.Append("</p>");
        sb.Append("</td>");
        sb.Append("</tr>");

        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 30
0
    private bool SendEmailInvitation(BidDetails biddetails, ArrayList recipients, ref int failedcount, ref int successcount)
    {
        bool   success = false;
        string subject = "Trans-Asia  Incorporated/ Commnunications : Invitation to Bid";

        failedcount  = 0;
        successcount = 0;

        try
        {
            for (int i = 0; i < recipients.Count; i++)
            {
                BidParticipant p = (BidParticipant)recipients[i];

                if (!MailHelper.SendEmail(MailTemplate.GetDefaultSMTPServer(),
                                          MailHelper.ChangeToFriendlyName(biddetails.Creator, biddetails.CreatorEmail),
                                          MailHelper.ChangeToFriendlyName(p.Name, p.EmailAddress),
                                          subject,
                                          CreateInvitationBody(biddetails, p),
                                          MailTemplate.GetTemplateLinkedResources(this)))
                {       // if sending failed
                    failedcount++;
                    LogHelper.EventLogHelper.Log("Bid Event > Send Invitation : Sending Failed to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {       // if sending successful
                    successcount++;
                    LogHelper.EventLogHelper.Log("Bid Event > Send Invitation : Email Sent to " + p.EmailAddress, System.Diagnostics.EventLogEntryType.Information);

                    //add 1 to emailsent field based on vendorID and BidRefNo
                    SqlParameter[] sqlparams = new SqlParameter[2];
                    sqlparams[0]       = new SqlParameter("@Vendorid", SqlDbType.Int);
                    sqlparams[0].Value = p.ID;
                    sqlparams[1]       = new SqlParameter("@BidRefNo", SqlDbType.VarChar);
                    sqlparams[1].Value = Int32.Parse(Session["BidRefNo"].ToString());
                    SqlHelper.ExecuteNonQuery(connstring, CommandType.StoredProcedure, "sp_BidInvitationAddEmailSent", sqlparams);
                }
            }

            success = true;
        }
        catch (Exception ex)
        {
            success = false;
            LogHelper.EventLogHelper.Log("Bid Event > Send Invitation : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
        }

        try
        {
            for (int j = 0; j < recipients.Count; j++)
            {
                BidParticipant p = (BidParticipant)recipients[j];

                if (SMSHelper.AreValidMobileNumbers(p.MobileNo.Trim()))
                {
                    SMSHelper.SendSMS(new SMSMessage(CreateInvitationSmsBody(biddetails, p).Trim(), p.MobileNo.Trim())).ToString();
                }
            }
        }

        catch (Exception ex)
        {
            LogHelper.EventLogHelper.Log("Bid Event > Send SMS Invitation : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
        }

        return(success);
    }
Ejemplo n.º 31
0
        public void SendMail(MailInput mail)
        {
            //validation
            if (mail.To == "")
            {
                throw new Exception("Please enter an E-Mail address to 'To' parameter!");
            }
            try
            {
                if (mail.To.Contains(';') == false)
                {
                    var addr = new System.Net.Mail.MailAddress(mail.To);
                }
                else
                {
                    foreach (string item in mail.To.Split(';'))
                    {
                        if (item != "")
                        {
                            var addr = new System.Net.Mail.MailAddress(item);
                        }
                    }
                }

                if (mail.CC != null)
                {
                    if (mail.CC.Contains(';') == false)
                    {
                        var addr = new System.Net.Mail.MailAddress(mail.CC);
                    }
                    else
                    {
                        foreach (string item in mail.CC.Split(';'))
                        {
                            if (item != "")
                            {
                                var addr = new System.Net.Mail.MailAddress(item);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("One of the receipent mail addresses are not valid.");
            }

            if (mail.ConnectionMethod == null)
            {
                throw new Exception("Please select a connection method.");
            }


            if (mail.MailType == null)
            {
                throw new Exception("Please select a mail type.");
            }
            //prepare object instance
            MailSend ms = new MailSend();

            if (mail.MailTemplateId != null)
            {
                if (string.IsNullOrEmpty(this.ConnectionString))
                {
                    throw new Exception("Template stucture is only available with db connection.");
                }
                List <IDataParameter> paramlist = new List <IDataParameter>();
                paramlist.Add(new CustomParameter("id", mail.MailTemplateId));
                List <MailTemplate> mtlist = qm.GetQueryResult <MailTemplate>("GetMailTemplate", paramlist);
                if (mtlist.Count == 0)
                {
                    throw new Exception("Mail Template has not been found on db!");
                }
                else
                {
                    MailTemplate mt        = mtlist[0];
                    string[]     variables = null;

                    string body = File.ReadAllText(mt.TemplateText);
                    if (mt.Variables != "" && mt.Variables.Contains(","))
                    {
                        variables = mt.Variables.Split(',');
                    }
                    if (mt.QueryType == "select")
                    {
                        DataTable dt = qm.GetQueryResultDataTableDirect(mt.Query, null);
                        if (dt.Rows.Count > 0)
                        {
                            string itr = "";
                            if (body.Contains("##for") && body.Contains("##endfor"))
                            {
                                Regex           rgx   = new Regex("##for(\n|.)*##endfor");
                                MatchCollection mtcol = rgx.Matches(body);
                                foreach (Match mtc in mtcol)
                                {
                                    if (mtc.Success)
                                    {
                                        itr = mtc.Value;

                                        string newstr  = itr;
                                        string lastStr = "";
                                        foreach (DataRow dr in dt.Rows)
                                        {
                                            foreach (string vr in variables)
                                            {
                                                newstr = newstr.Replace("#" + vr, dr[vr].ToString());
                                            }
                                            lastStr = lastStr + newstr;
                                            newstr  = itr;
                                        }
                                        body = body.Replace(itr, lastStr);
                                    }
                                }
                            }

                            DataRow drow = dt.Rows[0];
                            foreach (string vr in variables)
                            {
                                body = body.Replace("#" + vr, drow[vr].ToString());
                            }
                            body = body.Replace("##for", "").Replace("##endfor", "");
                        }
                    }
                    else if (mt.QueryType == "execute")
                    {
                        int result = qm.ExecuteQueryText(mt.Query);
                    }
                    else
                    {
                        throw new Exception("Please choose querytype between select and execute options.");
                    }



                    ms.Body = body;
                }
            }
            else
            {
                ms.Body = mail.Body;
            }

            ms.FilePath   = mail.AttachPath;
            ms.MailType   = Convert.ToInt16(mail.MailType);
            ms.MailStatus = 1;
            ms.Module     = "";
            ms.Sender     = mail.From;
            ms.SendDate   = mail.SendDate;
            ms.Subject    = mail.Subject;
            ms.ToAddress  = mail.To;
            ms.CC         = mail.CC;
            ms.InsertDate = DateTime.Now;
            if (ms.SendDate == null)
            {
                ms.SendDate = DateTime.Now;
            }

            //insert to sendmail

            if (mail.ConnectionMethod == ConnectionMethod.DataBase)
            {
                if (ConnectionString == "")
                {
                    throw new Exception("Altough your connection method is Database. Your connection string is empty!. Please enter valid database connection string into constructor method.");
                }
                mc.InsertMailDB(ms);
            }
            else if (mail.ConnectionMethod == ConnectionMethod.WebApi)
            {
                if (AccessKey == "")
                {
                    throw new Exception("Altough your connection method is Web Api. Your AccessKey is empty!. Please enter valid Access Key  into constructor method.");
                }
                mc.InsertMailWS(ms);
            }
        }
Ejemplo n.º 32
0
        public async Task ProcessAsync(Message message, MailTemplateEnums mailTemplateEnums)
        {
            var data      = DataProtectionProvider.Create("Subzz");
            var protector = data.CreateProtector("secretAdmin@0192837465");

            try
            {
                var configurationBuilder = new ConfigurationBuilder();
                var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
                configurationBuilder.AddJsonFile(path, false);
                var    root   = configurationBuilder.Build();
                string apiUrl = root.GetSection("URL").GetSection("api").Value;
                string web    = root.GetSection("URL").GetSection("web").Value;
                //Private Key
                var desKey = root.GetSection("KEY").GetSection("SECkey").Value;

                // Encryption
                var encEmail     = EncryptProvider.DESEncrypt(message.SendTo, desKey);
                var encPassword  = EncryptProvider.DESEncrypt(message.Password, desKey);
                var encAbsenceId = EncryptProvider.DESEncrypt(message.AbsenceId.ToString(), desKey);
                message.ProfilePicUrl     = apiUrl + "/Profile/" + message.Photo;
                message.UnsubscriptionUrl = web + "/unsubscribed/?email=" + message.SendTo;
                if (message.TemplateId == 14)
                {
                    message.ApproveUrl = web + "/?pa=" + encPassword + "&email=" + encEmail + "&job=" + encAbsenceId + "&ac=" + 3;
                    message.DenyUrl    = web + "/?pa=" + encPassword + "&email=" + encEmail + "&job=" + encAbsenceId + "&ac=" + 4;
                }
                if (message.TemplateId == 1 || message.TemplateId == 7)
                {
                    message.AcceptUrl  = web + "/?pa=" + encPassword + "&email=" + encEmail + "&job=" + encAbsenceId + "&ac=" + 1;
                    message.DeclineUrl = web + "/?pa=" + encPassword + "&email=" + encEmail + "&job=" + encAbsenceId + "&ac=" + 2;
                }
                if (message.TemplateId == 9)
                {
                    message.resetPassUrl = web + "/resetPassword/?email=" + message.SendTo + "&key=" + message.ActivationCode;
                }
                if (message.TemplateId == 25)
                {
                    //message.Password = EncryptProvider.DESEncrypt(message.Password, desKey);
                    //var EmailId = EncryptProvider.DESEncrypt(message.SendTo, desKey);
                    message.VerifyUrl = web + "/?pa=" + encPassword + "&email=" + encEmail + "&ac=" + 5;
                }
                MailTemplate mailTemplate = await CommunicationContainer.MailTemplatesBuilder
                                            .GetMailTemplateByIdAsync((int)mailTemplateEnums);

                string[] to;
                to = new string[] { message.SendTo };
                var    param = GetParam(message);
                string body  = PrepareBodyMessage(param, mailTemplate.EmailContent);
                if (mailTemplate.EmailDisclaimerNeeded)
                {
                    body += mailTemplate.EmailDisclaimerContent;
                }
                if (string.IsNullOrEmpty(message.AttachedFileName))
                {
                    await CommunicationContainer.MailClient.SendAsync(body, mailTemplate.Title, to,
                                                                      mailTemplate.SenderEmail, true, message.ImageBase64);
                }
                else
                {
                    await CommunicationContainer.MailClient.SendRawEmail(body, mailTemplate.Title, to,
                                                                         mailTemplate.SenderEmail, true, message.AttachedFileName, message.FileContentType);
                }
                DateTime updatedOn = DateTime.Now;
                CommunicationContainer.Logger.LogEmail(message.SendTo, body, mailTemplate.Notes, null, updatedOn, Convert.ToString(message.AbsenceId), "OK");
            }
            catch (System.Exception ex)
            {
                DateTime updatedOn = DateTime.Now;
                CommunicationContainer.Logger.LogEmail(message.SendTo, null, "Subzz Job Notification", Convert.ToString(ex), updatedOn, Convert.ToString(message.AbsenceId), "FAIL");
                //CommunicationContainer.Logger.LogError(ex, "Process", "EmailProcessor");
                //throw ex;
            }
            finally
            {
                protector = null;
            }
        }
Ejemplo n.º 33
0
 public ManagerMail(MailTemplate template, ErrorSettings setting)
 {
     _template = template;
     _setting  = setting;
 }
Ejemplo n.º 34
0
    private string CreateNotificationBody(string cfromName, string ctoName, string cAuthenticationNumber, string cVendorName)
    {
        SqlDataReader oReader;
        string        cServices = "";

        query = "SELECT t1.*, t2.CategoryName FROM tblVendorProductsAndServices t1, rfcProductCategory t2 WHERE t2.CategoryId = t1.CategoryId AND t1.VendorId = @VendorId";
        //query = "sp_GetVendorInformation"; //##storedProcedure
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                cmd.Parameters.AddWithValue("@VendorId", Convert.ToInt32(Session["VendorId"]));
                conn.Open();
                //Process results
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        cServices = cServices + "&bull; " + oReader["CategoryName"].ToString() + "<br>";
                    }
                }
            }
        }
        conn.Close();

        StringBuilder sb   = new StringBuilder();
        string        sTxt = "<table border='1' style='font-size:12px'>";

        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Vendor ID</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + Session["VendorId"] + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Company Name</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + cVendorName + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "<tr>";
        sTxt = sTxt + "<td><strong>&nbsp;Category</strong></td>";
        sTxt = sTxt + "<td>&nbsp;" + cServices + "&nbsp;</td>";
        sTxt = sTxt + "</tr>";
        sTxt = sTxt + "</table>";

        //sb.Append("<tr><td><p>Sent: " + DateTime.Now.ToLongDateString() + "<br>From: " + cfromName + "<br> To: " + ctoName + "<br><br> Good day!<br><br> This is to inform you that application for vendor accreditation has been reviewed for your approval.<br></p><br>" + sTxt + "<p>Very truly yours,<br><br><br> <strong>" + cfromName + "</strong></p><p>&nbsp;</p> <span style='font-size:10px; font-style:italic;'>Please do not reply to this auto-generated  message.&nbsp;</span></td></tr>");


        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Sent: " + DateTime.Now.ToLongDateString() + "<br>From: " + cfromName + "<br>");
        sb.Append("To: " + ctoName + "<br><br>");
        sb.Append("</p>");
        sb.Append("<tr><td>");
        sb.Append("<p>");
        sb.Append("Dear " + ctoName + ":<br><br>");
        sb.Append("Re: Request for Vendor Accreditation Approval -- " + cVendorName + "<br><br>");
        sb.Append("This is to request for your Approval of the ff: <br><br>");
        //sb.Append("<a href='http://'<br><br>");
        sb.Append(sTxt);
        sb.Append("</p><br><br>");
        //sb.Append("We are happy to be doing business with you. Thank you and God bless your dealings.<br><br><br>");
        sb.Append("Very truly yours,<br><br>");
        sb.Append("Trans-Asia<br><br>");
        sb.Append("</td></tr>");
        sb.Append("<tr><td>");
        sb.Append("<p>&nbsp;</p>");
        sb.Append("<b>Instructions:</b><br>");
        sb.Append("&nbsp;&nbsp;1. Go to <a href='" + System.Configuration.ConfigurationManager.AppSettings["ServerUrl"] + "' target='_blank'>" + System.Configuration.ConfigurationManager.AppSettings["ServerUrl"] + "</a><br>");
        sb.Append("&nbsp;&nbsp;2. Enter your Username and Password then click Login<br>");
        sb.Append("&nbsp;&nbsp;3. Click Vendors for Approval<br>");
        sb.Append("&nbsp;&nbsp;4. Click View<br>");
        sb.Append("</td></tr>");
        sb.Append("<tr><td>");
        sb.Append("<p>&nbsp;</p><span style='font-size:10px; font-style:italic;'>Please do not reply to this auto-generated  message.&nbsp;</span>");
        sb.Append("</td></tr>");

        return(MailTemplate.IntegrateBodyIntoTemplate(sb.ToString()));
    }
Ejemplo n.º 35
0
 public static bool Send(MailTemplate template)
 {
     var service = new MailService();
     return service.Dispatch(template);
 }
        public async Task <IActionResult> SaveMailTemplate(string applicationName, [FromBody] MailTemplate mailTemplate)
        {
            try
            {
                var traceProps = new Dictionary <string, string>();

                if (string.IsNullOrWhiteSpace(applicationName))
                {
                    this.LogAndThrowArgumentNullException("Application Name cannot be null or empty.", nameof(applicationName), traceProps);
                }

                if (mailTemplate is null)
                {
                    this.LogAndThrowArgumentNullException("Mail template param should not be null", nameof(mailTemplate), traceProps);
                }

                if (string.IsNullOrWhiteSpace(mailTemplate?.TemplateId))
                {
                    this.LogAndThrowArgumentNullException("Template name should not be empty", nameof(mailTemplate), traceProps);
                }

                if (string.IsNullOrWhiteSpace(mailTemplate.Description))
                {
                    this.LogAndThrowArgumentNullException("Template description should not be empty", nameof(mailTemplate), traceProps);
                }

                if (string.IsNullOrWhiteSpace(mailTemplate.Content))
                {
                    this.LogAndThrowArgumentNullException("Template content should not be empty", nameof(mailTemplate), traceProps);
                }

                if (string.IsNullOrWhiteSpace(mailTemplate.TemplateType))
                {
                    this.LogAndThrowArgumentNullException("Template type should not be empty", nameof(mailTemplate), traceProps);
                }

                if (!(mailTemplate.TemplateType.ToLowerInvariant() == "xslt" || mailTemplate.TemplateType.ToLowerInvariant() == "text"))
                {
                    this.LogAndThrowArgumentNullException("Template type should be 'Text' or 'XSLT'", nameof(mailTemplate), traceProps);
                }

                traceProps[AIConstants.Application] = applicationName;
                bool result;
                this.logger.TraceInformation($"Started {nameof(this.SaveMailTemplate)} method of {nameof(EmailController)}.", traceProps);
                result = await this.templateManager.SaveEmailTemplate(applicationName, mailTemplate).ConfigureAwait(false);

                this.logger.TraceInformation($"Finished {nameof(this.SaveMailTemplate)} method of {nameof(EmailController)}.", traceProps);
                return(this.Accepted(result));
            }
            catch (ArgumentNullException agNullEx)
            {
                return(this.BadRequest(agNullEx.Message));
            }
            catch (ArgumentException agEx)
            {
                return(this.BadRequest(agEx.Message));
            }
            catch (Exception ex)
            {
                this.logger.WriteException(ex);
                throw;
            }
        }
Ejemplo n.º 37
0
        public bool Dispatch(MailTemplate template)
        {
            string errorMessage;
            var mailMessage = GetMessage(template, out errorMessage);
            if (mailMessage == null)
                return false;

            var sendSuccess = mailMessage != null;
            try
            {
                if (BeforeSend != null)
                {
                    var args = new MailModificationArgs(mailMessage);
                    BeforeSend(this, args);
                    if (args.Abort)
                        return false;
                }
                _client.Send(mailMessage);
            }
            catch (Exception e)
            {
                errorMessage = e.ToString();
                sendSuccess = false;
            }

            if (template.StoreHistory)
            {
                var mailId = StoreMailHistory(mailMessage, template.TypeName, sendSuccess, errorMessage);
                template.MailId = mailId;
            }

            return sendSuccess;
        }
Ejemplo n.º 38
0
 public IActionResult SaveMailTemplate(long menuId, int id, string group)
 {
     if (!this.HasMenu(menuId))
     {
         return(this.GetResult(false, "无访问权限!"));
     }
     using (var db = this.GetMongodb())
     {
         try
         {
             var           menu          = this.GetMenu(menuId);
             var           isNew         = id == 0;
             ActionHistory actionHistory = null;
             MailTemplate  mailtemplate;
             if (isNew)
             {
                 id           = (int)db.MailTemplates.GetMaxId();
                 mailtemplate = new MailTemplate();
             }
             else
             {
                 mailtemplate = db.MailTemplates.FirstOrDefault(a => a.Id == id && a.MenuId == menuId);
                 #region 记录修改历史
                 if (menu.HasFlag(MenuFlag.RecordHistory))
                 {
                     actionHistory = new ActionHistory()
                     {
                         TargetId   = mailtemplate.Id.ToString(),
                         LastModify = DateTime.Now,
                         ModifyUser = this.LoginId,
                         IP         = HttpHelper.GetIP(),
                         Type       = ActionType.Article,
                         MenuId     = menuId,
                         Before     = JsonHelper.ToJson(mailtemplate)
                     };
                 }
                 #endregion
             }
             FormHelper.FillTo(mailtemplate, new FormField()
             {
                 Name = "Id", Disabled = true
             },
                               new FormField()
             {
                 Name = "Title", Text = "邮件标题", Required = true
             },
                               new FormField()
             {
                 Name = "Content", Text = "邮件内容", Required = true
             });
             mailtemplate.Id         = id;
             mailtemplate.ByOrder    = mailtemplate.Id;
             mailtemplate.Group      = group;
             mailtemplate.MenuId     = menuId;
             mailtemplate.LastModify = DateTime.Now;
             mailtemplate.ModifyUser = this.LoginId;
             #region 记录更新历史
             if (actionHistory != null)
             {
                 actionHistory.After = JsonHelper.ToJson(mailtemplate);
                 db.ActionHistories.Add(actionHistory);
             }
             #endregion
             var result = db.MailTemplates.Save(mailtemplate);
             #region 清除缓存
             var key = $"#mail_{mailtemplate.Id}";
             this.RemoveCache(key);
             #endregion
             return(this.GetResult(true));
         }
         catch (Exception ex)
         {
             return(this.GetResult(ex));
         }
     }
 }
Ejemplo n.º 39
0
 private  void SendErrorEmail(CreateCouponViewModel createCouponVm, string description)
 {
     var adminEmail = new SystemConfiguration().AdminEmergencyEmail;
     var mailTemplate = new MailTemplate(Language.CurrentCulture);           
     var username = Session.GetLoggedInUser().Username;
     var errorEmail = mailTemplate.GetCouponErrorEmail(description, createCouponVm.EventId, createCouponVm.PaymentId, username);
     var subject = string.Format(MyMentorResources.errorCreatingCoupon,username,createCouponVm.EventId);
     Mailer.SendMail(adminEmail, errorEmail, subject);
 }