// gets all templates // IEnumerator fetchAllTemplates () // { // string url = "https://uql53bqfta.execute-api.us-east-1.amazonaws.com/Artsy/get-templates"; // // Using the static constructor // var request = UnityWebRequest.Get(url); // // Wait for the response and then get our data // yield return request.SendWebRequest(); // var data = request.downloadHandler.text; // TemplateCollection collection = TemplateCollection.CreateFromJSON(data); // // Debug.Log("hello"); // // Debug.Log("size: " + collection.templates.Length); // foreach(TemplateItem templateItem in collection.templates) // { // allTemplates[templateItem.title] = templateItem.url; // } // Debug.Log("Done fetching templates :)"); // } IEnumerator fetchAllTemplatesAndSave() { string url = "https://uql53bqfta.execute-api.us-east-1.amazonaws.com/Artsy/get-templates"; // Using the static constructor var request = UnityWebRequest.Get(url); // Wait for the response and then get our data yield return(request.SendWebRequest()); var data = request.downloadHandler.text; TemplateCollection collection = TemplateCollection.CreateFromJSON(data); PlayerPrefs.SetInt("TOTAL_NUM_TEMPLATES", collection.numTemplates); foreach (TemplateItem templateItem in collection.templates) { string savePath = string.Format("{0}/template${1}.pdb", Application.persistentDataPath, templateItem.title); if (!System.IO.File.Exists(savePath)) { UnityWebRequest www = UnityWebRequestTexture.GetTexture(templateItem.url); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { System.IO.File.WriteAllBytes(savePath, www.downloadHandler.data); } } } }
public void Resolve_DerivedScriptUnderTheme_IncludesScript() { // arrange var derivedTemplateId = ID.NewID; var templates = new TemplateCollection(); var scriptTemplate = TemplateFactory.CreateTemplate(ScriptItem.TemplateId, null, templates); var derivedScriptTemplate = TemplateFactory.CreateTemplate(derivedTemplateId, ScriptItem.TemplateId, templates); var templateManager = TemplateFactory.CreateTemplateManager(new[] { scriptTemplate, derivedScriptTemplate }); var scriptItemMock = ItemFactory.CreateItem(templateId: derivedTemplateId); ItemFactory.SetIndexerField(scriptItemMock, FileItem.Fields.Url, "/url"); ItemFactory.SetIndexerField(scriptItemMock, ScriptItem.ScriptItemFields.FallbackUrl, "/fallbackurl"); ItemFactory.SetIndexerField(scriptItemMock, ScriptItem.ScriptItemFields.VerificationObject, "object"); var itemMock = ItemFactory.CreateItem(); var children = new ChildList(itemMock.Object, new[] { scriptItemMock.Object }); itemMock.Setup(x => x.GetChildren()).Returns(children); var sut = new ThemeFileResolver(templateManager); // act var result = sut.Resolve(itemMock.Object); // assert Assert.That(result.Stylesheets, Is.Empty); Assert.That(result.Scripts.Count(), Is.EqualTo(1)); var script = result.Scripts.First(); Assert.That(script.Url, Is.EqualTo("/url")); Assert.That(script.FallbackUrl, Is.EqualTo("/fallbackurl")); Assert.That(script.VerificationObject, Is.EqualTo("object")); }
void FillList() { this.listView_objects.Items.Clear(); if (this.FileName == "") return; try { templates = TemplateCollection.Load(this.FileName, false); } catch (Exception ex) { MessageBox.Show(this, ex.Message); return; } for (int i = 0; i < templates.Count; i++) { Template t = templates[i]; ListViewItem item = new ListViewItem(t.Object.Name, t.Object.Type); item.Tag = t; item.SubItems.Add(this.Url); this.listView_objects.Items.Add(item); } }
//************************************************************************* //* Private * //************************************************************************* //************************************************************************* //* Protected * //************************************************************************* //************************************************************************* //* Public * //************************************************************************* //*-----------------------------------------------------------------------* //* ParseProject * //*-----------------------------------------------------------------------* /// <summary> /// Parse the project text content into an abstracted definition /// collection. /// </summary> /// <param name="content"> /// JSON string content to be deserialized. /// </param> /// <param name="projectPath"> /// Path to the local working directory. /// </param> /// <param name="configs"> /// Configuration tables loaded in this session. /// </param> /// <param name="components"> /// Metadata component pages loaded in this session. /// </param> /// <param name="templates"> /// Template definitions loaded in this session. /// </param> /// <returns> /// Newly created and resolved JSON Template collection. /// </returns> /// <remarks> /// The project and template files both use generic templates. /// </remarks> public static void Parse(string content, string projectPath, ConfigurationCollection configs, ComponentCollection components, TemplateCollection templates) { ComponentItem iComponent = null; ConfigurationItem iConfig = null; TemplateItem iTemplate = null; JsonTemplateCollection project = JsonConvert. DeserializeObject<JsonTemplateCollection>(content); string typeName = ""; foreach(JsonTemplateItem template in project) { typeName = template.TypeName.ToLower(); switch(typeName) { case "componentpage": iComponent = ComponentItem.Parse(template.Name, template.Definition, projectPath); components.Add(iComponent); break; case "configuration": iConfig = ConfigurationItem.Parse(template.Name, template.Definition, projectPath); configs.Add(iConfig); break; case "template": iTemplate = TemplateItem.Parse(template.Name, template.Definition, projectPath); templates.Add(iTemplate); break; } } }
public TemplateCollection FetchAll() { TemplateCollection coll = new TemplateCollection(); Query qry = new Query(Template.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
public DocumentBuildContext(string buildOutputFolder, IEnumerable <FileAndType> allSourceFiles, ImmutableArray <string> externalReferencePackages, TemplateCollection templateCollection) { BuildOutputFolder = buildOutputFolder; AllSourceFiles = allSourceFiles.ToImmutableDictionary(ft => ((RelativePath)ft.File).GetPathFromWorkingFolder(), FilePathComparer.OSPlatformSensitiveStringComparer); TemplateCollection = templateCollection; ExternalReferencePackages = externalReferencePackages; }
public virtual void ReadChildData(BinaryReader reader) { int x = 0; for (x = 0; (x < _templateCollection.Count); x = (x + 1)) { TemplateCollection.Add(new SoundEffectTemplatesBlockBlock()); TemplateCollection[x].Read(reader); } for (x = 0; (x < _templateCollection.Count); x = (x + 1)) { TemplateCollection[x].ReadChildData(reader); } _inputEffectName.ReadString(reader); for (x = 0; (x < _additionalSoundInputs.Count); x = (x + 1)) { AdditionalSoundInputs.Add(new SoundEffectTemplateAdditionalSoundInputBlockBlock()); AdditionalSoundInputs[x].Read(reader); } for (x = 0; (x < _additionalSoundInputs.Count); x = (x + 1)) { AdditionalSoundInputs[x].ReadChildData(reader); } for (x = 0; (x < _unnamed0.Count); x = (x + 1)) { Unnamed0.Add(new PlatformSoundEffectTemplateCollectionBlockBlock()); Unnamed0[x].Read(reader); } for (x = 0; (x < _unnamed0.Count); x = (x + 1)) { Unnamed0[x].ReadChildData(reader); } }
/// <summary> /// Clears the internal cache of the templates collection and asks Sitecore for all templates to set it agian. /// </summary> public void ResetTemplatesCollection() { var sitecoreContext = ObjectFactory.Instance.Resolve <ISitecoreContext>(); if (!sitecoreContext.ShouldPullTemplatesFromSitecore) { return; } var loggingService = ObjectFactory.Instance.Resolve <ILoggingService>(); loggingService.Log <DataProviderMasterDatabase>("ResetTemplatesCollection called."); Stopwatch watch = new Stopwatch(); watch.Start(); _data = null; var templates = sitecoreContext.MasterDatabase.Engines.TemplateEngine.GetTemplates() .Where(x => x.Value.FullName.Contains("uCommerce definitions")) .Select(x => x.Value) .ToList(); SetTemplatesCollection(templates); watch.Stop(); loggingService.Log <DataProviderMasterDatabase>(string.Format("ResetTemplatesCollection took: {0} ms.", watch.ElapsedMilliseconds)); }
public TreeProcessor(IEnumerable<Token> tokens, object codeListing) { _collection = new TemplateCollection<Token[]>(GetType().Assembly, type => true); _tokens = tokens; _codeListing = codeListing; }
public TemplateEngine([NotNull] ITable templateTable, [NotNull] ILog logger) { this.templateTable = templateTable; templateCollection = new TemplateCollection(templateTable); rendererCollection = new RendererCollection(templateCollection); parserCollection = new ParserCollection(logger.ForContext("ExcelObjectPrinter")); }
/// <summary> /// Overriden base method to allow the selection of the correct DataTemplate /// </summary> /// <param name="item">The item for which the template should be retrieved</param> /// <param name="container">The object containing the current item</param> /// <returns>The <see cref="DataTemplate"/> to use when rendering the <paramref name="item"/></returns> public override DataTemplate SelectTemplate(object item, DependencyObject container) { //This should ensure that the item we are getting is in fact capable of holding our property //before we attempt to retrieve it. if (!(container is UIElement)) { return(base.SelectTemplate(item, container)); } //First, we gather all the templates associated with the current control through our dependency property TemplateCollection templates = GetTemplates(container as UIElement); if (templates == null || templates.Count == 0) { return(base.SelectTemplate(item, container)); } //Then we go through them checking if any of them match our criteria foreach (var template in templates) { //In this case, we are checking whether the type of the item //is the same as the type supported by our DataTemplate if (template.Value.IsInstanceOfType(item)) { //And if it is, then we return that DataTemplate return(template.DataTemplate); } } //If all else fails, then we go back to using the default DataTemplate return(base.SelectTemplate(item, container)); }
public DocumentBuildContext(string buildOutputFolder, IEnumerable<FileAndType> allSourceFiles, ImmutableArray<string> externalReferencePackages, TemplateCollection templateCollection) { BuildOutputFolder = buildOutputFolder; AllSourceFiles = allSourceFiles.ToImmutableDictionary(ft => ((RelativePath)ft.File).GetPathFromWorkingFolder(), FilePathComparer.OSPlatformSensitiveStringComparer); TemplateCollection = templateCollection; ExternalReferencePackages = externalReferencePackages; }
private void Transform(DocumentBuildContext context, TemplateCollection templateCollection, bool exportMetadata) { if (templateCollection == null || templateCollection.Count == 0) { Logger.LogWarning("No template is found."); } else { Logger.LogInfo("Start applying template..."); } var outputDirectory = context.BuildOutputFolder; List <TemplateManifestItem> manifest = new List <TemplateManifestItem>(); // Model can apply multiple template with different extension, so append the view model extension instead of change extension Func <string, string> metadataPathProvider = (s) => { return(s + ViewModelExtension); }; foreach (var item in context.Manifest) { var manifestItem = TemplateProcessor.Transform(context, item, templateCollection, outputDirectory, exportMetadata, metadataPathProvider); manifest.Add(manifestItem); } // Save manifest var manifestPath = Path.Combine(outputDirectory, ManifestFileName); JsonUtility.Serialize(manifestPath, manifest); Logger.Log(LogLevel.Verbose, $"Manifest file saved to {manifestPath}."); }
public override TemplateCollection GetTemplates(CallContext context) { #if DEBUG var timer = Stopwatch.StartNew(); #endif var headTemplates = HeadProvider.GetTemplates(context) ?? EmptyTemplates; var readOnlyTemplates = ReadOnlyProviders .SelectMany(x => x .GetTemplates(context) ?? EmptyTemplates); var templates = headTemplates .Concat(readOnlyTemplates) .GroupBy(x => x.ID).Select(x => x.First()) // .Distinct() .ToArray(); var result = new TemplateCollection(); result.Reset(templates); #if DEBUG this.Trace(result, timer, context); #endif return(result); }
public void Test_entity_conversion_to_generated_class_output_model() { var ns = new Namespace("MyApp.MyTest", null); var entity = new Base.Models.Entity.Entity("MyClass", ns); var targetPlatform = new TargetPlatform("test"); targetPlatform.RegisterClassNamingConvention(BasePluginConstants.Language_CSharp, new CSharpClassNamingConvention()); entity.AddAttribute(new EntityAttribute("Id", TestDataTypes.Int, null, null)); entity.AddAttribute(new EntityAttribute("Name", TestDataTypes.String, null, null)); entity.OutputConfiguration.RegisterOutputFolder(new Filter(EntityPluginConstants.OutputModelType_Entity_GeneratedClass), new ProjectFolder("")); entity.OutputConfiguration.RegisterTargetPlatformForDesignModelType(entity.DesignModelType, targetPlatform); var templateCollection = new TemplateCollection(); templateCollection.LoadTemplates(typeof(EntityPluginConstants).Assembly); var template = templateCollection.GetTemplate(EntityPluginConstants.OutputTemplateName_Entity_GeneratedClass); targetPlatform.RegisterOutputTemplate(EntityPluginConstants.OutputTemplateName_Entity_GeneratedClass, template); var converter = new EntityConverter(templateCollection); var generatedClass = converter.CreateEntityGeneratedClass(entity, BasePluginConstants.Language_CSharp); generatedClass.Should().NotBeNull(); generatedClass.ClassName.Should().Be("MyClass"); generatedClass.ClassNamespace.Should().Be("MyApp.MyTest"); var properties = generatedClass .Properties .Select(x => (name: x.Name, type: x.Type.TypeName)); properties.Should().BeEquivalentTo(new[]
private void btnExcluirFuncionarios_Click(object sender, EventArgs e) { try { InstanciaWatchComm(); this._watchComm.OpenConnection(); CardCollection listCartoes = new CardCollection(); foreach (DataRow dr in dsSDKBioLite.dtFuncionarios) { TemplateCollection templateCollection = new TemplateCollection(); Template template = new Template(); Card card = new Card(); card.Code = dr["Matricula"].ToString(); card.Name = dr["Nome"].ToString(); if (!dr["Senha"].ToString().Equals("")) { card.PassWord = Int32.Parse(dr["Senha"].ToString()); } if (dr["Supervisor"].ToString().Equals("True")) { card.MasterCard = TypeMasterCard.Master; } foreach (DataRow drTemplate in dsSDKBioLite.dtTemplates) { if (drTemplate["Matricula"].ToString().Equals(card.Code)) { template = new Template(); template.DedoDigital = (TypeDedoDigital)Int32.Parse(drTemplate["Dedo"].ToString()); template.Digital = drTemplate["String"].ToString(); templateCollection.Add(template); } } card.Template = templateCollection; listCartoes.Add(card); } this._watchComm.eraseCardListBioLite(listCartoes); this._watchComm.CloseConnection(); ComandoRecepcionadoComSucesso(); } catch (Exception ex) { this._watchComm.CloseConnection(); MessageBox.Show(ex.Message, "Erro"); } }
private BaseTemplateManager CreateTemplateManager(ID feedTemplateId) { var templates = new TemplateCollection(); var template = TemplateFactory.CreateTemplate(feedTemplateId, ID.NewID, templates); var templateManager = TemplateFactory.CreateTemplateManager(new[] { template }); return(templateManager); }
public override TemplateCollection GetTemplates(CallContext context) { var owner = new TemplateCollection(); var database = GetDatabase(context); var templatesRoot = database.GetItems(ItemIDs.TemplateRoot.ToString()); var templates = new List <Template>(templatesRoot.Count()); foreach (var syncItem in templatesRoot) { if (ID.IsNullOrEmpty(ID.Parse(syncItem.ID)) || syncItem.ID.Equals(TemplateIDs.TemplateFolder.ToString())) { continue; } var templateBuilder = new Template.Builder(syncItem.Name, ID.Parse(syncItem.ID), owner); templateBuilder.SetFullName(syncItem.ItemPath); var dataSection = templateBuilder.AddSection("Data", ID.NewID); foreach (var syncField in syncItem.SharedFields) { if (string.IsNullOrEmpty(syncField.FieldID) || string.IsNullOrEmpty(syncField.FieldName)) { continue; } if (syncField.FieldID.Equals(FieldIDs.BaseTemplate.ToString())) { templateBuilder.SetBaseIDs(syncField.FieldValue); } else { dataSection.AddField(syncField.FieldName, ID.Parse(syncField.FieldID)); } } var version = syncItem.GetLatestVersions().FirstOrDefault(); foreach (var syncField in version.Fields) { if (string.IsNullOrEmpty(syncField.FieldID) || string.IsNullOrEmpty(syncField.FieldName)) { continue; } dataSection.AddField(syncField.FieldName, ID.Parse(syncField.FieldID)); } templates.Add(templateBuilder.Template); } owner.Reset(templates.ToArray()); return(owner); }
public Template.Builder BuildTemplate(TemplateCollection owner) { var builder = new Template.Builder(TemplateName, Id, owner); builder.SetFullName(TemplateName); builder.SetBaseIDs(BaseIdsValue); return(builder); }
protected void Page_Load(object sender, EventArgs e) { UserTemplates = UserPropertyTemplate.TemplatesForUser(Page.User.Identity.Name, IncludeAutomaticTemplates); GroupedTemplates = TemplateCollection.GroupTemplates(UserTemplates); // No viewstate - refresh every time. Refresh(); TemplatesReady?.Invoke(this, new EventArgs()); }
internal RazorMailMessage(string subject, Assembly assembly, IFileReader fileReader) { Message = new MailMessage(); Message.Subject = subject; Encoding = Encoding.UTF8; Templates = new TemplateCollection(assembly, fileReader ?? new FileReader()); Set = new ExpandoObject(); }
public Table(object relatedModelElement) : base("Table.txt",System.Reflection.Assembly.GetExecutingAssembly(),_placeHolders, relatedModelElement) { string nl = System.Environment.NewLine; _primaryKeys = new StringCollection( ); //_primaryKeys.Tabs = 1; //_primaryKeys.FirstLineTabs = 0; _columnsName = new TemplateCollection(nl); _columnsName.Tabs = 1; _columnsName.FirstLineTabs = 0; }
/// <summary> /// Sets the internal data cache with the list of templates provided. /// </summary> /// <param name="templates"></param> public void SetTemplatesCollection(IList <Template> templates) { if (templates != null) { _data = new TemplateCollection(); foreach (var template in templates) { _data.Add(template); } } }
private void CreateTemplateProviderData(string databaseName) { _templateCollection = new TemplateCollection(); _idCollection = new IdCollection(); FakeDatabase fakeDatabase = ((FakeDatabase)Factory.GetDatabase(databaseName)); IEnumerable<Tuple<Item, IEnumerable<Item>>> templates = fakeDatabase.GetTemplateMappings(); foreach (Tuple<Item, IEnumerable<Item>> mapping in templates) { AddTemplate(mapping.Item1, mapping.Item2); } }
public static string UpdateFilePath(string path, string documentType, TemplateCollection templateCollection) { if (templateCollection == null) return path; var templates = templateCollection[documentType]; // Get default template extension if (templates == null || templates.Count == 0) return path; var defaultTemplate = templates.FirstOrDefault(s => s.IsPrimary) ?? templates[0]; return Path.ChangeExtension(path, defaultTemplate.Extension); }
public void TemplateCollectionConstructor_WithNoAssembly_ThrowsException() { // Arrange var reader = new Mock<IFileReader>(); // Act var collection = new TemplateCollection(null, reader.Object); // Assert // Exception thrown }
/// <summary> /// TemplateName can be either file or folder /// 1. If TemplateName is file, it is considered as the default template /// 2. If TemplateName is a folder, files inside the folder is considered as the template, each file is named after {DocumentType}.{extension} /// </summary> /// <param name="templateName"></param> /// <param name="resourceProvider"></param> public TemplateProcessor(ResourceCollection resourceProvider, DocumentBuildContext context, int maxParallelism = 0) { if (maxParallelism <= 0) { maxParallelism = Environment.ProcessorCount; } _resourceProvider = resourceProvider; _templateCollection = new TemplateCollection(resourceProvider, context, maxParallelism); Tokens = LoadTokenJson(resourceProvider) ?? new Dictionary<string, string>(); }
private void CreateTemplateProviderData(string databaseName) { _templateCollection = new TemplateCollection(); _idCollection = new IdCollection(); FakeDatabase fakeDatabase = ((FakeDatabase)Factory.GetDatabase(databaseName)); IEnumerable <Tuple <Item, IEnumerable <Item> > > templates = fakeDatabase.GetTemplateMappings(); foreach (Tuple <Item, IEnumerable <Item> > mapping in templates) { AddTemplate(mapping.Item1, mapping.Item2); } }
public void GetEnumerator_ReturnsEnumerator() { // Arrange var reader = new Mock<IFileReader>(); var collection = new TemplateCollection(Assembly.GetExecutingAssembly(), reader.Object); // Act var result = collection.GetEnumerator(); // Assert Assert.That(result, Is.Not.Null); }
public void Add_WithString_CreatesStringTemplate() { // Arrange var reader = new Mock<IFileReader>(); var collection = new TemplateCollection(Assembly.GetExecutingAssembly(), reader.Object); // Act collection.Add("This is a text template"); // Assert Assert.That(collection, Has.Some.TypeOf<StringTemplate>()); }
public void Add_WithEmbeddedResource_CreatesFileTemplate() { // Arrange var reader = new Mock<IFileReader>(); var collection = new TemplateCollection(Assembly.GetExecutingAssembly(), reader.Object); // Act collection.Add("Resources.Test.html"); // Assert Assert.That(collection, Has.Some.TypeOf<EmbeddedResourceTemplate>()); }
public TemplateModelTransformer(DocumentBuildContext context, TemplateCollection templateCollection, ApplyTemplateSettings settings, IDictionary<string, object> globals) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; _templateCollection = templateCollection; _settings = settings; _globalVariables = globals; _systemMetadataGenerator = new SystemMetadataGenerator(context); }
public override void Execute() { TemplateCollection.LoadTemplates(GetType().Assembly); var dataProject = Projects.GetFirstProjectByType(BasePluginConstants.ProjectType_Data); var mainOutputConfiguration = DesignModelCollection.RootNamespace.OutputConfiguration; mainOutputConfiguration.RegisterTargetPlatformForDesignModelType(EntityPluginConstants.DesignModelType_Entity, TargetPlatformCollection.GetTargetPlatform("NHibernate")); mainOutputConfiguration.RegisterOutputFolder(new Filter(EntityPluginConstants.OutputModelType_Entity_GeneratedClass), dataProject.GetFolder("Entity")); mainOutputConfiguration.RegisterOutputFolder(new Filter(EntityPluginConstants.OutputModelType_Entity_CustomClass), dataProject.GetFolder("Entity")); mainOutputConfiguration.RegisterOutputFolder(new Filter(EntityPluginConstants.OutputModelType_Entity_CustomClass), dataProject.GetFolder("Entity")); }
public void Add_WithFile_CreatesFileTemplate() { // Arrange var reader = new Mock<IFileReader>(); var collection = new TemplateCollection(Assembly.GetExecutingAssembly(), reader.Object); reader.Setup(x => x.Exists(It.IsAny<string>())).Returns(true); // Act collection.Add("C:\\Files\\Test.html"); // Assert Assert.That(collection, Has.Some.TypeOf<FileTemplate>()); }
public static BaseTemplateManager CreateTemplateManager(params ID[] templateIds) { var templates = new List <Template>(); var templateCollection = new TemplateCollection(); foreach (var id in templateIds) { var builder = new Template.Builder($"test-{id}", id, templateCollection); var template = builder.Template; templates.Add(template); } return(CreateTemplateManager(templates.ToArray())); }
public static Template CreateTemplate(ID templateId, ID baseTemplateId, TemplateCollection templateCollection) { var builder = new Template.Builder($"test-{templateId}", templateId, templateCollection); if (baseTemplateId != (ID)null) { builder.SetBaseIDs(baseTemplateId.ToString()); } var template = builder.Template; templateCollection.Add(template); return(template); }
public void WithMergeCellsTemplateExtractionTest() { var template = FakeTable.GenerateFromStringArray(stringTemplate); template.MergeCells(new Rectangle(new CellPosition("A3"), new CellPosition("B3"))); var templateCollection = new TemplateCollection(template); var rootTemplate = templateCollection.GetTemplate("RootTemplate"); var mergedCells = rootTemplate.MergedCells.ToArray(); mergedCells.Length.Should().Be(1); mergedCells[0].UpperLeft.CellReference.Should().Be("A2"); mergedCells[0].LowerRight.CellReference.Should().Be("B2"); }
public Template Convert(TemplateItem templateItem, TemplateCollection owner) { var builder = templateItem.BuildTemplate(owner); foreach (SectionItem section in templateItem.Children.OfType <SectionItem>()) { var sectionBuilder = section.Build(builder); foreach (FieldItem field in section.Children.OfType <FieldItem>()) { field.Build(sectionBuilder); } } return(builder.Template); }
protected virtual Template BuildTemplate(DbTemplate ft, TemplateCollection templates) { var builder = new Template.Builder(ft.Name, ft.ID, templates); var section = builder.AddSection("Data", ID.NewID); foreach (var field in ft.Fields) { var newField = section.AddField(field.Name, field.ID); newField.SetShared(field.Shared); newField.SetType(field.Type); } builder.SetBaseIDs(string.Join("|", ft.BaseIDs ?? new ID[] { } as IEnumerable <ID>)); return(builder.Template); }
public void Test_template_loading_from_subfolder() { using (var tempFolder = new TempFolder()) { var collection = new TemplateCollection(); tempFolder.CreateWriteTextFile("folder/template-a.hbs", "Contents A"); collection.LoadTemplates(new[] { tempFolder.GetRootPath() }); var templateA = collection.GetTemplate("folder/template-a"); templateA.Should().NotBeNull(); templateA.Name.Should().Be("folder/template-a"); templateA.RenderIntoString(new object()).Should().Be("Contents A"); } }
public override TemplateCollection GetTemplates(CallContext context) { var templates = new TemplateCollection(); if (this.DataStorage == null) { return(templates); } foreach (var ft in this.DataStorage.GetFakeTemplates()) { templates.Add(this.BuildTemplate(ft, templates)); } return(templates); }
void InitializeConfiguration(object o, RoutedEventArgs a) { // try { Model.Databases = DatabaseCollection.Load(Model.Configuration.datafile); Model.Templates = TemplateCollection.Load(Model.Configuration.templatefile); // why is this necessary? Model.Databases.Rechild(); a.Handled = true; // } catch (Exception e) { // throw e; // } finally { if (InitializeCompleteAction != null) { InitializeCompleteAction.Invoke(); } // } }
public TemplateCollection GetTemplates() { MakeSureWeAreReady(); var collection = new TemplateCollection(); var converter = new TemplateItemToStaticTemplateConverter(); foreach (ID id in _idList) { var item = _sitecoreItems[id] as Templates.TemplateItem; if (item != null) { collection.Add(converter.Convert(item, collection)); } } return(collection); }
static public string Parse( DatabaseCollection databases, DatabaseElement database, TemplateCollection templates, TableElement table, TableTemplate template ) { return(Parse( new DataCfg() { Databases = databases, Database = database, Table = table, Templates = templates, Template = template })); }
public void Test_template_registration() { var collection = new TemplateCollection(); collection.AddTemplate("test", "Hi {{User.Name}}"); var template = collection.GetTemplate("test"); template.Should().NotBeNull(); template.Name.Should().Be("test"); template.RenderIntoString(new { User = new { Name = "Test123" } }).Should().Be("Hi Test123"); }
public override TemplateCollection GetTemplates(CallContext context) { var templates = new TemplateCollection(); foreach (var ft in this.DataStorage.FakeTemplates.Values) { var builder = new Template.Builder(ft.Name, ft.ID, new TemplateCollection()); var section = builder.AddSection("Data", ID.NewID); foreach (var field in ft.Fields) { section.AddField(field.Name, field.ID); } templates.Add(builder.Template); } return templates; }
public static void UpdateFileMap(DocumentBuildContext context, string outputDirectory, TemplateCollection templateCollection) { //update internal XrefMap if (context.XRefSpecMap != null) { foreach (var pair in context.XRefSpecMap) { string targetFilePath; if (context.FileMap.TryGetValue(pair.Value.Href, out targetFilePath)) { pair.Value.Href = targetFilePath; } else { Logger.LogWarning($"{pair.Value.Href} is not found in .filemap"); } } } context.SetExternalXRefSpec(); }
public void TemplateCollectionConstructor_WithNoFileReader_ThrowsException() { // Arrange IFileReader reader = null; // Act var collection = new TemplateCollection(Assembly.GetExecutingAssembly(), reader); // Assert // Exception thrown }
/// <summary> /// TemplateName can be either file or folder /// 1. If TemplateName is file, it is considered as the default template /// 2. If TemplateName is a folder, files inside the folder is considered as the template, each file is named after {DocumentType}.{extension} /// </summary> /// <param name="templateName"></param> /// <param name="resourceProvider"></param> public TemplateProcessor(ResourceCollection resourceProvider) { _resourceProvider = resourceProvider; _templates = new TemplateCollection(resourceProvider); }
private IEnumerable<TemplateResourceInfo> ExtractDependentFilePaths(TemplateCollection templates) { return templates.Values.SelectMany(s => s).SelectMany(s => s.Resources); }
public override TemplateCollection GetTemplates(CallContext context) { var templates = new TemplateCollection(); if (this.DataStorage() == null) { return templates; } foreach (var ft in this.DataStorage().GetFakeTemplates()) { templates.Add(this.BuildTemplate(ft, templates)); } return templates; }
public override TemplateCollection GetTemplates(CallContext context) { var owner = new TemplateCollection(); var database = GetDatabase(context); var templatesRoot = database.GetItems(ItemIDs.TemplateRoot.ToString()); var templates = new List<Template>(templatesRoot.Count()); foreach (var syncItem in templatesRoot) { if (ID.IsNullOrEmpty(ID.Parse(syncItem.ID)) || syncItem.ID.Equals(TemplateIDs.TemplateFolder.ToString())) { continue; } var templateBuilder = new Template.Builder(syncItem.Name, ID.Parse(syncItem.ID), owner); templateBuilder.SetFullName(syncItem.ItemPath); var dataSection = templateBuilder.AddSection("Data", ID.NewID); foreach (var syncField in syncItem.SharedFields) { if (string.IsNullOrEmpty(syncField.FieldID) || string.IsNullOrEmpty(syncField.FieldName)) { continue; } if (syncField.FieldID.Equals(FieldIDs.BaseTemplate.ToString())) { templateBuilder.SetBaseIDs(syncField.FieldValue); } else { dataSection.AddField(syncField.FieldName, ID.Parse(syncField.FieldID)); } } var version = syncItem.GetLatestVersions().FirstOrDefault(); foreach (var syncField in version.Fields) { if (string.IsNullOrEmpty(syncField.FieldID) || string.IsNullOrEmpty(syncField.FieldName)) { continue; } dataSection.AddField(syncField.FieldName, ID.Parse(syncField.FieldID)); } templates.Add(templateBuilder.Template); } owner.Reset(templates.ToArray()); return owner; }
public TemplateCollection GetTemplates(int Number = 10) { DataSet templatesDS = new DataSet(); InternalTemplate = new Template(); TemplateCollection Forms = new TemplateCollection(); comm.CommandText = "SELECT TOP(@num) ID FROM " + Config.TableNames["Templates"]; comm.Parameters.AddWithValue("@num", Number); try { da.Fill(templatesDS); } catch (Exception ex) { throw new Exception("Error trying to open database connection in GetTopForms: " + ex.Message, ex); } var ids = templatesDS.GetResults(); if (ids != null) { foreach (DataRow id in ids) { Template formRef = GetTemplate((int)id["ID"]); Forms.Add(formRef); } } else { //throw new Exception("No results found"); return null; } return Forms; }
public static void SetTemplatesCollection(DependencyObject target, TemplateCollection value) { target.SetValue(TemplatesCollectionProperty, value); }
public static TemplateManifestItem Transform(DocumentBuildContext context, ManifestItem item, TemplateCollection templateCollection, string outputDirectory, bool exportMetadata, Func<string, string> metadataFilePathProvider) { var baseDirectory = context.BuildOutputFolder ?? string.Empty; var manifestItem = new TemplateManifestItem { DocumentType = item.DocumentType, OriginalFile = item.LocalPathFromRepoRoot, OutputFiles = new Dictionary<string, string>() }; if (templateCollection == null || templateCollection.Count == 0) { return manifestItem; } try { var model = item.Model?.Content; var templates = templateCollection[item.DocumentType]; // 1. process model if (templates == null) { // Logger.LogWarning($"There is no template processing {item.DocumentType} document \"{item.LocalPathFromRepoRoot}\""); } else { var modelFile = Path.Combine(baseDirectory, item.ModelFile); var systemAttrs = new SystemAttributes(context, item, TemplateProcessor.Language); foreach (var template in templates) { var extension = template.Extension; string outputFile = Path.ChangeExtension(item.ModelFile, extension); string outputPath = Path.Combine(outputDirectory ?? string.Empty, outputFile); var dir = Path.GetDirectoryName(outputPath); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); string transformed; if (model == null) { // TODO: remove // currently keep to pass UT transformed = template.Transform(item.ModelFile, systemAttrs); } else { var result = template.TransformModel(model, systemAttrs); if (exportMetadata) { if (metadataFilePathProvider == null) { throw new ArgumentNullException(nameof(metadataFilePathProvider)); } JsonUtility.Serialize(metadataFilePathProvider(outputPath), result.Model); } transformed = result.Result; } if (!string.IsNullOrWhiteSpace(transformed)) { if (extension.Equals(".html", StringComparison.OrdinalIgnoreCase)) { TranformHtml(context, transformed, item.ModelFile, outputPath); } else { File.WriteAllText(outputPath, transformed, Encoding.UTF8); } Logger.Log(LogLevel.Verbose, $"Transformed model \"{item.ModelFile}\" to \"{outputPath}\"."); } else { // TODO: WHAT to do if is transformed to empty string? STILL creat empty file? Logger.LogWarning($"Model \"{item.ModelFile}\" is transformed to empty string with template \"{template.Name}\""); File.WriteAllText(outputPath, string.Empty); } manifestItem.OutputFiles.Add(extension, outputFile); } } // 2. process resource if (item.ResourceFile != null) { PathUtility.CopyFile(Path.Combine(baseDirectory, item.ResourceFile), Path.Combine(outputDirectory, item.ResourceFile), true); manifestItem.OutputFiles.Add("resource", item.ResourceFile); } } catch (Exception e) { Logger.LogWarning($"Unable to transform {item.ModelFile}: {e.Message}. Ignored."); } return manifestItem; }
protected virtual Template BuildTemplate(DbTemplate ft, TemplateCollection templates) { var builder = new Template.Builder(ft.Name, ft.ID, templates); var sectionName = "Data"; var sectionId = ID.NewID; var sectionItem = ft.Children.FirstOrDefault(i => i.TemplateID == TemplateIDs.TemplateSection); if (sectionItem != null) { sectionName = sectionItem.Name; sectionId = sectionItem.ID; } var section = builder.AddSection(sectionName, sectionId); foreach (var field in ft.Fields) { if (ft.ID != TemplateIDs.StandardTemplate && field.IsStandard()) { continue; } var newField = section.AddField(field.Name, field.ID); newField.SetShared(field.Shared); newField.SetType(field.Type); newField.SetSource(field.Source); } if (ft.ID != TemplateIDs.StandardTemplate) { builder.SetBaseIDs(ft.BaseIDs.Any() ? string.Join("|", ft.BaseIDs as IEnumerable<ID>) : TemplateIDs.StandardTemplate.ToString()); } return builder.Template; }
public TemplateCollection FetchByID(object TemplateId) { TemplateCollection coll = new TemplateCollection().Where("TemplateId", TemplateId).Load(); return coll; }
public TemplateCollection FetchByQuery(Query qry) { TemplateCollection coll = new TemplateCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
int BuildTemplates(out TemplateCollection templates, out string strError) { strError = ""; templates = new TemplateCollection(); for (int i = 0; i < this.listView_objects.Items.Count; i++) { ListViewItem item = this.listView_objects.Items[i]; if (item.Checked == false) continue; if (item.ImageIndex == ResTree.RESTYPE_FOLDER || item.ImageIndex == ResTree.RESTYPE_FILE) { continue; } string strDbName = item.Text; string strUrl = item.SubItems[1].Text; DatabaseObjectTree tree = new DatabaseObjectTree(); tree.Initial(MainForm.Servers, MainForm.Channels, MainForm.stopManager, strUrl, strDbName); // RmsChannel channel = MainForm.Channels.GetChannel(strUrl); if (channel == null) goto ERROR1; List<string[]> logicNames = null; string strType; string strSqlDbName; string strKeysDef; string strBrowseDef; long nRet = channel.DoGetDBInfo( strDbName, "all", out logicNames, out strType, out strSqlDbName, out strKeysDef, out strBrowseDef, out strError); if (nRet == -1) goto ERROR1; Template template = new Template(); template.LogicNames = logicNames; template.Type = strType; template.SqlDbName = strSqlDbName; template.KeysDef = strKeysDef; template.BrowseDef = strBrowseDef; template.Object = tree.Root; templates.Add(template); } return 0; ERROR1: return -1; }
/// <summary> /// Sets the value of the <paramref name="element"/>'s attached <see cref="TemplatesProperty"/> /// </summary> /// <param name="element">The <see cref="UIElement"/> for which the attached property's value will be set</param> /// <param name="value">The array of <see cref="Template"/> objects to be used by the given <paramref name="element"/></param> public static void SetTemplates(UIElement element, TemplateCollection value) { element.SetValue(TemplatesProperty, value); }