Inheritance: RazorViewEngine
コード例 #1
0
        public void LoadActions()
        {
            try
            {
                if (this.engineManager == null || this.engineManager.IsDisposed)
                {
                    this.engineManager = new EngineManager(this);
                }

                this.engineManager.Clear();
                this.engineManager.Add(YuiCssEngine            = new YuiCssEngine());
                this.engineManager.Add(YuiJsEngine             = new YuiJsEngine());
                this.engineManager.Add(DeanEdwardsPackerEngine = new DeanEdwardsPackerEngine());
                this.engineManager.Add(ClosureCompilerEngine   = new ClosureCompilerEngine());
                this.engineManager.Add(LessEngine         = new LessEngine());
                this.engineManager.Add(MsJsEngine         = new MsJsEngine());
                this.engineManager.Add(MsCssEngine        = new MsCssEngine());
                this.engineManager.Add(ConfigEngine       = new ConfigEngine());
                this.engineManager.Add(ViewEngine         = new ViewEngine());
                this.engineManager.Add(T4Engine           = new T4Engine());
                this.engineManager.Add(CoffeeScriptEngine = new CoffeeScriptEngine());
                this.engineManager.Add(UglifyEngine       = new UglifyEngine());
                this.engineManager.Add(JSHintEngine       = new JSHintEngine());
                this.engineManager.Add(CSSLintEngine      = new CSSLintEngine());
                this.engineManager.Add(TypeScriptEngine   = new TypeScriptEngine());
                this.engineManager.Add(SassEngine         = new SassEngine());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
コード例 #2
0
        public async Task <IViewComponentResult> InvokeAsync(string nameOfView = null, IDictionary <string, object> customViewData = null, bool warnOnViewNotFound = true)
        {
            if (customViewData != null)
            {
                foreach (var vd in customViewData)
                {
                    ViewData[vd.Key] = vd.Value;
                }
            }

            var pth = $"Components/RequiredSection/{(!string.IsNullOrEmpty(nameOfView)?nameOfView:"Default")}";

            if (ViewEngine.FindView(ViewContext, pth, false).Success)
            {
                if (string.IsNullOrEmpty(nameOfView))
                {
                    return(View());
                }
                else
                {
                    return(View(viewName: nameOfView));
                }
            }

            if (warnOnViewNotFound)
            {
                logger.Log(LogLevel.Warning, "The Component-View {pth} was not found.", pth);
                return(Content(string.Empty));
            }

            throw new InvalidOperationException($"The Component-View {pth} was not found.");
        }
コード例 #3
0
        /// <summary>Tries to look at a thing.</summary>
        /// <param name="thingToLookAt">The thing to look at.</param>
        /// <param name="sender">The sender.</param>
        /// <returns>Returns the rendered view.</returns>
        private string TryLookAtThing(string thingToLookAt, Thing sender)
        {
            // @@@ TODO: Refactor ViewEngine to remove NVelicoty: https://wheelmud.codeplex.com/workitem/13348
            var viewEngine = new ViewEngine();

            // Look for target in the current room
            Thing thing = sender.Parent.FindChild(thingToLookAt);

            if (thing != null && this.sensesBehavior.CanPerceiveThing(thing))
            {
                return(viewEngine.RenderView(thing));
            }

            // If no target found, see if it matches any of the room's visuals.
            var room = sender.Parent.FindBehavior <RoomBehavior>();

            if (room != null)
            {
                string visual = room.FindVisual(thingToLookAt);
                if (!string.IsNullOrEmpty(visual))
                {
                    return(viewEngine.RenderView(visual));
                }
            }

            // At this point, target was not found.
            return(string.Empty);
        }
コード例 #4
0
        public IActionResult Settings(int moduleId, string moduleControl, string moduleAction)
        {
            PageInfo      page       = null;
            SettingsModel model      = new SettingsModel();
            ViewEngine    viewEngine = null;

            // Get module
            ModuleInfo module = _viewManager.GetModule(moduleId, true, true);

            if (module == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            // Get page
            page = _viewManager.GetPage(module.PageId);

            if (page == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            viewEngine = new ViewEngine(_cacheEngine);
            model.ModuleSettingsView = viewEngine.GetModuleDataByModuleId(page, module, moduleControl, moduleAction);
            model.ModuleSettingsView.RequiredClaims = new List <PermissionInfo>();
            model.ModuleSettingsView.RequiredClaims.Add(new PermissionInfo {
                Name = ModuleConfiguration.GrantedAccessPermission
            });

            return(View(model));
        }
コード例 #5
0
ファイル: ViewResult.cs プロジェクト: cdwork/microserver
        /// <inheritdoc />
        public override void ExecuteResult(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string content = string.Empty;

            if (ViewEngine == null)
            {
                try
                {
                    ViewEngine = new ViewEngine(ViewName, ViewSection);
                    content    = ViewEngine.Render(ViewData);
                    context.HttpContext.Response.ContentType = "text/html";
                    context.HttpContext.Response.StatusCode  = StatusCodes.Status200OK;
                }
                catch
                {
                    context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            else
            {
                content = ViewEngine.Render(ViewData);
            }

            context.HttpContext.Response.Write(content, "text/html");
        }
コード例 #6
0
        public string RenderViewToString(ActionContext actionContext, string viewPath, object model)
        {
            // Find the view
            var viewEngineResult = ViewEngine.FindView(actionContext, viewPath, false);

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException($"Couldn't find view '{viewPath}'");
            }

            // Use a stringwriter to write the output
            using (var output = new StringWriter())
            {
                // Create the context to render the view with
                var viewContext = new ViewContext(
                    actionContext,
                    viewEngineResult.View,
                    new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                },
                    new TempDataDictionary(actionContext.HttpContext, TempDataProvider),
                    output,
                    new HtmlHelperOptions());

                viewEngineResult.View.RenderAsync(viewContext).GetAwaiter().GetResult();

                return(output.ToString());
            }
        }
コード例 #7
0
        public ViewEngineResult GetPageFromPathInfo(string pathInfo)
        {
            if (pathInfo.EndsWith("/"))
            {
                pathInfo += "default.cshtml";
            }

            var viewPath = "~/wwwroot".CombineWith(pathInfo);

            if (!viewPath.EndsWith(".cshtml"))
            {
                viewPath += ".cshtml";
            }

            var viewEngineResult = ViewEngine.GetView("", viewPath,
                                                      isMainPage: viewPath == "~/wwwroot/default.cshtml");

            if (!viewEngineResult.Success)
            {
                viewPath = PagesPath.CombineWith(pathInfo);
                if (!viewPath.EndsWith(".cshtml"))
                {
                    viewPath += ".cshtml";
                }

                viewEngineResult = ViewEngine.GetView("", viewPath,
                                                      isMainPage: viewPath == $"{PagesPath}/default.cshtml");
            }

            return(viewEngineResult.Success
                ? viewEngineResult
                : null);
        }
コード例 #8
0
        /// <summary>Initializes the systems of this application.</summary>
        private void InitializeSystems()
        {
            this.viewEngine = new ViewEngine {
                ReplaceNewLine = false
            };
            this.viewEngine.AddContext("MudAttributes", MudEngineAttributes.Instance);

            this.Notify(this.DisplayStartup());
            this.Notify("Starting Application.");

            // Add environment variables needed by the program.
            VariableProcessor.Set("app.path", AppDomain.CurrentDomain.BaseDirectory);

            // Find and prepare all the application's most recent systems from those discovered by MEF.
            var systemExporters = this.GetLatestSystems();

            CoreManager.Instance.SubSystems = new List <ISystem>();
            foreach (var systemExporter in systemExporters)
            {
                CoreManager.Instance.SubSystems.Add(systemExporter.Instance);
            }

            CoreManager.Instance.SubscribeToSystem(this);
            CoreManager.Instance.Start();

            this.Notify("All services are started. Server is fully operational.");
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: aooshi/asmarty
        static void Main(string[] args)
        {
            ViewConfiguration vc = new ViewConfiguration();

            vc.Caching = true;
            //vc.PluginFolder = "";
            vc.WwwrootFolder = AppContext.BaseDirectory;
            vc.ViewFolder    = System.IO.Path.Combine(AppContext.BaseDirectory, "../../../Views/");
            vc.HomePath      = "/";
            vc.ViewExtension = ".tpl";
            vc.Caching       = false;

            //plugin register
            vc.PluginAssemblies.Add(typeof(Program).Assembly);

            //
            ViewEngine = new ViewEngine(vc);


            Adf.HttpServer server = new Adf.HttpServer(8080);
            server.Callback = HttpServerCallback;
            server.Start();

            Console.WriteLine("ok");
            Console.ReadLine();
        }
コード例 #10
0
        public void ViewEngine_SetsAreaPartialViewLocationFormats()
        {
            String[] expected = { "~/Views/{2}/{1}/{0}.cshtml", "~/Views/{2}/Shared/{0}.cshtml" };
            String[] actual   = new ViewEngine().AreaPartialViewLocationFormats;

            Assert.Equal(expected, actual);
        }
コード例 #11
0
	protected IViewResult View(IViewModel viewModel = null, [CallerMemberName] string action = "")
	{
	    UpdateViewData(viewModel);
	    string content = ViewEngine.RenderHtml(Name, action, ViewModel.Data);
	    IRenderable view = new View(content);
	    IViewResult viewResult = new ViewResult(view);
	    return viewResult;
	}
コード例 #12
0
        public void ProceedIfRuntimePolicyIsOff(ViewEngine.FindViews sut, IAlternateMethodContext context)
        {
            context.Setup(c => c.RuntimePolicyStrategy).Returns(() => RuntimePolicy.Off);

            sut.NewImplementation(context);

            context.Verify(c => c.Proceed());
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: Apozhidaev/EmailSender
 static void Main(string[] args)
 {
     var viewEngine = new ViewEngine();
     var bodyProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "<b>{{Value}}</b>") });
     var subjectProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "{{Title}}") });
     var emailService = new EmailService(new EmailRenderer(bodyProvider, viewEngine), new EmailRenderer(subjectProvider, viewEngine), new TestSmtpService());
     emailService.Send(new[] { "tt" }, new TestMail { Value = "777", Title = "555"});
     Console.ReadKey();
 }
