public static string HiddenInput(HtmlHelper html)
 {
     if (html.Context.ViewData.Metadata.HideSurroundingChrome)
         return System.String.Empty;
     
     return String(html);
 }
        internal static string HiddenInputTemplate(HtmlHelper html) {
            string result;

            if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingChrome) {
                result = String.Empty;
            }
            else {
                result = DefaultDisplayTemplates.StringTemplate(html);
            }

            object model = html.ViewContext.ViewData.Model;

            Binary modelAsBinary = model as Binary;
            if (modelAsBinary != null) {
                model = Convert.ToBase64String(modelAsBinary.ToArray());
            }
            else {
                byte[] modelAsByteArray = model as byte[];
                if (modelAsByteArray != null) {
                    model = Convert.ToBase64String(modelAsByteArray);
                }
            }

            result += html.Hidden(String.Empty, model).ToHtmlString();
            return result;
        }
		public void SetUp()
		{
			string siteRoot = GetSiteRoot();
			string viewPath = Path.Combine(siteRoot, "RenderingTests\\Views");
			Layout = null;
			PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
			Helpers = new HelperDictionary();
			StubMonoRailServices services = new StubMonoRailServices();
			services.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine());
			services.UrlTokenizer = new DefaultUrlTokenizer();
			UrlInfo urlInfo = new UrlInfo(
				"example.org", "test", "/TestBrail", "http", 80,
				"http://test.example.org/test_area/test_controller/test_action.tdd",
				Area, ControllerName, Action, "tdd", "no.idea");
			StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services,
													  urlInfo);
			StubEngineContext.AddService<IUrlBuilder>(services.UrlBuilder);
			StubEngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer);
			StubEngineContext.AddService<IViewComponentFactory>(ViewComponentFactory);
			StubEngineContext.AddService<ILoggerFactory>(new ConsoleFactory());
			StubEngineContext.AddService<IViewSourceLoader>(new FileAssemblyViewSourceLoader(viewPath));
			

			ViewComponentFactory = new DefaultViewComponentFactory();
			ViewComponentFactory.Service(StubEngineContext);
			ViewComponentFactory.Initialize();

			ControllerContext = new ControllerContext();
			ControllerContext.Helpers = Helpers;
			ControllerContext.PropertyBag = PropertyBag;
			StubEngineContext.CurrentControllerContext = ControllerContext;


			Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext);
			Helpers["htmlhelper"] = Helpers["html"] = new HtmlHelper(StubEngineContext);
			Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext);
			Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext);


			//FileAssemblyViewSourceLoader loader = new FileAssemblyViewSourceLoader(viewPath);
