/// <summary>
 /// Renderiza um template a partir do nome, substituindo as variáveis do template pelas variáveis passadas como parâmetro
 /// </summary>
 /// <param name="templateName">Nome do Template</param>
 /// <param name="data">Dicionário com as váriáveis (Chave/Valor)</param>
 /// <returns>Template com as variávies substituídas</returns>
 public string RenderTemplate(string templateName, IDictionary<string, object> data)
 {
     DynamicViewBag viewBag = new DynamicViewBag();
     viewBag.AddDictionaryValuesEx(data);
     var result = Razor.Parse(templateName, null, viewBag, null);
     return result;
 }
        public void CanAddViewBag()
        {
            var templateResolverMock = new Mock<ITemplateResolver>();

            // Request for html template
            templateResolverMock
                .Setup(x => x.ResolveTemplate(It.IsAny<string>(), false))
                .Returns("<b>Welcome @ViewBag.Name</b>");

            // Request for plain text template returns empty string (indicating the plain text template should no be used)
            templateResolverMock
                .Setup(x => x.ResolveTemplate(It.IsAny<string>(), true))
                .Returns("");

            var razorMailMessageFactory = new RazorMailMessageFactory(templateResolverMock.Object, typeof(DefaultTemplateBase<>), null, new Mock<InMemoryTemplateCache>().Object);
            var model = new { };

            dynamic viewBag = new DynamicViewBag();
            viewBag.Name = "Robin";

            var mailMessage = razorMailMessageFactory.Create("TestTemplate", model, viewBag);

            const string expectedResult = "<b>Welcome Robin</b>";
            Assert.AreEqual(expectedResult, mailMessage.Body);
            Assert.AreEqual(expectedResult, new StreamReader(mailMessage.AlternateViews[0].ContentStream).ReadToEnd());
        }
        public async Task<string> CreatePageForIncidentAsync(string siteRootDirectory, string sectionId, Incident incident, IEnumerable<FileContent> inspectionPhotos, IEnumerable<Video> incidentVideos)
        {
            var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml");
            var template = System.IO.File.ReadAllText(templateFile);
            var viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("InspectionPhotos", inspectionPhotos);
            viewBag.AddValue("IncidentVideos", incidentVideos);

            var html = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag);
            var content = new MultipartFormDataContent();
            content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation");

            foreach (var image in inspectionPhotos)
            {
                var itemContent = new ByteArrayContent(image.Bytes);
                var contentType = MimeMapping.GetMimeMapping(image.Name);
                itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(itemContent, image.Id);
            }

            this.pageEndPoint = string.Format("{0}/sections/{1}/pages", serviceBaseUrl, sectionId);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint);
            requestMessage.Content = content;

            var responseMessage = await HttpSendAsync(requestMessage, accessToken);
            if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                throw new HttpResponseException(responseMessage.StatusCode);

            var reponseObject = await GetReponseObjectAsync(responseMessage);
            return (string)reponseObject.links.oneNoteWebUrl.href;
        }
        private DynamicViewBag getInitViewBag()
        {
            var viewBag = new DynamicViewBag();
            viewBag.AddValue("HelpRoute", HelpRoute);  //将Help路由 传递到View

            return viewBag;
        }
 /// <summary>
 /// Creates a new instance of DynamicViewBag, setting initial values in the ViewBag.
 /// </summary>
 /// <param name="viewBag">The initial view bag data or NULL for an empty ViewBag.</param>
 public ExecuteContext(DynamicViewBag viewBag)
 {
     if (viewBag == null)
         _viewBag = new DynamicViewBag();
     else
         _viewBag = viewBag;
 }
 public dynamic Transform(string template, dynamic model, Slice slice)
 {
     var viewBag = new DynamicViewBag();
     model.Slice = slice;
     Razor.RunWithTemplate(template ?? "", model, viewBag);
     return ((dynamic)viewBag).Exports;
 }
        /// <summary>
        /// When overriden returns ViewBag for Razor view.
        /// </summary>
        /// <returns></returns>
        public virtual DynamicViewBag GetViewBag() {
            DynamicViewBag bag = new DynamicViewBag();

            bag.AddValue("Title", "Default page title");

            return bag;
        }
        public override DynamicViewBag GetViewBag() {
            DynamicViewBag bag = new DynamicViewBag();

            bag.AddValue("Title", "Razor in Starcounter");
            bag.AddValue("Products", Db.SQL("SELECT p FROM Simplified.Ring3.Product p ORDER BY p.Name"));

            return bag;
        }