コード例 #14
0
        public void ViewEngine_SetsAreaMasterLocationFormats()
        {
            ViewEngine viewEngine = new ViewEngine();

            String[] actual   = viewEngine.AreaMasterLocationFormats;
            String[] expected = { "~/Views/{2}/{1}/{0}.cshtml" };

            Assert.Equal(expected, actual);
        }
コード例 #15
0
        public static IApplicationBuilder UseEngine(this IApplicationBuilder app, ViewEngine viewEngine)
        {
            if (viewEngine != null)
            {
                ViewEngine.Current = viewEngine;
            }

            return(app);
        }
コード例 #16
0
        public async Task <string> ViewToStringAsync <T>(string viewName, T model)
        {
            var context = _ActionContextAccessor.ActionContext;

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var result = new ViewResult()
            {
                ViewData = new ViewDataDictionary(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary())
                {
                    Model = model,
                },
                TempData = new TempDataDictionary(
                    context.HttpContext,
                    _TempDataProvider),
                ViewName = viewName,
            };

            if (ViewEngine == null)
            {
                throw new ArgumentNullException(nameof(ViewEngine));
            }

            var viewEngineResult = ViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);

            if (viewEngineResult.View == null)
            {
                throw new ArgumentNullException(nameof(viewEngineResult.View));
            }

            using (var output = new StringWriter())
            {
                var viewContext = new ViewContext(
                    context,
                    viewEngineResult.View,
                    new ViewDataDictionary(
                        metadataProvider: new EmptyModelMetadataProvider(),
                        modelState: new ModelStateDictionary())
                {
                    Model = model
                },
                    new TempDataDictionary(
                        context.HttpContext,
                        _TempDataProvider),
                    output,
                    new HtmlHelperOptions());

                await viewEngineResult.View.RenderAsync(viewContext);

                return(output.ToString());
            }
        }
