public static MvcHtmlString Sidebar(this HtmlHelper htmlHelper, UrlHelper urlHelper, IEnumerable<Category> categories, int departmentId, int viewedCategoryId = -1)
        {
            var builder = new StringBuilder();

            builder.Append("<aside class=\"pro-left\">\n<aside class=\"gray-smll\">\n<h1>Shop By Category</h1><ul>");

            foreach (var category in categories)
            {
                builder.AppendFormat(
                    "<li><a href=\"{0}\"{1}>{2}</a></li>",
                    urlHelper.Action("Index", "Department", new { DepartmentId = departmentId, CategoryId = category.Id }),
                    category.Id == viewedCategoryId ? " class=\"current\"" : "",
                    category.Name
                );
            }

            builder.Append("</ul></aside>");

            builder.AppendFormat(
                "<img src=\"{0}\" class=\"left clear\" />",
                urlHelper.Content("~/Content/images/bg-gray-smll-bot.jpg")
            );
            builder.AppendFormat(
                "<img src=\"{0}\" class=\"left clear\" />",
                urlHelper.Content("~/Content/images/img-left-smll.jpg")
            );

            builder.Append("</aside>");

            return new MvcHtmlString(builder.ToString());
        }
Ejemplo n.º 2
0
        public static string PageExpander(this HtmlHelper htmlHelper, Node node, Node activeNode)
        {
            UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            if (node.ChildNodes.Count > 0)
            {
                TagBuilder expanderImage = new TagBuilder("img");

                if (node.Level < 1 || (node.IsInPath(activeNode)))
                {
                    expanderImage.AddCssClass("children-visible");
                    expanderImage.Attributes.Add("src", urlHelper.Content("~/manager/Content/Images/collapse.png"));
                }
                else
                {
                    expanderImage.AddCssClass("children-hidden");
                    expanderImage.Attributes.Add("src", urlHelper.Content("~/manager/Content/Images/expand.png"));
                }
                expanderImage.Attributes.Add("alt", "toggle");
                return expanderImage.ToString();
            }
            else
            {
                TagBuilder expanderSpan = new TagBuilder("span");
                string className = "no-children";
                expanderSpan.AddCssClass(className);
                return expanderSpan.ToString();
            }
        }
        private static MvcHtmlString ReferenceBundle(HtmlHelper helper, string bundlePath, TagBuilder baseTag, string key)
        {
            var bundle = BundleTable.Bundles.GetBundleFor(bundlePath);
            if (bundle == null)
                throw new ArgumentException("Invalid Bundle Path", "bundlePath");

            var httpContext = helper.ViewContext.HttpContext;
            if (!BundleConfigurationManager.Ignore(httpContext))
            {
                baseTag.MergeAttribute(key, BundleTable.Bundles.ResolveBundleUrl(bundlePath));
                return new MvcHtmlString(baseTag.ToString());
            }

            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var bundleContext = new BundleContext(helper.ViewContext.HttpContext, BundleTable.Bundles, urlHelper.Content(bundlePath));
            var htmlString = new StringBuilder();

            foreach (var file in bundle.EnumerateFiles(bundleContext))
            {
                var basePath = httpContext.Server.MapPath("~/");
                if (!file.FullName.StartsWith(basePath))
                    continue;

                var relPath = urlHelper.Content("~/" + file.FullName.Substring(basePath.Length));
                baseTag.MergeAttribute(key, relPath, true);
                htmlString.AppendLine(baseTag.ToString());
            }

            return new MvcHtmlString(htmlString.ToString());
        }
Ejemplo n.º 4
0
 public static MvcHtmlString EmployeeImageRight(this HtmlHelper helper, Employee item)
 {
     var url = new UrlHelper(helper.ViewContext.RequestContext);
     var path = HttpContext.Current.Server.MapPath("~/public/userfiles/employees/" + item.Id + ".jpg");
     if (File.Exists(path))
     {
         return MvcHtmlString.Create(
             string.Format("<a href='{3}' class='employee-photo top-photo'><img title='{1}'  src='{2}' /></a>",
                 url.Content("~/public/images/pix.gif"),
                 item.FullName,
                 url.Content("~/public/userfiles/employees/" + item.Id + ".jpg"),
                 url.Action("Card", "Employees", new { item.Id })
             )
         );
     }
     else
     {
         return MvcHtmlString.Create(
       string.Format("<a href='{3}' class='employee-photo'><img title='{1}' style='background-size: 100%;background-image: url({2})' src='{0}' /></a>",
           url.Content("~/public/images/pix.gif"),
           item.FullName,
           url.Content("~/public/images/picture_bg.jpg"),
           url.Action("Card", "Employees", new { item.Id })
       )
   );
     }
 }
