protected void Button1_Click(object sender, EventArgs e)
    {
        EmailHelper email = new EmailHelper();
        email.EmailFrom = "*****@*****.**";
        email.EmailTo = "*****@*****.**";

        email.SendEmail("测试邮件", "test");
    }
Beispiel #2
1
 private void btnTestEmail_Click(object sender, EventArgs e)
 {
     //using (EmailHelper Email = new EmailHelper())
     //{
         EmailHelper Email = new EmailHelper();
         Email.To = "*****@*****.**";
         Email.Subject = "Test";
         //Email.AddAttachment(@"\\compaq1600\SystemReport\WIP - SubCon\WIP_SubCon_2014_06_06.xls");
         Email.AddAttachment(@"C:\1020.log");
         Email.SendEmail();
     //            }
 }
Beispiel #3
1
        private void EmailReport(string ReportPath)
        {
            Logger.For(this).Info("开始");
            Excel.Application xlApp = new Excel.Application();
            xlApp.Caption = "NWMMS - WIP " + DateTime.Now.ToLongTimeString();

            try
            {
                Excel.Workbook xlWb = ExcelHelper.OpenWB(xlApp, ReportPath, true);
                if (xlWb == null)
                {
                    Logger.For(this).Error(string.Format("找不到报表 : {0}", ReportPath));
                }
                else
                {
                    if (string.IsNullOrEmpty(xlWb.BuiltinDocumentProperties["Category"].Value))
                    {
                        using (EmailHelper Email = new EmailHelper())
                        {
                            Email.Subject = string.Format("{0} - {1}", xlWb.BuiltinDocumentProperties["Subject"].Value.ToString(), DateTime.Today.ToString("yyyy-MM-dd"));
                            Email.To = xlWb.BuiltinDocumentProperties["Manager"].Value.ToString();
                            if (xlWb.BuiltinDocumentProperties["Comments"].Value != null)
                                Email.Body = xlWb.BuiltinDocumentProperties["Comments"].Value.ToString();
                            Email.AddAttachment(ReportPath);
                            Email.SendEmail();
                        }
                    }
                    xlWb.Close();
                    xlWb = null;
                }
            }
            catch(Exception Ex)
            {
                Logger.For(this).Error(string.Format("报表 : {0}, 错误 : {1}", ReportPath, Ex.Message));
            }

            xlApp.DisplayAlerts = true;
            ExcelHelper.KillExcelProcess(xlApp);
            Logger.For(this).Info("结束");
        }
 public void SendCustomerChargeFailedSucceeds()
 {
     client.Setup(x => x.Send(It.IsAny<MailMessage>()));
     IEmailHelper helper = new EmailHelper(client.Object);
     StripeCharge charge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeChargeJSON);
     helper.SendCustomerChargeFailed(charge, "Ian", "*****@*****.**", "1234");
 }
        public void ExecuteMailTest()
        {
            dynamic config = new Configuration();
            var userName = config.UserName;
            var password = config.Password;
            const string file = "c:\\temp\\KMs\\send\\km_e-Us_E_201406.pdf";

            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential(userName, password),
                EnableSsl = true
            };
            var emailHelper = new EmailHelper(client);

            emailHelper.SendTestEmail("","", file);
        }
 static EmailHelperTests()
 {
     if (EmailHelper == null)
     {
         EmailHelper = new EmailHelper(new EmailSettings
         {
             SmtpServer = "smtp.live.com",
             SmtpUserName = "******",
             SmtpPassword = "******",
             SmtpServerPort = 25,
             EnableSsl = true,
             EmailDisplayName = "Edi.TemplateEmail"
         })
         .SendAs("Edi.TemplateEmail.UnitTests")
         .LogExceptionWith((s, exception) => Debug.WriteLine(s + exception.Message));
         EmailHelper.UseSignature("signature test");
         EmailHelper.Settings.EmailWithSystemInfo = true;
         EmailHelper.WithFooter(string.Format("<p>Footer Test</p>"));
         //EmailHelper.EmailCompleted += (sender, message, args) => WriteEmailLog(sender as MailMessage, message);
     }
 }
        public ActionResult HandleForgottenPassword(ForgottenPasswordViewModel model)
        {
            var membershipService = ApplicationContext.Current.Services.MemberService;

            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }

            //Find the member with the email address
            var findMember = membershipService.GetByEmail(model.EmailAddress);

            if (findMember != null)
            {
                //We found the member with that email

                //Set expiry date to
                DateTime expiryTime = DateTime.Now.AddMinutes(15);

                //Lets update resetGUID property
                findMember.Properties["resetGUID"].Value = expiryTime.ToString("ddMMyyyyHHmmssFFFF");

                //Save the member with the up[dated property value
                membershipService.Save(findMember);

                //Send user an email to reset password with GUID in it
                EmailHelper email = new EmailHelper();
                email.SendResetPasswordEmail(findMember.Email, expiryTime.ToString("ddMMyyyyHHmmssFFFF"));
            }
            else
            {
                ModelState.AddModelError("ForgottenPasswordForm.", "No member found");
                return CurrentUmbracoPage();
            }

            return RedirectToCurrentUmbracoPage();
        }
        public void Execute(JobExecutionContext context)
        {
            string m_strJobName = context.JobDetail.FullName;

            //如果失败则再试 1 次
            if (context.RefireCount == 1)
            {
                log.Info(m_strJobName + "任务 重试" + "1" + "次后还是失败!");
                return;
            }
            EmailHelper email = new EmailHelper();
            email.Password = "******";
            email.EmailFrom = "*****@*****.**";
            email.EmailTo = "*****@*****.**";

            string emailBody=@" <table width='800' border='1' cellPadding='0' cellSpacing='1' borderColor='#c0c0c0' style='BORDER-COLLAPSE:collapse;font-size:12px;color:#535353;'>
                             <tr height='56'><td height='56' colspan='6' align='center' valign='middle' style=' font-size: 25px;font-weight: bold;'>******登记表</td></tr>
                             <tr><td colspan='4' height='26'>工号:</td>
                             <td width='81'>编号:</td><td>INS-REPORT-MAIL-</td>
                             </tr>
                             </table>";

            email.SendEmail("测试邮件", emailBody);
        }
 public void MyTestInitialize()
 {
     //_helper = new InterIMAPGmailHelper();
     _helper = new LumiIMAPGmailHelper();
     _helper.SetConfig("imap.gmail.com", 993, true, _username, _password);
     _helper.EnableConnection();
 }
Beispiel #10
0
        protected void SaveGoal()
        {
            var    g      = new HRR.Core.Domain.Goal();
            string emails = "";

            if (g.Managers.Count > 0)
            {
                foreach (var m in g.Managers)
                {
                    emails += m.PersonRef.Email + ",";
                }
            }
            if (CurrentGoal == null)
            {
                var r = new ReviewServices().GetEmployeeActiveReview(CurrentProfile.ID);
                g.DateCreated = DateTime.Now;
                g.Description = tbDescription.Text;
                g.AccountID   = ((Person)SecurityContextManager.Current.CurrentUser).AccountID;
                g.DueDate     = (DateTime)tbDueDate.SelectedDate;
                g.EnteredBy   = SecurityContextManager.Current.CurrentUser.ID;
                g.EnteredFor  = CurrentProfile.ID;
                g.GoalType    = 3;
                g.ReviewID    = r.ID;
                g.Score       = Convert.ToInt16(rsQuestion.SelectedValue);
                g.StatusID    = (int)GoalStatus.ACCEPTED;
                g.Progress    = CalculateProgress();
                g.IsAccepted  = true;
                g.IsApproved  = true;
                g.Title       = tbTitle.Text;
                new GoalServices().Save(g);

                var a = new Activity();
                a.AccountID    = CurrentProfile.AccountID;
                a.URL          = "/Goals/" + g.ID.ToString();
                a.ActivityType = (int)ActivityType.NEW_GOAL;
                a.DateCreated  = DateTime.Now;
                a.PerformedBy  = SecurityContextManager.Current.CurrentUser.ID;
                a.PerformedFor = CurrentProfile.ID;
                new ActivityServices().Save(a);

                EmailHelper.SendNewGoalNotification(g, emails);
            }
            else
            {
                g             = CurrentGoal;
                g.Description = tbDescription.Text;
                g.DueDate     = (DateTime)tbDueDate.SelectedDate;
                g.Score       = Convert.ToInt16(rsQuestion.SelectedValue);
                g.Progress    = CalculateProgress();
                g.Title       = tbTitle.Text;
                g.GoalType    = 3;
                g.Weight      = Convert.ToInt16(tbWeight.Text);
                new GoalServices().Save(g);

                var a = new Activity();
                a.AccountID    = CurrentProfile.AccountID;
                a.ActivityType = (int)ActivityType.GOAL_UPDATED;
                a.DateCreated  = DateTime.Now;
                a.URL          = "/Goals/" + g.ID.ToString();
                a.PerformedBy  = SecurityContextManager.Current.CurrentUser.ID;
                a.PerformedFor = CurrentProfile.ID;
                new ActivityServices().Save(a);

                EmailHelper.SendGoalUpdateNotification(g, emails);
            }
            Response.Redirect("/Goals/" + g.ID.ToString());
        }
 public void SendStripeInvoiceSucceeds()
 {
     client.Setup(x => x.Send(It.IsAny<MailMessage>()));
     IEmailHelper helper = new EmailHelper(client.Object);
     helper.SendStripeInvoice(new Stripe.StripeInvoice { AmountDueInCents = 2000 }, "Ian", "*****@*****.**", "1234");
 }
Beispiel #12
0
    /// <summary>
    /// Sends e-mail with password if required.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    /// <param name="toEmail">E-mail address of the mail recipient</param>
    /// <param name="subject">Subject of the e-mail sent</param>
    /// <param name="emailType">Type of the e-mail specificating the template used (NEW, CHANGED, RESEND)</param>
    /// <param name="showPassword">Indicates whether password is shown in message.</param>
    private void SendEmail(string subject, string pswd, int userId, string emailType, bool showPassword)
    {
        // Check whether the 'From' element was specified
        string emailFrom   = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSSendPasswordEmailsFrom");
        bool   fromMissing = string.IsNullOrEmpty(emailFrom);

        if ((!string.IsNullOrEmpty(emailType)) && (ui != null) && (!fromMissing))
        {
            if (!string.IsNullOrEmpty(ui.Email))
            {
                EmailMessage em = new EmailMessage();

                em.From        = emailFrom;
                em.Recipients  = ui.Email;
                em.Subject     = subject;
                em.EmailFormat = EmailFormatEnum.Default;

                string templateName = null;

                // Get e-mail template name
                switch (emailType.ToLowerCSafe())
                {
                case "new":
                    templateName = "Membership.NewPassword";
                    break;

                case "changed":
                    templateName = "Membership.ChangedPassword";
                    break;

                case "resend":
                    templateName = "Membership.ResendPassword";
                    break;

                default:
                    break;
                }

                // Get template info object
                if (templateName != null)
                {
                    try
                    {
                        // Get e-mail template
                        EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate(templateName, null);
                        if (template != null)
                        {
                            em.Body = template.TemplateText;

                            // Macros
                            string[,] macros = new string[2, 2];
                            macros[0, 0]     = "UserName";
                            macros[0, 1]     = ui.UserName;
                            macros[1, 0]     = "Password";
                            macros[1, 1]     = pswd;
                            // Create macro resolver
                            MacroResolver resolver = MacroContext.CurrentResolver;
                            resolver.SetNamedSourceData(macros);

                            // Add template attachments
                            EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                            // Send message immediately (+ resolve macros)
                            EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, em, template, resolver, true);

                            // Inform on success
                            ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(ui.Email));

                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Log the error to the event log
                        EventLogProvider.LogException("Password retrieval", "USERPASSWORD", ex);
                        ShowError("Failed to send the password: "******"Administration-User_Edit_Password.passshow"), pswd), true);
                }
                else
                {
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PassChangedNotSent"));
                }

                return;
            }
        }

        // Inform on error
        string errorMessage = GetString("Administration-User_Edit_Password.PasswordsNotSent");

        if (fromMissing)
        {
            ShowError(errorMessage + " " + GetString("Administration-User_Edit_Password.FromMissing"));
        }
        else
        {
            ShowError(errorMessage);
        }
    }
 public void SendStripeErrorSucceeds()
 {
     client.Setup(x => x.Send(It.IsAny<MailMessage>()));
     IEmailHelper helper = new EmailHelper(client.Object);
     helper.SendStripeError(new Stripe.StripeException { StripeError = new Stripe.StripeError { Code = "123", ErrorType = "error", Message = "Message" } });
 }
Beispiel #14
0
    private void Page_Load(System.Object sender, System.EventArgs e)
    {
        StyleHelper shelper = new StyleHelper();
            litStyleSheetJS.Text = shelper.GetClientScript();
            Utilities.ValidateUserLogin();
            if (!(Request.QueryString["action"] == null))
            {
                if (Request.QueryString["action"] != "")
                {
                    _PageAction = (string) (Ektron.Cms.Common.EkFunctions.HtmlEncode(Request.QueryString["action"].ToLower()));
                }
            }
            if (!(Request.QueryString["LangType"] == null))
            {
                if (Request.QueryString["LangType"] != "")
                {
                    _ContentLanguage = Convert.ToInt32(Request.QueryString["LangType"]);
                    _CommonApi.SetCookieValue("LastValidLanguageID", _ContentLanguage.ToString());
                }
                else
                {
                    if (_CommonApi.GetCookieValue("LastValidLanguageID") != "")
                    {
                        _ContentLanguage = Convert.ToInt32(_CommonApi.GetCookieValue("LastValidLanguageID"));
                    }
                }
            }
            else
            {
                if (_CommonApi.GetCookieValue("LastValidLanguageID") != "")
                {
                    _ContentLanguage = Convert.ToInt32(_CommonApi.GetCookieValue("LastValidLanguageID"));
                }
            }

            if (_ContentLanguage.ToString() == "CONTENT_LANGUAGES_UNDEFINED")
            {
                _CommonApi.ContentLanguage = Convert.ToInt32("ALL_CONTENT_LANGUAGES");
            }
            else
            {
                _CommonApi.ContentLanguage = _ContentLanguage;
            }

            _EnableMultilingual = System.Convert.ToInt32(_CommonApi.EnableMultilingual);
            EmailHelper ehelp = new EmailHelper();
            EmailArea.Text = ehelp.MakeEmailArea();
    }
