Ejemplo n.º 1
0
        private void ToXml(Stream stream)
        {
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.CheckCharacters    = false;

            using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
            {
                xmlWriter.WriteStartElement("Notifications");
                xmlWriter.WriteStartElement("Items");
                xmlWriter.WriteStartElement("Notification");

                LinkExtensions.Serialise(GetLinks(), xmlWriter);

                Model.XmlHelper.WriteElement(xmlWriter, "TimeTriggered", _WebhookNotification.TimeTriggered);
                Model.XmlHelper.WriteElement(xmlWriter, "SubscriptionType", _WebhookNotification.SubscriptionType);

                if (_WebhookNotification.ObjectDefinition != null)
                {
                    xmlWriter.WriteStartElement("Value");
                    ObjectInstance instance = new ObjectInstance(_WebhookNotification.ObjectDefinition, _WebhookNotification.ChangedObject);
                    instance.Links = new List <Link>();
                    instance.Serialise(xmlWriter);
                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();  // Notification
                xmlWriter.WriteEndElement();  // Items
                xmlWriter.WriteEndElement();  // Notifications
                xmlWriter.Flush();
            }
            stream.Position = 0;
        }
Ejemplo n.º 2
0
        public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName,
                                             string controllerName, object routeValues)
        {
            var actionLink = LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, routeValues, null);

            if (actionLink == MvcHtmlString.Empty)
            {
                return(MvcHtmlString.Empty);
            }

            var currentAction     = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            var builder = new TagBuilder("li")
            {
                InnerHtml = actionLink.ToHtmlString()
            };

            if (controllerName.ToLower() == currentController.ToLower())
            {
                builder.AddCssClass("active");
            }

            return(new MvcHtmlString(builder.ToString()));
        }
Ejemplo n.º 3
0
        public GuiController(IGuiForm f, string initialFile)
        {
            // This circular reference is a little aggressive here, but we need the form's
            // controller to be set immediately for our CreateNew call.  This is all
            // evidence that things are coupled quite a bit tighter than they should be.
            this.f = f;
            f.c    = this;

            UnbindSong();
            CreateNew();
            if (!System.IO.File.Exists(initialFile))
            {
                return;
            }

            File = new FileInfo(initialFile);
            if (LinkExtensions.Contains(File.Extension.ToLower()))
            {
                File = new FileInfo(WindowsShell.Shortcut.Resolve(initialFile));
            }

            using (FileStream input = File.OpenRead()) Metadata = new MetadataFile(input);
            WipeSelection();
            Dirty = false;
        }
Ejemplo n.º 4
0
        public static MvcHtmlString ActionlinkWithSpanForIcon(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes, string spanAttributes)
        {
            string strActionLink = LinkExtensions.ActionLink(htmlHelper, linkText, actionName, routeValues, htmlAttributes).ToString();

            /*var sb = new StringBuilder();
             * sb.Append(string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText));*/
            strActionLink = strActionLink.Replace(linkText, string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText));

            /*if (routeValues != null)
             * {
             *  RouteValueDictionary rvd = new RouteValueDictionary(routeValues);
             *  if (rvd.Count > 0)
             *  {
             *      sb.Append("/?");
             *      foreach (var rv in rvd)
             *      {
             *          sb.Append(rv.Key.ToString() + "=" + rv.Value + "&");
             *      }
             *      sb.Remove(sb.Length - 1, 1);
             *  }
             * }
             * TagBuilder spanBuilder = new TagBuilder("a");
             * if (routeValues != null)
             * {
             *  spanBuilder.Attributes.Add("href", string.Format("/{0}{1}",  actionName, sb.ToString()));
             * }
             * spanBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
             * spanBuilder.InnerHtml = string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText);*/

            return(MvcHtmlString.Create(strActionLink));
        }
Ejemplo n.º 5
0
        private void ToJson(Stream stream)
        {
            using (JsonWriter jsonWriter = new JsonWriter(stream))
            {
                jsonWriter.WriteObject();

                jsonWriter.WriteMember("Items");
                jsonWriter.WriteArray();

                jsonWriter.WriteObject();
                LinkExtensions.Serialise(GetLinks(), jsonWriter);

                jsonWriter.WriteMember("TimeTriggered");
                jsonWriter.WriteValue(_WebhookNotification.TimeTriggered);

                jsonWriter.WriteMember("SubscriptionType");
                jsonWriter.WriteValue(_WebhookNotification.SubscriptionType);

                if (_WebhookNotification.ObjectDefinition != null)
                {
                    jsonWriter.WriteMember("Value");
                    ObjectInstance instance = new ObjectInstance(_WebhookNotification.ObjectDefinition, _WebhookNotification.ChangedObject);
                    instance.Links = new List <Link>();
                    instance.Serialise(jsonWriter);
                }

                jsonWriter.WriteEndObject();

                jsonWriter.WriteEndArray();
                jsonWriter.WriteEndObject();
                jsonWriter.Flush();
            }
            stream.Position = 0;
        }
