public void ThrowWithProperInterfaceTypeNameIfSiteSettingsAreNotProvided() { String navigationContent = string.Empty.GetRandom(); String sidebarContent = string.Empty.GetRandom(); String pathToRoot = string.Empty.GetRandom(); var template = (null as Template).Create(); var templates = new List <Template>() { template }; var templateRepo = new Mock <ITemplateRepository>(); templateRepo.Setup(r => r.GetAllTemplates()) .Returns(templates); var container = new ServiceCollection(); container.AddSingleton <ITemplateRepository>(templateRepo.Object); String expected = typeof(SiteSettings).Name; try { var target = new TemplateProvider(container.BuildServiceProvider()); } catch (DependencyNotFoundException ex) { Assert.Equal(expected, ex.InterfaceTypeName); } }
public void ClassLevelSetUp() { _administrationUnitOfWork = new Mock <IAdministrationUnitOfWork>(); _templateProvider = new TemplateProvider(_administrationUnitOfWork.Object); SetUpAgency(); SetUpTemplate(); }
private void LoadAllTemplates() { var templateProvider = new TemplateProvider(new DatabaseProvider()); IList <Template> templates = templateProvider.Load(); AddToDictionary(templates); }
private void SendConfigButton_Click(object sender, EventArgs e) { foreach (ProtocolMessage msg in TemplateProvider.GetConfiguration(0x00, embeddedConfig, 0x01)) { connector.SendMessage(MessageCodec.EncodeMessage(msg)); } }
public ViewPageRef AddTemplate(string templatePath, string templateContents) { var templateFile = VirtualPathProvider.GetFile(templatePath); var templateName = templateFile.Name.WithoutExtension(); TemplateService templateService; if (!templateServices.TryGetValue(templateFile.Extension, out templateService)) { throw new ConfigurationErrorsException( "No BaseType registered with extension " + templateFile.Extension + " for template " + templateFile.Name); } var template = new ViewPageRef(this, templatePath, templateName, templateContents, RazorPageType.Template) { LastModified = templateFile.LastModified, Service = templateService, }; MasterPageTemplates.Add(templatePath, template); try { //template.Compile(); TemplateProvider.QueuePageToCompile(template); return(template); } catch (Exception ex) { Log.Error("AddViewPage() template.Prepare(): " + ex.Message, ex); return(null); } }
public void AddPage(ViewPageRef page) { try { TemplateProvider.QueuePageToCompile(page); AddViewPage(page); } catch (Exception ex) { HandleCompilationException(page, ex); } try { var templatePath = page.Template; if (page.Template == null) { return; } if (MasterPageTemplates.ContainsKey(templatePath)) { return; } var templateFile = VirtualPathProvider.GetFile(templatePath); var templateContents = GetPageContents(templateFile); AddTemplate(templatePath, templateContents); } catch (Exception ex) { Log.Error("Error compiling template " + page.Template + ": " + ex.Message, ex); } }
private void ExecuteLoadChecklistsCommand() { IsBusy = true; ChecklistGroups.Clear(); try { var checklists = TemplateProvider.GetChecklist(); foreach (var category in checklists) { var listGroup = new GroupedList { GroupName = category.Name, Icon = category.Icon }; foreach (var item in category.Items) { listGroup.Add(item); } ChecklistGroups.Add(listGroup); } } catch (Exception ex) { Debug.WriteLine(ex); Crashes.TrackError(ex); } finally { IsBusy = false; } }
public override string Execute(Dictionary <string, string> parameters) { string path = parameters["templatepath"]; if (string.IsNullOrEmpty(path)) { return(""); } string filename = parameters["templatefile"]; if (string.IsNullOrEmpty(filename)) { return(""); } try { string ModelProvider = parameters["dataprovider"]; string ModelConstructor = parameters["datasource"]; var ModelParameters = new Dictionary <string, string>(parameters); ModelParameters.Remove("templatepath"); ModelParameters.Remove("templatefile"); ModelParameters.Remove("dataprovider"); ModelParameters.Remove("datasource"); var Model = DataSourceProvider.Instance(ModelProvider).Invoke(ModelConstructor, ModelParameters); return(TemplateProvider.FindProviderAndExecute(path, filename, Dump(Model))); } catch (Exception ex) { return("Error : " + path + filename + " " + ex.Message); } }
protected override Task Actions(params object[] parameters) { this.Context.Output.WriteLine("Type the ID of the process you wish to open. Quit by pressing Enter."); TemplateProvider.EndlessPidLoop(pid => { string filePath = ""; foreach (Configuration configuration in this.Context.Processes.Keys) { if (configuration.ID == pid) { filePath = configuration.ProcessLocation; break; } } if (!File.Exists(filePath)) { return; } string argument = "/select, \"" + filePath + "\""; Process.Start("explorer.exe", argument); }, this.Context); return(Task.CompletedTask); }
public void ThrowWithProperInterfaceTypeNameIfSettingsAreNotProvided() { string navigationContent = string.Empty.GetRandom(); string sidebarContent = string.Empty.GetRandom(); string pathToRoot = string.Empty.GetRandom(); var template = (null as Template).Create(); var templates = new List <Template>() { template }; var container = new ServiceCollection(); container.AddSingleton <IEnumerable <Template> >(templates); // container.AddSingleton<SiteSettings>(Mock.Of<SiteSettings>()); string expected = typeof(ISettings).Name; try { var target = new TemplateProvider(container.BuildServiceProvider()); } catch (DependencyNotFoundException ex) { Assert.Equal(expected, ex.InterfaceTypeName); } }
public async Task <APIResponse> NewPassword([FromBody] NewPasswordModel model) { // validate if (BaseValidableModel.IsInvalid(model, out var errFields)) { return(APIResponse.BadRequest(errFields)); } var user = (DAL.Models.Identity.User)null; var audience = GetCurrentAudience(); var agent = GetUserAgentInfo(); var userLocale = GetUserLocale(); // check token if (!await Core.Tokens.JWT.IsValid( appConfig: AppConfig, jwtToken: model.Token, expectedAudience: JwtAudience.Cabinet, expectedArea: JwtArea.RestorePassword, validStamp: async(jwt, id) => { user = await UserManager.FindByNameAsync(id); return(""); } ) || user == null) { return(APIResponse.BadRequest(nameof(model.Token), "Invalid token")); } await UserManager.RemovePasswordAsync(user); await UserManager.AddPasswordAsync(user, model.Password); if (audience != null) { UserAccount.GenerateJwtSalt(user, audience.Value); await DbContext.SaveChangesAsync(); } // notification await EmailComposer.FromTemplate(await TemplateProvider.GetEmailTemplate(EmailTemplate.PasswordChanged, userLocale)) .Initiator(agent.Ip, agent.Agent, DateTime.UtcNow) .Send(user.Email, user.UserName, EmailQueue) ; // activity var userActivity = CoreLogic.User.CreateUserActivity( user: user, type: Common.UserActivityType.Password, comment: "Password changed", ip: agent.Ip, agent: agent.Agent, locale: userLocale ); DbContext.UserActivity.Add(userActivity); await DbContext.SaveChangesAsync(); return(APIResponse.Success()); }
private void PopulateLookupTable(TemplateProvider template) { lookupTable.Clear(); foreach (Category category in template.Categories) { lookupTable.Add(category.ToFormat(), category); } }
public static HtmlLoader BuildHtmlLoader() { var databaseProvider = new DatabaseProvider(); var templateProvider = new TemplateProvider(databaseProvider); var htmlLoader = new HtmlLoader(templateProvider); return(htmlLoader); }
public void Generate() { var data = DataProvider.GetData(); var output = Renderer.Render(data, TemplateProvider.GetTemplate(Options.TemplatePath)); var directoryInfo = new DirectoryInfo(Options.TargetPath); OutputService.Write(Path.Join(directoryInfo.FullName, $"ServiceCollectionExtensions.cs"), output); }
/// <summary> /// Obtiene una ConfigurationSection por reflection /// </summary> /// <param name="pConfiguration"></param> /// <param name="pSectionName">Ej databaseSettings</param> static void AddSectionFromAssembly(Configuration pConfiguration, String pSectionName) { String s = TemplateProvider.GetAssemblySections(pSectionName); ConfigurationSection wSection = (ConfigurationSection)Fwk.HelperFunctions.ReflectionFunctions.CreateInstance(s); pConfiguration.Sections.Add(pSectionName, wSection); wSection.SectionInformation.ForceSave = true; }
static void Main(string[] args) { var viewEngine = new ViewEngine(); var bodyProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "<b>{{Value}}</b>") }); var subjectProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "{{Title}}") }); var emailService = new EmailService(new EmailRenderer(bodyProvider, viewEngine), new EmailRenderer(subjectProvider, viewEngine), new TestSmtpService()); emailService.Send(new[] { "tt" }, new TestMail { Value = "777", Title = "555"}); Console.ReadKey(); }
public void Generate() { var data = DomainDataProvider.GetData(); foreach (var entity in data.Entities.Where(o => o.Manager != null)) { var code = Renderer.Render(entity, TemplateProvider.GetTemplate(Options.TemplatePath)); OutputService.Write(Path.Join(Options.TargetPath, $"{entity.Manager.Name}.cs"), code); } }
private static void WriteTemplate(TextWriter writer, AbstractFunctionDefinition functionDefinition) { TemplateProvider templateProvider = new TemplateProvider(); string templateSource = templateProvider.GetCSharpOutputCollectorTemplate(functionDefinition.OutputBinding); Func <object, string> template = Handlebars.Compile(templateSource); string output = template(functionDefinition); writer.Write(output); }
public async Task <APIResponse> ChangePassword([FromBody] ChangePasswordModel model) { // validate if (BaseValidableModel.IsInvalid(model, out var errFields)) { return(APIResponse.BadRequest(errFields)); } var user = await GetUserFromDb(); var agent = GetUserAgentInfo(); var userLocale = GetUserLocale(); // first check tfa if (user.TwoFactorEnabled && !Core.Tokens.GoogleAuthenticator.Validate(model.TfaCode, user.TfaSecret)) { return(APIResponse.BadRequest(nameof(model.TfaCode), "Invalid 2fa code")); } // check current password if (await UserManager.HasPasswordAsync(user) && (model.Current == null || !await UserManager.CheckPasswordAsync(user, model.Current))) { return(APIResponse.BadRequest(nameof(model.Current), "Invalid current password")); } // set new password await UserManager.RemovePasswordAsync(user); await UserManager.AddPasswordAsync(user, model.New); // notification await EmailComposer.FromTemplate(await TemplateProvider.GetEmailTemplate(EmailTemplate.PasswordChanged, userLocale)) .Initiator(agent.Ip, agent.Agent, DateTime.UtcNow) .Send(user.Email, user.UserName, EmailQueue) ; // activity var userActivity = CoreLogic.User.CreateUserActivity( user: user, type: Common.UserActivityType.Password, comment: "Password changed", ip: agent.Ip, agent: agent.Agent, locale: userLocale ); DbContext.UserActivity.Add(userActivity); await DbContext.SaveChangesAsync(); return(APIResponse.Success( new ChangePasswordView() { } )); }
private static void WriteTemplate(TextWriter writer, AbstractFunctionDefinition functionDefinition) { TemplateProvider templateProvider = new TemplateProvider(CompileTargetEnum.AzureFunctions); string templateSource = templateProvider.GetCSharpOutputParameterTemplate(functionDefinition.OutputBinding); Func <object, string> template = Handlebars.Compile(templateSource); string output = template(functionDefinition.OutputBinding); writer.Write(","); writer.Write(output); }
public IEnumerable <ViewPageRef> FindRazorPages(string dirPath) { var hasReloadableWebPages = false; foreach (var entry in templateServices) { var ext = entry.Key; var csHtmlFiles = VirtualPathProvider.GetAllMatchingFiles("*." + ext).ToList(); foreach (var csHtmlFile in csHtmlFiles) { if (ShouldSkipPath(csHtmlFile)) { continue; } if (csHtmlFile.GetType().Name != "ResourceVirtualFile") { hasReloadableWebPages = true; } var pageName = csHtmlFile.Name.WithoutExtension(); var pageContents = GetPageContents(csHtmlFile); var pageType = RazorPageType.ContentPage; if (VirtualPathProvider.IsSharedFile(csHtmlFile)) { pageType = RazorPageType.SharedViewPage; } else if (VirtualPathProvider.IsViewFile(csHtmlFile)) { pageType = RazorPageType.ViewPage; } var templateService = entry.Value; templateService.RegisterPage(csHtmlFile.VirtualPath, pageName); var templatePath = pageType == RazorPageType.ContentPage ? TemplateProvider.GetTemplatePath(csHtmlFile.Directory) : null; yield return(new ViewPageRef(this, csHtmlFile.VirtualPath, pageName, pageContents, pageType) { Template = templatePath, LastModified = csHtmlFile.LastModified, Service = templateService }); } } if (!hasReloadableWebPages) { WatchForModifiedPages = false; } }
public void Generate() { var data = DomainDataProvider.GetData(); foreach (var entity in data.Entities.Where(o => o.ControllerClass != null)) { var output = Renderer.Render(entity, TemplateProvider.GetTemplate(Options.TemplatePath)); var directoryInfo = new DirectoryInfo(Options.TargetPath); OutputService.Write(Path.Join(directoryInfo.FullName, $"{entity.ControllerClass.Name}.cs"), output); } }
public HttpResponseMessage Get() { try { var templates = new TemplateProvider(DbInfo).RetrieveTemplates(); return(Request.CreateResponse(HttpStatusCode.OK, templates)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.OK, ex.StackTrace)); } }
private void SendSine() { sendSine = true; long currentTime = stopwatch.ElapsedMilliseconds; while (stopwatch.ElapsedMilliseconds < currentTime + 600000 && sendSine) { double value = (((double)stopwatch.ElapsedMilliseconds / 100) % 6.28 - 3.14); connector.SendMessage(MessageCodec.EncodeMessage(TemplateProvider.GetChannelDataMessage((int)(100 * Math.Sin(value) + 128), stopwatch.ElapsedMilliseconds))); Thread.Sleep(1); } }
protected override Task Actions(params object[] parameters) { this.Context.Output.WriteLine("Type the ID of the process you wish to blacklist. Quit by pressing Enter."); TemplateProvider.EndlessPidLoop(pid => { DefaultProcessIdentifier.BlacklistProcess(this.Context.Processes.Values.Where(x => x.Id == pid).ToArray()[0]); }, this.Context); DefaultProcessIdentifier.ConfigurationUpdate(); return(Task.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="pConfiguration">Configuration del app.config</param> /// <param name="pSectionName">Seccion</param> /// <param name="pSectionGroupName">Grupo</param> internal static void AddSection(Configuration pConfiguration, String pSectionName, String pSectionGroupName, String pSettingTemplateName) { ConfigurationSectionGroup wConfigurationSectionGroup = null; SettingElement wSettingElement = null; XmlDocument doc = new XmlDocument(); XmlNode xmlValue = doc.CreateNode(XmlNodeType.Element, "value", String.Empty); ConfigurationSectionCollection wSections = null; if (pSectionGroupName.Length == 0) { AddSectionFromAssembly(pConfiguration, pSectionName); return; } else { wConfigurationSectionGroup = pConfiguration.GetSectionGroup(pSectionGroupName); if (wConfigurationSectionGroup == null) { wConfigurationSectionGroup = AddSectionGroup(pConfiguration, pSectionGroupName); } wSections = wConfigurationSectionGroup.Sections; } if (wSections.Get(pSectionName) != null) { return; } ClientSettingsSection wClientSettingsSection = new ClientSettingsSection(); wClientSettingsSection.SectionInformation.RequirePermission = false; wClientSettingsSection.SectionInformation.ForceSave = true; #region Settings Dictionary <String, String> wSettings = TemplateProvider.GetSettingDic(pSettingTemplateName); if (wSettings != null) { foreach (KeyValuePair <string, string> seting in wSettings) { wSettingElement = new SettingElement(); wSettingElement.Name = seting.Key; xmlValue.InnerXml = seting.Value; wSettingElement.Value.ValueXml = xmlValue.Clone(); wClientSettingsSection.Settings.Add(wSettingElement); } } #endregion wSections.Add(pSectionName, wClientSettingsSection); }
private void NewAnalysisButton_Click(object sender, RoutedEventArgs e) { var templateProvider = new TemplateProvider(new DatabaseProvider()); var templates = templateProvider.Load(); if (templates.Count == 0) { MessageBox.Show("Добавьте вначале шаблоны для анализов!", "Error!"); return; } Switcher.PageSwitcher.Navigate(new NewAnalysis()); }
// POST: api/Billing public HttpResponseMessage Post(Template template) { try { var provider = new TemplateProvider(DbInfo); var isSaved = provider.Save(template); return(Request.CreateResponse(HttpStatusCode.OK, isSaved)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } }
private static void WriteTemplate(TextWriter writer, AbstractFunctionDefinition functionDefinition) { TemplateProvider templateProvider = new TemplateProvider(); string templateSource = templateProvider.GetJsonOutputParameterTemplate(functionDefinition.OutputBinding); if (templateSource != null) { Func <object, string> template = Handlebars.Compile(templateSource); string output = template(functionDefinition.OutputBinding); writer.Write(","); writer.Write(output); } }
public SetupTripViewModel(INavigation navigation, Trip trip, TripsHolder tripsHolder) { Navigation = navigation; Trip = trip; TripsHolder = tripsHolder; SwipedCommand = new Command <SwipedCardEventArgs>(eventArgs => ExecuteSwipedCommand(eventArgs)); Threshold = (uint)(App.ScreenWidth / 3); TemplateCategories = TemplateProvider.GetChecklist(); TemplateCategories.RemoveAll(x => Trip.Categories.Exists(y => y.Name.Equals(x.Name))); SelectedCategories = new List <ItemCategory>(); }
private SyntaxTree CreateController(string namespaceName, DirectoryInfo directoryInfo, HttpFunctionDefinition httpFunctionDefinition) { string startupTemplateSource = TemplateProvider.GetTemplate("controller", "csharp"); Func <object, string> template = Handlebars.Compile(startupTemplateSource); string filenameWithoutExtension = $"{httpFunctionDefinition.Name}Controller"; string outputCode = template(httpFunctionDefinition); OutputDiagnosticCode(directoryInfo, filenameWithoutExtension, outputCode); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(outputCode, path: $"{filenameWithoutExtension}.cs"); return(syntaxTree); }
public void GetTemplate_ByTypeId(string requestedTypeId, string expectedName) { Guid typeId = new Guid(requestedTypeId); TemplateProvider tp = new TemplateProvider(); IElementTemplate template = tp.GetTemplate(typeId); Assert.NotNull(template); Assert.NotNull(template.SmallIcon); Assert.NotNull(template.MediumIcon); Assert.NotNull(template.SmallImage); Assert.NotNull(template.MediumImage); Assert.NotNull(template.MediumImageComplete); Assert.NotNull(template.MediumImageError); Assert.NotNull(template.LargeImage); Assert.NotNull(template.Definition); Assert.Equal(template.Definition.ElementTypeId, typeId); Assert.Equal(template.Definition.ElementName, expectedName); }
static bool CreateEquity(Trade trade, TradeInfo info, Market market, StringBuilder sb, TemplateProvider provider) { try { trade.Product = info.Security; trade.PriceType = trade.Product.QuoteName.QuoteType; // add ... provider.FillTrade(trade, market); return true; } catch (Exception x) { Logger.Error("Import Equity", x); sb.Append(TradeImportHelper.FormatErrorMessage("Fill Trade " + x.Message, info.HoldingID, info.TradeID, info.Instrument)); return false; } }
public void Templates_ReturnsAListOfAllElementTemplates() { TemplateProvider tp = new TemplateProvider(); IList<IElementTemplate> templates = tp.Templates; Assert.NotNull(templates); }
static bool CreateBond(Trade trade, TradeInfo info, FilterData filterData, Market market, StringBuilder sb, TemplateProvider provider) { try { var bond = (Bond)info.Security; trade.Product = info.Security; // assuming file has all clean price trade.PriceType = QuotationType.CleanPrice; if (bond.IssueDate > trade.SettlementDate) trade.SettlementDate = bond.IssueDate; trade.Price /= 100; info.MarketPrice /= 100; trade.Quantity = info.Nominal1/bond.FaceValue; if (!double.IsNaN(info.Quantity)) { if (trade.Quantity != info.Quantity) sb.Append("Warning Bad Quantity for Trade" + " Symbol " + info.Symbol + "\n"); } provider.FillTrade(trade, market); if (Double.IsNaN(trade.Accrual)) { trade.Accrual = 0; sb.Append("Warning Bad Accrual for Trade" + " Symbol " + info.Symbol + "\n"); } return true; } catch (Exception x) { Logger.Error("Import Bond", x); sb.Append(TradeImportHelper.FormatErrorMessage("Fill Trade " + x.Message, info.HoldingID, info.TradeID, info.Instrument)); return false; } }