コード例 #17
0
        /// <summary>
        /// Determines whether the currently selected master page or MVC layout is an instance of the given view.
        /// </summary>
        /// <param name="currentView">Path of current master page or MVC layout.</param>
        /// <param name="view">Check whether this view is currently selected.</param>
        /// <param name="viewEngine">The view engine.</param>
        /// <returns></returns>
        public static bool CurrentViewIs(string currentView, EsccWebsiteView view, ViewEngine viewEngine = ViewEngine.WebForms)
        {
            var generalSettings = ConfigurationManager.GetSection("Escc.EastSussexGovUK/GeneralSettings") as NameValueCollection;

            if (generalSettings == null)
            {
                generalSettings = ConfigurationManager.GetSection("EsccWebTeam.EastSussexGovUK/GeneralSettings") as NameValueCollection;
            }
            return(IsMasterPageInGroup(currentView, view.ToString(), generalSettings, viewEngine));
        }
コード例 #18
0
        public void PublishMessagesIfRuntimePolicyIsOnAndViewNotFound(ViewEngine.FindViews sut, IAlternateMethodContext context, ControllerContext controllerContext)
        {
            context.Setup(c => c.Arguments).Returns(GetArguments(controllerContext));
            context.Setup(c => c.TargetType).Returns(typeof(int));
            context.Setup(c => c.ReturnValue).Returns(new ViewEngineResult(Enumerable.Empty<string>()));

            sut.NewImplementation(context);

            context.MessageBroker.Verify(b => b.Publish(It.IsAny<ViewEngine.FindViews.Message>())); 
        }