Exemple #9
0
 protected string View(string viewName, object model)
 {
     var resourceName = string.Format("Scrutiny.Views.{0}.{1}.cshtml", this.Name, viewName);
     var template = Resources.GetString(resourceName);
     var viewBag = new RazorEngine.Templating.DynamicViewBag(this.ViewBag);
     var result = RazorEngine.Engine.Razor.RunCompile(template, resourceName, null, model, viewBag);
     return result;
 }
 /// <summary>
 /// Creates a new instance of DynamicViewBag, setting initial values in the ViewBag.
 /// </summary>
 /// <param name="viewBag">The initial view bag data or NULL for an empty ViewBag.</param>
 public ExecuteContext(DynamicViewBag viewBag)
 {
     if (viewBag == null)
         _viewBag = new DynamicViewBag();
     else
         _viewBag = viewBag;
     _currentSectionStack.Push(new HashSet<string>());
 }
Exemple #11
0
 /// <summary>
 /// Initialises a new instance of <see cref="DynamicViewBag"/>
 /// </summary>
 /// <param name="viewbag">The parent view bag.</param>
 public DynamicViewBag(DynamicViewBag viewbag = null)
 {
     if (viewbag != null)
     {
         // Add the viewbag to the current dictionary.
         foreach (var pair in viewbag._dict)
             _dict.Add(pair);
     }
 }
        // GET: RazorResult
        public ActionResult Index()
        {
            const string articleTemplate = "default_template_Template";
            var model = new List<NPArticleModel>
            {
                new NPArticleModel
                {
                    Title = "This is the first article",
                    Body = "This is the body of the first article",
                    PublishedDate = DateTime.Now,
                    AuthorDisplayName = "First Author",
                    RelativePublishedDate = DateTime.Now
                },
                new NPArticleModel
                {
                    Title = "This is the second article",
                    Body = "This is the body of the second article",
                    PublishedDate = DateTime.Now.AddDays(-1),
                    AuthorDisplayName = "second Author",
                    RelativePublishedDate = DateTime.Now
                },
                new NPArticleModel
                {
                    Title = "This is the third article",
                    Body = "This is the body of the third article",
                    PublishedDate = DateTime.Now.AddDays(-2),
                    AuthorDisplayName = "third Author",
                    RelativePublishedDate = DateTime.Now
                },
                new NPArticleModel
                {
                    Title = "This is the fourth article",
                    Body = "This is the body of the fourth article",
                    PublishedDate = DateTime.Now.AddDays(-3),
                    AuthorDisplayName = "fourth Author",
                    RelativePublishedDate = DateTime.Now
                }
            };
            var key = _service.GetKey(articleTemplate);
            var path = Path.Combine(_webPath, articleTemplate + ".cshtml");
            dynamic viewbag = new DynamicViewBag();
            viewbag.SPHostWebUrl = "https://tenant.sharepoint.com";
            // This text is added only once to the file.
            if (!System.IO.File.Exists(path))
            {
                throw new FileNotFoundException(string.Format("Cannot locate template file at {0}",path));
            }
            var template = System.IO.File.ReadAllText(path);
            // For the ResolvePathTemplateManager
            // var renderedresult = _service.RunCompile(key, model.GetType(), model);

            // For the DelegateTemplateManager
            var renderedresult = _service.RunCompile(template, articleTemplate, null, model, viewBag: (DynamicViewBag)viewbag);

            return Content(renderedresult);
        }
        //методы
        public virtual string Transform(string templateName, Dictionary<string, string> replaceStrings)
        {
            var viewBag = new DynamicViewBag();
            foreach (KeyValuePair<string, string> item in replaceStrings)
            {
                viewBag.AddValue(item.Key, item.Value);
            }

            return Engine.Razor.RunCompile(templateName, viewBag: viewBag);
        }
        public async Task Invoke(HttpContext context)
        {
            var requestPath = context.Request.Path.Value;
            if (!String.IsNullOrWhiteSpace(requestPath) &&
                requestPath.Equals("/", StringComparison.CurrentCultureIgnoreCase))
            {
                requestPath = "/Default.cshtml";
            }

            var fileInfo = _env.WebRootFileProvider.GetFileInfo(requestPath);



            if (fileInfo.Exists && CanHandle(fileInfo))
            {
                context.Response.StatusCode = 200;
                context.Response.ContentType = "text/html";

                var dynamicViewBag = new DynamicViewBag();
                dynamicViewBag.AddValue("IsHttps", context.Request.IsHttps);

                var config = new TemplateServiceConfiguration();
                // .. configure your instance
                config.TemplateManager = new ResolvePathTemplateManager(new[] { _env.MapPath("/Shared") });
                var service = RazorEngineService.Create(config);

                service.WithContext(new RazorPageContext { HttpContext = context });
                Engine.Razor = service;

                string result;
                if (Engine.Razor.IsTemplateCached(fileInfo.PhysicalPath, null))
                {
                    result = Engine.Razor.Run(fileInfo.PhysicalPath, null, null, dynamicViewBag);
                }
                else
                {
                    using (var stream = fileInfo.CreateReadStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var razor = await reader.ReadToEndAsync();
                            result = Engine.Razor.RunCompile(razor, fileInfo.PhysicalPath, null, null, dynamicViewBag);
                        }

                    }
                }

                await context.Response.WriteAsync(result);

                return;
            }

            await _next(context);
        }
 internal override ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType, ITemplateKey context)
 {
     var templateKey = GetKey(cacheName, resolveType, context);
     ICompiledTemplate compiledTemplate;
     if (!Configuration.CachingProvider.TryRetrieveTemplate(templateKey, modelType, out compiledTemplate))
     {
         compiledTemplate = Compile(templateKey, modelType);
         Configuration.CachingProvider.CacheTemplate(compiledTemplate, templateKey);
     }
     return CreateTemplate(compiledTemplate, model, viewbag);
 }
        internal virtual ITemplate CreateTemplate(ICompiledTemplate template, object model, DynamicViewBag viewbag)
        {
            var context = CreateInstanceContext(template.TemplateType);
            ITemplate instance = _config.Activator.CreateInstance(context);
            instance.InternalTemplateService = new InternalTemplateService(this, template.Key);
#pragma warning disable 0618 // Backwards Compat.
            instance.TemplateService = new TemplateService(_cached);
#pragma warning restore 0618 // Backwards Compat.
            instance.Razor = _cached;
            instance.SetData(model, viewbag);
            return instance;
        }
