Exemplo n.º 1
0
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            UserSessionContext us = new UserSessionContext(filterContext.HttpContext);

            int userId = us.GetUserId();

            var query = from u in db.Users
                        where u.Id == userId && u.Role == userRole
                        select u;

            var user = query.FirstOrDefault();

            if (user == null)
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "Login");
                redirectTargetDictionary.Add("controller", "Account");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
            else
            {
                filterContext.HttpContext.Items.Add("User", user);
            }

            this.OnActionExecuting(filterContext);
        }
Exemplo n.º 2
0
        public override void ExecuteResult(ControllerContext context)
        {
            //Get url
            string url = "";
            if (!string.IsNullOrEmpty(_url)) url = _url;
            else
            {
                //Create route
                var routeValues = new RouteValueDictionary(_Values);
                routeValues.Add("Action", _Action);
                routeValues.Add("Controller", _Controller);

                //Must persist ajax
                var request = HttpContext.Current.Request;
                if ((request["X-Requested-With"] != null &&
                    request["X-Requested-With"].Equals("XmlHttpRequest", StringComparison.InvariantCultureIgnoreCase)) ||
                    request.QueryString["_"] != null ||
                    context.HttpContext.Items["__IsAjaxRequest"] != null)
                    routeValues.Add("X-Requested-With", "XmlHttpRequest");

                url = RouteTable.Routes.GetVirtualPath(context.RequestContext, routeValues).VirtualPath;
            }

            HttpContext.Current.RewritePath(url, false);
            IHttpHandler httpHandler = new MvcHttpHandler();
            httpHandler.ProcessRequest(HttpContext.Current);

            //httpContext.Server.TransferRequest(url, true);
        }
Exemplo n.º 3
0
 public string UrlPath(string actionName, string controllerName, Object routeValues)
 {
     RouteValueDictionary values = new RouteValueDictionary(routeValues);
     values.Add("action", actionName);
     values.Add("controller", controllerName);
     return SiteData.Instance.Domain + Url.RouteCollection.GetVirtualPath(this.HttpContext.Request.RequestContext, values).VirtualPath;
 }
Exemplo n.º 4
0
        public static MvcHtmlString BuildNavigation(this HtmlHelper Helper, string activeLinkName, string linkGroupName)
        {
            TagBuilder LinkContainer = new TagBuilder("ul");
            LinkContainer.AddCssClass("nav nav-pills");

            LinkManager.Instance.GetLinks(linkGroupName)
                .ForEach(Lnk =>
                {
                    string routeName = null;
                    var linkItem = new TagBuilder("li");
                    var RouteParams = new RouteValueDictionary(Lnk.RouteParams);

                    if (!string.IsNullOrEmpty(Lnk.Controller))
                        RouteParams.Add("controller", Lnk.Controller);
                    if (!string.IsNullOrEmpty(Lnk.Action))
                        RouteParams.Add("action", Lnk.Action);
                    if (!string.IsNullOrEmpty(Lnk.Area))
                        RouteParams.Add("area", Lnk.Area);

                    if(Lnk.Name == activeLinkName)
                        linkItem.AddCssClass("active");

                    if (Lnk.UseNamedRoute)
                        routeName = Lnk.RouteName;
                    else
                        routeName = "Default";

                    linkItem.InnerHtml = Helper.RouteLink(Lnk.Text, routeName, RouteParams, Lnk.HtmlAttributes).ToString();

                    LinkContainer.InnerHtml += linkItem.ToString();
                });

            return new MvcHtmlString(LinkContainer.ToString());
        }
        public static RouteValueDictionary ToRouteValueDictionary(this object obj)
        {
            var result = new RouteValueDictionary();
            var props = obj.GetType().GetProperties().Where(p => p.GetValue(obj, null) != null);
            foreach (var p in props)
            {
                var value = p.GetValue(obj, null);
                var enumerable = value as ICollection;
                if (enumerable != null)
                {
                    var i = 0;

                    foreach (var item in enumerable)
                    {
                        result.Add(string.Format("{0}[{1}]", p.Name, i), item.ToString());
                        i++;
                    }
                }
                else
                {
                    var date = value as DateTime?;
                    if (date != null)
                    {
                        result.Add(p.Name, date.Value.ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        result.Add(p.Name, value.ToString());
                    }
                }
            }

            return result;
        }
Exemplo n.º 6
0
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(filterContext.RequestContext);
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NotAuthorized",
                        LogOnUrl = urlHelper.Action("Login", "Account", new { SessionTimeout = true })
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var routeValues = new RouteValueDictionary();

                routeValues.Add("Controller", "Account");
                routeValues.Add("Action", "Login");
                routeValues.Add("SessionTimeout", true);
                if (filterContext.HttpContext.Request.UrlReferrer != null)
                    routeValues.Add("ReturnUrl", filterContext.HttpContext.Request.UrlReferrer.PathAndQuery);
                filterContext.Result = new RedirectToRouteResult(routeValues);
            }
        }
Exemplo n.º 7
0
 protected override void OnException(ExceptionContext filterContext)
 {
     Entity.Monitoring.ExceptionLog exlog = new Entity.Monitoring.ExceptionLog();
     if (Session != null && Session["User"] != null)
         exlog.AccountId = ((Entity.User.Account)Session["User"]).Id;
     exlog.EntityValue = "";
     exlog.Exception = filterContext.Exception.ToString();
     exlog.ExceptionCode = filterContext.Exception.Source;
     exlog.ExceptionMessage = filterContext.Exception.Message;
     exlog.EntityValue = "";
     System.Web.Mvc.Controller _controller = ((System.Web.Mvc.Controller)filterContext.Controller);
     string key = "";
     for (int i = 0; i < _controller.ModelState.Keys.Count; i++)
     {
         key = _controller.ModelState.Keys.ToList()[i];
         exlog.EntityValue += "<" + key + " = ";
         for (int j = 0; j < ((string[])(_controller.ModelState[key].Value.RawValue)).Length; j++)
         {
             exlog.EntityValue += ((string[])(_controller.ModelState[key].Value.RawValue))[j] + " ; ";
         }
         exlog.EntityValue += ">";
     }
     exlog.ExecuteEntity = filterContext.Controller.GetType().Name;
     this.Bll.Monitoring.CreateExceptionLog(exlog);
     //data sonra değiştirilecek
     RouteValueDictionary rd = new RouteValueDictionary();
     rd.Add("controller", "Home");
     rd.Add("action", "Index");
     new RedirectToRouteResult("Default", rd);
 }
Exemplo n.º 8
0
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(!filterContext.HttpContext.Items.Contains("User"))
            {
                this.OnActionExecuting(filterContext);
                return;
            }

            User user = filterContext.HttpContext.Items["User"] as User;

            var query = from c in db.Characters.AsNoTracking()
                        where c.UserId == user.Id
                        select c;

            var character = query.FirstOrDefault();

            if (character == null)
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "Create");
                redirectTargetDictionary.Add("controller", "Character");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
            else
            {
                filterContext.HttpContext.Items.Add("Character", character);
            }

            this.OnActionExecuting(filterContext);
        }
 public ActionResult ReturnRoute(int? id, ActionResult defaultRoute)
 {
     RouteValueDictionary routeValues = new RouteValueDictionary();
     switch (GetRouteParameter())
     {
         case "c-tls":
             routeValues["controller"] = "Conference";
             routeValues["action"] = "TracksLocationsSlots";
             routeValues.Add("conferenceId", id);
             return Redirect(ModuleRoutingProvider.Instance().GenerateUrl(routeValues, ModuleContext));
         case "c-ss":
             routeValues["controller"] = "Conference";
             routeValues["action"] = "SessionsSpeakers";
             routeValues.Add("conferenceId", id);
             return Redirect(ModuleRoutingProvider.Instance().GenerateUrl(routeValues, ModuleContext));
         case "c-m":
             routeValues["controller"] = "Conference";
             routeValues["action"] = "Manage";
             routeValues.Add("conferenceId", id);
             return Redirect(ModuleRoutingProvider.Instance().GenerateUrl(routeValues, ModuleContext));
         case "s-v":
             routeValues["controller"] = "Session";
             routeValues["action"] = "View";
             routeValues.Add("conferenceId", ControllerContext.HttpContext.Request.Params["ConferenceId"]);
             routeValues.Add("SessionId", id);
             return Redirect(ModuleRoutingProvider.Instance().GenerateUrl(routeValues, ModuleContext));
     }
     return defaultRoute;
 }
Exemplo n.º 10
0
 /// <summary>
 /// 设置群组的审核状态
 /// </summary>
 /// <param name="siteUrls"></param>
 /// <param name="isApproved">是否通过</param>
 /// <returns></returns>
 public static string BatchUpdateGroupAuditStatu(this SiteUrls siteUrls, long groupId, bool isApproved = true)
 {
     RouteValueDictionary routeValueDictionary = new RouteValueDictionary();
     routeValueDictionary.Add("groupId", groupId);
     routeValueDictionary.Add("isApproved", isApproved);
     return CachedUrlHelper.Action("BatchUpdateGroupAuditStatu", "ControlPanelGroup", GroupAreaName, routeValueDictionary);
 }
Exemplo n.º 11
0
		public static void MapRoute(
			this System.Web.Routing.RouteCollection routes ,
			MvcRouteConfigurationSection section ) {
			// Manipulate the Ignore List
			foreach ( IgnoreItem ignoreItem in section.Ignore ) {
				var ignoreConstraints = new RouteValueDictionary();

				foreach ( Constraint constraint in ignoreItem.Constraints ) {
					ignoreConstraints.Add( constraint.Name , constraint.Value );
				}

				IgnoreRoute( routes , ignoreItem.Url , ignoreConstraints );
			}

			// Manipluate the Routing Table
			foreach ( RoutingItem routingItem in section.Map ) {
				var defaults = new RouteValueDictionary();
				var constraints = new RouteValueDictionary();

				if ( routingItem.Controller != string.Empty )
					defaults.Add( "controller" , routingItem.Controller );

				if ( routingItem.Action != string.Empty )
					defaults.Add( "action" , routingItem.Action );

				foreach ( Parameter param in routingItem.Paramaters ) {
					defaults.Add( param.Name , param.Value );
					if ( !string.IsNullOrEmpty( param.Constraint ) )
						constraints.Add( param.Name , param.Constraint );
				}

				MapRoute( routes , routingItem.Name , routingItem.Url , defaults , constraints );
			}
		}
Exemplo n.º 12
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (MySession.CurrentUser == null)
            {
                FormsAuthentication.SignOut();
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "Index");
                redirectTargetDictionary.Add("controller", "Account");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
            else if (MySession.CurrentUser.Type!="AD")
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "NoAccess");
                redirectTargetDictionary.Add("controller", "Home");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);

            }else
            {

                base.OnActionExecuting(filterContext);
            }
        }
Exemplo n.º 13
0
        private RouteValueDictionary CreateRouteConstraints(RouteSpecification routeSpec)
        {
            var constraints = new RouteValueDictionary();

            // Default constraints
            constraints.Add("httpMethod", new RestfulHttpMethodConstraint(routeSpec.HttpMethod));

            // Attribute-based constraints
            foreach (var constraintAttribute in routeSpec.ConstraintAttributes.Where(c => !constraints.ContainsKey(c.Key)))
                constraints.Add(constraintAttribute.Key, constraintAttribute.Constraint);

            var detokenizedUrl = DetokenizeUrl(CreateRouteUrl(routeSpec));
            var urlParameterNames = GetUrlParameterNames(detokenizedUrl);

            // Convention-based constraints
            foreach (var defaultConstraint in _configuration.DefaultRouteConstraints)
            {
                var pattern = defaultConstraint.Key;
                var matchedUrlParameterNames = urlParameterNames.Where(n => Regex.IsMatch(n, pattern));
                foreach (var urlParameterName in matchedUrlParameterNames.Where(n => !constraints.ContainsKey(n)))
                    constraints.Add(urlParameterName, defaultConstraint.Value);
            }

            return constraints;
        }
Exemplo n.º 14
0
 void Application_Start(object sender, EventArgs e)
 {
     RouteTable.Routes.RouteExistingFiles = true;
     // 在应用程序启动时运行的代码
     //RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     RouteValueDictionary defaults = new RouteValueDictionary();
     defaults.Add("name", "张三");
     RouteValueDictionary constraints = new RouteValueDictionary();
     constraints.Add("name",@"[1-10]");
     RouteValueDictionary dataTokens = new RouteValueDictionary();
     dataTokens.Add("age",22);
     dataTokens.Add("httpMethod",new HttpMethodConstraint("GET"));
     RouteTable.Routes.Ignore("Content/{filename}.css/{*pathInfo}");
     //1.
     RouteTable.Routes.MapPageRoute(
         "default",
         "Content/{name}",
         "~/Default.aspx", false, defaults,null,dataTokens
         );
     RouteTable.Routes.MapPageRoute(
     "route2",
     "Route/{age}",
     "~/Default.aspx", false, defaults, null, dataTokens
     );
     //PageRouteHandler pageRou teHandler=new PageRouteHandler(RouteTable.Routes.GetVirtualPath(null,null).VirtualPath);
     //2
     Route route=new Route("Hello/{name}",new PageRouteHandler("~/Default.aspx"));
     //PageRouteHandler  routeHandler=new PageRouteHandler();
     RouteTable.Routes.Add(route);
 }
