public void TestCompile_CommentAloneOnlyLine_PrintsSurroundingSpace()
 {
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile("    {{#! comment }}    ");
     string result = generator.Render(null);
     Assert.AreEqual("        ", result, "The wrong text was generated.");
 }
Exemplo n.º 2
0
 public void TestCompile_CommentContentComment_RemovesComment()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "{{#! comment }}Middle{{#! comment }}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new object());
     Assert.AreEqual("Middle", result, "The wrong text was generated.");
 }
Exemplo n.º 3
0
 public void TestCompile_CommentBlankComment_RemovesLine()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "{{#! comment }}    {{#! comment }}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new object());
     Assert.AreEqual(String.Empty, result, "The wrong text was generated.");
 }
Exemplo n.º 4
0
 public void TestCompile_Key_ReplacesWithValue()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { Name = "Bob" });
     Assert.AreEqual("Hello, Bob!!!", result, "The wrong text was generated.");
 }
Exemplo n.º 5
0
 public void TestCompile_LineAllWhitespace_PrintsWhitespace()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "\t    \t";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual(format, result, "The generated text was wrong.");
 }
Exemplo n.º 6
0
 public void TestCompile_NoTags_PrintsFormatString()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "This is an ordinary string.";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual(format, result, "The generated text was wrong.");
 }
Exemplo n.º 7
0
 public void TestCompile_CommentNewLineBlank_PrintsBlank()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"    {{#! comment }}
     ";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual("        ", result, "The wrong text was generated.");
 }
 public void TestCompile_CanUseContextVariablesToMakeDecisions()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#each this}}{{#if @index}}{{#index}}{{/if}}{{/each}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new int[] { 1, 1, 1, 1, });
     string expected = "123";
     Assert.AreEqual(expected, actual, "The numbers were not valid.");
 }
Exemplo n.º 9
0
 public void TestCompile_CanUseContextStartEndVariablesToMakeDecisions()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#each this}}{{#if @start}}<li class=""first""></li>{{#elif @end}}<li class=""last""></li>{{#else}}<li class=""middle""></li>{{/if}}{{/each}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new int[] { 1, 1, 1, 1, });
     string expected = @"<li class=""first""></li><li class=""middle""></li><li class=""middle""></li><li class=""last""></li>";
     Assert.AreEqual(expected, actual, "The string is not valid.");
 }
Exemplo n.º 10
0
        public void TestCompile_OutputNewLineBlank_PrintsBothLines()
        {
            FormatCompiler compiler = new FormatCompiler();
            const string format = @"Hello{{#newline}}
    ";

            const string expected = @"Hello
    ";
            Generator generator = compiler.Compile(format);
            string result = generator.Render(null);
            Assert.AreEqual(expected, result, "The wrong text was generated.");
        }
 public void TestCompile_CanUseContextVariableToToggle()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#set even}}{{#each this}}{{#if @even}}Even {{#else}}Odd {{/if}}{{#set even}}{{/each}}";
     Generator generator = compiler.Compile(format);
     generator.ValueRequested += (sender, e) =>
     {
         e.Value = !(bool)(e.Value ?? false);
     };
     string actual = generator.Render(new int[] { 1, 1, 1, 1 });
     string expected = "Even Odd Even Odd ";
     Assert.AreEqual(expected, actual, "The context variable was not toggled.");
 }