//			loader.AddAssemblySource(
//				new AssemblySourceInfo(Assembly.GetExecutingAssembly().FullName,
//									   "Castle.MonoRail.Views.Brail.Tests.ResourcedViews"));

			viewEngine = new AspViewEngine();
			viewEngine.Service(StubEngineContext);
			AspViewEngineOptions options = new AspViewEngineOptions();
			options.CompilerOptions.AutoRecompilation = true;
			options.CompilerOptions.KeepTemporarySourceFiles = false;
			ICompilationContext context = 
				new CompilationContext(
					new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory),
					new DirectoryInfo(siteRoot),
					new DirectoryInfo(Path.Combine(siteRoot, "RenderingTests\\Views")),
					new DirectoryInfo(siteRoot));

			List<ICompilationContext> compilationContexts = new List<ICompilationContext>();
			compilationContexts.Add(context);
			viewEngine.Initialize(compilationContexts, options);
		}
        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            TemplateInfo templateInfo = viewData.TemplateInfo;
            ModelMetadata modelMetadata = viewData.ModelMetadata;
            StringBuilder builder = new StringBuilder();

            if (templateInfo.TemplateDepth > 1) {    // DDB #224751
                return modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText;
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForEdit && !templateInfo.Visited(pm))) {
                if (!propertyMetadata.HideSurroundingChrome) {
                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();
                    if (!String.IsNullOrEmpty(label)) {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);
                    }

                    builder.Append("<div class=\"editor-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit));

                if (!propertyMetadata.HideSurroundingChrome) {
                    builder.Append(" ");
                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName, "*"));
                    builder.Append("</div>\r\n");
                }
            }

            return builder.ToString();
        }
        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            TemplateInfo templateInfo = viewData.TemplateInfo;
            ModelMetadata modelMetadata = viewData.ModelMetadata;
            StringBuilder builder = new StringBuilder();

            if (modelMetadata.Model == null) {    // DDB #225237
                return modelMetadata.NullDisplayText;
            }

            if (templateInfo.TemplateDepth > 1) {    // DDB #224751
                return modelMetadata.SimpleDisplayText;
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForDisplay && !templateInfo.Visited(pm))) {
                if (!propertyMetadata.HideSurroundingChrome) {
                    string label = propertyMetadata.GetDisplayName();
                    if (!String.IsNullOrEmpty(label)) {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"display-label\">{0}</div>", label);
                        builder.AppendLine();
                    }

                    builder.Append("<div class=\"display-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.ReadOnly));

                if (!propertyMetadata.HideSurroundingChrome) {
                    builder.AppendLine("</div>");
                }
            }

            return builder.ToString();
        }
		public static string Decimal(HtmlHelper html)
		{
			if (html.Context.ViewData.Template.Value == html.Context.ViewData.Model)
				html.Context.ViewData.Template.Value = string.Format(CultureInfo.CurrentCulture, 
					"{0:0.00}", html.Context.ViewData.Model);

			return String(html);
		}
Exemple #7
0
        public void Test1()
        {
            //string content = DownloadHelper.Download("");
            //DownloadHelper.ParseIndexPage("http://yongche.16888.com/index.html");
            //DownloadHelper download = new DownloadHelper();
            //download.DownloadFromRequest("http://yongche.16888.com/index.html");

            //string targetPath = "c:\\a.html";

            //1. write website rule
            //2. save website info or send it to MQ queue
            /*List<UrlModel> urls = new List<UrlModel>(){
                UrlManager.CreateModel("http://yongche.16888.com/mrzs/index_1_1.html","美容知识"),
                UrlManager.CreateModel("http://yongche.16888.com/yfzs/index_1_1.html","养护知识"),
                UrlManager.CreateModel("http://yongche.16888.com/gzzs/index_1_1.html","改装知识"),
                UrlManager.CreateModel("http://yongche.16888.com/cjzs/index_1_1.html","车居知识"),
                UrlManager.CreateModel("http://yongche.16888.com/cyp/index_1_1.html","汽车用品"),
                UrlManager.CreateModel("http://yongche.16888.com/bszh/index_1_1.html","保险知识"),
                UrlManager.CreateModel("http://yongche.16888.com/wxzs/index_1_1.html","维修知识")
            };

            RuleModel rule = RuleManager.CreateModel("//dt[1]//a[2]", "//div[@class='news_list']//dl",
                                                        "//dt[1]//a[@class='f_gray']", "//dt[1]//span[@class='ico_j']",
                                                        "//dd[1]//span[1]", "//dd[1]//img[1]", "//dt[1]//span[@class='f_r']");

            WebSiteModel model = WebSiteManager.CreateModel(urls, rule, "addr");*/

            WebSiteModel model = CreateTestModel();

            string result = JsonHelper.Serializer(model);
            FileHelper.WriteTo(result, "c:\\bb.data");

            //2. download from url
            //3. save result

            WebSiteModel newModel = WebSiteManager.GetSiteInfo("c:\\bb.data");
            HtmlHelper helper = new HtmlHelper();
            List<string> targetPaths = new List<string>();

            foreach (UrlModel item in newModel.DownloadUrls)
            {
                string url = item.Url;
                string localDriver = "c:\\";
                string targetPath = string.Format("{0}{1}.html", localDriver, FileHelper.GenerateFileName(url));

                helper.Download(url);
                helper.SaveTo(helper.M_Html, targetPath);

                targetPaths.Add(targetPath);
            }

            //4. pase page from local file
            WebSiteModel parseModel = WebSiteManager.GetSiteInfo("c:\\bb.data");
            YongcheHtmlHelper yongche = new YongcheHtmlHelper();
            string tempContent = System.IO.File.ReadAllText(targetPaths[0], Encoding.Default);
            List<Article> articles = yongche.ParseArticle(tempContent, parseModel);
        }
        internal static string BooleanTemplate(HtmlHelper html) {
            bool? value = null;
            if (html.ViewContext.ViewData.Model != null) {
                value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);
            }

            return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType
                        ? BooleanTemplateDropDownList(html, value)
                        : BooleanTemplateCheckbox(html, value ?? false);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RouteLinkHtmlElement"/> class.
        /// </summary>
        /// <param name="routeName">The name of the target route.</param>
        /// <param name="htmlHelper">The helper used to render HTML.</param>
        public RouteLinkHtmlElement(string routeName, HtmlHelper htmlHelper)
            : base(htmlHelper)
        {
            if (routeName.IsNullOrEmpty())
            {
                throw new ArgumentException("Route name cannot be null or empty.", "routeName");
            }

            this.routeName = routeName;
        }
        public void DefaultRouteCollectionIsRouteTableRoutes() {
            // Arrange
            var viewContext = new Mock<ViewContext>().Object;
            var viewDataContainer = new Mock<IViewDataContainer>().Object;

            // Act
            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);

            // Assert
            Assert.AreEqual(RouteTable.Routes, htmlHelper.RouteCollection);
        }
        public void ViewContextProperty() {
            // Arrange
            ViewContext viewContext = new Mock<ViewContext>().Object;
            HtmlHelper htmlHelper = new HtmlHelper(viewContext, new Mock<IViewDataContainer>().Object);

            // Act
            ViewContext value = htmlHelper.ViewContext;

            // Assert
            Assert.AreEqual(viewContext, value);
        }
        public void ViewDataContainerProperty() {
            // Arrange
            ViewContext viewContext = new Mock<ViewContext>().Object;
            IViewDataContainer container = new Mock<IViewDataContainer>().Object;
            HtmlHelper htmlHelper = new HtmlHelper(viewContext, container);

            // Act
            IViewDataContainer value = htmlHelper.ViewDataContainer;

            // Assert
            Assert.AreEqual(container, value);
        }
