Example #1
0
                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                    if (controllerContext == null) {
                        throw new ArgumentNullException("controllerContext");
                    }

                    return new FormCollection(controllerContext.HttpContext.Request.Form);
                }
 public async override Task ExecuteResultAsync(ControllerContext context)
 {
     ViewEngineResult result;
     var viewContext = InitializeView(context, out result);
     await viewContext.View.RenderAsync(viewContext, viewContext.Writer).ConfigureAwait(false);
     ReleaseView(context, result);
 }
        public override void ExecuteResult(ControllerContext context)
        {
            if (base.Content == null)
            {
                //使用IMessageHandler输出
                if (_messageHandlerDocument == null)
                {
                    throw new Senparc.Weixin.Exceptions.WeixinException("执行WeixinResult时提供的MessageHandler不能为Null!", null);
                }

                if (_messageHandlerDocument.FinalResponseDocument == null)
                {
                    //throw new Senparc.Weixin.MP.WeixinException("FinalResponseDocument不能为Null!", null);
                }
                else
                {
                    context.HttpContext.Response.ClearContent();
                    context.HttpContext.Response.ContentType = "text/xml";

                    var xml = _messageHandlerDocument.FinalResponseDocument == null 
                                ? "" 
                                : _messageHandlerDocument.FinalResponseDocument
                                                         .ToString().Replace("\r\n", "\n"); //腾

                    using (MemoryStream ms = new MemoryStream())//迅
                    {//真
                        var bytes = Encoding.UTF8.GetBytes(xml);//的

                        context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);//很
                    }//疼
                }
            }
        }
        /// <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 = ErrorMessageString ?? "Field invalid. Field can only contain alphanumeric characters: 'a-z', 'A-Z', '0-9'.", ValidationType = clientValidationRule };
            rule.ValidationParameters.Add("pattern", RootModuleConstants.AlphanumericExpression);

            yield return rule;
        }
        public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName)
        {
            Contract.Assert(controllerContext != null);

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

            List<MethodInfo> finalMethods = FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods);

            switch (finalMethods.Count)
            {
                case 0:
                    return null;

                case 1:
                    return finalMethods[0];

                default:
                    throw CreateAmbiguousMatchException(finalMethods, actionName);
            }  
        }
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>
        /// The bound value.
        /// </returns>
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            FacebookClient client = _config.ClientProvider.CreateClient();
            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                controllerContext.HttpContext,
                rawSignedRequest =>
                {
                    return client.ParseSignedRequest(rawSignedRequest);
                });
            if (signedRequest != null)
            {
                string accessToken = signedRequest.oauth_token;
                string userId = signedRequest.user_id;
                client.AccessToken = accessToken;
                return new FacebookContext
                {
                    Client = client,
                    SignedRequest = signedRequest,
                    AccessToken = accessToken,
                    UserId = userId,
                    Configuration = _config
                };
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
            }

            return null;
        }
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            //get the car 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 cart;
        }
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {
            _adaptersLock.EnterReadLock();

            try {
                List<ModelValidator> results = new List<ModelValidator>();

                if (AddImplicitRequiredAttributeForValueTypes &&
                        metadata.IsRequired &&
                        !attributes.Any(a => a is RequiredAttribute)) {
                    attributes = attributes.Concat(new[] { new RequiredAttribute() });
                }

                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
                    DataAnnotationsModelValidationFactory factory;
                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
                        factory = DefaultAttributeFactory;
                    }
                    results.Add(factory(metadata, context, attribute));
                }

                return results;
            }
            finally {
                _adaptersLock.ExitReadLock();
            }
        }
 public bool CanFormat(ControllerContext context, object resource, string mimeType)
 {
     return ((_targetMimeType == mimeType)
             || string.IsNullOrEmpty(_targetMimeType)
             || (alsoAcceptRequestsToFormat!=null&&alsoAcceptRequestsToFormat.Contains(mimeType)))
            && FindView(context, resource).View != null;
 }