Exemplo n.º 15
0
        public string GenerateTab(ref HtmlHelper html, string text, string value)
        {
            var routeDataValues = html.ViewContext.RequestContext.RouteData.Values;

            RouteValueDictionary pageLinkValueDictionary = new RouteValueDictionary { { Param, value } };

            if (html.ViewContext.RequestContext.HttpContext.Request.QueryString["search"] != null)
                pageLinkValueDictionary.Add("search", html.ViewContext.RequestContext.HttpContext.Request.QueryString["search"]);

            if (!pageLinkValueDictionary.ContainsKey("id") && routeDataValues.ContainsKey("id"))
                pageLinkValueDictionary.Add("id", routeDataValues["id"]);

            // To be sure we get the right route, ensure the controller and action are specified.
            if (!pageLinkValueDictionary.ContainsKey("controller") && routeDataValues.ContainsKey("controller"))
                pageLinkValueDictionary.Add("controller", routeDataValues["controller"]);

            if (!pageLinkValueDictionary.ContainsKey("action") && routeDataValues.ContainsKey("action"))
                pageLinkValueDictionary.Add("action", routeDataValues["action"]);

            // 'Render' virtual path.
            var virtualPathForArea = RouteTable.Routes.GetVirtualPathForArea(html.ViewContext.RequestContext, pageLinkValueDictionary);

            if (virtualPathForArea == null)
                return null;

            var stringBuilder = new StringBuilder("<li");

            if (value == CurrentValue)
                stringBuilder.Append(" class=active");

            stringBuilder.AppendFormat("><a href={0}>{1}</a></li>", virtualPathForArea.VirtualPath, text);

            return stringBuilder.ToString();
        }
Exemplo n.º 16
0
        public ActionResult SearchTabsPost(TabsViewModel viewModel)
        {
            var dic = new RouteValueDictionary()
                          {
                              {"tabkey", viewModel.TabKey},
                              {"tabid", viewModel.TabId},
                              {"MetalFilter", viewModel.MetalFilter},
                              {"OrderByPrice", viewModel.OrderByPrice},
                              {"itemsperpage", viewModel.ItemsPerPage}

                          };

            var counter = 0;
            if (viewModel.CustomFilters != null)
            {
                foreach (var filterValue in viewModel.CustomFilters)
                {
                    //TODO do tis strongly typed with reflaction
                    dic.Add("CustomFilters" + "[" + counter.ToString() + "].Value", filterValue.Value);
                    dic.Add("CustomFilters" + "[" + counter.ToString() + "].Name", filterValue.Name);
                    counter++;
                }
                dic.Add("page", 1);
            }
            else
            {
                dic.Add("page",viewModel.Page);
            }

            return RedirectToRoute("Tabs",dic );
        }
Exemplo n.º 17
0
 private static RouteValueDictionary Create(string action, string controller, object values)
 {
     RouteValueDictionary dict = new RouteValueDictionary(values);
     if(controller != null) dict.Add("controller", controller);
     dict.Add("action", action);
     return dict;
 }
Exemplo n.º 18
0
        public static string GetUrl(RequestContext requestContext, RouteValueDictionary routeValueDictionary)
        {
            RouteValueDictionary urlData = new RouteValueDictionary();
            UrlHelper urlHelper = new UrlHelper(requestContext);

            int i = 0;
            foreach (var item in routeValueDictionary)
            {
                if (string.Empty == item.Value as string)
                {
                    i++;
                    urlData.Add(item.Key, string.Format(ReplaceFormatString, i));
                }
                else
                {
                    urlData.Add(item.Key, item.Value);
                }
            }

            var url = urlHelper.RouteUrl(urlData);

            for (int index = 1; index <= i; index++)
            {
                url = url.Replace(string.Format(ReplaceFormatString, index), string.Empty);
            }

            return url;
        }
Exemplo n.º 19
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            MxUser mxUser = (MxUser)filterContext.HttpContext.Session["User"];
            RouteValueDictionary rvd = new RouteValueDictionary();
            if (mxUser != null)
            {
                if (!BLL.MxLicense.SeatCheck(mxUser.MbrUser.ProviderUserKey.ToString(), filterContext.HttpContext.Session.SessionID))
                {
                    //user has been kicked out and needs to login

                    //clear session
                    filterContext.HttpContext.Session.Clear();
                    FormsAuthentication.SignOut();

                    rvd.Add("msg", "noseat");
                    filterContext.Result = new RedirectToRouteResult("Login", rvd);
                }
            }
            else
            {
                //user is not logged in

                rvd.Add("msg", "session");
                filterContext.Result = new RedirectToRouteResult("Login", rvd);
            }
        }
 private void RedirectToTheLoginPage(ActionExecutedContext filterContext)
 {
     var routeValueDictionary = new RouteValueDictionary();
     routeValueDictionary.Add("controller", "Login");
     routeValueDictionary.Add("action", "Index");
     filterContext.Result = new RedirectToRouteResult(routeValueDictionary);
 }
Exemplo n.º 21
0
 public ActionResult Error()
 {
     RouteValueDictionary rd = new RouteValueDictionary();
     rd.Add("controller", "Home");
     rd.Add("action", "Index");
     return new RedirectToRouteResult("Default", rd);
 }
Exemplo n.º 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;
            //1.存在
            //
            name = this.RouteData.Values["name"] as string;
            //string rq = this.RouteData.GetRequiredString("name");
            //string rqlong =this.RouteData.Route.GetRouteData(this.Request.RequestContext.HttpContext).GetRequiredString("name");
            //string tk = this.RouteData.DataTokens["name"] as string;
            //this.Request.RequestContext.RouteData.Values.Add("name1","李四");
            RouteData rd = new RouteData();
            rd.Values.Add("age", 20);
            rd.Values.Add("name", "lifeng");
            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("name", "values");
            rvd.Add("age",12);
            RequestContext requestContext = new RequestContext();
            requestContext.HttpContext = new HttpContextWrapper(HttpContext.Current);
            requestContext.RouteData = rd;
            var p1 = RouteTable.Routes.GetVirtualPath(null, null);
            var p2 = RouteTable.Routes.GetVirtualPath(null, rvd);           //Content/values?age=12
            var p3 = RouteTable.Routes.GetVirtualPath(requestContext, null);// Content/values?age=20
            var p4 = RouteTable.Routes.GetVirtualPath(requestContext, rvd);//  Content/values?age=12
            var p5 = RouteTable.Routes.GetVirtualPath(Request.RequestContext, null);// 当前访问路径为Content/Site的时候:Content/Site

            RouteValueDictionary ra = new RouteValueDictionary();
            ra.Add("age",18);
            var p6 = RouteTable.Routes.GetVirtualPath(null, ra);
            var p7 = RouteTable.Routes.GetVirtualPath(requestContext, "route2", rvd);
        }
Exemplo n.º 23
0
 /// <summary>
 /// 添加评论
 /// </summary>
 public string AddComment(long belongId, long userId, string type)
 {
     RouteValueDictionary rvd = new RouteValueDictionary();
     rvd.Add("belongId", belongId);
     rvd.Add("userId", userId);
     rvd.Add("type", type);
     return urlHelper.Action("AddComment", "Channel", rvd);
 }
Exemplo n.º 24
0
        public static string ScaffoldUrl(this UrlHelper url, string tableName, string action, RouteValueDictionary routeValues)
        {
            RouteValueDictionary finalValues = new RouteValueDictionary(routeValues ?? new RouteValueDictionary());
            finalValues.Add("table", tableName);
            finalValues.Add("action", action);

            return url.RouteUrl(finalValues);
        }
Exemplo n.º 25
0
        public static ActionResult RedirectToScaffold(this Controller controller, string tableName, string action, RouteValueDictionary routeValues)
        {
            RouteValueDictionary finalValues = new RouteValueDictionary(routeValues ?? new RouteValueDictionary());
            finalValues.Add("table", tableName);
            finalValues.Add("action", action);

            return new RedirectToRouteResult(finalValues);
        }
 public ActionResult ChangeTheme(string theme, string Name)
 {
     themeRepository.SetThemeByName(Name, Int16.Parse(theme));
     RouteValueDictionary routeValues = new RouteValueDictionary();
     routeValues.Add("Name", Name);
     routeValues.Add("ViewType", "One");
     return RedirectToAction("Details",routeValues);
 }
Exemplo n.º 27
0
        public string GenerateKey(ControllerContext context, CacheSettings cacheSettings)
        {
            var actionName = context.RouteData.Values["action"].ToString();
            var controllerName = context.RouteData.Values["controller"].ToString();

            // remove controller, action and DictionaryValueProvider which is added by the framework for child actions
            var filteredRouteData = context.RouteData.Values.Where(x => x.Key.ToLowerInvariant() != "controller" &&
                                                                   x.Key.ToLowerInvariant() != "action" &&
                                                                   !(x.Value is DictionaryValueProvider<object>));

            var routeValues = new RouteValueDictionary(filteredRouteData.ToDictionary(x => x.Key.ToLowerInvariant(), x => x.Value));

            if (!context.IsChildAction)
            {
                // note that route values take priority over form values and form values take priority over query string values

                foreach (var formKey in context.HttpContext.Request.Form.AllKeys)
                {
                    if (!routeValues.ContainsKey(formKey.ToLowerInvariant()))
                    {
                        routeValues.Add(formKey.ToLowerInvariant(),
                                        context.HttpContext.Request.Form[formKey].ToLowerInvariant());
                    }
                }

                foreach (var queryStringKey in context.HttpContext.Request.QueryString.AllKeys)
                {
                    // queryStringKey is null if url has qs name without value. e.g. test.com?q
                    if (queryStringKey != null && !routeValues.ContainsKey(queryStringKey.ToLowerInvariant()))
                    {
                        routeValues.Add(queryStringKey.ToLowerInvariant(),
                                        context.HttpContext.Request.QueryString[queryStringKey].ToLowerInvariant());
                    }
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByParam))
            {
                if (cacheSettings.VaryByParam.ToLowerInvariant() == "none")
                {
                    routeValues.Clear();
                }
                else if (cacheSettings.VaryByParam != "*")
                {
                    var parameters = cacheSettings.VaryByParam.ToLowerInvariant().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    routeValues = new RouteValueDictionary(routeValues.Where(x => parameters.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value));
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByCustom))
            {
                routeValues.Add(cacheSettings.VaryByCustom.ToLowerInvariant(), context.HttpContext.ApplicationInstance.GetVaryByCustomString(HttpContext.Current, cacheSettings.VaryByCustom));
            }

            var key = _keyBuilder.BuildKey(controllerName, actionName, routeValues);

            return key;
        }
Exemplo n.º 28
0
        public static ActionResult TransferToAction(this Controller ctrl, string controller, string action)
        {
            RouteValueDictionary dict = new RouteValueDictionary();
            dict.Add("controller", controller);
            dict.Add("action", action);
            TransferToRouteResult result = new TransferToRouteResult(dict);
            return result;

        }
Exemplo n.º 29
0
 //public Pagination(int currentPage, int totalPages, string action, string controller, object routeValues = null, string pageQueryString = "page")
 //{
 //    RouteValueDictionary routeDictionary = new RouteValueDictionary(routeValues);
 //    routeDictionary.Add("controller", controller);
 //    routeDictionary.Add("action", action);
 //    this.Init(currentPage, totalPages, routeDictionary, pageQueryString);
 //}
 public Pagination(int currentPage, int count, int pageSize, string action, string controller, object routeValues = null, string pageQueryString = "page")
 {
     RouteValueDictionary routeDictionary = new RouteValueDictionary(routeValues);
     routeDictionary.Add("controller", controller);
     routeDictionary.Add("action", action);
     int totalPages = (int)Math.Ceiling((decimal)count / pageSize);
     this.PageSize = pageSize;
     this.Init(currentPage, totalPages, routeDictionary, pageQueryString);
 }
Exemplo n.º 30
0
        public ActionResult Delete(string id)
        {
            var routeValues = new RouteValueDictionary();
            routeValues.Add("Controller", "User");
            routeValues.Add("Action", "Index");

            userRepository.Delete(id);

            return new RedirectToRouteResult(routeValues);
        }