Exemple #13
0
        public override void GetDetailHtml(Product product, Site site)
        {
            loginfo.Location = this.GetType().Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
            loginfo.Url = product.Url;
            loginfo.KeyInfo = site.SiteName;

            HtmlHelper html = new HtmlHelper(product.Html);

            //get product detail nodes
            var product_node = html.GetNodeByXPath("//div[@class='products']/div[@class='product']/div[@class='desktop']");

            //get product description
            var description_nodes = html.GetNodesByXPath("./div[@class='bottom']/div[1]/div[1]/div[@class='description open-sans-regular']/*",product_node);
            string description = "";

            if (description_nodes.Count > 0)
            {
                foreach (var sellpoint_node in description_nodes)
                {
                    if (sellpoint_node.Equals(description_nodes.First()))
                    {
                        description += sellpoint_node.FirstChild.InnerText.Trim();
                    }
                    else
                    {
                        description += "|" + sellpoint_node.FirstChild.InnerText.Trim();
                    }
                }
            }

            //get sell point
            var sellpoint_nodes = html.GetNodesByXPath("./div[@class='bottom']/div[1]/div[1]/div[@class='bullets open-sans-regular']/div", product_node);
            string sellpoints = "";
            if(sellpoint_nodes.Count>0)
            {
                foreach(var sellpoint_node in sellpoint_nodes)
                {
                    if (sellpoint_node.Equals(sellpoint_nodes.First()))
                    {
                        sellpoints += sellpoint_node.FirstChild.InnerText.Trim();
                    }
                    else
                    {
                        sellpoints += "|" + sellpoint_node.FirstChild.InnerText.Trim();
                    }
                }
            }

            product.Description = description;
            product.SellPoint = sellpoints;
        }
        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            object model = html.ViewContext.ViewData.ModelMetadata.Model;
            if (model == null) {
                return String.Empty;
            }

            IEnumerable collection = model as IEnumerable;
            if (collection == null) {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        MvcResources.Templates_TypeMustImplementIEnumerable,
                        model.GetType().FullName
                    )
                );
            }

            Type typeInCollection = typeof(string);
            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));
            if (genericEnumerableType != null) {
                typeInCollection = genericEnumerableType.GetGenericArguments()[0];
            }
            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);

            string oldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;

            try {
                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;

                string fieldNameBase = oldPrefix;
                StringBuilder result = new StringBuilder();
                int index = 0;

                foreach (object item in collection) {
                    Type itemType = typeInCollection;
                    if (item != null && !typeInCollectionIsNullableValueType) {
                        itemType = item.GetType();
                    }
                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);
                    string fieldName = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++);
                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */);
                    result.Append(output);
                }

                return result.ToString();
            }
            finally {
                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;
            }
        }
            /// <summary>
            /// Renders a script block to the specified 
            /// <paramref name="writer"/>.
            /// </summary>
            /// <param name="writer">A <see cref="System.IO.TextWriter"/> 
            /// to render the script block to.</param>
            internal void Render(TextWriter writer)
            {
                HtmlHelper helper = new HtmlHelper(_manager._context);
                StringBuilder builder = new StringBuilder(Environment.NewLine);

                foreach (string code in _scripts.Where(a => a != null)
                    .Select(a => helper.Block(a)))
                    builder.AppendLine(code);

                if (builder.Length > Environment.NewLine.Length)
                    writer.WriteLine((_wrapper == null) ?
                        builder.ToString() :
                        helper.Block(_wrapper, builder.ToString()));
            }
		public static string Hidden(HtmlHelper html)
		{
			string elementName = html.Context.ViewData.Template
				.GetHtmlElementName(System.String.Empty);

			object model = html.Context.ViewData.Model;
			byte[] modelAsByteArray = (model as byte[]);
			if (modelAsByteArray != null)
				model = Convert.ToBase64String(modelAsByteArray);

			return html.Controls.Hidden(elementName,
				model, new {
					@id = elementName
				});
		}
