コード例 #1
0
        public static async Task SendPlainModel()
        {
            var template = new DefaultTemplate
            {
                Subject           = "Send plain model",
                PlainBodyTemplate = @"@model Cactus.FluentEmail.Source.Simple.TemplateModel
                                        @using System
                                        @using System.Text;

                                        Hi @Model.Name",
                HtmlBodyTemplate  = "New Message",
                FromAddress       = Sender
            };
            var plainlModel = new TemplateModel {
                Name = "User"
            };

            var email = new Email();
            await email.UseTemplate(() => template, null, plainlModel).To(Recipient).SendAsync();
        }
コード例 #2
0
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@ParameterType @ParameterName");
 }
        public void UseTemplateWithModels_Success()
        {
            //Arrange
            var fluentEmail = new Mock <IFluentEmail>();
            var template    = new DefaultTemplate
            {
                Name              = "tests template",
                Subject           = "subject of template",
                HtmlBodyTemplate  = "body of template",
                PlainBodyTemplate = "plain body of template",
                Priority          = Priority.Normal,
                Tag         = "tag of template",
                Language    = CultureInfo.CurrentCulture,
                FromAddress = "*****@*****.**"
            };
            Func <ITemplate> getTemplate = () => template;
            var emailData = new EmailData();
            var htmlModel = new BodyModel
            {
                Name = "Kirill",
                Age  = 22
            };
            var plainModel = new BodyModel
            {
                Name = "Vitalic",
                Age  = 21
            };

            BodyModel actualHtmlModel  = null;
            BodyModel actualPlainModel = null;

            //Expect
            fluentEmail
            .Setup(x => x.UsingTemplate(It.Is <string>(b => b == template.HtmlBodyTemplate), It.IsNotNull <object>(), It.Is <bool>(i => i)))
            .Callback <string, object, bool>((htmlTemplate, model, isHtml) =>
            {
                actualHtmlModel = (BodyModel)model;
            })
            .Returns(fluentEmail.Object);

            fluentEmail
            .Setup(x => x.PlaintextAlternativeUsingTemplate(It.Is <string>(b => b == template.PlainBodyTemplate), It.IsNotNull <object>()))
            .Callback <string, object>((plainTemplate, model) =>
            {
                actualPlainModel = (BodyModel)model;
            })
            .Returns(fluentEmail.Object);

            fluentEmail
            .Setup(x => x.Subject(It.Is <string>(b => b == template.Subject)))
            .Returns(fluentEmail.Object);

            fluentEmail
            .Setup(x => x.SetFrom(It.Is <string>(b => b == template.FromAddress), It.Is <string>(n => n == null)))
            .Returns(fluentEmail.Object);

            fluentEmail
            .SetupGet(x => x.Data)
            .Returns(emailData);

            fluentEmail
            .Setup(x => x.Tag(It.Is <string>(b => b == template.Tag)))
            .Returns(fluentEmail.Object);

            //Act
            FluentEmailExtenssion.UseTemplate(fluentEmail.Object, getTemplate, htmlModel, plainModel);

            //Assert
            Assert.AreEqual(emailData.Priority, template.Priority);

            Assert.IsNotNull(actualHtmlModel);
            Assert.AreEqual(htmlModel.Name, actualHtmlModel.Name);
            Assert.AreEqual(htmlModel.Age, actualHtmlModel.Age);

            Assert.IsNotNull(actualPlainModel);
            Assert.AreEqual(plainModel.Name, actualPlainModel.Name);
            Assert.AreEqual(plainModel.Age, actualPlainModel.Age);

            //Verify
            fluentEmail.VerifyAll();

            fluentEmail.Verify(x => x.Body(It.IsAny <string>(), It.IsAny <bool>()), Times.Never);
            fluentEmail.Verify(x => x.PlaintextAlternativeBody(It.IsAny <string>()), Times.Never);
        }
コード例 #4
0
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate("using @Namespace;");
 }