Exemple #17
0
 public string RunCompile(ITemplateKey key, Type modelType, object model, DynamicViewBag viewBag)
 {
     //判断唯一视图的缓存
     string path = (HuberVariable.CurWebDir + key.Name).Replace(@"\\", @"\");
     ICompiledTemplate cacheTemplate;
     cache.TryRetrieveTemplate(key, null, out cacheTemplate);
     if (cacheTemplate == null || !cacheTemplate.Key.Name.Trim().Equals(key.Name.Trim()))
     {
         CompileViewAndLayout(key, null, model, viewBag);
     }
     //当缓存存在返回结果
     return Engine.Razor.RunCompile(key, null, model, viewBag);
 }
        public string RenderFromContentTemplate(string content, IDictionary<string, object> data)
        {

            Engine.Razor.AddTemplate("template", content);
            // On startup
            Engine.Razor.Compile("template", null);
            // instead of the Razor.Parse call
            DynamicViewBag viewBag = new DynamicViewBag();
            viewBag.AddDictionary(data);

            var result = Engine.Razor.Run("template", null, viewBag);
            return result;
        }
        public void Given_a_model_the_email_should_format_the_email_correctly()
        {
            var viewBag = new DynamicViewBag();
            var email = _emailFormatter.BuildTemplatedEmailFrom(
                new SimpleEmailModel
                {
                    RecipientFirstName = "Michael",
                    ReferenceNumber = "REF123456",
                    Message = "Hello World!",
                    Url = "http://google.com"
                }, viewBag);

            ApprovalTests.Approvals.Verify(email.Everything());
        }
        public string RenderTemplate(string templateName, IDictionary<string, object> data)
        {
            var templateContent = File.ReadAllText(templateName);
            Engine.Razor.AddTemplate(templateName, templateContent);
            // On startup
            Engine.Razor.Compile(templateName, null);
            // instead of the Razor.Parse call
            DynamicViewBag viewBag = new DynamicViewBag();
            viewBag.AddDictionary(data);

        

            var result = Engine.Razor.Run(templateName, null, viewBag);
            return result;
        }
 private static void GenerateTemplate_ViewHelper(string templateFileName, List<string> tableList, IDBSchema dbSchema, string modelNamespaceVal, string savePath)
 {
     DisplayTemplateName(templateFileName);
     var templateText = TemplateHelper.ReadTemplate(templateFileName);
     foreach (var tableName in tableList)
     {
         var table = dbSchema.GetTableMetadata(tableName);
         if (table.PKs.Count == 0) throw new Exception(string.Format("表{0}:没有设置主键!", tableName));
         Display(tableName, table);
         dynamic viewbag = new DynamicViewBag();
         viewbag.classnameVal = tableName;
         viewbag.namespaceVal = modelNamespaceVal;
         var outputText = TemplateHelper.Parse(TemplateKey.ViewHelper, templateText, table, viewbag);
         outputText = TemplateHelper.Clean(outputText, RegexPub.H1());
         FileHelper.Save(string.Format(@"{0}\{1}ViewHelper.cs", savePath, viewbag.classnameVal), outputText);
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <param name="filePath"></param>
        /// <param name="encoding"></param>
        /// <param name="templateKey"></param>
        /// <param name="formatter"></param>
        private void WriteDocument <T>(T model, string filePath, Encoding?encoding, ITemplateKey templateKey, IClassDocumentFormatter formatter)
        {
            string dir = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            RazorEngine.Templating.DynamicViewBag viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("Formatter", formatter);

            using StreamWriter writer = new StreamWriter(filePath, false, encoding ?? Encoding.UTF8);

            Engine.Run(templateKey, writer, typeof(T), model, viewBag: viewBag);

            writer.Flush();
        }
        public IHtmlString Build(IEnumerable<string> permissions)
        {
            var config = new TemplateServiceConfiguration();
            config.TemplateManager = new WatchingResolvePathTemplateManager(new[] { HttpContext.Current.Server.MapPath("~/Views/Shared") }, new InvalidatingCachingProvider());
            var service = RazorEngineService.Create(config);
            Engine.Razor = service;

            var viewBag = new DynamicViewBag();
            viewBag.AddValue("Permissions", permissions);

            string outputString = Engine.Razor.RunCompile("AdminMenu.cshtml", null,
                Contained.Where(
                    x => permissions.Contains(x.Permission) ||
                         permissions.Contains("*") ||
                         string.IsNullOrEmpty(x.Permission)), viewBag);

            return new HtmlString(outputString);
        }
        public async static Task <string> CreatePageForIncidentAsync(GraphServiceClient graphService, string siteRootDirectory, Group group, Section section, Incident incident, IEnumerable <FileContent> inspectionPhotos, IEnumerable <Models.Video> incidentVideos)
        {
            var accessToken  = AuthenticationHelper.GetGraphAccessTokenAsync();
            var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml");
            var template     = System.IO.File.ReadAllText(templateFile);
            var viewBag      = new RazorEngine.Templating.DynamicViewBag();

            viewBag.AddValue("InspectionPhotos", inspectionPhotos);
            viewBag.AddValue("IncidentVideos", incidentVideos);

            var html    = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag);
            var content = new MultipartFormDataContent();

            content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation");

            foreach (var image in inspectionPhotos)
            {
                var itemContent = new ByteArrayContent(image.Bytes);
                var contentType = MimeMapping.GetMimeMapping(image.Name);
                itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(itemContent, image.Id);
            }

            var pageEndPoint   = string.Format("{0}groups/{1}/notes/sections/{2}/pages", AADAppSettings.GraphBetaResourceUrl, group.Id, section.id);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint);

            requestMessage.Content = content;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await accessToken);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var responseMessage = await client.SendAsync(requestMessage);

                if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    throw new HttpResponseException(responseMessage.StatusCode);
                }

                var payload = await responseMessage.Content.ReadAsStringAsync();

                return(JObject.Parse(payload)["links"]["oneNoteWebUrl"]["href"].ToString());
            }
        }
        public async Task <string> CreatePageForIncidentAsync(string siteRootDirectory, string sectionId, Incident incident, IEnumerable <FileContent> inspectionPhotos, IEnumerable <Video> incidentVideos)
        {
            var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml");
            var template     = System.IO.File.ReadAllText(templateFile);
            var viewBag      = new RazorEngine.Templating.DynamicViewBag();

            viewBag.AddValue("InspectionPhotos", inspectionPhotos);
            viewBag.AddValue("IncidentVideos", incidentVideos);

            var html    = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag);
            var content = new MultipartFormDataContent();

            content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation");

            foreach (var image in inspectionPhotos)
            {
                var itemContent = new ByteArrayContent(image.Bytes);
                var contentType = MimeMapping.GetMimeMapping(image.Name);
                itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(itemContent, image.Id);
            }

            this.pageEndPoint = string.Format("{0}/sections/{1}/pages", serviceBaseUrl, sectionId);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint);

            requestMessage.Content = content;

            var responseMessage = await HttpSendAsync(requestMessage, accessToken);

            if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
            {
                throw new HttpResponseException(responseMessage.StatusCode);
            }

            var reponseObject = await GetReponseObjectAsync(responseMessage);

            return((string)reponseObject.links.oneNoteWebUrl.href);
        }
