public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrEmpty(ContentType))
     {
         response.ContentType = ContentType;
     }
     else
     {
         response.ContentType = "application/json";
     }
     if (ContentEncoding != null)
     {
         response.ContentEncoding = ContentEncoding;
     }
     if (Data != null)
     {
         var enumerable = Data as IEnumerable;
         if (enumerable != null)
         {
             Data = new {d = enumerable};
         }
         var serializer = new JavaScriptSerializer();
         response.Write(serializer.Serialize(Data));
     }
 }
Exemplo n.º 2
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;
            if (this.Data == null)
                return;

            var scriptSerializer = JsonSerializer.Create(this.Settings);

            scriptSerializer.Converters.Add(new CustomConverter());
            using (var sw = new StringWriter())
            {

                scriptSerializer.Serialize(sw, this.Data);
                response.Write(sw.ToString());
            }
        }
        // Executes the result (called by ASP.NET MVC).
        public override void ExecuteResult(ControllerContext context)
        {
            // Sanity check.
            if (context == null)
                throw new ArgumentNullException("context");

            // Get the current HTTP response, and clear it of content and headers.
            var response = context.HttpContext.Response;
            response.ClearHeaders();
            response.Clear();           // Intellisense says this clears headers, but it doesn't

            // Add do-not-cache headers to the response, but in a way that still allows IE to save the file.
            AddDoNotCacheHeadersToFileSaveResponse(response, context.HttpContext.Request);

            // Set the content type and disposition.
            response.ContentType = "text/csv";
            response.AddHeader("content-disposition", "attachment; filename=" + FileName);

            // Make sure the contents of the file are all sent at the same time.
            response.Buffer = true;

            // Use the Western code page 1252 encoding, which corresponds to the ISO-8859-1 standard.
            response.ContentEncoding = Encoding.GetEncoding(1252);

            // Write out the data.
            response.Write(CsvData);
        }
 public override void ExecuteResult(ControllerContext context)
 {
     context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
     base.ExecuteResult(context);
     context.HttpContext.Response.Write("</textarea></body></html>");
     context.HttpContext.Response.ContentType = "text/html";
 }
		public void Init()
		{
			var en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture	= en;
			Thread.CurrentThread.CurrentUICulture = en;

			helper = new FormHelper();

			subscription = new Subscription();
			mock = new MockClass();
			months = new[] {new Month(1, "January"), new Month(1, "February")};
			product = new Product("memory card", 10, (decimal) 12.30);
			user = new SimpleUser();
			users = new[] { new SimpleUser(1, false), new SimpleUser(2, true), new SimpleUser(3, false), new SimpleUser(4, true) };
			mock.Values = new[] { 2, 3 };

			var controller = new HomeController();
			var context = new ControllerContext();

			context.PropertyBag.Add("product", product);
			context.PropertyBag.Add("user", user);
			context.PropertyBag.Add("users", users);
			context.PropertyBag.Add("roles", new[] { new Role(1, "a"), new Role(2, "b"), new Role(3, "c") });
			context.PropertyBag.Add("sendemail", true);
			context.PropertyBag.Add("confirmation", "abc");
			context.PropertyBag.Add("fileaccess", FileAccess.Read);
			context.PropertyBag.Add("subscription", subscription);
			context.PropertyBag.Add("months", months);
			context.PropertyBag.Add("mock", mock);

			helper.SetController(controller, context);
		}
Exemplo n.º 6
0
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
     {
         throw new InvalidOperationException("JsonRequest_GetNotAllowed");
     }
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrEmpty(this.ContentType))
     {
         response.ContentType = this.ContentType;
     }
     else
     {
         response.ContentType = "application/json";
     }
     if (this.ContentEncoding != null)
     {
         response.ContentEncoding = this.ContentEncoding;
     }
     if (this.Data != null)
     {
         var json = JsonConvert.SerializeObject(this.Data, Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects });
         response.Write(json);
     }
 }