Beispiel #15
0
    private void ViewTasks()
    {
        string actiontype = "both";
        string callBackPage = ""; //unknown
        System.Web.UI.WebControls.BoundColumn colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "TITLE";
        colBound.HeaderText = m_refMsg.GetMessage("generic Title");
        TaskDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "ID";
        colBound.HeaderText = m_refMsg.GetMessage("generic ID");
        TaskDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "STATE";
        colBound.HeaderText = m_refMsg.GetMessage("lbl state");
        TaskDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "PRIORITY";
        colBound.HeaderText = m_refMsg.GetMessage("lbl priority");
        TaskDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "DUEDATE";
        colBound.HeaderText = m_refMsg.GetMessage("lbl Due Date");
        TaskDataGrid.Columns.Add(colBound);

        if ((actiontype == "by") || (actiontype == "all") || (actiontype == "both"))
        {
            colBound = new System.Web.UI.WebControls.BoundColumn();
            colBound.DataField = "ASSIGNEDTO";
            colBound.HeaderText = m_refMsg.GetMessage("lbl Assigned to");
            TaskDataGrid.Columns.Add(colBound);
        }
        if ((actiontype == "to") || (actiontype == "all") || (actiontype == "both"))
        {
            colBound = new System.Web.UI.WebControls.BoundColumn();
            colBound.DataField = "ASSIGNEDBY";
            colBound.HeaderText = m_refMsg.GetMessage("lbl Assigned By");
            TaskDataGrid.Columns.Add(colBound);
        }

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "COMMENT";
        colBound.HeaderText = m_refMsg.GetMessage("lbl Last Added comments");
        TaskDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "DATECREATED";
        colBound.HeaderText = m_refMsg.GetMessage("lbl Create Date");
        TaskDataGrid.Columns.Add(colBound);

        TaskDataGrid.BorderColor = System.Drawing.Color.White;

        DataTable dt = new DataTable();
        DataRow dr;

        dt.Columns.Add(new DataColumn("TITLE", typeof(string)));
        dt.Columns.Add(new DataColumn("ID", typeof(string)));
        dt.Columns.Add(new DataColumn("STATE", typeof(string)));
        dt.Columns.Add(new DataColumn("PRIORITY", typeof(string)));
        dt.Columns.Add(new DataColumn("DUEDATE", typeof(string)));
        dt.Columns.Add(new DataColumn("ASSIGNEDTO", typeof(string)));
        dt.Columns.Add(new DataColumn("ASSIGNEDBY", typeof(string)));
        dt.Columns.Add(new DataColumn("COMMENT", typeof(string)));
        dt.Columns.Add(new DataColumn("DATECREATED", typeof(string)));

        if (TaskExists == true)
        {
            int TaskItemType = 1;
            m_refTask = m_refContentApi.EkTaskRef;

            Ektron.Cms.PageRequestData null_EktronCmsPageRequestData = null;
            cTasks = m_refTask.GetTasks(m_intId, -1, -1, TaskItemType, Request.QueryString["orderby"], ContentLanguage, ref null_EktronCmsPageRequestData, "");
        }

        int i = 0;
        EkTask cTask;

        if (cTasks != null)
        {
            EmailHelper m_refMail = new EmailHelper();
            while (i < cTasks.Count)
            {
                i++;
                cTask = cTasks.get_Item(i);
                if (!(cTask.TaskTypeID == (long)Ektron.Cms.Common.EkEnumeration.TaskType.BlogPostComment))
                {
                    Array.Resize(ref arrTaskTypeID, i - 1 + 1);
                    arrTaskTypeID[i - 1] = (string)("shown_task_" + i + "_" + (cTask.TaskTypeID <= 0 ? "NotS" : (cTask.TaskTypeID.ToString())));

                    dr = dt.NewRow();

                    dr["TITLE"] = "<a href=\"tasks.aspx?action=ViewTask&tid=" + cTask.TaskID + "&folderid=" + cTask.FolderId  +  "&contentid=" + cTask.ContentID +  "&fromViewContent=1&ty=both&LangType=" + cTask.ContentLanguage + callBackPage + "\">" + cTask.TaskTitle + "</a>";
                    dr["TITLE"] += "	<script language=\"JavaScript\">" + "\r\n";
                    dr["TITLE"] += "					AddShownTaskID(\'" + arrTaskTypeID[i - 1] + "\');" + "\r\n";
                    dr["TITLE"] += "				</script>	" + "\r\n";

                    dr["ID"] = cTask.TaskID;
                    int iState = System.Convert.ToInt32(cTask.State);
                    switch (iState)
                    {
                        case 1:
                            dr["STATE"] = "Not Started";
                            break;
                        case 2:
                            dr["STATE"] = "Active";
                            break;
                        case 3:
                            dr["STATE"] = "Awaiting Data";
                            break;
                        case 4:
                            dr["STATE"] = "On Hold";
                            break;
                        case 5:
                            dr["STATE"] = "Pending";
                            break;
                        case 6:
                            dr["STATE"] = "ReOpened";
                            break;
                        case 7:
                            dr["STATE"] = "Completed";
                            break;
                        case 8:
                            dr["STATE"] = "Archived";
                            break;
                        case 9:
                            dr["STATE"] = "Deleted";
                            break;
                    }
                    int iPrio = System.Convert.ToInt32(cTask.Priority);
                    switch (iPrio)
                    {
                        case 1:
                            dr["PRIORITY"] = "Low";
                            break;
                        case 2:
                            dr["PRIORITY"] = "Normal";
                            break;
                        case 3:
                            dr["PRIORITY"] = "High";
                            break;
                    }

                    if (cTask.DueDate != "")
                    {
                        if (System.Convert.ToDateTime(cTask.DueDate) < DateTime.Today) //Verify:Udai 11/22/04 Replaced Now.ToOADate - 1 with DateTime.Today
                        {
                            dr["DUEDATE"] = cTask.DueDate; //Response.Write("<td class=""important"">" & AppUI.GetInternationalDateOnly(cTask.DueDate) & "</td>")
                        }
                        else
                        {
                            dr["DUEDATE"] = cTask.DueDate; //Response.Write("<td>" & AppUI.GetInternationalDateOnly(cTask.DueDate) & "</td>")
                        }
                    }
                    else
                    {
                        dr["DUEDATE"] = "[Not Specified]";
                    }
                    EkTask tempcTask = cTask;
                    if ((actiontype == "by") || (actiontype == "all") || (actiontype == "both"))
                    {
                        if (cTask.AssignToUserGroupID == 0)
                        {
                            dr["ASSIGNEDTO"] = "All Authors of (" + cTask.ContentID.ToString() + ")";
                        }
                        else if (cTask.AssignedToUser != "")
                        {
                            dr["ASSIGNEDTO"] = "<img src=\"" + m_refContentApi.AppPath + "images/UI/Icons/user.png\" align=\"absbottom\">" + m_refMail.MakeUserTaskEmailLink(tempcTask, false);
                        }
                        else if (cTask.AssignedToUserGroup != "")
                        {
                            dr["ASSIGNEDTO"] = "<img src=\"" + m_refContentApi.AppPath + "images/UI/Icons/users.png\" align=\"absbottom\">";
                            if (cTask.AssignToUserGroupID != -1)
                            {
                                dr[5] += m_refMail.MakeUserGroupTaskEmailLink(tempcTask);
                            }
                            else
                            {
                                dr[5] += cTask.AssignedToUserGroup;
                            }
                        }
                    }
                    if ((actiontype == "to") || (actiontype == "all") || (actiontype == "both"))
                    {
                        dr["ASSIGNEDBY"] = m_refMail.MakeByUserTaskEmailLink(tempcTask, false);

                    }

                    if (cTask.LastComment == "")
                    {
                        dr["COMMENT"] = "[Not Specified]";
                    }
                    else
                    {
                        dr["COMMENT"] = "<div class=\"comment-block\">" + cTask.LastComment + "</div>";
                    }
                    dr["DATECREATED"] = cTask.DateCreated; //GetInternationalDateOnly

                    dt.Rows.Add(dr);
                }
            }
        }
        DataView dv = new DataView(dt);
        TaskDataGrid.DataSource = dv;
        TaskDataGrid.DataBind();
    }
Beispiel #16
0
 public EmailController()
 {
     _helper    = new EmailHelper(); //IOC can be used for loose coupling
     _providers = _helper.getRandomProviders();
 }
Beispiel #17
0
        public void SendEmail(string recipentAddress, string recipientName)
        {
            EmailHelper emailHelper = new EmailHelper();

            emailHelper.SendEmail(recipentAddress, recipientName);
        }
Beispiel #18
0
        public ServiceResponseModel <string> InserteFleetFueling(eFleetFuelingModelForService objModel)
        {
            var objReturnModel = new ServiceResponseModel <string>();

            try
            {
                var objFuelingRepository = new FuelingRepository();
                var objDARRepository     = new DARRepository();
                var objDARDetail         = new DARDetail();
                var objDAR = new DARModel();
                var Obj    = new eFleetFueling();
                AutoMapper.Mapper.CreateMap <eFleetFuelingModelForService, eFleetFueling>();
                Obj             = AutoMapper.Mapper.Map(objModel, Obj);
                Obj.CreatedBy   = objModel.UserId;
                Obj.CreatedDate = DateTime.UtcNow;
                objFuelingRepository.Add(Obj);
                if (Obj.FuelID > 0)
                {
                    objDARDetail.ActivityDetails = DarMessage.RegisterNeweFleetFueling(objModel.LocationName);
                    //objDAR.ActivityDetails = objModel.ActivityDetails;
                    objDARDetail.LocationId = objModel.LocationID;
                    objDARDetail.TaskType   = (long)TaskTypeCategory.EfleetFuelingSubmission;
                    objDARDetail.CreatedBy  = objModel.UserId;
                    objDARDetail.CreatedOn  = DateTime.UtcNow;
                    objDARDetail.DeletedBy  = null;
                    objDARDetail.DeletedOn  = null;
                    objDARDetail.IsDeleted  = false;
                    objDARDetail.IsManual   = false;
                    objDARDetail.ModifiedBy = null;
                    objDARDetail.ModifiedOn = null;

                    objDARDetail.UserId    = objModel.UserId;
                    objDARDetail.StartTime = objModel.FuelingDate;
                    objDARDetail.EndTime   = DateTime.UtcNow;
                    objDARRepository.Add(objDARDetail);
                    //Result result = _ICommonMethod.SaveDAR(objDARDetail);

                    #region Email
                    var    objEmailLogRepository = new EmailLogRepository();
                    var    objEmailReturn        = new List <EmailToManagerModel>();
                    var    objListEmailog        = new List <EmailLog>();
                    var    objTemplateModel      = new TemplateModel();
                    Result result;
                    workorderEMSEntities db = new workorderEMSEntities();
                    if (objDARDetail.DARId > 0)
                    {
                        objEmailReturn = objEmailLogRepository.SendEmailToManagerForeFleetInspection(objModel.LocationID, objModel.UserId).Result;
                    }

                    if (objEmailReturn.Count > 0 && objDARDetail.DARId > 0)
                    {
                        foreach (var item in objEmailReturn)
                        {
                            bool IsSent         = false;
                            var  objEmailHelper = new EmailHelper();
                            objEmailHelper.emailid              = item.ManagerEmail;
                            objEmailHelper.ManagerName          = item.ManagerName;
                            objEmailHelper.DriverNameforFueling = objModel.DriverName;
                            objEmailHelper.FuelType             = (from gc in db.GlobalCodes where gc.GlobalCodeId == objModel.FuelType select gc.CodeName).FirstOrDefault();
                            objEmailHelper.GasStatioName        = objModel.GasStatioName;
                            objEmailHelper.Mileage              = objModel.Mileage;
                            objEmailHelper.CurrentFuel          = objModel.CurrentFuel;
                            objEmailHelper.Total         = objModel.Total.ToString();
                            objEmailHelper.VehicleNumber = objModel.VehicleNumber;
                            objEmailHelper.LocationName  = objModel.LocationName;
                            objEmailHelper.UserName      = item.UserName;
                            objEmailHelper.QrCodeId      = objModel.QRCodeID;
                            objEmailHelper.FuelingDate   = objModel.FuelingDate.ToString();
                            //objEmailHelper.InfractionStatus = obj.Status;
                            objEmailHelper.MailType      = "EfleetFueling";
                            objEmailHelper.SentBy        = item.RequestBy;
                            objEmailHelper.LocationID    = item.LocationID;
                            objEmailHelper.TimeAttempted = DateTime.UtcNow.ToMobileClientTimeZone(objTemplateModel.TimeZoneName, objTemplateModel.TimeZoneOffset, objTemplateModel.IsTimeZoneinDaylight, false).ToString();

                            IsSent = objEmailHelper.SendEmailWithTemplate();

                            //Push Notification
                            string message = PushNotificationMessages.eFleetFuelingReported(objModel.LocationName, objModel.QRCodeID, objModel.VehicleNumber);
                            PushNotification.GCMAndroid(message, item.DeviceId, objEmailHelper);
                            if (IsSent == true)
                            {
                                var objEmailog = new EmailLog();
                                try
                                {
                                    objEmailog.CreatedBy   = item.RequestBy;
                                    objEmailog.CreatedDate = DateTime.UtcNow;
                                    objEmailog.DeletedBy   = null;
                                    objEmailog.DeletedOn   = null;
                                    objEmailog.LocationId  = item.LocationID;
                                    objEmailog.ModifiedBy  = null;
                                    objEmailog.ModifiedOn  = null;
                                    objEmailog.SentBy      = item.RequestBy;
                                    objEmailog.SentEmail   = item.ManagerEmail;
                                    objEmailog.Subject     = objEmailHelper.Subject;
                                    objEmailog.SentTo      = item.ManagerUserId;
                                    objListEmailog.Add(objEmailog);
                                }
                                catch (Exception)
                                {
                                    throw;
                                }
                            }
                        }

                        using (var context = new workorderEMSEntities())
                        {
                            context.EmailLogs.AddRange(objListEmailog);
                            context.SaveChanges();
                        }
                        //    //var x = EmailLogRepository.InsertEntitiesNew("EmailLog", objListEmailog);
                        //    //Task<bool> x = null;
                        //    //foreach (var i in objListEmailog)
                        //    //{
                        //    //    x = objEmailLogRepository.SaveEmailLogAsync(i);
                        //    //}
                        //}


                        #endregion Email

                        if (objDARDetail.DARId > 0)
                        {
                            objReturnModel.Response = Convert.ToInt32(ServiceResponse.SuccessResponse, CultureInfo.InvariantCulture);
                            objReturnModel.Message  = CommonMessage.Successful();
                        }
                        else
                        {
                            objReturnModel.Response = Convert.ToInt32(ServiceResponse.FailedResponse, CultureInfo.CurrentCulture);
                            objReturnModel.Message  = CommonMessage.FailureMessage();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WorkOrderEMS.BusinessLogic.Exception_B.Exception_B.exceptionHandel_Runtime(ex, "ServiceResponseModel<string> InsertPreventativeMaintenance(eFleetPreventaticeMaintenanceModel objModel)", "while insert preventative maintenance", objModel);
                objReturnModel.Message  = ex.Message;
                objReturnModel.Response = Convert.ToInt32(ServiceResponse.ExeptionResponse, CultureInfo.CurrentCulture);
                objReturnModel.Data     = null;
            }
            return(objReturnModel);
        }
Beispiel #19
0
        public shGoodReceiptIsuue XuatDuLieuDonHang(string OrderGuid, int?OrderStatus, string Description, int UserId, int Phieu, int MaKho, int LoaiPhieu, string GhiChu, int TrangThai, bool?Status, DateTime?CreateDate, string MaDonHang)
        {
            // 1. Cập nhật trạng thái đơn hàng
            shOrderService _order = new shOrderService();
            shOrder        order  = _order.FindByKey(OrderGuid);

            order.OrderStatus = OrderStatus;
            _order.Update(order);

            shGoodReceiptIsuue receipt = new shGoodReceiptIsuue();

            if (OrderStatus != C.Core.Common.OrderStatus.HuyDonHang.GetHashCode())
            {
                // 2. ghi lịch sử cập nhật đơn hàng
                shOrderHistoryService _orderHistory = new shOrderHistoryService();
                shOrderHistory        orderHistory  = _orderHistory.Insert_Update(
                    null,
                    order.OrderGuid,
                    OrderStatus,
                    null,
                    Description,
                    UserId,
                    true,
                    DateTime.Now);

                // 3. Tạo hóa đơn xuất kho
                receipt = Insert_Update(
                    null,
                    null,
                    Phieu,
                    null,
                    null,
                    MaKho,
                    null,
                    LoaiPhieu,
                    MaDonHang,
                    GhiChu,
                    UserId,
                    TrangThai,
                    Status,
                    CreateDate
                    );


                // 4 Cập nhật số lượng tồn của mỗi sản phẩm
                shOrderDetailService        _orderdetail = new shOrderDetailService();
                IEnumerable <shOrderDetail> ds           = _orderdetail.DanhSachOrderDetailBy(order.OrderGuid, order.MemberGuid, null);

                shSizeService _size = new shSizeService();
                shSetSize     size  = new shSetSize();
                foreach (var item in ds)
                {
                    size = _size.FindByKey(item.SizeGuid);
                    if (size == null)
                    {
                        size = new shSetSize();
                    }

                    // 5.. Tạo chi tiết hóa đơn xuất hàng hóa
                    shGoodReceiptIsuueDetailService _receiptDetail = new shGoodReceiptIsuueDetailService();
                    shGoodReceiptIsuueDetail        receiptDetail  = _receiptDetail.Insert_Update(
                        null,
                        null,
                        receipt.ReceiptIsuueGuid,
                        size.ProductGuid,
                        size.SectionGuid,
                        size.SizeGuid,
                        item.Number,
                        Status,
                        CreateDate,
                        Phieu);

                    // 6.Update số lượng tồn ở bảng size

                    size.Inventory = size.Inventory - item.Number;
                    _size.Update(size);
                }

                // 5. Thông báo cho Khach hàng biết đơn hàng đã xử lý
                shMemberService _member   = new shMemberService();
                shMember        member    = _member.FindByKey(order.MemberGuid);
                int             MemberId  = member != null ? member.MemberId : 0;
                ThongBaoService _thongbao = new ThongBaoService();
                _thongbao.InsertOrUpdate(
                    null,
                    "Thông báo đơn hàng đang trong quá trình xử lý",
                    "Đơn hàng của bạn đang trong quá trình vận chuyển. Vui lòng kiểm tra thông tin cá nhân trong quá trình chúng tôi vận chuyển sản phẩm",
                    null,
                    UserId,
                    MemberId,
                    DateTime.Now,
                    false,
                    Config.THONG_BAO_DA_XU_LY_DON_HANG,
                    null
                    );

                // 6. Gửi Email báo xử lý đơn hàng

                string noidungdonhang = EmailHelper.NoiDungDonHang(order, new List <CartItem>());
                string noidungEmail   = EmailHelper.NoiDungMailThongBaoXuLyDatHang(noidungdonhang);

                EmailHelper.ThongBaoEmailDonHangMoiToiNguoiDatHang(member.Email, noidungEmail);
            }


            return(receipt);
        }
Beispiel #20
0
 public void Upgrade()
 {
     Console.WriteLine("Upgrading the membership");
     EmailHelper.SendEmail("Email Sent: Upgrading the membership");
 }
Beispiel #21
0
 public void Activate()
 {
     Console.WriteLine("Activating the membership");
     EmailHelper.SendEmail("Email Sent: Activating the membership");
 }
        public ResponseBase <bool> Inscrever(InscricaoRequest request)
        {
            ResponseBase <bool> br = new ResponseBase <bool>();

            var usuario = new Usuario(request.Nome, request.Senha, request.ConfirmacaoDeSenha, request.Email, request.Telefone)
            {
                Idioma = _contexto.Idioma.FirstOrDefault(i => i.Id == request.Idioma)
            };

            if (request.Tipo.HasValue)
            {
                usuario.Tipo = (TipoDeUsuario)request.Tipo;
            }

            if (_contexto.Usuario.Where(x => x.Email == request.Email).Count() > 0)
            {
                br.Mensagens.Add("Já existe um usuário cadastrado com este e-mail.");
            }

            var validationContext = new ValidationContext(usuario, null, null);
            var validationResults = ((IValidatableObject)usuario).Validate(validationContext);

            if (validationResults.Count() > 0)
            {
                foreach (ValidationResult v in validationResults)
                {
                    br.Mensagens.Add(v.ErrorMessage);
                }
            }

            if (br.Sucesso)
            {
                _contexto.Usuario.Add(usuario);
                if (_contexto.SaveChanges() > 0)
                {
                    // Enviar e-mail com token de validação do cadastro!
                    //http://app.demo.ethm.com/login?type=confirmed-email&token=asdhuasdhuashudashuduhasd

                    var template = @"<!DOCTYPE html><html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml""><head><meta charset=""utf-8"" /><title>demo.ethm</title></head><body><p>Clique <a href=""http://app.demo.ethm.com/login?type=confirmed-email&token={token}"">aqui</a> para confirmar seu cadastro em demo.ethm.com.</p></body></html>";

                    var assem = GetType().Assembly;

                    //var lista = assem.GetManifestResourceNames();

                    using (var stream = assem.GetManifestResourceStream("demo.ethm.Aplicacao.Resources.email_confirmar_cadastro_pt_br.html"))
                    {
                        template = new StreamReader(stream).ReadToEnd();
                    }

                    template.Replace("{token}", usuario.TokenConfirmacaoEmail);

                    // SMTP
                    // Server name: smtp-mail.outlook.com
                    // Port: 587
                    // Encryption method: TLS
                    // TODO: Move to configuration file
                    EmailHelper helper = new EmailHelper("smtp-mail.outlook.com", false, 25, "*****@*****.**", "lcD!12345");

                    // TODO: Traduzir assunto do e-mail de confirmação de cadastro
                    br.Sucesso = helper.Enviar(usuario.Email, Constants.ArquivoDeConfiguracao.Default.EmailSuporte, "demo.ethm - Confirmação de Cadastro", template.Replace("\r\n", "<br />").Replace("&", "&amp;"));
                }
            }

            return(br);
        }
Beispiel #23
0
        private void SendEmail(AmpliacionCredito ampliacionCredito, SolicitudResult resultadoSolicitud, Usuario usuario)
        {
            var correoDiners = System.Configuration.ConfigurationManager.AppSettings["CorreoDinersSac"];
            var asuntoEmail  = "Canal Web – SOLICITUD DE INCREMENTO DE LÍNEA";
            var emailsTo     = new List <string>();

            if (!string.IsNullOrEmpty(usuario.EmailPrincipal))
            {
                string correoUsuario = usuario.EmailSeleccionado == "1" ? usuario.EmailPrincipal : usuario.EmailAlternativo;
                emailsTo.Add(correoUsuario);
            }

            var emailsToDiners = new List <string>();

            emailsToDiners.Add(correoDiners);

            var dataPrincipal = new List <List <string> >();
            var data          = new List <string>();

            data.Add("Solicitud");
            data.Add("Solicitud de Incremento de Línea");
            dataPrincipal.Add(data);

            data = new List <string>();
            data.Add("Fecha y hora");
            var fechaFormateada = resultadoSolicitud.FechaRegistro.HasValue ? String.Format("{0:dd/MM/yyyy HH:mm}", (DateTime)resultadoSolicitud.FechaRegistro) : string.Empty;

            data.Add(fechaFormateada);
            dataPrincipal.Add(data);

            data = new List <string>();
            data.Add("N° Solicitud");
            data.Add(resultadoSolicitud.NumeroSolicitud.ToString());
            dataPrincipal.Add(data);

            data = new List <string>();
            data.Add("Tarjeta");
            data.Add(string.Format("{0} {1}", ampliacionCredito.NombreProducto, ampliacionCredito.NumeroTarjeta));
            dataPrincipal.Add(data);

            data = new List <string>();
            data.Add("Línea de crédito actual");
            data.Add(string.Format("S/ {0}", ampliacionCredito.CreditoActual.ToString("0,0.00")));
            dataPrincipal.Add(data);

            data = new List <string>();
            data.Add("Línea de crédito nueva");
            data.Add(string.Format("S/ {0}", ampliacionCredito.CreditoSolicitado.ToString("0,0.00")));
            dataPrincipal.Add(data);

            try
            {
                var contentParaUsuario = EmailHelper.CrearHtmlOperacionEmail(usuario.Socio.NombreCompleto, dataPrincipal);

                EmailSenderService.SendEmail(asuntoEmail, contentParaUsuario, correoDiners, emailsTo, null, null, null);
                data = new List <string>();
                data.Add("Información del socio");
                data.Add("");
                dataPrincipal.Add(data);

                data = new List <string>();
                data.Add("Nombre");
                data.Add(string.Format("{0} {1} {2}", usuario.Socio.Nombre, usuario.Socio.ApellidoPaterno, usuario.Socio.ApellidoMaterno));
                dataPrincipal.Add(data);

                data = new List <string>();
                data.Add("Documento de identidad");
                data.Add(string.Format("{0} {1} ", usuario.Socio.TipoDocumentoIdentidad, usuario.Socio.NumeroDocumentoIdentidad));
                dataPrincipal.Add(data);

                data = new List <string>();
                data.Add("Email");
                data.Add(usuario.EmailPrincipal);
                dataPrincipal.Add(data);

                data = new List <string>();
                data.Add("Celular");
                data.Add(usuario.NumeroCelular);
                dataPrincipal.Add(data);

                var contentParaDiners = EmailHelper.CrearHtmlOperacionEmail(usuario.Socio.NombreCompleto, dataPrincipal);

                EmailSenderService.SendEmail(asuntoEmail, contentParaDiners, correoDiners, emailsToDiners, null, null, null);
            }
            catch (System.Exception) { throw; }
        }
 public SpendItemMapper(EmailHelper emailHelper)
 {
     _emailHelper = emailHelper;
 }
Beispiel #25
0
        public ActionResult TwitterCallback(string oauth_token, string oauth_verifier, string state)
        {
            var requesttoken = new OAuthRequestToken {
                Token = oauth_token
            };
            string key    = ConfigurationManager.AppSettings["TwitterKey"].ToString();
            string secret = ConfigurationManager.AppSettings["TwitterSecret"].ToString();

            string[] myArray = state.Split('-');
            try
            {
                if (oauth_token != null)
                {
                    TwitterService   service     = new TwitterService(key, secret);
                    OAuthAccessToken accesstoken = service.GetAccessToken(requesttoken, oauth_verifier);
                    service.AuthenticateWith(accesstoken.Token, accesstoken.TokenSecret);
                    VerifyCredentialsOptions option = new VerifyCredentialsOptions();
                    TwitterUser user = service.VerifyCredentials(option);
                    TwitterLinkedInLoginModel obj = new TwitterLinkedInLoginModel();
                    if (user != null)
                    {
                        string[] name = user.Name.Split(' ');
                        if (name.Length > 1)
                        {
                            obj.firstName = name[0].ToString();
                            obj.lastName  = name[1].ToString();
                        }
                        else
                        {
                            obj.firstName = name[0].ToString();
                            obj.lastName  = "";
                        }

                        obj.id               = user.Id.ToString();
                        obj.pictureUrl       = user.ProfileImageUrlHttps;
                        obj.publicProfileUrl = "https://twitter.com/" + user.ScreenName;
                        obj.userType         = 3;


                        UserEntity userObj = new Business.UserService().AddOrUpdateUser(obj);
                        Session["UserObj"] = userObj;
                        Session["UserID"]  = userObj.UserID;
                        string message = string.Empty;
                        if (myArray[0] != "0")
                        {
                            if (myArray[1] == "C")
                            {
                                message = new Business.CompanyService().VoteForCompany(Convert.ToInt32(myArray[0]), userObj.UserID);
                                if (CacheHandler.Exists("TopVoteCompaniesList"))
                                {
                                    CacheHandler.Clear("TopVoteCompaniesList");
                                }
                                string compname = "";
                                if (!string.IsNullOrEmpty(Session["CompanyName"].ToString()))
                                {
                                    compname = Session["CompanyName"].ToString();
                                }
                                if (CacheHandler.Exists(compname))
                                {
                                    CacheHandler.Clear(compname);
                                }
                            }
                            else if (myArray[1] == "N")
                            {
                                message = new Business.SoftwareService().VoteForSoftware(Convert.ToInt32(myArray[0]), userObj.UserID);
                                string softwarename = "";
                                if (!string.IsNullOrEmpty(Session["SoftwareName"].ToString()))
                                {
                                    softwarename = Session["SoftwareName"].ToString();
                                }
                                if (CacheHandler.Exists(softwarename))
                                {
                                    CacheHandler.Clear(softwarename);
                                }
                            }
                        }
                    }
                }
                if (myArray[1] == "H")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString()));
                }
                else if (myArray[1] == "L")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + Convert.ToString(Session["FocusAreaName"])));
                }
                else if (myArray[1] == "C")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "Profile/" + Convert.ToString(Session["CompanyName"])));
                }
                else if (myArray[1] == "U")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "company/my-dashboard"));
                }
                else if (myArray[1] == "S")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + Convert.ToString(Session["SoftwareCategory"])));
                }
                else if (myArray[1] == "N")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "Software/" + Convert.ToString(Session["SoftwareName"])));
                }

                return(null);

                // return RedirectToAction("HomePage", "Home");
            }
            catch (Exception ex)
            {
                EmailHelper.SendErrorEmail(ex);
                throw;
            }
        }
        public async Task <bool> SendEmail(string to, string from, string subject, string plainTextMesage, string htmlMessage, string replyTo = null)
        {
            EmailHelper emailHelper = new EmailHelper(to, from, subject, plainTextMesage, htmlMessage, null);

            return(await emailHelper.SendEmailAsync());
        }
        public ActionResult HandleRegister(RegisterViewModel model)
        {
            var membershipService = ApplicationContext.Current.Services.MemberService;

            if (!ModelState.IsValid)
            {
                return PartialView("Register", model);
            }

            //Model valid let's create the member
            try
            {
                //Member createMember = Member.MakeNew(model.Name, model.EmailAddress, model.EmailAddress, umbJobMemberType, umbUser);
                // WARNING: update to your desired MembertypeAlias...
                var createMember = membershipService.CreateMember(model.EmailAddress, model.EmailAddress, model.Name, "CMember");

                //Set the verified email to false
                createMember.Properties["hasVerifiedEmail"].Value = false;

                //Set the profile URL to be the member ID, so they have a unqie profile ID, until they go to set it
                createMember.Properties["profileURL"].Value = model.ProfileURL;

                //Save the changes, if we do not do so, we cannot save the password.
                membershipService.Save(createMember);

                //Set password on the newly created member
                membershipService.SavePassword(createMember, model.Password);
            }
            catch (Exception ex)
            {
                //EG: Duplicate email address - already exists
                ModelState.AddModelError("memberCreation", ex.Message);

                return CurrentUmbracoPage();
            }

            //Create temporary GUID
            var tempGUID = Guid.NewGuid();

            //Fetch our new member we created by their email
            var updateMember = membershipService.GetByEmail(model.EmailAddress);

            //Just to be sure...
            if (updateMember != null)
            {
                //Set the verification email GUID value on the member
                updateMember.Properties["emailVerifyGUID"].Value = tempGUID.ToString();

                //Set the Joined Date label on the member
                updateMember.Properties["joinedDate"].Value = DateTime.Now.ToString("dd/MM/yyyy @ HH:mm:ss");

                //Save changes
                membershipService.Save(updateMember);
            }

            //Send out verification email, with GUID in it
            EmailHelper email = new EmailHelper();
            email.SendVerifyEmail(model.EmailAddress, tempGUID.ToString());

            //Update success flag (in a TempData key)
            TempData["IsSuccessful"] = true;

            //All done - redirect back to page
            return RedirectToCurrentUmbracoPage();
        }