Exemple #26
0
        /// <summary>
        /// 编译视图和层layout
        /// </summary>
        /// <param name="key">视图的唯一路径</param>
        /// <param name="modelType">视图类型 :视图/layout</param>
        /// <param name="model">页面 MODEL</param>
        /// <param name="viewBag">viewBag</param>
        public void CompileViewAndLayout(ITemplateKey key, Type modelType, object model, DynamicViewBag viewBag)
        {
            //获取视图
            string FullPath = (HuberVariable.CurWebDir + key.Name.Replace("/", @"\")).Replace(@"\\", @"\");
            string content = System.IO.File.ReadAllText(FullPath);
            //匹配layout
            var matchs = layoutEx.Matches(content);
            string layoutPath = string.Empty;
            if (matchs != null)
            {

                foreach (Match m in matchs)
                {
                    layoutPath = m.Groups[1].Value;
                }
            }
            if (layoutPath != string.Empty)
            {
                //添加layout到模板
                string FullLayoutPath = (HuberVariable.CurWebDir + layoutPath.Replace("/", @"\")).Replace(@"\\", @"\");

                if (File.Exists(FullLayoutPath))
                {
                    ITemplateKey layoutKey = Engine.Razor.GetKey(layoutPath, ResolveType.Layout);
                    CompileViewAndLayout(layoutKey, null, model, viewBag);
                }
            }
            if (key.TemplateType == ResolveType.Layout)
            {
                Engine.Razor.AddTemplate(key, content);
            }
            else
            {
                //编译视图
                Engine.Razor.RunCompile(content, key, null, model);
            }

        }
Exemple #27
0
        /// <inheritdoc/>
        public void WriteTypeDocument(TypeWithComment type, IClassDocumentFormatter formatter)
        {
            string filePath = GetTypeDocumentFilePath(type, false);
            string dir      = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            RazorEngine.Templating.DynamicViewBag viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("Formatter", formatter);

            if (!TypeDocumentTemplateState.IsCompiled)
            {
                TypeDocumentTemplateState.Compile(typeof(TypeWithComment));
            }

            using (StreamWriter writer = new StreamWriter(filePath, false, Settings.TypeDodumentSettings.Encoding))
            {
                Engine.Run(TypeDocumentTemplateState.Key, writer, type.GetType(), type, viewBag: viewBag);
                writer.Flush();
            }
        }
        public override Task Invoke(IOwinContext context)
        {
            var path = FileSystem.MapPath(_options.BasePath, context.Request.Path.Value);
            var ext = Path.GetExtension(path);
            if (CanHandle(ext))
            {
                Trace.WriteLine("Invoke RazorMiddleware");

                context.Response.StatusCode = 200;
                context.Response.ContentType = MimeTypeService.GetMimeType(".html");

                var dynamicViewBag = new DynamicViewBag();
                dynamicViewBag.AddValue("Options", _options);

                var razor = File.ReadAllText(path);
                var result = Razor.Parse(razor, null, dynamicViewBag, String.Empty);

                context.Response.Write(result);

                return Globals.CompletedTask;
            }

            return Next.Invoke(context);
        }
Exemple #29
0
        public void RunTemplate(ICompiledTemplate template, System.IO.TextWriter writer, object model, DynamicViewBag viewBag)
#endif
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            var instance = CreateTemplate(template, model, viewBag);

#if RAZOR4
            await instance.Run(CreateExecuteContext(), writer);
#else
            instance.Run(CreateExecuteContext(), writer);
#endif
        }
Exemple #30
0
 /// <summary>
 /// See <see cref="RazorEngineService.RunCompile"/>.
 /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.RunCompile"/>.
 /// Convenience method which creates a <see cref="TextWriter"/> and returns the result as string.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="templateSource"></param>
 /// <param name="name"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 /// <returns></returns>
 public static string RunCompile(this IRazorEngineService service, string templateSource, string name, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     service.AddTemplate(name, templateSource);
     return(service.RunCompile(name, modelType, model, viewBag));
 }
 /// <summary>
 /// Runs the template with the specified cacheName.
 /// </summary>
 /// <param name="cacheName">The name of the template in cache.  The template must be in cache.</param>
 /// <param name="model">The model for the template or NULL if there is no model.</param>
 /// <param name="viewBag">The initial ViewBag contents NULL for an empty ViewBag.</param>
 /// <returns>The string result of the template.</returns>
 public string Run(string cacheName, object model, DynamicViewBag viewBag)
 {
     return(_proxy.Run(cacheName, model, viewBag));
 }
Exemple #32
0
        internal virtual ITemplate CreateTemplate(ICompiledTemplate template, object model, DynamicViewBag viewbag)
        {
            var       context  = CreateInstanceContext(template.TemplateType);
            ITemplate instance = _config.Activator.CreateInstance(context);

            instance.InternalTemplateService = new InternalTemplateService(this, template.Key);

            instance.Razor = _cached;
            instance.SetData(model, viewbag);
            return(instance);
        }
Exemple #33
0
 /// <summary>
 /// See <see cref="RazorEngineService.RunCompile"/>.
 /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.RunCompile"/>.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="templateSource"></param>
 /// <param name="name"></param>
 /// <param name="writer"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 public static void RunCompile(this IRazorEngineService service, string templateSource, string name, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     service.AddTemplate(name, templateSource);
     service.RunCompile(name, writer, modelType, model, viewBag);
 }
Exemple #34
0
 /// <summary>
 /// Creates a new instance of ExecuteContext with an empty ViewBag.
 /// </summary>
 public ExecuteContext()
 {
     _viewBag = new DynamicViewBag();
 }
        public void RunTemplate(ICompiledTemplate template, System.IO.TextWriter writer, object model, DynamicViewBag viewBag)
#endif
        {
            if (template == null)
                throw new ArgumentNullException("template");

            var instance = CreateTemplate(template, model, viewBag);
#if RAZOR4
            await instance.Run(CreateExecuteContext(), writer);
#else
            instance.Run(CreateExecuteContext(), writer);
#endif
        }
 public ExecuteContext(DynamicViewBag viewbag)
 {
     throw new NotSupportedException("This kind of usage is no longer supported!");
 }
        internal override ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType, ITemplateKey context)
        {
            var templateKey = GetKey(cacheName, resolveType, context);
            ICompiledTemplate compiledTemplate;

            if (!Configuration.CachingProvider.TryRetrieveTemplate(templateKey, modelType, out compiledTemplate))
            {
                compiledTemplate = Compile(templateKey, modelType);
                Configuration.CachingProvider.CacheTemplate(compiledTemplate, templateKey);
            }
            return(CreateTemplate(compiledTemplate, model, viewbag));
        }
Exemple #38
0
        /// <summary>
        /// Runs the specified template and returns the result.
        /// </summary>
        /// <param name="template">The template to run.</param>
        /// <param name="writer"></param>
        /// <param name="model"></param>
        /// <param name="viewBag">The ViewBag contents or NULL for an initially empty ViewBag.</param>
        /// <returns>The string result of the template.</returns>
#if RAZOR4
        public async Task RunTemplate(ICompiledTemplate template, System.IO.TextWriter writer, object model, DynamicViewBag viewBag)
 /// <summary>
 /// See <see cref="RazorEngineService.Run"/>.
 /// Convenience method which creates a <see cref="TextWriter"/> and returns the result as string.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="key"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 /// <returns></returns>
 public static string Run(this IRazorEngineService service, ITemplateKey key, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     return(WithWriter(writer => service.Run(key, writer, modelType, model, viewBag)));
 }
Exemple #40
0
        /// <summary>
        /// Runs the specified template and returns the result.
        /// </summary>
        /// <param name="template">The template to run.</param>
        /// <param name="writer"></param>
        /// <param name="model"></param>
        /// <param name="viewBag">The ViewBag contents or NULL for an initially empty ViewBag.</param>
        /// <returns>The string result of the template.</returns>

        public async Task RunTemplate(ICompiledTemplate template, System.IO.TextWriter writer, object model, DynamicViewBag viewBag)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            var instance = CreateTemplate(template, model, viewBag);

            await instance.Run(CreateExecuteContext(), writer);
        }