Example #10
0
        public override void ExecuteResult(ControllerContext controllerContext)
        {
            if (controllerContext != null)
            {
                var request = controllerContext.HttpContext.Request;
                object callback = request[CALLBACK_QUERYSTRING];
                if (callback == null)
                {
                    controllerContext.RouteData.Values.TryGetValue(CALLBACK_QUERYSTRING, out callback);
                }

                var hasCallback = !string.IsNullOrWhiteSpace(callback == null ? "" : callback as string);

                if (hasCallback)
                {
                    SetContentTypeIfEmpty();
                    var response = controllerContext.HttpContext.Response;

                    response.Write(callback);
                    response.Write("(");
                    base.ExecuteResult(controllerContext);
                    response.Write(")");
                }
                else
                {
                    base.ExecuteResult(controllerContext);
                }
            }
        }
Example #11
0
        /// <summary>
        ///   El código es el mismo de ASP.NET MVC 3, cambie el método que escribe en el response
        ///   http://aspnet.codeplex.com/SourceControl/changeset/view/63930#266491
        /// </summary>
        /// <param name = "context"></param>
        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(
                    "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            var 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 settings = new JsonSerializerSettings();
                settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                settings.Converters.Add(new IsoDateTimeConverter());
                response.Write(JsonConvert.SerializeObject(this.Data, Formatting.None, settings));
            }
        }
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null) {
                throw new ArgumentNullException("bindingContext");
            }

            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // case 1: there was no <input ... /> element containing this data
            if (valueResult == null) {
                return null;
            }

            string value = valueResult.AttemptedValue;

            // case 2: there was an <input ... /> element but it was left blank
            if (String.IsNullOrEmpty(value)) {
                return null;
            }

            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
            // then we need to remove these quotes put in place by the ToString() method.
            string realValue = value.Replace("\"", String.Empty);
            return Convert.FromBase64String(realValue);
        }
        ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache, bool partial)
        {
            if (controllerContext == null) throw new ArgumentNullException("controllerContext");

             RouteData routeData = controllerContext.RouteData;

             string baseLocation = routeData.DataTokens[DataTokenKeys.ViewsLocation] as string;

             ViewEngineResult result;

             if (!String.IsNullOrEmpty(baseLocation)) {

            string controller = routeData.GetRequiredString("controller");

            string location = String.Concat(baseLocation, "/", controller);

            routeData.Values["controller"] = location;

            result = (partial) ?
               this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
               : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);

            routeData.Values["controller"] = controller;

             } else {

            result = (partial) ?
               this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
               : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);
             }

             return result;
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
            User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;

            int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
            int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
            string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
            string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();

            IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);

            string[] splitIds = selectedProfilePictureIds.Split(',');
            List<int> selectedProfilePictures = new List<int>();

            foreach (string id in splitIds) {
                if (id != string.Empty) {
                    selectedProfilePictures.Add(Int32.Parse(id));
                }
            }

            return new PhotosModel() {
                UserId = myUserId,
                ProfilePictureURL = myProfilePictureURL,
                Photos = myPhotos,
                SelectedPhotos = selectedProfilePictures
            };
        }
Example #15
0
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
     if (string.IsNullOrEmpty(stringified))
         return null;
     return Serializer.Deserialize(stringified, bindingContext.ModelType);
 }
        public void Output(ControllerContext context, object resource, string contentType)
        {
            var outerStatusCode = context.RequestContext.HttpContext.Response.StatusCode;

            if (!context.Controller.GetType().Name.StartsWith("Partial"))
            {
                SetContentType(context, contentType);
            }

            var result = FindView(context, resource);
            if (result.View != null)
            {
                context.Controller.ViewData.Model = resource;

                result.View.Render(
                    new ViewContext(
                        context,
                        result.View,
                        context.Controller.ViewData,
                        new TempDataDictionary(),
                        context.HttpContext.Response.Output
                        ),
                    context.HttpContext.Response.Output
                    );
            }

            if(result.ViewEngine != null)
                result.ViewEngine.ReleaseView(context, result.View);

            context.RequestContext.HttpContext.Response.StatusCode = outerStatusCode;
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            CheckPropertyFilter(bindingContext);
            ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);
            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
                binder = Providers.GetBinder(controllerContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation and return the model
                    newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);
                    return newBindingContext.Model;
                }
            }

            return null; // something went wrong
        }