Exemplo n.º 31
0
        public ActionResult GlobalLookup(GlobalLookupViewModel model)
        {
            var gService = new GlobalLookupService();

            if (ModelState.IsValid)
            {
                var gdata = new Global_Lookup_Data();
                if (model.operation == Operation.U || model.operation == Operation.D)
                {
                    var cri = new GlobalLookupCriteria();
                    cri.Lookup_Data_ID = model.Lookup_Data_ID;
                    var result = gService.GetGlobalLookupData(cri);
                    if (result.Code == ReturnCode.SUCCESS)
                    {
                        var gdatas = result.Object as List <Global_Lookup_Data>;
                        if (gdatas != null && gdatas.Count() == 1)
                        {
                            gdata = gdatas.FirstOrDefault();
                        }
                    }
                }

                if (model.operation != Operation.D)
                {
                    gdata.Def_ID    = model.Def_ID.Value;
                    gdata.Data_Code = model.Data_Code;
                    gdata.Name      = model.Name;
                }

                if (model.operation == Operation.C)
                {
                    gdata.Record_Status = Record_Status.Active;
                    model.result        = gService.InsertGlobalLookupData(gdata);
                }
                else if (model.operation == Operation.U)
                {
                    model.result = gService.UpdateGlobalLookupData(gdata);
                }
                else if (model.operation == Operation.D)
                {
                    gdata.Record_Status = Record_Status.Delete;
                    model.result        = gService.UpdateGlobalLookupData(gdata);
                    if (model.result.Code == ReturnCode.SUCCESS)
                    {
                        model.result = new ServiceResult()
                        {
                            Code = ReturnCode.SUCCESS, Msg = Success.GetMessage(ReturnCode.SUCCESS_DELETE), Field = Resource.Global_Lookup
                        }
                    }
                    ;
                    else
                    {
                        model.result = new ServiceResult()
                        {
                            Code = ReturnCode.ERROR_DELETE, Msg = Error.GetMessage(ReturnCode.ERROR_DELETE), Field = Resource.Global_Lookup
                        }
                    };

                    var route = new RouteValueDictionary(model.result);
                    route.Add("search_Def_ID", gdata.Def_ID);
                    return(RedirectToAction("GlobalLookup", route));
                }

                if (model.result.Code == ReturnCode.SUCCESS)
                {
                    var route = new RouteValueDictionary(model.result);
                    route.Add("search_Def_ID", model.Def_ID);
                    return(RedirectToAction("GlobalLookup", route));
                }
            }

            var cService = new ComboService();

            model.cGlobalDefList = cService.LstLookupDef();
            if (model.cGlobalDefList.Count > 0 && !model.search_Def_ID.HasValue)
            {
                model.search_Def_ID = NumUtil.ParseInteger(model.cGlobalDefList[0].Value);
            }

            if (model.search_Def_ID.HasValue)
            {
                var cri    = new GlobalLookupCriteria();
                var result = gService.GetGlobalLookupData(cri);
                if (result.Code == ReturnCode.SUCCESS)
                {
                    model.GlobalDataList = result.Object as List <Global_Lookup_Data>;
                }
            }
            return(View(model));
        }
    }
 public void UnbindModel(RouteValueDictionary routeValueDictionary, string routeName, object routeValue)
 {
     routeValueDictionary.Add(routeName, routeValue);
 }
        private bool MatchComplexSegmentCore(TemplateSegment routeSegment,
                                             string requestSegment,
                                             IReadOnlyDictionary <string, object> defaults,
                                             RouteValueDictionary values,
                                             int indexOfLastSegmentUsed)
        {
            Debug.Assert(routeSegment != null);
            Debug.Assert(routeSegment.Parts.Count > 1);

            // Find last literal segment and get its last index in the string
            var lastIndex = requestSegment.Length;

            TemplatePart parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value
            TemplatePart lastLiteral         = null; // Keeps track of the left-most literal we've encountered

            var outValues = new RouteValueDictionary();

            while (indexOfLastSegmentUsed >= 0)
            {
                var newLastIndex = lastIndex;

                var part = routeSegment.Parts[indexOfLastSegmentUsed];
                if (part.IsParameter)
                {
                    // Hold on to the parameter so that we can fill it in when we locate the next literal
                    parameterNeedsValue = part;
                }
                else
                {
                    Debug.Assert(part.IsLiteral);
                    lastLiteral = part;

                    var startIndex = lastIndex - 1;
                    // If we have a pending parameter subsegment, we must leave at least one character for that
                    if (parameterNeedsValue != null)
                    {
                        startIndex--;
                    }

                    if (startIndex < 0)
                    {
                        return(false);
                    }

                    var indexOfLiteral = requestSegment.LastIndexOf(part.Text,
                                                                    startIndex,
                                                                    StringComparison.OrdinalIgnoreCase);
                    if (indexOfLiteral == -1)
                    {
                        // If we couldn't find this literal index, this segment cannot match
                        return(false);
                    }

                    // If the first subsegment is a literal, it must match at the right-most extent of the request URI.
                    // Without this check if your route had "/Foo/" we'd match the request URI "/somethingFoo/".
                    // This check is related to the check we do at the very end of this function.
                    if (indexOfLastSegmentUsed == (routeSegment.Parts.Count - 1))
                    {
                        if ((indexOfLiteral + part.Text.Length) != requestSegment.Length)
                        {
                            return(false);
                        }
                    }

                    newLastIndex = indexOfLiteral;
                }

                if ((parameterNeedsValue != null) &&
                    (((lastLiteral != null) && (part.IsLiteral)) || (indexOfLastSegmentUsed == 0)))
                {
                    // If we have a pending parameter that needs a value, grab that value

                    int parameterStartIndex;
                    int parameterTextLength;

                    if (lastLiteral == null)
                    {
                        if (indexOfLastSegmentUsed == 0)
                        {
                            parameterStartIndex = 0;
                        }
                        else
                        {
                            parameterStartIndex = newLastIndex;
                            Debug.Assert(false, "indexOfLastSegementUsed should always be 0 from the check above");
                        }
                        parameterTextLength = lastIndex;
                    }
                    else
                    {
                        // If we're getting a value for a parameter that is somewhere in the middle of the segment
                        if ((indexOfLastSegmentUsed == 0) && (part.IsParameter))
                        {
                            parameterStartIndex = 0;
                            parameterTextLength = lastIndex;
                        }
                        else
                        {
                            parameterStartIndex = newLastIndex + lastLiteral.Text.Length;
                            parameterTextLength = lastIndex - parameterStartIndex;
                        }
                    }

                    var parameterValueString = requestSegment.Substring(parameterStartIndex, parameterTextLength);

                    if (string.IsNullOrEmpty(parameterValueString))
                    {
                        // If we're here that means we have a segment that contains multiple sub-segments.
                        // For these segments all parameters must have non-empty values. If the parameter
                        // has an empty value it's not a match.
                        return(false);
                    }
                    else
                    {
                        // If there's a value in the segment for this parameter, use the subsegment value
                        outValues.Add(parameterNeedsValue.Name, parameterValueString);
                    }

                    parameterNeedsValue = null;
                    lastLiteral         = null;
                }

                lastIndex = newLastIndex;
                indexOfLastSegmentUsed--;
            }

            // If the last subsegment is a parameter, it's OK that we didn't parse all the way to the left extent of
            // the string since the parameter will have consumed all the remaining text anyway. If the last subsegment
            // is a literal then we *must* have consumed the entire text in that literal. Otherwise we end up matching
            // the route "Foo" to the request URI "somethingFoo". Thus we have to check that we parsed the *entire*
            // request URI in order for it to be a match.
            // This check is related to the check we do earlier in this function for LiteralSubsegments.
            if (lastIndex == 0 || routeSegment.Parts[0].IsParameter)
            {
                foreach (var item in outValues)
                {
                    values.Add(item.Key, item.Value);
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 34
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (PagerContext == null)
            {
                return;
            }
            if (String.IsNullOrEmpty(ControllerName) || String.IsNullOrEmpty(ActionName))
            {
                throw new Exception("controllerName and actionName must be specified for PageLinks.");
            }
            if (PagerContext.PageCount <= 1)
            {
                return;
            }

            var builder = new StringBuilder();

            if (String.IsNullOrEmpty(MoreTextClass))
            {
                builder.Append($"<li><span class=\"page-link\">{Resources.More}:</span></li>");
            }
            else
            {
                builder.Append($"<li><span class=\"page-link {MoreTextClass}\">{Resources.More}</span></li>");
            }

            if (PagerContext.PageIndex != 1 && Low != 1)
            {
                // first page link
                builder.Append("<li class=\"page-item\">");
                var firstRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = 1 });
                if (RouteParameters != null)
                {
                    foreach (var item in RouteParameters)
                    {
                        firstRouteDictionary.Add(item.Key, item.Value);
                    }
                }
                var firstLink = _htmlGenerator.GenerateActionLink(ViewContext, "|«", ActionName, ControllerName, null, null, null,
                                                                  firstRouteDictionary, new { title = Resources.First, @class = "page-link" });
                builder.Append(GetString(firstLink));
                builder.Append("</li>");
                if (PagerContext.PageIndex > 2)
                {
                    // previous page link
                    var previousIndex = PagerContext.PageIndex - 1;
                    if (Low != 0)
                    {
                        previousIndex = Low - 1;
                    }
                    builder.Append("<li class=\"page-item\">");
                    var previousRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = previousIndex });
                    if (RouteParameters != null)
                    {
                        foreach (var item in RouteParameters)
                        {
                            previousRouteDictionary.Add(item.Key, item.Value);
                        }
                    }
                    var previousLink = _htmlGenerator.GenerateActionLink(ViewContext, "«", ActionName, ControllerName, null, null, null, previousRouteDictionary, new { title = Resources.Previous, rel = "prev", @class = "page-link" });
                    builder.Append(GetString(previousLink));
                    builder.Append("</li>");
                }
            }

            if (Low == 0 || High == 0)
            {
                // not a multipage set of links used in partial page
                // calc low and high limits for numeric links
                var low  = PagerContext.PageIndex - 1;
                var high = PagerContext.PageIndex + 3;
                if (low < 1)
                {
                    low = 1;
                }
                if (high > PagerContext.PageCount)
                {
                    high = PagerContext.PageCount;
                }
                if (high - low < 5)
                {
                    while ((high < low + 4) && high < PagerContext.PageCount)
                    {
                        high++;
                    }
                }
                if (high - low < 5)
                {
                    while ((low > high - 4) && low > 1)
                    {
                        low--;
                    }
                }
                for (var x = low; x < high + 1; x++)
                {
                    // numeric links
                    if (x == PagerContext.PageIndex)
                    {
                        if (String.IsNullOrEmpty(CurrentTextClass))
                        {
                            builder.Append($"<li class=\"page-item active\"><span class=\"page-link\">{x} of {PagerContext.PageCount}</span></li>");
                        }
                        else
                        {
                            builder.Append($"<li class=\"page-item {CurrentTextClass}\"><span class=\"page-link\">{x} of {PagerContext.PageCount}</span></li>");
                        }
                    }
                    else
                    {
                        builder.Append("<li>");
                        var numericRouteDictionary = new RouteValueDictionary {
                            { "controller", ControllerName }, { "action", ActionName }, { "page", x }
                        };
                        if (RouteParameters != null)
                        {
                            foreach (var item in RouteParameters)
                            {
                                numericRouteDictionary.Add(item.Key, item.Value);
                            }
                        }
                        var link = _htmlGenerator.GenerateActionLink(ViewContext, x.ToString(), ActionName, ControllerName, null, null, null, numericRouteDictionary, new { @class = "page-link" });
                        builder.Append(GetString(link));
                        builder.Append("</li>");
                    }
                }
            }
            else
            {
                // multipage set of links used in partial page
                // calc low and high limits for numeric links
                var calcLow  = PagerContext.PageIndex - 1;
                var calcHigh = PagerContext.PageIndex + 3;
                if (calcLow < 1)
                {
                    calcLow = 1;
                }
                if (calcHigh > PagerContext.PageCount)
                {
                    calcHigh = PagerContext.PageCount;
                }
                if (calcHigh - calcLow < 5)
                {
                    while ((calcHigh < calcLow + 4) && calcHigh < PagerContext.PageCount)
                    {
                        calcHigh++;
                    }
                }
                if (calcHigh - calcLow < 5)
                {
                    while ((calcLow > calcHigh - 4) && calcLow > 1)
                    {
                        calcLow--;
                    }
                }
                var isRangeRendered = false;
                for (var x = calcLow; x < calcHigh + 1; x++)
                {
                    // numeric links
                    if (x >= Low && x <= High)
                    {
                        if (!isRangeRendered)
                        {
                            isRangeRendered = true;
                            if (String.IsNullOrEmpty(CurrentTextClass))
                            {
                                builder.Append($"<li class=\"active\"><span class=\"page-link\">{Low}-{High} of {PagerContext.PageCount}</span></li>");
                            }
                            else
                            {
                                builder.Append($"<li class=\"active {CurrentTextClass}\"><span class=\"page-link\">{Low}-{High} of {PagerContext.PageCount}</span></li>");
                            }
                        }
                    }
                    else
                    {
                        builder.Append("<li class=\"page-item\">");
                        var numericRouteDictionary = new RouteValueDictionary {
                            { "controller", ControllerName }, { "action", ActionName }, { "page", x }
                        };
                        if (RouteParameters != null)
                        {
                            foreach (var item in RouteParameters)
                            {
                                numericRouteDictionary.Add(item.Key, item.Value);
                            }
                        }
                        var link = _htmlGenerator.GenerateActionLink(ViewContext, x.ToString(), ActionName, ControllerName, null, null, null, numericRouteDictionary, new { @class = "page-link" });
                        builder.Append(GetString(link));
                        builder.Append("</li>");
                    }
                }
            }

            if (PagerContext.PageIndex != PagerContext.PageCount && High < PagerContext.PageCount)
            {
                if (PagerContext.PageIndex < PagerContext.PageCount - 1)
                {
                    // next page link
                    var nextIndex = PagerContext.PageIndex + 1;
                    builder.Append("<li class=\"page-item\">");
                    var nextRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = nextIndex });
                    if (RouteParameters != null)
                    {
                        foreach (var item in RouteParameters)
                        {
                            nextRouteDictionary.Add(item.Key, item.Value);
                        }
                    }
                    var nextLink = _htmlGenerator.GenerateActionLink(ViewContext, "»", ActionName, ControllerName, null, null, null, nextRouteDictionary, new { title = Resources.Next, rel = "next", @class = "page-link" });
                    builder.Append(GetString(nextLink));
                    builder.Append("</li>");
                }
                // last page link
                builder.Append("<li class=\"page-item\">");
                var lastRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = PagerContext.PageCount });
                if (RouteParameters != null)
                {
                    foreach (var item in RouteParameters)
                    {
                        lastRouteDictionary.Add(item.Key, item.Value);
                    }
                }
                var lastLink = _htmlGenerator.GenerateActionLink(ViewContext, "»|", ActionName, ControllerName, null, null, null, lastRouteDictionary, new { title = Resources.Last, @class = "page-link" });
                builder.Append(GetString(lastLink));
                builder.Append("</li>");
            }

            output.TagMode = TagMode.StartTagAndEndTag;
            output.TagName = "ul";
            if (!String.IsNullOrWhiteSpace(Class))
            {
                output.Attributes.Add("class", Class);
            }
            output.Content.AppendHtml(builder.ToString());
        }
Exemplo n.º 35
0
 public static RouteValueDictionary AppendContext(AjaxHelper ajaxHelper, RouteValueDictionary routeValues)
 {
     routeValues.Add("context", ajaxHelper.ViewData["context"].ToJson());
     return(routeValues);
 }