Ejemplo n.º 5
0
        public static List<Menu> GetMenu(RequestContext _context)
        {
            UrlHelper Url = new UrlHelper(_context);
            List<Menu> menus = new List<Menu>();
            Menu m1 = new Menu("a10", null, "首页", "menu-icon fa fa-home", Url.Content("~/Home/Index"));
            Menu m2 = new Menu("a11", null, "人员列表", "menu-icon fa fa-list", Url.Content("~/Human/List"));

            Menu m4 = new Menu("a15", null, "人员信息统计", "menu-icon fa fa-bar-chart-o", "#");
            m4.AddChild("a1501", "按年龄段统计", string.Empty, Url.Action("NianLing", "TongJi"));
            m4.AddChild("a1502", "按学历统计", string.Empty, Url.Action("XueLi", "TongJi"));
            m4.AddChild("a1503", "按政治面貌统计", string.Empty, Url.Action("ZhengZhi", "TongJi"));
            m4.AddChild("a1504", "按入职时间统计", string.Empty, Url.Action("RuZhi", "TongJi"));
            m4.AddChild("a1505", "按岗位统计", string.Empty, Url.Action("GangWei", "TongJi"));
            m4.AddChild("a1506", "按职称统计", string.Empty, Url.Action("ZhiCheng", "TongJi"));
            Menu m3 = new Menu("a12", null, "系统设置", "menu-icon fa fa-pencil-square-o", "#");

            m3.AddChild("a13", "数据字典栏目", string.Empty, Url.Action("Index", "DicLan"));
            m3.AddChild("a14", "数据字典", string.Empty, Url.Action("Index", "DicLan"));

            menus.Add(m1);
            menus.Add(m2);
            menus.Add(m4);
            menus.Add(m3);

            return menus;
        }
Ejemplo n.º 6
0
        public static MvcHtmlString UnitImage(this HtmlHelper helper, String controller, String action, Object parameters, String src, String alt = "", String title = "")
        {
            var tagBuilder = new TagBuilder("img");
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var url = urlHelper.Action(action, controller, parameters);
            var imgUrl = urlHelper.Content(src);
            var image = "";
            var html = new StringBuilder();

            // build the image tag.
            tagBuilder.MergeAttribute("src", imgUrl);
            tagBuilder.MergeAttribute("alt", alt);
            //tagBuilder.MergeAttribute("width", "100");
            //tagBuilder.MergeAttribute("height", "100");
            tagBuilder.MergeAttribute("title", title);
            image = tagBuilder.ToString(TagRenderMode.SelfClosing);

            html.Append("<a href=\"");
            html.Append(urlHelper.Content(src));
            html.Append("\">");
            html.Append(image);
            html.Append("</a>");

            return MvcHtmlString.Create(html.ToString());
        }