Beispiel #28
0
        // GET: Email
        public ActionResult Index(int id)
        {
            EmailHelper helper = new EmailHelper();

            return(View(helper.GetEmail(id)));
        }
        public ActionResult FinalizeazaComanda(FinalizareComandaModel finalizeazaComanda)
        {
            var userLogat = Session["UserLogat"].ToString();
            var user      = _userManager.GetUsers().Where(u => u.UserName == userLogat).FirstOrDefault();
            var client    = _userManager.GetClientForUsername(user.IdUser);

            var listaProduseInCos = _cosManager.GetCartProducts(client.IdClient);

            var sb = new StringBuilder();

            decimal total = 0;

            sb.Append("S-au comandat urmatoarele produse:");
            sb.Append(Environment.NewLine);
            foreach (var produs in listaProduseInCos)
            {
                sb.Append(Environment.NewLine);
                sb.Append("Denumire Produs: " + produs.Produs.NumeProdus + "  , " + "Cantitate: " + produs.Cantitate + "  , " + "Pret: " + (produs.Produs.PretProdus * produs.Cantitate).ToString("#.##") + " RON");
                total = total + produs.Produs.PretProdus;
            }

            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append("TOTAL: " + total.ToString("#.##") + " RON");
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);

            sb.Append("Produsele vor fi expediate la adresa: ");
            sb.Append(Environment.NewLine);
            sb.Append("Strada: " + finalizeazaComanda.Strada + " , " + "Numar: " + finalizeazaComanda.Numar);
            sb.Append(Environment.NewLine);
            sb.Append("Oras: " + finalizeazaComanda.Oras + " , " + "Cod postal: " + finalizeazaComanda.CodPostal + ", " + finalizeazaComanda.Tara);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append("Produsele va for fi livrate in data de: " + DateTime.Now.AddDays(3));
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append("Va multumim!");

            var emailBody = sb.ToString();

            var adresa = new Adresa()
            {
                Strada    = finalizeazaComanda.Strada,
                CodPostal = finalizeazaComanda.CodPostal,
                Judet     = finalizeazaComanda.Judet,
                Numar     = finalizeazaComanda.Numar.ToString(),
                Oras      = finalizeazaComanda.Oras
            };

            var esteComandaAdaugata = _cosManager.AdaugaComanda(adresa, client.IdClient, listaProduseInCos);

            if (esteComandaAdaugata)
            {
                EmailHelper.SendEmail(
                    Constants.EmailFrom,
                    client.Email,
                    Constants.FromName,
                    Constants.EmailTimeStamp + DateTime.Now,
                    emailBody);
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #30
0
        public ActionResult GetEmailBody(int emailID)
        {
            EmailHelper helper = new EmailHelper();

            return(Content(helper.GetEmailBody(emailID)));
        }
Beispiel #31
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext       = ((MvcApplication)sender).Context;
            var currentController = " ";
            var currentAction     = " ";
            var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !string.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !string.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }
            var ex = Server.GetLastError();

            try
            {
                if (ex is HttpException)
                {
                    if (((HttpException)ex).GetHttpCode() != 404)
                    {
                        EmailHelper.SendErrorEmail(ConfigurationManager.AppSettings["ErrorEmailAddress"], ex, currentController, currentAction);
                    }
                }
            }
            catch (Exception exx)
            {
                //
            }

            var routeData = new RouteData();
            var action    = "GenericError";

            if (ex is HttpException)
            {
                var httpEx = ex as HttpException;

                switch (httpEx.GetHttpCode())
                {
                case 400:
                    action = "BadRequest";
                    break;

                case 404:
                    action = "NotFound";
                    break;
                    // others if any
                }
            }

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode             = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;

            routeData.Values["controller"] = "Error";
            routeData.Values["action"]     = action;
            routeData.Values["exception"]  = new HandleErrorInfo(ex, currentController, currentAction);

            IController        errorController = new ErrorController();
            HttpContextWrapper wrapper         = new HttpContextWrapper(httpContext);
            var rc = new RequestContext(wrapper, routeData);

            errorController.Execute(rc);
        }
Beispiel #32
0
        public ActionResult GetPrevPublisherEmail(string countryCode, PublisherStatus status, int publisherId)
        {
            EmailHelper helper = new EmailHelper();

            return(Json(helper.GetPrevEmailByPublisherCountryAndStatus(countryCode, status, publisherId), JsonRequestBehavior.AllowGet));
        }
 public void SendErrorSucceeds()
 {
     client.Setup(x => x.Send(It.IsAny<MailMessage>()));
     IEmailHelper helper = new EmailHelper(client.Object);
     helper.SendErrorEmail(new Exception());
 }