Ejemplo n.º 6
0
        public static MvcHtmlString ActionLinkForQueueCount <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, long queueLkup, long discCat)
        {
            StringBuilder output = new StringBuilder();
            long          count  = (long)ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
            QueueSummary  Model  = helper.ViewData.Model as QueueSummary;

            if (Model.lstUserAccessQueueLkups != null && Model.lstUserAccessQueueLkups.Contains(queueLkup) && count != 0)
            {
                HtmlString anchorTag;
                if (discCat == (long)DiscripancyCategory.OOA || discCat == (long)DiscripancyCategory.SCC || discCat == (long)DiscripancyCategory.TRR)
                {
                    anchorTag = LinkExtensions.ActionLink(helper, count.ToString(), "SearchFromHome", "Common", new { @ComplianceStartDate = Model.StartDate, @ComplianceEndDate = Model.EndDate, @Queue = queueLkup, @data = discCat }, new { @class = "count-button", @Title = "View Queue" });
                }
                else
                {
                    anchorTag = LinkExtensions.ActionLink(helper, count.ToString(), "SearchFromHome", "Common", new { @CaseCreationStartDate = Model.StartDate, @CaseCreationEndDate = Model.EndDate, @Queue = queueLkup, @data = discCat }, new { @class = "count-button", @Title = "View Queue" });
                }
                output.Append(anchorTag);
            }
            else
            {
                output.Append(string.Format(count.ToString()));
            }
            return(new MvcHtmlString(output.ToString()));
        }
Ejemplo n.º 7
0
        public static MvcHtmlString ActionlinkWithSpanForIcon(this HtmlHelper htmlHelper, string actionName, object routeValues, object htmlAttributes, string spanAttributes)
        {
            string strActionLink = LinkExtensions.ActionLink(htmlHelper, "null", actionName, routeValues, htmlAttributes).ToString();

            strActionLink = strActionLink.Replace("null", string.Format("<span class='{0}'></span>", spanAttributes));

            return(MvcHtmlString.Create(strActionLink));
        }
Ejemplo n.º 8
0
        public static MvcHtmlString CultureActionLink(this HtmlHelper htmlHelper, String langName)
        {
            var culture     = CultureInfo.CreateSpecificCulture(langName);
            var displayName = culture.Name.StartsWith("en")
                ? culture.NativeName
                : culture.EnglishName + " - " + culture.NativeName;

            return(LinkExtensions.ActionLink(htmlHelper, displayName, "Language", "Home", new { Lang = culture.Name }, null));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// se o usuário logado tem acesso ao recurso, gera um item de menu usando um list item html. Retorna string vazia caso contrário.
        /// </summary>
        /// <param name="html">HtmlHelper - o html helper do Razor</param>
        /// <param name="texto">string - o texto do menu</param>
        /// <param name="acao">string - a ação a ser verificada</param>
        /// <param name="controller">string - o controller a ser verificado</param>
        /// <returns>HtmlString - Um item de menu em html</returns>
        public static HtmlString MenuItemLiSeguro(this HtmlHelper html, string texto, string acao, string controller)
        {
            if (ControleAcesso.TemAcesso(controller, acao))
            {
                return(new HtmlString(string.Format("<li>{0}</li>", LinkExtensions.ActionLink(html, texto, acao, controller))));
            }

            return(new HtmlString(""));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates the links of the references.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper">The html helper</param>
        /// <param name="referencies">The referencies contained IDs and labels</param>
        /// <param name="action">The action name</param>
        /// <param name="controller">The controller name</param>
        /// <param name="htmlAttributes">The html attributes</param>
        /// <returns>Returns the created links of the references</returns>
        public static string CreateLinks <T>(this HtmlHelper <T> htmlHelper, ReferenceString referenceString, string action, string controller, object htmlAttributes)
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <Guid, string> reference in referenceString.GetReferencies())
            {
                sb.Append(LinkExtensions.ActionLink(htmlHelper, reference.Value, action, controller, new { id = reference.Key, name = UrlUtils.ToSeoUrl(reference.Value) }, htmlAttributes).ToString());
            }
            return(sb.ToString());
        }