コード例 #5
0
 /// <summary>
 /// Sets up the template
 /// </summary>
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate("using @Namespace;");
 }
コード例 #6
0
        public async Task Update_Success()
        {
            //Arrange
            var templatesRepository = new Mock<ITemplatesRepository>();
            var templatesManager = new TemplatesManager(templatesRepository.Object);

            var searchingName = "tests template 1";
            var searchingLanguage = new CultureInfo("en");
            var entities = new List<Template>
            {
                new Template
                {
                    Name = searchingName,
                    Subject = "tests subject 1",
                    HtmlBodyTemplate = "Hi my friend :)",
                    PlainBodyTemplate = "test plain",
                    Priority = EmailMessagePriority.Normal,
                    Tag = "test tag",
                    Language = searchingLanguage.Name,
                    FromAddress = "*****@*****.**",
                    CreatedDateTime = DateTime.UtcNow
                },
                new Template
                {
                    Name = searchingName,
                    Subject = "tests subject 2",
                    HtmlBodyTemplate = "Hi my friend :)",
                    PlainBodyTemplate = "test plain",
                    Priority = EmailMessagePriority.Normal,
                    Tag = "test tag",
                    Language = "es",
                    FromAddress = "*****@*****.**",
                    CreatedDateTime = DateTime.UtcNow
                }
            };

            var templatesUpdates = new DefaultTemplate
            {
                Name = "test template)",
                Subject = "test subject",
                HtmlBodyTemplate = "Hi, it's your email",
                PlainBodyTemplate = "test plain",
                Priority = Priority.Low,
                Tag = "tag 1",
                Language = new CultureInfo("en"),
                FromAddress = "*****@*****.**"
            };
            Template actualTemplateUpdates = null;

            //Expect
            templatesRepository
                .Setup(x => x.UpdateAsync(It.IsNotNull<Template>()))
                .Callback<Template>(template =>
                {
                    actualTemplateUpdates = template;
                })
                .Returns(Task.CompletedTask);

            templatesRepository
                .Setup(x => x.GetQuerable())
                .Returns(new AsyncEnumerable<Template>(entities));

            //Act
            await templatesManager.Update(searchingName, searchingLanguage, templatesUpdates);

            //Assert
            Assert.IsNotNull(actualTemplateUpdates);
            Assert.AreEqual(searchingName, actualTemplateUpdates.Name);
            Assert.AreEqual(searchingLanguage.Name, actualTemplateUpdates.Language);

            Assert.AreEqual(templatesUpdates.Subject, actualTemplateUpdates.Subject);
            Assert.AreEqual(templatesUpdates.HtmlBodyTemplate, actualTemplateUpdates.HtmlBodyTemplate);
            Assert.AreEqual(templatesUpdates.PlainBodyTemplate, actualTemplateUpdates.PlainBodyTemplate);
            Assert.AreEqual(EmailMessagePriority.Low, actualTemplateUpdates.Priority);
            Assert.AreEqual(templatesUpdates.Tag, actualTemplateUpdates.Tag);
            Assert.AreEqual(templatesUpdates.FromAddress, actualTemplateUpdates.FromAddress);
            Assert.AreEqual(entities[0].CreatedDateTime, actualTemplateUpdates.CreatedDateTime);

            //Verify
            templatesRepository.VerifyAll();
        }
コード例 #7
0
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@ParameterType @ParameterName");
 }
コード例 #8
0
        protected override void SetupTemplate()
        {
            Template = new DefaultTemplate(@"/* Code generated using Craig's Utility Library
            http://cul.codeplex.com */
            @Usings

            namespace @Namespace
            {
            /// <summary>
            /// @ClassName class
            /// </summary>
            @AccessModifier @Modifier class @ClassName
            {
            #region Constructor

            @Constructor

            #endregion

            #region Properties

            @Properties

            #endregion

            #region Functions

            @Functions

            #endregion
            }
            }");
        }
コード例 #9
0
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@AccessModifier @ExtraModifiers @PropertyType @PropertyName{ get{@GetMethod} set{@SetMethod} }");
 }