Beispiel #34
0
        public ActionResult GetPublisherEmailsTotal(int publisherId)
        {
            EmailHelper helper = new EmailHelper();

            return(Json(helper.GetTotalRecords(publisherId), JsonRequestBehavior.AllowGet));
        }
 public void SendStripSubscriptionSucceeds()
 {
     client.Setup(x => x.Send(It.IsAny<MailMessage>()));
     IEmailHelper helper = new EmailHelper(client.Object);
     helper.SendStripeSubscription("1234");
 }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName   = String.Empty;
            string nickName   = String.Empty;
            string firstName  = String.Empty;
            string lastName   = String.Empty;
            string emailValue = String.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            if (txtUserName != null)
            {
                userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            }

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName))
            {
                userName = emailValue;
                if (String.IsNullOrEmpty(emailValue))
                {
                    formUser.StopProcessing = true;
                    lblError.Visible        = true;
                    lblError.Text           = GetString("customregistrationform.usernameandemail");
                    return;
                }
                else
                {
                    formUser.Data.SetValue("UserName", userName);
                }
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            // Test if "global" or "site" user exists.
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
            if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                return;
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Validate and save form with new user data
            if (!formUser.Save())
            {
                // Return if saving failed
                return;
            }

            // Get user info from form
            UserInfo ui = (UserInfo)formUser.Info;

            // Add user prefix if settings is on
            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign    = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            // Fill optionally full user name
            if (String.IsNullOrEmpty(ui.FullName))
            {
                ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
            }

            // Ensure nick name
            if (ui.UserNickName.Trim() == String.Empty)
            {
                ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
            }

            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
            ui.UserSettings.UserLogActivities        = true;
            ui.UserSettings.UserShowIntroductionTile = true;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            // Get user password and save it in apropriate format after form save
            string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
            UserInfoProvider.SetPassword(ui, password);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            // Prepare macro replacements
            string[,] replacements = new string[6, 2];
            replacements[0, 0]     = "confirmaddress";
            replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
            replacements[1, 0]     = "username";
            replacements[1, 1]     = userName;
            replacements[2, 0]     = "password";
            replacements[2, 1]     = password;
            replacements[3, 0]     = "Email";
            replacements[3, 1]     = emailValue;
            replacements[4, 0]     = "FirstName";
            replacements[4, 1]     = firstName;
            replacements[5, 0]     = "LastName";
            replacements[5, 1]     = lastName;

            // Set resolver
            resolver.SetNamedSourceData(replacements);

            // Email message
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.EmailFormat = EmailFormatEnum.Default;
            emailMessage.Recipients  = ui.Email;

            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                }
            }

            if (template != null)
            {
                emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                // Enable macro encoding for body
                resolver.Settings.EncodeResolvedValues = true;
                emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                // Disable macro encoding for plaintext body and subject
                resolver.Settings.EncodeResolvedValues = false;
                emailMessage.PlainTextBody             = resolver.ResolveMacros(template.TemplatePlainText);
                emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                emailMessage.CcRecipients  = template.TemplateCc;
                emailMessage.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(currentSiteName, emailMessage, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                }

                if (mEmailTemplate == null)
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    // E-mail template ok
                    replacements       = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = userName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(currentSiteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                {
                    HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }

                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Site and roles addition and authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string siteName in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, sn))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlRegForm.Visible = false;
                lblInfo.Visible    = true;
                lblInfo.Text       = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty);
                if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash")))
                {
                    URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
                }
                else if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
 protected void Button4_Click(object sender, EventArgs e)
 {
     EmailHelper eh = new EmailHelper();
     eh.Send_Registration_Email("James", "Choi", "jameschoi", "*****@*****.**");
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Functions"/> class.
        /// </summary>
        /// <param name="fulfillmentApiClient">The fulfillment API client.</param>
        /// <param name="subscriptionRepository">The subscription repository.</param>
        /// <param name="applicationConfigRepository">The application configuration repository.</param>
        /// <param name="subscriptionLogRepository">The subscription log repository.</param>
        /// <param name="emailTemplaterepository">The email templaterepository.</param>
        /// <param name="planEventsMappingRepository">The plan events mapping repository.</param>
        /// <param name="offerAttributesRepository">The offer attributes repository.</param>
        /// <param name="eventsRepository">The events repository.</param>
        /// <param name="azureKeyVaultClient">The azure key vault client.</param>
        /// <param name="planRepository">The plan repository.</param>
        /// <param name="offersRepository">The offers repository.</param>
        /// <param name="usersRepository">The users repository.</param>
        /// <param name="armTemplateRepository">The arm template repository.</param>
        /// <param name="azureBlobFileClient">The azure BLOB file client.</param>
        /// <param name="subscriptionTemplateParametersRepository">The subscription template parameters repository.</param>
        /// <param name="keyVaultConfig">The key vault configuration.</param>
        /// <param name="emailService">The email service.</param>
        /// <param name="emailHelper">The email helper.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public Functions(
            IFulfillmentApiClient fulfillmentApiClient,
            ISubscriptionsRepository subscriptionRepository,
            IApplicationConfigRepository applicationConfigRepository,
            ISubscriptionLogRepository subscriptionLogRepository,
            IEmailTemplateRepository emailTemplaterepository,
            IPlanEventsMappingRepository planEventsMappingRepository,
            IOfferAttributesRepository offerAttributesRepository,
            IEventsRepository eventsRepository,
            IPlansRepository planRepository,
            IOffersRepository offersRepository,
            IUsersRepository usersRepository,
            IEmailService emailService,
            EmailHelper emailHelper,
            ILoggerFactory loggerFactory)
        {
            this.fulfillmentApiClient        = fulfillmentApiClient;
            this.subscriptionRepository      = subscriptionRepository;
            this.applicationConfigrepository = applicationConfigRepository;
            this.emailTemplaterepository     = emailTemplaterepository;
            this.planEventsMappingRepository = planEventsMappingRepository;
            this.offerAttributesRepository   = offerAttributesRepository;
            this.eventsRepository            = eventsRepository;
            this.subscriptionLogRepository   = subscriptionLogRepository;
            this.planRepository           = planRepository;
            this.offersRepository         = offersRepository;
            this.usersRepository          = usersRepository;
            this.emialService             = emailService;
            this.emailHelper              = emailHelper;
            this.loggerFactory            = loggerFactory;
            this.activateStatusHandlers   = new List <ISubscriptionStatusHandler>();
            this.deactivateStatusHandlers = new List <ISubscriptionStatusHandler>();

            this.activateStatusHandlers.Add(new PendingActivationStatusHandler(
                                                fulfillmentApiClient,
                                                subscriptionRepository,
                                                subscriptionLogRepository,
                                                planRepository,
                                                usersRepository,
                                                this.loggerFactory.CreateLogger <PendingActivationStatusHandler>()));

            this.activateStatusHandlers.Add(new PendingFulfillmentStatusHandler(
                                                fulfillmentApiClient,
                                                this.applicationConfigrepository,
                                                subscriptionRepository,
                                                subscriptionLogRepository,
                                                planRepository,
                                                usersRepository,
                                                this.loggerFactory.CreateLogger <PendingFulfillmentStatusHandler>()));

            this.activateStatusHandlers.Add(new NotificationStatusHandler(
                                                fulfillmentApiClient,
                                                planRepository,
                                                this.applicationConfigrepository,
                                                emailTemplaterepository,
                                                planEventsMappingRepository,
                                                offerAttributesRepository,
                                                eventsRepository,
                                                subscriptionRepository,
                                                usersRepository,
                                                offersRepository,
                                                emailService,
                                                this.loggerFactory.CreateLogger <NotificationStatusHandler>()));

            this.deactivateStatusHandlers.Add(new UnsubscribeStatusHandler(
                                                  fulfillmentApiClient,
                                                  subscriptionRepository,
                                                  subscriptionLogRepository,
                                                  planRepository,
                                                  usersRepository,
                                                  this.loggerFactory.CreateLogger <UnsubscribeStatusHandler>()));

            this.deactivateStatusHandlers.Add(new NotificationStatusHandler(
                                                  fulfillmentApiClient,
                                                  planRepository,
                                                  this.applicationConfigrepository,
                                                  emailTemplaterepository,
                                                  planEventsMappingRepository,
                                                  offerAttributesRepository,
                                                  eventsRepository,
                                                  subscriptionRepository,
                                                  usersRepository,
                                                  offersRepository,
                                                  emailService,
                                                  this.loggerFactory.CreateLogger <NotificationStatusHandler>()));
        }
Beispiel #39
0
 public void Init()
 {
     _emailHelper = new EmailHelper("site", "user", "password",
                                                    "https://secure.eloqua.com/API/REST/1.0/");
 }
Beispiel #40
0
        public ActionResult EditarMatriz(MatrizViewModel matrizviewmodel)
        {
            try
            {
                var usuario = BL.Usuario.Get(a => a.IdUsuario == matrizviewmodel.IdResponsavel).FirstOrDefault();
                //matrizviewmodel.ReprovacaoMatriz.Observacao = Request.Form["descricao"];
                matrizviewmodel.Aprovado = (!string.IsNullOrEmpty(Request.Form["aprovarMatriz"])) ? Convert.ToInt16(Request.Form["aprovarMatriz"]) : new Nullable <short>();

                var modulo = ModuloViewModel.MapToModel((List <ModuloComponenteViewModel>)Session["Modulos"]);
                BL.Modulo.VinculoModuloComponentes(modulo, matrizviewmodel.Nome, matrizviewmodel.CH.ToString());

                if (matrizviewmodel.Aprovado == 0 && matrizviewmodel.ReprovacaoMatriz.observacao != null)
                {
                    BL.Matriz.AtualizarReprovacaoMatriz(MatrizViewModel.MapToModel(matrizviewmodel), DateTime.Now, matrizviewmodel.ReprovacaoMatriz.observacao);
                    EmailHelper.DispararEmail(usuario.Nome, "Reprovação de matriz", usuario.Email, "", "A Matriz foi reprovada pelo seguinte motivo: " + matrizviewmodel.ReprovacaoMatriz.observacao);
                }
                else if (matrizviewmodel.Aprovado != 1)
                {
                    matrizviewmodel.Aprovado = null;
                    BL.Matriz.AtualizarMatriz(MatrizViewModel.MapToModel(matrizviewmodel));
                }
                else if (matrizviewmodel.Aprovado == 1)
                {
                    if (string.IsNullOrEmpty(matrizviewmodel.ReprovacaoMatriz.observacao))
                    {
                        matrizviewmodel.ReprovacaoMatriz.observacao = "";
                    }
                    BL.Matriz.AtualizarReprovacaoMatriz(MatrizViewModel.MapToModel(matrizviewmodel), DateTime.Now, matrizviewmodel.ReprovacaoMatriz.observacao);
                }



                if (Session["Sucesso"] != null)
                {
                    if ((bool)Session["Sucesso"])
                    {
                        var model = MatrizViewModel.MapToModel(matrizviewmodel);
                        BL.Matriz.AtualizarMatriz(model);

                        TempData["Sucesso"]        = true;
                        TempData["SucessoMessage"] = "Edição de Matriz realizada com sucesso.";
                    }
                    Session["Sucesso"] = null;
                }
                else
                {
                    TempData["Error"]        = true;
                    TempData["ErrorMessage"] = Session["ErrorMessage"];
                    Session["ErrorMessage"]  = null;
                }
            }
            catch (Exception ex)
            {
                TempData["Error"]        = true;
                TempData["ErrorMessage"] = "Erro ao editar Matriz.";

                Logging.getInstance().Error("Erro ao editar Matriz", ex);
            }

            return(RedirectToAction("Index"));
        }
Beispiel #41
0
        public ActionResult LinkedINAuth(string code, string state)
        {
            try
            {
                //This method path is your return URL
                string[] myArray = state.Split('-');
                if (code != null)
                {
                    //try
                    //{
                    var a       = Request.Url;
                    var client  = new RestClient("http://www.linkedin.com/oauth/v2/accessToken");
                    var request = new RestRequest(Method.POST);
                    request.AddParameter("grant_type", "authorization_code");
                    request.AddParameter("code", code);
                    request.AddParameter("redirect_uri", _baseURL + "Login/LinkedINAuth");
                    request.AddParameter("client_id", ConfigurationManager.AppSettings["LinkedInClientID"].ToString());
                    request.AddParameter("client_secret", ConfigurationManager.AppSettings["LinkedInCLientSecret"].ToString());
                    request.AddParameter("scope", "all");
                    var    response     = client.Execute <InventoryItem>(request);
                    var    content      = response.Content;
                    string access_token = response.Data.access_token;
                    //client = new RestClient("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,certifications,date-of-birth,email-address,picture-url,summary,public-profile-url,positions,skills,location)?oauth2_access_token=" + access_token + "&format=json");
                    client  = new RestClient("https://api.linkedin.com/v2/me?oauth2_access_token=" + access_token); //for user info
                    request = new RestRequest(Method.GET);
                    var          response1       = client.Execute(request);
                    LinkedInInfo linkedInUserobj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <LinkedInInfo>(response1.Content.ToString());

                    //client = new RestClient("https://api.linkedin.com/v2/me?projection=(id,profilePicture(displayImage~:playableStreams))&oauth2_access_token=" + access_token);--for profileimage
                    //client = new RestClient("https://api.linkedin.com/v2/me?fields=id,firstName,lastName,educations,skills,positions&oauth2_access_token=" + access_token);
                    client = new RestClient("https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))&oauth2_access_token=" + access_token);

                    request = new RestRequest(Method.GET);

                    response1 = client.Execute(request);
                    LinkedInImageInfo linkedInImgObj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <LinkedInImageInfo>(response1.Content.Replace("~", "tilde").ToString());
                    string            imageName      = "";
                    if (linkedInImgObj.profilePicture != null && linkedInImgObj.profilePicture.displayImagetilde != null)
                    {
                        foreach (var item in linkedInImgObj.profilePicture.displayImagetilde.elements)
                        {
                            if (imageName == "")
                            {
                                foreach (var img in item.identifiers)
                                {
                                    if (img.identifier.Contains("_100_100"))
                                    {
                                        imageName = img.identifier;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    //TwitterLinkedInLoginModel obj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<TwitterLinkedInLoginModel>(response1.Content.ToString());
                    TwitterLinkedInLoginModel obj = new TwitterLinkedInLoginModel();
                    obj.firstName        = linkedInUserobj.localizedFirstName;
                    obj.id               = linkedInUserobj.id;
                    obj.lastName         = linkedInUserobj.localizedLastName;
                    obj.pictureUrl       = imageName;
                    obj.publicProfileUrl = "";
                    obj.userType         = 2; //LinkedIn
                    UserEntity userObj = new Business.UserService().AddOrUpdateUser(obj);
                    if (userObj != null)
                    {
                        Session["UserObj"] = userObj;
                        Session["UserID"]  = userObj.UserID;
                        string message = string.Empty;
                        if (myArray[0] != "0")
                        {
                            if (myArray[1] == "C")
                            {
                                message = new Business.CompanyService().VoteForCompany(Convert.ToInt32(myArray[0]), userObj.UserID);
                                if (CacheHandler.Exists("TopVoteCompaniesList"))
                                {
                                    CacheHandler.Clear("TopVoteCompaniesList");
                                }
                                string compname = "";
                                if (!string.IsNullOrEmpty(Session["CompanyName"].ToString()))
                                {
                                    compname = Session["CompanyName"].ToString();
                                }
                                if (CacheHandler.Exists(compname))
                                {
                                    CacheHandler.Clear(compname);
                                }
                            }
                            else if (myArray[1] == "N")
                            {
                                message = new Business.SoftwareService().VoteForSoftware(Convert.ToInt32(myArray[0]), userObj.UserID);
                                string softwarename = "";
                                if (!string.IsNullOrEmpty(Session["SoftwareName"].ToString()))
                                {
                                    softwarename = Session["SoftwareName"].ToString();
                                }
                                if (CacheHandler.Exists(softwarename))
                                {
                                    CacheHandler.Clear(softwarename);
                                }
                            }
                        }
                    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    throw ex;
                    //}
                }
                if (myArray[1] == "H")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString()));
                }
                else if (myArray[1] == "L")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + Convert.ToString(Session["FocusAreaName"])));
                }
                else if (myArray[1] == "C")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "Profile/" + Convert.ToString(Session["CompanyName"])));
                }
                else if (myArray[1] == "U")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "company/my-dashboard"));
                }
                else if (myArray[1] == "S")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + Convert.ToString(Session["SoftwareCategory"])));
                }
                else if (myArray[1] == "N")
                {
                    return(Redirect(ConfigurationManager.AppSettings["WebBaseURL"].ToString() + "Software/" + Convert.ToString(Session["SoftwareName"])));
                }
            }
            catch (Exception ex)
            {
                EmailHelper.SendErrorEmail(ex);
                throw ex;
            }

            return(null);
        }
        public async Task SavePeriodictEmailNotificationsAndUpdateScoreCardAndOfferStatus()
        {
            Console.WriteLine("In SavePeriodictEmailNotificationsAndUpdateScoreCardAndOfferStatus method ....");
            LogHelper.LogInfo("In SavePeriodictEmailNotificationsAndUpdateScoreCardAndOfferStatus method ....");


            DIBZ.Common.DTO.EmailTemplateResponse emailTemplateReminder          = new Common.DTO.EmailTemplateResponse();
            DIBZ.Common.DTO.EmailTemplateResponse emailTemplatePaymentRunningOut = new Common.DTO.EmailTemplateResponse();

            try
            {
                //var emailTemplateLogic = Context.Create<EmailTemplateLogic>();

                LogicContext = new LogicContext();
                var emailTemplateLogic = LogicContext.Create <EmailTemplateLogic>();

                Console.WriteLine("fetching all swaps with offer status payment needed....");
                LogHelper.LogInfo("fetching all swaps with offer status payment needed....");

                var swapsWithPaymentNeeded = await emailTemplateLogic.GetAllSwapsWithPaymentNeeded();


                Console.WriteLine("fetched payment needed email template....");
                LogHelper.LogInfo("fetched payment needed email template....");

                var scorecardLogic = LogicContext.Create <ScorecardLogic>();
                var offerLogic     = LogicContext.Create <OfferLogic>();
                foreach (var item in swapsWithPaymentNeeded)
                {
                    var timeElapsed = DateTime.Now.Subtract(DIBZ.Common.ConversionHelper.ConvertDateToTimeZone(item.CreatedTime)).TotalHours;
                    // saving for gamer offerer

                    /*if (!item.Offer.ApplicationUser.Transactions.Any(o => o.OfferId == item.OfferId)
                     *  && (timeElapsed > SystemSettings.PeriodicEmailHour && timeElapsed < (SystemSettings.PeriodicEmailHour * 3) - 12))
                     * {
                     *  EmailTemplateHelper templates = new EmailTemplateHelper();
                     *
                     *  templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);
                     *
                     *  var emailBody = templates.FillTemplate(emailTemplateReminder.Body);
                     *
                     *  Console.WriteLine("saving periodic reminder email notification for the offerer....");
                     *  LogHelper.LogInfo("saving periodic reminder email notification for the offerer....");
                     *
                     *  await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.Medium);
                     * }
                     * else if (!item.Offer.ApplicationUser.Transactions.Any(o => o.OfferId == item.OfferId) && timeElapsed > SystemSettings.PaymentTimeInHours - 6)
                     * {
                     *  emailTemplateReminder = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.FinalPaymentReminder);
                     *  EmailTemplateHelper templates = new EmailTemplateHelper();
                     *
                     *  templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);
                     *
                     *  var emailBody = templates.FillTemplate(emailTemplateReminder.Body);
                     *
                     *  Console.WriteLine("saving final reminder email notification for the offerer....");
                     *  LogHelper.LogInfo("saving final reminder email notification for the offerer....");
                     *
                     *  await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.High);
                     * }
                     *
                     * // saving for gamer swapper
                     * if (!item.GameSwapPserson.Transactions.Any(o => o.OfferId == item.OfferId)
                     *  && (timeElapsed > SystemSettings.PeriodicEmailHour && timeElapsed < (SystemSettings.PeriodicEmailHour * 3) - 12))
                     * {
                     *  EmailTemplateHelper templates = new EmailTemplateHelper();
                     *
                     *  templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);
                     *
                     *  var emailBody = templates.FillTemplate(emailTemplateReminder.Body);
                     *
                     *  Console.WriteLine("saving periodic reminder email notification for the swapper....");
                     *  LogHelper.LogInfo("saving periodic reminder email notification for the swapper....");
                     *
                     *  await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.Medium);
                     * }
                     * else if (!item.GameSwapPserson.Transactions.Any(o => o.OfferId == item.OfferId) && timeElapsed > SystemSettings.PaymentTimeInHours - 6)
                     * {
                     *  emailTemplateReminder = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.FinalPaymentReminder);
                     *
                     *  EmailTemplateHelper templates = new EmailTemplateHelper();
                     *
                     *  templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                     *  templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);
                     *
                     *  var emailBody = templates.FillTemplate(emailTemplateReminder.Body);
                     *
                     *  Console.WriteLine("saving final reminder email notification for the swapper....");
                     *  LogHelper.LogInfo("saving final reminder email notification for the swapper....");
                     *
                     *  await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.High);
                     *
                     * }*/


                    //Reminder email sent to the party who doesn't make the payment after 30 minutes
                    //sent to the party who has not paid
                    // saving for gamer offerer
                    if (!item.Offer.ApplicationUser.Transactions.Any(o => o.OfferId == item.OfferId) && (timeElapsed > SystemSettings.SrvcPaymentTimeInHours / 2 && timeElapsed < SystemSettings.SrvcPaymentTimeInHours))
                    {
                        emailTemplateReminder = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.FinalPaymentReminder);

                        EmailTemplateHelper templates = new EmailTemplateHelper();

                        templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);

                        var emailBody = templates.FillTemplate(emailTemplateReminder.Body);

                        Console.WriteLine("saving final reminder email notification for the offerer....");
                        LogHelper.LogInfo("saving final reminder email notification for the offerer....");

                        await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.Offer.ApplicationUser.Email, emailTemplateReminder.Title, emailBody);
                    }
                    // saving for gamer swapper
                    if (!item.GameSwapPserson.Transactions.Any(o => o.OfferId == item.OfferId) && (timeElapsed > SystemSettings.SrvcPaymentTimeInHours / 2 && timeElapsed < SystemSettings.SrvcPaymentTimeInHours))
                    {
                        emailTemplateReminder = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.FinalPaymentReminder);

                        EmailTemplateHelper templates = new EmailTemplateHelper();

                        templates.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templates.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templates.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);

                        var emailBody = templates.FillTemplate(emailTemplateReminder.Body);

                        Console.WriteLine("saving final reminder email notification for the swapper....");
                        LogHelper.LogInfo("saving final reminder email notification for the swapper....");

                        await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplateReminder.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.GameSwapPserson.Email, emailTemplateReminder.Title, emailBody);
                    }

                    //When time has ran out : Sent to both parties in the swap
                    if (item.Offer.ApplicationUser.Transactions.Count() == 0 && timeElapsed > SystemSettings.SrvcPaymentTimeInHours)
                    {
                        await offerLogic.UpdateOfferStatusToPending(item.OfferId);

                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.Offer.ApplicationUserId);

                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.GameSwapPsersonId);

                        emailTemplatePaymentRunningOut = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.PaymentTimeRanOut);

                        // to offerer

                        EmailTemplateHelper templatesForOfferer = new EmailTemplateHelper();

                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);

                        var emailBody = templatesForOfferer.FillTemplate(emailTemplatePaymentRunningOut.Body);

                        Console.WriteLine("saving final reminder email notification for the Offerer....");
                        LogHelper.LogInfo("saving final reminder email notification for the Offerer....");

                        await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplatePaymentRunningOut.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.Offer.ApplicationUser.Email, emailTemplatePaymentRunningOut.Title, emailBody);

                        // to swapper

                        EmailTemplateHelper templatesForSwapper = new EmailTemplateHelper();

                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);

                        var emailBodyForSwapper = templatesForSwapper.FillTemplate(emailTemplatePaymentRunningOut.Body);

                        Console.WriteLine("saving final reminder email notification for the Offerer....");
                        LogHelper.LogInfo("saving final reminder email notification for the Offerer....");
                        await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplatePaymentRunningOut.Title, emailBodyForSwapper, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.GameSwapPserson.Email, emailTemplatePaymentRunningOut.Title, emailBodyForSwapper);
                    }
                }
                await Task.Delay((int)((SystemSettings.SrvcPaymentTimeInHours * 60) / 2) *60000);
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.Message, ex);
            }
        }
