Example #1
0
        private string createbundle(HtmlHelper html)
        {
            var server = html.ViewContext.RequestContext.HttpContext.Server;
            html.ResourceSettings(new HTMLResourceOptions() { Bundle = true, BundleTimeout = 1 });
            html.Resource("~/Content/Test.css");
            html.Resource("~/Content/themes/base/jquery.ui.dialog.css");

            var htmlstr = html.RenderResources().ToHtmlString();
            return server.MapPath("~" + Regex.Match(htmlstr, @"href=""([^\?]+)").Groups[1]);
        }
Example #2
0
        public void GetLabel_DummyLocalizedController_EnsuresTheResourceStringIsFound()
        {
            // Arrange
            var  initializer = new DummyControllerContainerInitializer();
            Type controller  = typeof(DummyLocalizedController);

            var context = new ViewContext();

            context.Controller = new DummyLocalizedController();
            var urlHelper = new HtmlHelper(context, new DummyViewDataContainer());

            using (new ObjectFactoryContainerRegion())
            {
                ObjectFactory.Container.RegisterType <ConfigManager, ConfigManager>(typeof(XmlConfigProvider).Name.ToUpperInvariant(), new InjectionConstructor(typeof(XmlConfigProvider).Name));
                ObjectFactory.Container.RegisterType <XmlConfigProvider, DummyConfigProvider>();
                Config.RegisterSection <ResourcesConfig>();
                Config.RegisterSection <ProjectConfig>();

                // Act
                initializer.RegisterControllerPublic(controller);

                var resourceString = urlHelper.Resource("DummyResource");

                // Assert
                var resourceRegistered = ObjectFactory.Container.IsRegistered(typeof(DummyLocalizationControllerResources), Res.GetResourceClassId(typeof(DummyLocalizationControllerResources)));
                Assert.IsTrue(resourceRegistered, "String resources were not registered for the controller.");
                Assert.IsFalse(resourceString.IsNullOrEmpty(), "The resource with the given key was not found");
                Assert.AreEqual("Dummy Resource", resourceString, "The returned resource is not as expected");
            }
        }
        public void GetLabel_DummyLocalizedController_EnsuresTheResourceStringIsFound()
        {
            // Arrange
            var initializer = new DummyControllerContainerInitializer();
            Type controller = typeof(DummyLocalizedController);

            var context = new ViewContext();
            context.Controller = new DummyLocalizedController();
            var urlHelper = new HtmlHelper(context, new DummyViewDataContainer());

            using (new ObjectFactoryContainerRegion())
            {
                ObjectFactory.Container.RegisterType<ConfigManager, ConfigManager>(typeof(XmlConfigProvider).Name.ToUpperInvariant(), new InjectionConstructor(typeof(XmlConfigProvider).Name));
                ObjectFactory.Container.RegisterType<XmlConfigProvider, DummyConfigProvider>();
                Config.RegisterSection<ResourcesConfig>();
                Config.RegisterSection<ProjectConfig>();

                // Act
                initializer.RegisterControllerPublic(controller);

                var resourceString = urlHelper.Resource("DummyResource");

                // Assert
                var resourceRegistered = ObjectFactory.Container.IsRegistered(typeof(DummyLocalizationControllerResources), Res.GetResourceClassId(typeof(DummyLocalizationControllerResources)));
                Assert.IsTrue(resourceRegistered, "String resources were not registered for the controller.");
                Assert.IsFalse(resourceString.IsNullOrEmpty(), "The resource with the given key was not found");
                Assert.AreEqual("Dummy Resource", resourceString, "The returned resource is not as expected");
            }
        }
Example #4
0
        public static MvcHtmlString AwesomeGrid <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, bool renderImmediately)
        {
            GridModel gridModel = InitGridModel(htmlHelper, expression);

            htmlHelper.Resource("js", gridModel.ModelName, HttpUtility.HtmlDecode(htmlHelper.Raw(htmlHelper.Partial("_GridPartial", gridModel)).ToString()), renderImmediately);

            // The grid div
            TagBuilder gridDiv = new TagBuilder("div");

            gridDiv.MergeAttribute("id", gridModel.DivName);
            return(MvcHtmlString.Create(gridDiv.ToString()));
        }