Ejemplo n.º 11
0
        public static MvcHtmlString MenuLinkLi(this HtmlHelper htmlHelper, string linkText, string action, string controller, string userName)
        {
            ////UsuarioTO usuarioTO = Cache.DiccionarioUsuariosLogueados[usuario];
            //string areaName = (htmlHelper.ViewContext.RouteData.DataTokens["area"] != null && string.IsNullOrEmpty((string)htmlHelper.ViewContext.RouteData.DataTokens["area"])) ? string.Empty : (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];
            ////string controllerName = (string)html.ViewContext.RouteData.GetRequiredString("controller");
            ////string actionName = (string)html.ViewContext.RouteData.DataTokens["action"];

            ///*if(Cache.DiccionarioUsuariosLogueados.ContainsKey(userName) && Cache.DiccionarioUsuariosLogueados[userName].havePermissions(areaName, controller, action)) {
            //*/

            //    var result = new StringBuilder();
            //    //LinkExtensions.ActionLink(htmlHelper, linkText, action, controller);
            //    //var url = UrlHelper.GenerateContentUrl("/" + controller + "/" + action, html.ViewContext.HttpContext);
            //    result.Append("<li>");
            //   // result.Append("<a href=\"");
            //    //result.Append(HttpUtility.HtmlAttributeEncode(url));
            //    //result.Append("\" data-ajax-update=\"");
            //    //result.Append("\" >" + linkString + "</a>");
            //    result.Append(LinkExtensions.ActionLink(htmlHelper, linkText, action, controller).ToString());
            //    result.Append("</li>");
            //    //result.Append(HttpUtility.HtmlAttributeEncode("#" + ajaxUpdateId));
            //    // ... and so on
            //   // <li>@Html.ActionLink(@Resources.Resources.administracion_menu_roles, "Index", "Roles")</li>

            //    return new MvcHtmlString(result.ToString());
            ///*}*/
            ////return new MvcHtmlString("");

            //UsuarioTO usuarioTO = Cache.DiccionarioUsuariosLogueados[usuario];
            string areaName = (htmlHelper.ViewContext.RouteData.DataTokens["area"] != null && string.IsNullOrEmpty((string)htmlHelper.ViewContext.RouteData.DataTokens["area"])) ? string.Empty : (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];

            //string controllerName = (string)html.ViewContext.RouteData.GetRequiredString("controller");
            //string actionName = (string)html.ViewContext.RouteData.DataTokens["action"];

            if (Cache.DiccionarioUsuariosLogueados.ContainsKey(userName) && Cache.DiccionarioUsuariosLogueados[userName].havePermissions(areaName, controller, action))
            {
                var result = new StringBuilder();
                //LinkExtensions.ActionLink(htmlHelper, linkText, action, controller);
                //var url = UrlHelper.GenerateContentUrl("/" + controller + "/" + action, html.ViewContext.HttpContext);
                result.Append("<li>");
                // result.Append("<a href=\"");
                //result.Append(HttpUtility.HtmlAttributeEncode(url));
                //result.Append("\" data-ajax-update=\"");
                //result.Append("\" >" + linkString + "</a>");
                result.Append(LinkExtensions.ActionLink(htmlHelper, linkText, action, controller).ToString());
                result.Append("</li>");
                //result.Append(HttpUtility.HtmlAttributeEncode("#" + ajaxUpdateId));
                // ... and so on
                // <li>@Html.ActionLink(@Resources.Resources.administracion_menu_roles, "Index", "Roles")</li>

                return(new MvcHtmlString(result.ToString()));
            }
            return(new MvcHtmlString(""));
        }
Ejemplo n.º 12
0
 public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol = null, string hostName = null, string fragment = null, object routeValues = null, string accessKey = null, string charset = null, string coords = null, string cssClass = null, string dir = null, string hrefLang = null, string id = null, string lang = null, string name = null, string rel = null, string rev = null, string shape = null, string style = null, string target = null, string title = null)
 {
     return(LinkExtensions.RouteLink(
                htmlHelper,
                linkText,
                routeName,
                protocol,
                hostName,
                fragment,
                routeValues as RouteValueDictionary ?? new RouteValueDictionary(routeValues),
                AnchorAttributes(accessKey, charset, coords, cssClass, dir, hrefLang, id, lang, name, rel, rev, shape, style, target, title)
                ));
 }
Ejemplo n.º 13
0
        public static MvcHtmlString LocalizedActionLink <T>(this HtmlHelper <T> htmlHelper, string resourceKey, string action = "#", string controller = "", object routeValues = null, object htmlAttributes = null)
        {
            string tempName = Guid.NewGuid().ToString();

            if (routeValues == null && action != "Index" && action != "#")
            {
                action += "/";
            }
            string actionLinkMvcHtmlString = LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, routeValues, htmlAttributes).ToHtmlString();

            actionLinkMvcHtmlString = actionLinkMvcHtmlString.Replace(tempName, ResourceUtils.GetString(resourceKey));
            return(MvcHtmlString.Create(actionLinkMvcHtmlString));
        }
Ejemplo n.º 14
0
        public static MvcHtmlString ListGroupLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues)
        {
            var currentAction     = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            if (actionName.ToLower() == currentAction.ToLower())
            {
                return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, currentController, routeValues, new { @class = "list-group-item active" }));
            }
            else
            {
                return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, currentController, routeValues, new { @class = "list-group-item" }));
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Checks user security permissions.  If allowed, displays link. Otherwise, displays nothing.
 /// </summary>
 /// <returns>Link or empty string.</returns>
 public static MvcHtmlString AuthorizedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary <string, object> htmlAttributes)
 {
     // See if user has access to the action.
     if (ActionIsAccessibleToUser(htmlHelper: htmlHelper, actionName: actionName, controllerName: controllerName, routeValues: routeValues))
     {
         // User has access. Generate ActionLink.
         return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes));
     }
     else
     {
         // User does not have access. Return empty string.
         return(MvcHtmlString.Empty);
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates the localized link for open the dialog.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper">The html helper</param>
        /// <param name="resourceKey">The resource key to be localized</param>
        /// <param name="targetDialog">The html id of the dialog to be opened</param>
        /// <param name="action">The action to execute</param>
        /// <param name="controller">The controller of the action</param>
        /// <param name="routeValues">The route values for the action</param>
        /// <param name="htmlAttributes">The additional html attributes for the link</param>
        /// <returns></returns>
        public static MvcHtmlString DialogActionLink <T>(this HtmlHelper <T> htmlHelper, string resourceKey, string targetDialog, string action, string controller, object routeValues = null, object htmlAttributes = null)
        {
            string tempName = Guid.NewGuid().ToString();
            RouteValueDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            attributes.Add("data-toggle", "modal");
            attributes.Add("data-target", targetDialog);
            attributes.Add("data-placement", "top");
            attributes["class"] += " show-dialog tooltips";
            if (attributes.ContainsKey("title"))
            {
                attributes["title"] = ResourceUtils.GetString(attributes["title"].ToString());
            }
            return(MvcHtmlString.Create(LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues), attributes).ToHtmlString().Replace(tempName, ResourceUtils.GetString(resourceKey))));
        }