Beispiel #43
0
    private void Page_Init(System.Object sender, System.EventArgs e)
    {
        m_refMsg = m_refContentApi.EkMsgRef;
        if (m_refContentApi.RequestInformationRef.IsMembershipUser == 1 || m_refContentApi.RequestInformationRef.UserId == 0)
        {
            Response.Redirect(m_refContentApi.ApplicationPath + "reterror.aspx?info=" + Server.UrlEncode(m_refMsg.GetMessage("msg login cms user")), false);
            return;
        }
        this.ShowAjaxTreeJsValues();
        this.SetEktronContentTemplateJsValues();
        this.RegisterJs();
        this.RegisterCss();

        Response.CacheControl = "no-cache";
        Response.AddHeader("Pragma", "no-cache");
        Response.Expires = -1;

        if (m_refContentApi.GetCookieValue("user_id") == "0")
        {
            if (!(Request.QueryString["callerpage"] == null))
            {
                Session["RedirectLnk"] = "Content.aspx?" + AntiXss.UrlEncode(Request.QueryString.ToString());
            }
            Response.Redirect("login.aspx?fromLnkPg=1", false);
            return;
        }

        if (!string.IsNullOrEmpty(Request.QueryString["action"]))
        {
            PageAction = Convert.ToString(Request.QueryString["action"]).ToLower().Trim();
        }

        if (!string.IsNullOrEmpty(Request.QueryString["membership"]))
        {
            m_strMembership = Convert.ToString(Request.QueryString["membership"]).ToLower().Trim();
        }

        if (m_refContentApi.TreeModel == 1)
        {
            m_bAjaxTree = true;
        }

        Int32 lastValidLanguageID;
        string LastValidLanguage = m_refContentApi.GetCookieValue("LastValidLanguageID");
        if (LastValidLanguage == null || !Int32.TryParse(LastValidLanguage, out lastValidLanguageID)) lastValidLanguageID = Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED;
        if (!(Request.QueryString["LangType"] == null))
        {
            if (Request.QueryString["LangType"] != "")
            {
                if (Request.QueryString["LangType"] != null) Int32.TryParse(Request.QueryString["LangType"], out ContentLanguage);

                if (ContentLanguage != lastValidLanguageID)
                {
                    m_bLangChange = true;
                }
                m_refContentApi.SetCookieValue("LastValidLanguageID", ContentLanguage.ToString());
            }
            else
            {
                if (lastValidLanguageID != Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED)
                {
                    ContentLanguage = lastValidLanguageID;
                }
            }
        }
        else
        {
            if (lastValidLanguageID != Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED)
            {
                ContentLanguage = lastValidLanguageID;
            }
        }

        if (ContentLanguage == Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED)
        {
            m_refContentApi.ContentLanguage = Ektron.Cms.Common.EkConstants.ALL_CONTENT_LANGUAGES;
        }
        else
        {
            m_refContentApi.ContentLanguage = ContentLanguage;
        }
        StyleHelper styleHelper = new StyleHelper();
        ltrStyleSheetJs.Text = styleHelper.GetClientScript();
        txtContentLanguage.Text = m_refContentApi.ContentLanguage.ToString();
        txtDefaultContentLanguage.Text = m_refContentApi.DefaultContentLanguage.ToString();
        txtEnableMultilingual.Text = m_refContentApi.EnableMultilingual.ToString();

        switch (PageAction)
        {
            case "viewarchivecontentbycategory":
            case "viewcontentbycategory":
                UniqueLiteral.Text = "viewfolder";
                m_viewfolder = (viewfolder)(LoadControl("controls/folder/viewfolder.ascx"));
                m_viewfolder.ID = "viewfolder";
                if (m_bLangChange == true)
                {
                    m_viewfolder.ResetPostData();
                }
                DataHolder.Controls.Add(m_viewfolder);
                break;
            case "deletecontentbycategory":
                UniqueLiteral.Text = "deletecontentbycategory";
                removefolderitem m_removefolderitem;
                m_removefolderitem = (removefolderitem)(LoadControl("controls/folder/removefolderitem.ascx"));
                m_removefolderitem.ID = "deletecontentbycategory";
                DataHolder.Controls.Add(m_removefolderitem);
                break;
            case "movecontentbycategory":
                UniqueLiteral.Text = "movefolderitem";
                movefolderitem m_movefolderitem;
                m_movefolderitem = (movefolderitem)(LoadControl("controls/folder/movefolderitem.ascx"));
                m_movefolderitem.ID = "movefolderitem";
                DataHolder.Controls.Add(m_movefolderitem);
                break;
            case "selectpermissions":
                UniqueLiteral.Text = "permission";
                selectpermissions m_selectpermissions;
                m_selectpermissions = (selectpermissions)(LoadControl("controls/permission/selectpermissions.ascx"));
                m_selectpermissions.ID = "permission";
                DataHolder.Controls.Add(m_selectpermissions);
                break;
        }
        EmailHelper m_mail = new EmailHelper();

        string strEmailArea;
        strEmailArea = m_mail.EmailJS();
        strEmailArea += m_mail.MakeEmailArea();
        ltrEmailAreaJs.Text = strEmailArea;

        if (PageAction.ToLower().ToString() != "viewcontentbycategory")
        {
            ShowDropUploader(false);
        }

        // resource text string tokens
        string closeDialogText = m_refMsg.GetMessage("close this dialog");
        string cancelText = m_refMsg.GetMessage("btn cancel");

        // assign resource text string values
        btnConfirmOk.Text = m_refMsg.GetMessage("lbl ok");
        btnConfirmOk.NavigateUrl = "#" + m_refMsg.GetMessage("lbl ok");
        btnConfirmCancel.Text = cancelText;
        btnConfirmCancel.NavigateUrl = "#" + cancelText;
        btnCloseSyncStatus.Text = m_refMsg.GetMessage("close title");
        btnCloseSyncStatus.NavigateUrl = "#" + m_refMsg.GetMessage("close title");
        btnStartSync.Text = m_refMsg.GetMessage("btn sync now");
        btnCloseConfigDialog.Text = m_refMsg.GetMessage("close title");
        closeDialogLink.Text = "<span class=\"ui-icon ui-icon-closethick\">" + m_refMsg.GetMessage("close title") + "</span>";
        closeDialogLink.NavigateUrl = "#" + System.Text.RegularExpressions.Regex.Replace(m_refMsg.GetMessage("close title"), "\\s+", "");
        closeDialogLink.ToolTip = closeDialogText;
        closeDialogLink2.Text = closeDialogLink.Text;
        closeDialogLink2.NavigateUrl = closeDialogLink.NavigateUrl;
        closeDialogLink2.ToolTip = closeDialogText;
        closeDialogLink3.Text = closeDialogLink.Text;
        closeDialogLink3.NavigateUrl = closeDialogLink.NavigateUrl;
        closeDialogLink3.ToolTip = closeDialogText;
        lblSyncStatus.Text = string.Format(m_refMsg.GetMessage("lbl sync status"), " <span class=\"statusHeaderProfileId\"></span>");
        m_jsResources = (SyncResources)(LoadControl("sync/SyncResources.ascx"));
        m_jsResources.ID = "jsResources";
        sync_jsResourcesPlaceholder.Controls.Add(m_jsResources);
    }
Beispiel #44
0
        // PUT: api/TravelFinance/5
        // for restButtonID 0 = Approve Advance 1 = Approve Recap (closes auth form) 2 = Deny Advance 3 = Deny Recap
        public void Put([FromUri] string restUserID, [FromUri] string restButtonID, [FromBody] TravelAuthForm travelAuthForm)
        {
            log.WriteLogEntry("Begin TravelFinanceController PUT...");
            if (int.TryParse(restUserID, out int userID))
            {
                if (int.TryParse(restButtonID, out int buttonID))
                {
                    log.WriteLogEntry("Starting LoginHelper...");
                    LoginHelper loginHelp = new LoginHelper();
                    if (loginHelp.LoadUserSession(userID))
                    {
                        DomainUser user = new DomainUser();
                        log.WriteLogEntry("Starting UserHelper...");
                        UserHelper userHelp = new UserHelper(user);
                        if (userHelp.LoadDomainUser(userID))
                        {
                            try
                            {
                                if (travelAuthForm.GetType() == typeof(TravelAuthForm))
                                {
                                    log.DumpObject(travelAuthForm);
                                    log.WriteLogEntry("Starting FormHelper...");
                                    FormHelper travelFormHelp = new FormHelper();
                                    if (travelFormHelp.HandleFinanceAction(buttonID, travelAuthForm))
                                    {
                                        log.WriteLogEntry("Starting EmailHelper...");
                                        EmailHelper email = new EmailHelper();
                                        switch (buttonID)
                                        {
                                        case 0:
                                        {
                                            email.NotifySubmitter(travelAuthForm.Email, Constants.NotificationTravelAdvance);
                                            break;
                                        }

                                        case 1:
                                        {
                                            email.NotifySubmitter(travelAuthForm.Email, Constants.NotificationTravelRecap);
                                            break;
                                        }

                                        case 2:
                                        {
                                            string message = string.Format("{0}{1}{2}{3}{4}", travelAuthForm.EventTitle, Environment.NewLine, travelAuthForm.Location, Environment.NewLine, travelAuthForm.MailMessage);
                                            email.NotifySubmitter(travelAuthForm.Email, message);
                                            break;
                                        }

                                        case 3:
                                        {
                                            string message = string.Format("{0}{1}{2}{3}{4}", travelAuthForm.EventTitle, Environment.NewLine, travelAuthForm.Location, Environment.NewLine, travelAuthForm.MailMessage);
                                            email.NotifySubmitter(travelAuthForm.Email, message);
                                            break;
                                        }

                                        default:
                                        {
                                            log.WriteLogEntry("Fell through button ID switch. No email sent.");
                                            break;
                                        }
                                        }
                                    }
                                }
                                else
                                {
                                    log.WriteLogEntry("FAILED submitted form is the wrong type!");
                                }
                            }
                            catch (Exception ex)
                            {
                                log.WriteLogEntry("FAILED to submit travel authorization form! " + ex.Message);
                            }
                        }
                        else
                        {
                            log.WriteLogEntry("FAILED to load current user data!");
                        }
                    }
                    else
                    {
                        log.WriteLogEntry("FAILED to load active user session!");
                    }
                }
                else
                {
                    log.WriteLogEntry("FAILED invalid button id!");
                }
            }
            else
            {
                log.WriteLogEntry("FAILED invalid user id!");
            }
            log.WriteLogEntry("End TravelFinanceController PUT.");
        }