Exemple #41
0
 /// <summary>
 /// See <see cref="RazorEngineService.RunCompile"/>.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="name"></param>
 /// <param name="writer"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 public static void RunCompile(this IRazorEngineService service, string name, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     service.RunCompile(service.GetKey(name), writer, modelType, model, viewBag);
 }
 /// <summary>
 /// Runs the template with the specified name.
 /// </summary>
 /// <param name="template">The template to run.</param>
 /// <param name="viewBag">The ViewBag contents or NULL for an initially empty ViewBag.</param>
 /// <returns>The string result of the template.</returns>
 public string Run(ITemplate template, DynamicViewBag viewBag)
 {
     return(_proxy.Run(template, viewBag));
 }
 /// <summary>
 /// Creates a new <see cref="ExecuteContext"/> for tracking templates.
 /// </summary>
 /// <param name="viewBag">The dynamic view bag.</param>
 /// <returns>The execute context.</returns>
 public ExecuteContext CreateExecuteContext(DynamicViewBag viewBag = null)
 {
     return _service.CreateExecuteContext(viewBag);
 }
 /// <summary>
 /// Creates a new <see cref="ExecuteContext"/> used to tracking templates.
 /// </summary>
 /// <param name="viewBag">This parameter is ignored, set the Viewbag with template.SetData(null, viewBag)</param>
 /// <returns>The instance of <see cref="ExecuteContext"/></returns>
 ExecuteContext ITemplateService.CreateExecuteContext(DynamicViewBag viewBag)
 {
     throw new NotSupportedException("This operation is not supported directly by the IsolatedTemplateService.");
 }