Ejemplo n.º 17
0
        public override string GenerateUrl(string pathTemplate, string[] parameters, NDjango.Interfaces.IContext context)
        {
            var htmlHelperOption = context.tryfind("Html");

            if (htmlHelperOption == null)
            {
                return("");
            }

            var htmlHelper = (HtmlHelper)htmlHelperOption.Value;
            var anchor     = LinkExtensions.ActionLink(htmlHelper, pathTemplate, pathTemplate, parameters[0]).ToHtmlString();

            //retriving relativePath from anchor element.
            var startindex = anchor.IndexOf("href") + 6; var endIndex = anchor.IndexOf("\"", startindex);

            return(anchor.Substring(startindex, endIndex - startindex));
        }
Ejemplo n.º 18
0
        public static MvcHtmlString UserInfo(this HtmlHelper htmlHelper)
        {
            string res = "<div style=\"position: absolute; right: 10px; top: 10px;\" >";

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                res += $"<div>Zalogowano jako: {HttpContext.Current.User.Identity.Name}</div>";
                res += "<div>" + LinkExtensions.ActionLink(htmlHelper, "Wyloguj", "Logout", "Account") + "</div>";
            }

            else
            {
                res += "<div>" + LinkExtensions.ActionLink(htmlHelper, "Zaloguj", "Login", "Account") + "</div>";
            }

            res += "</div>";

            return(MvcHtmlString.Create(res));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets the breadcrumb for the current location.
        /// </summary>
        /// <param name="html">A HtmlHelper that is the current HTML helper.</param>
        /// <param name="separator">A MvcHtmlString containing the separator to use between the breadcrumbs.</param>
        /// <param name="homeController">A string containing the name of the homepage controller.</param>
        /// <param name="indexAction">A string containing the name of the index action.</param>
        /// <returns>A MvcHtmlString containing the breadcrumb.</returns>
        public static MvcHtmlString GetBreadcrumb(this HtmlHelper html, MvcHtmlString separator, string homeController = "Home", string indexAction = "Index")
        {
            MvcHtmlString ReturnValue;

            if (html.GetControllerName(out string ControllerName) && html.GetActionName(out string ActionName))
            {
                if (ControllerName != homeController)
                {
                    string ModelName;

                    ModelName = html.GetModelDisplayName();
                    if (ModelName == null)
                    {
                        ModelName = ControllerName;
                    }

                    ReturnValue = LinkExtensions.ActionLink(html, homeController, indexAction, homeController);
                    ReturnValue = ReturnValue.Concat(separator);
                    if (ActionName != indexAction)
                    {
                        string ActionDisplayName;

                        ActionDisplayName = html.GetActionDisplayName();
                        if (ActionDisplayName == null)
                        {
                            ActionDisplayName = ActionName;
                        }

                        ReturnValue = ReturnValue.Concat(LinkExtensions.ActionLink(html, ModelName, indexAction, html.ViewContext.RouteData.Values["controller"].ToString()));
                        ReturnValue = ReturnValue.Concat(separator);
                        ReturnValue = ReturnValue.Concat(ActionDisplayName);
                    }
                    else
                    {
                        ReturnValue = ReturnValue.Concat(ModelName);
                    }
                }
                else
                {
                    ReturnValue = new MvcHtmlString(homeController);
                }
            }
Ejemplo n.º 20
0
        private static MvcHtmlString WriteMenuLink(HtmlHelper html, string text, string action, string controller, string area, object routeValues = null, params string[] cssClasses)
        {
            RouteValueDictionary        allRouteValues    = new RouteValueDictionary(routeValues);
            Dictionary <string, object> allHtmlAttributes = new Dictionary <string, object>();
            MvcHtmlString link = null;

            if (area != null)
            {
                allRouteValues["area"] = area;
            }

            if (!cssClasses.IsNullOrEmpty())
            {
                allHtmlAttributes["class"] = string.Join(" ", cssClasses);
            }

            link = LinkExtensions.ActionLink(html, text, action, controller, routeValues: allRouteValues, htmlAttributes: allHtmlAttributes);

            return(link);
        }
Ejemplo n.º 21
0
        private ActionResult GetRedirectOnFinish()
        {
            var redirectTo = ControllerContext.HttpContext.Request["redirectTo"];

            if (!string.IsNullOrEmpty(redirectTo))
            {
                return(Redirect(redirectTo));
            }

            var defaultRedirect = RunningObjectsSetup.Configuration.DefaultRedirect;

            if (defaultRedirect != null)
            {
                var routeValues = defaultRedirect.Action != RunningObjectsAction.Welcome
                                      ? LinkExtensions.CreateRouteValueDictionary(defaultRedirect.Type, defaultRedirect.Arguments)
                                      : null;

                return(RedirectToAction(defaultRedirect.Action.ToString(), "Presentation", routeValues));
            }
            return(RedirectToAction(RunningObjectsAction.Welcome.ToString(), "Presentation"));
        }
Ejemplo n.º 22
0
        public static IHtmlString EndingFormButtons(this HtmlHelper html, string submitButtonText = "Save", string anchorValue = "Go Back", string anchorAction = "GoBack", string anchorController = "Home")
        {
            TagBuilder div = new TagBuilder("div");

            div.AddCssClass("input-group mb-3 my-3 d-flex justify-content-around");

            MvcHtmlString anchor = LinkExtensions.ActionLink(html, anchorValue, anchorAction, anchorController, new { area = "" }, new { @class = "btn btn-secondary btn-lg" });

            TagBuilder submit = new TagBuilder("input");

            submit.AddCssClass("btn btn-success btn-lg");
            submit.MergeAttribute("type", "submit");
            submit.MergeAttribute("value", submitButtonText);

            StringBuilder htmlBuilder = new StringBuilder();

            htmlBuilder.Append(anchor.ToHtmlString());
            htmlBuilder.Append(submit.ToString(TagRenderMode.SelfClosing));

            div.InnerHtml = htmlBuilder.ToString();
            return(MvcHtmlString.Create(div.ToString(TagRenderMode.Normal)));
        }
Ejemplo n.º 23
0
        private Func <object, ActionResult> OnSuccess(Type modelType)
        {
            return(instance =>
            {
                var redirectTo = ControllerContext.HttpContext.Request["redirectTo"];
                if (!string.IsNullOrEmpty(redirectTo))
                {
                    return Redirect(redirectTo);
                }

                var defaultRedirect = RunningObjectsSetup.Configuration.DefaultRedirect;
                if (defaultRedirect != null)
                {
                    var routeValues = defaultRedirect.Action != RunningObjectsAction.Welcome
                        ? LinkExtensions.CreateRouteValueDictionary(defaultRedirect.Type, defaultRedirect.Arguments)
                        : null;

                    return RedirectToAction(defaultRedirect.Action.ToString(), "Presentation", routeValues);
                }
                return RedirectToAction("Index", new { modelType = modelType.PartialName() });
            });
        }
Ejemplo n.º 24
0
        public static MvcHtmlString Pagination(this HtmlHelper helper, int currnetPage, int allPages, string actionName, string controllerName, string pageVarName)
        {
            TagBuilder nav = new TagBuilder("nav");
            TagBuilder ul  = new TagBuilder("ul");

            ul.MergeAttribute("class", "pagination");
            TagBuilder li = new TagBuilder("li");

            if (currnetPage == 1)
            {
                li.AddCssClass("disabled");
            }

            li.InnerHtml = LinkExtensions.ActionLink(helper, "<<", actionName, controllerName, new { id = currnetPage - 1 }, htmlAttributes: null).ToString();
            ul.InnerHtml = li.ToString();
            for (int i = 1; i <= allPages; i++)
            {
                li = new TagBuilder("li");
                if (i == currnetPage)
                {
                    li.AddCssClass("active");
                }

                li.InnerHtml  = LinkExtensions.ActionLink(helper, i.ToString(), actionName, controllerName, new { id = i }, htmlAttributes: null).ToString();
                ul.InnerHtml += li.ToString();
            }

            li = new TagBuilder("li");
            if (currnetPage == allPages)
            {
                li.AddCssClass("disabled");
            }

            li.InnerHtml  = LinkExtensions.ActionLink(helper, ">>", actionName, controllerName, new { id = currnetPage + 1 }, htmlAttributes: null).ToString();
            ul.InnerHtml += li.ToString();
            nav.InnerHtml = ul.ToString();
            return(new MvcHtmlString(nav.ToString()));
        }
        /// <summary>
        /// Returns the table row Edit | Details | Delete links which the user in scope has permission to.
        /// </summary>
        /// <param name="html"></param>
        /// <param name="linkId"></param>
        /// <returns></returns>
        public static MvcHtmlString IndexLinks(this HtmlHelper html, object linkId)
        {
            // Get the users role
            EnumHelper.Roles role = EnumHelper.Roles.Viewer;
            if (HttpContext.Current.User.IsInRole(EnumHelper.Roles.Author.ToString()))
            {
                role = EnumHelper.Roles.Author;
            }
            else if (HttpContext.Current.User.IsInRole(EnumHelper.Roles.Admin.ToString()))
            {
                role = EnumHelper.Roles.Admin;
            }

            // Get the current route Controller name
            var    currentRouteData = html.ViewContext.RouteData;
            string controller       = currentRouteData.GetRequiredString("controller");

            // Check user permissions
            CustomApplicationDbContext  context          = new CustomApplicationDbContext();
            IQueryable <RolePermission> rolePermissions  = context.RolePermissions;
            PermissionHelper            permissionHelper = new PermissionHelper(rolePermissions);

            // Build the MvcHtmlString
            StringBuilder linkStringBuilder = new StringBuilder();

            if (permissionHelper.HasPermission(role, controller, "Edit"))
            {
                linkStringBuilder.Append(string.Format("{0} |",
                                                       LinkExtensions.ActionLink(html, "Edit", "Edit", linkId)));
            }
            linkStringBuilder.Append(LinkExtensions.ActionLink(html, "Details", "Details", linkId));
            if (permissionHelper.HasPermission(role, controller, "Delete"))
            {
                linkStringBuilder.Append(string.Format("| {0}",
                                                       LinkExtensions.ActionLink(html, "Delete", "Delete", linkId)));
            }
            return(new MvcHtmlString(linkStringBuilder.ToString()));
        }
Ejemplo n.º 26
0
        public static MvcHtmlString Grid <T>(this HtmlHelper html, IEnumerable <T> items, string defaultSort, string gridCaption, bool canPage = false, int rowPerPage = 50, int rowCount = 0, int activePage = 1, string idGrid = "grid", bool isWindowMode = false, List <KeyValuePair <string, object> > parameters = null)
        {
            StringBuilder output = new StringBuilder();

            if (items.Count() > 0)
            {
                List <GridColumnOrder> columns = new List <GridColumnOrder>();
                if (parameters == null)
                {
                    parameters = new List <KeyValuePair <string, object> >();
                }

                parameters.Add(new KeyValuePair <string, object>("windowMode", isWindowMode));
                if (rowCount == 0)
                {
                    rowCount = items.Count();
                }

                if (canPage)
                {
                    output.AppendLine(CreatePageNavigator(html, rowPerPage, rowCount, activePage: activePage, parameters: parameters).ToHtmlString());
                }

                var grid = new WebGrid((IEnumerable <dynamic>)items, canPage: false, canSort: false, rowsPerPage: rowPerPage, defaultSort: defaultSort);
                foreach (var property in typeof(T).GetProperties())
                {
                    bool showColumn = true;
                    var  attributes = (property.GetCustomAttributes(typeof(GridConfigAttribute), false));
                    if (attributes != null)
                    {
                        foreach (var attribute in attributes)
                        {
                            string propertyName = property.Name;
                            var    attr         = (GridConfigAttribute)attribute;
                            string style        = attr.Style;

                            showColumn = !attr.Hidden;
                            if (showColumn)
                            {
                                showColumn = !(isWindowMode && attr.HiddenOnWindowMode);
                            }

                            if (showColumn)
                            {
                                showColumn = attr.Index > 0;
                            }

                            if (attr.CreateCheckBox && !isWindowMode)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Format = (dynamic item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        return(InputExtensions.CheckBox(html, String.Format("chk{0}", propertyName), new { @class = "checkable", value = objectValue }));
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.CreateImage && !isWindowMode)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    //Header = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(propertyName),
                                    Format = (dynamic item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        objectValue     = String.Concat(SpongeSolutions.ServicoDireto.Admin.SiteContext.LayoutPath, objectValue);
                                        return(new MvcHtmlString(String.Format("<img src='{0}'/>", objectValue)));
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.CreateEditLink)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Format = (item) =>
                                    {
                                        var entity = (T)(((WebGridRow)item).Value);
                                        try
                                        {
                                            string objectValue       = entity.GetType().GetProperty(propertyName).GetValue(entity, null).ToString();
                                            string objectDescription = null;

                                            if (attr.RelatedFieldName != null && attr.RelatedFieldName.Count() > 0)
                                            {
                                                foreach (var fieldName in attr.RelatedFieldName)
                                                {
                                                    objectDescription += String.Format("{0}-", entity.GetType().GetProperty(fieldName).GetValue(entity, null));
                                                }

                                                objectDescription = objectDescription.Remove(objectDescription.Length - 1, 1);
                                            }
                                            if (objectDescription == null)
                                            {
                                                objectDescription = objectValue;
                                            }

                                            if (isWindowMode)
                                            {
                                                return(new HtmlString(String.Format("<a href=\"javascript:AddSelected('{0}','{1}')\">{2}</a>", objectValue, objectDescription, SpongeSolutions.ServicoDireto.Internationalization.Label.Select)));
                                            }
                                            else
                                            {
                                                return(LinkExtensions.ActionLink(html, SpongeSolutions.ServicoDireto.Internationalization.Label.Edit, "create", new { id = objectValue }));
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            return(string.Empty);
                                        }
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.EnumType != null)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Style      = style,
                                    ColumnName = property.Name,
                                    Header     = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(property.Name),
                                    Format     = (item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        //var enumSource = Activator.CreateInstance(attr.EnumType);
                                        //TODO: COLOCAR DE MODO DINAMICO
                                        return(SpongeSolutions.Core.Translation.EnumTranslator.Translate <Enums.StatusType>(SpongeSolutions.Core.Helpers.EnumHelper.TryParse <Enums.StatusType>(objectValue)).DisplayName);
                                    }
                                }));
                                showColumn = false;
                            }

                            if (showColumn)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    ColumnName = property.Name,
                                    Header     = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(property.Name)
                                    ,
                                    Style = style
                                }));
                            }
                        }
                    }
                }

                output.AppendLine(MvcHtmlString.Create(grid.GetHtml(
                                                           tableStyle: "grid",
                                                           caption: gridCaption,
                                                           alternatingRowStyle: "alternating",
                                                           htmlAttributes: new { id = idGrid },
                                                           columns: columns.OrderBy(p => p.Index).Select(p => p.Column).ToArray()).ToHtmlString()).ToHtmlString());

                if (canPage)
                {
                    output.AppendLine(CreatePageNavigator(html, rowPerPage, rowCount, activePage: activePage, parameters: parameters).ToHtmlString());
                }
            }
            else
            {
                var container = new TagBuilder("div");
                container.AddCssClass("notice");
                container.SetInnerText(Internationalization.Label.Records_Not_Found);
                output.Append(container.ToString());
            }
            return(MvcHtmlString.Create(output.ToString()));
        }