コード例 #19
0
        private string GetViewName(DefinitionRegistry registry, IDefinition definition)
        {
            var definitionSystemName = definition.SystemName;

            if (ViewEngine.FindView(ViewContext, definitionSystemName, false).Success)
            {
                return(definitionSystemName);
            }
            return(GetDefaultViewName(registry, definition));
        }
コード例 #20
0
ファイル: EmailViewRenderer.cs プロジェクト: breaman/EMS
        IView CreateView(string viewName, ActionContext actionContext)
        {
            var viewResult = ViewEngine.FindView(actionContext, viewName, true);

            if (!viewResult.Success)
            {
                throw new Exception($"Email not found for {viewName}. Locations searched: {Environment.NewLine} {string.Join(Environment.NewLine, viewResult.SearchedLocations)}");
            }

            return(viewResult.View);
        }
コード例 #21
0
        public void SetProperties(ViewEngine.FindViews.Message findViewMessage, View.Render.Message viewRenderMessage)
        { 
            var model = new ViewsModel(findViewMessage, viewRenderMessage);

            Assert.Equal(findViewMessage.ViewName, model.ViewName);
            Assert.Equal(findViewMessage.MasterName, model.MasterName);
            Assert.Equal(findViewMessage.IsPartial, model.IsPartial);
            Assert.Equal(findViewMessage.BaseType, model.ViewEngineType);
            Assert.Equal(findViewMessage.UseCache, model.UseCache);
            Assert.Equal(findViewMessage.IsFound, model.IsFound);
            Assert.Equal(findViewMessage.SearchedLocations, model.SearchedLocations);
            Assert.NotNull(model.ViewModelSummary); 
        } 
コード例 #22
0
        private HttpResponse ViewByName <T>(string viewPath, object viewModel)
        {
            IViewEngine viewEngine = new ViewEngine();
            var         html       = File.ReadAllText(viewPath);

            html = viewEngine.GetHtml(html, viewModel);

            var layout         = File.ReadAllText("Views/Shared/_Layout.html");
            var bodyWithLayout = layout.Replace("@RenderBody()", html);

            bodyWithLayout = viewEngine.GetHtml(bodyWithLayout, viewModel);
            return(new HtmlResponse(bodyWithLayout));
        }
コード例 #23
0
        public ViewEngineFixture()
        {
            this.templateLocator = A.Fake<IViewLocator>();
            this.viewCompiler = A.Fake<IViewCompiler>();
            this.view = A.Fake<IView>();
            this.viewLocationResult = new ViewLocationResult(@"c:\some\fake\path", null);

            A.CallTo(() => templateLocator.GetTemplateContents("test")).Returns(viewLocationResult);
            A.CallTo(() => viewCompiler.GetCompiledView<object>(null)).Returns(view);
            A.CallTo(() => viewCompiler.GetCompiledView<MemoryStream>(null)).Returns(view);

            this.engine = new ViewEngine(templateLocator, viewCompiler);
        }
コード例 #24
0
ファイル: ViewsShould.cs プロジェクト: GitObjects/Glimpse
        public void ReturnResult(Views sut, ITabContext context, View.Render.Arguments renderArgs, ViewEngine.FindViews.Message findViewMessage, View.Render.Message renderMessage)
        { 
            context.TabStore.Setup(ds => ds.Contains(typeof(IList<ViewEngine.FindViews.Message>).AssemblyQualifiedName)).Returns(true);
            context.TabStore.Setup(ds => ds.Get(typeof(IList<ViewEngine.FindViews.Message>).AssemblyQualifiedName)).Returns(new List<ViewEngine.FindViews.Message> { findViewMessage });
             
            context.TabStore.Setup(ds => ds.Contains(typeof(IList<View.Render.Message>).AssemblyQualifiedName)).Returns(true);
            context.TabStore.Setup(ds => ds.Get(typeof(IList<View.Render.Message>).AssemblyQualifiedName)).Returns(new List<View.Render.Message> { renderMessage });

            var result = sut.GetData(context) as List<ViewsModel>;

            Assert.NotNull(result);
            Assert.NotEmpty(result);
        }