Ejemplo n.º 7
0
        public static MvcHtmlString Menu(this HtmlHelper helper, bool isMobile = false)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var sb = new StringBuilder();

            if (isMobile)
            {
                sb.Append("<select onchange='location.href=this.value;'>");
                sb.Append("<option value=''></option>");
                sb.AppendFormat("<option {0} value='{1}'>{2}</option>",
                    IsCurrentPage(urlHelper.Content("~/"), HttpContext.Current.Request) ? "selected='selected'" : "",
                    urlHelper.Content("~/"), "Dashboard");
            }
            else
                sb.Append("<ul id='menu'>");
            var siteMap = new FileInfo(HttpContext.Current.Server.MapPath("~/web.sitemap"));
            if (siteMap.Exists)
            {
                var smXDoc = new XmlDocument();
                smXDoc.Load(siteMap.FullName);
                _xmlnsManager = new XmlNamespaceManager(smXDoc.NameTable);
                _xmlnsManager.AddNamespace("mi", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");

                var nodes = smXDoc.SelectNodes("/mi:siteMap/mi:siteMapNode/mi:siteMapNode", _xmlnsManager);
                WriteNodes(sb, nodes, urlHelper, isMobile);
            }
            if (isMobile)
                sb.Append("</select>");
            else
                sb.Append("</ul>");


            return new MvcHtmlString(sb.ToString());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns a string containing Javascript 'constants' for the site.
        /// </summary>
        public ActionResult GlobalJsVars()
        {
            UrlHelper helper = new UrlHelper(HttpContext.Request.RequestContext);

            StringBuilder builder = new StringBuilder();
            builder.AppendLine(string.Format("var SPRUCE_SCRIPTPATH = '{0}';", helper.Content("~/Assets/Scripts/")));
            builder.AppendLine(string.Format("var SPRUCE_CSSPATH = '{0}';", helper.Content("~/Assets/Css/")));
            builder.AppendLine(string.Format("var SPRUCE_IMAGEPATH = '{0}';", helper.Content("~/Assets/Images/")));

            return Content(builder.ToString(), "text/javascript");
        }
		public static MvcHtmlString EmplloyeePhoto(this HtmlHelper helper, EmployeePhoto photo) {
			if (photo == null)
				return MvcHtmlString.Empty;

			var url = new UrlHelper(helper.ViewContext.RequestContext);

			return MvcHtmlString.Create(string.Format("<a rel='gallery' class='employeephoto-photo' href='{0}'><img src='{1}'/></a>",
				url.Content("~/public/UserFiles/employeephotos/big/" + photo.FileName),
				url.Content("~/public/UserFiles/employeephotos/small/" + photo.FileName)
			));
		}
Ejemplo n.º 10
0
        private static string GetSocialImage(this HtmlHelper htmlHelper, SocialFeature feature)
        {
            var img = new TagBuilder("img");

            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            img.MergeAttribute("class", "pop rollover");
            img.MergeAttribute("src", urlHelper.Content(string.Format("~/Content/Images/social_icons/{0}.png", feature.FeatureImagePart)));
            img.MergeAttribute("data-rollover", urlHelper.Content(string.Format("~/Content/Images/social_icons/{0}-hover.png", feature.FeatureImagePart)));
            img.MergeAttribute("alt", feature.FeatureImagePart);

            return MvcHtmlString.Create(img.ToString()).ToHtmlString();
        }
Ejemplo n.º 11
0
 public static string ImageUrlFor(this HtmlHelper helper, string contentUrl)
 {
     // Put some caching logic here if you want it to perform better
     UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
     if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
     {
         return urlHelper.Content("~/Content/images/none.jpg");
     }
     else
     {
         return urlHelper.Content(contentUrl);
     }
 }
Ejemplo n.º 12
0
 public static IHtmlString CssBuilder(this HtmlHelper htmlHelper, UrlHelper url, string value, bool removeProtocol = true)
 {
     TagBuilder builder = new TagBuilder("link");
     if (GlobalConfig.IsAssetsEnabled)
     {
         string protocol = "^http[s]*:";
         builder.Attributes.Add("href", url.Content(String.Format("{0}/content/{1}", removeProtocol ? Regex.Replace(GlobalConfig.AssetsBaseUrl, protocol, String.Empty) : GlobalConfig.AssetsBaseUrl, value)));
     }
     else
         builder.Attributes.Add("href", url.Content("~/Content/" + value));
     builder.Attributes.Add("rel", "stylesheet");
     builder.Attributes.Add("type", "text/css");
     return htmlHelper.Raw(builder.ToString(TagRenderMode.SelfClosing));
 }
Ejemplo n.º 13
0
        public static MvcHtmlString Script(this HtmlHelper helper, string scriptFilename)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            TagBuilder builder = new TagBuilder("script");

            if (Path.GetExtension(scriptFilename) == ".js") {
                builder.Attributes.Add("src", urlHelper.Content("~/Scripts/" + scriptFilename));
            } else {
                builder.Attributes.Add("src", urlHelper.Content("~/Scripts/" + scriptFilename + ".js"));
            }

            return MvcHtmlString.Create( builder.ToString() );
        }
Ejemplo n.º 14
0
 public static IHtmlString JsBuilder(this HtmlHelper htmlHelper, UrlHelper url, string value, bool removeProtocol = true)
 {
     TagBuilder builder = new TagBuilder("script");
     //builder.Attributes.Add("src", url.Content("~/Scripts/" + value));
     if (GlobalConfig.IsAssetsEnabled)
     {
         string protocol = "^http[s]*:";
         builder.Attributes.Add("src", url.Content(String.Format("{0}/scripts/{1}", removeProtocol ? Regex.Replace(GlobalConfig.AssetsBaseUrl, protocol, String.Empty) : GlobalConfig.AssetsBaseUrl, value)));
     }
     else
         builder.Attributes.Add("src", url.Content("~/Scripts/" + value));
     builder.Attributes.Add("type", "text/javascript");
     builder.Attributes.Add("language", "JavaScript");
     return htmlHelper.Raw(builder.ToString());
 }
        protected void Application_Error(object sender, EventArgs eventArgs)
        {
            // ----------------------------------------------------------------------------
            // If ELMAH was not being used, you could instead use this event handler to log
            // but not handle exceptions that get thrown by the site.
            // ----------------------------------------------------------------------------

            var exception = Server.GetLastError();
            exception = exception == null ? exception : exception.GetBaseException();
            var httpException = exception as HttpException;

            if (httpException == null || httpException.GetHttpCode() != 404)
            {
                // Now log the exception in some way.
            }

            // ----------------------------------------------------------------------------
            // The following code shows how fallback to a static HTML error page
            // if the MVC error page throws an exception.
            // ----------------------------------------------------------------------------

            var appRelativePath = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;

            if (appRelativePath.StartsWith("~/" + ErrorControllerName + "/", StringComparison.OrdinalIgnoreCase))
            {
                Response.ClearHeaders();
                Response.ClearContent();
                Response.TrySkipIisCustomErrors = true;
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                Server.ClearError();
                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                Server.Transfer(urlHelper.Content("~/" + FatalErrorFileName));
            }
        }