Exemple #45
0
 public ExecuteContext(DynamicViewBag viewbag)
 {
     throw new NotSupportedException("This kind of usage is no longer supported!");
 }
 /// <summary>
 /// Resolves the template with the specified name.
 /// </summary>
 /// <param name="name">The name of the template type in cache.</param>
 /// <param name="model">The model or NULL if there is no model for the template.</param>
 /// <param name="modelType"></param>
 /// <param name="resolveType"></param>
 /// <returns>The resolved template.</returns>
 public ITemplate Resolve(string name, object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType)
 {
     DynamicWrapperService.CheckModelType(modelType);
     return(_service.ResolveInternal(name, DynamicWrapperService.GetDynamicModel(
                                         modelType, model, _service.Configuration.AllowMissingPropertiesOnDynamic), modelType, viewbag, resolveType, _template));
 }
Exemple #47
0
 /// <summary>
 /// See <see cref="RazorEngineService.RunCompile"/>.
 /// Convenience method which creates a <see cref="TextWriter"/> and returns the result as string.
 /// </summary>
 /// <param name="service"></param>
 /// <param name="name"></param>
 /// <param name="modelType"></param>
 /// <param name="model"></param>
 /// <param name="viewBag"></param>
 /// <returns></returns>
 public static string RunCompile(this IRazorEngineService service, string name, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     return(WithWriter(writer => service.RunCompile(name, writer, modelType, model, viewBag)));
 }