Exemplo n.º 7
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
                throw new InvalidOperationException("Cannot update instances");

            if(controllerContext.RouteData.Values.ContainsKey("r"))
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.RouteData.Values["r"].ToString()
                           };
            }
            else if(controllerContext.HttpContext.Request.QueryString["r"] != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.QueryString["r"]
                           };
            }
            else if (controllerContext.HttpContext.Request.UrlReferrer != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.UrlReferrer.PathAndQuery
                           };
            }

            return new ReturnUrl();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Enables processing of the result of an action method by a
        /// custom type that inherits from
        /// <see cref="T:System.Web.Mvc.ActionResult"/>.
        /// </summary>
        /// <param name="context">The context within which the
        /// result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            if (!String.IsNullOrEmpty(ContentType))
                response.ContentType = ContentType;
            else
                response.ContentType = "application/javascript";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Callback == null || Callback.Length == 0)
            {
                Callback = context.HttpContext.
                  Request.QueryString["callback"];
            }

            if (Data != null)
            {
                // The JavaScriptSerializer type was marked as obsolete
                // prior to .NET Framework 3.5 SP1
                JavaScriptSerializer serializer =
                     new JavaScriptSerializer();
                string ser = serializer.Serialize(Data);
                response.Write(Callback + "(" + ser + ");");
            }
        }
Exemplo n.º 9
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
                (ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
            bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
            string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";

            //since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
            //use Project.Name even if your makrup dont have Project prefix
            model.Project = new Project();
            //populate the fields of the model
            model.Project.ProjectId = 0;
            model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
            model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
            model.Project.CreatedOn  =  DateTime.Now;
            model.Project.UpdatedOn = DateTime.Now;
            model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
            model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
            model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
            model.Project.Tags = new List<Tag>();

            foreach (var tagid in GetValue(bindingContext, searchPrefix, "Tags").Split(','))
            {
                var tag = new Tag { TagId = int.Parse(tagid)};
                model.Project.Tags.Add(tag);
            }

            var total = model.Project.Tags.Count;

            return model;
        }
        public ActionDescriptorCreator FindAction(ControllerContext controllerContext, string actionName)
        {
            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (controllerContext.RouteData != null)
            {
                MethodInfo target = controllerContext.RouteData.GetTargetActionMethod();
                if (target != null)
                {
                    // short circuit the selection process if a direct route was matched.
                    return GetActionDescriptorDelegate(target);
                }
            }

            List<MethodInfo> finalMethods = ActionMethodSelector.FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods);
            
            switch (finalMethods.Count)
            {
                case 0:
                    return null;

                case 1:
                    MethodInfo entryMethod = finalMethods[0];
                    return GetActionDescriptorDelegate(entryMethod);

                default:
                    throw CreateAmbiguousActionMatchException(finalMethods, actionName);
            }
        }
 public override void ExecuteResult(ControllerContext context)
 {
     // Set the response code to 401.
     context.HttpContext.Response.StatusCode = 401;
     context.HttpContext.Response.Write("Session has expired. Please log in again!");
     context.HttpContext.Response.End();
 }
Exemplo n.º 12
0
        protected virtual object GetDictionaryModel(ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string prefix)
        {
            List<KeyValuePair<object, object>> list = new List<KeyValuePair<object, object>>();

            bool numericIndex;
            IEnumerable<string> indexes = GetIndexes(prefix, valueProvider, out numericIndex);
            Type[] genericArguments = modelType.GetGenericArguments();
            Type keyType = genericArguments[0];
            Type valueType = genericArguments[1];

            foreach (var index in indexes)
            {
                string indexPrefix = prefix + "[" + index + "]";
                if (!valueProvider.ContainsPrefix(indexPrefix) && numericIndex)
                {
                    break;
                }
                string keyPrefix = indexPrefix + ".Key";
                string valulePrefix = indexPrefix + ".Value";
                object key = GetModel(controllerContext, keyType,
                                           valueProvider, keyPrefix);
                object value = GetModel(controllerContext, valueType,
                                           valueProvider, valulePrefix);
                list.Add(new KeyValuePair<object, object>(key, value));
            }
            object model = CreateModel(modelType);
            ReplaceHelper.ReplaceDictionary(keyType, valueType, model, list);
            return model;
        }
Exemplo n.º 13
0
        public QueueableViewAsPdf(ControllerContext context, object model)
        {
            _context = context;
            _model = model;

            ViewHtmlString = GetHtmlFromView();
        }
