public void SetUp() { configurationMock = MockRepository.GenerateMock<IConfiguration>(); projectFileManagerMock = MockRepository.GenerateMock<IProjectFileManager>(); depencyInjectionManagerMock = MockRepository.GenerateMock<IDepencyInjectionManager>(); fileSystemMock = MockRepository.GenerateMock<IFileSystem>(); var templateEngine = new TemplateEngine(fileSystemMock); serviceGenerator = new ServiceGenerator(templateEngine, configurationMock, projectFileManagerMock, depencyInjectionManagerMock); }
public void SetUp() { configurationMock = MockRepository.GenerateMock<IConfiguration>(); projectFileManagerMock = MockRepository.GenerateMock<IProjectFileManager>(); depencyInjectionManagerMock = MockRepository.GenerateMock<IDepencyInjectionManager>(); fileSystemMock = MockRepository.GenerateMock<IFileSystem>(); webConfigHelperMock = MockRepository.GenerateMock<IWebConfigHelper>(); var templateEngine = new TemplateEngine(fileSystemMock); securityGenerator = new SecurityGenerator(configurationMock, templateEngine, projectFileManagerMock, depencyInjectionManagerMock, fileSystemMock, webConfigHelperMock); }
public void SetUp() { configurationMock = MockRepository.GenerateMock<IConfiguration>(); projectFileManagerMock = MockRepository.GenerateMock<IProjectFileManager>(); depencyInjectionManagerMock = MockRepository.GenerateMock<IDepencyInjectionManager>(); fileSystemMock = MockRepository.GenerateMock<IFileSystem>(); entityManagerMock = MockRepository.GenerateMock<IEntityManager>(); autoMapperHelperMock = MockRepository.GenerateMock<IAutoMapperHelper>(); var templateEngine = new TemplateEngine(fileSystemMock); uiGenerator = new UiGenerator(entityManagerMock, templateEngine, configurationMock, projectFileManagerMock, depencyInjectionManagerMock, autoMapperHelperMock, fileSystemMock); }
public void ElseTrue() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#if(true) indeed #else no #end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual(" indeed ", result); }
// Get the rooms with given conditions. private async Task <DialogTurnResult> GetMeetingRooms(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await Accessor.GetAsync(sc.Context); state.MeetingInfo.UnconfirmedMeetingRoom = !string.IsNullOrEmpty(state.MeetingInfo.MeetingRoomName) ? await SearchService.GetMeetingRoomAsync(state.MeetingInfo.MeetingRoomName) : await SearchService.GetMeetingRoomAsync(state.MeetingInfo.Building, state.MeetingInfo.FloorNumber.GetValueOrDefault()); if (state.MeetingInfo.UnconfirmedMeetingRoom.Count == 0) { if (!string.IsNullOrEmpty(state.MeetingInfo.MeetingRoomName)) { var tokens = new { MeetingRoom = state.MeetingInfo.MeetingRoomName }; var activity = TemplateEngine.GenerateActivityForLocale(FindMeetingRoomResponses.MeetingRoomNotFoundByName, tokens); await sc.Context.SendActivityAsync(activity); state.MeetingInfo.MeetingRoomName = null; } else { var tokens = new { state.MeetingInfo.Building, state.MeetingInfo.FloorNumber, DateTime = SpeakHelper.ToSpeechMeetingTime(TimeConverter.ConvertUtcToUserTime((DateTime)state.MeetingInfo.StartDateTime, state.GetUserTimeZone()), state.MeetingInfo.AllDay == true, DateTime.UtcNow > state.MeetingInfo.StartDateTime), }; var activity = TemplateEngine.GenerateActivityForLocale(FindMeetingRoomResponses.MeetingRoomNotFoundByBuildingAndFloor, tokens); await sc.Context.SendActivityAsync(activity); if (state.MeetingInfo.FloorNumber.GetValueOrDefault() == 0) { state.MeetingInfo.Building = null; } state.MeetingInfo.FloorNumber = null; } return(await sc.ReplaceDialogAsync(Actions.RecreateMeetingRoom, cancellationToken : cancellationToken)); } return(await sc.NextAsync(cancellationToken : cancellationToken)); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
private async Task <DialogTurnResult> AfterConfirmEmail(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await Accessor.GetAsync(sc.Context); var options = sc.Options as FindContactDialogOptions; var confirmedPerson = state.MeetingInfo.ContactInfor.ConfirmedContact; var result = sc.Result as string; // Highest probability if (!(state.InitialIntent == CalendarLuis.Intent.CheckAvailability) && (string.IsNullOrEmpty(result) || !result.Equals(nameof(AfterSelectEmail)))) { var name = confirmedPerson.DisplayName; var userString = string.Empty; if (!name.Equals(confirmedPerson.Emails.First().Address ?? confirmedPerson.UserPrincipalName)) { userString = name + " (" + (confirmedPerson.Emails.First().Address ?? confirmedPerson.UserPrincipalName) + ")"; } else { userString = confirmedPerson.Emails.First().Address ?? confirmedPerson.UserPrincipalName; } var activity = TemplateEngine.GenerateActivityForLocale(FindContactResponses.PromptOneNameOneAddress, new { User = userString }); await sc.Context.SendActivityAsync(activity); } var attendee = new EventModel.Attendee { DisplayName = confirmedPerson.DisplayName, Address = confirmedPerson.Emails.First().Address, UserPrincipalName = confirmedPerson.UserPrincipalName }; if (state.MeetingInfo.ContactInfor.Contacts.All(r => r.Address != attendee.Address)) { state.MeetingInfo.ContactInfor.Contacts.Add(attendee); } return(await sc.EndDialogAsync()); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
public async Task <DialogTurnResult> PromptToDelete(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await EmailStateAccessor.GetAsync(sc.Context); var skillOptions = (EmailSkillDialogOptions)sc.Options; var message = state.Message?.FirstOrDefault(); if (message != null) { var nameListString = DisplayHelper.ToDisplayRecipientsString_Summay(message.ToRecipients); var senderIcon = await GetUserPhotoUrlAsync(sc.Context, message.Sender.EmailAddress); var emailCard = new EmailCardData { Subject = message.Subject, EmailContent = message.BodyPreview, Sender = message.Sender.EmailAddress.Name, EmailLink = message.WebLink, ReceivedDateTime = message?.ReceivedDateTime == null ? CommonStrings.NotAvailable : message.ReceivedDateTime.Value.UtcDateTime.ToDetailRelativeString(state.GetUserTimeZone()), Speak = SpeakHelper.ToSpeechEmailDetailOverallString(message, state.GetUserTimeZone()), SenderIcon = senderIcon }; emailCard = await ProcessRecipientPhotoUrl(sc.Context, emailCard, message.ToRecipients); var speech = SpeakHelper.ToSpeechEmailSendDetailString(message.Subject, nameListString, message.BodyPreview); var prompt = TemplateEngine.GenerateActivityForLocale( DeleteEmailResponses.DeleteConfirm, new { emailInfo = speech, emailDetails = emailCard }); var retry = TemplateEngine.GenerateActivityForLocale(EmailSharedResponses.ConfirmSendFailed); return(await sc.PromptAsync(Actions.TakeFurtherAction, new PromptOptions { Prompt = prompt as Activity, RetryPrompt = retry as Activity })); } skillOptions.SubFlowMode = true; return(await sc.BeginDialogAsync(Actions.UpdateSelectMessage, skillOptions)); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
public async Task <DialogTurnResult> ReplyEmail(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await EmailStateAccessor.GetAsync(sc.Context); sc.Context.TurnState.TryGetValue(StateProperties.APIToken, out var token); var message = state.Message.FirstOrDefault(); var service = ServiceManager.InitMailService(token as string, state.GetUserTimeZone(), state.MailSourceType); // reply user message. if (message != null) { var content = state.Content.Equals(EmailCommonStrings.EmptyContent) ? string.Empty : state.Content; await service.ReplyToMessageAsync(message.Id, content); } var emailCard = new EmailCardData { Subject = state.Subject.Equals(EmailCommonStrings.EmptySubject) ? null : state.Subject, EmailContent = state.Content.Equals(EmailCommonStrings.EmptyContent) ? null : state.Content, }; emailCard = await ProcessRecipientPhotoUrl(sc.Context, emailCard, state.FindContactInfor.Contacts); var stringToken = new StringDictionary { { "Subject", state.Subject }, }; var reply = TemplateEngine.GenerateActivityForLocale( EmailSharedResponses.SentSuccessfully, new { subject = state.Subject, emailDetails = emailCard }); await sc.Context.SendActivityAsync(reply); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } await ClearConversationState(sc); return(await sc.EndDialogAsync(true)); }
public async Task <DialogTurnResult> AskGoBackToStartConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await ToDoStateAccessor.GetAsync(sc.Context); var taskCount = Math.Min(state.PageSize, state.AllTasks.Count); Activity prompt; Activity retryPrompt; if (state.Tasks.Count <= 1) { prompt = TemplateEngine.GenerateActivityForLocale(ShowToDoResponses.GoBackToStartPromptForSingleTask, new { ListType = state.ListType, TaskCount = taskCount }); retryPrompt = TemplateEngine.GenerateActivityForLocale(ShowToDoResponses.GoBackToStartForSingleTaskConfirmFailed, new { ListType = state.ListType, TaskCount = taskCount }); } else { prompt = TemplateEngine.GenerateActivityForLocale(ShowToDoResponses.GoBackToStartPromptForTasks, new { ListType = state.ListType, TaskCount = taskCount }); retryPrompt = TemplateEngine.GenerateActivityForLocale(ShowToDoResponses.GoBackToStartForTasksConfirmFailed, new { ListType = state.ListType, TaskCount = taskCount }); } return(await sc.PromptAsync(Actions.ConfirmPrompt, new PromptOptions() { Prompt = prompt, RetryPrompt = retryPrompt })); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
public void EmailCommentToBlogAuthor(FeedbackItem comment) { if (String.IsNullOrEmpty(Blog.Email) || comment.FeedbackType == FeedbackType.PingTrack || Context.User.IsAdministrator()) { return; } string fromEmail = comment.Email; if (String.IsNullOrEmpty(fromEmail)) { fromEmail = null; } var commentForTemplate = new { blog = Blog, comment = new { author = comment.Author, title = comment.Title, source = Url.FeedbackUrl(comment).ToFullyQualifiedUrl(Blog), email = fromEmail ?? "none given", authorUrl = comment.SourceUrl, ip = comment.IpAddress, // we're sending plain text email by default, but body includes <br />s for crlf body = (comment.Body ?? string.Empty).Replace("<br />", Environment.NewLine).Replace("<br />", Environment. NewLine) }, spamFlag = comment.FlaggedAsSpam ? "Spam Flagged " : "" }; ITextTemplate template = TemplateEngine.GetTemplate("CommentReceived"); string message = template.Format(commentForTemplate); string subject = String.Format(CultureInfo.InvariantCulture, Resources.Email_CommentVia, comment.Title, Blog.Title); if (comment.FlaggedAsSpam) { subject = "[SPAM Flagged] " + subject; } string from = EmailProvider.UseCommentersEmailAsFromAddress ? (fromEmail ?? EmailProvider.AdminEmail) : EmailProvider.AdminEmail; EmailProvider.Send(Blog.Email, from, subject, message); }
/// <summary> /// This takes a filename and return an instance of the view ready to be used. /// If the file does not exist, an exception is raised /// The cache is checked to see if the file has already been compiled, and it had been /// a check is made to see that the compiled instance is newer then the file's modification date. /// If the file has not been compiled, or the version on disk is newer than the one in memory, a new /// version is compiled. /// Finally, an instance is created and returned /// </summary> public NHamlMonoRailView GetCompiledScriptInstance(string file, IControllerContext controllerContext) { // normalize filename - replace / or \ to the system path seperator var filename = file.Replace('/', Path.DirectorySeparatorChar) .Replace('\\', Path.DirectorySeparatorChar); filename = EnsurePathDoesNotStartWithDirectorySeparator(filename); Trace.WriteLine(string.Format("Getting compiled instance of {0}", filename)); GetTemplate(controllerContext, new [] { filename }); var template = TemplateEngine.Compile(file).CreateInstance(); return((NHamlMonoRailView)template); }
public virtual void SetUp() { PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase); Helpers = new HelperDictionary(); var services = new StubMonoRailServices { UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine()), UrlTokenizer = new DefaultUrlTokenizer() }; var urlInfo = new UrlInfo( "example.org", "test", "/TestBrail", "http", 80, "http://test.example.org/test_area/test_controller/test_action.tdd", Area, ControllerName, Action, "tdd", "no.idea"); StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services, urlInfo); StubEngineContext.AddService<IUrlBuilder>(services.UrlBuilder); StubEngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer); ViewComponentFactory = new DefaultViewComponentFactory(); ViewComponentFactory.Service(StubEngineContext); ViewComponentFactory.Initialize(); StubEngineContext.AddService<IViewComponentFactory>(ViewComponentFactory); ControllerContext = new ControllerContext { Helpers = Helpers, PropertyBag = PropertyBag }; StubEngineContext.CurrentControllerContext = ControllerContext; Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext); Helpers["formhelper"] = Helpers["form"] = new FormHelper(StubEngineContext); Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext); Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext); var loader = new FileAssemblyViewSourceLoader("Views"); _monoRailViewEngine = new NHamlMonoRailViewEngine(); _monoRailViewEngine.TemplateEngine.Options.TemplateCompiler = new CSharp3TemplateCompiler(); _monoRailViewEngine.SetViewSourceLoader(loader); _templateEngine = _monoRailViewEngine.TemplateEngine; _templateEngine.Options.TemplateBaseType = typeof( NHamlMonoRailView ); ViewComponentFactory.Inspect(GetType().Assembly); }
public void TestCertPaid(Entities.Context.OrderDetail orderDetail) { var template = MailTemplateService.GetTemplate(MailTemplates.TestCertPaid, orderDetail.Order.User.FullName); var body = TemplateEngine.GetText( template.Description, new { TestCert = H.Anchor("/order/testcertificates", orderDetail.UserTest.Test.Name).AbsoluteHref(), }); Send(info, MailAddress(orderDetail.Order.User), body, template.Name); Send(info, siteCertOrders, GetOrderCmsAnchor(orderDetail.Order).ToString() , "Сертификат оплачен"); }
protected async Task <DialogTurnResult> PromptToReshow(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var activity = TemplateEngine.GenerateActivityForLocale(ShowEmailResponses.ReadOutMore); return(await sc.PromptAsync(Actions.Prompt, new PromptOptions { Prompt = activity as Activity })); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
private static string UpdateStatus(User user, Group g, string template) { var dateText = GetDateText(g); var courseUrl = GetCourseUrl(g); var message = TemplateEngine.GetText(template, new { CourseName = StringUtils.AngleBrackets(g.Course.WebName), Date = dateText, CourseUrl = courseUrl }); PostStatusUpdate(user, message); return(message); }
public void TestTemplateRef() { var engine = new TemplateEngine().AddFile(GetExampleFilePath("TemplateRef.lg")); var scope = new { time = "morning", name = "Dong Lei" }; Assert.AreEqual(engine.EvaluateTemplate("Hello", scope), "Good morning Dong Lei"); Assert.AreEqual(engine.EvaluateTemplate("Hello2", scope), "Good morning Dong Lei"); Assert.AreEqual(engine.EvaluateTemplate("Hello3", scope), "Good morning Dong Lei"); }
public void Config(TemplateEngine template) { try { var config = System.Config; var data = JToken.FromObject(config); template.Context["config_data"] = data.ToString(Formatting.Indented); WriteResponse(template); } catch (Exception e) { HandleError(e); } }
public void write_to_template_can_be_transformed_thanks_to_SetWriteTransform() { var c = new GlobalContext(); c.Register("Model", new[] { "This", "will", "be", "in uppercase" }); var e = new TemplateEngine(c); e.SetWriteTransform((s, sb) => sb.Append(s.ToUpperInvariant())); var r = e.Process("<%foreach txt in Model {%> - <%=txt%><%}%> like '<% $writer.Write( 'this' ) %>' but not <% $writer.WriteRaw( 'using WriteRaw' ) %>."); r.ErrorMessage.Should().BeNull(); r.Script.Should().NotBeNull(); r.Text.Should().Be(" - THIS - WILL - BE - IN UPPERCASE like 'THIS' but not using WriteRaw."); }
private static void CreateCode(string strAuthor, string mName, string mPath, string mTemplate) { DateTime dt = DateTime.Now; TemplateEngine.TemplateBasePath = "Assets/Editor/UITool/Template/"; Dictionary <string, string> valueDic = new Dictionary <string, string>(); valueDic["Author"] = strAuthor; valueDic["CreateDate"] = string.Format("{0}.{1}.{2}", dt.Year, dt.Month, dt.Day); valueDic["moduleName"] = mName; TemplateEngine.CreateCodeFile(mPath.Replace("${moduleName}", mName), mTemplate, valueDic); TemplateEngine.TemplateBasePath = null; }
public void template_with_WriteRaw() { var c = new GlobalContext(); c.Register("Model", new[] { "This", "will", "be", "in uppercase" }); var e = new TemplateEngine(c); e.SetWriteTransform((s, sb) => sb.Append(s.ToUpperInvariant())); var r = e.Process("<%= 'a' + Model.Length %>|<% $writer.WriteRaw( 'a' + Model.Length ) %>."); r.ErrorMessage.Should().BeNull(); r.Script.Should().NotBeNull(); r.Text.Should().Be("A4|a4."); }
private async Task <DialogTurnResult> AfterUpdateUserName(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var userInput = sc.Result as string; var state = await Accessor.GetAsync(sc.Context); var currentRecipientName = state.MeetingInfo.ContactInfor.CurrentContactName; var options = (FindContactDialogOptions)sc.Options; if (string.IsNullOrEmpty(userInput) && options.UpdateUserNameReason != FindContactDialogOptions.UpdateUserNameReasonType.Initialize) { var activity = TemplateEngine.GenerateActivityForLocale(FindContactResponses.UserNotFoundAgain, new { Source = state.EventSource == EventSource.Microsoft ? "Outlook Calendar" : "Google Calendar", UserName = currentRecipientName }); await sc.Context.SendActivityAsync(activity); return(await sc.EndDialogAsync()); } if (!string.IsNullOrEmpty(userInput) && state.MeetingInfo.ContactInfor.CurrentContactName != null && IsEmail(userInput)) { state.MeetingInfo.ContactInfor.UnconfirmedContact.Add(new CustomizedPerson() { DisplayName = state.MeetingInfo.ContactInfor.CurrentContactName, Emails = new List <ScoredEmailAddress>() { new ScoredEmailAddress() { Address = userInput } } }); return(await sc.EndDialogAsync()); } state.MeetingInfo.ContactInfor.CurrentContactName = string.IsNullOrEmpty(userInput) ? state.MeetingInfo.ContactInfor.CurrentContactName : userInput; return(await sc.NextAsync()); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
private async Task <DialogTurnResult> ShowEventsList(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken)) { try { var state = await Accessor.GetAsync(sc.Context); var options = sc.Options as ShowMeetingsDialogOptions; // no meeting if (!state.ShowMeetingInfo.ShowingMeetings.Any()) { var activity = TemplateEngine.GenerateActivityForLocale(SummaryResponses.ShowNoMeetingMessage); await sc.Context.SendActivityAsync(activity); state.Clear(); return(await sc.EndDialogAsync(true)); } if (options != null && options.Reason == ShowMeetingReason.ShowNextMeeting) { return(await sc.BeginDialogAsync(Actions.ShowNextEvent, options)); } else if (state.ShowMeetingInfo.ShowingMeetings.Count == 1) { return(await sc.BeginDialogAsync(Actions.Read, options)); } else if (options != null && (options.Reason == ShowMeetingReason.FirstShowOverview || options.Reason == ShowMeetingReason.ShowOverviewAfterPageTurning)) { return(await sc.BeginDialogAsync(Actions.ShowEventsOverview, options)); } else if (options != null && options.Reason == ShowMeetingReason.ShowOverviewAgain) { return(await sc.BeginDialogAsync(Actions.ShowEventsOverviewAgain, options)); } return(await sc.NextAsync()); } catch (SkillException ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
public void TestBasicTemplateRefWithParameters() { var engine = new TemplateEngine().AddFile(GetExampleFilePath("6.lg")); string evaled = engine.EvaluateTemplate("welcome", null).ToString(); Assert.IsTrue(evaled == "Hi DongLei :)" || evaled == "Hey DongLei :)" || evaled == "Hello DongLei :)"); evaled = engine.EvaluateTemplate("welcome", new { userName = "******" }).ToString(); Assert.IsTrue(evaled == "Hi DL :)" || evaled == "Hey DL :)" || evaled == "Hello DL :)"); }
private async Task <DialogTurnResult> PromptForNameAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // If we have been provided a input data structure we pull out provided data as appropriate // and make a decision on whether the dialog needs to prompt for anything. if (stepContext.Options is SampleActionInput actionInput && !string.IsNullOrEmpty(actionInput.Name)) { // We have Name provided by the caller so we skip the Name prompt. return(await stepContext.NextAsync(actionInput.Name, cancellationToken)); } var prompt = TemplateEngine.GenerateActivityForLocale("NamePrompt"); return(await stepContext.PromptAsync(DialogIds.NamePrompt, new PromptOptions { Prompt = prompt }, cancellationToken)); }
public void TestIsTemplateFunction() { var engine = new TemplateEngine().AddFile(GetExampleFilePath("IsTemplate.lg")); var evaled = engine.EvaluateTemplate("template2", new { templateName = "template1" }); Assert.AreEqual("template template1 exists", evaled); evaled = engine.EvaluateTemplate("template2", new { templateName = "wPhrase" }); Assert.AreEqual("template wPhrase exists", evaled); evaled = engine.EvaluateTemplate("template2", new { templateName = "xxx" }); Assert.AreEqual("template xxx does not exist", evaled); }
public async Task Test_Intro_Message() { await GetTestFlow() .Send(new Activity() { Type = ActivityTypes.ConversationUpdate, MembersAdded = new List <ChannelAccount>() { new ChannelAccount("user") } }) .AssertReply(TemplateEngine.GenerateActivityForLocale("IntroText")) .StartTestAsync(); }
static void Main(string[] args) { TemplateEngine.IsDebug = false; TemplateEngine.Init(new HashSet <string> { "Common.dll" }); //BaseTest(); //IfTest(); //ElseIfTest(); //EachTest(); //IncludeTest(); //LayoutTest(); UsingTest(); }
public virtual void SetUp() { PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase); Helpers = new HelperDictionary(); var services = new StubMonoRailServices { UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine()), UrlTokenizer = new DefaultUrlTokenizer() }; var urlInfo = new UrlInfo( "example.org", "test", "/TestBrail", "http", 80, "http://test.example.org/test_area/test_controller/test_action.tdd", Area, ControllerName, Action, "tdd", "no.idea"); StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services, urlInfo); StubEngineContext.AddService <IUrlBuilder>(services.UrlBuilder); StubEngineContext.AddService <IUrlTokenizer>(services.UrlTokenizer); ViewComponentFactory = new DefaultViewComponentFactory(); ViewComponentFactory.Service(StubEngineContext); ViewComponentFactory.Initialize(); StubEngineContext.AddService <IViewComponentFactory>(ViewComponentFactory); ControllerContext = new ControllerContext { Helpers = Helpers, PropertyBag = PropertyBag }; StubEngineContext.CurrentControllerContext = ControllerContext; Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext); Helpers["formhelper"] = Helpers["form"] = new FormHelper(StubEngineContext); Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext); Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext); var loader = new FileAssemblyViewSourceLoader("Views"); _monoRailViewEngine = new NHamlMonoRailViewEngine(); _monoRailViewEngine.TemplateEngine.Options.TemplateCompiler = new CSharp3TemplateCompiler(); _monoRailViewEngine.SetViewSourceLoader(loader); _templateEngine = _monoRailViewEngine.TemplateEngine; _templateEngine.Options.TemplateBaseType = typeof(NHamlMonoRailView); ViewComponentFactory.Inspect(GetType().Assembly); }
public void can_handle_return_values_from_a_method(string methodName, string returnValue) { //Arrange var sut = new TemplateEngine(GetTemplateDataModelDummyWithMethods(), "<TagName>${" + methodName + "}</TagName>"); //SUT = [S]ystem [U]nder [T]est string ShouldReturnString = "<TagName>" + returnValue + "</TagName>"; //Act string ReturnString = sut.CreateStringFromTemplate(); //Assert Assert.AreEqual(ShouldReturnString, ReturnString); }
public virtual void SendWelcomeMail(string name, string password, string email) { var model = new { From = FromAddress, To = email, Name = name, Password = password, LogOnUrl = "http://mycompany.com/logon" }; var mail = TemplateEngine.Execute(SendWelcomeMailTemplateName, model); Sender.Send(mail); }
public void Can_a_template_with_escaped_brackets_render_correctly(string template, string expected) { //given var data = new { Name = "Charlie Brown", }; //when string actual = new TemplateEngine(template).Merge(data); //then Assert.Equal(expected, actual); }
private async Task <DialogTurnResult> AfterConfirmNumber(WaterfallStepContext sc, CancellationToken cancellationToken) { try { var state = await Accessor.GetAsync(sc.Context); if (sc.Result is bool) { if ((bool)sc.Result) { var selectedEvent = state.ShowMeetingInfo.FocusedEvents.First(); var activity = TemplateEngine.GenerateActivityForLocale(JoinEventResponses.JoinMeeting); await sc.Context.SendActivityAsync(activity); var replyEvent = sc.Context.Activity.CreateReply(); replyEvent.Type = ActivityTypes.Event; replyEvent.Name = "OpenDefaultApp"; var eventJoinLink = new OpenDefaultApp { MeetingUri = selectedEvent.OnlineMeetingUrl ?? GetTeamsMeetingLinkFromMeeting(selectedEvent), TelephoneUri = "tel:" + GetDialInNumberFromMeeting(selectedEvent) }; replyEvent.Value = JsonConvert.SerializeObject(eventJoinLink); await sc.Context.SendActivityAsync(replyEvent, cancellationToken); } else { var activity = TemplateEngine.GenerateActivityForLocale(JoinEventResponses.NotJoinMeeting); await sc.Context.SendActivityAsync(activity); } } state.ShowMeetingInfo.ShowingMeetings.Clear(); return(await sc.EndDialogAsync()); } catch (SkillException ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } catch (Exception ex) { await HandleDialogExceptions(sc, ex); return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs)); } }
public void can_handle_double_values_from_propertys() { //Arrange string propertyName = "DummyDoubleProp1"; double value = 1.75; string expectedOutput = Convert.ToString(value, CultureInfo.CreateSpecificCulture("en-US")); var sut = new TemplateEngine(GetTemplateDataModelDummy(), "<TagName>${" + propertyName + "}</TagName>"); //SUT = [S]ystem [U]nder [T]est string ShouldReturnString = "<TagName>" + expectedOutput + "</TagName>"; //Act string ReturnString = sut.CreateStringFromTemplate(); //Assert Assert.AreEqual(ShouldReturnString, ReturnString); }
public void Can_a_template_containing_only_simple_tags_render_correctly(string template, string expected) { //given var data = new { First = "Charlie", Last = "Brown" }; //when string actual = new TemplateEngine(template).Merge(data); //then Assert.Equal(expected, actual); }
public void can_set_a_custom_null_value_String() { //Arrange var sut = new TemplateEngine(GetTemplateDataModelDummy(), "<TagName>${DummyStringProp2}</TagName>"); //SUT = [S]ystem [U]nder [T]est sut.NullStringValue = "Nothing"; string ShouldReturnString = "<TagName>Nothing</TagName>"; //Act string ReturnString = sut.CreateStringFromTemplate(); //Assert Assert.AreEqual(ShouldReturnString, ReturnString); }
public void ComplexConditions() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate(@" #if(false) #elseif(false) #elseif(true) #if(false) #elseif(false) faky #elseif(true) #if(false) #elseif(false) #elseif(true) #if(false) #else indeed #end #elseif(false) #else #end #elseif(false) test #else #end #elseif(false) #else some #end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual("indeed", result.Trim()); }
public static void Main() { string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\StoredProcedures.cst"); var engine = new TemplateEngine(new DefaultEngineHost(System.IO.Path.GetDirectoryName(path))); CompileTemplateResult result = engine.Compile(path); if (result.Errors.Count == 0) { var database = new DatabaseSchema(new SqlSchemaProvider(), @"Server=.;Database=PetShop;Integrated Security=True;"); TableSchema table = database.Tables["Inventory"]; CodeTemplate template = result.CreateTemplateInstance(); template.SetProperty("SourceTable", table); template.SetProperty("IncludeDrop", false); template.SetProperty("InsertPrefix", "Insert"); template.Render(Console.Out); } else { foreach (var error in result.Errors) Console.Error.WriteLine(error.ToString()); } Console.WriteLine("\r\nPress any key to continue."); Console.ReadKey(); }
/// <summary> /// Initializes a new instance of the <see cref="TemplateRule"/> class. /// </summary> /// <param name="iterator">The iterator.</param> /// <param name="condition">The condition.</param> public TemplateRule(TemplateEngine parent, string iterator, string condition) : this(parent) { this.Iterator = iterator; this.Condition = condition; }
public void Add(string extension, TemplateEngine engine) { if (!extension.Equals("tm")) Console.WriteLine("Warning: key is set to 'tm' regardless of the value of extension"); _engines.Add("tm", engine); }
public void InvalidForeachStart() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#foreach (${person} in ${persons})${person}#end"); }
public void LongElseElseIf() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate(@" #if(false) #elseif(false) #elseif(false) #elseif(false) #else #end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual(string.Empty, result.Trim()); }
/// <summary> /// Udpate contructor. /// </summary> /// <param name="go">GameObject to generate an AnimatorAccess class for.</param> public ClassElementsBuilder (GameObject go) { BaseAnimatorAccess animatorAccess = go.GetComponent<BaseAnimatorAccess> (); if (animatorAccess != null) { existingClassBuilder = new ReflectionCodeElementsBuilder (animatorAccess); className = existingClassBuilder.ClassName; config = ConfigFactory.Get (className); templateEngine = new SmartFormatTemplateEngine (); builder = new AnimatorCodeElementsBuilder (go, className, config); existingAllTransitionsHash = animatorAccess.AllTransitionsHash; } else { Logger.Error ("Cannot access component BaseAnimatorAccess from object " + go.name); } }
// ExStart:MailMerge public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_SMTP(); string dstEmail = dataDir + "EmbeddedImage.msg"; // Create a new MailMessage instance MailMessage msg = new MailMessage(); // Add subject and from address msg.Subject = "Hello, #FirstName#"; msg.From = "*****@*****.**"; // Add email address to send email also Add mesage field to HTML body msg.To.Add("*****@*****.**"); msg.HtmlBody = "Your message here"; msg.HtmlBody += "Thank you for your interest in <STRONG>Aspose.Email</STRONG>."; // Use GetSignment as the template routine, which will provide the same signature msg.HtmlBody += "<br><br>Have fun with it.<br><br>#GetSignature()#"; // Create a new TemplateEngine with the MSG message, Register GetSignature routine. It will be used in MSG. TemplateEngine engine = new TemplateEngine(msg); engine.RegisterRoutine("GetSignature", GetSignature); // Create an instance of DataTable and Fill a DataTable as data source DataTable dt = new DataTable(); dt.Columns.Add("Receipt", typeof(string)); dt.Columns.Add("FirstName", typeof(string)); dt.Columns.Add("LastName", typeof(string)); DataRow dr = dt.NewRow(); dr["Receipt"] = "abc<*****@*****.**>"; dr["FirstName"] = "a"; dr["LastName"] = "bc"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Receipt"] = "John<*****@*****.**>"; dr["FirstName"] = "John"; dr["LastName"] = "Doe"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Receipt"] = "Third Recipient<*****@*****.**>"; dr["FirstName"] = "Third"; dr["LastName"] = "Recipient"; dt.Rows.Add(dr); MailMessageCollection messages; try { // Create messages from the message and datasource. messages = engine.Instantiate(dt); // Create an instance of SmtpClient and specify server, port, username and password SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "*****@*****.**", "your.password"); client.SecurityOptions = SecurityOptions.Auto; // Send messages in bulk client.Send(messages); } catch (MailException ex) { Debug.WriteLine(ex.ToString()); } catch (SmtpException ex) { Debug.WriteLine(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Message sent after performing mail merge."); }
public void Text() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("a$toprint}a"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { {"toprint", "this"} }, null); string result = templateItem.Evaluate(context); Assert.AreEqual("a$toprint}a", result); }
public void SingleLineCommentWithoutLineEnding() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("test##aaa${test}aaa#end#foreacg#if###"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual("test", result); }
public void OneEndTooMany() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#comment a #end #end"); }
public void MultiLineCommentInOneLine() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#*#foreach(${person} in ${persons})${person}#end*#"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual(string.Empty, result); }
/// <summary> /// Registers a template engine. The supplied name is used to match against the /// mime type attribute on a template script element. /// </summary> /// <param name="name">The name of template engine.</param> /// <param name="engine">The engine to be used to handle the supplied name.</param> public void RegisterTemplateEngine(string name, TemplateEngine engine) { Debug.Assert(String.IsNullOrEmpty(name) == false); Debug.Assert(engine != null); Debug.Assert(_registeredTemplateEngines.ContainsKey(name) == false, "A template engine with name '" + name + "' was already registered."); _registeredTemplateEngines[name] = engine; }
public void InvalidIfPrintStatement() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("test${asddsa\na}"); }
public void SetUp() { _templateFactoryFactoryMock = new Mock<ITemplateFactoryFactory>(); _templateEngine = new TemplateEngine(_templateFactoryFactoryMock.Object); }
private void SendEmail() { try { // Build message MailMessage msg = new MailMessage(); msg.From = txtFrom.Text; msg.Subject = txtSubject.Text; msg.HtmlBody = txtHtmlBody.Text; msg.To.Add(new MailAddress("#Recipient#", true)); // create a message template engine with the above message TemplateEngine msgTemplateEngine = new TemplateEngine(msg); // create data table for the template DataTable dt = new DataTable(); // Add 3 columns dt.Columns.Add("Recipient", typeof(string)); dt.Columns.Add("FirstName", typeof(string)); dt.Columns.Add("LastName", typeof(string)); // add rows to the table DataRow row; foreach (ListItem item in lstRecipients.Items) { string recipientEmail = item.Text; string firstName = item.Value.Split(delimeter, StringSplitOptions.None)[0]; string lastName = item.Value.Split(delimeter, StringSplitOptions.None)[1]; // add rows to the data table row = dt.NewRow(); row["Recipient"] = recipientEmail; row["FirstName"] = firstName; row["LastName"] = lastName; dt.Rows.Add(row); } MailMessageCollection msgCollection; msgCollection = msgTemplateEngine.Instantiate(dt); // add recipients // Send message SmtpClient smtp = new SmtpClient( txtHost.Text, int.Parse(txtPort.Text), txtUsername.Text, txtPassword.Text); // SSL settings if (chSSL.Checked == true) { smtp.EnableSsl = true; smtp.SecurityMode = SmtpSslSecurityMode.Explicit; } // send bulk emails smtp.BulkSend(msgCollection); // show message on screen that email has been sent lblMessage.ForeColor = System.Drawing.Color.Green; lblMessage.Text = "Email sent successfully<br><hr>"; } catch (Exception ex) { // display error message lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Error: " + ex.Message + "<br><hr>"; } }
/// <summary> /// Initializes a new instance of the <see cref="TemplateRule"/> class. /// </summary> public TemplateRule(TemplateEngine parent) { this.Parent = parent; this.Actions = new List<TemplateAction>(); }
public void setup() { engine = new TemplateEngine(); input = new TemplateInput(); }
public void ForeachWithMultipleElements() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#foreach(${person} in ${persons})${person}#end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { {"persons", new List<string>(){ "one", "two", "three" }} }, null); string result = templateItem.Evaluate(context); Assert.AreEqual("onetwothree", result); }
public void LongElseElseIfElse() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate(@" #if(false) #elseif(false) #elseif(false) #elseif(false) #else indeed #end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.IsTrue(result.Contains("indeed")); }
public void InvalidIfStart() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#if (true) #end"); }
public void MultiLineCommentInMultipleLines() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("\r\tq#*#foreach(\r${person} in ${persons})${pe\nrson}#end*#\na"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual("\r\tqa", result); }
public void MultiLineCommentInMultipleLinesWithoutEnding() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("\n\n\r\tq#*#foreach(\r${person} in ${persons})${pe\nrson}#end\na"); }
public void IfFalse() { TemplateEngine engine = new TemplateEngine(); RootTemplate templateItem = engine.BuildTemplate("#if(false)no#end"); EvaluationContext context = new EvaluationContext(new Dictionary<string, object>() { }, null); string result = templateItem.Evaluate(context); Assert.AreEqual(string.Empty, result); }
/// <summary> /// Contructor in case of the very first generation of an AnimatorAccess class. On subsequent generations /// ClassElementsBuilder (GameObject go) is called. /// </summary> /// <param name="go">GameObject to generate an AnimatorAccess class for.</param> /// <param name="fileName">File name where to save the file. A subdirectory 'Generated' is recommended to /// emphasize that this code shouldn't be edited.</param> public ClassElementsBuilder (GameObject go, string fileName) { className = Path.GetFileNameWithoutExtension (fileName); config = ConfigFactory.Get (className); templateEngine = new SmartFormatTemplateEngine (); builder = new AnimatorCodeElementsBuilder (go, className, config); existingClassBuilder = new ReflectionCodeElementsBuilder ("Assembly-CSharp", config.DefaultNamespace, className); }