Example #5
0
        /// <summary>
        /// Show a text representation of the difference between a given date and now
        /// </summary>
        /// <param name="htmlHelper">HtmlHelper</param>
        /// <param name="date">The date to compare with the current date</param>
        /// <param name="format">Format string (default is "D")</param>
        /// <returns>Localized versions of "Today", "Yesterday", "X days ago" (for less than a week ago) or the formatted date</returns>
        public static string DateDiff(this HtmlHelper htmlHelper, DateTime?date, string format = "D")
        {
            if (date != null)
            {
                int dayDiff = (int)(DateTime.Now.Date - ((DateTime)date).Date).TotalDays;
                if (dayDiff <= 0)
                {
                    return(htmlHelper.Resource("core.todayText"));
                }
                if (dayDiff == 1)
                {
                    return(htmlHelper.Resource("core.yesterdayText"));
                }
                if (dayDiff <= 7)
                {
                    return(String.Format(htmlHelper.Resource("core.xDaysAgoText"), dayDiff));
                }

                return(((DateTime)date).ToString(format, WebRequestContext.Localization.CultureInfo));
            }
            return(null);
        }
Example #6
0
 /// <summary>
 /// Read a resource string and format it with parameters
 /// </summary>
 /// <param name="htmlHelper">HtmlHelper</param>
 /// <param name="resourceName">The resource key (eg core.readMoreText)</param>
 /// <param name="parameters">Format parameters</param>
 /// <returns>The formatted resource value, or key name if none found</returns>
 public static string FormatResource(this HtmlHelper htmlHelper, string resourceName, params object[] parameters)
 {
     return(string.Format(htmlHelper.Resource(resourceName), parameters));
 }
Example #7
0
        public static IHtmlString PermissionResource(this HtmlHelper htmlHelper, string key)
        {
            string resourceClass = "Permissions";

            return(htmlHelper.Resource(resourceClass, key));
        }