コード例 #10
0
 public void _Constructor_1()
 {
     other = new DefaultTemplate(ModuleType.Incident, Guid.Empty);
 }
コード例 #11
0
 public void SetUp()
 {
     templateId         = Guid.NewGuid();
     defaultTemplateObj = new DefaultTemplateDerived(ModuleType.Incident, templateId);
     other = new DefaultTemplate(ModuleType.Incident, templateId);
 }
コード例 #12
0
        public InvoiceModule()
        {
            this.RequiresAuthentication();
            Post["/createinvoice"] = p =>
            {
                try
                {
                    Invoices result = this.InvoiceService().Create(this.Request.Form.invoice, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(result));
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new { error = true, message = ex.Message }));
                }
            };
            Get["/GetDataInvoice"] = p =>
            {
                int countInvoice = this.InvoicesQueryRepository().CountInvoice(this.CurrentAccount().OwnerId);
                return(Response.AsJson(countInvoice));
            };
            Get["/GetDataInvoiceToPaging/{start}/{limit}"] = p =>
            {
                int start = p.start;
                int limit = p.limit;
                IEnumerable <Invoices> invoices = this.InvoicesQueryRepository().GetDataInvoiceToPaging(this.CurrentAccount().OwnerId, start, limit);
                return(Response.AsJson(invoices));
            };
            Get["/GetDataInvoiceToPDF/{id}"] = p =>
            {
                Guid          invoiceId     = p.id;
                Invoices      invoice       = this.InvoicesQueryRepository().FindById(invoiceId, this.CurrentAccount().OwnerId);
                InvoiceReport invoiceReport = new InvoiceReport(invoice);
                Customer      customer      = this.CustomerReportRepository().GetCustomerById(Guid.Parse(invoice.CustomerId));
                Organization  organization  = this.OrganizationReportRepository().FindByOwnerId(this.CurrentAccount().OwnerId);

                LogoOrganization logo     = this.LogoOrganizationQuery().GetLogo(this.CurrentAccount().OwnerId);
                DefaultTemplate  template = new DefaultTemplate();

                string html = template.GetInvoiceDefaultTemplate(invoiceReport, customer, organization, logo);
                EO.Pdf.Runtime.AddLicense("aP0BELxbvNO/++OfmaQHEPGs4PP/6KFspbSzy653hI6xy59Zs7PyF+uo7sKe" +
                                          "tZ9Zl6TNGvGd3PbaGeWol+jyH+R2mbbA3a5rp7XDzZ+v3PYEFO6ntKbEzZ9o" +
                                          "tZGby59Zl8AEFOan2PgGHeR3q9bF266OzffU8MOSwdXjFvlww7vSIrx2s7ME" +
                                          "FOan2PgGHeR3hI7N2uui2un/HuR3hI514+30EO2s3MKetZ9Zl6TNF+ic3PIE" +
                                          "EMidtbjC4K9qq73K47J1pvD6DuSn6unaD71GgaSxy5914+30EO2s3OnP566l" +
                                          "4Of2GfKe3MKetZ9Zl6TNDOul5vvPuIlZl6Sxy59Zl8DyD+NZ6w==");
                EO.Pdf.HtmlToPdf.Options.OutputArea = new System.Drawing.RectangleF(0.5f, 0.3f, 7.5f, 10f);
                MemoryStream memStream = new MemoryStream();
                HtmlToPdf.ConvertHtml(html, memStream);
                MemoryStream resultStream = new MemoryStream(memStream.GetBuffer());
                return(Response.FromStream(resultStream, "application/pdf"));
            };
            Delete["/deleteInvoice/{invoiceId}"] = p =>
            {
                try
                {
                    Guid _id = Guid.Parse(p.invoiceId);
                    this.InvoiceService().Delete(_id, this.CurrentAccount().OwnerId);
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new { error = true, message = ex.Message }));
                }
                return(Response.AsJson("OK"));
            };
            Get["/SearchInvoice/{key}"] = p =>
            {
                string                       key           = p.key;
                IList <Invoices>             invoices      = new List <Invoices>();
                IEnumerable <InvoiceReports> invoiceReport = this.InvoicesQueryRepository().Search(this.CurrentAccount().OwnerId, new string[] { key });
                foreach (InvoiceReports invoice in invoiceReport)
                {
                    invoices.Add(this.InvoicesRepository().Get(invoice._id, invoice.OwnerId));
                }
                return(Response.AsJson(invoices));
            };
            Post["/UpdateInvoice"] = p =>
            {
                try
                {
                    this.InvoiceService().Update(this.Request.Form.invoice, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(new { error = false }));
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new { error = true, message = ex.Message }));
                }
            };
            Get["/invoice/{id}"] = p =>
            {
                Guid     invoiceId = p.id;
                Invoices invoice   = this.InvoicesQueryRepository().FindById(invoiceId, this.CurrentAccount().OwnerId);
                return(Response.AsJson(invoice));
            };
            Post["/approveinvoice/{id}"] = p =>
            {
                try
                {
                    Guid invoiceId = p.id;
                    this.InvoiceService().ApproveInvoice(p.id, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(new { error = false }));
                }
                catch (Exception e)
                {
                    return(Response.AsJson(new { error = true, message = e.Message }));
                }
            };

            Get["/InvoiceAutoNumber"] = p =>
            {
                var autoNumber = this.InvoiceAutoNumberGenerator().GetInvoiceAutoNumberConfig(this.CurrentAccount().OwnerId);
                return(Response.AsJson(new { prefix = autoNumber.Prefix, mode = autoNumber.Mode }));
            };
            Post["/SetupInvoiceAutoNumber"] = p =>
            {
                try
                {
                    string Data = this.Request.Form.data;
                    InvoiceAutoNumberConfig config = Newtonsoft.Json.JsonConvert.DeserializeObject <InvoiceAutoNumberConfig>(Data);
                    this.InvoiceAutoNumberGenerator().SetupInvoiceAutoMumber(config.Mode, config.Prefix, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(new { error = false }));
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new { error = true, message = ex.Message }));
                }
            };

            Post["/cancelinvoice/{id}"] = p =>
            {
                try
                {
                    this.InvoiceService().Cancel(p.id, this.Request.Form.Note, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(new { error = false }));
                }
                catch (Exception e)
                {
                    return(Response.AsJson(new { error = true, message = e.Message }));
                }
            };

            Post["/forcecancelinvoice/{id}"] = p =>
            {
                try
                {
                    this.InvoiceService().ForceCancel(p.id, this.Request.Form.Note, this.CurrentAccount().OwnerId);
                    return(Response.AsJson(new { error = false }));
                }
                catch (Exception e)
                {
                    return(Response.AsJson(new { error = true, message = e.Message }));
                }
            };
        }