Ejemplo n.º 16
0
        // Extension method
        public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, string imagePath, string alt, string anchorCssClass, string imgCssClass, object routeAttributes)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            if(imgCssClass != null)
                imgBuilder.AddCssClass(imgCssClass);
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            if (routeAttributes == null)
                anchorBuilder.MergeAttribute("href", url.Action(action, controllerName));
            else
                anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeAttributes));

            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            if(anchorCssClass != null)
                anchorBuilder.AddCssClass(anchorCssClass);
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }
Ejemplo n.º 17
0
        public Rss20FeedFormatter Feed(string absoluteUri, UrlHelper url)
        {
            if (url == null) { throw new ArgumentNullException("url"); }

            var cssUri = new UriBuilder(absoluteUri)
            {
                // ReSharper disable Html.PathError - the bundler takes care of creating this path for us
                Path = url.Content("~/bundles/css")
                // ReSharper restore Html.PathError
            }.Uri;

            var items = _db.Posts
                        .OrderByDescending(p => p.PostDate)
                        .Take(20).ToList().Select(post => new SyndicationItem(
                        String.Format("{0} - {1} - {2}",
                            post.ForumAccount.Name,
                            post.Thread.Title,
                            post.Id),
                        String.Format("<link href='{0}' rel='stylesheet' /><br />{1}", cssUri, HttpUtility.HtmlDecode(post.Content)),
                        new UriBuilder(absoluteUri)
                        {
                            Path = url.Action("Details", "Posts", new { id = post.Id })
                        }.Uri))
                    .ToList();

            var feed = new SyndicationFeed("Nishkriya - Latest Posts", "An Exalted developer / writer tracker", new Uri(absoluteUri), items)
            {
                Language = "en-US",
                LastUpdatedTime = items.Max(i => i.PublishDate)
            };

            return new Rss20FeedFormatter(feed);
        }
Ejemplo n.º 18
0
        public static MvcHtmlString Skype(this HtmlHelper helper, UrlHelper url)
        {
            return
                new MvcHtmlString(@"<a href='skype:tc.zasz?call'><img src='" +
                    url.Content("~/Content/Images/skype.png") +
@"' style='border: none;' title='To avoid spam, this is an image. You cannot select or copy.' alt='Skype T Chandirasekar'/></a>");
        }
Ejemplo n.º 19
0
        public static string Generate(RequestContext requestContext, NavigationRequest navigationItem, RouteValueDictionary routeValues)
        {
            if (requestContext == null)
                throw new ArgumentNullException("requestContext");
            if (navigationItem == null)
                throw new ArgumentNullException("navigationItem");

            var urlHelper = new UrlHelper(requestContext);
            string generatedUrl = null;

            if (!string.IsNullOrEmpty(navigationItem.RouteName))
            {
                generatedUrl = urlHelper.RouteUrl(navigationItem.RouteName, routeValues);
            }
            else if (!string.IsNullOrEmpty(navigationItem.ControllerName) && !string.IsNullOrEmpty(navigationItem.ActionName))
            {
                generatedUrl = urlHelper.Action(navigationItem.ActionName, navigationItem.ControllerName, routeValues, null, null);
            }
            else if (!string.IsNullOrEmpty(navigationItem.Url))
            {
                generatedUrl = navigationItem.Url.StartsWith("~/", StringComparison.Ordinal) 
                    ? urlHelper.Content(navigationItem.Url) 
                    : navigationItem.Url;
            }
            else if (routeValues.Any())
            {
                generatedUrl = urlHelper.RouteUrl(routeValues);
            }

            return generatedUrl;

        }
 private static string PrintTag(this HtmlHelper helper, string file, Func<string, string> printTagFunction)
 {
     var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
     var fileName = urlHelper.Content(file);
     var tag = printTagFunction(fileName);
     return tag;
 }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (!actionContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (actionContext.HttpContext.Request.IsAjaxRequest())
                {
                    UrlHelper u = new UrlHelper(actionContext.RequestContext);
                    actionContext.Result = new JsonResult
                    {
                        Data = new AjaxForbiddenModel
                            {
                                Redirect = u.Content(FormsAuthentication.LoginUrl)
                            },
                        ContentEncoding = System.Text.Encoding.UTF8,
                        ContentType = "application/json",
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                    return;
                }

                actionContext.Result = new HttpUnauthorizedResult();
                return;
            }

            if (_roles == null)
                return;

            string role = _roles.Where(r => actionContext.HttpContext.User.IsInRole(r)).FirstOrDefault();

            if (role == null)
            {
                String error = String.Format(CultureInfo.InvariantCulture, "User {0} requested page {1}", ((Identity)actionContext.HttpContext.User.Identity).Email, actionContext.HttpContext.Request.Path);
                throw new HttpException((int) HttpStatusCode.Forbidden, error);
            }
        }