Beispiel #45
0
    private void Page_Load(System.Object sender, System.EventArgs e)
    {
        string action = "view";
        string inFolder = "";
        int k = 0;
        string[] id = null;
        string folderList = "";
        string folderId = "";
        long rootFolder = 0;
        string userNames = "None";
        string groupNames = "None";
        string userIdList = "";
        string groupIdList = "";
        string[] userId = null;
        string[] groupId = null;
        string userList = "";
        Ektron.Cms.UserAPI userAPI = new Ektron.Cms.UserAPI();
        int i = 0;
        bool doesExcludeAll = false;
        bool isSubmit = true;
        CommonApi commonApi = new CommonApi();
        bool continueSub = false;

        if ((_ContentApi.EkContentRef).IsAllowed(0, 0, "users", "IsLoggedIn", 0) == false)
        {
            Response.Redirect("login.aspx?fromLnkPg=1", false);
            return;
        }
        if (_ContentApi.RequestInformationRef.IsMembershipUser == 1 || _ContentApi.RequestInformationRef.UserId == 0)
        {
            Response.Redirect("reterror.aspx?info=Please login as cms user", false);
            return;
        }
        //set language
        _ContentLanguage = string.IsNullOrEmpty(Request.QueryString["LangType"]) ? Convert.ToInt32(_ContentApi.GetCookieValue("LastValidLanguageID")) : Convert.ToInt32(Request.QueryString["LangType"]);

        _ContentApi.SetCookieValue("LastValidLanguageID", _ContentLanguage.ToString());
        _ContentApi.ContentLanguage = System.Convert.ToInt32(_ContentLanguage == Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED ? Ektron.Cms.Common.EkConstants.ALL_CONTENT_LANGUAGES : _ContentLanguage);
        _EnableMultilingual = _ContentApi.EnableMultilingual;

        //set filter
        _FilterType = (string)((string.IsNullOrEmpty(Request.QueryString["filterType"])) ? string.Empty : (AntiXss.HtmlEncode(Request.QueryString["filtertype"])));
        if (!string.IsNullOrEmpty(Request.QueryString["filterid"]) )
        {
            folderId = Request.QueryString["filterid"];
            if (!folderId.Contains(","))
            {
                if (Request.QueryString["filterid"] != null)
                { _FilterId = long.Parse(Request.QueryString["filterid"]); }
            }
            if (_FilterType == "path")
            {
                id = folderId.Split(',');
                for (k = 0; k <= id.Length - 1; k++)
                {
                    if (!string.IsNullOrEmpty(_FolderName))
                    {
                        if (_FolderName.Length > 0)
                        {
                            _FolderName = _FolderName + ",";
                        }
                    }
                    _FolderName = _FolderName + _ContentApi.GetFolderById(long.Parse(id[k])).Name;
                    _FilterId = long.Parse(id[k]);
                    // Set limit for listing folder-names:
                    if ((k >= 0) && (k < (id.Length - 1)))
                    {
                        _FolderName += ", ...";
                        break;
                    }
                }
                //FldrName = m_refContentApi.GetFolderById(FilterId).Name & """"
                _FolderName += "\"";
                inFolder = " In Folder \"";
            }
        }

        //set page action - throw if contains ampersand
        _PageAction = (string)((string.IsNullOrEmpty(Request.QueryString["action"])) ? string.Empty : (EkFunctions.HtmlEncode(Convert.ToString(Request.QueryString["action"])).ToLower().Trim()));
        if (_PageAction.Contains("&"))
        {
            Utilities.ShowError(_MessageHelper.GetMessage("invalid querstring"));
            return;
        }
        _PageAction = AntiXss.HtmlEncode(_PageAction);
        //get querystrings
        _AppImgPath = _ContentApi.AppImgPath;
        _Interval = (string)((string.IsNullOrEmpty(Request.QueryString["interval"])) ? string.Empty : (AntiXss.HtmlEncode(Request.QueryString["interval"])));
        _OrderBy = (string)((string.IsNullOrEmpty(Request.QueryString["orderby"])) ? string.Empty : (AntiXss.HtmlEncode(Request.QueryString["orderby"])));

        if (!string.IsNullOrEmpty(Request.QueryString["rootfolder"]))
        {
            rootFolder = long.Parse(Request.QueryString["rootfolder"]);
        }
        if (!string.IsNullOrEmpty(Request.QueryString["subfldInclude"]))
        {
            _IsSubFolderIncluded = bool.Parse(Request.QueryString["subfldInclude"]);
        }
        if ((Request.QueryString["rptFolder"] == null) || (Request.QueryString["rptFolder"] == ""))
        {
            _Folder = " Content Folder ";
        }
        else if (!(Request.QueryString["filterType"] == null) && Request.QueryString["filterType"] != "")
        {
            id = (EkFunctions.HtmlEncode(Request.QueryString["filterid"])).Split(',');
            for (k = 0; k <= id.Length - 1; k++)
            {
                if (_Folder.Length > 0)
                {
                    _Folder = _Folder + ",";
                }
                _Folder = _Folder + _ContentApi.GetFolderById(long.Parse(id[k])).Name;
            }
        }
        else
        {
            _Folder = EkFunctions.HtmlEncode(Request.QueryString["rptFolder"]);
        }
        if (Request.QueryString[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam] != "")
        {
            if (Information.IsNumeric(Request.QueryString[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam]))
            {
                _ContentType = Convert.ToInt32(Request.QueryString[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam]);
                _ContentTypeSelected = Request.QueryString[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam].ToString();
                _ContentApi.SetCookieValue(Ektron.Cms.Common.EkConstants.ContentTypeUrlParam, _ContentTypeSelected);
            }
        }
        else if (Ektron.Cms.CommonApi.GetEcmCookie()[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam] != "")
        {
            if (Information.IsNumeric(Ektron.Cms.CommonApi.GetEcmCookie()[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam]))
            {
                _ContentTypeSelected = (Ektron.Cms.CommonApi.GetEcmCookie()[Ektron.Cms.Common.EkConstants.ContentTypeUrlParam]).ToString();
            }
        }

        switch (_PageAction)
        {
            case "checkinall":
                Process_CheckInAll();
                break;
            case "submitall":
                Process_SubmitAll();
                break;
            case "viewallreporttypes":
                Display_ReportTypes();
                break;
            case "viewasynchlogfile":
                Display_AsynchLogFile();
                break;
            case "contentreviews":
                Display_ContentReviews();
                break;
            case "contentflags":
                Display_ContentFlags();
                break;
            case "viewsearchphrasereport":
                SearchPhraseReport();
                break;
            case "viewpreapproval":
                Display_Preapproval();
                break;
            case "viewcheckedout":
                continueSub = true;
                _ReportType = "checkedout";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports checked out title") + inFolder + _FolderName);
                break;
            case "viewcheckedin":
                //look at last line in page_load for loading of viewcheckedin control
                continueSub = true;
                _ReportType = "checkedin";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports checked in title") + inFolder + _FolderName);
                break;
            case "viewsubmitted":
                continueSub = true;
                _ReportType = "submitted";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports submitted title") + inFolder + _FolderName);
                break;
            case "viewnewcontent":
                continueSub = true;
                _ReportType = "newcontent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports new title") + inFolder + _FolderName);
                break;
            case "viewpending":
                continueSub = true;
                _ReportType = "pendingcontent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports pending title") + inFolder + _FolderName);
                break;
            case "viewrefreshreport":
                continueSub = true;
                _ReportType = "refreshdcontent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports refresh title") + inFolder + _FolderName);
                break;
            case "viewexpired":
                continueSub = true;
                _ReportType = "expiredcontent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports expired title") + inFolder + _FolderName);
                break;
            case "viewtoexpire":
                continueSub = true;
                _ReportType = "expireToContent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("lbl cont expire") + "&nbsp;" + _Interval + "&nbsp;" + _MessageHelper.GetMessage("lbl sync monthly days") + inFolder + _FolderName);
                break;
            case "siteupdateactivity":
                continueSub = true;
                _ReportType = "updateactivityContent";
                _HasData = true;
                _TitleBarMsg = (string)(_MessageHelper.GetMessage("content reports site activity title") + inFolder + _FolderName);
                break;
            default:
                continueSub = true;
                _ReportType = "";
                _HasData = false;
                _TitleBarMsg = "";
                break;
        }

        //set js vars
        litPageAction.Text = _PageAction;
        litOrderBy.Text = _OrderBy;
        litFilterType.Text = _FilterType;
        litFilterId.Text = _FilterId.ToString();
        litInterval.Text = _Interval;

        if (continueSub == true)
        {
            int j;
            Collection pagedata = null;
            Collection cUser = null;
            long[] arUserIds;
            string sExclUserId = "";
            int idx = 0;

            //Dim sitedata As ContentData()
            if ((_PageAction == "viewcheckedout") || (_PageAction == "viewnewcontent"))
            {
                lblAction.Text = "var actionString = \"reports.aspx?action=CheckinAll&PreviousAction=" + _PageAction + "&filtertype=" + _FilterType + "&filterid=" + _FilterId + "&orderby=" + _OrderBy + "\";";
                lblAction.Text += "if (WarnAllCheckin()) { DisplayHoldMsg_Local(true); document.forms.selections.action = actionString; document.forms.selections.submit(); }";
            }
            if (_PageAction == "viewcheckedin")
            {
                lblAction.Text += "var actionString = \"reports.aspx?action=SubmitAll&PreviousAction=" + _PageAction + "&filtertype=" + _FilterType + "&filterid=" + _FilterId + "&orderby=" + _OrderBy + "\";";
                lblAction.Text += "if (WarnAllSubmit()) { DisplayHoldMsg_Local(true); document.forms.selections.action = actionString; document.forms.selections.submit(); }";
            }

            rptTitle.Value = _TitleBarMsg;
            top.Visible = false;

            if (_PageAction == "viewtoexpire")
            {
                selInterval.Visible = true;
                txtInterval.Visible = true;

                if (0 != _Interval.Length)
                {
                    txtInterval.Value = _Interval;
                }

                selInterval.Items.Clear();
                selInterval.Items.Add(new ListItem("Select Interval", ""));
                selInterval.Items.Add(new ListItem("10", "10"));
                selInterval.Items.Add(new ListItem("20", "20"));
                selInterval.Items.Add(new ListItem("30", "30"));
                selInterval.Items.Add(new ListItem("40", "40"));
                selInterval.Items.Add(new ListItem("50", "50"));
                selInterval.Items.Add(new ListItem("60", "60"));
                selInterval.Items.Add(new ListItem("70", "70"));
                selInterval.Items.Add(new ListItem("80", "80"));
                selInterval.Items.Add(new ListItem("90", "90"));

                if (0 != _Interval.Length)
                {
                    for (j = 1; j <= 9; j++)
                    {
                        if (_Interval == selInterval.Items[j].Value)
                        {
                            selInterval.Items[j].Selected = true;
                            break;
                        }
                    }
                }
                else
                {
                    selInterval.Items[0].Selected = true;
                }

                lblDays.Text = _MessageHelper.GetMessage("lbl sync monthly days");
                lblDays.Visible = true;
                top.Visible = true;
                IncludeContentToExpireJS();
            }
            else if (_PageAction == "siteupdateactivity")
            {
                System.Text.StringBuilder result = new System.Text.StringBuilder();
                EditScheduleHtml.Text = "";
                if (!(Request.QueryString["ex_users"] == null))
                {
                    if (Request.QueryString["ex_users"] != "")
                    {
                        userIdList = EkFunctions.HtmlEncode(Request.QueryString["ex_users"]);
                    }
                }
                if (!(Request.QueryString["ex_groups"] == null))
                {
                    if (Request.QueryString["ex_groups"] != "")
                    {
                        groupIdList = EkFunctions.HtmlEncode(Request.QueryString["ex_groups"]);
                    }
                }
                if (Request.QueryString["btnSubmit"] == null)
                {
                    isSubmit = false;
                    editSchedule.Visible = true;
                    lblDays.Visible = true;
                    tr_startDate.Visible = true;
                    tr_endDate.Visible = true;
                    lblStartDate.Text = _MessageHelper.GetMessage("generic start date label");
                    lblEndDate.Text = _MessageHelper.GetMessage("generic end date label");
                }
                else
                {
                    // User wants Site Activity report
                    isSubmit = true;
                    if (!(Request.Form["excludeAllUsers"] == null))
                    {
                        doesExcludeAll = Convert.ToBoolean(Request.Form["excludeAllUsers"]);
                    }
                    if (!(Request.Form["start_date"] == null))
                    {
                        _StartDate = Request.Form["start_date"];
                    }
                    else if (!(Request.QueryString["startdate"] == null))
                    {
                        _StartDate = EkFunctions.HtmlEncode(Request.QueryString["startdate"]);
                        _StartDate = _StartDate.Replace("\'", "");
                    }
                    if (!(Request.Form["end_date"] == null))
                    {
                        _EndDate = Request.Form["end_date"];
                        if (!Information.IsDate(_EndDate))
                        {
                            _EndDate = "";
                        }
                    }
                    else if (!(Request.QueryString["enddate"] == null))
                    {
                        _EndDate = EkFunctions.HtmlEncode(Request.QueryString["enddate"]);
                        _EndDate = _EndDate.Replace("\'", "");
                        if (!Information.IsDate(_EndDate))
                        {
                            _EndDate = "";
                        }
                    }
                }
                DisplayDateFields();

                //EditScheduleHtml.Text = EditScheduleHtml.Text & MakeIFrameArea()
                result.Append("<input id=\"fId\" type=\"hidden\" name=\"fId\" ");
                if (Request.QueryString["filterid"] == null)
                {
                    result.Append("value=\"\">" + "\r\n");
                }
                else
                {
                    result.Append("value=\"" + EkFunctions.HtmlEncode(Request.QueryString["filterid"]) + "\"/>" + "\r\n");
                }
                result.Append("<input id=\"rptType\" type=\"hidden\" name=\"rptType\"/>" + "\r\n");
                result.Append("<input id=\"rptFolderList\" type=\"hidden\" name=\"rptFolderList\"/>" + "\r\n");
                result.Append("<input id=\"rootFolder\" type=\"hidden\" name=\"rootFolder\" value=\"" + rootFolder + "\"/>" + "\r\n");
                result.Append("<input id=\"rptLink\" type=\"hidden\" name=\"rptLink\"/>" + "\r\n");
                result.Append("<input id=\"ContType\" type=\"hidden\" name=\"ContType\" value=\"" + _ContentType + "\"/>" + "\r\n");
                result.Append("<input id=\"subfldInclude\" type=\"hidden\" name=\"subfldInclude\" value=\"" + _IsSubFolderIncluded + "\"/>" + "\r\n");
                result.Append("<input id=\"LangType\" type=\"hidden\" name=\"LangType\" value=\"" + _ContentLanguage + "\"/>" + "\r\n");
                result.Append("<input id=\"excludeUserIds\" type=\"hidden\" name=\"excludeUserIds\" value=\"" + userIdList + "\"/>" + "\r\n");
                result.Append("<input id=\"excludeUserGroups\" type=\"hidden\" name=\"excludeUserGroups\" value=\"" + groupIdList + "\"/>" + "\r\n");
                result.Append("<input id=\"excludeAllUsers\" type=\"hidden\" name=\"excludeAllUsers\" value=\"" + doesExcludeAll + "\"/>" + "\r\n");
                //select folder
                result.Append("<table id=\"EditText\" width=\"100%\" class=\"ektronGrid\">");
                result.Append("<tr><td id=\"lblSelFolder\" class=\"label\">" + _MessageHelper.GetMessage("lbl select folder") + "</td>");
                result.Append("<td id=\"selectedFolderList\"><a title=\"" + _MessageHelper.GetMessage("lbl select folder") + "\" href=\"#\" id=\"hselFolder\" onclick=\"LoadFolderChildPage(\'" + _PageAction + "\',\'" + _ContentLanguage + "\');return true;\">");
                if ((Request.QueryString["filterid"] == null) || ("" == Request.QueryString["filterid"]))
                {
                    //result.Append(m_refMsg.GetMessage("lbl Root Folder"))
                    result.Append("\\");
                }
                else
                {
                    id = (EkFunctions.HtmlEncode(Request.QueryString["filterid"])).Split(',');
                    for (k = 0; k <= id.Length - 1; k++)
                    {
                        if (folderList.Length > 0)
                        {
                            folderList = folderList + ",";
                        }
                        folderList = folderList + _ContentApi.GetFolderById(long.Parse(id[k])).Name;
                    }
                    result.Append(folderList);
                }
                result.Append("</a></td></tr>" + "\r\n");
                string sShow = "display:none";
                if (_IsSubFolderIncluded)
                {
                    sShow = "display:block";
                }
                result.Append("<tr><td id=\"subfldIncludetxt\" colspan=\"2\" style=\"" + sShow + "\">");
                result.Append(_MessageHelper.GetMessage("lbl subfolder included"));
                result.Append("</td></tr>" + "\r\n");
                //report type
                _ReportDisplay = EkFunctions.HtmlEncode(Request.QueryString["report_display"]);
                result.Append("<tr><td class=\"label\">" + _MessageHelper.GetMessage("lbl report type") + "</td><td><select id=\"selDisplay\" name=\"selDisplay\">");
                result.Append("<option id=\"ev\" value=\"ev\"");
                if ("ev" == _ReportDisplay)
                {
                    result.Append(" SELECTED");
                }
                result.Append(">" + _MessageHelper.GetMessage("lbl executive view") + "</option>");
                result.Append("<option id=\"dv\" value=\"dv\"");
                if ("dv" == _ReportDisplay)
                {
                    result.Append(" selected=\'selected\'");
                }
                result.Append(">" + _MessageHelper.GetMessage("lbl detail view") + "</option>");
                result.Append("<option id=\"cv\" value=\"cv\"");
                if ("cv" == _ReportDisplay)
                {
                    result.Append(" selected=\'selected\'");
                }
                result.Append(">" + _MessageHelper.GetMessage("lbl combined view") + "</option></select></td></tr>" + "\r\n");
                //exclude user
                result.Append("<tr><td id=\"lblSelUser\" class=\"label\">" + _MessageHelper.GetMessage("lbl exclude users") + "</td>" + "\r\n");
                result.Append("<td>");
                result.Append("<div id=\"excludeUserList\">");
                if (userIdList.Length > 0 || groupIdList.Length > 0)
                {
                    if (userIdList.Length > 0)
                    {
                        userNames = "";
                        userId = userIdList.Split(",".ToCharArray());
                        for (i = 0; i <= userId.Length - 1; i++)
                        {
                            if (userNames.Length > 0)
                            {
                                userNames = userNames + ",";
                            }
                            userNames = userNames + userAPI.UserObject(int.Parse(userId[i])).Username;
                        }
                        if (userNames.Length == 0)
                        {
                            userNames = "None";
                        }
                    }
                    if (groupIdList.Length > 0)
                    {
                        groupNames = "";
                        groupId = groupIdList.Split(",".ToCharArray());
                        for (i = 0; i <= groupId.Length - 1; i++)
                        {
                            if (groupNames.Length > 0)
                            {
                                groupNames = groupNames + ",";
                            }
                            groupNames = groupNames + _ContentApi.EkUserRef.GetActiveUserGroupbyID(Convert.ToInt64(groupId[i])).GroupName;
                            if (groupNames.Length == 0)
                            {
                                groupNames = "None";
                            }
                        }
                    }
                    userList = "User (" + userNames.Replace(",", ", ") + ")<br />User Group (" + groupNames.Replace(",", ", ") + ")";
                    result.Append(userList);
                }
                result.Append("</div>");
                result.Append("<ul class=\'buttonWrapper buttonWrapperLeft\'><li><a title=\"" + _MessageHelper.GetMessage("lbl Select User or Group") + "\" class=\"button buttonInlineBlock greenHover buttonCheckAll\" href=\"javascript://\" id=\"selExclUser\" onclick=\"LoadUserListChildPage(\'" + _PageAction + "_siteRpt\');return true;\">");
                result.Append(_MessageHelper.GetMessage("lbl Select User or Group"));
                result.Append("</a></li></ul></td></tr>" + "\r\n");
                //generate report button
                result.Append("<tr><td class=\'label\'>&nbsp;</td><td><ul class=\'buttonWrapper buttonWrapperLeft\'><li><a class=\"button buttonInlineBlock greenHover buttonGetResult\" id=\"btnResult\" onclick=\"ReportSiteUpdateActivity()\" title=\"" + _MessageHelper.GetMessage("btn get result") + "\">" + _MessageHelper.GetMessage("btn get result") + "</a></li></ul></td></tr>" + "\r\n");
                result.Append("</table>");
                EditScheduleHtml.Text = EditScheduleHtml.Text + result.ToString();

                IncludeSiteUpdateActivityJS();
            }

            _AssetInfoData = _ContentApi.GetAssetSupertypes();
            if (Ektron.Cms.Common.EkConstants.CMSContentType_Content == Convert.ToInt32(_ContentTypeSelected) || Ektron.Cms.Common.EkConstants.CMSContentType_Archive_Content == Convert.ToInt32(_ContentTypeSelected) || Ektron.Cms.Common.EkConstants.CMSContentType_Forms == Convert.ToInt32(_ContentTypeSelected) || Ektron.Cms.Common.EkConstants.CMSContentType_Library == Convert.ToInt32(_ContentTypeSelected) || Ektron.Cms.Common.EkConstants.CMSContentType_NonImageLibrary == Convert.ToInt32(_ContentTypeSelected) || Ektron.Cms.Common.EkConstants.CMSContentType_PDF == Convert.ToInt32(_ContentTypeSelected))
            {
                _ContentType2 = int.Parse(_ContentTypeSelected);
            }
            else if (Ektron.Cms.Common.EkConstants.ManagedAsset_Min <= Convert.ToInt32(_ContentTypeSelected) && Convert.ToInt32(_ContentTypeSelected) <= Ektron.Cms.Common.EkConstants.ManagedAsset_Max)
            {
                if (DoesAssetSupertypeExist(_AssetInfoData, int.Parse(_ContentTypeSelected)))
                {
                    _ContentType2 = int.Parse(_ContentTypeSelected);
                }
            }

            if (_HasData)
            {
                if (("viewrefreshreport" == _PageAction | "refreshdcontent" == _PageAction | "viewpending" == _PageAction | "viewcheckedin" == _PageAction) && !_ContentApi.EkContentRef.IsAllowed(_ContentApi.RequestInformationRef.UserId, 0, "users", "IsAdmin"))
                {
                    _FilterType = "User";
                    _FilterId = _ContentApi.RequestInformationRef.UserId;
                }
                cUser = new Collection();
                pagedata = new Collection();
                pagedata.Add(_ReportType, "StateWanted", null, null);
                pagedata.Add(_FilterType, "FilterType", null, null);
                pagedata.Add(_FilterId, "FilterID", null, null);
                pagedata.Add(_OrderBy, "OrderBy", null, null);
                pagedata.Add(_Interval, "Interval", null, null);
                if (_ContentType2 > 0)
                {
                    pagedata.Add(_ContentType2, "ContentType", null, null);
                }

                if (_PageAction == "viewtoexpire")
                {
                    _ReportData = _ContentApi.GetExpireContent(pagedata);
                }
                else if ("siteupdateactivity" == _PageAction)
                {
                    pagedata.Add(_StartDate, "StartDate", null, null);
                    pagedata.Add(_EndDate, "EndDate", null, null);
                    pagedata.Add(_IsSubFolderIncluded, "SubFolders", null, null);
                    pagedata.Add(folderId, "FolderId", null, null);
                    pagedata.Add(rootFolder, "RootFolder", null, null);

                    if (groupIdList.Length > 0)
                    {
                        string[] temp = groupIdList.Split(",".ToCharArray());
                        long[] arrIdList = new long[temp.Length - 1 + 1];
                        int index;
                        for (index = 0; index <= temp.Length - 1; index++)
                        {
                            arrIdList[index] = Convert.ToInt64(temp[index]);
                        }
                        arUserIds = _ContentApi.EkUserRef.GetAllUsersIdsByGroup(arrIdList, "userid");
                        if (arUserIds.Length > 0)
                        {
                            for (idx = 0; idx <= arUserIds.Length - 1; idx++)
                            {
                                if (sExclUserId.Length > 0)
                                {
                                    sExclUserId = sExclUserId + ",";
                                }
                                sExclUserId = sExclUserId + arUserIds[idx].ToString(); //("UserID")
                            }
                        }
                    }
                    if (userIdList.Length > 0)
                    {
                        if (sExclUserId.Length > 0)
                        {
                            sExclUserId = sExclUserId + ",";
                        }
                        sExclUserId = sExclUserId + userIdList;
                    }
                    if (0 == sExclUserId.Length)
                    {
                        sExclUserId = "EktNone";
                    }
                    pagedata.Add(sExclUserId, "ExUserIds", null, null);
                    pagedata.Add(doesExcludeAll, "ExAllUsers", null, null);
                }
                else
                {
                    //_ReportData = _ContentApi.GetContentReport(pagedata)
                    _PageInfo.RecordsPerPage = _ContentApi.RequestInformationRef.PagingSize;
                    _PageInfo.CurrentPage = System.Convert.ToInt32(this.uxPaging.SelectedPage + 1);
                    try
                    {
                        _ReportData = _ContentApi.GetContentReport(pagedata, _PageInfo);
                    }
                    catch
                    {
                        Response.Redirect("reports.aspx?action=ViewPending");
                    }
                    if (_ReportData != null && _PageInfo.TotalPages > 1)
                    {
                        this.uxPaging.Visible = true;
                        this.uxPaging.TotalPages = _PageInfo.TotalPages;
                        this.uxPaging.CurrentPageIndex = _PageInfo.CurrentPage - 1;
                    }
                    else
                    {
                        this.uxPaging.Visible = false;
                    }
                }
            }

            reportstoolbar m_reportsToolBar;
            System.Web.UI.WebControls.BoundColumn colBound = new System.Web.UI.WebControls.BoundColumn();

            DataTable dt = new DataTable();
            DataRow dr;
            bool bIsChart = false;
            m_reportsToolBar = (reportstoolbar)(LoadControl("controls/reports/reportstoolbar.ascx"));
            ToolBarHolder.Controls.Add(m_reportsToolBar);
            m_reportsToolBar.AppImgPath = _AppImgPath;
            if (_ReportType.ToLower() == "updateactivitycontent")
            {
                m_reportsToolBar.Data = "";
            }
            else
            {
                m_reportsToolBar.Data = _ReportData;
            }
            m_reportsToolBar.PageAction = _PageAction;
            m_reportsToolBar.FilterType = _FilterType;
            m_reportsToolBar.TitleBarMsg = _TitleBarMsg;
            m_reportsToolBar.MultilingualEnabled = _EnableMultilingual;
            m_reportsToolBar.ContentLang = _ContentApi.ContentLanguage;
            m_reportsToolBar.HasData = isSubmit;

            //DATA DISPLAY
            // Grid is different for the activity report
            if (_ReportType.ToLower() != "updateactivitycontent")
            {
                chart.Visible = false;
                lblTbl.Visible = false;

                colBound.DataField = "TITLE";
                if ((_PageAction == "viewcheckedout") || (_PageAction == "viewcheckedin")){
                    colBound.HeaderText = "<input type=\"checkbox\" name=\"all\" onclick=\"javascript:checkAll(this);\"> ";
                }
                colBound.HeaderText += _MessageHelper.GetMessage("generic Title");
                colBound.ItemStyle.Wrap = false;
                colBound.ItemStyle.VerticalAlign = VerticalAlign.Top;
                colBound.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                colBound.HeaderStyle.CssClass = "title-header";
                dgReport.Columns.Add(colBound);

                colBound = new System.Web.UI.WebControls.BoundColumn();
                colBound.DataField = "ID";
                colBound.HeaderText = _MessageHelper.GetMessage("generic ID");
                colBound.ItemStyle.VerticalAlign = VerticalAlign.Top;
                colBound.HeaderStyle.CssClass = "title-header";
                colBound.ItemStyle.Wrap = false;
                dgReport.Columns.Add(colBound);

                colBound = new System.Web.UI.WebControls.BoundColumn();
                colBound.DataField = "LASTEDITOR";
                colBound.HeaderText = _MessageHelper.GetMessage("generic Last Editor");
                colBound.HeaderStyle.CssClass = "title-header";
                colBound.ItemStyle.Wrap = false;
                colBound.ItemStyle.VerticalAlign = VerticalAlign.Top;
                colBound.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                dgReport.Columns.Add(colBound);

                string msg = "";
                if (_PageAction == "viewpending")
                {
                    msg = _MessageHelper.GetMessage("generic Go Live");
                }
                else if (_PageAction == "viewexpired")
                {
                    msg = _MessageHelper.GetMessage("generic End Date");
                }
                else if (_PageAction == "viewtoexpire")
                {
                    msg = _MessageHelper.GetMessage("generic End Date");
                }
                else
                {
                    msg = _MessageHelper.GetMessage("generic Date Modified");
                }
                colBound = new System.Web.UI.WebControls.BoundColumn();
                colBound.DataField = "DATE";
                colBound.HeaderText = msg;
                colBound.ItemStyle.VerticalAlign = VerticalAlign.Top;
                colBound.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                colBound.HeaderStyle.CssClass = "title-header";
                colBound.ItemStyle.Wrap = false;
                dgReport.Columns.Add(colBound);

                colBound = new System.Web.UI.WebControls.BoundColumn();
                colBound.DataField = "PATH";
                colBound.HeaderText = _MessageHelper.GetMessage("generic Path");
                colBound.ItemStyle.VerticalAlign = VerticalAlign.Top;
                colBound.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                colBound.HeaderStyle.CssClass = "title-header";
                colBound.ItemStyle.Wrap = false;
                dgReport.Columns.Add(colBound);

                dgReport.BorderColor = System.Drawing.Color.White;
                string cLinkArray = "";
                string fLinkArray = "";
                string lLinkArray = "";

                dt.Columns.Add(new DataColumn("TITLE", typeof(string)));
                dt.Columns.Add(new DataColumn("ID", typeof(long)));
                dt.Columns.Add(new DataColumn("LASTEDITOR", typeof(string)));
                dt.Columns.Add(new DataColumn("DATE", typeof(string)));
                dt.Columns.Add(new DataColumn("PATH", typeof(string)));
                if (_PageAction == "viewcheckedout")
                {
                    action = "ViewStaged";
                }
                if (!(_ReportData == null))
                {
                    editSchedule.Visible = false;
                    dgReport.Visible = true;

                    for (i = 0; i <= _ReportData.Length - 1; i++)
                    {
                        if ((_PageAction == "viewcheckedout") || (_PageAction == "viewcheckedin"))
                        {
                            top.Visible = true;
                        }
                        dr = dt.NewRow();
                        if ((_PageAction == "viewcheckedout") || (_PageAction == "viewcheckedin"))
                        {
                            dr[0] += "<input type=\"checkbox\" name=\"frm_check" + i + "\" onclick=\"document.forms.selections[\'frm_hidden" + i + "\'].value=(this.checked ?" + _ReportData[i].Id + " : 0);\"> ";
                        }
                        else
                        {
                            dr[0] += "<input type=\"hidden\" name=\"frm_check" + i + "\" onclick=\"document.forms.selections[\'frm_hidden" + i + "\'].value=(this.checked ?" + _ReportData[i].Id + ": 0);\"> ";
                        }
                        if (_ReportData[i].ContType == 1)
                        {
                            if (_ReportData[i].SubType == EkEnumeration.CMSContentSubtype.WebEvent)
                            {
                                dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/calendarViewDay.png" + "></img>&nbsp;";
                            }
                            else
                            {
                                dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/contentHtml.png" + "></img>&nbsp;";
                            }
                        }
                        else if (_ReportData[i].ContType == 2)
                        {
                            dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/contentForm.png" + "></img>&nbsp;";
                        }
                        else if (_ReportData[i].ContType == 3)
                        {
                            dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/contentHTML.png" + "></img>&nbsp;";
                        }
                        else if (_ReportData[i].ContType == 1111)
                        {
                            dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/asteriskOrange.png" + "></img>&nbsp;";
                        }
                        else if (_ReportData[i].ContType == 3333)
                        {
                            dr[0] += "&nbsp;<img id=\"img\" src=" + _ContentApi.AppPath + "images/ui/icons/brick.png" + "></img>&nbsp;";
                        }
                        else
                        {
                            dr[0] += "&nbsp;<img id=\"img\" src=" + _ReportData[i].AssetData.Icon + "></img>&nbsp;";
                        }

                        dr[0] += "<input type=\"hidden\" cid=\"" + _ReportData[i].Id + "\" fid=\"" + _ReportData[i].FolderId + "\" name=\"frm_hidden" + i + "\" value=\"0\"> ";
                        if (_ReportData[i].ContType != 2)
                        {
                            dr[0] += "<a href=\"content.aspx?action=" + action + "&LangType=" + _ReportData[i].LanguageId + "&id=" + _ReportData[i].Id + "&callerpage=" + "reports.aspx" + "&origurl=" + EkFunctions.UrlEncode((string)("action=" + _PageAction + "&filtertype=" + _FilterType + "&filterid=" + _FilterId + "&orderby=" + _OrderBy + "&interval=" + _Interval)) + "\" title=\'" + _MessageHelper.GetMessage("generic View") + " \"" + Strings.Replace(_ReportData[i].Title, "\'", "`", 1, -1, 0) + "\"" + "\'>" + _ReportData[i].Title + "</a>";
                        }
                        else
                        {
                            //Link to cmsforms.aspx
                            dr[0] += "<a href=\"cmsform.aspx?action=ViewForm" + "&LangType=" + _ReportData[i].LanguageId + "&form_id=" + _ReportData[i].Id + "&folder_id=" + _ReportData[i].FolderId + "\" title=\'" + _MessageHelper.GetMessage("generic view") + " \"" + Strings.Replace(_ReportData[i].Title, "\'", "`", 1, -1, 0) + "\"" + "\'>" + _ReportData[i].Title + "</a>";
                        }
                        dr[1] = _ReportData[i].Id;
                        dr[2] = "<a href=\"reports.aspx?action=" + _PageAction + "&interval=" + _Interval + "&filtertype=USER&filterId=" + _ReportData[i].UserId + "&orderby=" + _OrderBy + "\" title=\"" + _MessageHelper.GetMessage("click to filter msg") + "\">" + _ReportData[i].EditorLastName + ", " + _ReportData[i].EditorFirstName + "</a>";
                        string _lnk = MakeLink(_ReportData[i]);
                        if (_lnk != "")
                        {
                            dr[2] = _lnk;
                        }
                        else
                        {
                            dr[2] = "<a href=\"reports.aspx?action=" + _PageAction + "&interval=" + _Interval + "&filtertype=USER&filterId=" + _ReportData[i].UserId + "&orderby=" + _OrderBy + "\" title=\"" + _MessageHelper.GetMessage("click to filter msg") + "\">" + _ReportData[i].EditorLastName + ", " + _ReportData[i].EditorFirstName + "</a>";
                        }
                        if (_PageAction == "viewpending")
                        {
                            dr[3] = _ReportData[i].DisplayGoLive;
                        }
                        else if ((_PageAction == "viewexpired") || (_PageAction == "viewtoexpire"))
                        {
                            dr[3] = _ReportData[i].DisplayEndDate;
                        }
                        else
                        {
                            dr[3] = _ReportData[i].DisplayLastEditDate;
                        }
                        if (_PageAction == "ViewToExpire")
                        {
                            dr[4] = _ReportData[i].Path;
                        }
                        else
                        {
                            dr[4] = "<a href=\"reports.aspx?action=" + _PageAction + "&interval=" + _Interval + "&filtertype=path&filterId=" + _ReportData[i].FolderId + "&orderby=" + _OrderBy + "\" title=\"" + _MessageHelper.GetMessage("click to filter msg") + "\">" + _ReportData[i].Path + "</a>";
                        }
                        cLinkArray = cLinkArray + "," + _ReportData[i].Id;
                        fLinkArray = fLinkArray + "," + _ReportData[i].FolderId;
                        lLinkArray = System.Convert.ToString(lLinkArray + "," + _ReportData[i].LanguageId);
                        dt.Rows.Add(dr);
                    }

                    if (cLinkArray.Length > 0)
                    {
                        cLinkArray = Strings.Right(cLinkArray, Strings.Len(cLinkArray) - 1);
                        fLinkArray = Strings.Right(fLinkArray, Strings.Len(fLinkArray) - 1);
                        lLinkArray = Strings.Right(lLinkArray, Strings.Len(lLinkArray) - 1);
                    }

                    litCollectionList.Text = cLinkArray;
                    litFolderList.Text = fLinkArray;
                    litLanguageList.Text = lLinkArray;

                    _DataView = new DataView(dt);
                    dgReport.DataSource = _DataView;
                    dgReport.DataBind();
                }
                else
                {
                    //Currently there is no data to report. Show such message
                    if (EditScheduleHtml.Text.IndexOf("Currently there is no data") == -1)
                    {
                        System.Text.StringBuilder result = new System.Text.StringBuilder();
                        result.Append("<table>");
                        result.Append("<tr><td>").Append(_MessageHelper.GetMessage("msg no data report")).Append("</td></tr>");
                        result.Append("</table>");
                        EditScheduleHtml.Text = EditScheduleHtml.Text + result.ToString();
                    }
                    editSchedule.Visible = true;
                    dgReport.Visible = false;
                }
            }
            else
            {
                // If it is not a chart and report for site activity
                if ((Request.QueryString["btnSubmit"] == "1") && !bIsChart)
                {
                    chart.Visible = false;
                    lblTbl.Visible = false;

                    _SiteData = _ContentApi.GetSiteActivityReportv2_0(pagedata);
                    if (!(_SiteData == null))
                    {
                        ShowSiteActivity();
                        if (!(Request.QueryString["reporttype"] == null) && "export" == Request.QueryString["reporttype"])
                        {
                            Process_Export();
                        }
                    }
                }
            }
        }
        EmailHelper ehelp = new EmailHelper();
        EmailArea.Text = ehelp.MakeEmailArea();

        switch (this._PageAction.ToLower())
        {
            case "viewcheckedin":
                Display_CheckedIn();
                break;
            case "viewcheckedout":
                Display_CheckedOut();
                break;
            case "viewnewcontent":
                Display_NewContent();
                break;
        }
    }