コード例 #13
0
 private ITemplate GetTemplate(StackFlairOptions flairOptions, StackData stackData)
 {
     ITemplate template = null;
     switch (flairOptions.Theme.ToLower()) {
         /*case "glitter":
             template = new GlitterTemplate(stackData, flairOptions);
             break;*/
         case "black":
             template = new BlackTemplate(stackData, flairOptions);
             break;
         case "hotdog":
             template = new HotDogTemplate(stackData, flairOptions);
             break;
         case "holy":
             template = new HoLyTemplate(stackData, flairOptions);
             break;
         case "nimbus":
             template = new NimbusTemplate(stackData, flairOptions);
             break;
         default:
             template = new DefaultTemplate(stackData, flairOptions);
             break;
     }
     return template;
 }
コード例 #14
0
ファイル: AppController.cs プロジェクト: HALS8/Covid19
        public async Task <ActionResult <ReportDTO> > PostReport([FromBody] ReportDTO newReport)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogTrace("Report posted with invalid model state.", newReport);
                    return(BadRequest("Parameters Invalid."));
                }

                var user = await _unitOfWork.UserManager.FindVerifiedByNameAsync(User.Identity.Name).ConfigureAwait(false);

                if (user == null)
                {
                    _logger.LogInformation("Report created by invalid or unverified user: {Report}", newReport);
                    return(BadRequest("Failed to send report: invalid or unverified user."));
                }

                var report = new Report
                {
                    ReportedBy   = user,
                    ReportedByIp = _ipService.GetIPAddress(HttpContext),
                    Date         = DateTime.UtcNow,
                    Type         = newReport.Type,
                    Reason       = newReport.Reason,
                    Explanation  = newReport.Explanation
                };

                var reportReason = "inappropriate";
                switch (newReport.Reason)
                {
                case ReportReason.VoteManipulation:
                {
                    reportReason = "manipulated";
                    break;
                }

                case ReportReason.Offensive:
                {
                    reportReason = "offensive";
                    break;
                }

                case ReportReason.Duplicate:
                {
                    reportReason = "duplicate";
                    break;
                }

                case ReportReason.Conspiracy:
                {
                    reportReason = "conspiratorial";
                    break;
                }

                case ReportReason.Dangerous:
                {
                    reportReason = "dangerous";
                    break;
                }

                case ReportReason.Misleading:
                {
                    reportReason = "misleading";
                    break;
                }

                case ReportReason.FakeCompany:
                {
                    reportReason = "false";
                    break;
                }

                case ReportReason.IncorrectDetails:
                {
                    reportReason = "inaccurate";
                    break;
                }

                default:
                {
                    reportReason = "inappropriate";
                    break;
                }
                }

                var  emailMessage = "Error";
                var  subject      = $"{report.Reason} content reported for ";
                Guid guid         = (ShortGuid)newReport.ReportedId;
                switch (newReport.Type)
                {
                case ReportType.Review:
                {
                    var review = await _unitOfWork.Reviews.GetReviewById(guid, false, true).ConfigureAwait(false);

                    if (review == null)
                    {
                        return(NotFound("Reported review not found."));
                    }

                    report.ReportedReview = review;

                    subject     += $"review ID: {review.Id}";
                    emailMessage = $"{user.UserName} reported review (ID: {review.Id}) on {report.Date:yyyy-MM-dd HH:mm} for {reportReason} content, " +
                                   $"with explanation '{report.Explanation}'.";
                    break;
                }

                case ReportType.Company:
                {
                    var company = await _unitOfWork.Companies.GetCompanyById(guid, false, false, true, false).ConfigureAwait(false);

                    if (company == null)
                    {
                        return(NotFound("Reported company not found"));
                    }

                    report.ReportedCompany = company;

                    subject     += $"company ID: {company.Id}";
                    emailMessage = $"{user.UserName} reported company {company.Name} (ID: {company.Id}) on {report.Date:yyyy-MM-dd HH:mm} for " +
                                   $"{reportReason} content, with explanation '{report.Explanation}'.";
                    break;
                }

                default:
                {
                    _logger.LogError($"Report submitted with invalid report type: {newReport.Type}");
                    return(BadRequest("Invalid report type."));
                }
                }

                _unitOfWork.Reports.Add(report);
                await _unitOfWork.Complete().ConfigureAwait(false);

                _logger.LogInformation($"New report stored internally, ID: {report.Id}");

                emailMessage += $" Stored internally as ID: { report.Id}";

                var internalEmailData = new DefaultTemplate()
                {
                    Subject = subject,
                    Message = emailMessage
                };

                var internalEmailResponse = await _emailSender
                                            .SendEmailAsync("*****@*****.**", _config["SendGrid:Templates:InternalReport"], EmailFrom.Report, internalEmailData)
                                            .ConfigureAwait(false);

                if (internalEmailResponse.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    _logger.LogInformation("New report dispatched internally.");

                    var userEmailData = new ReportTemplate()
                    {
                        Username     = user.UserName,
                        ReportReason = reportReason
                    };

                    var userEmailResponse = await _emailSender
                                            .SendEmailAsync(user.Email, _config["SendGrid:Templates:ReportReceived"], EmailFrom.Report, userEmailData)
                                            .ConfigureAwait(false);

                    if (userEmailResponse.StatusCode != System.Net.HttpStatusCode.Accepted)
                    {
                        _logger.LogError($"SendGrid failed to send report notification to {user.UserName}.");
                    }
                    else
                    {
                        _logger.LogInformation($"Report notification email dispatched to {user.UserName}.");
                    }

                    return(CreatedAtAction("PostReport", new { id = report.Id }, _mapper.Map <Report, ReportDTO>(report)));
                }
                else
                {
                    _logger.LogError("Failed to send report: status code {StatusCode}, {Report}", internalEmailResponse.StatusCode, report);
                    return(StatusCode(500, "Failed to send report."));
                }
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogError(ex, "Database error during new report save.");
                return(StatusCode(500, "Failed to send report."));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to post report.");
                return(StatusCode(500, "Failed to send report."));
            }
        }