Ejemplo n.º 22
0
        public static MvcHtmlString Stylesheet(this HtmlHelper helper, string cssFilename)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            TagBuilder builder = new TagBuilder("link");

            if (Path.GetExtension(cssFilename) == ".css")
                builder.Attributes.Add("href", urlHelper.Content("~/Content/" + cssFilename));
            else
                builder.Attributes.Add("href", urlHelper.Content("~/Content/" + cssFilename + ".css"));

            builder.Attributes.Add("rel", "stylesheet");
            builder.Attributes.Add("type", "text/css");

            return MvcHtmlString.Create(builder.ToString());
        }
Ejemplo n.º 23
0
        public string GenerateContentUrl(string relativePath)
        {
            var httpRequest = GetCurrentRequest();
            var urlHelper = new UrlHelper(httpRequest.RequestContext, RouteTable.Routes);

            return urlHelper.Content(relativePath);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            HttpSessionStateBase session = filterContext.HttpContext.Session;

            Services.User user = (Services.User)session[Constants.SESSION_USER];
            if (user != null) {
                return;
            }

            String urlFrom = String.Empty;
            UrlHelper url;

            //send them off to the login page
            url = new UrlHelper(filterContext.RequestContext);
            urlFrom = filterContext.Controller.ControllerContext.RequestContext.HttpContext.Request.RawUrl;
            if (!String.IsNullOrEmpty(urlFrom)) {
                urlFrom = String.Format("?{0}", urlFrom);
            }
            var loginUrl = url.Content(String.Format("~/LogIn{0}", urlFrom));
            session.RemoveAll();
            session.Clear();
            session.Abandon();

            filterContext.HttpContext.Response.StatusCode = 403;
            filterContext.HttpContext.Response.Redirect(loginUrl, false);
            filterContext.Result = new EmptyResult();
        }
Ejemplo n.º 25
0
        public static MvcHtmlString ActionImage(this HtmlHelper html, ActionResult action, Image image, int size = 100, string genericPath = null)
        {
            string path;
            string alt;
            if (image != null)
            {
                path = image.Url;
                alt = image.AltText;
            }
            else
            {
                path = genericPath;
                alt = string.Empty;
            }

            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(path));
            imgBuilder.MergeAttribute("alt", alt);
            imgBuilder.MergeAttribute("height", size.ToString());
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// The action image.
        /// </summary>
        /// <param name="html">
        /// The html.
        /// </param>
        /// <param name="action">
        /// The action.
        /// </param>
        /// <param name="controller">
        /// The controller.
        /// </param>
        /// <param name="routeValues">
        /// The route values.
        /// </param>
        /// <param name="imagePath">
        /// The image path.
        /// </param>
        /// <param name="alt">
        /// The alt.
        /// </param>
        /// <param name="confirmation">
        /// The confirmation.
        /// </param>
        /// <returns>
        /// The <see cref="MvcHtmlString"/>.
        /// </returns>
        public static MvcHtmlString ActionImage(
            this HtmlHelper html, 
            string action, 
            string controller, 
            object routeValues, 
            string imagePath, 
            string alt, 
            bool confirmation)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            string onclick = "return confirm('Are you sure that you want to perform delete operaion ?')";
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            if (confirmation)
            {
                imgBuilder.MergeAttribute("onclick", onclick);
            }

            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
            return MvcHtmlString.Create(anchorHtml);
        }
Ejemplo n.º 27
0
        public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
        {
            // Instantiate a UrlHelper
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            // Create tag builder
            var builder = new TagBuilder("img");

            if (!string.IsNullOrEmpty(id))
            {
                builder.GenerateId(id);
            }

            // Add attributes
            builder.MergeAttribute("src", urlHelper.Content(url));

            if (!string.IsNullOrEmpty(alternateText))
            {
                builder.MergeAttribute("alt", alternateText);
                builder.MergeAttribute("title", alternateText);
            }

            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            // Render tag
            return builder.ToString(TagRenderMode.SelfClosing);
        }