コード例 #25
0
        public void CollectionWithComplexTypeThrowsDuringRenderingTest(Type complexType)
        {
            ViewEngine engine = ViewEngineSetup.SetupViewEngine("<ul>@Model.Collection.Collection(<li>@Item</li>)</ul>");

            object[] complexObjectCollection = { Activator.CreateInstance(complexType) };

            Dictionary <string, object> propertyBag = new Dictionary <string, object>
            {
                ["Collection"] = complexObjectCollection
            };

            Assert.That(() => engine.RenderView(string.Empty, string.Empty, propertyBag), Throws.ArgumentException);
        }
コード例 #26
0
ファイル: ViewEngineTests.cs プロジェクト: DDeveloperBG/Tasks
        public void TestWithoutViewModel(string folderName)
        {
            string path = FolderPath + folderName;

            string input          = FileReader.ReadAllText(path + "ImputData.html");
            string expectedResult = FileReader.ReadAllText(path + "ResultData.html");

            IViewEngine viewEngine = new ViewEngine();

            string actualResult = viewEngine.GetHtml(input, null, null);

            Assert.Equal(expectedResult, actualResult);
        }
コード例 #27
0
        public void CollectionRenderingTest(params object[] collection)
        {
            ViewEngine engine = ViewEngineSetup.SetupViewEngine("<ul>@Model.Collection.Collection(<li>@Item</li>)</ul>");

            Dictionary <string, object> propertyBag = new Dictionary <string, object>
            {
                ["Collection"] = collection
            };

            string renderedView = engine.RenderView(string.Empty, string.Empty, propertyBag);

            Assert.That(renderedView, Is.EqualTo($"<ul>{string.Concat(collection.Select(item => $"<li>{item}</li>"))}</ul>"));
        }
コード例 #28
0
        public void NullPrimitiveValueRenderingTest()
        {
            ViewEngine viewEngine = ViewEngineSetup.SetupViewEngine("<h1>@Model.Value</h1>");

            Dictionary <string, object> propertyBag = new Dictionary <string, object>
            {
                ["Value"] = null
            };

            string renderedHtml = viewEngine.RenderView(string.Empty, string.Empty, propertyBag);

            Assert.That(renderedHtml, Is.EqualTo("<h1>null</h1>"));
        }
コード例 #29
0
ファイル: MvcDisplay.cs プロジェクト: GitObjects/Glimpse
        private void UpdateView(ViewEngine.FindViews.Message message, ITabSetupContext context)
        {
            if (message.IsFound)
            {
                var model = GetModel(context.GetTabStore());

                model.ChildViewCount++;

                if (model.ViewName == null)
                {
                    model.ViewName = message.ViewName;
                }
            }
        }
コード例 #30
0
        ///// <summary> Find a view by a specific path and filename. </summary>
        ///// <param name="filepath"> The filepath. </param>
        ///// <returns> The found view. </returns>
        //x private IFileInfo _FindView(string filepath)
        //{
        //    IFileInfo result = null;
        //    foreach (var fp in RazorViewEngineOptions.FileProviders)
        //    {
        //        result = fp.GetFileInfo(filepath);
        //        if (result?.Exists == true) return result;
        //    }
        //    return result ?? new NotFoundFileInfo(filepath);
        //}

        /// <summary> Using a base path and type name find a view file. </summary>
        /// <exception cref="FileNotFoundException"> Thrown when the requested file is not present. </exception>
        /// <param name="searchPaths"> The locations to search under (without the filename). </param>
        /// <param name="name"> Name of the type to find a nested view for. </param>
        /// <param name="required">
        ///     (Optional) True if the view is required. If required and not found an exception will be thrown. Default is true.
        /// </param>
        /// <returns> The found view. </returns>
        private ViewEngineResult _FindView(IEnumerable <string> searchPaths, string name, bool required = true)
        {
            List <string> filenames = new List <string>();

            filenames.Add(Path.ChangeExtension(name, "cshtml")); // (put the most likely one first)
            filenames.Add(Path.ChangeExtension(name, "cs.cshtml"));
            filenames.Add(name);

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

            ViewEngineResult result = null;

            // ... detect if this is a base path, or path with a file name ...
            // ('GetView()' expects the base path to end with '/', otherwise the last path name will be truncated off)

            var _searchPaths = searchPaths.ToArray();

            for (int i = 0, n = _searchPaths.Length; i < n; ++i)
            {
                var searchPath = _searchPaths[i];

                if (string.IsNullOrWhiteSpace(Path.GetExtension(searchPath)) && !searchPath.EndsWith("/"))
                {
                    searchPath += "/";
                }

                foreach (var filename in filenames)
                {
                    result = ViewEngine.GetView(searchPath, filename, false);
                    if (result.Success)
                    {
                        return(result);
                    }
                    else
                    {
                        locationsSearched.AddRange(result.SearchedLocations);
                    }
                }
            }

            if (required)
            {
                throw new FileNotFoundException("Failed to find view '" + name + "'. Locations searched: " + Environment.NewLine + " > " + string.Join(Environment.NewLine + " > ", locationsSearched));
            }
            else
            {
                return(null);
            }
        }