Exemplo n.º 36
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie

            /*app.UseCookieAuthentication(new CookieAuthenticationOptions
             * {
             *  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
             *  LoginPath = new PathString("/Account/Login"),
             *  Provider = new CookieAuthenticationProvider
             *  {
             *      // Enables the application to validate the security stamp when the user logs in.
             *      // This is a security feature which is used when you change a password or add an external login to your account.
             *      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
             *          validateInterval: TimeSpan.FromMinutes(30),
             *          regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
             *  }
             * });    */


            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);

            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            var originalHandler = provider.OnApplyRedirect;

            //Our logic to dynamically modify the path
            provider.OnApplyRedirect = context =>
            {
                var mvcContext = new HttpContextWrapper(HttpContext.Current);
                var routeData  = RouteTable.Routes.GetRouteData(mvcContext);

                //Get the current language
                RouteValueDictionary routeValues = new RouteValueDictionary();
                routeValues.Add("language", routeData.Values["language"]);

                //Reuse the RetrunUrl
                Uri    uri       = new Uri(context.RedirectUri);
                string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);

                //Overwrite the redirection uri
                context.RedirectUri = url.Action("Login", "Account", routeValues);
                originalHandler.Invoke(context);
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(url.Action("Login", "Account")),
                //Set the Provider
                Provider = provider
            });


            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 37
0
        public HtmlString Pager(string actioName, string controllerName, object routeValues, int page, int pageSize, int totalItems, Action <IPagerBuilder> options = null)
        {
            var pagerOptions = new PagerBuilder();

            options?.Invoke(pagerOptions);

            var rootUlElement = new TagBuilder("ul");

            rootUlElement.AddCssClass("pagination");

            var howMuchPagesPerPager = 5;

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

            var mergedRouteValues = new RouteValueDictionary(routeValues ?? new {});

            foreach (var mergedRouteValue in mergedRouteValues.ToList())
            {
                if (mergedRouteValue.Key.ToLowerInvariant() == "page")
                {
                    mergedRouteValues.Remove(mergedRouteValue.Key);
                }
            }

            foreach (
                var additionalRoute in pagerOptions.AdditionalRoutes ?? Enumerable.Empty <KeyValuePair <string, Object> >()
                )
            {
                if (additionalRoute.Key.ToLowerInvariant() == "page")
                {
                    continue;
                }

                mergedRouteValues.Add(additionalRoute.Key, additionalRoute.Value);
            }


            Func <int, string> buildUrlForPage = pageNo =>
            {
                var finalRoute = new RouteValueDictionary(mergedRouteValues)
                {
                    { "page", pageNo }
                };

                return(urlHelper.Action(new UrlActionContext
                {
                    Action = actioName,
                    Controller = controllerName,
                    Values = finalRoute
                }));
            };

            var totalPages = totalItems / pageSize + 1;

            if (page > totalPages)
            {
                page = totalPages;
            }
            if (page < 1)
            {
                page = 1;
            }
            var pagesToProcess = new LinkedList <int>();


            var firstPage = Math.Max(page - howMuchPagesPerPager / 2, 1);

            for (var i = firstPage; i < page; i++)
            {
                pagesToProcess.AddLast(i);
            }

            pagesToProcess.AddFirst(page);

            var lastPage = Math.Min(totalPages, page + howMuchPagesPerPager / 2);

            for (var i = page + 1; i < lastPage; i++)
            {
                pagesToProcess.AddLast(i);
            }

            while (pagesToProcess.Count < howMuchPagesPerPager && lastPage < totalPages)
            {
                lastPage += 1;
                pagesToProcess.AddLast(lastPage);
            }

            while (pagesToProcess.Count < howMuchPagesPerPager && firstPage > 1)
            {
                lastPage -= 1;
                pagesToProcess.AddFirst(lastPage);
            }

            var prevButton = new TagBuilder("li");

            prevButton.AddCssClass("paginate_button");
            prevButton.AddCssClass("previous");
            var aPrevButton = new TagBuilder("a");

            aPrevButton.InnerHtml.SetContent("Previous");
            if (page > 1)
            {
                aPrevButton.Attributes["href"] = buildUrlForPage(page - 1);
            }
            else
            {
                prevButton.AddCssClass("disabled");
            }

            prevButton.InnerHtml.SetHtmlContent(aPrevButton);
            rootUlElement.InnerHtml.AppendHtml(prevButton);


            foreach (var pageToProcess in pagesToProcess)
            {
                var li = new TagBuilder("li");
                li.AddCssClass("paginate_button");
                if (pageToProcess == page)
                {
                    li.AddCssClass("active");
                }

                var a = new TagBuilder("a");
                a.Attributes["href"] = buildUrlForPage(pageToProcess);
                a.InnerHtml.SetContent(pageToProcess.ToString("D"));

                li.InnerHtml.SetHtmlContent(a);

                rootUlElement.InnerHtml.AppendHtml(li);
            }


            var nextButton = new TagBuilder("li");

            nextButton.AddCssClass("paginate_button");
            nextButton.AddCssClass("next");
            var aNextButton = new TagBuilder("a");

            aNextButton.InnerHtml.SetContent("Previous");
            if (page < totalPages)
            {
                aNextButton.Attributes["href"] = buildUrlForPage(page - 1);
            }
            else
            {
                nextButton.AddCssClass("disabled");
            }

            nextButton.InnerHtml.SetHtmlContent(aNextButton);
            rootUlElement.InnerHtml.AppendHtml(nextButton);


            return(new HtmlString(rootUlElement.ToString()));
        }
Exemplo n.º 38
0
        public ActionResult EditPOST(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            var    user         = Services.ContentManager.Get <UserPart>(id, VersionOptions.DraftRequired);
            string previousName = user.UserName;

            var shellSettings = this.Services.WorkContext.Resolve <ShellSettings>();
            var siteSettings  = _siteService.GetSiteSettings();

            if (!string.IsNullOrEmpty(shellSettings.RequestUrlPrefix) && string.Equals(user.UserName, siteSettings.SuperUser, StringComparison.Ordinal))
            {
                throw new OrchardSecurityException(T("You don't have permission to moderate the user"));
            }

            var model = Services.ContentManager.UpdateEditor(user, this);

            var editModel = new UserEditViewModel {
                User = user
            };

            if (TryUpdateModel(editModel))
            {
                if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email))
                {
                    AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
                }
                else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase))
                {
                    // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                    ModelState.AddModelError("Email", T("You must specify a valid email address."));
                }
                else
                {
                    // also update the Super user if this is the renamed account
                    if (String.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal))
                    {
                        _siteService.GetSiteSettings().As <SiteSettingsPart>().SuperUser = editModel.UserName;
                    }

                    user.NormalizedUserName = editModel.UserName.ToLowerInvariant();
                }
            }

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null);
                editor.Metadata.Position = "2";
                model.Content.Add(editor);

                return(View(model));
            }

            Services.ContentManager.Publish(user.ContentItem);

            RouteValueDictionary activityStreamRouteValues = new RouteValueDictionary();

            activityStreamRouteValues.Add("action", "Display");
            activityStreamRouteValues.Add("controller", "User");
            activityStreamRouteValues.Add("area", "orchard.crm.Project");
            activityStreamRouteValues.Add("userId", user.Id);

            string changeDescription = string.Format(CultureInfo.CurrentUICulture, "Update user '{0}'", CRMHelper.GetFullNameOfUser(user));

            this.activityStreamService.WriteChangesToStreamActivity(Services.WorkContext.CurrentUser.Id, user.Id, user.ContentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, changeDescription, activityStreamRouteValues);

            return(RedirectToAction("Display", new { Controller = "User", area = "Orchard.CRM.Project", userId = user.Id }));
        }
Exemplo n.º 39
0
        public ActionResult CreatePOST(UserCreateViewModel createModel)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (!string.IsNullOrEmpty(createModel.UserName))
            {
                if (!_userService.VerifyUserUnicity(createModel.UserName, createModel.Email))
                {
                    AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
                }
            }

            if (!Regex.IsMatch(createModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase))
            {
                // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                ModelState.AddModelError("Email", T("You must specify a valid email address."));
            }

            if (createModel.Password != createModel.ConfirmPassword)
            {
                AddModelError("ConfirmPassword", T("Password confirmation must match"));
            }

            var user = Services.ContentManager.New <IUser>("User");

            if (ModelState.IsValid)
            {
                user = _membershipService.CreateUser(new CreateUserParams(
                                                         createModel.UserName,
                                                         createModel.Password,
                                                         createModel.Email,
                                                         null, null, true));
            }

            var model = Services.ContentManager.UpdateEditor(user, this);

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: createModel, Prefix: null);
                editor.Metadata.Position = "2";
                model.Content.Add(editor);

                return(View(model));
            }

            RouteValueDictionary activityStreamRouteValues = new RouteValueDictionary();

            activityStreamRouteValues.Add("action", "Display");
            activityStreamRouteValues.Add("controller", "User");
            activityStreamRouteValues.Add("area", "orchard.crm.Project");
            activityStreamRouteValues.Add("userId", user.Id);

            string changeDescription = string.Format(CultureInfo.CurrentUICulture, "Creates new user '{0}'", CRMHelper.GetFullNameOfUser(user));

            this.activityStreamService.WriteChangesToStreamActivity(Services.WorkContext.CurrentUser.Id, user.Id, user.ContentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, changeDescription, activityStreamRouteValues);

            string actionName = this.crmContentOwnershipService.IsOperator(user.Id) ? "Operators" : "Customers";

            return(RedirectToAction(actionName, new { Controller = "User", area = "Orchard.CRM.Project" }));
        }
        public void InitializeHttpFunctionRoutes(IScriptJobHost host)
        {
            var routesLogBuilder = new StringBuilder();

            routesLogBuilder.AppendLine("Initializing function HTTP routes");

            _router.ClearRoutes();

            // TODO: FACAVAL Instantiation of the ScriptRouteHandler should be cleaned up
            WebJobsRouteBuilder routesBuilder = _router.CreateBuilder(new ScriptRouteHandler(_loggerFactory, host, _environment, false), _httpOptions.Value.RoutePrefix);

            WebJobsRouteBuilder warmupRouteBuilder = null;

            if (!_environment.IsLinuxConsumption() && !_environment.IsWindowsConsumption())
            {
                warmupRouteBuilder = _router.CreateBuilder(new ScriptRouteHandler(_loggerFactory, host, _environment, isWarmup: true), routePrefix: "admin");
            }

            foreach (var function in host.Functions)
            {
                var httpTrigger = function.HttpTriggerAttribute;
                if (httpTrigger != null)
                {
                    var constraints = new RouteValueDictionary();
                    if (httpTrigger.Methods != null)
                    {
                        constraints.Add("httpMethod", new HttpMethodRouteConstraint(httpTrigger.Methods));
                    }

                    string route = httpTrigger.Route;

                    if (string.IsNullOrEmpty(route))
                    {
                        route = function.Name;
                    }

                    routesBuilder.MapFunctionRoute(function.Metadata.Name, route, constraints, function.Metadata.Name);

                    LogRouteMap(routesLogBuilder, function.Metadata.Name, route, httpTrigger.Methods, _httpOptions.Value.RoutePrefix);
                }
                else if (warmupRouteBuilder != null && function.IsWarmupFunction())
                {
                    warmupRouteBuilder.MapFunctionRoute(function.Metadata.Name, "warmup", function.Metadata.Name);
                }
            }

            IRouter proxyRouter    = null;
            IRouter functionRouter = null;

            if (routesBuilder.Count == 0)
            {
                routesLogBuilder.AppendLine("No HTTP routes mapped");
            }
            else
            {
                functionRouter = routesBuilder.Build();
            }

            _router.AddFunctionRoutes(functionRouter, proxyRouter);

            if (warmupRouteBuilder != null)
            {
                // Adding the default admin/warmup route when no warmup function is present
                if (warmupRouteBuilder.Count == 0)
                {
                    warmupRouteBuilder.MapFunctionRoute(string.Empty, "warmup", string.Empty);
                }
                IRouter warmupRouter = warmupRouteBuilder.Build();
                _router.AddFunctionRoutes(warmupRouter, null);
            }

            ILogger logger = _loggerFactory.CreateLogger <WebScriptHostHttpRoutesManager>();

            logger.LogInformation(routesLogBuilder.ToString());
        }
        internal static Uri GetODataBatchBaseUri(this HttpRequest request, string oDataRouteName, IRouter route)
        {
            Contract.Assert(request != null);

            if (oDataRouteName == null)
            {
                // Return request's base address.
                return(new Uri(request.GetDisplayUrl()));
            }

            HttpContext context = request.HttpContext;

#if !NETSTANDARD2_0
            // Here's workaround to help "EndpointLinkGenerator" to generator
            ODataBatchPathMapping batchMapping = request.HttpContext.RequestServices.GetRequiredService <ODataBatchPathMapping>();
            if (batchMapping.IsEndpointRouting)
            {
                context = new DefaultHttpContext
                {
                    RequestServices = request.HttpContext.RequestServices,
                };

                IEndpointFeature endpointFeature = new ODataEndpointFeature();
                endpointFeature.Endpoint = new Endpoint((d) => null, null, "anything");
                context.Features.Set(endpointFeature);

                context.Request.Scheme = request.Scheme;
                context.Request.Host   = request.Host;
            }

            context.Request.ODataFeature().RouteName = oDataRouteName;
#endif

            // The IActionContextAccessor and ActionContext will be present after routing but not before
            // GetUrlHelper only uses the HttpContext and the Router, which we have so construct a dummy
            // action context.
            ActionContext actionContext = new ActionContext
            {
                HttpContext      = context,
                RouteData        = new RouteData(),
                ActionDescriptor = new ActionDescriptor()
            };

            actionContext.RouteData.Routers.Add(route);
            IUrlHelperFactory factory = request.HttpContext.RequestServices.GetRequiredService <IUrlHelperFactory>();
            IUrlHelper        helper  = factory.GetUrlHelper(actionContext);

            RouteValueDictionary routeData = new RouteValueDictionary()
            {
                { ODataRouteConstants.ODataPath, String.Empty }
            };
            RouteValueDictionary batchRouteData = request.ODataFeature().BatchRouteData;
            if (batchRouteData != null && batchRouteData.Any())
            {
                foreach (var data in batchRouteData)
                {
                    routeData.Add(data.Key, data.Value);
                }
            }

            string baseAddress = helper.Link(oDataRouteName, routeData);
            if (baseAddress == null)
            {
                throw new InvalidOperationException(SRResources.UnableToDetermineBaseUrl);
            }
            return(new Uri(baseAddress));
        }