Exemple #48
0
        internal virtual ITemplate CreateTemplate(ICompiledTemplate template, object model, DynamicViewBag viewbag)
        {
            var       context  = CreateInstanceContext(template.TemplateType);
            ITemplate instance = _config.Activator.CreateInstance(context);

            instance.InternalTemplateService = new InternalTemplateService(this, template.Key);

#if !NO_CODEDOM
#pragma warning disable 0618 // Backwards Compat.
            instance.TemplateService = new TemplateService(_cached);
#pragma warning restore 0618 // Backwards Compat.
#endif
            instance.Razor = _cached;
            instance.SetData(model, viewbag);
            return(instance);
        }
Exemple #49
0
        internal virtual ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewBag, ResolveType resolveType, ITemplateKey context)
        {
            var templateKey      = GetKey(cacheName, resolveType, context);
            var compiledTemplate = Compile(templateKey, modelType);

            return(CreateTemplate(compiledTemplate, model, viewBag));
        }
        public void RazorEngineService_CustomLocalizerHelper_ViewBag()
        {
            RunTestHelper(service =>
            {
                var model = new Person() { Forename = "forname", Surname = "surname" };
                var template = @"@Model.Forename @Include(""test"") @Localizer.Language";

                service.Compile("@Model.Surname", "test", typeof(Person));
                dynamic viewbag = new DynamicViewBag();
                viewbag.Language = "lang";
                string result = service.RunCompile(template, Guid.NewGuid().ToString(), typeof(Person), model, (DynamicViewBag) viewbag);
                Assert.AreEqual("forname surname lang", result);
            }, config =>
            {
                config.BaseTemplateType = typeof(AddLanguageInfo_Viewbag<>);
            });
        }
        /// <summary>
        /// Creates a new <see cref="ExecuteContext"/> for tracking templates.
        /// </summary>
        /// <param name="viewBag">The dynamic view bag.</param>
        /// <returns>The execute context.</returns>
        public virtual ExecuteContext CreateExecuteContext(DynamicViewBag viewBag = null)
        {
            var context = new ExecuteContext(new DynamicViewBag(viewBag));

            return(context);
        }
        /// <summary>
        /// Runs the specified template and returns the result.
        /// </summary>
        /// <param name="template">The template to run.</param>
        /// <param name="writer"></param>
        /// <param name="model"></param>
        /// <param name="viewBag">The ViewBag contents or NULL for an initially empty ViewBag.</param>
        /// <returns>The string result of the template.</returns>
#if RAZOR4
        public async Task RunTemplate(ICompiledTemplate template, System.IO.TextWriter writer, object model, DynamicViewBag viewBag)