コード例 #31
0
        /// <summary>
        /// The application_ start.
        /// </summary>
        protected void Application_Start()
        {
            // 注册MVC区域
            AreaRegistration.RegisterAllAreas();

            // WebApiConfig.Register(GlobalConfiguration.Configuration);
            // 注册过滤器
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            // 注册路由规则
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            // 注册视图规则
            ViewEngine.RegisterView(ViewEngines.Engines);
        }
コード例 #32
0
ファイル: ViewEngineTests.cs プロジェクト: DDeveloperBG/Tasks
        public void TestWithViewModel()
        {
            string path = FolderPath + "Test5/";

            string input          = FileReader.ReadAllText(path + "ImputData.html");
            string expectedResult = FileReader.ReadAllText(path + "ResultData.html");

            IViewEngine viewEngine = new ViewEngine();

            var viewModel = new MockClass1("*****@*****.**", "Gosho", 20);

            string actualResult = viewEngine.GetHtml(input, viewModel, null);

            Assert.Equal(expectedResult, actualResult);
        }
コード例 #33
0
        /// <summary>Looks at room. @@@ Move to SensesBehavior?</summary>
        /// <param name="sender">The sender.</param>
        /// <returns>Returns the text of the rendered room template.</returns>
        private string LookAtRoom(Thing sender)
        {
            var context = new Hashtable
            {
                { "Room", sender.Parent },
                { "Exits", this.sensesBehavior.PerceiveExits() },
                { "Entities", this.sensesBehavior.PerceiveEntities() },
                { "Items", this.sensesBehavior.PerceiveItems() }
            };

            string viewTemplateName = MudEngineAttributes.Instance.RoomFormatingTemplateFile;
            var    viewEngine       = new ViewEngine();

            return(viewEngine.RenderCachedView(viewTemplateName, context));
        }
コード例 #34
0
ファイル: HtmlHelper.cs プロジェクト: softwx/ServiceStack
        public MvcHtmlString Partial(string viewName, object model)
        {
            var masterModel = this.viewData;

            try
            {
                this.viewData = new ViewDataDictionary(model);
                var result = ViewEngine.RenderPartial(viewName, model, this.RenderHtml, Writer, this);
                return(MvcHtmlString.Create(result));
            }
            finally
            {
                this.viewData = masterModel;
            }
        }
コード例 #35
0
        public void TestGetHtmlWithGenericTemplateModel()
        {
            var viewModel = new Dictionary <string, Dictionary <string, int> >()
            {
                {
                    "Pesho",
                    new Dictionary <string, int>
                    {
                        { "C# Basics", 100 }, { "C# Web", 75 },
                    }
                },
                {
                    "Gosho",
                    new Dictionary <string, int>
                    {
                        { "JavaScript Advanced", 30 }, { "PHP Web", 50 },
                    }
                }
            };

            var         viewContent           = @"
@foreach (var student in Model)
{
<p> User: @student.Key </p>
<ul>
@foreach (var course in student.Value)
{
<li> @course.Key -> @course.Value </li>
}
</ul>
}";
            var         expectedResultContent = @"
<p> User: Pesho </p>
<ul>
<li> C# Basics -> 100 </li>
<li> C# Web -> 75 </li>
</ul>
<p> User: Gosho </p>
<ul>
<li> JavaScript Advanced -> 30 </li>
<li> PHP Web -> 50 </li>
</ul>
";
            IViewEngine viewEngine            = new ViewEngine();
            var         actualResult          = viewEngine.GetHtml(viewContent, viewModel, null);

            Assert.Equal(expectedResultContent, actualResult);
        }