Exemplo n.º 42
0
        public ActionResult ProductDetails(int productId, string attributes, ProductVariantQuery query)
        {
            var product = _productService.GetProductById(productId);

            if (product == null || product.Deleted || product.IsSystemProduct)
            {
                return(HttpNotFound());
            }

            // Is published? Check whether the current user has a "Manage catalog" permission.
            // It allows him to preview a product before publishing.
            if (!product.Published && !_services.Permissions.Authorize(Permissions.Catalog.Product.Read))
            {
                return(HttpNotFound());
            }

            // ACL (access control list)
            if (!_aclService.Authorize(product))
            {
                return(HttpNotFound());
            }

            // Store mapping
            if (!_storeMappingService.Authorize(product))
            {
                return(HttpNotFound());
            }

            // Is product individually visible?
            if (product.Visibility == ProductVisibility.Hidden)
            {
                // Find parent grouped product.
                var parentGroupedProduct = _productService.GetProductById(product.ParentGroupedProductId);
                if (parentGroupedProduct == null)
                {
                    return(HttpNotFound());
                }

                var seName = parentGroupedProduct.GetSeName();
                if (seName.IsEmpty())
                {
                    return(HttpNotFound());
                }

                var routeValues = new RouteValueDictionary();
                routeValues.Add("SeName", seName);

                // Add query string parameters.
                Request.QueryString.AllKeys.Each(x => routeValues.Add(x, Request.QueryString[x]));

                return(RedirectToRoute("Product", routeValues));
            }

            // Prepare the view model
            var model = _helper.PrepareProductDetailsPageModel(product, query);

            // Some cargo data
            model.PictureSize          = _mediaSettings.ProductDetailsPictureSize;
            model.CanonicalUrlsEnabled = _seoSettings.CanonicalUrlsEnabled;

            // Save as recently viewed
            _recentlyViewedProductsService.AddProductToRecentlyViewedList(product.Id);

            // Activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewProduct", T("ActivityLog.PublicStore.ViewProduct"), product.Name);

            // Breadcrumb
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadcrumb(_breadcrumb, ControllerContext, product);

                _breadcrumb.Track(new MenuItem
                {
                    Text     = model.Name,
                    Rtl      = model.Name.CurrentLanguage.Rtl,
                    EntityId = product.Id,
                    Url      = Url.RouteUrl("Product", new { model.SeName })
                });
            }

            return(View(model.ProductTemplateViewPath, model));
        }
        public void ShouldNotAuthExpiredDelegate()
        {
            string       hdid         = "The User HDID";
            string       resourceHDID = "The Resource HDID";
            string       token        = "Fake Access Token";
            string       userId       = "User ID";
            string       username     = "******";
            string       scopes       = "user/Observation.read";
            List <Claim> claims       = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(GatewayClaims.HDID, hdid),
                new Claim(GatewayClaims.Scope, scopes),
            };
            ClaimsIdentity  identity        = new ClaimsIdentity(claims, "TestAuth");
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
            PatientModel    patientModel    = new PatientModel()
            {
                Birthdate = DateTime.Now
                            .AddYears(MaxDependentAge * -1)
            };
            RequestResult <PatientModel> getPatientResult =
                new RequestResult <PatientModel>(patientModel, ResultType.Success);

            IHeaderDictionary headerDictionary = new HeaderDictionary();

            headerDictionary.Add("Authorization", token);
            RouteValueDictionary routeValues = new RouteValueDictionary();

            routeValues.Add("hdid", resourceHDID);
            Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary);
            httpRequestMock.Setup(s => s.RouteValues).Returns(routeValues);

            Mock <HttpContext> httpContextMock = new Mock <HttpContext>();

            httpContextMock.Setup(s => s.User).Returns(claimsPrincipal);
            httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object);

            Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object);

            using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger <FhirResourceDelegateAuthorizationHandler> logger = loggerFactory.CreateLogger <FhirResourceDelegateAuthorizationHandler>();

            Mock <IResourceDelegateDelegate> mockDependentDelegate = new Mock <IResourceDelegateDelegate>();

            mockDependentDelegate.Setup(s => s.Exists(resourceHDID, hdid)).Returns(true);

            Mock <IPatientService> mockPatientService = new Mock <IPatientService>();

            mockPatientService
            .Setup(s => s.GetPatient(resourceHDID, PatientIdentifierType.HDID))
            .ReturnsAsync(getPatientResult);

            FhirResourceDelegateAuthorizationHandler authHandler = new FhirResourceDelegateAuthorizationHandler(
                logger,
                this.GetConfiguration(),
                httpContextAccessorMock.Object,
                mockPatientService.Object,
                mockDependentDelegate.Object
                );
            var requirements = new[] { new FhirRequirement(FhirResource.Observation, FhirAccessType.Read, supportsUserDelegation: true) };

            AuthorizationHandlerContext context = new AuthorizationHandlerContext(requirements, claimsPrincipal, null);

            authHandler.HandleAsync(context);
            Assert.False(context.HasSucceeded);
            Assert.False(context.HasFailed);
        }
Exemplo n.º 44
0
        public static RouteValueDictionary GetRouteValuesFromExpression <TController>(
            Expression <Action <TController> > action
            ) where TController : Controller
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            MethodCallExpression call = action.Body as MethodCallExpression;

            if (call == null)
            {
                throw new ArgumentException(
                          MvcResources.ExpressionHelper_MustBeMethodCall,
                          "action"
                          );
            }

            string controllerName = typeof(TController).Name;

            if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(
                          MvcResources.ExpressionHelper_TargetMustEndInController,
                          "action"
                          );
            }
            controllerName = controllerName.Substring(
                0,
                controllerName.Length - "Controller".Length
                );
            if (controllerName.Length == 0)
            {
                throw new ArgumentException(
                          MvcResources.ExpressionHelper_CannotRouteToController,
                          "action"
                          );
            }

            // TODO: How do we know that this method is even web callable?
            //      For now, we just let the call itself throw an exception.

            string actionName = GetTargetActionName(call.Method);

            var rvd = new RouteValueDictionary();

            rvd.Add("Controller", controllerName);
            rvd.Add("Action", actionName);

            ActionLinkAreaAttribute areaAttr =
                typeof(TController)
                .GetCustomAttributes(
                    typeof(ActionLinkAreaAttribute),
                    true     /* inherit */
                    )
                .FirstOrDefault() as ActionLinkAreaAttribute;

            if (areaAttr != null)
            {
                string areaName = areaAttr.Area;
                rvd.Add("Area", areaName);
            }

            AddParameterValuesFromExpressionToDictionary(rvd, call);
            return(rvd);
        }
Exemplo n.º 45
0
        public static MvcHtmlString LsInput <TModel, TValue>(
            this HtmlHelper <TModel> html,
            Expression <Func <TModel, TValue> > expression,
            string LabelAddText   = "",
            object htmlAttributes = null)
        {
            var rvd              = new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            var metaData         = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var memberExpression = (MemberExpression)expression.Body;
            var isRequired       = memberExpression.Member.GetCustomAttributes(typeof(RequiredAttribute), false).Length != 0;

            var displayAttribute = (DisplayAttribute[])memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false);

            var propertyName = metaData.PropertyName;
            var displayName  = metaData.DisplayName ?? propertyName;



            var step = "1";

            var type = "text";

            switch (memberExpression.Type.Name)
            {
            case "Int32":
                type = "number";
                break;

            case "Decimal":
                type = "number";
                step = "0.01";
                break;

            default:
                break;
            }

            if (metaData.DataTypeName == "Password")
            {
                type = "password";
            }

            rvd.Add("type", type);

            if (rvd.Any(q => q.Key == "class"))
            {
                rvd["class"] = rvd["class"] + " form-control text-box single-line";
            }
            else
            {
                rvd["class"] = "form-control text-box single-line";
            }

            if (type == "number")
            {
                rvd.Add("step", step);
            }

            var input = InputExtensions.TextBoxFor(html, expression, rvd);


            var OuterDiv = new TagBuilder("div");

            OuterDiv.AddCssClass("form-group row m-form__group");


            var fieldLabel = new TagBuilder("label");

            fieldLabel.Attributes.Add("for", propertyName);
            fieldLabel.AddCssClass("col-form-label col-md-2");
            fieldLabel.InnerHtml = displayName + LabelAddText + (isRequired ? "<em>*</em>" : "");

            bool hasError = false;

            var validationSpan = new TagBuilder("span");

            validationSpan.AddCssClass("form-control-feedback");

            var modelState = html.ViewData.ModelState;

            if (modelState[propertyName] != null)
            {
                var error = modelState[propertyName].Errors.FirstOrDefault();
                if (error != null)
                {
                    hasError = true;
                    validationSpan.InnerHtml = error.ErrorMessage;
                }
            }

            if (hasError)
            {
                OuterDiv.AddCssClass("has-danger");
            }

            var inputWrapper = new TagBuilder("div");

            inputWrapper.AddCssClass("col-md-8");
            inputWrapper.InnerHtml = input + validationSpan.ToString();


            OuterDiv.InnerHtml = fieldLabel.ToString() + inputWrapper.ToString();

            return(MvcHtmlString.Create(OuterDiv.ToString()));
        }
Exemplo n.º 46
0
        internal virtual string Create(ControlFormProvider formProvider)
        {
            if (HtmlBuilder != null)
            {
                return(HtmlBuilder());
            }

            if (childActions.Count > 0)
            {
                var sb = new StringBuilder();
                sb.AppendFormat("<button data-toggle=\"dropdown\" class=\"{0} dropdown-toggle\">", string.IsNullOrEmpty(CssClass) ? "btn" : CssClass.Trim());
                sb.Append(Text);
                sb.Append("&nbsp;<span class=\"caret\"></span>");
                sb.AppendFormat("</button>");

                sb.Append("<ul class=\"dropdown-menu\">");
                foreach (var childAction in childActions)
                {
                    sb.Append(childAction);
                }
                sb.Append("</ul>");

                return(sb.ToString());
            }

            if (IsSubmitButton)
            {
                var attributes = new RouteValueDictionary();

                if (!HtmlAttributes.IsNullOrEmpty())
                {
                    foreach (var attribute in HtmlAttributes)
                    {
                        attributes.Add(attribute.Key, attribute.Value);
                    }
                }

                var cssClass = (formProvider.GetButtonSizeCssClass(ButtonSize) + " " + formProvider.GetButtonStyleCssClass(ButtonStyle) + " " + CssClass + (!IsValidationSupported ? " cancel" : "")).Trim();

                if (!string.IsNullOrEmpty(cssClass))
                {
                    attributes.Add("class", cssClass);
                }

                if (!string.IsNullOrEmpty(ClientId))
                {
                    attributes.Add("id", ClientId);
                }

                if (!string.IsNullOrEmpty(ConfirmMessage))
                {
                    attributes.Add("onclick", string.Format("return confirm('{0}');", ConfirmMessage));
                }

                if (!string.IsNullOrEmpty(ClientClickCode))
                {
                    attributes["onclick"] = ClientClickCode;
                }

                var tagBuilder = new TagBuilder("button")
                {
                    InnerHtml = Text
                };
                tagBuilder.MergeAttribute("type", "submit");
                tagBuilder.MergeAttribute("value", Value);
                tagBuilder.MergeAttribute("name", Name);
                tagBuilder.MergeAttribute("id", "btn" + Name);
                tagBuilder.MergeAttribute("title", Description ?? Text);
                tagBuilder.MergeAttributes(attributes);

                if (!string.IsNullOrEmpty(IconCssClass))
                {
                    var icon = new TagBuilder("i");
                    icon.AddCssClass(IconCssClass);

                    tagBuilder.InnerHtml = string.Concat(icon.ToString(), " ", Text);
                }

                return(tagBuilder.ToString(TagRenderMode.Normal));
            }
            else
            {
                var attributes = new RouteValueDictionary();

                if (!HtmlAttributes.IsNullOrEmpty())
                {
                    foreach (var attribute in HtmlAttributes)
                    {
                        attributes.Add(attribute.Key, attribute.Value);
                    }
                }

                var cssClass = (formProvider.GetButtonSizeCssClass(ButtonSize) + " " + formProvider.GetButtonStyleCssClass(ButtonStyle) + " " + CssClass + (!IsValidationSupported ? " cancel" : "")).Trim();
                if (!string.IsNullOrEmpty(cssClass))
                {
                    attributes.Add("class", cssClass);
                }

                if (!string.IsNullOrEmpty(ClientId))
                {
                    attributes.Add("id", ClientId);
                }

                if (!string.IsNullOrEmpty(ClientClickCode))
                {
                    attributes["onclick"] = ClientClickCode;
                }

                attributes["href"] = Url;

                if (IsShowModalDialog)
                {
                    attributes.Add("data-toggle", "fancybox");
                    attributes.Add("data-fancybox-type", "iframe");
                    attributes.Add("data-fancybox-width", ModalDialogWidth);
                    attributes.Add("data-fancybox-height", ModalDialogHeight);
                }

                var tagBuilder = new TagBuilder("a")
                {
                    InnerHtml = Text
                };
                tagBuilder.MergeAttributes(attributes);

                if (!string.IsNullOrEmpty(IconCssClass))
                {
                    var icon = new TagBuilder("i");
                    icon.AddCssClass(IconCssClass);

                    tagBuilder.InnerHtml = string.Concat(icon.ToString(), " ", Text);
                }

                return(tagBuilder.ToString(TagRenderMode.Normal));
            }
        }
 /// <summary>
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <created author="laurentiu.macovei" date="Fri, 06 Jan 2012 19:43:08 GMT"/>
 void IDictionary <string, object> .Add(string key, object value)
 {
     _HtmlAttributes.Add(key, value);
 }