Example #8
0
        private static MvcHtmlString DropDownListCheckable <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, IEnumerable <SelectListItem> selectList, object htmlAttributes, bool multiselect, bool canBeEmpty)
        {
            string path = HttpRuntime.AppDomainAppVirtualPath;

            if (path != null && !path.EndsWith("/"))
            {
                path += "/";
            }
            htmlHelper.Resource("css", "bootstrap-multiselect.css", "<link rel='stylesheet' href='" + path + "Content/bootstrap-multiselect.css' type='text/css'/>");
            htmlHelper.Resource("js", "bootstrap-multiselect.js", "<script type='text/javascript' src='" + path + "Scripts/bootstrap-multiselect.js'></script>");

            //Model field name
            string name = ExpressionHelper.GetExpressionText(expression);

            //Get name with prefixes to link properly control in partial views
            string fullHtmlFieldName;

            if (htmlHelper.ViewContext.ViewData != null)
            {
                fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            }
            else
            {
                fullHtmlFieldName = name;
            }

            object value = null;
            var    model = htmlHelper.ViewData.Model;

            if (model != null)
            {
                value = ((LambdaExpression)expression).Compile().DynamicInvoke(model);
            }



            //<select>
            var select = new TagBuilder("select");

            select.MergeAttribute("id", name);
            select.MergeAttribute("name", fullHtmlFieldName + "[]");
            if (multiselect)
            {
                select.MergeAttribute("multiple", "multiple");
            }
            if (selectList == null)
            {
                selectList = new List <SelectListItem>();
            }

            ModelState modelState = null;

            if (htmlHelper.ViewData.ModelState.TryGetValue(fullHtmlFieldName, out modelState))
            {
                if (modelState.Errors.Count > 0)
                {
                    select.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                }
                if (modelState.Value != null)
                {
                    value = modelState.Value.ConvertTo(typeof(string[]), (CultureInfo)null);
                }
            }

            //Model field value (used to know the current item)
            string[] fieldsValue = { "" };
            if (value != null)
            {
                if (value.GetType().IsArray)
                {
                    object[] values = (object[])value;
                    fieldsValue = values.Select(x => x.ToString()).ToArray();
                }
                else
                {
                    fieldsValue = new[] { value.ToString() };
                }
            }

            //Default empty value
            if (canBeEmpty && !multiselect)
            {
                var option = new TagBuilder("option");
                option.MergeAttribute("value", "");
                option.InnerHtml  = Localization.LocResources.NoElementsSelected;
                select.InnerHtml += option.ToString();
            }

            //<option>
            foreach (var selectListItem in selectList)
            {
                var option = new TagBuilder("option");
                option.MergeAttribute("value", selectListItem.Value);
                option.InnerHtml = selectListItem.Text;
                if (fieldsValue.Contains(selectListItem.Value) || fieldsValue.Contains(selectListItem.Text))
                {
                    option.MergeAttribute("selected", "selected");
                }
                select.InnerHtml += option.ToString();
            }


            //multiSelect attributes and class
            String attributes = "";
            IDictionary <string, object> htmlAttributesDictionnary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            List <string> reservedAttributes = new List <string>()
            {
                "class", "onChange", "disableIfEmpty", "disabled", "tabindex"
            };

            foreach (var htmlAttribute in htmlAttributesDictionnary)
            {
                if (!reservedAttributes.Contains(htmlAttribute.Key))
                {
                    attributes += htmlAttribute.Key + "=\"" + htmlAttribute.Value + "\" ";
                }
            }
            string tabIndex = htmlAttributesDictionnary["tabindex"] != null ? htmlAttributesDictionnary["tabindex"].ToString() : "";

            if (!string.IsNullOrEmpty(tabIndex))
            {
                select.MergeAttribute("tabindex", tabIndex);
            }

            string htmlclass  = htmlAttributesDictionnary["class"] != null ? htmlAttributesDictionnary["class"].ToString() : "";
            bool   isDisabled = htmlAttributesDictionnary["disabled"] != null && (htmlAttributesDictionnary["disabled"].ToString().ToLower() == "true" || htmlAttributesDictionnary["disabled"].ToString().ToLower() == "disabled");
            string disable    = isDisabled ? "$('#" + name + "').multiselect('disable');" : "";

            //TODO: refactor to be params of this method (not html classes)
            string onChangeHandler       = htmlAttributesDictionnary["onChange"] != null ? htmlAttributesDictionnary["onChange"].ToString() + "(option, checked);" : "";
            string disableIfEmptyHandler = htmlAttributesDictionnary["disableIfEmpty"] != null ? htmlAttributesDictionnary["disableIfEmpty"].ToString() : "true";

            //Plugin that load bootstrap-multiselect with options
            string plugin = "<script type='text/javascript'>";

            plugin += "$(document).ready(function() {";
            plugin += "$('#" + name + "').multiselect({";
            plugin += "templates: {button: '<button type=\"button\" class=\"multiselect dropdown-toggle\" style=\"overflow: hidden; text-overflow: ellipsis;white-space: nowrap;\" data-toggle=\"dropdown\"></button>'},";
            plugin += "maxHeight: 200,";
            plugin += "dropRight: true,";
            plugin += "enableCaseInsensitiveFiltering: true,";
            plugin += "includeSelectAllOption: true,";
            plugin += "selectAllText: '" + Localization.LocResources.SelectAll + "',";
            plugin += "nonSelectedText: '" + Localization.LocResources.NoElementsSelected + "',";
            plugin += "nSelectedText: '" + Localization.LocResources.NumberElementsSelected + "',";
            plugin += "allSelectedText: '" + Localization.LocResources.AllElementsSelected + "',";
            plugin += "onChange: function(option, checked) { ";
            plugin += onChangeHandler;
            plugin += "},";
            //              Corrected in bootstrap multiselect (pull request)
            //plugin +=                   "rebuild: function(){";
            //plugin +=                       "var that = $('#" + name + "'); ";
            //plugin +=                       "if (that.length > 0) ";
            //plugin +=                           "that.multiselect('enable');";
            //plugin +=                       "else ";
            //plugin +=                           "that.multiselect('disable');";
            //plugin +=                   "},";
            plugin += "disableIfEmpty: " + disableIfEmptyHandler + ",";
            plugin += "buttonClass: '" + htmlclass + " " + attributes + "'";
            plugin += "});";
            plugin += disable;
            plugin += "});";
            plugin += "</script>";
            htmlHelper.Resource("js", name, plugin);

            return(MvcHtmlString.Create(select.ToString()));
        }