Beispiel #46
0
    /// <summary>
    /// Sets new UserInfo for approved user.
    /// </summary>
    /// <param name="userID">User to be approved</param>
    protected void SetUserInfo(int userID)
    {
        UserInfo user = UserInfoProvider.GetFullUserInfo(userID);

        // Cancel waiting for approval attribute
        user.UserSettings.UserWaitingForApproval = false;
        // Set activation time to now
        user.UserSettings.UserActivationDate = DateTime.Now;
        // Set user who activated this account
        user.UserSettings.UserActivatedByUserID = MembershipContext.AuthenticatedUser.UserID;
        // Enable user
        user.Enabled = true;

        UserInfoProvider.SetUserInfo(user);

        // Send e-mail to user
        if (!String.IsNullOrEmpty(user.Email))
        {
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("RegistrationUserApproved", SiteContext.CurrentSiteName);
            if (template != null)
            {
                string from = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                if (!String.IsNullOrEmpty(from))
                {
                    EmailMessage email = new EmailMessage();
                    email.EmailFormat = EmailFormatEnum.Default;
                    // Get e-mail sender and subject from template, if used
                    email.From       = from;
                    email.Recipients = user.Email;

                    MacroResolver resolver = MembershipResolvers.GetRegistrationApprovalResolver(user, URLHelper.GetAbsoluteUrl("~/"));

                    // Enable encoding of macro results for HTML mail body
                    resolver.Settings.EncodeResolvedValues = true;
                    email.Body = resolver.ResolveMacros(template.TemplateText);

                    // Disable encoding of macro results for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    string emailSubject = EmailHelper.GetSubject(template, GetString("registrationform.registrationapprovalemailsubject"));
                    email.Subject = resolver.ResolveMacros(emailSubject);

                    email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                    email.CcRecipients  = template.TemplateCc;
                    email.BccRecipients = template.TemplateBcc;

                    try
                    {
                        // Add attachments
                        EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(SiteContext.CurrentSiteName, email);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "WaitingForApprovalEmail");
                    }
                }
                else
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "WaitingForApproval", "EmailSenderNotSpecified");
                }
            }
            else
            {
                // Log missing e-mail template
                try
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationUserApproved", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                catch
                {
                }
            }
        }

        // User is approved and enabled, could be logged into statistics
        AnalyticsHelper.LogRegisteredUser(SiteContext.CurrentSiteName, user);
    }
 public static string VerifyEmail(string email, string name)
 {
     return(EmailHelper.IsValidEmail(email)
         ? email
         : throw new ArgumentException("E-mail address must not be null and must be valid", name));
 }
