private static ModelValidator GetModelValidator(this object model, ControllerBase controller)
 {
     return ModelValidator.GetModelValidator(
         ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
         controller.ControllerContext
         );
 }
        /// <summary>
        /// Sets the alert for the mvc view to render. Rendered by Html.RenderAlertMessages().
        /// </summary>
        /// <param name="controllerBase">The MVC controller from which this call is being made.</param>
        /// <param name="alert">The populated alert to show to the user.</param>
        /// <exception cref="ArgumentNullException">If either argument is null.</exception>
        public static void AppendAlert(ControllerBase controllerBase, AlertDetail alert)
        {
            if (controllerBase == null)
                throw new ArgumentNullException("controllerBase");
            if (alert == null)
                throw new ArgumentNullException("alert");

            Queue<AlertDetail> queue;

            // Get the queue
            if (alert.EnableCrossView)
                queue = controllerBase.TempData["CouncilSoft.BootstrapAlerts"] as Queue<AlertDetail>;
            else
                queue = controllerBase.ViewData["CouncilSoft.BootstrapAlerts"] as Queue<AlertDetail>;

            // Or create the queue
            if (queue == null)
                queue = new Queue<AlertDetail>();

            // Enqueue the item
            queue.Enqueue(alert);

            // Persist the updated queue.
            if (alert.EnableCrossView)
                controllerBase.TempData["CouncilSoft.BootstrapAlerts"] = queue;
            else
                controllerBase.ViewData["CouncilSoft.BootstrapAlerts"] = queue;
        }
 public ShapePartialResult(ControllerBase controller, dynamic shape)
 {
     ViewData = controller.ViewData;
     TempData = controller.TempData;
     ViewData.Model = shape;
     ViewName = "ShapeResult/DisplayPartial";
 }
        /// <summary>
        /// Ensure TempData and ViewData is copied across
        /// </summary>
        private static void CopyControllerData(ControllerContext context, ControllerBase controller)
        {
            foreach (var d in context.Controller.ViewData)
                controller.ViewData[d.Key] = d.Value;

            controller.TempData = context.Controller.TempData;
        }
        /// <summary>
        /// Get the label with the specified key from the resource files.
        /// </summary>
        /// <param name="controller">Controller that requests the resource.</param>
        /// <param name="key">The key.</param>
        /// <param name="fallbackToKey">If true then if a resource is not found with the specified key the key is returned.</param>
        private static string Resource(ControllerBase controller, RouteData routeData, string key, bool fallbackToKey)
        {
            var resClass = LocalizationHelpers.FindResourceStringClassType(controller.GetType());

            var widgetName = routeData != null ? routeData.Values["widgetName"] as string : null;
            if (!string.IsNullOrEmpty(widgetName))
            {
                var widget = FrontendManager.ControllerFactory.ResolveControllerType(widgetName);
                if (widget != null)
                {
                    var widgetResClass = LocalizationHelpers.FindResourceStringClassType(widget);
                    string res;
                    if (widgetResClass != null && Res.TryGet(widgetResClass.Name, key, out res))
                    {
                        return res;
                    }
                }
            }

            string result;
            if (Res.TryGet(resClass.Name, key, out result))
            {
                return result;
            }

            if (fallbackToKey)
            {
                return key;
            }
            
            return "#ResourceNotFound: {0}, {1}#".Arrange(resClass.Name, key);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaxonomyUrlParamsMapper" /> class.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="taxonUrlEvaluator">The taxon URL evaluator.</param>
 /// <param name="actionName">Name of the action.</param>
 public TaxonomyUrlParamsMapper(ControllerBase controller, TaxonUrlMapper taxonUrlEvaluator, string actionName = TaxonomyUrlParamsMapper.DefaultActionName)
     : base(controller)
 {
     this.actionName = actionName;
     this.taxonUrlEvaluator = taxonUrlEvaluator;
     this.actionMethod = controller.GetType().GetMethod(this.actionName, BindingFlags.Instance | BindingFlags.Public);
 }
 private static ActionDescriptor GetActionDescriptor(ControllerBase controller, RouteData routeData)
 {
     var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
     var actionName = routeData.GetRequiredString("action");
     var actionDescriptor = controllerDescriptor.FindAction(controller.ControllerContext, actionName);
     return actionDescriptor;
 }
 private static void EnsureControllerContext(ControllerBase controller)
 {
     if (controller.ControllerContext==null)
     {
         controller.ControllerContext=new ControllerContext();
     }
 }
Example #9
0
 private static IDictionary<string, MvcHtmlString> GetFlashMessages(ControllerBase controller, string sessionKey)
 {
     sessionKey = "Flash." + sessionKey;
     return (controller.TempData[sessionKey] != null
                 ? (IDictionary<string, MvcHtmlString>)controller.TempData[sessionKey]
                 : new Dictionary<string, MvcHtmlString>());
 }
Example #10
0
 public static ControllerContext CreateMockControllerContext(ControllerBase controller)
 {
     var mockHttpContext = CreateMockHttpContext();
       var controllerContext = new ControllerContext(mockHttpContext, new RouteData(), controller);
       controller.ControllerContext = controllerContext;
       return controllerContext;
 }
        public void Hydrate(ControllerBase controller)
        {
            if (string.IsNullOrEmpty(_title))
                return;

            controller.ViewBag.Title = _title;
        }
        private static void WriteForgeryToken(ControllerBase controller)
        {
            string cookieToken, formToken;
            var context = controller.ControllerContext.HttpContext;

            var oldCookie = context.Request.Cookies[AntiForgeryConfig.CookieName];
            var oldCookieToken = oldCookie != null ? oldCookie.Value : null;

            AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);
            context.Items[FlushedAntiForgeryTokenKey] = formToken;

            if (AntiForgeryConfig.RequireSsl && !context.Request.IsSecureConnection)
            {
                throw new InvalidOperationException("WebPageResources.AntiForgeryWorker_RequireSSL");
                    //TODO: Find string message
            }

            var response = context.Response;

            if (!string.IsNullOrEmpty(cookieToken))
            {
                response.Cookies.Set(new HttpCookie(AntiForgeryConfig.CookieName, cookieToken) { HttpOnly = true });
            }

            if (!AntiForgeryConfig.SuppressXFrameOptionsHeader)
            {
                // Adding X-Frame-Options header to prevent ClickJacking. See
                // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10
                // for more information.
                response.AddHeader("X-Frame-Options", "SAMEORIGIN");
            }
        }
 public FakeControllerContext(
     ControllerBase controller,
     IPrincipal principal
     )
     : base(new FakeHttpContext(principal, null, null, null, null), new RouteData(), controller)
 {
 }