Exemplo n.º 14
0
        public QueueableViewAsPdf(ControllerContext context, string viewName)
        {
            _context = context;
            _viewName = viewName;

            ViewHtmlString = GetHtmlFromView();
        }
Exemplo n.º 15
0
 public override void ExecuteResult(ControllerContext context)
 {
     context.HttpContext.Response.Clear();
     context.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
     context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public);
     if (id == -2)
     {
         context.HttpContext.Response.ContentType = "image/jpeg";
         context.HttpContext.Response.BinaryWrite(NoPic2());
     }
     else if (id == -2)
     {
         context.HttpContext.Response.ContentType = "image/jpeg";
         context.HttpContext.Response.BinaryWrite(NoPic1());
     }
     else
     {
         var i = ImageData.DbUtil.Db.Images.SingleOrDefault(ii => ii.Id == id);
         if (i == null)
         {
             context.HttpContext.Response.ContentType = "image/jpeg";
             context.HttpContext.Response.BinaryWrite(size == 1 ? NoPic1() : NoPic2());
         }
         else
         {
             context.HttpContext.Response.ContentType = i.Mimetype ?? "image/jpeg";
             context.HttpContext.Response.BinaryWrite(i.Bits);
         }
     }
 }
Exemplo n.º 16
0
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((this.JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet)
         && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
     {
         throw new InvalidOperationException();
     }
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrEmpty(this.ContentType))
     {
         response.ContentType = this.ContentType;
     }
     else
     {
         response.ContentType = "application/json";
     }
     if (this.ContentEncoding != null)
     {
         response.ContentEncoding = this.ContentEncoding;
     }
     if (this.Data != null)
     {
         //IsoDateTimeConverter converter = new IsoDateTimeConverter();
         //converter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
         response.Write(JsonConvert.SerializeObject(this.Data, Newtonsoft.Json.Formatting.Indented, Settings));
     }
 }
        public void UsesSpecifiedBinder()
        {
            var controller = typeof(FromRouteAttr.SpecifiedBinderController);

             routes.Clear();
             routes.MapCodeRoutes(controller);

             var httpContextMock = new Mock<HttpContextBase>();
             httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/Foo/yes");

             var httpResponseMock = new Mock<HttpResponseBase>();
             httpContextMock.Setup(c => c.Response).Returns(httpResponseMock.Object);

             var routeData = routes.GetRouteData(httpContextMock.Object);

             var controllerInstance = (ControllerBase)Activator.CreateInstance(controller);
             controllerInstance.ValidateRequest = false;

             var requestContext = new RequestContext(httpContextMock.Object, routeData);
             var controllerContext = new ControllerContext(requestContext, controllerInstance);

             controllerInstance.ValueProvider = new ValueProviderCollection(new IValueProvider[] { new RouteDataValueProvider(controllerContext) });

             ((IController)controllerInstance).Execute(requestContext);

             httpResponseMock.Verify(c => c.Write(It.Is<string>(s => s == "True")), Times.AtLeastOnce());
        }
Exemplo n.º 18
0
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null) throw new ArgumentNullException("context");
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrWhiteSpace(_contenttype)) response.ContentType = _contenttype;
     response.OutputStream.Write(this._image, 0, this._image.Length);
 }
Exemplo n.º 19
0
        public object BindModel(ControllerContext context, string modelName, Type modelType)
        {
            if (modelType.IsValueType || typeof(string) == modelType)
            {
                object instance;
                if (GetValueTypeInstance(context, modelName, modelType, out instance))
                {
                    return instance;
                }
                return Activator.CreateInstance(modelType);
            }

            object modelInstance = Activator.CreateInstance(modelType);
            foreach (PropertyInfo property in modelType.GetProperties())
            {
                if (!property.CanWrite || (!property.PropertyType.IsValueType && property.PropertyType != typeof(string)))
                {
                    continue;
                }
                object propertyValue;
                if (GetValueTypeInstance(context, property.Name, property.PropertyType, out propertyValue))
                {
                    property.SetValue(modelInstance, propertyValue, null);
                }
            }
            return modelInstance;
        }
        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (string.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "viewName");
            }

            string[] viewLocationsSearched;
            string[] masterLocationsSearched;
            bool incompleteMatch = false;

            string controllerName = controllerContext.RouteData.GetRequiredString("controller");

            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats,
                                      "ViewLocationFormats", viewName, controllerName, cacheKeyPrefix_View, useCache,
                                      /* checkPathValidity */ true, ref incompleteMatch, out viewLocationsSearched);

            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats,
                                        "MasterLocationFormats", masterName, controllerName, cacheKeyPrefix_Master,
                                        useCache, /* checkPathValidity */ false, ref incompleteMatch,
                                        out masterLocationsSearched);

            if (string.IsNullOrEmpty(viewPath) || (string.IsNullOrEmpty(masterPath) && !string.IsNullOrEmpty(masterName)))
            {
                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
            }

            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(JsonRequest_GetNotAllowed);
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                var serializer = new JavaScriptSerializer { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
                response.Write(serializer.Serialize(Data));
            }
        }