Exemplo n.º 48
0
        /// <summary>
        /// 產生排序用的超連結
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression">VM中用來排序的屬性</param>
        /// <param name="linkText">超連結文字</param>
        /// <param name="actionName">Action Name</param>
        /// <param name="routeValuesNow">目前的route value dictionary</param>
        /// <param name="sortColumnName">要排序的欄位名稱</param>
        /// <param name="defaultNextSort">預設的第一次按下去的排序方向 asc desc</param>
        /// <returns></returns>
        public static MvcHtmlString SortActionLink <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, string linkText, string actionName, RouteValueDictionary routeValuesNow, string sortColumnName, string defaultNextSort)
        {
            //新建一個route dictionary
            RouteValueDictionary routeValuesNew = new RouteValueDictionary(routeValuesNow);

            //取得排序屬性的名稱
            string sortPropName = ((MemberExpression)expression.Body).Member.Name;
            //是否改變排序的欄位
            bool changeSortColumn = false;
            //排序條件在route裡面的binding key
            string columnKey = sortPropName + ".Column";
            string sortKey   = sortPropName + ".Sort";
            //若有升降序則加入ICON
            string iconClassName = string.Empty;

            //欄位名稱設定
            if (routeValuesNew[columnKey] == null)
            {
                routeValuesNew.Add(columnKey, sortColumnName);
            }
            else
            {
                //判斷是否換了排序的欄位
                changeSortColumn          = sortColumnName != routeValuesNew[columnKey].ToString();
                routeValuesNew[columnKey] = sortColumnName;
            }

            //排序方向設定
            if (routeValuesNew[sortKey] == null)
            {
                //若原本無排序 則用預設下一個排序
                routeValuesNew.Add(sortKey, defaultNextSort);
            }
            else
            {
                //若有欄位 且換了欄位,則排序重來,從指定的排序開始
                if (changeSortColumn)
                {
                    routeValuesNew[sortKey] = defaultNextSort;
                }
                else
                {
                    //若沒換欄位,則排序往下一順位(不指定→asc→desc→不指定)
                    switch (routeValuesNew[sortKey].ToString())
                    {
                    case ("asc"):
                        routeValuesNew[sortKey] = "desc";                         //下一次按時會換的方向
                        iconClassName           = "glyphicon glyphicon-arrow-up"; //目前要用的ICON
                        break;

                    case ("desc"):
                        //不能指定空的,用移除這個KEY VALUE的方式變為不指定
                        routeValuesNew.Remove(sortKey);                   //下一次按時會換的方向
                        iconClassName = "glyphicon glyphicon-arrow-down"; //目前要用的ICON
                        break;

                    case (""):
                        routeValuesNew[sortKey] = "asc";        //下一次按時會換的方向
                        iconClassName           = string.Empty; //目前要用的ICON
                        break;

                    default:
                        break;
                    }
                }
            }
            var baseLink = htmlHelper.ActionLink(linkText
                                                 , actionName
                                                 , routeValuesNew);

            if (!string.IsNullOrEmpty(iconClassName))
            {
                var icon = string.Format($"<span class=\"{iconClassName}\" aria-hidden=\"true\"></span>");
                return(new MvcHtmlString(baseLink.ToHtmlString().Insert(baseLink.ToHtmlString().IndexOf(@"</a>"), icon)));
            }
            else
            {
                return(baseLink);
            }
        }
Exemplo n.º 49
0
        // GET: Vehicles
        public ActionResult Overview(VehicleType?Type, Color?Color, FuelType?FuelType, string Regnr = "", string Brand = "", string SortOn = "", bool Ascending = true, int page = 1)
        {
            var vehiclesTemp = db.Vehicles.Where(v => (Regnr == "" || v.Regnr.Contains(Regnr)) &&
                                                 (Type == null || v.Type == Type.ToString()) &&
                                                 (Color == null || v.Color == Color.ToString()) &&
                                                 (FuelType == null || v.FuelType == FuelType.ToString()) &&
                                                 (Brand.Trim() == "" || v.Brand.Contains(Brand.Trim())));

            switch (SortOn)
            {
            case "Regnr":
                if (Ascending)
                {
                    vehiclesTemp = vehiclesTemp.OrderBy(v => v.Regnr);
                }
                else
                {
                    vehiclesTemp = vehiclesTemp.OrderByDescending(v => v.Regnr);
                }
                break;

            case "Type":
                if (Ascending)
                {
                    vehiclesTemp = vehiclesTemp.OrderBy(v => v.Type);
                }
                else
                {
                    vehiclesTemp = vehiclesTemp.OrderByDescending(v => v.Type);
                }
                break;

            case "Color":
                if (Ascending)
                {
                    vehiclesTemp = vehiclesTemp.OrderBy(v => v.Color);
                }
                else
                {
                    vehiclesTemp = vehiclesTemp.OrderByDescending(v => v.Color);
                }
                break;

            case "ParkedTime":
                if (Ascending)
                {
                    vehiclesTemp = vehiclesTemp.OrderBy(v => v.ParkedTime);
                }
                else
                {
                    vehiclesTemp = vehiclesTemp.OrderByDescending(v => v.ParkedTime);
                }
                break;

            default:
                break;
            }

            List <VehicleOverview> vehicles = new List <VehicleOverview>();

            foreach (var v in vehiclesTemp.ToList())
            {
                vehicles.Add(new VehicleOverview(v.Id, v.Regnr, v.Type, v.Color, v.ParkedTime));
            }

            var queryDictionary = new RouteValueDictionary();

            if (Regnr != "")
            {
                queryDictionary.Add("Regnr", Regnr);
            }
            if (Type != null)
            {
                queryDictionary.Add("Type", Type);
            }
            if (Color != null)
            {
                queryDictionary.Add("Color", Color);
            }
            if (Brand != "")
            {
                queryDictionary.Add("Brand", Brand);
            }
            if (FuelType != null)
            {
                queryDictionary.Add("FuelType", FuelType);
            }

            queryDictionary.Add("SortOn", "");
            queryDictionary.Add("Ascending", true);

            var vehiclesOverview = new VehiclesOverview(vehicles.ToPagedList(Math.Max(page, 1), 10), SortOn, Ascending, queryDictionary);

            return(View(vehiclesOverview));
        }