Ejemplo n.º 27
0
 /// <summary>
 /// 返回一个链接
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="linkText">链接文字</param>
 /// <param name="actionName">动作名</param>
 /// <param name="controllerName">控制器名</param>
 /// <param name="areaName">区域名</param>
 /// <param name="htmlAttributes">html特性</param>
 public static MvcHtmlString AsiatekActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string areaName, object htmlAttributes)
 {
     return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, new { controller = controllerName, area = areaName }, htmlAttributes));
 }
Ejemplo n.º 28
0
 public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, RouteValueDictionary routeValues, object htmlAttributes)
 {
     return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, routeValues, htmlAttributes.CastToDictionary()));
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates link similar to Html.ActionLink, just correctly sets the sortDir and sortCol parameters and CSS classes
        /// </summary>
        /// <param name="html">Extension instance</param>
        /// <param name="linkText">Text to display as the link</param>
        /// <param name="actionName">Action name as in Html.ActionLink</param>
        /// <param name="controllerName">Controller name as in Html.ActionLink</param>
        /// <param name="routeDictionary">RouteDictionary same as in Html.ActionLink</param>
        /// <param name="htmlAttributes">HtmlAttributes dictionary same as in Html.ActionLink</param>
        /// <param name="sortColumn">What sortcol id will this column stand for</param>
        /// <returns>Formatted and styled link</returns>
        public static MvcHtmlString SortableHeaderActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, object routeDictionary, IDictionary <string, object> htmlAttributes, int sortColumn)
        {
            int querySortDir;

            if (!int.TryParse(((html.ViewBag.sortDir ?? html.ViewContext.HttpContext.Request.QueryString["sortDir"]) ?? "").ToString(), out querySortDir))
            {
                querySortDir = (int)SortDirection.Asc;
            }

            int oppositeQuerySortDir = querySortDir == (int)SortDirection.Asc ? (int)SortDirection.Desc : (int)SortDirection.Asc;

            int querySortCol;

            if (!int.TryParse(((html.ViewBag.sortCol ?? html.ViewContext.HttpContext.Request.QueryString["sortCol"]) ?? "").ToString(), out querySortCol))
            {
                querySortCol = 0;
            }

            RouteValueDictionary newRouteDictionary = new RouteValueDictionary(routeDictionary ?? new { });

            // for "key with multiple values" ends up like "&xxx=x&xxx=xx" in the url, the above code can not translate it into
            // newRouteDictionary.Add("xxx", x);
            // newRouteDictionary.Add("xxx", xx);
            // the key can not be duplicated we will need to do some work around
            // The below code translate it into
            // newRouteDictionary.Add("xxx[0]", x);
            // newRouteDictionary.Add("xxx[1]", xx);
            // it will be like "&xxx[0]=x&xxx[1]=xx" in the query string, this is accepted by the controller action as array as well
            // reference http://stackoverflow.com/questions/27383705/how-to-build-a-routevaluedictionary-when-a-route-has-multiple-values
            List <KeyValuePair <string, object> > multiValueRoutes = newRouteDictionary.Where(x => x.Value != null && x.Value.GetType().IsArray).ToList();

            if (multiValueRoutes.Count() > 0)
            {
                foreach (KeyValuePair <string, object> multiValueRoute in multiValueRoutes)
                {
                    if (multiValueRoute.Value is int[])
                    {
                        int[] values = (int[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                    else if (multiValueRoute.Value is string[])
                    {
                        string[] values = (string[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                    else if (multiValueRoute.Value is bool[])
                    {
                        bool[] values = (bool[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                }
            }

            if (!newRouteDictionary.ContainsKey("sortDir"))
            {
                newRouteDictionary.Add("sortDir", querySortCol == sortColumn ? oppositeQuerySortDir : (int)SortDirection.Asc);
            }
            else
            {
                newRouteDictionary["sortDir"] = querySortCol == sortColumn ? oppositeQuerySortDir : (int)SortDirection.Asc;
            }
            if (!newRouteDictionary.ContainsKey("sortCol"))
            {
                newRouteDictionary.Add("sortCol", sortColumn.ToString());
            }

            string keyword = html.ViewContext.HttpContext.Request.QueryString["keyword"];

            if (keyword != null && !newRouteDictionary.ContainsKey("keyword"))
            {
                newRouteDictionary.Add("keyword", keyword);
            }

            string index = html.ViewContext.HttpContext.Request.QueryString["index"];

            if (index != null && !newRouteDictionary.ContainsKey("index"))
            {
                newRouteDictionary.Add("index", index);
            }

            htmlAttributes = htmlAttributes ?? new Dictionary <string, object>();
            if (htmlAttributes.ContainsKey("class"))
            {
                htmlAttributes["class"] += " " + (querySortCol == sortColumn ? (querySortDir == (int)SortDirection.Asc ? "headerSortUp" : "headerSortDown") : "unsorted-header");
            }
            else
            {
                htmlAttributes.Add("class", querySortCol == sortColumn ? (querySortDir == (int)SortDirection.Asc ? "headerSortUp" : "headerSortDown") : "unsorted-header");
            }

            htmlAttributes.Add("id", string.Format("sortable-header-{0}-{1}", actionName, querySortCol.ToString()));

            if (controllerName == null)
            {
                return(LinkExtensions.ActionLink(html, linkText, actionName, controllerName, newRouteDictionary, htmlAttributes));
            }
            else
            {
                return(LinkExtensions.ActionLink(html, linkText, actionName, newRouteDictionary, htmlAttributes));
            }
        }
Ejemplo n.º 30
0
        public MvcHtmlString InitPagerHtml(HtmlHelper htmlHelper)
        {
            MvcHtmlString result;

            if (this.TotalRecords == 0)
            {
                result = MvcHtmlString.Empty;
            }
            else
            {
                int num = this.TotalRecords / this.PageSize;
                if (this.TotalRecords % this.PageSize > 0)
                {
                    num++;
                }
                string text  = "<a href='#'>1</a>";
                string value = "<span>{totalText}:</span> <span>{totalRecords}</span> <span>{totalRecordsText}</span>  <span>{first}</span> <span> {previous}</span> <span> {numberRange}</span> <span>{next}</span> <span>{last}</span>  <span>{pageCount} pages</span>";
                if (string.IsNullOrEmpty(this.ControllerName) || string.IsNullOrEmpty(this.ActionName))
                {
                    throw new Exception("controllerName and actionName must be specified for PageLinks.");
                }
                RouteValueDictionary routeValueDictionary = new RouteValueDictionary(this.RouteValues);
                routeValueDictionary.Add("controller", this.ControllerName);
                routeValueDictionary.Add("action", this.ActionName);
                routeValueDictionary.Add("page", 1);
                string newValue = LinkExtensions.RouteLink(htmlHelper, this.FirstText, routeValueDictionary).ToString();
                routeValueDictionary["page"] = num;
                string newValue2 = LinkExtensions.RouteLink(htmlHelper, this.LastText, routeValueDictionary).ToString();
                routeValueDictionary["page"] = this.PageIndex + 1;
                string newValue3 = LinkExtensions.RouteLink(htmlHelper, this.NextText, routeValueDictionary).ToString();
                routeValueDictionary["page"] = this.PageIndex - 1;
                string newValue4 = LinkExtensions.RouteLink(htmlHelper, this.PreviousText, routeValueDictionary).ToString();
                if (this.PageIndex == 1)
                {
                    newValue  = this.FirstText;
                    newValue4 = this.PreviousText;
                }
                if (this.PageIndex == num)
                {
                    newValue3 = this.NextText;
                    newValue2 = this.LastText;
                }
                if (num <= this.PageRange)
                {
                    text = "";
                    for (int i = 1; i <= num; i++)
                    {
                        if (this.PageIndex == i)
                        {
                            text += i.ToString();
                        }
                        else
                        {
                            routeValueDictionary["page"] = i;
                            text += LinkExtensions.RouteLink(htmlHelper, i.ToString(), routeValueDictionary).ToString();
                        }
                        text += "  ";
                    }
                }
                else
                {
                    for (int i = 0; i <= num / this.PageRange; i++)
                    {
                        int num2 = this.PageRange * i;
                        int num3 = this.PageRange * (i + 1);
                        if (this.PageIndex > num2 && this.PageIndex <= num3)
                        {
                            text = "";
                            for (int j = num2 + 1; j <= num3; j++)
                            {
                                if (this.PageIndex == j)
                                {
                                    text += j.ToString();
                                }
                                else
                                {
                                    routeValueDictionary["page"] = j;
                                    text += LinkExtensions.RouteLink(htmlHelper, j.ToString(), routeValueDictionary).ToString();
                                }
                                text += "  ";
                            }
                        }
                    }
                }
                StringBuilder stringBuilder = new StringBuilder(value);
                stringBuilder.Replace("{totalText}", this.TotalText).Replace("{totalRecords}", this.TotalRecords.ToString()).Replace("{totalRecordsText}", this.TotalRecordsText).Replace("{first}", newValue).Replace("{totalRecordsText}", this.TotalRecordsText);
                stringBuilder.Replace("{previous}", newValue4).Replace("{numberRange}", text).Replace("{next}", newValue3).Replace("{last}", newValue2).Replace("{pageCount}", num.ToString());
                result = MvcHtmlString.Create(stringBuilder.ToString());
            }
            return(result);
        }