Exemplo n.º 12
0
        protected string GenerateChangelog(Settings settings, ReleaseHistory releaseHistory)
        {
            var format = $@"# {{{{ProductName}}}} {{{{CurrentVersion}}}}{{{{#newline}}}}
{{{{#newline}}}}
{{{{#each Releases}}}}{{{{#newline}}}}
## {{{{Version}}}}{{{{#newline}}}}
{{{{#each Changes}}}}{{{{#newline}}}}
* **{{{{TypeDescription}}}}**: {{{{Description}}}}
{{{{/each}}}}{{{{#newline}}}}
{{{{/each}}}}";

            var compiler  = new FormatCompiler();
            var generator = compiler.Compile(format);

            return(generator.Render(releaseHistory));
        }
Exemplo n.º 13
0
        public static string Render(string str_format, object obj_value)
        {
            if (obj_value == null)
            {
                obj_value = new object();
            }

            try
            {
                FormatCompiler compiler  = new FormatCompiler();
                Generator      generator = compiler.Compile(str_format);
                return(generator.Render(obj_value));
            }
            catch { }

            return(string.Empty);
        }
Exemplo n.º 14
0
        public string ParseAfterRegister(string templateBody, UserInfo MyUserInfo)
        {
            string      ReturnValue   = "";
            string      TemplateBody  = "";
            string      ParseValue    = "";
            TemplateDTO MyTemplateDTO = new TemplateDTO();

            try
            {
                //Get Template Body from TemplateID
                //MyTemplateDTO = m_TemplateDbService.GetTemplateByTemplateCode(TemplateCode, MyUserInfo);
                try
                {
                    MyUserInfo.UserName = MyUserInfo.UserName.Split(' ')[0];
                }
                catch (Exception exp)
                {
                    var messge = exp.ToString();
                }


                TemplateBody = templateBody;
                //Parse Here
                FormatCompiler compiler = new FormatCompiler();

                Generator generator = compiler.Compile(TemplateBody);

                string JSONString = string.Empty;
                JSONString = JsonConvert.SerializeObject(MyUserInfo);
                //var reportData = String.Format("{{ feeTypes: {0} }}", JSONString);
                var     reportData = JSONString;
                JObject jsonData   = JObject.Parse(reportData);
                ParseValue = generator.Render(jsonData);

                ReturnValue = ParseValue;

                return(ReturnValue);
            }

            catch (Exception exp)
            {
                throw;
            }
        }
Exemplo n.º 15
0
        private static string TransformText(string text, object data, IFormatProvider formatter)
        {
            // if we don't have any data, or, if data is a dictionary, it has
            // no values, skip formatting and just return the original text
            if (data == null || (data as IDictionary)?.Count == 0)
            {
                return(text);
            }

            if (data is JToken)
            {
                data = JsonConvert.DeserializeObject <Dictionary <string, object> >(data.ToString());
            }

            var compiler  = new FormatCompiler();
            var generator = compiler.Compile(text);

            return(generator.Render(formatter, data));
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Send email asynchronously by using pre-defined template.
        /// </summary>
        /// <param name="recipients"></param>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        public async Task SendAsync(string[] recipients, string templateName, object data)
        {
            // Find template config by using name.
            var mailTemplate = GetMailTemplate(templateName);

            if (mailTemplate == null)
            {
                return;
            }

            // Initiate SendGrid client.
            var sendGridClient = new SendGridClient(ApiKey);

            // Render mail content.
            // Initialize template.
            var formatCompiler = new FormatCompiler();
            var generator      = formatCompiler.Compile(mailTemplate.Content);
            var mailContent    = generator.Render(data);

            // Initiate mail message.
            var recipientMails = recipients.Select(x => new EmailAddress {
                Email = x
            }).ToList();

            // Initiate SendGrid message.
            var sendGridMailMessage = new SendGridMessage();

            sendGridMailMessage.AddTos(recipientMails);
            sendGridMailMessage.From = new EmailAddress(MailServiceProvider);

            if (mailTemplate.IsHtml)
            {
                sendGridMailMessage.HtmlContent = mailContent;
            }
            else
            {
                sendGridMailMessage.PlainTextContent = mailContent;
            }
            sendGridMailMessage.SetSubject(mailTemplate.Subject);

            await sendGridClient.SendEmailAsync(sendGridMailMessage);
        }
Exemplo n.º 17
0
        protected override void LoadTemplate()
        {
            base.LoadTemplate();

            if (!string.IsNullOrEmpty(this.TemplateHtml))
            {
                this.fileTag = new FileTagDefinition();

                FormatCompiler compiler = new FormatCompiler()
                {
                    RemoveNewLines = false
                };

                compiler.RegisterTag(this.fileTag, true);
                compiler.RegisterTag(new IfMatchTagDefinition(), true);
                compiler.RegisterTag(new ExtendedElseTagDefinition(), false);
                this.generator              = compiler.Compile(this.TemplateHtml);
                this.generator.KeyNotFound += this.Generator_KeyNotFound;
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            const string html = @"{{Form.Name}} {{#! Hello }} {{url|Homepage}}";

            var compiler = new FormatCompiler();

            compiler.RegisterTag(new CommandTagDefinition("url", Url), true);

            var generator = compiler.Compile(html);

            generator.KeyNotFound += (sender, eventArgs) => Console.WriteLine(eventArgs.Key);

            var model = new FormPost();

            model.Form.Name = "Hello";

            string rendered = generator.Render(model);

            Console.ReadKey();
        }
Exemplo n.º 19
0
        public static void run2()
        {
            FormatCompiler compiler = new FormatCompiler();
            const string   format   = @"{{#set even}}
{{#each this}}
{{#if @even}}
Even
{{#else}}
Odd
{{/if}}
{{#set even}}
{{/each}}";

            Generator generator = compiler.Compile(format);

            generator.ValueRequested += (sender, e) =>
            {
                e.Value = !(bool)(e.Value ?? false);
            };
            string result = generator.Render(new int[] { 0, 1, 2, 3 });
        }
Exemplo n.º 20
0
        public string Render(object context)
        {
            FormatCompiler compiler  = new FormatCompiler();
            Generator      generator = compiler.Compile(this.template);
            string         result;

            try
            {
                result = generator.Render(context).Trim();
            }
            catch (Exception e)
            {
                result = this.template;
            }

            if (this.filter != String.Empty)
            {
                result = this.FilterCompile(result, this.filter);
            }

            return(result);
        }
Exemplo n.º 21
0
        public HttpResponseMessage GetMustacheSharpPage()
        {
            string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "article2.html");

            using (StreamReader reader = new StreamReader(templatePath))
            {
                string strTemp = reader.ReadToEnd();

                var data = TemplateData.Create();

                FormatCompiler compiler = new FormatCompiler();
                compiler.RegisterTag(new ListTagDefinition <Item>(), true);
                Generator generator = compiler.Compile(strTemp);
                string    result    = generator.Render(data);

                var response = new HttpResponseMessage();
                response.Content = new StringContent(result);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

                return(response);
            }
        }
Exemplo n.º 22
0
        public void TestEach()
        {
            Dictionary<string, object> allparameters = new Dictionary<string, object>();
            allparameters.Add("stuName", "Jason");
            allparameters.Add("schoolName", "SH LJZ");
            //-----------------------------------------------------
            var class1 = new Dictionary<string, object>();
            class1.Add("Address", "Tong ren road 258号");
            class1.Add("Date", DateTime.Now);

            var Class2 = new Dictionary<string, object>();
            Class2.Add("Address", "People square");
            Class2.Add("Date", DateTime.Now);

            List<object> classes = new List<object>();
            classes.Add(class1);
            classes.Add(Class2);
            //-------------------------------------------------------
            allparameters.Add("Classes", classes);
            //--------------------------------------------------------
            var school1 = new Dictionary<string, object>();
            school1.Add("SchoolName", "LJZ");
            school1.Add("StuCount", 10);

            var school2 = new Dictionary<string, object>();
            school2.Add("SchoolName", "PSQ");
            school2.Add("StuCount", "20");

            List<object> schools = new List<object>();
            schools.Add(school1);
            schools.Add(school2);
            //---------------------------------------------------------
            allparameters.Add("Schools", schools);
            FormatCompiler compiler = new FormatCompiler();
            Generator generator = compiler.Compile(template);
            string actual = generator.Render(allparameters);
            Assert.IsNotNull(actual);
        }
Exemplo n.º 23
0
        /// <summary>
        ///     Send email to a list of recipients with subject and content.
        /// </summary>
        /// <param name="recipients"></param>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public void Send(string[] recipients, string templateName, object data)
        {
            // Find mail template from configuration.
            var mailTemplate = GetMailTemplate(templateName);

            // Template is not defined.
            if (mailTemplate == null)
            {
                return;
            }

            // Initiate a mail message.
            var mailMessage = new MailMessage();

            // To
            foreach (var recipient in recipients)
            {
                mailMessage.To.Add(new MailAddress(recipient));
            }

            // Subject and multipart/alternative Body
            mailMessage.Subject    = mailTemplate.Subject;
            mailMessage.IsBodyHtml = mailTemplate.IsHtml;

            // Initialize template.
            var formatCompiler = new FormatCompiler();
            var generator      = formatCompiler.Compile(templateName);
            var mailContent    = generator.Render(data);

            mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(mailContent, null, mailTemplate.IsHtml ? MediaTypeNames.Text.Html : MediaTypeNames.Text.Plain));

            // Init SmtpClient and send
            var smtpClient = new SmtpClient();

            smtpClient.Send(mailMessage);
        }
 public void TestCompile_MissingKey_CallsKeyNotFoundHandler()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name}}!!!";
     Generator generator = compiler.Compile(format);
     generator.KeyNotFound += (obj, args) =>
     {
         args.Substitute = "Unknown";
         args.Handled = true;
     };
     string actual = generator.Render(new object());
     string expected = "Hello, Unknown!!!";
     Assert.AreEqual(expected, actual, "The wrong message was generated.");
 }
 public void TestCompile_KeyWithPositiveAlignment_OptionalPlus_AppliesAlignment()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name,+10}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { Name = "Bob" });
     Assert.AreEqual("Hello,        Bob!!!", result, "The wrong text was generated.");
 }
 public void TestCompile_KeyKey_PrintsBothLines()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{this}}{{#newline}}
     {{this}}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render("Content");
     const string expected = @"Content
     Content";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
 public void TestCompile_If_EvaluatesToTrue_PrintsContent()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Content{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     Assert.AreEqual("BeforeContentAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_IfNewLineEndIf_PrintsNothing()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = @"{{#if this}}
     {{/if}}";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     Assert.AreEqual(String.Empty, result, "The wrong text was generated.");
 }
 public void TestCompile_IfElse_TwoElses_IncludesSecondElseInElse_Throws()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Yay{{#else}}Nay{{#else}}Bad{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(false);
     Assert.AreEqual("BeforeNay{{#else}}BadAfter", result, "The wrong text was generated.");
 }
Exemplo n.º 30
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var compiler = new FormatCompiler();

            // build the track 2 string

            const string track2Template = "M{{Pan}}={{ExpiryYear:00}}{{ExpiryMonth:00}}0?";

            var track2Data = new
            {
                Pan         = processPaymentRequest.CreditCardNumber,
                ExpiryYear  = processPaymentRequest.CreditCardExpireYear - 2000,
                ExpiryMonth = processPaymentRequest.CreditCardExpireMonth.ToString("D2")
            };

            //var track2String = compiler.format(track2Template, track2Data);
            Generator generator    = compiler.Compile(track2Template);
            var       track2String = generator.Render(track2Data);

            // build the MKey string

            const string mkeyTemplate = "{{MkeyPassword}}{{TerminalId}}27{{Amount}}{{SubmissionDate:yyyyMMddHHmmss}}{{Track2}}";

            //var reference = (_eigenPaymentSettings.UseSandbox ? "TEST" : "") + processPaymentRequest.OrderGuid.ToString();
            //var reference = processPaymentRequest.OrderGuid.ToString();
            var reference  = _orderService.GetMaxOrderNumber().ToString();
            var flightInfo = processPaymentRequest.FlightInfo;

            //submission.DateSubmitted = DateTime.UtcNow;
            var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);

            var eigenData = new
            {
                TerminalId     = _eigenPaymentSettings.TerminalID,
                MkeyPassword   = _eigenPaymentSettings.HashPassword,
                Track2         = track2String,
                Amount         = Convert.ToInt32(orderTotal * 100M),
                SubmissionDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Eastern Standard Time"),
                Reference      = reference,
                FlightInfo     = flightInfo,
                Mkey           = new StringBuilder()
            };

            //var mKeyPlainString = compiler.Format(mkeyTemplate, eigenData);
            generator = compiler.Compile(mkeyTemplate);
            var mKeyPlainString = generator.Render(eigenData);

            // build the request URL with query string

            eigenData.Mkey.Append(CreateSha1HashHexString(mKeyPlainString));

            const string eigenQueryTemplate = "MTQ,TG{{TerminalId}},TC27,T2{{Track2}},A1{{Amount}},ED{{FlightInfo}},IN{{Reference}},DT{{SubmissionDate:yyyyMMddHHmmss}},MY{{Mkey}}";

            generator = compiler.Compile(eigenQueryTemplate);
            var querystring = generator.Render(eigenData);

            var uriBuilder = new UriBuilder(GetEigenUrl())
            {
                Query = querystring
            };

            // submit the transaction to Eigen

            Dictionary <string, string> responseCodes = null;

            try
            {
                using (var client = new HttpClient())
                {
                    var response = client.GetAsync(uriBuilder.Uri).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        var responseString = response.Content.ReadAsStringAsync().Result;
                        responseCodes = GetResponseCodes(responseString);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (responseCodes == null || !responseCodes.Any())
            {
                result.AddError("Eigen unknown error");
            }

            switch (responseCodes.GetValueOrDefault("AB"))
            {
            case "Y":
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
                result.AddError(string.Format("Declined ({0})", responseCodes.GetValueOrDefault("RM")));
                break;
            }

            result.AuthorizationTransactionResult = responseCodes.GetValueOrDefault("RM");
            result.AuthorizationTransactionCode   = responseCodes.GetValueOrDefault("IN");
            result.AuthorizationTransactionId     = responseCodes.GetValueOrDefault("AC");
            result.AllowStoringCreditCardNumber   = _eigenPaymentSettings.AllowStoringTransactionLog;


            foreach (var responseCode in responseCodes)
            {
                if (responseCode.Key == "PA" || responseCode.Key == "T2")
                {
                    continue;
                }
                result.ResponseCodes.Add(responseCode.Key, responseCode.Value);
                //submission.ResponseCodes.Add(responseCode.Key, responseCode.Value);
            }

            return(result);
        }
Exemplo n.º 31
0
        public void Render()
        {
            string layoutTemplate = "";

            if (this.currentModule != null)
            {
                this.currentModule.beforeRender(this);
            }

            var total = this.templateStack.Count;

            for (var i = total - 1; i >= 0; i--)
            {
                var templateName = templateStack[i];

                var localPath = Path.Combine("views", templateName + ".html");
                var fileName  = site.GetFullPath(localPath);

                string body;

                if (System.IO.File.Exists(fileName))
                {
                    body = System.IO.File.ReadAllText(fileName);
                }
                else
                {
                    this.error = "Error loading view '" + templateName + "', the file was not found!";
                    localPath  = Path.Combine("views", "404.html");
                    fileName   = site.GetFullPath(localPath);

                    if (System.IO.File.Exists(fileName))
                    {
                        body = System.IO.File.ReadAllText(fileName);
                    }
                    else
                    {
                        this.Echo(this.error);
                        return;
                    }
                }

                layoutTemplate = body.Replace("$body", layoutTemplate);
            }

            if (this.currentModule != null)
            {
                this.currentModule.afterRender(this, layoutTemplate);
            }

            var compiler = new FormatCompiler();

            compiler.RemoveNewLines          = false;
            compiler.AreExtensionTagsAllowed = true;
            Generator generator = compiler.Compile(layoutTemplate);

            generator.TagFormatted += escapeInvalidHtml;
            generator.KeyNotFound  += (sender, e) =>
            {
                e.Handled = true;

                object obj;
                ((Mustache.Scope)sender).TryFind("this", out obj);

                var entity = obj as Entity;
                if (entity != null)
                {
                    e.Substitute = entity.GetFieldValue(e.Key);
                }
                else
                {
                    e.Substitute = null;
                }


                return;
            };
            string result = generator.Render(this);

            Echo(result);
        }
Exemplo n.º 32
0
        //public nancyExport(IConfigProvider configProvider, IJwtWrapper jwtWrapper)
        public nancyExport()
            : base("/export")
        {
            Get["/"] = x =>
            {
                #region //....
                var o = (Response) @"

<!DOCTYPE html>
<html xmlns=""http://www.w3.org/1999/xhtml"">
<head>
    <title>@domain/@path</title>
</head>
<body>
    <form name=form id=form method=post action=""#"">
        <input type=text name=msg id=msg />
        <input type=submit />
    </form>

    <script>
        function listener(event) {
            //if (event.origin !== 'http://javascript.info') return;
            var data = event.data;
            document.getElementById('msg').value = data;
            //alert(data);
            document.getElementById('form').submit();
        }

        if (window.addEventListener) {
            addEventListener('message', listener, false)
        } else {
            attachEvent('onmessage', listener)
        }
    </script>
</body>
</html>


";
                o.StatusCode  = Nancy.HttpStatusCode.OK;
                o.ContentType = "text/html";
                return(o);

                #endregion
            };

            Post["/"] = x =>
            {
                string   s_html        = "";
                string   s_description = "";
                string   s_msg         = Request.Form["msg"];
                string[] ab            = s_msg.Split('|');
                if (ab.Length == 6)
                {
                    s_description = ab[2].f_Base64ToString();
                    string
                        s_body_template_64 = ab[0],
                        s_config_64        = ab[1],

                        s_header_64          = ab[3],
                        s_master_template_64 = ab[4],
                        s_detail_template_64 = ab[5];

                    string config = s_config_64.f_Base64ToString();

                    if (!string.IsNullOrWhiteSpace(config))
                    {
                        string[] a = config.ToLower().Split(new string[] { "api" }, StringSplitOptions.None);
                        if (a.Length > 0)
                        {
                            string
                                s_main_template   = s_body_template_64.f_Base64ToString(),
                                s_header          = s_header_64.f_Base64ToString(),
                                s_master_template = s_master_template_64.f_Base64ToString(),
                                s_detail_template = s_detail_template_64.f_Base64ToString();

                            string api = a[1].Replace(@"""", "").Replace(@":", "").Split(',')[0];

                            msgPara m = new msgPara()
                            {
                                api    = api,
                                config = s_config_64
                            };



                            string s_query = "json|" + JsonConvert.SerializeObject(m);
                            var    ds      = msg.ProcessMessage(s_query, 1, 1000000,
                                                                msg_type.table_td, s_detail_template);


                            FormatCompiler compiler  = new FormatCompiler();
                            Generator      generator = compiler.Compile(s_detail_template);
                            switch (api)
                            {
                            default:
                                string tbody2 = ds.Item2;

                                if (s_main_template.Contains(msg_render.col_tbody_key) && tbody2.Trim().Length > 10)
                                {
                                    s_html = s_main_template.Replace(msg_render.col_tbody_key, tbody2);
                                }
                                else
                                {
                                    s_html = s_main_template + "<table>" + tbody2 + "</table>";
                                }
                                if (ds.Item4 != null)
                                {
                                    var arrTempCols = ExtractCols(s_master_template);

                                    if (arrTempCols.Length > 0 && (s_master_template != ""))
                                    {
                                        var    bodyItems    = "";
                                        int    index        = 0;
                                        string bodyTemplate = s_master_template;
                                        string body         = s_detail_template;
                                        //Generator generator_am = compiler.Compile(s_master_template);
                                        foreach (var i in ds.Item4)
                                        {
                                            index += 1;
                                            var bodyDetail = s_detail_template.Replace("[{{meter_id}}]", bodyTemplate);
                                            var temp       = FillToExTemplateWithObject(bodyDetail, i, arrTempCols, index);
                                            bodyItems += temp;
                                        }
                                        s_html = s_html.Replace(msg_render.col_tbody_key, bodyItems);
                                    }
                                    else
                                    {
                                        s_html = generator.Render(ds.Item4);
                                    }
                                }
                                break;

                            case "store":
                                string tbody = ds.Item2;

                                if (s_main_template.Contains(msg_render.col_tbody_key))
                                {
                                    s_html = s_main_template.Replace(msg_render.col_tbody_key, tbody);
                                }
                                else
                                {
                                    s_html = s_main_template + "<table>" + tbody + "</table>";
                                }

                                m_meter[] am2 = ds.Item5;
                                //if (am != null && (am.Length > 0 && s_master_template != ""))
                                //{
                                //    string[] masterTemplateValues = s_master_template.Split(new string[] { "<td>" }, StringSplitOptions.None).Where(o => o != "").Select(o => "").ToArray();
                                //    string s_master_template_def = string.Join("<td></td>", masterTemplateValues);
                                //    Generator generator_am = compiler.Compile(s_master_template);

                                //    foreach (var i in am)
                                //    {
                                //        string val = generator_am.Render(i);
                                //        if (string.IsNullOrWhiteSpace(val))
                                //            s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", s_master_template_def);
                                //        else
                                //            s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", val);
                                //    }
                                //}


                                if (am2 != null && (am2.Length > 0 && s_master_template != ""))
                                {
                                    string[]  masterTemplateValues  = s_master_template.Split(new string[] { "<td>" }, StringSplitOptions.None).Where(o => o != "").Select(o => "").ToArray();
                                    string    s_master_template_def = string.Join("<td></td>", masterTemplateValues);
                                    Generator generator_am          = compiler.Compile(s_master_template);
                                    var       arrsplitCols          = ExtractCols(s_master_template);
                                    bool      has_split_cols        = arrsplitCols.Length > 0;

                                    foreach (var i in am2)
                                    {
                                        string val = generator_am.Render(i);
                                        if (has_split_cols)
                                        {
                                            var tempBody = FillToTemplateWithObject(s_master_template, i, arrsplitCols);
                                            s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", tempBody);
                                        }
                                        else if (string.IsNullOrWhiteSpace(val))
                                        {
                                            s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", s_master_template_def);
                                        }
                                        else
                                        {
                                            s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", val);
                                        }
                                    }
                                }


                                break;
                            }

                            //FormatCompiler compiler = new FormatCompiler();
                            //Generator generator = compiler.Compile(s_detail_template);
                            //switch (api)
                            //{
                            //    default:
                            //        var arrTempCols = ExtractCols(s_detail_template);
                            //        if (arrTempCols.Length > 0)
                            //        {
                            //            string body = ExtracBody(s_detail_template);
                            //            string result = s_detail_template.Replace(body, "##bodyitems##");
                            //            string bodyItems = "";
                            //            int index = 0;
                            //            foreach (var obj in ds.Item4)
                            //            {
                            //                index += 1;
                            //                bodyItems += FillToExTemplateWithObject(body, obj, arrTempCols, index);
                            //            }
                            //            s_html = result.Replace("##bodyitems##", bodyItems);
                            //        }
                            //        else
                            //            s_html = generator.Render(ds.Item4);
                            //        break;
                            //    case "store":
                            //        string j_data = ds.Item2;
                            //        m_meter[] am = ds.Item5;

                            //       // j_data = @"[{""index_"":1, ""data_type"":1602001,""file_id"":53539,""dcu_id"":105353094,""device_id"":1501000425,""yyyyMMdd"":""04/01/2016"",""HHmmss"":""23:37"",""phase"":""_1pha"",""data"":""FIX_DAY"",""tech"":""PLC"",""factory"":""PSMART"",""meter_id"":1501000425,""time_chot"":160103,""time_read"":1601040010,""p_giao_tong"":30.79,""p_giao_bieu_1"":30.79,""p_giao_bieu_2"":0,""p_giao_bieu_3"":0,""p_giao_bieu_4"":0,""p_nhan_tong"":0,""p_nhan_bieu_1"":0,""p_nhan_bieu_2"":0,""p_nhan_bieu_3"":0,""p_nhan_bieu_4"":0}]";

                            //        var dt_Data = JsonConvert.DeserializeObject<dynamic[]>(j_data);
                            //        s_html = generator.Render(dt_Data);

                            //        if (am != null && (am.Length > 0 && s_master_template != ""))
                            //        {
                            //            string[] masterTemplateValues = s_master_template.Split(new string[] { "<td>" }, StringSplitOptions.None).Where(o => o != "").Select(o => "").ToArray();
                            //            string s_master_template_def = string.Join("<td></td>", masterTemplateValues);
                            //            Generator generator_am = compiler.Compile(s_master_template);
                            //            var arrsplitCols = ExtractCols(s_master_template);
                            //            bool has_split_cols = arrsplitCols.Length > 0;

                            //            foreach (var i in am)
                            //            {
                            //                string val = generator_am.Render(i);
                            //                if (has_split_cols)
                            //                {
                            //                    var tempBody = FillToTemplateWithObject(s_master_template, i, arrsplitCols);
                            //                    s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", tempBody);
                            //                }
                            //                else if (string.IsNullOrWhiteSpace(val))
                            //                    s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", s_master_template_def);
                            //                else
                            //                    s_html = s_html.Replace("[" + i.meter_id.ToString() + "]", val);
                            //            }
                            //        }
                            //        break;
                            //}//end template
                        }
                    }
                }

                var r = new Response();
                r.Contents = w =>
                {
                    StringBuilder s = new StringBuilder();

                    s.Append(
                        @"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
<head>
    <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>DanhSach</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
</head>");
                    s.Append("<body>");
                    s.Append(s_description);
                    s.Append(s_html);
                    s.Append("</body>");
                    s.Append("</html>");


                    byte[] bytes = Encoding.UTF8.GetBytes(s.ToString());
                    for (int i = 0; i < 10; ++i)
                    {
                        w.Write(bytes, 0, bytes.Length);
                        w.Flush();
                    }
                };
                string fileName = "danhsach_export.xls";
                r.Headers.Add("Content-Disposition", string.Format("attachment;filename={0}", fileName));
                return(r.AsAttachment(fileName, "application/vnd.ms-exce"));
            };



            Get["/{img_name}.jpg"] = x =>
            {
                string img_name = x.img_name;

                ObjectCache cache = MemoryCache.Default;
                string      data  = cache[img_name] as string;

                //byte[] myImageByteArray = null;
                //return Response.FromByteArray(myImageByteArray, "image/jpeg");

                //data:image/gif;base64,
                //byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
                byte[] bytes  = Convert.FromBase64String(data);
                Stream stream = new MemoryStream(bytes);

                return(Response.FromStream(stream, "image/jpeg"));
            };



            Get["/demo"] = x =>
            {
                var r = new Response();
                r.Contents = w =>
                {
                    StringBuilder s = new StringBuilder();
                    s.Append(@"<html xmlns:x=""urn: schemas - microsoft - com:office: excel"">");
                    s.Append("<head>");
                    s.Append(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=utf8"">");
                    s.Append("<!--[if gte mso 9]>");
                    s.Append("<xml>");
                    s.Append("<x:ExcelWorkbook>");
                    s.Append("<x:ExcelWorksheets>");
                    s.Append("<x:ExcelWorksheet>");
                    //this line names the worksheet
                    s.Append("<x:Name>gridlineTest</x:Name>");
                    s.Append("<x:WorksheetOptions>");
                    //these 2 lines are what works the magic
                    s.Append("<x:Panes>");
                    s.Append("</x:Panes>");
                    s.Append("</x:WorksheetOptions>");
                    s.Append("</x:ExcelWorksheet>");
                    s.Append("</x:ExcelWorksheets>");
                    s.Append("</x:ExcelWorkbook>");
                    s.Append("</xml>");
                    s.Append("<![endif]-->");
                    s.Append("</head>");
                    s.Append("<body>");
                    s.Append("<table>");
                    s.Append("<tr><td>ID</td><td>Name</td><td>Balance</td></tr>");
                    s.Append("<tr><td>1234</td><td>Al Bundy</td><td>45</td></tr>");
                    s.Append("<tr><td>9876</td><td>Homer Simpson</td><td>-129</td></tr>");
                    s.Append("<tr><td>5555</td><td>Peter Griffin</td><td>0</td></tr>");
                    s.Append("</table>");
                    s.Append("</body>");
                    s.Append("</html>");

                    byte[] bytes = Encoding.UTF8.GetBytes(s.ToString());
                    for (int i = 0; i < 10; ++i)
                    {
                        w.Write(bytes, 0, bytes.Length);
                        w.Flush();
                        //Thread.Sleep(500);
                    }
                };
                string fileName = "test2.xls";
                r.Headers.Add("Content-Disposition", string.Format("attachment;filename={0}", fileName));
                return(r.AsAttachment(fileName, "application/vnd.ms-exce"));
            };
        }
Exemplo n.º 33
0
        /// <summary>
        /// Send email.
        /// </summary>
        /// <param name="recipients"></param>
        /// <param name="carbonCopies"></param>
        /// <param name="blindCarbonCopies"></param>
        /// <param name="subject">Subject of email.</param>
        /// <param name="content">Email raw content</param>
        /// <param name="data">Data which should be used for formatting email.</param>
        /// <param name="bIsHtml"></param>
        /// <param name="bIsErrorSuppressed">Whether exception should be suppressed or not.</param>
        public void SendMail(MailAddress[] recipients, MailAddress[] carbonCopies, MailAddress[] blindCarbonCopies, string subject, string content, object data, bool bIsHtml, bool bIsErrorSuppressed)
        {
            var szMessageBuilder = new StringBuilder();

            szMessageBuilder.AppendLine("Sending email ...");
            szMessageBuilder.AppendLine($"Recipients: {string.Join(",", recipients.Select(x => x.Address))}");

            // Carbon copies has been specified.
            if (carbonCopies != null && carbonCopies.Length > 0)
            {
                szMessageBuilder.AppendLine($"Ccs: {carbonCopies.Select(x => x.Address)}");
            }

            // Blind carbon copies list has been defined.
            if (blindCarbonCopies != null && blindCarbonCopies.Length > 0)
            {
                szMessageBuilder.AppendLine($"Blind carbon copies: {string.Join(",", blindCarbonCopies.Select(x => x.Address))}");
            }
            szMessageBuilder.AppendLine($"Subject: {subject}");
            szMessageBuilder.AppendLine($"Content: {content}");

            // Data is defined.
            if (data != null)
            {
                szMessageBuilder.AppendLine($"Data: {JsonConvert.SerializeObject(data)}");
            }
            _log.Info(szMessageBuilder);

            using (var smtpClient = new SmtpClient())
            {
                try
                {
                    var mailMessage = new MailMessage();
                    mailMessage.Subject = subject;


                    //#if DEBUG
                    //                    // In debugging mode. Just send email to a specific person.

                    //                        mailMessage.To.Add(new MailAddress("*****@*****.**"));
                    //#else

                    // Add recipients.
                    foreach (var recipient in recipients)
                    {
                        mailMessage.To.Add(recipient);
                    }

                    // Add carbon copies.
                    if (carbonCopies != null)
                    {
                        foreach (var carbonCopy in carbonCopies)
                        {
                            mailMessage.CC.Add(carbonCopy);
                        }
                    }

                    // Add blind carbon copy.
                    if (blindCarbonCopies != null)
                    {
                        foreach (var blindCarbonCopy in blindCarbonCopies)
                        {
                            mailMessage.Bcc.Add(blindCarbonCopy);
                        }
                    }

                    //#endif

                    if (data != null)
                    {
                        var formatCompiler = new FormatCompiler();
                        var generator      = formatCompiler.Compile(content);
                        mailMessage.Body = generator.Render(data);
                    }
                    else
                    {
                        mailMessage.Body = content;
                    }

                    mailMessage.IsBodyHtml = bIsHtml;

                    smtpClient.Send(mailMessage);
                }
                catch (Exception exception)
                {
                    _log.Error(exception.Message, exception);
                }
            }
        }
 public void TestCompile_IfElif_ElifFalse_PrintsNothing()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if First}}First{{#elif Second}}Second{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new { First = false, Second = false });
     Assert.AreEqual("BeforeAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_IfElse_EvaluatesToFalse_PrintsElse()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Yay{{#else}}Nay{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(false);
     Assert.AreEqual("BeforeNayAfter", result, "The wrong text was generated.");
 }
        public void ServiceHost_ClientInputRecieved(object sender, ClientInputMessage e)
        {
            Trace.WriteLine("ClientInputRecieved Recieved User Id : " + e.idUsuario, "Warning");
            try
            {
                /*Crear Blob desde un Stream*/
                // Se obtiene la cuenta de almacenamiento
                storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnectionString"));

                // Se crea el cliente de blobs
                blobClient = storageAccount.CreateCloudBlobClient();

                // Obtencion del container
                container = blobClient.GetContainerReference(VariablesConfiguracion.containerName);

                Int64 subid = 1;

                String mustacheTemplateStr = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/mustacheCloud.txt");

                //Template para generar los MDL
                FormatCompiler compiler     = new FormatCompiler();
                Generator      generatorMDL = compiler.Compile(mustacheTemplateStr);

                //Obtener parametros del cliente
                SimulacionParameters parametros = JsonConvert.DeserializeObject <SimulacionParameters>(e.message);

                //Barrido paramétrico
                //Especificar número de parámetros, n
                Int32 n = parametros.reacciones.Count(r => r.rate != null);
                if (n > 0)
                {
                    //Inicializo vector de inicios, fines y steps
                    LinkedList <Double> inicios = new LinkedList <Double>();
                    LinkedList <Double> fines   = new LinkedList <Double>();
                    LinkedList <Double> steps   = new LinkedList <Double>();
                    foreach (var reaccion in parametros.reacciones.FindAll(r => r.rate != null))
                    {
                        var inicio = reaccion.rate.rateInicio;
                        var fin    = reaccion.rate.rateFin;
                        var step   = reaccion.rate.rateStep;
                        inicios.AddLast(inicio);
                        fines.AddLast(fin);
                        steps.AddLast(step);
                    }

                    var iniciosArray = inicios.ToArray();
                    var finesArray   = fines.ToArray();
                    var stepsArray   = steps.ToArray();


                    //Defino vector lógico L para hacer barrido selectivo
                    Int32[] vectorLogico = new Int32[n];
                    for (int i = 0; i < n; i++)
                    {
                        //vectorLogico[i] = i < 5 ? 1 : 100;
                        vectorLogico[i] = 1000;
                    }

                    // Inicialización del vector j
                    Double[] j = new Double[n];
                    for (var k = 0; k < n; k++)
                    {
                        if (k == vectorLogico[k])
                        {
                            iniciosArray[k] += stepsArray[k];
                        }
                        j[k] = iniciosArray[k];
                    }

                    LinkedList <Double[]> jotas = new LinkedList <double[]>();
                    //Barrido parametrico
                    Int32 z = n - 1;
                    while (z >= 0)
                    {
                        if ((j[z] - finesArray[z]) * stepsArray[z] > 0)
                        {
                            j[z] = iniciosArray[z];
                            z--;
                        }
                        else
                        {
                            jotas.AddLast((double[])j.Clone()); //Para ver las combinaciones que creo
                            var    auxId  = subid;
                            Thread thread = new Thread(() => CrearMDL(e, auxId, (double[])j.Clone(), parametros, generatorMDL));
                            thread.Start();
                            //CrearMDL(e, subid, (double[])j.Clone(), parametros, generatorMDL);
                            z = n - 1;
                            subid++;
                        }
                        if (z >= 0)
                        {
                            j[z] += stepsArray[z];
                            if (z == vectorLogico[z])
                            {
                                j[z] += stepsArray[z];
                            }
                        }
                    }
                }
                else
                {
                    List <Double> valores = new List <double>();
                    CrearMDL(e, 0, valores.ToArray(), parametros, generatorMDL);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                throw;
            }
        }
 public void TestCompile_IfNewLineEndIfNewLineContentNewLineIfNewLineEndIf_PrintsContent()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = @"{{#if this}}
     {{/if}}
     Content
     {{#if this}}
     {{/if}}";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     const string expected = @"Content";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
 public void TestCompile_Each_Index_PrintsIndexOfItem()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "<ul>{{#each this}}<li value=\"{{this}}\">Item {{#index}}</li>{{/each}}</ul>";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new int[] { 1, 2, 3 });
     const string expected = @"<ul><li value=""1"">Item 0</li><li value=""2"">Item 1</li><li value=""3"">Item 2</li></ul>";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
Exemplo n.º 39
0
        /// <summary>
        /// Запуск задачи
        /// </summary>
        /// <param name="parameters">Провайдер параметров</param>
        public void Run(ParameterProvider parameters)
        {
            System.Threading.Thread.Sleep(5000);
            FormatCompiler compiler = new FormatCompiler();

            if (string.IsNullOrWhiteSpace(_template) && !string.IsNullOrWhiteSpace(_templateFile))
            {
                _template = File.ReadAllText(parameters.Parse(_templateFile).First());
            }

            //Компилция шаблона
            Generator generator = compiler.Compile(_template);

            //В шаблоне можно использовать все параметры, заданные в конфигурации.
            var _templateParams = new Dictionary <string, object>();

            foreach (var param in parameters.GetParameters())
            {
                _templateParams.Add(param.Key, param.Value);
            }


            foreach (var param in _paramsDescription)
            {
                object value    = null;
                var    filePath = parameters.Parse(param.FilePath).First();
                var    enc      = String.IsNullOrEmpty(param.Encoding) ? System.Text.Encoding.UTF8 : System.Text.Encoding.GetEncoding(param.Encoding);

                if (File.Exists(filePath))
                {
                    switch (param.Mode)
                    {
                    case "text":
                        if (param.HasHeaders)
                        {
                            value = string.Join("\n", File.ReadAllLines(filePath).Skip(1));
                        }
                        else
                        {
                            value = File.ReadAllText(filePath, enc);
                        }
                        break;

                    case "csv":
                        value = File.ReadAllLines(filePath, enc).Skip(param.HasHeaders ? 1 : 0).Select(x => x.Split(';')).ToList();
                        break;

                    case "tsv":
                        value = File.ReadAllLines(filePath, enc).Skip(param.HasHeaders ? 1 : 0).Select(x => x.Split('\t')).ToList();
                        break;

                    default:
                        value = File.ReadAllText(filePath, enc);
                        break;
                    }
                }



                _templateParams.Add(param.Name, value);
            }

            parameters.AddParameter(_outputParam, generator.Render(_templateParams));
        }
 public void TestCompile_Each_PopulatedCollection_PrintsContentForEach()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#each this}}{{this}}{{/each}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new int[] { 1, 2, 3 });
     Assert.AreEqual("Before123After", result, "The wrong text was generated.");
 }
 public void TestCompile_KeyInParent_LooksUpKeyInParent()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#with Address}}{{FirstName}} from {{City}}{{/with}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new
     {
         FirstName = "Bob",
         Address = new
         {
             City = "Philadelphia",
         }
     });
     string expected = "Bob from Philadelphia";
     Assert.AreEqual(expected, actual, "The wrong message was generated.");
 }
        public void TestCompile_ExitContext_RemoveContext()
        {
            FormatCompiler compiler = new FormatCompiler();
            Context[] context = null;
            compiler.PlaceholderFound += (o, e) =>
            {
                context = e.Context;
            };
            compiler.Compile(@"{{#with Address}}{{/with}}{{FirstName}}");

            Assert.IsNotNull(context, "The context was not set.");
            Assert.AreEqual(1, context.Length, "The context did not contain the right number of items.");

            Assert.AreEqual(String.Empty, context[0].TagName, "The top-most context had the wrong tag type.");
        }
 public void TestCompile_KeyWithFormat_AppliesFormatting()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{When:yyyyMMdd}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { When = new DateTime(2012, 01, 31) });
     Assert.AreEqual("Hello, 20120131!!!", result, "The wrong text was generated.");
 }
        public void TestCompile_FindsPlaceholders_ProvidesContext()
        {
            FormatCompiler compiler = new FormatCompiler();
            Context[] context = null;
            compiler.PlaceholderFound += (o, e) =>
            {
                context = e.Context;
            };
            compiler.Compile(@"{{#with Address}}{{ZipCode}}{{/with}}");

            Assert.IsNotNull(context, "The context was not set.");
            Assert.AreEqual(2, context.Length, "The context did not contain the right number of items.");

            Assert.AreEqual(String.Empty, context[0].TagName, "The top-most context had the wrong tag type.");
            Assert.AreEqual("with", context[1].TagName, "The bottom context had the wrong tag type.");

            Assert.AreEqual(0, context[0].Parameters.Length, "The top-most context had the wrong number of parameters.");
            Assert.AreEqual(1, context[1].Parameters.Length, "The bottom context had the wrong number of parameters.");
            Assert.AreEqual("Address", context[1].Parameters[0].Argument, "The bottom context had the wrong argument.");
        }
 public void TestCompile_MissingDefaultParameter_ProvidesDefault()
 {
     FormatCompiler compiler = new FormatCompiler();
     compiler.RegisterTag(new DefaultTagDefinition(), true);
     const string format = @"{{#default}}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual("123", result, "The wrong text was generated.");
 }
 public void TestCompile_FindsPlaceholders_RecordsPlaceholders()
 {
     FormatCompiler compiler = new FormatCompiler();
     HashSet<string> keys = new HashSet<string>();
     compiler.PlaceholderFound += (o, e) =>
     {
         keys.Add(e.Key);
     };
     compiler.Compile(@"{{FirstName}} {{LastName}}");
     string[] expected = new string[] { "FirstName", "LastName" };
     string[] actual = keys.OrderBy(s => s).ToArray();
     CollectionAssert.AreEqual(expected, actual, "Not all placeholders were found.");
 }
 public void TestCompile_FindsVariables_RecordsVariables()
 {
     FormatCompiler compiler = new FormatCompiler();
     HashSet<string> variables = new HashSet<string>();
     compiler.VariableFound += (o, e) =>
     {
         variables.Add(e.Name);
     };
     compiler.Compile(@"{{@FirstName}}{{@LastName}}");
     string[] expected = new string[] { "FirstName", "LastName" };
     string[] actual = variables.OrderBy(s => s).ToArray();
     CollectionAssert.AreEqual(expected, actual, "Not all variables were found.");
 }
Exemplo n.º 48
0
 public void Dispose()
 {
     compiler  = null;
     generator = null;
 }