Example #18
0
        /// <summary>
        /// Execute result
        /// </summary>
        /// <param name="context"></param>
        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("HttpMethot GET not allowed.");
            }

            var response = context.HttpContext.Response;
            var json = JsonConvert.SerializeObject(new { Type, Data },
                Formatting.Indented,
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

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

            if (!string.IsNullOrEmpty(context.HttpContext.Request["callback"]))
            {
                json = string.Format("{0}({1})", context.HttpContext.Request["callback"], json);
            }

            context.HttpContext.Response.Write(json);

            base.ExecuteResult(context);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = _contentType;

            response.OutputStream.Write(_bytes, 0, _bytes.Length);
        }
        private void LogRequest(ControllerContext actionContext, string context, string actName = "", string parameterList = "")
        {
            var request = actionContext.HttpContext.Request;
            var actionName = request.RawUrl ?? actName;

            try
            {
                string userName = (request.IsAuthenticated)
                    ? actionContext.HttpContext.User.Identity.Name
                    : request.Params["userName"];

                if(string.IsNullOrEmpty(actionName))
                 actionName = ActionName;

                var sessionId = request.Params["ASP.NET_SessionId"] + "-" + userName;

                Task.Run(
                    () =>
                        _logger.Log(
                            string.Format("{0} by UserName: {1}, ActionName: {2}, Params: {3}", context, userName, actionName, parameterList),
                            LogCategory.Verbose, sessionId));
            }
            catch
            {
            }
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            DetectionGroup obj = null;

            string groupId = ModelBinderHelper.FromPostedData<String>(bindingContext, "Key");
            if (string.IsNullOrEmpty(groupId))
            {
                groupId = Guid.NewGuid().ToString("N");
                obj = (DetectionGroup)(bindingContext.Model ?? new DetectionGroup(groupId,
                    RepositoryFactory.GetRepository<IDetectionCompanyRepository, DetectionCompany>().FindBy(ModelBinderHelper.FromPostedData<String>(bindingContext, "DetectionCompany")),
                    DetectionGroupCategory.Misc));
                obj.IsLocked = false;
            }
            else
            {
                obj = RepositoryFactory.GetRepository<IDetectionGroupRepository, DetectionGroup>().FindBy(groupId);
            }

            obj.Name = ModelBinderHelper.FromPostedData<String>(bindingContext, "Name");
            obj.Telephone = ModelBinderHelper.FromPostedData<String>(bindingContext, "Telephone");

            return obj;
        }
Example #22
0
 public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return filterRegistry.Items.Where(item => item.IsMatching(controllerContext, actionDescriptor))
         .SelectMany(item => item.BuildFilters())
         .OrderBy(x => x.Order)
         .ToArray();
 }
