public async Task <Deployment> BeginDeploymentAsync(IDeployable deployment) { using (var client = await _managementClientProvider.CreateResourceManagementClient(deployment.SubscriptionId)) { await client.ResourceGroups.CreateOrUpdateAsync( deployment.ResourceGroupName, new ResourceGroup { Location = deployment.Location }); var templateParams = deployment.DeploymentParameters; var properties = new Microsoft.Azure.Management.ResourceManager.Models.Deployment { Properties = new DeploymentProperties { Template = await _templateProvider.GetTemplate(deployment.TemplateName), Parameters = _templateProvider.GetParameters(templateParams), Mode = DeploymentMode.Incremental } }; // Start the ARM deployment var deploymentResult = await client.Deployments.BeginCreateOrUpdateAsync( deployment.ResourceGroupName, deployment.DeploymentName, properties); return(ToDeploymentStatus(deploymentResult)); } }
public void Compile(IReadOnlyCollection <AbstractFunctionDefinition> functionDefinitions, OpenApiOutputModel openApiOutputModel, string outputBinaryFolder, string outputNamespaceName) { HandlebarsHelperRegistration.RegisterHelpers(); foreach (AbstractFunctionDefinition functionDefinition in functionDefinitions) { string templateSource = _templateProvider.GetJsonTemplate(functionDefinition); Func <object, string> template = Handlebars.Compile(templateSource); functionDefinition.AssemblyName = $"{outputNamespaceName}.dll"; functionDefinition.FunctionClassTypeName = $"{functionDefinition.Namespace}.{functionDefinition.Name}"; string json = template(functionDefinition); WriteFunctionTemplate(outputBinaryFolder, functionDefinition.Name, json); } if (openApiOutputModel != null && openApiOutputModel.IsConfiguredForUserInterface) { string templateSource = _templateProvider.GetTemplate("swaggerui", "json"); Func <object, string> template = Handlebars.Compile(templateSource); string json = template(new { AssemblyName = $"{outputNamespaceName}.dll", Namespace = outputNamespaceName }); WriteFunctionTemplate(outputBinaryFolder, "OpenApiProvider", json); } }
public TModel GetFormattedModel() { var template = _templateProvider.GetTemplate(); var output = (TModel)Activator.CreateInstance(typeof(TModel), template); return(output); }
private void CreateNugetRestoreProj(string nugetPackProjPath, string name, string version) { string template = _templateProvider.GetTemplate(NugetRestoreProjName); string nugetRestoreProjFileContent = ReplaceMacro(template, name, version); File.WriteAllText(nugetPackProjPath, nugetRestoreProjFileContent); }
/// <summary> /// Create a New Report Using the Specified Template /// </summary> public Guid CreateReportWithTemplate(Guid templateId, bool isSupplement, TReportDetails details) { // Find the Template var template = TemplateProvider.GetTemplate(templateId); // Create the Report return(CreateReport(template, isSupplement, details).Id); }
private void CreateFromTemplate(PackageInfo packageInfo, string filesSection, string dependenciesSection, string filePath) { string template = _templateProvider.GetTemplate(_packageNuspecFileName); string nuspecFileContent = ReplaceMacro(template, packageInfo, filesSection, dependenciesSection); File.WriteAllText(filePath, nuspecFileContent); }
public async Task <EmailRequest> BuildAsync <T>(EmailRequest <T> request) where T : class { string templateName = _resolver.Resolve(request.Model); string templateContent = await _provider.GetTemplate(templateName).ConfigureAwait(false); string compiledBody = await _compiler.CompileBody(request.Model, templateContent).ConfigureAwait(false); return(request.Copy(compiledBody)); }
private List <SyntaxTree> CompileSource(IReadOnlyCollection <AbstractFunctionDefinition> functionDefinitions, OpenApiOutputModel openApiOutputModel, Type backlinkType, PropertyInfo backlinkPropertyInfo, string newAssemblyNamespace, string outputAuthoredSourceFolder) { List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); DirectoryInfo directoryInfo = outputAuthoredSourceFolder != null ? new DirectoryInfo(outputAuthoredSourceFolder) : null; if (directoryInfo != null && !directoryInfo.Exists) { directoryInfo = null; } foreach (AbstractFunctionDefinition functionDefinition in functionDefinitions) { string templateSource = _templateProvider.GetCSharpTemplate(functionDefinition); AddSyntaxTreeFromHandlebarsTemplate(templateSource, functionDefinition.Name, functionDefinition, directoryInfo, syntaxTrees); } if (openApiOutputModel != null && openApiOutputModel.IsConfiguredForUserInterface) { string templateSource = _templateProvider.GetTemplate("swaggerui", "csharp"); AddSyntaxTreeFromHandlebarsTemplate(templateSource, "SwaggerUi", new { Namespace = newAssemblyNamespace }, directoryInfo, syntaxTrees); } { string templateSource = _templateProvider.GetTemplate("startup", "csharp"); AddSyntaxTreeFromHandlebarsTemplate(templateSource, "Startup", new { Namespace = newAssemblyNamespace }, directoryInfo, syntaxTrees); } CreateLinkBack(functionDefinitions, backlinkType, backlinkPropertyInfo, newAssemblyNamespace, directoryInfo, syntaxTrees); return(syntaxTrees); }
public void Compile(IReadOnlyCollection <AbstractFunctionDefinition> functionDefinitions, OpenApiOutputModel openApiOutputModel, string outputBinaryFolder, string outputNamespaceName) { HandlebarsHelperRegistration.RegisterHelpers(); foreach (AbstractFunctionDefinition functionDefinition in functionDefinitions) { string templateSource = _templateProvider.GetJsonTemplate(functionDefinition); Func <object, string> template = Handlebars.Compile(templateSource); functionDefinition.AssemblyName = $"{outputNamespaceName}.dll"; functionDefinition.FunctionClassTypeName = $"{functionDefinition.Namespace}.{functionDefinition.Name}"; string json = template(functionDefinition); WriteFunctionTemplate(outputBinaryFolder, functionDefinition.Name, json); if (functionDefinition is CosmosDbFunctionDefinition cosmosDbFunctionDefinition) { if (cosmosDbFunctionDefinition.TrackRemainingWork) { TimerFunctionDefinition cosmosMonitorDefinition = new TimerFunctionDefinition(functionDefinition.CommandType) { AssemblyName = cosmosDbFunctionDefinition.AssemblyName, CommandDeserializerType = null, CommandType = null, CronExpression = cosmosDbFunctionDefinition.RemainingWorkCronExpression, FunctionClassTypeName = $"{functionDefinition.Namespace}.Monitor{functionDefinition.Name}" }; string timerTemplateSource = _templateProvider.GetJsonTemplate(cosmosMonitorDefinition); Func <object, string> timerTemplate = Handlebars.Compile(timerTemplateSource); string timerJson = timerTemplate(cosmosMonitorDefinition); WriteFunctionTemplate(outputBinaryFolder, $"Monitor{functionDefinition.Name}", timerJson); } } } if (openApiOutputModel != null && openApiOutputModel.IsConfiguredForUserInterface) { string templateSource = _templateProvider.GetTemplate("swaggerui", "json"); Func <object, string> template = Handlebars.Compile(templateSource); string json = template(new { AssemblyName = $"{outputNamespaceName}.dll", Namespace = outputNamespaceName }); WriteFunctionTemplate(outputBinaryFolder, "OpenApiProvider", json); } }
/// <summary> /// Finds and renders a template /// </summary> /// <param name="viewContext">The view context.</param> /// <param name="viewData">The view data.</param> /// <param name="modelExplorer">The model explorer.</param> /// <param name="purpose">The purpose.</param> /// <param name="htmlFieldName">Name of the HTML field.</param> /// <param name="templateName">Name of the template.</param> /// <param name="additionalViewData">The additional view data.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// <paramref name="viewContext"/>, /// <paramref name="viewData"/>, /// <paramref name="modelExplorer"/>, /// or /// <paramref name="purpose"/> /// </exception> /// <exception cref="InvalidOperationException"> /// When no template is found /// </exception> public IHtmlContent RenderTemplate( ViewContext viewContext, ViewDataDictionary viewData, ModelExplorer modelExplorer, string purpose, string htmlFieldName, string templateName, object additionalViewData) { Guard.NotNull(viewContext, nameof(viewContext)); Guard.NotNull(viewData, nameof(viewData)); Guard.NotNull(modelExplorer, nameof(modelExplorer)); Guard.NotNullOrEmpty(purpose, nameof(purpose)); if (viewData.TemplateInfo.Visited(modelExplorer)) { return(HtmlString.Empty); } var templateViewData = CreateTemplateViewData( viewData, modelExplorer, purpose: purpose, htmlFieldName: htmlFieldName, additionalViewData: additionalViewData); var templateContext = new ViewContext(viewContext, viewContext.View, templateViewData, viewContext.Writer); var template = _templateProvider.GetTemplate( _viewEngine, templateContext, purpose: purpose, templateName: templateName); if (template is null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.TemplateHelpers_NoTemplate, modelExplorer.ModelType.FullName)); } templateViewData.TemplateInfo.AddVisited(modelExplorer.Model ?? modelExplorer.ModelType); var result = template.Render(this, _bufferScope, templateContext); return(result); }
private async Task DeployRepository(AssetRepository repository) { try { using (var client = await _clientProvider.CreateResourceManagementClient(repository.SubscriptionId)) { await client.ResourceGroups.CreateOrUpdateAsync(repository.ResourceGroupName, new ResourceGroup { Location = repository.Subnet.Location }); var templateParams = repository.GetTemplateParameters(); var properties = new Microsoft.Azure.Management.ResourceManager.Models.Deployment { Properties = new DeploymentProperties { Template = await _templateProvider.GetTemplate(repository.GetTemplateName()), Parameters = _templateProvider.GetParameters(templateParams), Mode = DeploymentMode.Incremental } }; // Start the ARM deployment await client.Deployments.BeginCreateOrUpdateAsync( repository.Deployment.ResourceGroupName, repository.Deployment.DeploymentName, properties); // TODO re-enable below for background monitoring. // Queue a request for the background host to monitor the deployment // and update the state and IP address when it's done. //await _deploymentQueue.Add(new ActiveDeployment //{ // FileServerName = repository.Name, // StartTime = DateTime.UtcNow, //}); repository.State = StorageState.Creating; repository.InProgress = false; await UpdateRepository(repository); } } catch (CloudException ex) { _logger.LogError(ex, $"Failed to deploy storage server: {ex.Message}."); throw; } }
public async Task <Mail> GetBody() { StringBuilder body = new StringBuilder(); var templateBody = await _templateProvider.GetTemplate(TemplateFile); foreach (var param in _parameters) { body.Append(templateBody.Replace($"<{param.Key}>", param.Value)); } return(new Mail() { Body = body.ToString(), IsHtml = true }); }
private List <SyntaxTree> CompileSource(IReadOnlyCollection <AbstractFunctionDefinition> functionDefinitions, OpenApiOutputModel openApiOutputModel, Type functionAppConfigurationType, string newAssemblyNamespace, string outputAuthoredSourceFolder) { List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); DirectoryInfo directoryInfo = outputAuthoredSourceFolder != null ? new DirectoryInfo(outputAuthoredSourceFolder) : null; if (directoryInfo != null && !directoryInfo.Exists) { directoryInfo = null; } foreach (AbstractFunctionDefinition functionDefinition in functionDefinitions) { string templateSource = _templateProvider.GetCSharpTemplate(functionDefinition); AddSyntaxTreeFromHandlebarsTemplate(templateSource, functionDefinition.Name, functionDefinition, directoryInfo, syntaxTrees); } if (openApiOutputModel != null && openApiOutputModel.IsConfiguredForUserInterface) { string templateSource = _templateProvider.GetTemplate("swaggerui", "csharp"); AddSyntaxTreeFromHandlebarsTemplate(templateSource, "SwaggerUi", new { Namespace = newAssemblyNamespace }, directoryInfo, syntaxTrees); } // Now we need to create a class that references the assembly with the configuration builder // otherwise the reference will be optimised away by Roslyn and it will then never get loaded // by the function host - and so at runtime the builder with the runtime info in won't be located string linkBackTemplateSource = _templateProvider.GetCSharpLinkBackTemplate(); Func <object, string> linkBackTemplate = Handlebars.Compile(linkBackTemplateSource); LinkBackModel linkBackModel = new LinkBackModel { ConfigurationTypeName = functionAppConfigurationType.EvaluateType(), Namespace = newAssemblyNamespace }; string outputLinkBackCode = linkBackTemplate(linkBackModel); OutputDiagnosticCode(directoryInfo, "ReferenceLinkBack", outputLinkBackCode); SyntaxTree linkBackSyntaxTree = CSharpSyntaxTree.ParseText(outputLinkBackCode); syntaxTrees.Add(linkBackSyntaxTree); return(syntaxTrees); }
private async Task DeployFileServer(NfsFileServer repository, IManagementClientProvider managementClientProvider) { try { using (var client = await managementClientProvider.CreateResourceManagementClient(repository.SubscriptionId)) { await client.ResourceGroups.CreateOrUpdateAsync(repository.ResourceGroupName, new ResourceGroup { Location = repository.Subnet.Location }); var templateParams = GetTemplateParameters(repository); var properties = new Deployment { Properties = new DeploymentProperties { Template = await _templateProvider.GetTemplate("linux-file-server.json"), Parameters = _templateProvider.GetParameters(templateParams), Mode = DeploymentMode.Incremental } }; // Start the ARM deployment await client.Deployments.BeginCreateOrUpdateAsync( repository.ResourceGroupName, repository.DeploymentName, properties); // Queue a request for the background host to monitor the deployment // and update the state and IP address when it's done. await _deploymentQueue.Add(new ActiveDeployment { FileServerName = repository.Name, StartTime = DateTime.UtcNow, }); repository.ProvisioningState = ProvisioningState.Running; repository.InProgress = false; await UpdateRepository(repository); } } catch (CloudException ex) { _logger.LogError(ex, $"Failed to deploy NFS server: {ex.Message}."); throw; } }
protected override void Send(AuditableAction action, Dictionary <string, string> tokens, WebhookNotificationChannelDefinition settings) { HttpClient client = new HttpClient(); HttpRequestMessage message = new HttpRequestMessage(); string content = action.IsSuccess ? templates.GetTemplate(settings.TemplateSuccess) : templates.GetTemplate(settings.TemplateFailure); content = TokenReplacer.ReplaceAsJson(tokens, content); message.Content = new StringContent(content, Encoding.UTF8, settings.ContentType); message.RequestUri = new Uri(settings.Url); message.Method = new HttpMethod(settings.HttpMethod); var response = client.SendAsync(message).GetAwaiter().GetResult(); response.EnsureSuccessStatusCode(); }
protected Type GetTemplateCodeTypeByFile(String Name) { if (TemplateProvider == null) { throw(new Exception("No specified TemplateProvider")); } lock (CachedTemplatesByFile) { if (!CachedTemplatesByFile.ContainsKey(Name)) { using (var TemplateStream = TemplateProvider.GetTemplate(Name)) { return(CachedTemplatesByFile[Name] = GetTemplateCodeTypeByString(TemplateStream.ReadAllContentsAsString(Encoding))); } } return(CachedTemplatesByFile[Name]); } }
protected override void Send(AuditableAction action, Dictionary <string, string> tokens, SmtpNotificationChannelDefinition settings) { string message = action.IsSuccess ? templates.GetTemplate(settings.TemplateSuccess) : templates.GetTemplate(settings.TemplateFailure); string subject = GetSubjectLine(message, action.IsSuccess); message = TokenReplacer.ReplaceAsHtml(tokens, message); subject = TokenReplacer.ReplaceAsPlainText(tokens, subject); HashSet <string> recipients = new HashSet <string>(StringComparer.OrdinalIgnoreCase); settings.EmailAddresses.ForEach(t => recipients.Add(t)); if (recipients.Remove("{user.EmailAddress}")) { if (action?.User?.EmailAddress != null) { recipients.Add(action.User.EmailAddress); } } this.SendEmail(recipients, subject, message); }
public async Task <TemplateToPdfCommandResult> Handle(TemplateToPdfCommand request, CancellationToken cancellationToken) { string template = _templateProvider.GetTemplate(request); TemplateMetadataEntity templateMetadataEntity = _parser.ParseTemplate(template); foreach (TokenMapEntity tokenMapEntity in templateMetadataEntity.TokenMapEntities) { DataTable dataTable = _saleRepository.QueryView(tokenMapEntity.ViewName, request.Id); Dictionary <string, string> data = _parser.CreateDynamicMap(tokenMapEntity, dataTable.Rows[0]); template = _templateCompiler.Compile(template, data); } Stream stream = _pdfRenderer.RenderHtml(template); return(new TemplateToPdfCommandResult { Stream = stream }); }
public TemplateResult LoadTemplate(object data, TemplateProperty templateProperty) { TemplateContent content = fileProvider.GetTemplate(templateProperty); if (content == null) { return(null); } TemplateResult result = null; foreach (var g in generators) { result = g.GenerateResult(data, content); if (result != null) { break; } } return(result); }
public void SendMail(string from, string to, string messageType, IMessageBodyDictionary body) { var temp = templateProvider.GetTemplate(messageType); var content = contentBuilder.BuildContent(temp, body); //Create message var message = new MimeMessage(); message.To.Add(new MailboxAddress(to)); message.From.Add(new MailboxAddress(from)); message.Body = new TextPart("html") { Text = content }; var cred = credentialsProvider.GetCredentials(); smtpClient.Connect(cred.Username, cred.Password); smtpClient.SendMessage(message); smtpClient.Diconnect(); }
protected string GetTemplate(ChannelType channelType) { return(templateProvider.GetTemplate(channelType)); }
public async Task <string> FormatEmailMessage <TModel>(string templateName, TModel model) where TModel : class { var template = _templateProvider.GetTemplate(templateName); return(await _templateParser.Parse(template, model)); }
private void CreateNugetPackProj(string nugetPackProjPath) { string template = _templateProvider.GetTemplate(NugetPackProjName); File.WriteAllText(nugetPackProjPath, template); }