Exemplo n.º 50
0
        private VirtualPathData GenerateVirtualPath(
            VirtualPathContext context,
            OutboundRouteEntry entry,
            TemplateBinder binder)
        {
            // In attribute the context includes the values that are used to select this entry - typically
            // these will be the standard 'action', 'controller' and maybe 'area' tokens. However, we don't
            // want to pass these to the link generation code, or else they will end up as query parameters.
            //
            // So, we need to exclude from here any values that are 'required link values', but aren't
            // parameters in the template.
            //
            // Ex:
            //      template: api/Products/{action}
            //      required values: { id = "5", action = "Buy", Controller = "CoolProducts" }
            //
            //      result: { id = "5", action = "Buy" }
            var inputValues = new RouteValueDictionary();

            foreach (var kvp in context.Values)
            {
                if (entry.RequiredLinkValues.ContainsKey(kvp.Key))
                {
                    var parameter = entry.RouteTemplate.GetParameter(kvp.Key);

                    if (parameter == null)
                    {
                        continue;
                    }
                }

                inputValues.Add(kvp.Key, kvp.Value);
            }

            var bindingResult = binder.GetValues(context.AmbientValues, inputValues);

            if (bindingResult == null)
            {
                // A required parameter in the template didn't get a value.
                return(null);
            }

            var matched = RouteConstraintMatcher.Match(
                entry.Constraints,
                bindingResult.CombinedValues,
                context.HttpContext,
                this,
                RouteDirection.UrlGeneration,
                _constraintLogger);

            if (!matched)
            {
                // A constraint rejected this link.
                return(null);
            }

            var pathData = entry.Handler.GetVirtualPath(context);

            if (pathData != null)
            {
                // If path is non-null then the target router short-circuited, we don't expect this
                // in typical MVC scenarios.
                return(pathData);
            }

            var path = binder.BindValues(bindingResult.AcceptedValues);

            if (path == null)
            {
                return(null);
            }

            return(new VirtualPathData(this, path));
        }
        public IDictionary <string, object> Match([NotNull] string requestPath)
        {
            var requestSegments = requestPath.Split(Delimiters);

            var values = new RouteValueDictionary();

            for (var i = 0; i < requestSegments.Length; i++)
            {
                var routeSegment   = Template.Segments.Count > i ? Template.Segments[i] : null;
                var requestSegment = requestSegments[i];

                if (routeSegment == null)
                {
                    // If pathSegment is null, then we're out of route segments. All we can match is the empty
                    // string.
                    if (requestSegment.Length > 0)
                    {
                        return(null);
                    }
                }
                else if (routeSegment.Parts.Count == 1)
                {
                    // Optimize for the simple case - the segment is made up for a single part
                    var part = routeSegment.Parts[0];
                    if (part.IsLiteral)
                    {
                        if (!string.Equals(part.Text, requestSegment, StringComparison.OrdinalIgnoreCase))
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        Debug.Assert(part.IsParameter);

                        if (part.IsCatchAll)
                        {
                            var captured = string.Join(SeparatorString, requestSegments, i, requestSegments.Length - i);
                            if (captured.Length > 0)
                            {
                                values.Add(part.Name, captured);
                            }
                            else
                            {
                                // It's ok for a catch-all to produce a null value
                                object defaultValue;
                                Defaults.TryGetValue(part.Name, out defaultValue);

                                values.Add(part.Name, defaultValue);
                            }

                            // A catch-all has to be the last part, so we're done.
                            break;
                        }
                        else
                        {
                            if (requestSegment.Length > 0)
                            {
                                values.Add(part.Name, requestSegment);
                            }
                            else
                            {
                                object defaultValue;
                                if (Defaults.TryGetValue(part.Name, out defaultValue))
                                {
                                    values.Add(part.Name, defaultValue);
                                }
                                else if (part.IsOptional)
                                {
                                    // This is optional (with no default value)
                                    // - there's nothing to capture here, so just move on.
                                }
                                else
                                {
                                    // There's no default for this parameter
                                    return(null);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (!MatchComplexSegment(routeSegment, requestSegment, Defaults, values))
                    {
                        return(null);
                    }
                }
            }

            for (var i = requestSegments.Length; i < Template.Segments.Count; i++)
            {
                // We've matched the request path so far, but still have remaining route segments. These need
                // to be all single-part parameter segments with default values or else they won't match.
                var routeSegment = Template.Segments[i];
                if (routeSegment.Parts.Count > 1)
                {
                    // If it has more than one part it must contain literals, so it can't match.
                    return(null);
                }

                var part = routeSegment.Parts[0];
                if (part.IsLiteral)
                {
                    return(null);
                }

                Debug.Assert(part.IsParameter);

                // It's ok for a catch-all to produce a null value
                object defaultValue;
                if (Defaults.TryGetValue(part.Name, out defaultValue) || part.IsCatchAll)
                {
                    values.Add(part.Name, defaultValue);
                }
                else if (part.IsOptional)
                {
                    // This is optional (with no default value) - there's nothing to capture here, so just move on.
                }
                else
                {
                    // There's no default for this (non-catch-all) parameter so it can't match.
                    return(null);
                }
            }

            // Copy all remaining default values to the route data
            foreach (var kvp in Defaults)
            {
                if (!values.ContainsKey(kvp.Key))
                {
                    values.Add(kvp.Key, kvp.Value);
                }
            }

            return(values);
        }
Exemplo n.º 52
0
        private static void BuildAction <TModelRecord>(StringBuilder sb, TModelRecord item, IRoboUIGridRowAction action, IRoboUIFormProvider formProvider, bool addLiTag)
        {
            if (!action.IsVisible(item))
            {
                return;
            }

            var enabled    = action.IsEnabled(item);
            var attributes = new RouteValueDictionary(action.GetAttributes(item));

            if (addLiTag)
            {
                sb.Append("<li>");
            }

            if (action.ChildActions.Count > 0)
            {
                var dropdownId = Guid.NewGuid().ToString();

                sb.AppendFormat("<div id=\"dropdown-content-{0}\" style=\"display: none;\">", dropdownId);

                foreach (var childAction in action.ChildActions)
                {
                    BuildAction(sb, item, childAction, formProvider, false);
                }

                sb.Append("</div>");

                var cssClass =
                    (formProvider.GetButtonSizeCssClass(action.ButtonSize) + " " +
                     formProvider.GetButtonStyleCssClass(action.ButtonStyle)).Trim();

                sb.AppendFormat("<button id=\"dropdown-button-{2}\" type=\"button\" class=\"{0}\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"bottom\" data-html=\"true\" data-trigger=\"focus\" data-template=\"<div class='popover popover-dropdown' role='tooltip'><div class='arrow'></div><div class='popover-content'></div></div>\" onclick=\"if(!$('#dropdown-button-{2}').data('bs.popover')){{ $('#dropdown-button-{2}').popover({{ content: function(){{ return $('#dropdown-content-{2}').html(); }} }}).popover('show'); }}\">{1} <span class=\"caret\"></span></button>", cssClass, action.Text, dropdownId);

                return;
            }

            if (action.IsSubmitButton)
            {
                var value = action.GetValue(item);

                var cssClass =
                    (formProvider.GetButtonSizeCssClass(action.ButtonSize) + " " +
                     formProvider.GetButtonStyleCssClass(action.ButtonStyle) + " " + action.CssClass).Trim();

                if (!string.IsNullOrEmpty(cssClass))
                {
                    attributes.Add("class", cssClass);
                }

                if (!enabled)
                {
                    attributes.Add("disabled", "disabled");
                }

                if (!string.IsNullOrEmpty(action.ClientClickCode))
                {
                    attributes.Add("onclick", action.ClientClickCode);
                }
                else
                {
                    if (!string.IsNullOrEmpty(action.ConfirmMessage))
                    {
                        attributes.Add("onclick", string.Format("return confirm('{0}');", action.ConfirmMessage));
                    }
                }

                attributes.Add("id", "btn" + Guid.NewGuid().ToString("N").ToLowerInvariant());
                attributes.Add("style", "white-space: nowrap;");

                var tagBuilder = new TagBuilder("button");
                tagBuilder.MergeAttribute("type", "submit");
                tagBuilder.MergeAttribute("name", action.Name);
                tagBuilder.InnerHtml.AppendHtml(action.Text);
                tagBuilder.MergeAttribute("value", Convert.ToString(value));
                tagBuilder.MergeAttributes(attributes, true);
                sb.Append(tagBuilder.ToHtmlString());
            }
            else
            {
                var href = action.GetUrl(item);

                var cssClass =
                    (formProvider.GetButtonSizeCssClass(action.ButtonSize) + " " +
                     formProvider.GetButtonStyleCssClass(action.ButtonStyle) + " " + action.CssClass).Trim();

                if (!string.IsNullOrEmpty(cssClass))
                {
                    if (enabled)
                    {
                        attributes.Add("class", cssClass);
                    }
                    else
                    {
                        attributes.Add("class", cssClass + " disabled");
                    }
                }
                else
                {
                    if (!enabled)
                    {
                        attributes.Add("class", "disabled");
                    }
                }

                attributes.Add("style", "white-space: nowrap;");

                if (action.IsShowModalDialog && enabled)
                {
                    attributes.Add("data-toggle", "fancybox");
                    attributes.Add("data-fancybox-type", "iframe");
                    attributes.Add("data-fancybox-width", action.ModalDialogWidth);
                }

                var tagBuilder = new TagBuilder("a");
                if (enabled)
                {
                    tagBuilder.MergeAttribute("href", href ?? "javascript:void(0)");
                }
                else
                {
                    tagBuilder.MergeAttribute("href", "javascript:void(0)");
                }
                tagBuilder.InnerHtml.AppendHtml(action.Text);
                tagBuilder.MergeAttributes(attributes, true);
                sb.Append(tagBuilder.ToHtmlString());
            }

            if (addLiTag)
            {
                sb.Append("</li>");
            }
        }
        public IHtmlString TextBox(string id, string placeholder = "", TextBoxType type = TextBoxType.Texto, bool exibirMsgValidacao = true, object htmlAttributes = null)
        {
            var attributes = new RouteValueDictionary(htmlAttributes);

            attributes.Add("class", "form-control");
            if (!string.IsNullOrEmpty(placeholder))
            {
                attributes.Add("placeholder", placeholder);
            }

            switch (type)
            {
            case TextBoxType.Texto:


                break;

            case TextBoxType.Nome:

                break;

            case TextBoxType.Email:
                //var iconBuilderEmail = new TagBuilder("i");
                //iconBuilderEmail.MergeAttribute("class", "icon-prepend fa fa-envelope-o");
                //labelBuilder.InnerHtml += iconBuilderEmail;
                break;

            case TextBoxType.Telefone:
                var iconBuilderTelefone = new TagBuilder("i");
                iconBuilderTelefone.MergeAttribute("class", "icon-prepend fa fa-phone");
                attributes.Add("data-mask", "(99)9999-9999");
                //labelBuilder.InnerHtml += iconBuilderTelefone;
                break;

            case TextBoxType.Cep:
                attributes.Add("data-mask", "99.999-999");
                break;

            case TextBoxType.Senha:
                var iconBuilderSenha = new TagBuilder("i");
                iconBuilderSenha.MergeAttribute("class", "icon-prepend fa fa-lock");
                attributes.Add("type", "password");
                //labelBuilder.InnerHtml += iconBuilderSenha;
                break;

            case TextBoxType.Data:
                var iconBuilderData = new TagBuilder("i");
                iconBuilderData.MergeAttribute("class", "icon-append fa fa-calendar");
                //labelBuilder.InnerHtml += iconBuilderData;
                attributes.Add("class", "datepicker");
                attributes.Add("data-dateformat", "dd/mm/yy");
                attributes.Add("data-mask", "99/99/9999");
                break;
            }

            var textBoxHelper = helper.TextBox(id, helper.Value(id).ToHtmlString(), attributes);
            //labelBuilder.InnerHtml += textBoxHelper;


            //var tagMsgValidation = string.Empty;

            //if (!helper.ViewData.ModelState.IsValidField(id))
            //{
            //    labelBuilder.AddCssClass("state-error");

            //    if (exibirMsgValidacao)
            //    {
            //        var validationBuilder = helper.ValidationMessage(id).ToString().Replace("span", "em");
            //        tagMsgValidation += validationBuilder.ToString();
            //    }

            //}

            //var htmlRetorno = labelBuilder + tagMsgValidation;
            var htmlRetorno = textBoxHelper;

            return(MvcHtmlString.Create(htmlRetorno.ToString()));
        }
Exemplo n.º 54
0
        public static MvcHtmlString AsiatekAjaxPager <T>(this AjaxHelper <T> ajaxHelper, AsiatekAjaxPagerOptions2 asiatekAjaxPagerOptions, IAsiatekPagedList pageList)
        {
            if (string.IsNullOrWhiteSpace(asiatekAjaxPagerOptions.SearchPageFieldName))
            {
                asiatekAjaxPagerOptions.SearchPageFieldName = "SearchPage";
            }

            //利用请求上下文对象创建url对象,用于分页超链接的创建
            UrlHelper URL = new UrlHelper(ajaxHelper.ViewContext.RequestContext);


            #region 配置路由参数值
            //反射查询参数对象,将系统类型的属性值添加到路由参数值中,属性名是路由参数的key
            //之所以这样做,是因为对于分页查询所需要的参数肯定都是简单类型
            //比如视图采用模型StudentSetting,StudentSetting包含下拉列表Grades年级,以及对应的值GradeID
            //对于我们的查询而言,需要的只是GradeID,而不是Grades下拉列表属性

            var model = ajaxHelper.ViewData.Model;

            Type type  = model.GetType();
            var  props = type.GetProperties().Where(p => p.PropertyType.ToString().StartsWith("System.") && !p.PropertyType.IsGenericType);
            RouteValueDictionary rvd = new RouteValueDictionary();
            foreach (PropertyInfo p in props)
            {
                rvd.Add(p.Name, p.GetValue(model, null));
            }

            if (!rvd.ContainsKey(asiatekAjaxPagerOptions.SearchPageFieldName))
            {
                //允许自定义分页查询  当前页字段名 比如currentPage
                //相当于往请求参数中附加了currentPage=1
                rvd.Add(asiatekAjaxPagerOptions.SearchPageFieldName, 1);
            }
            else
            {
                rvd[asiatekAjaxPagerOptions.SearchPageFieldName] = 1;
            }
            //查询操作所属区域名
            rvd.Add("area", asiatekAjaxPagerOptions.AreaName);
            #endregion



            int pageIndex = pageList.CurrentPageIndex; //当前页索引
            int pageCount = pageList.TotalPageCount;   //总页数

            string voidStr = "javascript:void(0)";

            TagBuilder asiatekPagerDiv = new TagBuilder("div");//最外层DIV
            asiatekPagerDiv.GenerateId("asiatekPager");


            TagBuilder asiatekPagerBackDiv = new TagBuilder("div");//第一页
            asiatekPagerBackDiv.GenerateId("asiatekPagerBack");
            TagBuilder backLink = new TagBuilder("a");
            backLink.MergeAttribute("href", voidStr);
            backLink.SetInnerText("||<");
            backLink.AddCssClass("asiatekPagerDefault");
            if (pageCount != 1)//只有当总页数不为1时,才需要为返回第一页的html标签设置地址
            {
                asiatekAjaxPagerOptions.Url = URL.Action(asiatekAjaxPagerOptions.ActionName, asiatekAjaxPagerOptions.ControllerName, rvd);
                backLink.MergeAttributes(asiatekAjaxPagerOptions.ToUnobtrusiveHtmlAttributes());
            }
            asiatekPagerBackDiv.InnerHtml = backLink.ToString();


            TagBuilder asiatekPagerFrontDiv = new TagBuilder("div");//末页
            asiatekPagerFrontDiv.GenerateId("asiatekPagerFront");
            TagBuilder frontLink = new TagBuilder("a");
            frontLink.MergeAttribute("href", voidStr);
            frontLink.SetInnerText(">||");
            frontLink.AddCssClass("asiatekPagerDefault");
            if (pageCount != 1)//只有当总页数不为1时,才需要为末页的html标签设置地址
            {
                rvd[asiatekAjaxPagerOptions.SearchPageFieldName] = pageCount;
                asiatekAjaxPagerOptions.Url = URL.Action(asiatekAjaxPagerOptions.ActionName, asiatekAjaxPagerOptions.ControllerName, rvd);
                frontLink.MergeAttributes(asiatekAjaxPagerOptions.ToUnobtrusiveHtmlAttributes());
            }
            asiatekPagerFrontDiv.InnerHtml = frontLink.ToString();


            //内容(页选择)
            TagBuilder asiatekPagerContentDiv = new TagBuilder("div");//页内容
            asiatekPagerContentDiv.GenerateId("asiatekPagerContent");


            for (int i = 1; i <= pageCount; i++)
            {
                TagBuilder numLink = new TagBuilder("a");
                numLink.AddCssClass("asiatekPagerDefault");
                numLink.MergeAttribute("href", voidStr);
                if (i == pageIndex)//当前页添加 css
                {
                    numLink.AddCssClass("asiatekPagerSelected");
                }
                if (pageCount != 1)//如果总页数超过1,那么才对 页链接创建非注入式脚本,否则不添加
                {
                    rvd[asiatekAjaxPagerOptions.SearchPageFieldName] = i;
                    asiatekAjaxPagerOptions.Url = URL.Action(asiatekAjaxPagerOptions.ActionName, asiatekAjaxPagerOptions.ControllerName, rvd);
                    numLink.MergeAttributes(asiatekAjaxPagerOptions.ToUnobtrusiveHtmlAttributes());
                }
                numLink.SetInnerText(i.ToString());
                asiatekPagerContentDiv.InnerHtml += numLink.ToString();
            }
            int contentWidth = 250; //页数内容容器默认宽度250px
            int pagerWidth   = 320; //整个分页导航总宽度默认320px
            if (pageCount < 10)     //最多同时显示10页,当少于10页时,动态计算整体宽度,每个页链接占用25px,第一页与末页链接各占用35px
            {
                contentWidth = pageCount * 25;
                pagerWidth   = 70 + contentWidth;
            }
            //设置容器宽度
            asiatekPagerContentDiv.MergeAttribute("style", "width:" + contentWidth + "px;");
            asiatekPagerDiv.MergeAttribute("style", "width:" + pagerWidth + "px;");

            //合并全部HTML
            asiatekPagerDiv.InnerHtml = asiatekPagerBackDiv.ToString() + asiatekPagerContentDiv.ToString() + asiatekPagerFrontDiv.ToString();
            return(MvcHtmlString.Create(asiatekPagerDiv.ToString()));
        }
        public string GenerateKey(ControllerContext context, CacheSettings cacheSettings)
        {
            var actionName     = context.RouteData.Values["action"].ToString();
            var controllerName = context.RouteData.Values["controller"].ToString();

            // remove controller, action and DictionaryValueProvider which is added by the framework for child actions
            var filteredRouteData = context.RouteData.Values.Where(
                x => x.Key.ToLowerInvariant() != "controller" &&
                x.Key.ToLowerInvariant() != "action" &&
                !(x.Value is DictionaryValueProvider <object>)
                );

            var routeValues = new RouteValueDictionary(filteredRouteData.ToDictionary(x => x.Key.ToLowerInvariant(), x => x.Value));

            if (!context.IsChildAction)
            {
                // note that route values take priority over form values and form values take priority over query string values

                if ((cacheSettings.Options & OutputCacheOptions.IgnoreFormData) != OutputCacheOptions.IgnoreFormData)
                {
                    foreach (var formKey in context.HttpContext.Request.Form.AllKeys)
                    {
                        if (routeValues.ContainsKey(formKey.ToLowerInvariant()))
                        {
                            continue;
                        }

                        var item = context.HttpContext.Request.Form[formKey];
                        routeValues.Add(
                            formKey.ToLowerInvariant(),
                            item != null
                                ? item.ToLowerInvariant()
                                : string.Empty
                            );
                    }
                }

                if ((cacheSettings.Options & OutputCacheOptions.IgnoreQueryString) != OutputCacheOptions.IgnoreQueryString)
                {
                    foreach (var queryStringKey in context.HttpContext.Request.QueryString.AllKeys)
                    {
                        // queryStringKey is null if url has qs name without value. e.g. test.com?q
                        if (queryStringKey == null || routeValues.ContainsKey(queryStringKey.ToLowerInvariant()))
                        {
                            continue;
                        }

                        var item = context.HttpContext.Request.QueryString[queryStringKey];
                        routeValues.Add(
                            queryStringKey.ToLowerInvariant(),
                            item != null
                                ? item.ToLowerInvariant()
                                : string.Empty
                            );
                    }
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByParam))
            {
                if (cacheSettings.VaryByParam.ToLowerInvariant() == "none")
                {
                    routeValues.Clear();
                }
                else if (cacheSettings.VaryByParam != "*")
                {
                    var parameters = cacheSettings.VaryByParam.ToLowerInvariant().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    routeValues = new RouteValueDictionary(routeValues.Where(x => parameters.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value));
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByCustom))
            {
                routeValues.Add(
                    cacheSettings.VaryByCustom.ToLowerInvariant(),
                    context.HttpContext.ApplicationInstance.GetVaryByCustomString(HttpContext.Current, cacheSettings.VaryByCustom)
                    );
            }

            var key = _keyBuilder.BuildKey(controllerName, actionName, routeValues);

            return(key);
        }
Exemplo n.º 56
0
        public static MvcHtmlString ControlGroupFor <TModel, TValue>(
            this HtmlHelper <TModel> html,
            Expression <Func <TModel, TValue> > expression,
            InputEditorType editorType = InputEditorType.TextBox,
            bool required                = false,
            string helpHint              = null,
            string breakpoint            = "md",
            string additionalCtrlClasses = "")
        {
            if (editorType == InputEditorType.Hidden)
            {
                return(html.HiddenFor(expression));
            }

            string inputHtml      = "";
            var    htmlAttributes = new RouteValueDictionary();
            var    metadata       = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var    dataTypeName   = metadata.DataTypeName.EmptyNull();
            var    groupClass     = "form-group row";
            var    labelClass     = "col-{0}-3 col-form-label".FormatInvariant(breakpoint.NullEmpty() ?? "md");
            var    controlsClass  = "col-{0}-9".FormatInvariant(breakpoint.NullEmpty() ?? "md");
            var    sb             = new StringBuilder("<div class='{0}'>".FormatWith(groupClass));

            if (editorType != InputEditorType.Checkbox)
            {
                var className = labelClass + (required ? " required" : "");
                var fieldId   = html.IdFor(expression).ToString();
                sb.AppendLine(html.LabelFor(expression, new { @class = className, @for = fieldId }).ToString());
            }

            sb.AppendLine("<div class='{0}'>".FormatWith(controlsClass));

            if (!required && (editorType == InputEditorType.TextBox || editorType == InputEditorType.Password))
            {
                htmlAttributes.Add("placeholder", EngineContext.Current.Resolve <ILocalizationService>().GetResource("Common.Optional"));
            }

            switch (dataTypeName)
            {
            case "EmailAddress":
                htmlAttributes.Add("type", "email");
                break;

            case "PhoneNumber":
                htmlAttributes.Add("type", "tel");
                break;
            }

            htmlAttributes.Add("class", "form-control" + (additionalCtrlClasses.HasValue() ? " " + additionalCtrlClasses : ""));

            switch (editorType)
            {
            case InputEditorType.Checkbox:
                CommonHelper.TryConvert <bool>(metadata.Model, out var isChecked);
                inputHtml = string.Format("<div class='form-check'>{0}<label class='form-check-label' for='{1}'>{2}</label></div>",
                                          html.CheckBox(ExpressionHelper.GetExpressionText(expression), isChecked, new { @class = "form-check-input" }).ToString(),
                                          html.IdFor(expression),
                                          metadata.DisplayName);
                break;

            case InputEditorType.Password:
                inputHtml = html.PasswordFor(expression, htmlAttributes).ToString();
                break;

            default:
                inputHtml = html.TextBoxFor(expression, htmlAttributes).ToString();
                break;
            }

            sb.AppendLine(inputHtml);
            sb.AppendLine(html.ValidationMessageFor(expression).ToString());
            if (helpHint.HasValue())
            {
                sb.AppendLine(string.Format("<div class='form-text text-muted'>{0}</div>", helpHint));
            }
            sb.AppendLine("</div>"); // div.controls

            sb.AppendLine("</div>"); // div.control-group

            return(MvcHtmlString.Create(sb.ToString()));
        }
        public ActionResult Add(int contentId, string comment, string returnUrl)
        {
            var contentItem = this.contentManager.Get(contentId);

            var commentsPart = contentItem.As <CRMCommentsPart>();

            if (commentsPart == null)
            {
                return(new HttpUnauthorizedResult());
            }

            if (!this.contentOwnershipService.CurrentUserCanViewContent(contentItem))
            {
                return(new HttpUnauthorizedResult());
            }

            int userId = this.services.WorkContext.CurrentUser.Id;

            // create new comment part
            var crmCommentItem = this.contentManager.New("CRMComment");

            this.contentManager.Create(crmCommentItem, VersionOptions.Draft);
            var crmCommentPart = crmCommentItem.As <CRMCommentPart>();

            crmCommentPart.Record.CommentText           = comment;
            crmCommentPart.Record.CRMCommentsPartRecord = commentsPart.Record;
            crmCommentPart.Record.User = new Users.Models.UserPartRecord {
                Id = userId
            };
            dynamic model = this.contentManager.UpdateEditor(crmCommentItem, this);

            this.contentManager.Publish(crmCommentItem);

            // Add to activity stream
            string contentDescription = this.contentItemDescriptorManager.GetDescription(contentItem);

            contentDescription = this.T("commented on the '{0}'", contentDescription).Text;
            RouteValueDictionary routeValueDictionary = new RouteValueDictionary();

            routeValueDictionary.Add("action", "Display");
            routeValueDictionary.Add("controller", "Item");
            routeValueDictionary.Add("area", "Orchard.CRM.Core");
            routeValueDictionary.Add("id", contentItem.Id);
            this.activityStreamService.WriteChangesToStreamActivity(userId, contentItem.Id, contentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, contentDescription, routeValueDictionary);

            var documentIndex = this.indexProvider.New(contentItem.Id);

            this.contentManager.Index(contentItem, documentIndex);
            this.indexProvider.Store(TicketController.SearchIndexName, documentIndex);

            bool isAjaxRequest = Request.IsAjaxRequest();

            if (isAjaxRequest)
            {
                return(this.Json(this.CreateAjaxMessageModel(crmCommentItem, string.Empty), JsonRequestBehavior.AllowGet));
            }
            else if (!string.IsNullOrEmpty(returnUrl))
            {
                return(this.Redirect(returnUrl));
            }
            else if (contentItem.TypeDefinition.Name == "Ticket")
            {
                return(this.RedirectToAction("Edit", "Ticket", new { id = contentId, area = "Orchard.CRM.Core" }));
            }
            else if (contentItem.TypeDefinition.Name == "Request")
            {
                return(this.RedirectToAction("Edit", "Request", new { id = contentId, area = "Orchard.CRM.Core" }));
            }
            else
            {
                return(this.RedirectToAction("Edit", "Item", new { area = "Orchard.CRM.Core", id = contentId }));
            }
        }
        public void InitializeHttpFunctionRoutes(IScriptJobHost host)
        {
            var routesLogBuilder = new StringBuilder();

            routesLogBuilder.AppendLine("Initializing function HTTP routes");

            _router.ClearRoutes();

            // TODO: FACAVAL Instantiation of the ScriptRouteHandler should be cleaned up
            WebJobsRouteBuilder routesBuilder = _router.CreateBuilder(new ScriptRouteHandler(_loggerFactory, host, _environment, false), _httpOptions.Value.RoutePrefix);

            // Proxies do not honor the route prefix defined in host.json
            WebJobsRouteBuilder proxiesRoutesBuilder = _router.CreateBuilder(new ScriptRouteHandler(_loggerFactory, host, _environment, true), routePrefix: null);

            foreach (var function in host.Functions)
            {
                var httpTrigger = function.GetTriggerAttributeOrNull <HttpTriggerAttribute>();
                if (httpTrigger != null)
                {
                    var constraints = new RouteValueDictionary();
                    if (httpTrigger.Methods != null)
                    {
                        constraints.Add("httpMethod", new HttpMethodRouteConstraint(httpTrigger.Methods));
                    }

                    string route = httpTrigger.Route;

                    if (string.IsNullOrEmpty(route) && !function.Metadata.IsProxy)
                    {
                        route = function.Name;
                    }

                    WebJobsRouteBuilder builder = function.Metadata.IsProxy ? proxiesRoutesBuilder : routesBuilder;
                    builder.MapFunctionRoute(function.Metadata.Name, route, constraints, function.Metadata.Name);

                    LogRouteMap(routesLogBuilder, function.Metadata.Name, route, httpTrigger.Methods, function.Metadata.IsProxy, _httpOptions.Value.RoutePrefix);
                }
            }

            IRouter proxyRouter    = null;
            IRouter functionRouter = null;

            if (routesBuilder.Count == 0 && proxiesRoutesBuilder.Count == 0)
            {
                routesLogBuilder.AppendLine("No HTTP routes mapped");
            }
            else
            {
                if (proxiesRoutesBuilder.Count > 0)
                {
                    proxyRouter = proxiesRoutesBuilder.Build();
                }

                if (routesBuilder.Count > 0)
                {
                    functionRouter = routesBuilder.Build();
                }
            }

            _router.AddFunctionRoutes(functionRouter, proxyRouter);

            ILogger logger = _loggerFactory.CreateLogger <WebScriptHostHttpRoutesManager>();

            logger.LogInformation(routesLogBuilder.ToString());
        }
Exemplo n.º 59
0
        public Breadcrumb(UrlHelper url, params RouteValueDictionary[] routevalues)
        {
            /* Merge all route values into one list. */
            var list = new RouteValueDictionary();

            routevalues.ToList().ForEach(i => i.ToList().ForEach(j => list.Add(j.Key, j.Value)));

            /* Those are the levels in the desired order of display. */
            var levels = new string[] { "area", "cell", "controller", "tag", "action" };

            /* Creates breadcrumb. */
            StringBuilder sb = new StringBuilder();

            /* Inserts top level. */
            TagBuilder a = new TagBuilder("a");

            a.MergeAttribute("href", url.Content("~/"));
            a.SetInnerText("Tigra");
            TagBuilder li = new TagBuilder("li")
            {
                InnerHtml = a.ToString()
            };

            sb.Append(li.ToString());

            /* Add all empty values to the route dictionary. */
            var atb = new RouteValueDictionary();

            levels.ToList().ForEach(i => atb.Add(i, null));

            /* Reset item tags to properly handle current active level. */
            TagBuilder oli, oa;

            oli = oa = li = a = null;

            /* Iterate through all bradcrumb levels. */
            foreach (var k in levels)
            {
                oli = li;
                oa  = a;

                /* Check for current level. */
                object v;
                if (true == list.TryGetValue(k, out v) && v != null && v.ToString().Length != 0)
                {
                    a      = new TagBuilder("a");
                    atb[k] = v.ToString();
                    a.MergeAttribute("href", this.Route(url, atb));

                    string title = v.ToString();

                    /* Get cell name. */
                    if (k == "cell")
                    {
                        title = v.GetCell().CellName;
                    }
                    /* Get topic title. */
                    else if (k == "tag")
                    {
                        if (list.TryGetValue("title", out v))
                        {
                            title = v.ToString();
                        }
                    }
                    /* Get area, controller or action description. */
                    else
                    {
                        LevelsDicionary.TryGetValue(title, out title);
                    }

                    /* Skip if title not found. */
                    if (title == null)
                    {
                        continue;
                    }

                    a.SetInnerText(title.ToString());
                    li = new TagBuilder("li")
                    {
                        InnerHtml = a.ToString()
                    };

                    /* Add last level in memory. */
                    if (oli != null && oa != null)
                    {
                        sb.Append(oli.ToString());
                        oli = li;
                        oa  = a;
                    }
                }
            }

            /* Remove link of current active level. */
            oli.InnerHtml = oa.InnerHtml;
            oli.AddCssClass("active");
            sb.Append(oli.ToString());

            /* Append all to breadcrumb. */
            var ol = new TagBuilder("ol");

            ol.AddCssClass("breadcrumb");
            ol.InnerHtml = sb.ToString();

            /* Sets HTML code. */
            this.HtmlCode = ol.ToString();
        }
Exemplo n.º 60
0
        private static void MapByRoutingCollection(RouteCollection routes, bool cutOutUrlFirstSection, string areaName, RoutingCollection routingCollection, NamespacesCollection namespacesCollection)
        {
            if (routingCollection == null || routingCollection.Count <= 0)
            {
                return;
            }
            List <string> namespaces = new List <string>();

            if (namespacesCollection != null)
            {
                foreach (Namespace ns in namespacesCollection)
                {
                    namespaces.Add(ns.Name);
                }
            }
            DeviceType?dtype = null;
            string     tmp   = routingCollection.Device;
            DeviceType tt;

            if (string.IsNullOrWhiteSpace(tmp) == false && Enum.TryParse <DeviceType>(tmp, true, out tt))
            {
                dtype = tt;
            }
            string re_url = routingCollection.RedirectUrlForOtherDevices;
            string domain = routingCollection.Domain;

            foreach (RoutingItem routingItem in routingCollection)
            {
                RouteValueDictionary defaults    = new RouteValueDictionary();
                RouteValueDictionary constraints = new RouteValueDictionary();
                if (string.IsNullOrWhiteSpace(routingItem.Controller) == false)
                {
                    defaults.Add("controller", routingItem.Controller);
                }
                if (string.IsNullOrWhiteSpace(routingItem.Action) == false)
                {
                    defaults.Add("action", routingItem.Action);
                }
                foreach (Parameter param in routingItem.Paramaters)
                {
                    if (string.IsNullOrWhiteSpace(param.Value) == false)
                    {
                        string v = param.Value.Trim();
                        if (v == "UrlParameter.Optional")
                        {
                            defaults.Add(param.Name, UrlParameter.Optional);
                        }
                        else
                        {
                            defaults.Add(param.Name, v);
                        }
                    }
                    if (string.IsNullOrWhiteSpace(param.Constraint) == false)
                    {
                        constraints.Add(param.Name, param.Constraint);
                    }
                }
                MapRoute(routes, cutOutUrlFirstSection, routingItem.Name, routingItem.Url, defaults, constraints, areaName, namespaces.ToArray(),
                         dtype, string.IsNullOrWhiteSpace(routingItem.RedirectUrlForOtherDevices) ? re_url : routingItem.RedirectUrlForOtherDevices, domain, routingItem.AuthKey);
            }
        }