Example #23
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            var controllerName = context.RouteData.GetRequiredString("controller");

            if (string.IsNullOrEmpty(ViewName))
            {
                ViewName = context.RouteData.GetRequiredString("action");
            }

            var searchedLocations = new List<string>();
            var factories = ViewEngines.Engines.OfType<SparkViewFactory>();

            if (!factories.Any())
                throw new CompilerException("No SparkViewFactory instances are registered");

            foreach (var factory in factories)
            {
                var descriptor = factory.DescriptorBuilder.BuildDescriptor(
                    new BuildDescriptorParams("", controllerName, ViewName, MasterName, false, factory.DescriptorBuilder.GetExtraParameters(context)), searchedLocations);
                descriptor.Language = LanguageType.Javascript;
                var entry = factory.Engine.CreateEntry(descriptor);
                context.HttpContext.Response.ContentType = "text/javascript";
                context.HttpContext.Response.Write(entry.SourceCode);
                return;
            }

            throw new CompilerException("Unable to find templates at " +
                                            string.Join(", ", searchedLocations.ToArray()));
        }
        public void TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue() {
            // Arrange
            ControllerContext controllerContext = new ControllerContext();
            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext() {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
                ModelName = "someName",
                ModelState = new ModelStateDictionary(),
                ModelBinderProviders = new ModelBinderProviderCollection(),
                ValueProvider = new SimpleValueProvider()
            };

            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();
            mockIntBinder
                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) {
                        Assert.AreEqual("someName.key", mbc.ModelName);
                        return true;
                    });
            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);

            // Act
            int model;
            bool retVal = KeyValuePairModelBinderUtil.TryBindStrongModel<int>(controllerContext, bindingContext, "key", new EmptyModelMetadataProvider(), out model);

            // Assert
            Assert.IsTrue(retVal);
            Assert.AreEqual(default(int), model);
            Assert.AreEqual(1, bindingContext.ValidationNode.ChildNodes.Count, "Child validation node should have been added.");
            Assert.AreEqual(0, bindingContext.ModelState.Count, "ModelState should remain unmodified.");
        }
 public override void ExecuteResult(ControllerContext context)
 {
     ViewEngineResult result;
     var viewContext = InitializeView(context, out result);
     viewContext.View.Render(viewContext, viewContext.Writer);
     ReleaseView(context, result);
 }
 private static string GetResourceCommon(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue, Func<ControllerContext, string> resourceAccessor)
 {
     string displayName = modelMetadata.GetDisplayName();
     string errorMessageTemplate = resourceAccessor(controllerContext);
     string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, incomingValue, displayName);
     return errorMessage;
 }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var obj = new DataTablesParam();
            var request = controllerContext.HttpContext.Request.Params;

            obj.iDisplayStart = Convert.ToInt32(request["iDisplayStart"]);
            obj.iDisplayLength = Convert.ToInt32(request["iDisplayLength"]);
            obj.iColumns = Convert.ToInt32(request["iColumns"]);
            obj.sSearch = request["sSearch"];
            obj.bEscapeRegex = Convert.ToBoolean(request["bEscapeRegex"]);
            obj.iSortingCols = Convert.ToInt32(request["iSortingCols"]);
            obj.sEcho = int.Parse(request["sEcho"]);

            for (int i = 0; i < obj.iColumns; i++)
            {
                obj.bSortable.Add(Convert.ToBoolean(request["bSortable_" + i]));
                obj.bSearchable.Add(Convert.ToBoolean(request["bSearchable_" + i]));
                obj.sSearchColumns.Add(request["sSearch_" + i]);
                obj.bEscapeRegexColumns.Add(Convert.ToBoolean(request["bEscapeRegex_" + i]));
                obj.iSortCol.Add(Convert.ToInt32(request["iSortCol_" + i]));
                obj.sSortDir.Add(request["sSortDir_" + i]);
            }

            return obj;
        }
 public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
 {
     ControllerContext = controllerContext;
     PartialViewName = partialViewName;
     View = new TestMvcView();
     return new ViewEngineResult(View, this);
 }
Example #29
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;

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

            if (Data == null)
            {
                return;
            }

            var scriptSerializer = JsonSerializer.Create(Settings);

            scriptSerializer.Serialize(response.Output, Data);
        }
Example #30
0
        protected override void OnMetadataProcess(ModelMetadata meta, string name, ViewDataDictionary viewData, ControllerContext context)
        {
            base.OnMetadataProcess(meta, name, viewData, context);

            if (name.IsEmpty())
            {
                throw new Exception("Name from ControlFor is empty");
            }

            this.Name = name;

            if (meta.IsReadOnly)
            {
                this.ReadOnly = true;
            }

            if (this.FieldLabel.IsEmpty())
            {
                this.FieldLabel = meta.GetDisplayName();
            }

            if (this.Note.IsEmpty() && meta.Description.IsNotEmpty())
            {
                this.Note = meta.Description;
            }

            ModelState modelState;
            if (viewData.ModelState.TryGetValue(name, out modelState))
            {
                if (modelState.Errors.Count > 0)
                {
                    this.CustomConfig.Add(new ConfigItem("activeError", JSON.Serialize(modelState.Errors.Select(e => e.ErrorMessage)), ParameterMode.Raw));
                }
            }
        }