コード例 #15
0
 /// <summary>
 /// Sets up the template
 /// </summary>
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@AccessModifier @ClassName(@ParameterList)
     {
     @Body
     }");
 }
コード例 #16
0
ファイル: ContentPresenter.cs プロジェクト: JianwenSun/cc
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        static ContentPresenter()
        {
            DataTemplate template;
            FrameworkElementFactory text;
            Binding binding;

            // Default template for strings when hosted in ContentPresener with RecognizesAccessKey=true
            template = new DataTemplate();
            text = CreateAccessTextFactory();
            text.SetValue(AccessText.TextProperty, new TemplateBindingExtension(ContentProperty));
            template.VisualTree = text;
            template.Seal();
            s_AccessTextTemplate = template;

            // Default template for strings
            template = new DataTemplate();
            text = CreateTextBlockFactory();
            text.SetValue(TextBlock.TextProperty, new TemplateBindingExtension(ContentProperty));
            template.VisualTree = text;
            template.Seal();
            s_StringTemplate = template;

            // Default template for XmlNodes
            template = new DataTemplate();
            text = CreateTextBlockFactory();
            binding = new Binding();
            binding.XPath = ".";
            text.SetBinding(TextBlock.TextProperty, binding);
            template.VisualTree = text;
            template.Seal();
            s_XmlNodeTemplate = template;

            // Default template for UIElements
            template = new UseContentTemplate();
            template.Seal();
            s_UIElementTemplate = template;

            // Default template for everything else
            template = new DefaultTemplate();
            template.Seal();
            s_DefaultTemplate = template;

            // Default template selector
            s_DefaultTemplateSelector = new DefaultSelector();
        }
コード例 #17
0
 /// <summary>
 /// Sets up the template
 /// </summary>
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@AccessModifier @Modifier @Type @FunctionName(@ParameterList)
     {
     @Body
     }");
 }
コード例 #18
0
 /// <summary>
 /// Sets up the template
 /// </summary>
 protected override void SetupTemplate()
 {
     Template = new DefaultTemplate(@"@AccessModifier @ExtraModifiers @PropertyType @PropertyName{ get; set; }");
 }
コード例 #19
0
 private bool ConvertToTemplateChangeCallback(object context)
 {
     PropertyDescriptor templateDescriptor = TypeDescriptor.GetProperties(Component).Find("ItemTemplate", false);
     ITemplate template = new DefaultTemplate();
     templateDescriptor.SetValue(Component, template);
     return true;
 }
コード例 #20
0
 public new bool CheckEquals(DefaultTemplate other)
 {
     return(base.CheckEquals(other));
 }
コード例 #21
0
 public Template()
 {
     Default = new DefaultTemplate();
 }