Exemple #53
0
        public string SendEmail()
        {
            DateTime    _endDate = DateTime.Today.Date.AddDays(-35);
            MailAddress _From    = new MailAddress("*****@*****.**");
            MailAddress _To      = new MailAddress("*****@*****.**");
            //MailAddress _From = new MailAddress("*****@*****.**");
            //MailAddress _To = new MailAddress("*****@*****.**");
            MailMessage _Mail = new MailMessage(_From, _To);

            _Mail.To.Add("*****@*****.**");
            _Mail.To.Add("*****@*****.**");
            _Mail.IsBodyHtml = true;
            _Mail.Subject    = "DailyPerformance Report";
            string _html = "";
            string path  = HttpContext.Server.MapPath("~/Views/DailyQuotes/SendEmail.cshtml");

            var template = System.IO.File.ReadAllText(path);

            RazorEngine.Templating.DynamicViewBag _ViewBag = new RazorEngine.Templating.DynamicViewBag();
            _ViewBag.AddValue("test", "test data");

            List <DailyQuote> result = new List <DailyQuote>();

            GetCTQ();

            _ViewBag.AddValue("_CTQDatestring", _Dstring);
            _ViewBag.AddValue("_CTQ", _CTopQuote);
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Confused" && x.QuoteType == "Partner Quotes").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_PTQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Confused" && x.QuoteType == "Top Quote").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTopQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Confused" && x.QuoteType == "Top Quotes Q %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTopQP", GetData(result, true));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Confused" && x.QuoteType == "Top Quotes HI %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTopHIP", GetData(result, true));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Confused" && x.QuoteType == "Quotes Blocked %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CQBP", GetData(result, true));


            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go Compare" && x.QuoteType == "Total Quotes").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GTQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go Compare" && x.QuoteType == "Partner Quotes").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GPQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go Compare" && x.QuoteType == "Top Quote").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GTopQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go Compare" && x.QuoteType == "Top Quotes Q %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GTopQP", GetData(result, true));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go ComPare" && x.QuoteType == "Top Quotes HI %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GTopHIP", GetData(result, true));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Go Compare" && x.QuoteType == "Quotes Blocked %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_GQBP", GetData(result, true));



            //compare the Market
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Consumer Enquiries").OrderByDescending(x => x.Date).ToList();

            _ViewBag.AddValue("_CTMCE", GetData(result, false));
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Prices Presented").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTMPP", GetData(result, false));
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Prices Presented @P1").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTMPP1", GetData(result, false));
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Click Through (PCTs)").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTMCT", GetData(result, false));
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Top Quotes %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTMTQP", GetData(result, true));
            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Compare The Market" && x.QuoteType == "Quotes Declined %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_CTMQD", GetData(result, true));



            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Total Queries").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMTQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Total Quotes Returned").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMTQR", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Total Clicks").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMTC", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Provider Quote Rate %").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMPQR", GetData(result, true));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Filtered Quotes").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMFQ", GetData(result, false));

            result = db.DailyQuotes.Where(x => x.Date <= DateTime.Today.Date && x.Date >= _endDate && x.QuoteSource == "Money Supermarket" && x.QuoteType == "Top Quotes").OrderByDescending(x => x.Date).ToList();
            _ViewBag.AddValue("_MSMTQS", GetData(result, false));

            DailyQuote model = new DailyQuote();

            var config = new TemplateServiceConfiguration
            {
                Language             = Language.CSharp,
                EncodedStringFactory = new RawStringFactory()
            };

            config.EncodedStringFactory = new HtmlEncodedStringFactory();

            var service = RazorEngineService.Create(config);

            Engine.Razor = service;

            // _html= Razor.Parse(template,model,_ViewBag,null);
            var templateService = new TemplateService(config);

            _html = Engine.Razor.RunCompile(template, "Email", null, null, _ViewBag);



            _Mail.Body = _html;
            SmtpClient smtp = new SmtpClient
            {
                Port        = 25,
                Host        = "auth.smtp.1and1.co.uk",
                Credentials = new NetworkCredential("*****@*****.**", "paragon")
            };

            smtp.Send(_Mail);

            return("<h2>Email Sent</h2>");
        }
 internal virtual ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewBag, ResolveType resolveType, ITemplateKey context)
 {
     var templateKey = GetKey(cacheName, resolveType, context);
     var compiledTemplate = Compile(templateKey, modelType);
     return CreateTemplate(compiledTemplate, model, viewBag);
 }
Exemple #55
0
 /// <summary>
 /// Runs the template using the specified <paramref name="model"/>.
 /// </summary>
 /// <param name="model"></param>
 /// <param name="textWriter"></param>
 /// <param name="viewBag"></param>
 public void Run(TModel model, TextWriter textWriter, DynamicViewBag viewBag = null)
 {
     _service.Run(_key, textWriter, typeof(TModel), model, viewBag);
 }