Exemplo n.º 22
0
        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();

            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }
Exemplo n.º 23
0
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            string dataRuleTypeStr;

            string dataruleTypeName = !string.IsNullOrWhiteSpace(bindingContext.ModelName) ? (bindingContext.ModelName + ".DataRuleType") : "DataRuleType";

            dataRuleTypeStr = controllerContext.HttpContext.Request[dataruleTypeName];

            if (string.IsNullOrEmpty(dataRuleTypeStr))
            {
                return null;
            }
            var dataRuleInt = Int32.Parse(dataRuleTypeStr);
            DataRuleType dataRuleTypeEnum = (DataRuleType)dataRuleInt;
            object model = null;
            switch (dataRuleTypeEnum)
            {
                case DataRuleType.Folder:
                    model = new FolderDataRule();
                    break;
                case DataRuleType.Schema:
                    model = new SchemaDataRule();
                    break;
                case DataRuleType.Category:
                    model = new CategoryDataRule();
                    break;
            }
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            return model;
        }
Exemplo n.º 24
0
        protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            if (propertyDescriptor == null)
            {
                throw new ArgumentNullException("propertyDescriptor");
            }

            if (value is string && controllerContext.HttpContext.Request.ContentType.StartsWith(WebConstants.APPLICATIONJSON, StringComparison.OrdinalIgnoreCase))
            {
                if (controllerContext.Controller.ValidateRequest && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
                {
                    int index;

                    if (IsDangerousString(value.ToString(), out index))
                    {
                        throw new HttpRequestValidationException("Dangerous Input Detected");
                    }
                }
            }

            return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Resolves the UI culture from different sources of filter context.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public static CultureInfo ResolveCulture(ControllerContext filterContext)
        {
            if (filterContext == null)
            {
                return Globalizer.GetPossibleImplemented(null);
            }

            // Priority 1: from a lang parameter in the query string
            string languageFromRoute = filterContext.RouteData.Values["lang"] != null
                ? filterContext.RouteData.Values["lang"].ToString()
                : string.Empty;
            if (!string.IsNullOrEmpty(languageFromRoute))
            {
                // Reuse UI Culture as it was set beforehand from Globalizer if CountryCulture fails
                var foundCulture = Globalizer.GetCountryCulture(languageFromRoute) ?? Thread.CurrentThread.CurrentUICulture;

                // TODO: Set in User preferences (if we will have one)
                filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(CultureCookieName) { Value = foundCulture.Name });
                return foundCulture;
            }

            // Priority 2: Get culture from user's preferences/settings (if appropriate)

            // Priority 3: Get culture from user's cookie
            HttpCookie languageCookie = filterContext.HttpContext.Request.Cookies[CultureCookieName];
            if (languageCookie != null)
            {
                string languageFromCookie = languageCookie.Value;
                if (!string.IsNullOrEmpty(languageFromCookie))
                {
                    CultureInfo cultureToSet;
                    try
                    {
                        cultureToSet = new CultureInfo(languageFromCookie);
                    }
                    catch
                    {
                        // Cookie is damaged or tampered with - setting same culture as already set for UI
                        cultureToSet = Thread.CurrentThread.CurrentUICulture;
                    }

                    return cultureToSet;
                }
            }

            // Priority 4: Get culture from user's browser
            string languageFromBrowser = CultureHelper.GetRequestLanguage(filterContext);
            if (!string.IsNullOrEmpty(languageFromBrowser))
            {
                // Reuse UI Culture as it was set beforehand from Globalizer if CountryCulture fails
                var foundCulture = Globalizer.GetCountryCulture(languageFromBrowser) ?? Thread.CurrentThread.CurrentUICulture;

                // TODO: Set in User preferences (if we will have one)
                filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(CultureCookieName) { Value = foundCulture.Name });
                return foundCulture;
            }

            // Just return same culture as UI culture, as it is set first.
            return Thread.CurrentThread.CurrentUICulture;
        }
        public object BindModel(ControllerContext controllerContext, 
            ModelBindingContext bindingContext)
        {
            // get the cart from the session

            Cart cart = null;

            if (controllerContext.HttpContext.Session != null)
            {
                cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
            }

            // create the cart if there wasn't one in the session data
            if (cart == null)
            {
                cart = new Cart();
                if (controllerContext.HttpContext.Session != null)
                {
                    controllerContext.HttpContext.Session[sessionKey] = cart;
                }
            }

            // return silly cart
            return cart;
        }