Example #14
0
        public static void ToPaging(int pageIndex, int dataCount, ControllerBase controller, int pageSize = 20)
        {
            int pagesCount = 1;
            int pageStartIndex = 1;
            int pageEndIndex = 0;
            controller.ViewBag.PageNowIndex = pageIndex;
            controller.ViewBag.PageSize = pageSize;
            controller.ViewBag.PagesCount = pagesCount = pageEndIndex = int.Parse(Math.Ceiling((double)dataCount / pageSize).ToString());

            if (pagesCount > 9)
            {
                //最多显示9个页码
                if (pageIndex > 5)
                {
                    pageStartIndex = pageIndex - 4;
                    if (pagesCount - pageIndex > 4)
                        pageEndIndex = pageIndex + 4;
                }
                else
                    pageEndIndex = 9;
            }

            controller.ViewBag.PageStartIndex = pageStartIndex;
            controller.ViewBag.PageEndIndex = pageEndIndex;
        }
		public static ControllerContext CreateControllerContext (ControllerBase controller, Dictionary<string, string> formValues, 
									 HttpCookieCollection requestCookies, IDictionary<string, string> routeData)
		{
			HttpContextBase httpContext = CreateHttpContext ();

			if (formValues != null) {
				foreach (string key in formValues.Keys)
					httpContext.Request.Form.Add (key, formValues[key]);
			}

			if (requestCookies != null) {
				foreach (string key in requestCookies.Keys)
					httpContext.Request.Cookies.Add (requestCookies[key]);
			}

			RouteData route = new RouteData ();
			route.Values.Add ("controller", controller.GetType ().Name);

			if (routeData != null) {
				foreach (var valuePair in routeData)
					route.Values.Add (valuePair.Key, valuePair.Value);
			}

			return new ControllerContext (new RequestContext (httpContext, route), controller);
		}
Example #16
0
 public static void darErroresValidacion(ModelStateDictionary errores, ControllerBase controller)
 {
     var encontrados = new Dictionary<string,string>();
     var propiedades = errores.Keys.ToList();
     var errs = new List<string>();
     foreach (var item in errores.Values)
     {
         foreach (var e in item.Errors)
         {
             errs.Add(e.ErrorMessage);
         }
     }
     for (int i = 0; i <propiedades.Count; i++)
     {
         var prop = propiedades[i];
         string mensaje = string.Empty;
         try
         {
             mensaje = errs[i];
         }
         catch (Exception)
         {
             mensaje = "";
         }
         encontrados.Add(prop,mensaje);
     }
     controller.TempData["errores"] = encontrados;
 }
        public void Hydrate(ControllerBase controller)
        {
            if (_model == null)
                return;

            controller.ViewData.Model = _model;
        }
