public void TemplateBase_CanRenderInclude_WithInlineTemplate()
        {
            using (var service = new TemplateService())
            {
                const string child = "@model RazorEngine.Tests.TestTypes.InlineTemplateModel\[email protected](Model)";
                const string template = "@model RazorEngine.Tests.TestTypes.InlineTemplateModel\n@{ Model.InlineTemplate = @<h1>@ViewBag.Name</h1>; }@Include(\"Child\", Model)";
                const string expected = "<h1>Matt</h1>";

                dynamic bag = new DynamicViewBag();
                bag.Name = "Matt";

                service.GetTemplate(child, null, "Child");
                string result = service.Parse(template, new InlineTemplateModel(), bag, null);
                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void Issue133_ViewBagShouldPersistToIncludes()
        {
            using (var service = new TemplateService())
            {
                const string child = "<h1>@ViewBag.Name</h1>";
                const string template = "@Include(\"Child\")";
                const string expected = "<h1>Matt</h1>";

                dynamic bag = new DynamicViewBag();
                bag.Name = "Matt";

                service.GetTemplate(child, null, "Child");
                string result = service.Parse(template, null, bag, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void Issue26_ViewBagInitializationOutsideOfTemplate()
        {
            using (var service = new TemplateService())
            {
                const string template = "@ViewBag.TestValue";
                const string expected = "This is a test";

                DynamicViewBag viewBag = new DynamicViewBag();
                viewBag.AddValue("TestValue", "This is a test");

                string result = service.Parse(template, null, viewBag, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Example #4
0
        public void CompileCategoryContent(int categoryId)
        {
            //逐条生成

            //获取栏目实体
            var categoryModel = _cmsCoreDB.Category.FirstOrDefault(p => p.ID == categoryId);

            if (categoryModel != null)
            {
                //自定义内容模型
                if (categoryModel.ModelType == 1)
                {
                    var customContentModel = _cmsCoreDB.ContentModel.FirstOrDefault(p => p.ID == categoryModel.ModelId);
                    if (customContentModel != null)
                    {
                        var pageSize         = categoryModel.ShowPageSize;
                        var pageIndex        = 0;
                        var templateFilePath = string.Format("{0}\\Templates\\{1}\\{2}",
                                                             AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'),
                                                             categoryModel.DefaultStyle,
                                                             categoryModel.ShowTemplate.Replace("/", "\\"));

                        //按分页遍历生成
                        var dataModelManage = new DataModelManage();

                        //GOTO返回获取数据标志
RELOADPAGELIST:

                        #region GOTO循环获取分页数据,直至分页为0

                        var pageListModel = dataModelManage.GetPageList(customContentModel.TableName, categoryId, pageIndex, pageSize);

                        //如果存在数据
                        var listModel = pageListModel as dynamic[] ?? pageListModel.ToArray();
                        if (listModel.Any())
                        {
                            //逐个渲染模型
                            foreach (var m in listModel)
                            {
                                var viewBag = new DynamicViewBag();

                                viewBag.AddValue("Data", m);

                                //渲染
                                var parseResult = ParsePathContent(templateFilePath, viewBag);

                                //发布
                                if (!string.IsNullOrEmpty(parseResult))
                                {
                                    var publishResult = new PublishResult
                                    {
                                        Context = parseResult,
                                        Path    = categoryModel.CatPath, //递归路径
                                    };

                                    publishResult.FileName = m.ID.ToString();

                                    _publishEngine.Push(publishResult);
                                }
                            }

                            //当前分页索引递增至下一页
                            pageIndex++;

                            //重新获取下一分页数据
                            goto RELOADPAGELIST;
                        }

                        #endregion
                    }
                }
            }
        }
Example #5
0
        public void RunFinished()
        {
            if (!isSln)
            {
                return;
            }
            string unexpectedDir = Path.GetDirectoryName(Path.GetDirectoryName(this.dte2.Solution.Projects.Item(1).FullName));

            List <string> projectNames = new List <string>();

            foreach (Project prj in this.dte2.Solution.Projects)
            {
                projectNames.Add(prj.FullName);
            }

            foreach (string prjName in projectNames)
            {
                this.AdjustProjectLoaction(prjName);
            }

            foreach (string prjName in projectNames)
            {
                Directory.Delete(Path.GetDirectoryName(prjName), true);

                if (Path.GetDirectoryName(prjName).EndsWith(".Models.EF"))
                {
                    string slnPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(prjName)));

                    var batPath = Path.Combine(slnPath, Path.GetDirectoryName(prjName).Split(new char[] { '/', '\\' }).Last(), "scaffold.bat");

                    if (!initEFCore)
                    {
                        continue;
                    }
                    var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                    {
                        FileName         = batPath,
                        WorkingDirectory = Path.GetDirectoryName(batPath)
                    });
                    proc.WaitForExit();
                    if (proc.ExitCode != 0)
                    {
                        MessageBox.Show(
                            "EFCore Models 更新失敗",
                            "更新失敗,請檢查批次檔內的資料庫連線字串",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return;
                    }

                    // 產生控制器
                    Assembly currentAssembly = Assembly.GetExecutingAssembly();

                    Stream stream   = currentAssembly.GetManifestResourceStream(currentAssembly.GetName().Name + ".Templates.Controller.txt");
                    var    template = new StreamReader(stream).ReadToEnd();

                    foreach (var model in Directory.GetFiles(Path.GetDirectoryName(batPath), "*.cs", SearchOption.TopDirectoryOnly))
                    {
                        var filename = Path.GetFileNameWithoutExtension(model);
                        if (filename.EndsWith("Context") && filename != "Context")
                        {
                            continue;
                        }

                        var viewBag = new DynamicViewBag();
                        foreach (var kv in replacementsDictionary)
                        {
                            viewBag.AddValue(kv.Key.Replace("$", ""), kv.Value);
                        }
                        viewBag.AddValue("ModelName", filename);
                        viewBag.AddValue("SlnName", Path.GetFileName(slnPath));


                        #region Get Id Type
                        var modelClass = File.ReadAllText(model);

                        Regex propertyRegex = new Regex(@"(?>public|internal)\s+(?!class)((virtual|static|readonly)\s)?(?<Type>[^\s]+)\s+(?<Name>[^\s]+)");

                        var properties = propertyRegex.Matches(modelClass);

                        bool hasKeyType = false;
                        foreach (Match property in properties)
                        {
                            if (property.Groups["Name"].Value?.ToUpper() == "Id".ToUpper())
                            {
                                viewBag.AddValue("ModelKeyType", property.Groups["Type"].Value);
                                hasKeyType = true;

                                break;
                            }
                        }

                        if (!hasKeyType)
                        {
                            viewBag.AddValue("ModelKeyType", "object");
                        }
                        #endregion


                        var output =
                            Engine.Razor.RunCompile(
                                template,
                                "ControllerTemplate",
                                viewBag: viewBag);

                        File.WriteAllText(Path.Combine(slnPath, Path.GetFileName(slnPath), "Controllers", $"{filename}Controller.cs"), output);
                    }
                }
            }
        }
Example #6
0
 /// <summary>Runs the given cached template.</summary>
 public void Run(ITemplateKey key, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     m_engineService.Run(key, writer, modelType, model, viewBag);
 }
Example #7
0
        /// <summary>
        /// 渲染分布视图
        /// </summary>
        /// <param name="module">分布视图所属模块</param>
        /// <param name="viewName">分布视图名称</param>
        /// <param name="model">分布视图Model</param>
        /// <param name="viewBag">动态视图数据字典</param>
        /// <example>
        ///     @Raw(RenderPart("Home", "Footer"))
        /// </example>
        /// <returns></returns>
        public string RenderPart(string module, string viewName, object model = null, DynamicViewBag viewBag = null)
        {
            var path   = Common.GetViewPath(module, viewName);
            var source = File.ReadAllText(path);

            return(Razor.RunCompile(source, $"{module}\\{viewName}", model?.GetType(), model, viewBag));
        }
Example #8
0
File: TPL.cs Project: vanehu/MM
 /// <summary>
 /// 新建视图背包
 /// </summary>
 public DynamicViewBag NewViewBag()
 {
     ViewBag = new DynamicViewBag(viewBag);
     return(ViewBag);
 }
Example #9
0
File: TPL.cs Project: vanehu/MM
 /// <summary>
 /// 新建视图背包
 /// </summary>
 public DynamicViewBag NewViewBag_default()
 {
     viewBag = new DynamicViewBag(viewBag);
     return(viewBag);
 }
Example #10
0
 // Renders the partial view with the given view data and, implicitly, the given view data's model
 public IEncodedString RenderPartial(string partialViewName, string controllerName, DynamicViewBag ViewBag)
 {
     return(RenderPartial(partialViewName, controllerName, new { }, ViewBag));
 }
Example #11
0
        public IEncodedString ViewPartial(string partialViewName, string controllerName = "", object model = null, DynamicViewBag ViewBag = null)
        {
            if (controllerName == string.Empty)
            {
                controllerName = "Shared";
            }
            string key  = "\\Views\\" + controllerName + "\\" + partialViewName + ".cshtml";
            var    tKey = Engine.Razor.GetKey(key, ResolveType.Include);

            return(new RawString(new CompileView().RunCompile(tKey, null, model, ViewBag)));
        }
Example #12
0
        // Renders the partial view with a copy of the given view data plus the given model
        /// <summary>
        /// 部分视图
        /// </summary>
        /// <param name="partialViewName">部分视图名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="model"> model</param>
        /// <param name="ViewBag">ViewBag</param>
        /// <returns></returns>
        public IEncodedString RenderPartial(string partialViewName, string controllerName, object model, DynamicViewBag ViewBag)
        {
            RefRequestEntity paras = SetParamValue(model);

            var    t          = HuberHttpModule.CurDomainAssembly.GetType(HuberHttpModule.CurDomainAssemblyName + ".Controllers." + controllerName + "Controller");
            var    ActionFunc = t.GetMethod(partialViewName);
            object dObj       = Activator.CreateInstance(t);

            var AddViewBageFunc = t.GetMethod("AddViewBageValues");

            foreach (string key in ViewBag.GetDynamicMemberNames())
            {
                AddViewBageFunc.Invoke(dObj, new object[] { key, Impromptu.InvokeGet(ViewBag, key) });
            }

            object result = ActionFunc.Invoke(dObj, new object[] { paras });

            return(new RawString((result as RefRespondEntity).ResultContext.ToString()));
        }