Exemplo n.º 27
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object result = null;
            var args = new BindModelEvent(controllerContext, bindingContext);
            StrixPlatform.RaiseEvent(args);

            if (args.IsBound)
            {
                result = args.Result;
            }
            else
            {
                result = base.BindModel(controllerContext, bindingContext);

                if (bindingContext.ModelMetadata.Container == null && result != null && result.GetType().Equals(typeof(string)))
                {
                    if (controllerContext.Controller.ValidateRequest)
                    {
                        int index;

                        if (IsDangerousString((string)result, out index))
                        {
                            throw new HttpRequestValidationException("Dangerous Input Detected");
                        }
                    }

                    result = GetSafeValue((string)result);
                }
            }

            return result;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Prepares the controller context.
 /// </summary>
 /// <returns>The controller context.</returns>
 public static ControllerContext PrepareControllerContext()
 {
     var requestContext = PrepareRequestContext();
     var controllerBase = MockRepository.GenerateStub<ControllerBase>();
     var controllerContext = new ControllerContext(requestContext, controllerBase);
     return controllerContext;
 }
Exemplo n.º 29
0
		//
		// GET: /Test/

		public ActionResult Index()
		{
			StringWriter sw = new StringWriter();
			IFileSystem files = N2.Context.Current.Resolve<IFileSystem>();
			List<ContentRegistration> expressions = new List<ContentRegistration>();
			foreach (var file in files.GetFiles("~/Dinamico/Themes/Default/Views/ContentPages/").Where(f => f.Name.EndsWith(".cshtml")))
			{
				var cctx = new ControllerContext(ControllerContext.HttpContext, new RouteData(), new ContentPagesController());
				cctx.RouteData.Values.Add("controller", "DynamicPages");
				var v = ViewEngines.Engines.FindView(cctx, file.VirtualPath, null);

				if (v.View == null)
					sw.Write(string.Join(", ", v.SearchedLocations.ToArray()));
				else
				{
					var temp = new ContentPage();
					cctx.RequestContext.RouteData.ApplyCurrentPath(new N2.Web.PathData(temp));
					var vdd = new ViewDataDictionary { Model = temp };
					var re = new ContentRegistration(new DefinitionMap().GetOrCreateDefinition(typeof(ContentPage)).Clone());
					N2.Web.Mvc.Html.RegistrationExtensions.SetRegistrationExpression(cctx.HttpContext, re);
					v.View.Render(new ViewContext(cctx, v.View, vdd, new TempDataDictionary(), sw), sw);
					expressions.Add(re);
				}
			}
			return View(expressions);
		}
Exemplo n.º 30
0
 public Page_Context(ControllerContext controllerContext, PageRequestContext pageRequestContext)
 {
     this.ControllerContext = controllerContext;
     this.PageRequestContext = pageRequestContext;
     Styles = new List<IHtmlString>();
     Scripts = new List<IHtmlString>();
 }