Example #18
0
        private static NavigationHubStatus OnQueryStatusCallback(
            NavigationHub hub,
            TfsWebContext tfsWebContext,
            ControllerBase controller)
        {
            if (tfsWebContext == null)
            {
                return null;
            }

            // this gets the appropriate route name for the NavigationContextLevel of the current context.
            var controllerActionRouteName = TfsRouteHelpers.GetControllerActionRouteName(tfsWebContext);

            // builds the ActionLink using that NavigationContextLevel appropriate route
            var actionLink = tfsWebContext.Url.RouteUrl(
                controllerActionRouteName,
                "index",
                "customhome",
                new { routeArea = string.Empty });

            return new NavigationHubStatus(hub)
            {
                HubGroup = WellKnownHubGroup.Custom,
                HubGroupDisplayText = CustomAreaName,
                DisplayText = "Echo",
                CommandId = "Custom.CustomHome.Index",
                Order = 100,
                ActionLink = actionLink,
                ActionArguments = new { message = "None" },
                Selected = controller is CustomHomeController
            };
        }
 public void SetController(ControllerBase cntrl)
 {
     if (controller != null && controller.Equals(cntrl))
     {
         return;
     }
     controller = cntrl;
 }
 private void ExecuteResult(ControllerBase controller)
 {
     var result = new ViewResult
                      {
                          ViewData = controller.ViewData,
                          TempData = controller.TempData
                      };
     result.ExecuteResult(controller.ControllerContext);
 }
Example #21
0
 public ControllerContext(RequestContext requestContext, ControllerBase controller)
 {
     if (requestContext == null)
     throw new ArgumentNullException("requestContext");
       if (controller == null)
     throw new ArgumentNullException("controller");
       this.RequestContext = requestContext;
       this.Controller = controller;
 }
 private ControllerContext GenerateControllerContext(ControllerBase controller)
 {
     var fakeIdentity = new GenericIdentity("Jimmy");
     var fakeUser = new GenericPrincipal(fakeIdentity,null);
     var httpContext = new Moq.Mock<HttpContextBase>();
     httpContext.Setup(x => x.User).Returns(fakeUser);
     var reqContext = new RequestContext(httpContext.Object, new RouteData());
     return new ControllerContext(reqContext, controller);
 }
        private static string InvokeAction(ControllerBase controller, string actionName, string controllerName, RouteValueDictionary routeValues)
        {
            var viewContext = new ViewContext(controller.ControllerContext, new WebFormView(controller.ControllerContext, "tmp"),
                                              controller.ViewData, controller.TempData, TextWriter.Null);

            var htmlHelper = new HtmlHelper(viewContext, new ViewPage());

            return htmlHelper.Action(actionName, controllerName, routeValues).ToString();
        }
        public static string GetViewContextValue(ControllerBase context, string valueKey)
        {
            var value = context.ValueProvider.GetValue(valueKey);

            if (value == null)
                return null;

            return value.RawValue as string;
        }
 /// <summary>
 /// Abstract method implementation to get the object in ViewData.Model
 /// </summary>
 /// <param name="controller">The controller object</param>
 /// <returns>The ViewData.Model object</returns>
 protected override object GetModel(ControllerBase controller)
 {
     object model = controller.ViewData.Model;
     if (null != model && model.GetType() == ModelType)
     {
         return model;
     }
     return null;
 }
 private static ActionExecutingContext GetFilterContext(ControllerBase controller)
 {
     controller.ControllerContext = new ControllerContext { Controller = controller };
     var actionExecutingContext = new ActionExecutingContext()
                                  	{
                                  		ActionParameters = new Dictionary<string, object>(),
                                         Controller = controller
                                  	};
     return actionExecutingContext;
 }
 protected virtual bool IsIlaroAdminController(ControllerBase controller)
 {
     var currentType = controller.GetType();
     return currentType == typeof (EntitiesController) ||
            currentType == typeof (EntityController) ||
            currentType == typeof (AccountController) ||
            currentType == typeof (GroupController) ||
            currentType == typeof (ResourceController) ||
            currentType == typeof (SharedController);
 }