Exemple #17
0
    public static Modal Dialog(HtmlHelper helper, string id, string closeBtn=null, IDictionary<string, string> buttons=null)
    {
      var opts = new Options();

      opts.Id = id;
      opts.Titled = false;
      opts.CloseButton = closeBtn;
      if (opts.CloseButton != null) {
        opts.Footer = true;
      }
      if (buttons != null && buttons.Count > 0) {
        opts.Footer = true;
      }

      return CreateModal(helper, opts);
    }
        public void PropertiesAreSet() {
            // Arrange
            var viewContext = new Mock<ViewContext>().Object;
            var viewData = new ViewDataDictionary<String>("The Model");
            var routes = new RouteCollection();
            var mockViewDataContainer = new Mock<IViewDataContainer>();
            mockViewDataContainer.Setup(vdc => vdc.ViewData).Returns(viewData);

            // Act
            var htmlHelper = new HtmlHelper(viewContext, mockViewDataContainer.Object, routes);

            // Assert
            Assert.AreEqual(viewContext, htmlHelper.ViewContext);
            Assert.AreEqual(mockViewDataContainer.Object, htmlHelper.ViewDataContainer);
            Assert.AreEqual(routes, htmlHelper.RouteCollection);
            Assert.AreEqual(viewData.Model, htmlHelper.ViewData.Model);
        }
		public static string Enumeration(HtmlHelper html)
		{
			string elementName = html.Context.ViewData.Template
				.GetHtmlElementName(System.String.Empty);

			Type enumType = html.Context.ViewData.Metadata.Type;

			if (!enumType.IsEnum) // handle enums only
				return Object(html);

			return html.Controls.DropDownList(elementName,
				EnumerationValues(enumType, html.Context.ViewData
					.Metadata.IsNullableValueType, 
					html.Context.ViewData.Model),
				new {
					@id = elementName
				});
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="ActionLinkHtmlElement"/> class.
        /// </summary>
        /// <param name="actionName">The name of the target action.</param>
        /// <param name="controllerName">The name of the target controller.</param>
        /// <param name="htmlHelper">The helper used to render HTML.</param>
        public ActionLinkHtmlElement(string actionName, string controllerName, HtmlHelper htmlHelper)
            : base(htmlHelper)
        {
            if (actionName.IsNullOrEmpty())
            {
                this.actionName = htmlHelper.InnerHelper.ViewContext.RouteData.Values["Action"].ToString();
            }
            else
            {
                this.actionName = actionName;
            }

            if (controllerName.IsNullOrEmpty())
            {
                this.controllerName = htmlHelper.InnerHelper.ViewContext.RouteData.Values["Controller"].ToString();
            }
            else
            {
                this.controllerName = controllerName;
            }
        }
        public static string Boolean(HtmlHelper html)
        {
            string elementName = html.Context.ViewData.Template
                .GetHtmlElementName(System.String.Empty);
            bool model = false;

            if (html.Context.ViewData.Model != null)
                model = Convert.ToBoolean(html.Context.ViewData.Model, 
                    CultureInfo.InvariantCulture);

            if (html.Context.ViewData.Metadata.IsNullableValueType)
            {
                bool isNull = (html.Context.ViewData.Model == null);
                return html.Controls.DropDownList(elementName,
                    DefaultEditorTemplates.TriStateValues(isNull, model), 
                    new { @id = elementName, @disabled = "disabled" });
            }
            
            return html.Controls.CheckBox(elementName, model,
                new { @id = elementName, @disabled = "disabled" });
        }
		public static string Collection(HtmlHelper html)
		{
			object model = html.Context.ViewData.Model;
			if (model == null)
				return string.Empty;

			IEnumerable collection = (model as IEnumerable);
			if (collection == null)
				throw Error.CollectionTypeMustBeEnumerable(model.GetType());

			Type elementType = collection.GetType().GetSequenceElementType() ?? typeof(string);
			elementType = elementType.MakeNonNullableType();
			string oldPrefix = html.Context.ViewData.Template.Prefix;

			try
			{
				html.Context.ViewData.Template.Prefix = string.Empty;

				StringBuilder result = new StringBuilder();
				int index = 0;

				foreach (object item in collection)
				{
					Type itemType = elementType;
					if (item != null)
						itemType = item.GetType().MakeNonNullableType();
					
					ModelMetadata metadata = Configuration.Instance.Models
						.MetadataProvider.GetMetadata(itemType);

					string fieldName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", oldPrefix, index++);
					result.Append(html.Templates.Render(DataBoundControlMode.ReadOnly, metadata, null, fieldName, item));
				}
				return result.ToString();
			}
			finally
			{
				html.Context.ViewData.Template.Prefix = oldPrefix;
			}
		}
        private static HtmlHelper GetFormHelper(string formOpenTagExpectation, string formCloseTagExpectation, out Mock<HttpResponseBase> mockHttpResponse) {
            Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>();
            mockHttpRequest.Expect(r => r.Url).Returns(new Uri("http://www.contoso.com/some/path"));
            mockHttpRequest.Expect(r => r.RawUrl).Returns("/some/path");
            mockHttpResponse = new Mock<HttpResponseBase>(MockBehavior.Strict);
            mockHttpResponse.Expect(r => r.Write(formOpenTagExpectation)).Verifiable();

            Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { CallBase = true };
            mockViewContext.Expect(c => c.HttpContext.Request.Url).Returns(new Uri("http://www.contoso.com/some/path"));
            mockViewContext.Expect(c => c.HttpContext.Request.RawUrl).Returns("/some/path");
            mockViewContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/");
            mockViewContext.Expect(c => c.HttpContext.Request.Path).Returns("/");
            mockViewContext.Expect(c => c.HttpContext.Response).Returns(mockHttpResponse.Object);

            if (!String.IsNullOrEmpty(formCloseTagExpectation)) {
                mockHttpResponse.Expect(r => r.Write(formCloseTagExpectation)).AtMostOnce().Verifiable();
            }
            mockHttpResponse.Expect(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => HtmlHelperTest.AppPathModifier + r);

            RouteCollection rt = new RouteCollection();
            rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            RouteData rd = new RouteData();
            rd.Values.Add("controller", "home");
            rd.Values.Add("action", "oldaction");

            mockViewContext.Expect(c => c.RouteData).Returns(rd);
            HtmlHelper helper = new HtmlHelper(mockViewContext.Object, new Mock<IViewDataContainer>().Object, rt);
            helper.FormIdGenerator = () => "form_id";
            return helper;
        }
        /// <summary>
        /// Instantiates and initializes the Ajax, Html, and Url properties.
        /// </summary>
        public virtual void InitHelpers(ViewContext context)
        {
			Precondition.Require(context, 
				() => Mvc.Error.ArgumentNull("context"));

            SetContentType(context.Context);
            _parameters = context.Context.Request.Parameters;
            _html = new HtmlHelper(context);
            _url = new UrlHelper(context);
            _ajax = new AjaxHelper(context);
            _validation = new ValidationHelper(context);
        }
        public void EndFormWritesCloseTag() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            mockViewContext.Expect(c => c.HttpContext.Response.Write("</form>")).Verifiable();

            HtmlHelper htmlHelper = new HtmlHelper(mockViewContext.Object, new Mock<IViewDataContainer>().Object, new RouteCollection());

            // Act
            htmlHelper.EndForm();

            // Assert
            mockViewContext.Verify();
        }
        internal static HtmlHelper GetHtmlHelper(string protocol, int port) {
            HttpContextBase httpcontext = GetHttpContext("/app/", null, null, protocol, port);
            RouteCollection rt = new RouteCollection();
            rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            RouteData rd = new RouteData();
            rd.Values.Add("controller", "home");
            rd.Values.Add("action", "oldaction");

            ViewDataDictionary vdd = new ViewDataDictionary();

            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            mockViewContext.Expect(c => c.HttpContext).Returns(httpcontext);
            mockViewContext.Expect(c => c.RouteData).Returns(rd);
            mockViewContext.Expect(c => c.ViewData).Returns(vdd);
            Mock<IViewDataContainer> mockVdc = new Mock<IViewDataContainer>();
            mockVdc.Expect(vdc => vdc.ViewData).Returns(vdd);

            HtmlHelper htmlHelper = new HtmlHelper(mockViewContext.Object, mockVdc.Object, rt);
            return htmlHelper;
        }
        private static void TestHttpMethodOverrideMethodException(Action<HtmlHelper> method) {
            // Arrange
            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, GetViewDataContainer(null), new RouteCollection()); ;

            // Act & Assert
            ExceptionHelper.ExpectArgumentException(
                delegate {
                    method(htmlHelper);
                },
                @"The GET and POST HTTP methods are not supported.
Parameter name: httpMethod");
        }
        private static void TestHttpMethodOverrideVerbException(Action<HtmlHelper> method) {
            // Arrange
            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, GetViewDataContainer(null), new RouteCollection()); ;

            // Act & Assert
            ExceptionHelper.ExpectArgumentException(
                delegate {
                    method(htmlHelper);
                },
                @"The specified HttpVerbs value is not supported. The supported values are Delete, Head, and Put.
Parameter name: httpVerb");
        }
        public void HttpMethodOverrideWithVerbRendersHiddenField() {
            // Arrange
            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, GetViewDataContainer(null), new RouteCollection()); ;

            // Act
            MvcHtmlString hiddenField = htmlHelper.HttpMethodOverride(HttpVerbs.Delete);

            // Assert
            Assert.AreEqual<string>(@"<input name=""X-HTTP-Method-Override"" type=""hidden"" value=""DELETE"" />", hiddenField.ToHtmlString());
        }
        public void HttpMethodOverrideWithNullThrowsException() {
            // Arrange
            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, GetViewDataContainer(null), new RouteCollection()); ;

            // Act & Assert
            ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
                delegate {
                    htmlHelper.HttpMethodOverride(null);
                },
                "httpMethod");
        }