Ejemplo n.º 28
0
        public string Generate(RequestContext requestContext, INavigatable navigationItem, RouteValueDictionary routeValues)
        {
            Guard.IsNotNull(requestContext, "requestContext");
            Guard.IsNotNull(navigationItem, "navigationItem");

            UrlHelper urlHelper = new UrlHelper(requestContext);
            string generatedUrl = null;

            if (!string.IsNullOrEmpty(navigationItem.RouteName))
            {
                generatedUrl = urlHelper.RouteUrl(navigationItem.RouteName, routeValues);
            }
            else if (!string.IsNullOrEmpty(navigationItem.ControllerName) && !string.IsNullOrEmpty(navigationItem.ActionName))
            {
                generatedUrl = urlHelper.Action(navigationItem.ActionName, navigationItem.ControllerName, routeValues, null, null);
            }
            else if (!string.IsNullOrEmpty(navigationItem.Url))
            {
                generatedUrl = navigationItem.Url.StartsWith("~/", StringComparison.Ordinal) ?
                               urlHelper.Content(navigationItem.Url) :
                               navigationItem.Url;
            }
            else if (routeValues.Any())
            {
                generatedUrl = urlHelper.RouteUrl(routeValues);
            }

            return generatedUrl;
        }
Ejemplo n.º 29
0
        public static string Minify(System.Web.Mvc.UrlHelper urlHelper, string cssPath, string requestPath, string cssContent)
        {
            // this construct is to enable us to refer to the relativePath above ...
            MatchEvaluator urlDelegate = new MatchEvaluator(delegate(Match m)
            {
                // Change relative (to the original CSS) URL references to make them relative to the requested URL (controller / action)
                string url = m.Value;

                Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

                if (uri.IsAbsoluteUri || VirtualPathUtility.IsAbsolute(url))
                {
                    // if the URL is absolute ("http://server/path/file.ext") or app absolute ("/path/file.ext") then leave it as it is
                }
                else
                {
                    // get app relative url
                    url = VirtualPathUtility.Combine(cssPath, url);
                    url = VirtualPathUtility.MakeRelative(requestPath, url);


                    url = urlHelper.Content(url);
                }

                return(url);
            });

            return(Minify(urlHelper, urlDelegate, cssContent, 0));
        }
Ejemplo n.º 30
0
        public static MvcHtmlString ImageDataForCart(this HtmlHelper helper, int clothesId,string clothesName)
        {
            TagBuilder imageData = null; //To Build the Image Tag
            var imgUrl = new UrlHelper(helper.ViewContext.RequestContext);

            UCEntities uCEntities = new UCEntities();
            int? imageId = uCEntities.Pictures.FirstOrDefault(x => x.ClothesId == clothesId).PictureId;

               // if (imageId!=0)
               //{
            byte[] imageArray = uCEntities.Pictures.Where(x => x.PictureId == imageId).FirstOrDefault().Image;
            //Convert to Image
            TypeConverter bmpConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
            Bitmap imageReceived = (Bitmap)bmpConverter.ConvertFrom(imageArray);

            //Now Generate the Image Tag for Mvc Html String
            imageReceived.Save(HostingEnvironment.MapPath("~/Images") + @"\I" + imageId.ToString() + ".jpg");
              //}
            imageData = new TagBuilder("img");
            //Set the Image Url for <img> tag as <img src="">
            imageData.MergeAttribute("src", imgUrl.Content("~/Images") + @"/I" + imageId.ToString() + ".jpg");
            imageData.Attributes.Add("alt", clothesName);
            //imageData.Attributes.Add("style", "opacity:1;");

            return MvcHtmlString.Create(imageData.ToString(TagRenderMode.SelfClosing));
        }
Ejemplo n.º 31
0
        internal string GetContentFromHttpContext(HttpContextBase httpContext, ControllerContext controllerContext)
        {
            var urlHelper = new UrlHelper(controllerContext.RequestContext);

            StringBuilder sb = new StringBuilder();
            foreach (var ses in (from s in MothScriptHelper.Stylesheets.SelectMany(i => i.Items)
                                 group s by s.Category into g
                                 select g.Select(x => x.Filename)))
            {
                var stylesheets = ses.ToList();

                var key = "scripthelper.rendercss." + string.Join("|", stylesheets.ToArray());

                sb.AppendLine(Provider.GetFromCache(key, () =>
                {
                    // hashcode bepalen
                    StringBuilder stylo = MothScriptHelper.GetFileContent(stylesheets, httpContext);

                    var outputFile = Encoding.UTF8.GetBytes(stylo.ToString());
                    var hashcode = HashingInstance.Hash(outputFile);

                    string url = urlHelper.Content("~/resources/css/");
                    return string.Format("<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"{2}?keys={0}&amp;{1}\" />", string.Join("|", stylesheets.ToArray()), hashcode, url);
                }, Provider.CacheDurations.ExternalScript));
            }

            return sb.ToString();
        }