Exemplo n.º 31
0
 /// <summary>
 /// 更新缓存数据
 /// </summary>
 /// <param name="cachedResponse">可被缓存的响应数据</param>
 /// <param name="context">MVC 请求上下文</param>
 /// <param name="policy">缓存策略</param>
 protected virtual void UpdateCache(ICachedResponse cachedResponse, ControllerContext context, CachePolicy policy)
 {
     policy.UpdateCache(cachedResponse);
 }
Exemplo n.º 32
0
 public StringLengthFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
     : base(metadata, controllerContext, rule, validator)
 {
     ShouldValidate = false;
 }
Exemplo n.º 33
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "requiredif",
            };

            string depProp = BuildDependentPropertyId(metadata, context as ViewContext);

            // find the value on the control we depend on;
            // if it's a bool, format it javascript style
            // (the default is True or False!)

            StringBuilder sb = new StringBuilder();

            foreach (var obj in this._targetValue)
            {
                string targetValue = (obj ?? "").ToString();

                if (obj.GetType() == typeof(bool))
                {
                    targetValue = targetValue.ToLower();
                }

                sb.AppendFormat("|{0}", targetValue);
            }

            rule.ValidationParameters.Add("dependentproperty", depProp);
            rule.ValidationParameters.Add("targetvalue", sb.ToString().TrimStart('|'));

            yield return(rule);
        }
Exemplo n.º 34
0
 public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result)
 {
     return(new ValidationResult());                //empty errors
 }
Exemplo n.º 35
0
 public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext)
 {
     return(validationContext);
 }
Exemplo n.º 36
0
 public ValidationResult AfterMvcValidation(ControllerContext cc, ValidationContext context, ValidationResult result)
 {
     return(new ValidationResult());
 }
Exemplo n.º 37
0
 public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context)
 {
     return(null);
 }
Exemplo n.º 38
0
            public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context)
            {
                var newContext = context.Clone(selector: new MemberNameValidatorSelector(properties));

                return(newContext);
            }
 public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     if (bindingContext.ModelType == typeof(ISomeModel))
     {
         HttpRequestBase request = controllerContext.HttpContext.Request;
         bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Value");
Exemplo n.º 40
0
        public string Render(ControllerContext ContCont)
        {
            List <ItemOrdered> ItemsOrdered = SessionControl.SessionManager.GetItemsOrdered(ContCont.HttpContext.Session);
            decimal            taxrate;

            try
            {
                taxrate = Convert.ToDecimal(SessionControl.SessionManager.ReturnParameter(ContCont.HttpContext.Session, "TaxRate"));
                if (taxrate > 0)
                {
                    taxrate = taxrate / 100;
                }
            }
            catch
            {
                taxrate = 0;
            }
            if (ItemsOrdered == null)
            {
                return(RenderHelper.RenderViewToString(ContCont, "~/Views/OrderCart/_EmptyCartView.cshtml", null, ViewData));
                //return PartialView("_EmptyCartView");
            }
            List <ItemOrdered> ItemsSorted = new List <ItemOrdered>(); //ItemsOrdered.OrderBy(o=>o.Category).ThenBy(o=>o.SubCategory).ThenBy(o=>o.ItemName).ToList();

            decimal itemtotal     = 0;
            decimal shippingtotal = 0;
            decimal taxTotal      = 0;
            decimal totaltotal    = 0;
            decimal priortotal    = 0;

            ViewBag.PriorityDesc = "";

            foreach (ItemOrdered item in ItemsOrdered)
            {
                itemtotal += (item.ItemPrice * item.ItemQuantity);

                if (!KeyExists(item.SetKeys, "Shipping"))
                {
                    ItemsSorted.Add(item);
                    shippingtotal += (item.ItemShipping * item.ItemQuantity);
                    taxTotal      += taxrate * (item.ItemPrice + item.ItemShipping) * item.ItemQuantity;
                }
                else
                {
                    if (KeyValueEquals(item.SetKeys, "Shipping", "Priority"))
                    {
                        ViewBag.PriorityDesc = (ViewBag.PriorityDesc == "") ? item.ItemName : ViewBag.PriorityDesc + ", " + item.ItemName;
                        priortotal          += item.ItemShipping;
                    }
                    else
                    {
                        shippingtotal += (item.ItemShipping * item.ItemQuantity);
                    }
                }
            }
            ViewBag.PriorityAmount = priortotal;
            totaltotal             = itemtotal + shippingtotal + priortotal + taxTotal;



            ViewBag.ItemTotal     = itemtotal;
            ViewBag.ShippingTotal = shippingtotal;
            ViewBag.TotalTotal    = totaltotal;
            ViewBag.TaxTotal      = taxTotal;

            //return PartialView("_OrderCartView", ItemsSorted);

            return(RenderHelper.RenderViewToString(ContCont, "~/Views/OrderCart/_OrderCartView.cshtml", ItemsSorted, ViewData));
        }
Exemplo n.º 41
0
        /// <summary>
        /// When implemented in a class, returns client validation rules for that class.
        /// </summary>
        /// <param name="metadata">The model metadata.</param>
        /// <param name="context">The controller context.</param>
        /// <returns>The client validation rules for this validator.</returns>
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage   = ErrorMessage ?? ErrorMessageString,
                ValidationType = "greaterdate"
            };

            rule.ValidationParameters["earlierdate"] = EarlierDateField;

            yield return(rule);
        }
        /// <summary>
        /// Returns client validation rules.
        /// </summary>
        ///
        /// <returns>
        /// The client validation rules for this validator.
        /// </returns>
        /// <param name="metadata">The model metadata.</param><param name="context">The controller context.</param>
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var validationRule = new ModelClientValidationRule();

            validationRule.ErrorMessage   = ErrorMessageString;
            validationRule.ValidationType = "dategreaterthan";
            validationRule.ValidationParameters.Add("pastdate", _propertyName);

            yield return(validationRule);
        }
 public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
 {
     return(base.FindPartialView(controllerContext, partialViewName, useCache));
 }