Beispiel #48
0
        public Return FieldFrontEndFormSubmissionHandler(long fieldId)
        {
            var returnObj = BaseMapper.GenerateReturn("No action performed");

            if (HttpContext.Current.Request.Form["fieldId"] == null)
            {
                returnObj = BaseMapper.GenerateReturn("'fieldId' is missing");
                return(returnObj);
            }

            var field = (MediaDetailField)FieldsMapper.GetByID(fieldId);

            if (field == null)
            {
                returnObj = BaseMapper.GenerateReturn($"Cannot find field with id '{fieldId}'");
                return(returnObj);
            }

            var FormDictionary = new Dictionary <string, string>();

            foreach (string key in HttpContext.Current.Request.Form.Keys)
            {
                var value = HttpContext.Current.Request.Form[key];

                if (value.Contains(","))
                {
                    value = "\"" + value + "\"";
                }

                FormDictionary.Add(key, value);
            }

            FormDictionary.Add("DateSubmitted", StringHelper.FormatDateTime(DateTime.Now));

            var currentEntries = StringHelper.JsonToObject <Newtonsoft.Json.Linq.JArray>(field.FrontEndSubmissions);

            var files     = new Dictionary <string, List <string> >();
            var fileIndex = 0;

            foreach (string key in HttpContext.Current.Request.Files)
            {
                var postedFile = HttpContext.Current.Request.Files[fileIndex];

                var uploadFolder = MediaDetailField.GetUploadFolder(field);

                if (!uploadFolder.Exists)
                {
                    uploadFolder.Create();
                }

                var fieldName = postedFile.FileName.ToLower().Replace(" ", "-");

                var uploadFilePath = uploadFolder.FullName + key + "_" + fieldName;
                postedFile.SaveAs(uploadFilePath);

                var relativePath = URIHelper.ConvertAbsPathToAbsUrl(uploadFilePath);

                if (files.ContainsKey(key))
                {
                    files[key].Add(relativePath);
                }
                else
                {
                    files.Add(key, new List <string>()
                    {
                        relativePath
                    });
                }

                fileIndex++;
            }


            var jObjectUploadFiles = JObject.Parse(StringHelper.ObjectToJson(files));

            var jsonEntry = new JavaScriptSerializer().Serialize(FormDictionary);

            var jObject = JObject.Parse(jsonEntry);

            jObject.Merge(jObjectUploadFiles);

            if (currentEntries == null)
            {
                currentEntries = new JArray();
                currentEntries.Add(jObject);
            }
            else
            {
                currentEntries.Add(jObject);
            }

            field.FrontEndSubmissions = currentEntries.ToString(Formatting.None);

            returnObj = FieldsMapper.Update(field);

            var formFieldSettings = StringHelper.JsonToObject <FormFieldSettings>(field.FieldSettings);

            if (formFieldSettings != null && !string.IsNullOrEmpty(formFieldSettings.EmailTemplateMediaID) && long.TryParse(formFieldSettings.EmailTemplateMediaID, out long i))
            {
                var media = MediasMapper.GetByID(long.Parse(formFieldSettings.EmailTemplateMediaID));

                if (media != null)
                {
                    var layout       = MediaDetailsMapper.ParseSpecialTags(media.GetLiveMediaDetail());
                    var parsedLayout = ParserHelper.ParseData(layout, jObject);

                    EmailHelper.Send(AppSettings.SystemEmailAddress, EmailHelper.GetMailAddressesFromString(formFieldSettings.EmailAddress), formFieldSettings.Subject, parsedLayout, (AppSettings.AttemptSMTPMailer)? EmailHelper.EmailMode.Both : EmailHelper.EmailMode.Direct);
                }
            }

            return(returnObj);
        }
        public async Task SaveExpiryDayRuleEmailNotificationsAndUpdateScoreCardAndOfferStatus()
        {
            Console.WriteLine("In SaveExpiryDayRuleEmailNotificationsAndUpdateScoreCardAndOfferStatus method ....");
            LogHelper.LogInfo("In SaveExpiryDayRuleEmailNotificationsAndUpdateScoreCardAndOfferStatus method ....");


            DIBZ.Common.DTO.EmailTemplateResponse emailTemplateExpiryDayRule = new Common.DTO.EmailTemplateResponse();

            try
            {
                //var emailTemplateLogic = Context.Create<EmailTemplateLogic>();

                LogicContext = new LogicContext();
                var emailTemplateLogic = LogicContext.Create <EmailTemplateLogic>();

                Console.WriteLine("fetching all swaps with offer status payment done....");
                LogHelper.LogInfo("fetching all swaps with offer status payment done....");

                var swapsWithPaymentDone = await emailTemplateLogic.GetAllSwapsWithPaymentDone();


                Console.WriteLine("fetched expiry day rule email template....");
                LogHelper.LogInfo("fetched expiry day rule email template....");

                var scorecardLogic = LogicContext.Create <ScorecardLogic>();
                var offerLogic     = LogicContext.Create <OfferLogic>();
                var swapLogic      = LogicContext.Create <SwapLogic>();
                foreach (var item in swapsWithPaymentDone)
                {
                    emailTemplateExpiryDayRule = await emailTemplateLogic.GetEmailTemplate(EmailType.Email, EmailContentType.ExpiryDayRule);

                    var getWorkingDaysCount = swapLogic.GetWorkingDaysCount(ConversionHelper.ConvertDateToTimeZone(item.CreatedTime));

                    //Condition when both party hasn't sent game on time.
                    if (item.Offer.OfferStatus == OfferStatus.Accept &&
                        item.Offer.Transactions.Count() == 2 &&
                        (item.SwapStatus == SwapStatus.Payment_Done_By_Offerer || item.SwapStatus == SwapStatus.Payment_Done_By_Swapper) &&
                        getWorkingDaysCount > SystemSettings.SrvcDayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.GameSwapPsersonId);

                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.Offer.ApplicationUserId);

                        await swapLogic.UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(item.OfferId, item.Id);



                        // to offerer

                        EmailTemplateHelper templatesForOfferer = new EmailTemplateHelper();

                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.UrlContactUs, string.Format("<a href='{0}'>link</a>", hostName + "/Dashboard/ContactUs"));

                        var emailBody = templatesForOfferer.FillTemplate(emailTemplateExpiryDayRule.Body);

                        Console.WriteLine("saving expiry dary rule email notification for the Offerer....");
                        LogHelper.LogInfo("saving expiry dary rule email notification for the Offerer....");

                        await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplateExpiryDayRule.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.Offer.ApplicationUser.Email, emailTemplateExpiryDayRule.Title, emailBody);

                        // to swapper
                        EmailTemplateHelper templatesForSwapper = new EmailTemplateHelper();

                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);
                        templatesForSwapper.AddParam(DIBZ.Common.Model.Contants.UrlContactUs, string.Format("<a href='{0}'>link</a>", hostName + "/Dashboard/ContactUs"));

                        var emailBodyForSwapper = templatesForSwapper.FillTemplate(emailTemplateExpiryDayRule.Body);

                        Console.WriteLine("saving expiry dary rule email notification for the swapper....");
                        LogHelper.LogInfo("saving expiry dary rule email notification for the swapper....");
                        await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplateExpiryDayRule.Title, emailBodyForSwapper, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.GameSwapPserson.Email, emailTemplateExpiryDayRule.Title, emailBodyForSwapper);
                    }

                    //Condition when offerer party hasn't sent game on time.
                    if (item.Offer.OfferStatus == OfferStatus.Accept &&
                        item.Offer.Transactions.Count() == 2 &&
                        (item.SwapStatus != SwapStatus.Payment_Done_By_Offerer || item.SwapStatus != SwapStatus.Payment_Done_By_Swapper && item.SwapStatus == SwapStatus.Game2_Received) &&
                        getWorkingDaysCount > SystemSettings.SrvcDayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.Offer.ApplicationUserId);

                        await swapLogic.UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(item.OfferId, item.Id);

                        EmailTemplateHelper templatesForOfferer = new EmailTemplateHelper();

                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.Offer.ApplicationUser.NickName);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.UrlContactUs, string.Format("<a href='{0}'>link</a>", hostName + "/Dashboard/ContactUs"));

                        var emailBody = templatesForOfferer.FillTemplate(emailTemplateExpiryDayRule.Body);

                        Console.WriteLine("saving expiry dary rule email notification for the Offerer....");
                        LogHelper.LogInfo("saving expiry dary rule email notification for the Offerer....");

                        await emailTemplateLogic.SaveEmailNotification(item.Offer.ApplicationUser.Email, emailTemplateExpiryDayRule.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.Offer.ApplicationUser.Email, emailTemplateExpiryDayRule.Title, emailBody);
                    }

                    //Condition when swapper party hasn't sent game on time.
                    if (item.Offer.OfferStatus == OfferStatus.Accept &&
                        item.Offer.Transactions.Count() == 2 &&
                        (item.SwapStatus != SwapStatus.Payment_Done_By_Offerer || item.SwapStatus != SwapStatus.Payment_Done_By_Swapper && item.SwapStatus == SwapStatus.Game1_Received) &&
                        getWorkingDaysCount > SystemSettings.SrvcDayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(item.GameSwapPsersonId);

                        await swapLogic.UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(item.OfferId, item.Id);

                        EmailTemplateHelper templatesForOfferer = new EmailTemplateHelper();

                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.OfferedGame, item.Offer.GameCatalog.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.SwappedGame, item.GameSwapWith.Name);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.AppUserNickName, item.GameSwapPserson.NickName);
                        templatesForOfferer.AddParam(DIBZ.Common.Model.Contants.UrlContactUs, string.Format("<a href='{0}'>link</a>", hostName + "/Dashboard/ContactUs"));

                        var emailBody = templatesForOfferer.FillTemplate(emailTemplateExpiryDayRule.Body);

                        Console.WriteLine("saving expiry dary rule email notification for the Offerer....");
                        LogHelper.LogInfo("saving expiry dary rule email notification for the Offerer....");

                        await emailTemplateLogic.SaveEmailNotification(item.GameSwapPserson.Email, emailTemplateExpiryDayRule.Title, emailBody, EmailType.Email, Priority.High);

                        EmailHelper.Email(item.GameSwapPserson.Email, emailTemplateExpiryDayRule.Title, emailBody);
                    }
                }

                await Task.Delay(SystemSettings.SrvcDayRuleRunningTimeInMS);
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.Message, ex);
            }
        }
        public void SendMentorCompleteEmail(string url, Guid compAppId, Guid currentUserId)
        {
            var orgManager                = this.container.GetInstance <OrganizationManager>();
            var compAppManager            = this.container.GetInstance <ComplianceApplicationManager>();
            var inspectionScheduleManager = this.container.GetInstance <InspectionScheduleManager>();
            var userManager               = this.container.GetInstance <UserManager>();
            var applicationSettingManager = this.container.GetInstance <ApplicationSettingManager>();
            var applicationManager        = this.container.GetInstance <ApplicationManager>();


            var scheds = inspectionScheduleManager.GetAllForCompliance(compAppId);

            var compApp = compAppManager.GetById(compAppId);

            var app = applicationManager.GetByComplianceApplicationId(compAppId)?.FirstOrDefault();

            if (compApp == null || app == null)
            {
                throw new Exception("Cannot find application");
            }

            var coordinator = userManager.GetById(compApp.CoordinatorId);

            var creds = coordinator.UserCredentials.Aggregate(string.Empty,
                                                              (current, cred) => current + (cred.Credential.Name + ", "));

            if (creds.Length > 2)
            {
                creds = creds.Substring(0, creds.Length - 2);
            }

            var factEmail = applicationSettingManager.GetByName(Constants.ApplicationSettings.AutoCcEmailAddress);

            foreach (var sched in scheds)
            {
                var ccs = new List <string>
                {
                    factEmail?.Value ?? "*****@*****.**",
                    coordinator.EmailAddress
                };

                var traineeDetail =
                    sched.InspectionScheduleDetails.FirstOrDefault(
                        x => x.AccreditationRoleId == (int)Constants.AccreditationRoles.InspectorTrainee);

                var mentorDetail = sched.InspectionScheduleDetails.FirstOrDefault(x => x.IsMentor && x.UserId == currentUserId);

                if (traineeDetail == null || mentorDetail == null)
                {
                    continue;
                }

                var trainee = userManager.GetById(traineeDetail.UserId);
                var mentor  = userManager.GetById(mentorDetail.UserId);

                var org = orgManager.GetById(sched.OrganizationId);

                var reminderHtml        = url + "app/email.templates/mentorComplete.html";
                var appUrl              = $"{url}#/Compliance?app={app.Id}&c={compAppId}";
                var inspectionReportUrl = $"{url}#/Reporting?app={app.Id}&c={compAppId}&org={org.Name}&r=Trainee%20Inspection%20Summary";

                var html = WebHelper.GetHtml(reminderHtml);
                html = html.Replace("{ApplicationUrl}", appUrl);
                html = html.Replace("{InspectionReportUrl}", inspectionReportUrl);
                html = html.Replace("{OrgName}", org.Name);
                html = html.Replace("{MentorName}", $"{mentor.FirstName} {mentor.LastName}");
                html = html.Replace("{TraineeName}", $"{trainee.FirstName} {trainee.LastName}");
                html = html.Replace("{CoordinatorName}", $"{coordinator.FirstName} {coordinator.LastName}, {creds}");
                html = html.Replace("{CoordinatorTitle}", coordinator.Title);
                html = html.Replace("{CoordinatorPhoneNumber}", coordinator.WorkPhoneNumber);
                html = html.Replace("{CoordinatorEmailAddress}", coordinator.EmailAddress);

                var subject = $"FACT Mentor Review Complete – {org.Name}";

                ccs.Add(mentor.EmailAddress);

                EmailHelper.Send(new List <string> {
                    trainee.EmailAddress
                }, ccs, subject, html, null, true);
            }
        }