コード例 #36
0
ファイル: ViewsModel.cs プロジェクト: GProulx/Glimpse
        public ViewsModel(ViewEngine.FindViews.Message viewEngineFindView, View.Render.Message viewRender)
        { 
            ViewName = viewEngineFindView.ViewName;
            MasterName = viewEngineFindView.MasterName;
            IsPartial = viewEngineFindView.IsPartial;
            ViewEngineType = viewEngineFindView.BaseType;
            UseCache = viewEngineFindView.UseCache;
            IsFound = viewEngineFindView.IsFound;
            SearchedLocations = viewEngineFindView.SearchedLocations;

            if (viewRender != null)
            {
                SourceController = viewRender.ControllerName;
                ViewModelSummary = new ViewModelSummary(viewRender.ViewData, viewRender.TempData, viewRender.ViewDataModelType, viewRender.ModelStateIsValid, viewEngineFindView.DisplayModeId, viewEngineFindView.DisplayModeType);
            }
        }
コード例 #37
0
 /// <summary>
 /// Gets the current master page or MVC layout type based on its path
 /// </summary>
 /// <param name="currentView">Path of current master page or MVC layout.</param>
 /// <param name="viewEngine">The view engine.</param>
 /// <returns></returns>
 public static EsccWebsiteView CurrentViewIs(string currentView, ViewEngine viewEngine = ViewEngine.WebForms)
 {
     if (CurrentViewIs(currentView, EsccWebsiteView.Desktop, viewEngine))
     {
         return(EsccWebsiteView.Desktop);
     }
     if (CurrentViewIs(currentView, EsccWebsiteView.FullScreen, viewEngine))
     {
         return(EsccWebsiteView.FullScreen);
     }
     if (CurrentViewIs(currentView, EsccWebsiteView.Plain, viewEngine))
     {
         return(EsccWebsiteView.Plain);
     }
     return(EsccWebsiteView.Unknown);
 }
コード例 #38
0
        protected virtual IViewable View([CallerMemberName] string actionName = default)
        {
            string controllerName = GetType().Name.Replace(MvcContext.ControllersSuffix, string.Empty);

            string viewContent;

            try
            {
                viewContent = ViewEngine.RenderView(controllerName, actionName, PropertyBag);
            }
            catch (Exception e)
            {
                viewContent = ViewEngine.RenderError(e.Message, PropertyBag["role"].ToString());
            }

            return(new ViewResult(new View(viewContent)));
        }
コード例 #39
0
        public void PublishMessagesIfRuntimePolicyIsOnAndViewIsFound([Frozen] IProxyFactory proxyFactory, ViewEngine.FindViews sut, IAlternateMethodContext context, IView view, IViewEngine engine, ControllerContext controllerContext)
        {
            context.Setup(c => c.Arguments).Returns(GetArguments(controllerContext));
            context.Setup(c => c.ReturnValue).Returns(new ViewEngineResult(view, engine));
            context.Setup(c => c.TargetType).Returns(typeof(int));
            proxyFactory.Setup(p => p.IsWrapInterfaceEligible<IView>(It.IsAny<Type>())).Returns(true);
            proxyFactory.Setup(p => 
                    p.WrapInterface(
                        It.IsAny<IView>(), 
                        It.IsAny<IEnumerable<IAlternateMethod>>(),
                        It.IsAny<IEnumerable<object>>()))
                    .Returns(view);

            sut.NewImplementation(context);

            proxyFactory.Verify(p => p.IsWrapInterfaceEligible<IView>(It.IsAny<Type>()));
            context.Logger.Verify(l => l.Info(It.IsAny<string>(), It.IsAny<object[]>()));
            context.VerifySet(c => c.ReturnValue = It.IsAny<ViewEngineResult>());
            context.MessageBroker.Verify(b => b.Publish(It.IsAny<ViewEngine.FindViews.Message>())); 
        }
コード例 #40
0
        public void Setup(IInspectorContext context)
        {
            var logger = context.Logger;

            var alternateImplementation = new ViewEngine(context.ProxyFactory);

            var currentEngines = ViewEngines.Engines;
            for (var i = 0; i < currentEngines.Count; i++)
            {
                var originalEngine = currentEngines[i];

                IViewEngine newEngine;
                if (alternateImplementation.TryCreate(originalEngine, out newEngine))
                {
                    currentEngines[i] = newEngine;
                    logger.Info(Resources.ViewEngineSetupReplacedViewEngine, originalEngine.GetType());
                }
                else
                {
                    logger.Warn(Resources.ViewEngineSetupNotReplacedViewEngine, originalEngine.GetType()); 
                }
            }
        }