Exemplo n.º 44
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "twosqrt",
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName())
            };

            //rule.ValidationParameters["inputstring"] = InputString;
            yield return(rule);
        }
Exemplo n.º 45
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();

            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("wordcount", _maxWords);
            rule.ValidationType = "maxwords";

            yield return(rule);
        }
Exemplo n.º 46
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ErrorMessage = UmbracoValidationHelper.GetDictionaryItem(_errorMessageDictionaryKey, _defaultText);

            var error = FormatErrorMessage(metadata.DisplayName);
            var rule  = new ModelClientValidationEqualToRule(error, _otherProperty);

            yield return(rule);
        }
Exemplo n.º 47
0
 public override void ExecuteResult(ControllerContext context)
 {
     OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
 }
Exemplo n.º 48
0
 public Task BindModelAsync(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 49
0
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            WriteToResponse(response);
        }
Exemplo n.º 50
0
 /// <summary>
 /// 创建缓存策略
 /// </summary>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <param name="parameters"></param>
 /// <returns></returns>
 protected abstract CachePolicy CreateCachePolicy(ControllerContext context, ActionDescriptor action, IDictionary <string, object> parameters);
Exemplo n.º 51
0
 public void ReleaseController(ControllerContext context, object controller)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 52
0
 /// <summary>
 /// 更新缓存数据
 /// </summary>
 /// <param name="context">控制器上下文</param>
 /// <param name="result">Action执行结果</param>
 /// <param name="mvcCachePolicy">MVC 缓存策略</param>
 protected virtual void UpdateCache(ControllerContext context, ActionResult result, IMvcCachePolicy mvcCachePolicy)
 {
     mvcCachePolicy.UpdateCache(context, result);
 }