Example #28
0
 public object GetFormletResult(ControllerBase controller, string actionName, HttpRequestBase request)
 {
     var type = formletType ?? controller.GetType();
     var methodName = formletMethodName ?? (actionName + "Formlet");
     var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
     if (method == null)
         throw new Exception(string.Format("Formlet method '{0}' not found in '{1}'", methodName, type));
     var formlet = method.Invoke(controller, null);
     return formlet.GetType().GetMethod("Run").Invoke(formlet, new[] { GetCollectionBySource(request) });
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomActionParamsMapper"/> class.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <param name="routeTemplateResolver">This function should return the route template that the mapper will use.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <exception cref="System.ArgumentNullException">routeTemplateResolver</exception>
        public CustomActionParamsMapper(ControllerBase controller, Func<string> routeTemplateResolver, string actionName = CustomActionParamsMapper.DefaultActionName)
            : base(controller)
        {
            if (routeTemplateResolver == null)
                throw new ArgumentNullException("routeTemplateResolver");

            this.actionName = actionName;
            this.actionMethod = controller.GetType().GetMethod(this.actionName, BindingFlags.Instance | BindingFlags.Public);
            this.routeTemplateResolver = routeTemplateResolver;
        }
Example #30
0
 /// <summary>
 /// Returns html of Mvc views.
 /// </summary>
 /// <param name="model">Model for view.</param>
 /// <param name="viewFullPath">View path to render view</param>
 /// <returns>Returns html in string.</returns>
 public static string RenderMvcViewToString(this System.Web.Mvc.ControllerBase controller, object model, string viewFullPath)
 {
     controller.ViewData.Model = model;
     using (var sw = new StringWriter())
     {
         var viewResult  = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewFullPath);
         var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
         viewResult.View.Render(viewContext, sw);
         viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
         return(sw.GetStringBuilder().ToString());
     }
 }
Example #31
0
 /// <summary>
 /// Returns html of ascx object.
 /// </summary>
 /// <typeparam name="T">Type of te model to instaniate view data dictionary</typeparam>
 /// <param name="viewPath">Path of the ascx file to render.</param>
 /// <param name="model">Model to pas .ascx</param>
 /// <param name="masterPagePath">Maser page to render in returned html.</param>
 /// <returns>Returns html in string.</returns>
 public static string RenderFormViewToString <T>(this System.Web.Mvc.ControllerBase controller, string viewPath, T model, string masterPagePath)
 {
     controller.ViewData.Model = model;
     using (var writer = new StringWriter())
     {
         var view    = new WebFormView(controller.ControllerContext, viewPath, masterPagePath);
         var vdd     = new ViewDataDictionary <T>(model);
         var viewCxt = new ViewContext(controller.ControllerContext, view, vdd, new TempDataDictionary(), writer);
         viewCxt.View.Render(viewCxt, writer);
         return(writer.ToString());
     }
 }
Example #32
0
 internal FormCollection(ControllerBase controller, Func <NameValueCollection> validatedValuesThunk, Func <NameValueCollection> unvalidatedValuesThunk)
 {
     Add(controller == null || controller.ValidateRequest ? validatedValuesThunk() : unvalidatedValuesThunk());
 }
Example #33
0
 public ControllerContext(HttpContextBase httpContext, RouteData routeData, ControllerBase controller)
     : this(new RequestContext(httpContext, routeData), controller)
 {
 }
 public object Execute(ControllerBase controller, object[] parameters)
 {
     return(_executor(controller, parameters));
 }
        protected virtual ActionResult Dynamic(ControllerBase controller, string viewName, object model, Func<ControllerBase, Dictionary<string, object>, string, object, object> json)
        {
            var propertyBag = new Dictionary<string, object>();
            
            if (model != null)
            {
                List<JsonField> properties;
                var cacheKey = model.GetType().FullName;

                if (!_propertyCache.TryGet(cacheKey, out properties))
                {
                    properties = new List<JsonField>();
                    properties.AddRange(model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        .Where(property => GetCustomAttribute(property, typeof(JsonPropertyAttribute)) != null)
                        .Select(property => new JsonField(property, (JsonPropertyAttribute)GetCustomAttribute(property, typeof(JsonPropertyAttribute))))
                        .ToList());
                    properties.AddRange(model.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                        .Where(field => GetCustomAttribute(field, typeof(JsonPropertyAttribute)) != null)
                        .Select(field => new JsonField(field, (JsonPropertyAttribute)GetCustomAttribute(field, typeof(JsonPropertyAttribute))))
                        .ToList());

                    _propertyCache.Add(cacheKey, properties);
                }

                properties.ForEach(property => propertyBag.Add(property.Name, property.GetValue(model)));
            }

            return controller.AsDynamic().Json(json(controller, propertyBag, viewName, model), JsonRequestBehavior.AllowGet);
        }