コード例 #41
0
        public void Setup(IInspectorContext context)
        {
            var logger = context.Logger;

            var alternateImplementation = new ViewEngine(context.ProxyFactory);

            var currentEngines = ViewEngines.Engines;
            for (var i = 0; i < currentEngines.Count; i++)
            {
                var originalEngine = currentEngines[i];

                IViewEngine newEngine;
                if (alternateImplementation.TryCreate(originalEngine, out newEngine))
                {
                    currentEngines[i] = newEngine;
                    logger.Info("Replaced IViewEngine of type '{0}' with proxy implementation.", originalEngine.GetType());
                }
                else
                {
                    logger.Warn("Couldn't replace IViewEngine of type '{0}' with proxy implementation.", originalEngine.GetType()); 
                }
            }
        }
コード例 #42
0
ファイル: SessionManager.cs プロジェクト: Hobbitron/WheelMUD
        private void LoadSplashScreens()
        {
            string name = Configuration.GetDataStoragePath();
            string path = Path.Combine(Path.GetDirectoryName(name), "Files");
            path = Path.Combine(path, "SplashScreens");

            var viewEngine = new ViewEngine();
            viewEngine.AddContext("MudAttributes", MudEngineAttributes.Instance);

            var dirInfo = new DirectoryInfo(path);
            var files = new List<FileInfo>(dirInfo.GetFiles());

            foreach (var fileInfo in files)
            {
                var sr = new StreamReader(fileInfo.FullName);
                string splashContent = sr.ReadToEnd();
                sr.Close();

                string renderedScreen = viewEngine.RenderView(splashContent);

                splashScreens.Add(renderedScreen);
                this.SystemHost.UpdateSystemHost(this, string.Format("{0} has been loaded.", fileInfo.Name));
            }
        }
コード例 #43
0
ファイル: Look.cs プロジェクト: Hobbitron/WheelMUD
        /// <summary>
        /// Looks at room. @@@ Move to SensesBehavior?
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <returns>Returns the text of the rendered room template.</returns>
        private string LookAtRoom(Thing sender)
        {
            var context = new Hashtable
            {
                { "Room", sender.Parent },
                { "Exits", this.sensesBehavior.PerceiveExits() },
                { "Entities", this.sensesBehavior.PerceiveEntities() },
                { "Items", this.sensesBehavior.PerceiveItems() }
            };

            string viewTemplateName = MudEngineAttributes.Instance.RoomFormatingTemplateFile;
            var viewEngine = new ViewEngine();
            return viewEngine.RenderCachedView(viewTemplateName, context);
        }
コード例 #44
0
ファイル: Look.cs プロジェクト: Hobbitron/WheelMUD
        /// <summary>
        /// Tries the look at thing.
        /// </summary>
        /// <param name="thingToLookAt">The thing to look at.</param>
        /// <param name="sender">The sender.</param>
        /// <returns>Returns the rendered view.</returns>
        private string TryLookAtThing(string thingToLookAt, Thing sender)
        {
            // @@@ TODO: Refactor ViewEngine to remove NVelicoty: https://wheelmud.codeplex.com/workitem/13348
            var viewEngine = new ViewEngine();

            // Look for target in the current room
            Thing thing = sender.Parent.FindChild(thingToLookAt);
            if (thing != null && this.sensesBehavior.CanPerceiveThing(thing))
            {
                return viewEngine.RenderView(thing);
            }

            // If no target found, see if it matches any of the room's visuals.
            var room = sender.Parent.FindBehavior<RoomBehavior>();
            if (room != null)
            {
                string visual = room.FindVisual(thingToLookAt);
                if (!string.IsNullOrEmpty(visual))
                {
                    return viewEngine.RenderView(visual);
                }
            }

            // At this point, target was not found.
            return string.Empty;
        }
コード例 #45
0
 /// <summary>
 /// Sets the default properties of this behavior instance.
 /// </summary>
 protected override void SetDefaultProperties()
 {
     this.Controller = null;
     this.ViewEngine = new ViewEngine();
 }
コード例 #46
0
        public void ReturnAllMethodImplementationsWithAllMethods(ViewEngine sut)
        {
            var allMethods = sut.AllMethods;

            Assert.Equal(2, allMethods.Count());
        }