Exemplo n.º 53
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var clientValidationRule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "fileuploadvalidator"
            };

            var clientvalidationmethods = new List <string>();
            var parameters    = new List <string>();
            var errorMessages = new List <string>();

            if (_minimumFileSizeValidator != null)
            {
                clientvalidationmethods.Add(_minimumFileSizeValidator.GetClientValidationRules(metadata, context).First().ValidationType);
                parameters.Add(_minimumFileSizeValidator.MinimumFileSize.ToString());
                errorMessages.Add(_minimumFileSizeValidator.FormatErrorMessage(metadata.GetDisplayName()));
            }

            if (_maximumFileSizeValidator != null)
            {
                clientvalidationmethods.Add(_maximumFileSizeValidator.GetClientValidationRules(metadata, context).First().ValidationType);
                parameters.Add(_maximumFileSizeValidator.MaximumFileSize.ToString());
                errorMessages.Add(_maximumFileSizeValidator.FormatErrorMessage(metadata.GetDisplayName()));
            }

            if (_validFileTypeValidator != null)
            {
                clientvalidationmethods.Add(_validFileTypeValidator.GetClientValidationRules(metadata, context).First().ValidationType);
                parameters.Add(String.Join(",", _validFileTypeValidator.ValidFileTypes));
                errorMessages.Add(_validFileTypeValidator.FormatErrorMessage(metadata.GetDisplayName()));
            }

            clientValidationRule.ValidationParameters.Add("clientvalidationmethods", clientvalidationmethods.ToConcatenatedString(s => s, ","));
            clientValidationRule.ValidationParameters.Add("parameters", parameters.ToConcatenatedString(s => s, "|"));
            clientValidationRule.ValidationParameters.Add("errormessages", errorMessages.ToConcatenatedString(s => s, ","));

            yield return(clientValidationRule);
        }
        public new IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ErrorMessage = UmbracoDictionary.GetDictionaryValue(DictionaryKey);

            yield return(new ModelClientValidationRemoteRule(FormatErrorMessage(metadata.GetDisplayName()), this.GetUrl(context), this.HttpMethod, this.AdditionalFields));
        }
Exemplo n.º 55
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule
            {
                ValidationType = "nois",
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName())
            };

            //此參數一定要是小寫!
            rule.ValidationParameters["input"] = Input;
            yield return(rule);
        }
Exemplo n.º 56
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var clientValidationRule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "minimumfilesize"
            };

            clientValidationRule.ValidationParameters.Add("size", MinimumFileSize);

            return(new[] { clientValidationRule });
        }
        public override object BindModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext)
        {
            object result = null;

            if (bindingContext.ModelType == typeof(decimal))
            {
                string modelName      = bindingContext.ModelName;
                string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;


                // Depending on cultureinfo the NumberDecimalSeparator can be "," or "."
                // Both "." and "," should be accepted, but aren't.
                string wantedSeperator    = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
                string alternateSeperator = (wantedSeperator == "," ? "." : ",");

                if (attemptedValue.IndexOf(wantedSeperator) == -1 &&
                    attemptedValue.IndexOf(alternateSeperator) != -1)
                {
                    attemptedValue = attemptedValue.Replace(alternateSeperator, wantedSeperator);
                }

                try
                {
                    result = decimal.Parse((attemptedValue != "")? attemptedValue : "0", NumberStyles.Any);
                }
                catch (FormatException e)
                {
                    bindingContext.ModelState.AddModelError(modelName, e);
                }
            }
            else if (bindingContext.ModelType == typeof(string))
            {
                string modelName = bindingContext.ModelName;
                var    value     = bindingContext.ValueProvider.GetValue(modelName);

                try
                {
                    result = Convert.ToString(value == null? "" : value.AttemptedValue);
                }
                catch (FormatException e)
                {
                    bindingContext.ModelState.AddModelError(modelName, e);
                }
            }
            else
            {
                try
                {
                    string modelName = bindingContext.ModelName;
                    var    value     = bindingContext.ValueProvider.GetValue(modelName);
                    if (value != null)
                    {
                        result = base.BindModel(controllerContext, bindingContext);
                    }
                    else
                    {
                        result = base.BindModel(controllerContext, bindingContext);
                    }
                }
                catch (FormatException e)
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, e);
                }
            }

            return(result);
        }
Exemplo n.º 58
0
        public System.Collections.Generic.IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var clientValidationRule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "validfiletype"
            };

            clientValidationRule.ValidationParameters.Add("filetypes", ValidFileTypes.ToConcatenatedString(s => s, ","));

            return(new[] { clientValidationRule });
        }
Exemplo n.º 59
0
 public FoolproofValidator(ModelMetadata metadata, ControllerContext context, ModelAwareValidationAttribute attribute)
     : base(metadata, context, attribute)
 {
 }
 public PdfPartialViewContent(string partialViewName, object model, ControllerContext controllerContext)
     : base(PdfViewContent.ViewToString(partialViewName, null, model, true, controllerContext, false))
 {
 }