public static MvcHtmlString SortableLinkFor <TModelItem, TValue>(this HtmlHelper <PagedData <TModelItem> > htmlHelper, System.Linq.Expressions.Expression <System.Func <TModelItem, TValue> > expression, string linkText = null) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression <TModelItem, TValue>(expression, new ViewDataDictionary <TModelItem>()); string propertyName = ExpressionHelper.GetExpressionText(expression); if (string.IsNullOrEmpty(linkText)) { linkText = metadata.DisplayName; } if (string.IsNullOrEmpty(linkText)) { linkText = propertyName; } PagedData <TModelItem> pagedData = htmlHelper.ViewData.Model; System.Web.Routing.RouteValueDictionary htmlAttributes = new System.Web.Routing.RouteValueDictionary(); string sort = string.IsNullOrEmpty(metadata.RealSort()) ? propertyName : metadata.RealSort(); htmlAttributes.Add("orderBy", sort); if (sort == pagedData.Pager.OrderBy) { htmlAttributes.Add("isDesc", !pagedData.Pager.IsDesc); htmlAttributes.Add("class", (pagedData.Pager.IsDesc ? "desc" : "asc") + " sortableLink"); } else { htmlAttributes.Add("isDesc", false); htmlAttributes.Add("class", "sortableLink"); } return(htmlHelper.ActionLink(linkText, "", null, htmlAttributes)); }
void redirectToUnauthorize(ActionExecutingContext filterContext, string actionName, string controllerName) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("action", actionName); route.Add("controller", controllerName); filterContext.Result = new RedirectToRouteResult(route); }
public ActionResult SignOn(SignOnModel model, string returnUrl) { if (ModelState.IsValid) { bool allowMultipleSessions = false; AppSession appSession = Global.GetAppSession(this.HttpContext); UserEnvironmentStructure ues = new UserEnvironmentStructure(); ues.AppCode = appSession.AppCode; ues.AppId = appSession.AppId; ues.AppVersion = appSession.AppVersion; SignonResultsStructure results = UserSignon.Signon(Global.GetDataAccessMgr(this.HttpContext) , appSession.SignonControl , model.UserName , model.Password , ues , allowMultipleSessions); if (results.ResultEnum == SignonResultsEnum.Success) { FormsService.SignIn(model.UserName, model.RememberMe); Session[SessionManagement.Constants.UserSessionMgr] = results.UserSessionMgr; if (!string.IsNullOrEmpty(returnUrl)) { string[] urlParts = returnUrl.Split(new string[] { Constants.UIControlCodeTag }, StringSplitOptions.None); int controlCode = urlParts.Length > 1 ? Convert.ToInt32(urlParts[1]) : 0; if (!results.UserSessionMgr.IsAccessAllowed(controlCode) || true) { string msg = string.Format("Sorry, you are not authorized to access this page: {0}." , urlParts[0]); System.Web.Routing.RouteValueDictionary dictionary = new System.Web.Routing.RouteValueDictionary(); dictionary.Add(Constants.Message, msg); dictionary.Add(Constants.UrlReferrer, model.GoBackUri); return(RedirectToAction(Constants.AccessDenied, Constants.Home, dictionary)); } } if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction(Constants.Index, Constants.Home)); } } else { #warning "Add other case conditions" ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { LoginUserDetails objLoginUserDetails = (LoginUserDetails)Common.Common.GetSessionValue(ConstEnum.SessionValue.UserDetails); try { int RedirectionType; object path = null; string sController = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string sAction = filterContext.ActionDescriptor.ActionName; string ControllerAction = sController + sAction; int ValidationType = ConstEnum.ValidateTo[ControllerAction]; int LoggenInUserId = objLoginUserDetails.LoggedInUserID; CommonDAL objCommonDAL = new CommonDAL(); CommonModel objCommonModel = new CommonModel(); CommonDTO objCommonDTO = new CommonDTO(); objCommonDTO = objCommonDAL.InitialChecks(objLoginUserDetails.CompanyDBConnectionString, ValidationType, LoggenInUserId, out RedirectionType); if (RedirectionType != 0) { path = ConstEnum.Redirect[RedirectionType]; var sType = path.GetType(); var values = new System.Web.Routing.RouteValueDictionary(); foreach (var prop in sType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { values.Add(prop.Name, Convert.ToString(prop.GetValue(path, null))); } if (objCommonDTO != null) { var sourceType = objCommonDTO.GetType(); foreach (var property in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (Convert.ToString(property.GetValue(objCommonDTO, null)) != null && Convert.ToString(property.GetValue(objCommonDTO, null)) != "") { values.Add(property.Name, Convert.ToString(property.GetValue(objCommonDTO, null))); } } } filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(values)); } } catch (Exception exp) { throw exp; } }
public override void OnAuthorization(AuthorizationContext filterContext) { if (this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { base.OnAuthorization(filterContext); } else { string ReturnURL = filterContext.RequestContext.HttpContext.Request.Path.ToString(); filterContext.Controller.TempData.Add("Message", $"you must be in at least one of the following roles to access this resource: {Roles}"); filterContext.Controller.TempData.Add("ReturnURL", ReturnURL); System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(); dict.Add("Controller", "Home"); dict.Add("Action", "Login"); filterContext.Result = new RedirectToRouteResult(dict); } }
public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { //Call base class to allow user into the action method base.OnAuthorization(filterContext); } else { string ReturnURL = filterContext.RequestContext.HttpContext.Request.Path.ToString(); filterContext.Controller.TempData.Add("Message", $"you must be logged into any account to access this resource, you are not currently logged in at all"); filterContext.Controller.TempData.Add("ReturnURL", ReturnURL); System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(); dict.Add("Controller", "Home"); dict.Add("Action", "Login"); filterContext.Result = new RedirectToRouteResult(dict); } }
/// <summary> /// Redirects to the specified action using the action name. /// </summary> /// <param name="actionName">The name of the action.</param> /// <param name="controllerName">The name of the controller</param> /// <param name="routeValues">The parameters for a route.</param> /// <returns>The redirect result object.</returns> protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, System.Web.Routing.RouteValueDictionary routeValues) { if (routeValues != null) { routeValues.Add("Area", "Admin"); } else { routeValues = new RouteValueDictionary(); routeValues.Add("Area", "Admin"); } return(base.RedirectToAction(actionName, controllerName, routeValues)); }
public ActionResult EditProfile() { UserSession userSessionMgr = (UserSession)Session[SessionManagement.Constants.UserSessionMgr]; if (userSessionMgr == null) // we were not signed on yet { return(RedirectToAction(Constants.SignOn, Constants.Account, Constants.Admin)); } if (userSessionMgr.IsAccessAllowed(Constants.UIControlCode_AdminEditProfile_Code)) { DataAccessMgr daMgr = Global.GetDataAccessMgr(this.HttpContext); DbCommand dbCmd = UserMaster.GetUserMasterCmd(daMgr); dbCmd.Parameters[daMgr.BuildParamName(DataManagement.Constants.UserId)].Value = this.HttpContext.User.Identity.Name; EditProfileModel profileData = daMgr.ExecuteCollection <EditProfileModel>(dbCmd, null).First(); return(View(Constants._Page_EditProfile, profileData)); } ViewBag.Status = "Insufficient privileges for the action." + Request.Url; string referUrl = Request.QueryString[Constants.UrlReferrer]; System.Web.Routing.RouteValueDictionary dictionary = new System.Web.Routing.RouteValueDictionary(); dictionary.Add(Constants.UrlReferrer, referUrl); return(RedirectToAction(Constants.AccessDenied, Constants.Home, dictionary)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { try { string[] Params = null; string sController = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string sAction = filterContext.ActionDescriptor.ActionName; string sControllerAction = sController + sAction; CommonDAL objCommonDAL = new CommonDAL(); CommonDTO objCommonDTO = new CommonDTO(); LoginUserDetails objLoginUserDetails = (LoginUserDetails)Common.Common.GetSessionValue(ConstEnum.SessionValue.UserDetails); if (objLoginUserDetails != null && objLoginUserDetails.CompanyDBConnectionString != null) { objCommonDTO = objCommonDAL.GlobalRedirection(objLoginUserDetails.CompanyDBConnectionString, sControllerAction, objLoginUserDetails.LoggedInUserID); //objCommonDTO = objCommonDAL.GlobalRedirectionForInitialCheck(objLoginUserDetails.CompanyDBConnectionString, sControllerAction, objLoginUserDetails.LoggedInUserID, out RedirectionType); //if (RedirectionType != 0)//"temp" && RedirectionType != null) //{ // path = ConstEnum.Redirect[RedirectionType]; // var sType = path.GetType(); var values = new System.Web.Routing.RouteValueDictionary(); // foreach (var prop in sType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) // { // values.Add(prop.Name, Convert.ToString(prop.GetValue(path, null))); // } if (objCommonDTO != null) { var sourceType = objCommonDTO.GetType(); foreach (var property in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (Convert.ToString(property.GetValue(objCommonDTO, null)) != null && Convert.ToString(property.GetValue(objCommonDTO, null)) != "") { if (property.Name == "Parameter") { Params = Convert.ToString(property.GetValue(objCommonDTO, null)).Split(','); } else { values.Add(property.Name, Convert.ToString(property.GetValue(objCommonDTO, null))); } } } if (Params != null) { for (int i = 0; i < Params.Length; i = i + 2) { values.Add(Params[i], Params[i + 1]); } } } if (values.Keys.Count != 0) { if (values.Values.Contains("UserDetails") && values.Values.Contains("ChangePassword")) { Common.Common.SetSessionValue("IsChangePassword", true); } else { Common.Common.SetSessionValue("IsChangePassword", false); } filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(values)); } } //} } catch (Exception e) { throw e; } }
public static MvcHtmlString Sorter(this HtmlHelper htmlHelper, string ColumnName, string displayText, int resultCount, string actionName, string controllerName = "", AjaxOptions ajaxOptions = null, object routeValues = null, object htmlAttributes = null, bool isAddClickAttr = false) { if (resultCount > 0) { string sortOrder = ""; var builder = new TagBuilder("a"); var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); string url = actionName; if (routeValues != null) { var rValues = new System.Web.Routing.RouteValueDictionary(routeValues); rValues.Add("fieldName", ColumnName); if (string.IsNullOrEmpty(rValues["sortOrder"].ToString())) { rValues["sortOrder"] = "desc"; } else { sortOrder = rValues["sortOrder"].ToString(); } rValues["sortOrder"] = rValues["sortOrder"].ToString() == "asc" ? "desc" : "asc"; //sortOrder = rValues["sortOrder"].ToString(); if (controllerName == "") { url = urlHelper.Action(actionName, rValues); } else { url = urlHelper.Action(actionName, controllerName, rValues); } if (isAddClickAttr) { builder.Attributes.Add("onclick", "SortingChange(this,'" + url + "','" + ColumnName + "','" + rValues["sortOrder"] + "')"); } else { builder.MergeAttribute("href", url); builder.MergeAttribute("href", "#"); } } if (htmlAttributes != null) { builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } if (ajaxOptions != null) { builder.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes()); } builder.InnerHtml = displayText; if (!string.IsNullOrEmpty(sortOrder)) { var innerTag = new TagBuilder("i"); innerTag.MergeAttribute("class", sortOrder == "asc" ? "glyphicon glyphicon-arrow-up icon-sml" : "glyphicon glyphicon-arrow-down icon-sml"); builder.InnerHtml = displayText + " " + innerTag.ToString(TagRenderMode.Normal); } return(MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal))); } else { return(MvcHtmlString.Create(displayText)); } }
bool MatchSegment(int segIndex, int argsCount, string[] argSegs, List <PatternToken> tokens, RouteValueDictionary ret) { string pathSegment = argSegs [segIndex]; int pathSegmentLength = pathSegment != null ? pathSegment.Length : -1; int startIndex = pathSegmentLength - 1; PatternTokenType tokenType; int tokensCount = tokens.Count; PatternToken token; string tokenName; for (int tokenIndex = tokensCount - 1; tokenIndex > -1; tokenIndex--) { token = tokens [tokenIndex]; if (startIndex < 0) { return(false); } tokenType = token.Type; tokenName = token.Name; if (segIndex > segmentCount - 1 || tokenType == PatternTokenType.CatchAll) { var sb = new StringBuilder(); for (int j = segIndex; j < argsCount; j++) { if (j > segIndex) { sb.Append('/'); } sb.Append(argSegs [j]); } ret.Add(tokenName, sb.ToString()); break; } int scanIndex; if (token.Type == PatternTokenType.Literal) { int nameLen = tokenName.Length; if (startIndex + 1 < nameLen) { return(false); } scanIndex = startIndex - nameLen + 1; if (String.Compare(pathSegment, scanIndex, tokenName, 0, nameLen, StringComparison.OrdinalIgnoreCase) != 0) { return(false); } startIndex = scanIndex - 1; continue; } // Standard token int nextTokenIndex = tokenIndex - 1; if (nextTokenIndex < 0) { // First token ret.Add(tokenName, pathSegment.Substring(0, startIndex + 1)); continue; } if (startIndex == 0) { return(false); } var nextToken = tokens [nextTokenIndex]; string nextTokenName = nextToken.Name; // Skip one char, since there can be no empty segments and if the // current token's value happens to be the same as preceeding // literal text, we'll save some time and complexity. scanIndex = startIndex - 1; int lastIndex = pathSegment.LastIndexOf(nextTokenName, scanIndex, StringComparison.OrdinalIgnoreCase); if (lastIndex == -1) { return(false); } lastIndex += nextTokenName.Length - 1; string sectionValue = pathSegment.Substring(lastIndex + 1, startIndex - lastIndex); if (String.IsNullOrEmpty(sectionValue)) { return(false); } ret.Add(tokenName, sectionValue); startIndex = lastIndex; } return(true); }
public string BuildUrl(Route route, RequestContext requestContext, RouteValueDictionary userValues, RouteValueDictionary constraints, out RouteValueDictionary usedValues) { usedValues = null; if (requestContext == null) { return(null); } RouteData routeData = requestContext.RouteData; RouteValueDictionary defaultValues = route != null ? route.Defaults : null; RouteValueDictionary ambientValues = routeData.Values; if (defaultValues != null && defaultValues.Count == 0) { defaultValues = null; } if (ambientValues != null && ambientValues.Count == 0) { ambientValues = null; } if (userValues != null && userValues.Count == 0) { userValues = null; } // Check URL parameters // It is allowed to take ambient values for required parameters if: // // - there are no default values provided // - the default values dictionary contains at least one required // parameter value // bool canTakeFromAmbient; if (defaultValues == null) { canTakeFromAmbient = true; } else { canTakeFromAmbient = false; foreach (KeyValuePair <string, bool> de in parameterNames) { if (defaultValues.ContainsKey(de.Key)) { canTakeFromAmbient = true; break; } } } bool allMustBeInUserValues = false; foreach (KeyValuePair <string, bool> de in parameterNames) { string parameterName = de.Key; // Is the parameter required? if (defaultValues == null || !defaultValues.ContainsKey(parameterName)) { // Yes, it is required (no value in defaults) // Has the user provided value for it? if (userValues == null || !userValues.ContainsKey(parameterName)) { if (allMustBeInUserValues) { return(null); // partial override => no match } if (!canTakeFromAmbient || ambientValues == null || !ambientValues.ContainsKey(parameterName)) { return(null); // no value provided => no match } } else if (canTakeFromAmbient) { allMustBeInUserValues = true; } } } // Check for non-url parameters if (defaultValues != null) { foreach (var de in defaultValues) { string parameterName = de.Key; if (parameterNames.ContainsKey(parameterName)) { continue; } object parameterValue = null; // Has the user specified value for this parameter and, if // yes, is it the same as the one in defaults? if (userValues != null && userValues.TryGetValue(parameterName, out parameterValue)) { object defaultValue = de.Value; if (defaultValue is string && parameterValue is string) { if (String.Compare((string)defaultValue, (string)parameterValue, StringComparison.Ordinal) != 0) { return(null); // different value => no match } } else if (defaultValue != parameterValue) { return(null); // different value => no match } } } } // We're a match, generate the URL var ret = new StringBuilder(); usedValues = new RouteValueDictionary(); bool canTrim = true; // Going in reverse order, so that we can trim without much ado int tokensCount = tokens.Length - 1; for (int i = tokensCount; i >= 0; i--) { PatternToken token = tokens [i]; if (token == null) { if (i < tokensCount && ret.Length > 0 && ret [0] != '/') { ret.Insert(0, '/'); } continue; } if (token.Type == PatternTokenType.Literal) { ret.Insert(0, token.Name); continue; } string parameterName = token.Name; object tokenValue; #if SYSTEMCORE_DEP if (userValues.GetValue(parameterName, out tokenValue)) { if (tokenValue != null) { usedValues.Add(parameterName, tokenValue.ToString()); } if (!defaultValues.Has(parameterName, tokenValue)) { canTrim = false; if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (defaultValues.GetValue(parameterName, out tokenValue)) { object ambientTokenValue; if (ambientValues.GetValue(parameterName, out ambientTokenValue)) { tokenValue = ambientTokenValue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } usedValues.Add(parameterName, tokenValue.ToString()); continue; } canTrim = false; if (ambientValues.GetValue(parameterName, out tokenValue)) { if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); usedValues.Add(parameterName, tokenValue.ToString()); } continue; } #endif } // All the values specified in userValues that aren't part of the original // URL, the constraints or defaults collections are treated as overflow // values - they are appended as query parameters to the URL if (userValues != null) { bool first = true; foreach (var de in userValues) { string parameterName = de.Key; #if SYSTEMCORE_DEP if (parameterNames.ContainsKey(parameterName) || defaultValues.Has(parameterName) || constraints.Has(parameterName)) { continue; } #endif object parameterValue = de.Value; if (parameterValue == null) { continue; } var parameterValueAsString = parameterValue as string; if (parameterValueAsString != null && parameterValueAsString.Length == 0) { continue; } if (first) { ret.Append('?'); first = false; } else { ret.Append('&'); } ret.Append(Uri.EscapeDataString(parameterName)); ret.Append('='); if (parameterValue != null) { ret.Append(Uri.EscapeDataString(de.Value.ToString())); } usedValues.Add(parameterName, de.Value.ToString()); } } return(ret.ToString()); }