Ejemplo n.º 32
0
        public static string GetObjectColorImageUrl(ObjectColor color)
        {
            var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            if (color == ObjectColor.Red)
            {
                return(url.Content("~/Content/Icons/Circle-Red.png"));
            }

            if (color == ObjectColor.Yellow)
            {
                return(url.Content("~/Content/Icons/Circle-Yellow.png"));
            }

            if (color == ObjectColor.Green)
            {
                return(url.Content("~/Content/Icons/Circle-Green.png"));
            }

            return(url.Content("~/Content/Icons/Circle-Gray.png"));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// If specific route can be found, return that route with the parameter tokens in route string.
        /// </summary>
        public static string JavaScriptReplaceableUrl(this UrlHelper urlHelper, ActionResult result)
        {
            var    rvd  = result.GetRouteValueDictionary();
            string area = string.Empty;
            object token;

            if (rvd.TryGetValue("area", out token))
            {
                area = token.ToString();
            }

            if (!rvd.TryGetValue("controller", out token))
            {
                throw new Exception("T4MVC JavascriptReplacableUrl could not locate controller in source dictionary");
            }
            string controller = token.ToString();

            if (!rvd.TryGetValue("SecureAction", out token))
            {
                throw new Exception("T4MVC JavascriptReplacableUrl could not locate SecureAction in source dictionary");
            }
            string SecureAction = token.ToString();

            // This matches the ActionResult to a specific route (so we can get the exact URL)
            string specificSecureActionUrl = RouteTable.Routes.OfType <Route>()
                                             .Where(r => r.DataTokens.CompareValue("area", area) &&
                                                    r.Defaults.CompareValue("controller", controller) &&
                                                    r.Defaults.CompareValue("SecureAction", SecureAction))
                                             .Select(r => r.Url)
                                             .FirstOrDefault();

            if (String.IsNullOrEmpty(specificSecureActionUrl))
            {
                return(urlHelper.RouteUrl(null, result.GetRouteValueDictionary()));
            }

            return(urlHelper.Content("~/" + specificSecureActionUrl));
        }
Ejemplo n.º 34
0
 public static string Website1(this UrlHelper helper, string url)
 {
     url = cssUrl + url;
     // return value;
     return(helper.Content(url));
 }
Ejemplo n.º 35
0
        /// <summary>
        /// ResizeImage图片地址生成
        /// </summary>
        /// <param name="url">图片地址</param>
        /// <param name="w">最大宽度</param>
        /// <param name="h">最大高度</param>
        /// <param name="quality">质量0~100</param>
        /// <param name="image">占位图类别</param>
        /// <returns>地址为空返回null</returns>
        public static string ResizeImage(string url, int?w = null, int?h = null,
                                         int?quality       = null,
                                         DummyImage?image  = DummyImage.Default,
                                         ResizerMode?mode  = null,
                                         ReszieScale?scale = null
                                         )
        {
            var Url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            else
            {
                if (Url.IsLocalUrl(url))
                {
                    var t = new Uri(HttpContext.Current.Request.Url, Url.Content(url)).AbsoluteUri;
                    Dictionary <string, string> p = new Dictionary <string, string>();
                    if (w.HasValue)
                    {
                        p.Add("w", w.ToString());
                    }
                    if (h.HasValue)
                    {
                        p.Add("h", h.ToString());
                    }
                    if (scale.HasValue)
                    {
                        p.Add("scale", scale.Value.ToString());
                    }
                    if (quality.HasValue)
                    {
                        p.Add("quality", quality.ToString());
                    }
                    if (image.HasValue)
                    {
                        p.Add("404", image.ToString());
                    }
                    if (mode.HasValue)
                    {
                        p.Add("mode", mode.ToString());
                    }
                    return(t + p.ToParam("?"));
                }
                else if (url.Contains(QinQiuApi.ServerLink))
                {
                    var fileType = System.IO.Path.GetExtension(url);

                    StringBuilder sbUrl = new StringBuilder(url);
                    if (fileType == ".mp4")
                    {
                        sbUrl.Append("?vframe/jpg/offset/1");
                        if (w.HasValue)
                        {
                            sbUrl.Append($"/w/{w}");
                        }
                        if (h.HasValue)
                        {
                            sbUrl.Append($"/h/{h}");
                        }
                        return(sbUrl.ToString());
                    }
                    else
                    {
                        sbUrl.Append("?imageView2");
                        switch (mode)
                        {
                        case ResizerMode.Pad:
                        default:
                        case ResizerMode.Crop:
                            sbUrl.Append("/1");
                            break;

                        case ResizerMode.Max:
                            sbUrl.Append("/0");
                            break;
                        }
                        if (w.HasValue)
                        {
                            sbUrl.Append($"/w/{w}");
                        }
                        if (h.HasValue)
                        {
                            sbUrl.Append($"/h/{h}");
                        }
                        quality = quality ?? 100;
                        sbUrl.Append($"/q/{quality}");
                        return(sbUrl.ToString());
                    }
                }
                else
                {
                    return(url);
                }
            }
        }
Ejemplo n.º 36
0
 public static string Website(this UrlHelper helper, string url)
 {
     url = "https://ouikumstorage.blob.core.windows.net/upload/Content/Website/" + url;
     // return value;
     return(helper.Content(url));
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Renders the page tag link.
        /// </summary>
        /// <param name="helper">The helper.</param>
        /// <param name="newsItem">The news item.</param>
        /// <param name="urlHelper">The URL helper.</param>
        /// <returns>Current page tag's link</returns>
        public static IHtmlString RenderPageTagLink(this HtmlHelper helper, NewsItem newsItem, System.Web.Mvc.UrlHelper urlHelper)
        {
            var tagId = ((Telerik.OpenAccess.TrackedList <System.Guid>)newsItem.GetValue("Tags")).First();

            var taxonomyManager = TaxonomyManager.GetManager();
            var tag             = taxonomyManager.GetTaxa <FlatTaxon>().Where(t => t.Id == tagId).Single();

            var pageManager = PageManager.GetManager();
            var pageNode    = pageManager.GetPageNodes().Where(node => node.Title.Contains(tag.Name) && node.RootNodeId == SiteInitializer.CurrentFrontendRootNodeId).FirstOrDefault();

            return(pageNode == null ? null : new HtmlString(string.Format("<a href=\"{0}\">{1}</a>", urlHelper.Content(pageNode.GetFullUrl()), tag.Title)));
        }
Ejemplo n.º 38
0
 public static string CdnContentUrl(this UrlHelper url, string contentPath)
 {
     return(url.Content(contentPath));
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Get cultural Url of an asset by adding current culture to its beginning
 /// for exmaple, path msgs_js will be converted to /en-us/msgs_js
 /// </summary>
 /// <param name="urlHelper">url helper</param>
 /// <param name="path">path</param>
 /// <returns></returns>
 public static string GetCulturalUrl(this UrlHelper urlHelper, string path)
 {
     return(urlHelper.Content("~/") + UTD.Tricorder.Website.UIText.CultureName() + "/" + path);
 }
Ejemplo n.º 40
0
 public static string GetProductImagePath(UrlHelper helper)
 {
     return(helper.Content("~/Images/Products/"));
 }
Ejemplo n.º 41
0
 public static string ContentVersioned(this UrlHelper urlHelper, string contentPath)
 {
     return(String.Format("{0}?v={1}", urlHelper.Content(contentPath), VersionUtils.VersionNumber));
 }
Ejemplo n.º 42
0
 public static string HomeBanner(this UrlHelper helper, string url)
 {
     url = "https://ouikumstorage.blob.core.windows.net/upload/Content/Default/banner/b2bthai/" + url;
     // return value;
     return(helper.Content(url));
 }
Ejemplo n.º 43
0
        public static HtmlString LoaderDiv(this HtmlHelper htmlHelper, object htmlAttributes)
        {
            TagBuilder div = new TagBuilder("div");

            div.MergeAttributes(Common.DynamicObjectToDictionary(new { id = "LoaderDiv", style = "display: none;" }));
            if (htmlAttributes != null)
            {
                div.MergeAttributes(Common.DynamicObjectToDictionary(htmlAttributes), true);
            }
            UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;

            TagBuilder img = new TagBuilder("img");

            img.MergeAttributes(Common.DynamicObjectToDictionary(new { width = 16, height = 16, alt = MyMessages.ButtonText.Loading, src = urlHelper.Content("~/images/loader.gif") }));

            div.InnerHtml = img.ToString();
            return(new HtmlString(div.ToString()));
        }
Ejemplo n.º 44
0
 public static string cssDefault(this UrlHelper helper, string url)
 {
     url = "~/Content/Default/" + url;
     // return value;
     return(helper.Content(url));
 }
Ejemplo n.º 45
0
 /// <summary>
 /// (自定义)使用指定的虚拟路径生成操作方法的完全限定 URL。
 /// </summary>
 /// <param name="url">UrlHelper。</param>
 /// <param name="virtualPath">虚拟路径。</param>
 /// <returns>操作方法的完全限定 URL。</returns>
 public static string Content(this UrlHelper url, string virtualPath)
 {
     return(string.Format("{0}{1}", SiteUrl(url), url.Content(virtualPath)));
 }
Ejemplo n.º 46
0
 public static string Website(this UrlHelper helper, string Action, int?CompID)
 {
     return(helper.Content("~/WebSite/" + Action + "/" + CompID));
 }
Ejemplo n.º 47
0
 public static string js(this UrlHelper helper, string value)
 {
     value = jsUrl + value;
     // return value;
     return(helper.Content(value));
 }