Ejemplo n.º 1
0
        public async Task BindModelAsync(ModelBindingContext bindingContext) {
            var ModelValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (ModelValue == ValueProviderResult.None) return;

            Guid Id;
            if (Guid.TryParse(ModelValue.FirstValue, out Id)) {
                var database = (SharpDiskDbContext)bindingContext
                    .HttpContext
                    .RequestServices//透過DI取得本次Request產生之Scoped範圍的DbContext實例
                    .GetService(typeof(SharpDiskDbContext));

                try {
                    var result = (from t in database.Group.Include(x=>x.Owner)
                                  where t.Id == Id
                                  select t).First();
                    bindingContext.Result = ModelBindingResult.Success(result);
                } catch (Exception e) {
                    bindingContext.Result = ModelBindingResult.Failed();
                    if (e is SqlException) {
                        throw new DatabaseException(e);
                    } else if (e is InvalidOperationException) {
                        throw new EntityNotFoundException($"找不到指定的{nameof(Group)}實例", e);
                    } else {
                        throw new UnknowException(e);
                    }
                }
            } else {
                bindingContext.Result = ModelBindingResult.Failed();
            }
        }
Ejemplo n.º 2
0
        public System.Threading.Tasks.Task BindModelAsync(Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var filterLogic = bindingContext.ValueProvider.GetValue("filter[logic]");
            //           if (filterLogic == ValueProviderResult.None)
            //                      return Task.CompletedTask;

//?page=1&pageSize=20&sort[0][field]=Date&sort[0][dir]=asc&filter[logic]=and&filter[filters][0][field]=Date&filter[filters][0][operator]=gte&filter[filters][0][value]=4/1/2018
//?page=1&pageSize=20&sort[0][field]=Name&sort[0][dir]=asc&filter[logic]=and&filter[filters][0][field]=Name&filter[filters][0][operator]=contains&filter[filters][0][value]=schuebel
//&filter[logic]=and&filter[filters][0][field]=Name&filter[filters][0][operator]=contains&filter[filters][0][value]=schuebel
            var page      = bindingContext.ValueProvider.GetValue("page").FirstValue;// bindingContext.ModelName);
            var pageSize  = bindingContext.ValueProvider.GetValue("pageSize").FirstValue;
            var filtering = GetFilterObjects(bindingContext, filterLogic.FirstValue);
            var sorting   = GetSortObjects(bindingContext);

            var result = new coreevent.SearchRequest {
                Page                = int.Parse(page ?? "0"),
                PageSize            = int.Parse(pageSize ?? "25"),
                FilterObjectWrapper = filtering,
                SortObjects         = sorting
            };

            bindingContext.Result = ModelBindingResult.Success(result);
            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
		/// <summary>
		/// Binds the model.
		/// </summary>
		public async Task BindModelAsync(ModelBindingContext bindingContext)
		{
			var typeFieldNamePrefix = !string.IsNullOrEmpty(bindingContext.ModelName)
				? $"{bindingContext.ModelName}."
				: "";

			var typeName = (string)bindingContext.ValueProvider
				.GetValue($"{typeFieldNamePrefix}{_baseType.Name}Type")
				.ConvertTo(typeof(string));

			if (typeName == null)
				return;
			
			var derivedModelBinderKvp = _derivedModelBinders.First(kvp => kvp.Key.Name == typeName);
			var derivedModelType = derivedModelBinderKvp.Key;
			var derivedModelBinder = derivedModelBinderKvp.Value;

			ModelBindingResult result;
			using (bindingContext.EnterNestedScope(
				_modelMetadataProvider.GetMetadataForType(derivedModelType),
				bindingContext.FieldName,
				bindingContext.ModelName,
				model: null
				))
			{
				await derivedModelBinder.BindModelAsync(bindingContext);
				result = bindingContext.Result;
			}

			bindingContext.Result = result;
		}
Ejemplo n.º 4
0
        protected coreevent.FilterObjectWrapper GetFilterObjects(Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext bindingContext, string filterLogic)
        {
            var list       = new List <coreevent.FilterObject>();
            var filterKeys = new List <KeyValuePair <string, string> >();

            //&filter[logic]=and&filter[filters][0][field]=Date&filter[filters][0][operator]=contains&filter[filters][0][value]=4/1/2018
            //&filter[logic]=and&filter[filters][0][field]=Date&filter[filters][0][operator]=gte&filter[filters][0][value]=Mon+Apr+23+2018+00%3A00%3A00+GMT-0500+(Central+Daylight+Time)&filter[filters][1][field]=Date&filter[filters][1][operator]=lte&filter[filters][1][value]=Mon+Apr+30+2018+00%3A00%3A00+GMT-0500+(Central+Daylight+Time)&_=1562110553341
            for (int i = 0; i < 10; i++)
            {
                var fieldName = bindingContext.ValueProvider.GetValue($"filter[filters][{i}][field]").FirstValue;
                if (fieldName == null)
                {
                    break;
                }
                else
                {
                    var fltObj = new coreevent.FilterObject();
                    fltObj.Field1    = fieldName;
                    fltObj.Operator1 = bindingContext.ValueProvider.GetValue($"filter[filters][{i}][operator]").FirstValue;
                    fltObj.Value1    = bindingContext.ValueProvider.GetValue($"filter[filters][{i}][value]").FirstValue;

                    list.Add(fltObj);
                }
            }
            return(new coreevent.FilterObjectWrapper(filterLogic, list));
        }
Ejemplo n.º 5
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            object value;
            if(!bindingContext.ActionContext.HttpContext.Items.TryGetValue(DefaultRouter.CurrentNodeKey, out value))
            {
                bindingContext.Result = ModelBindingResult.Failed();
                //return await ModelBindingResult.NoResultAsync;
            }
            TrieNode node = value as TrieNode;
            if (node == null)
            {
                bindingContext.Result = ModelBindingResult.Failed();
                //return await ModelBindingResult.NoResultAsync;
            }

            var requestCultureFeature = bindingContext.ActionContext.HttpContext.Features.Get<IRequestCultureFeature>();
            var requestCulture = requestCultureFeature.RequestCulture;

            using (var session = _documentStore.OpenAsyncSession())
            {
                bindingContext.Result = ModelBindingResult.Success(await session.LoadAsync<dynamic>(string.Join("/", node.PageId, requestCulture.Culture.TwoLetterISOLanguageName,"content")));
/*                return await ModelBindingResult.SuccessAsync(bindingContext.FieldName,
                    );*/
            }
        }
Ejemplo n.º 6
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (!bindingContext.ModelMetadata.IsEnumerableType)
            {
                bindingContext.Result = ModelBindingResult.Failed();
                return(Task.CompletedTask);
            }
            var providedValue = bindingContext.ValueProvider
                                .GetValue(bindingContext.ModelName)
                                .ToString();

            if (string.IsNullOrEmpty(providedValue))
            {
                bindingContext.Result = ModelBindingResult.Success(null);
                return(Task.CompletedTask);
            }
            var genericType =
                bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
            var converter   = TypeDescriptor.GetConverter(genericType);
            var objectArray = providedValue.Split(new[] { "," },
                                                  StringSplitOptions.RemoveEmptyEntries)
                              .Select(x => converter.ConvertFromString(x.Trim()))
                              .ToArray();
            var guidArray = Array.CreateInstance(genericType, objectArray.Length);

            objectArray.CopyTo(guidArray, 0);
            bindingContext.Model  = guidArray;
            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            return(Task.CompletedTask);
        }
Ejemplo n.º 7
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            object value;
            if (!bindingContext.ActionContext.HttpContext.Items.TryGetValue(DefaultRouter.CurrentNodeKey, out value))
            {
                bindingContext.Result = ModelBindingResult.Failed();
                //return await ModelBindingResult.NoResultAsync;
            }
            TrieNode node = value as TrieNode;
            if (node == null)
            {
                bindingContext.Result = ModelBindingResult.Failed();
                //return await ModelBindingResult.NoResultAsync;
            }

            var requestCultureFeature = bindingContext.ActionContext.HttpContext.Features.Get<IRequestCultureFeature>();
            var requestCulture = requestCultureFeature.RequestCulture;

            using (var session = _documentStore.OpenAsyncSession())
            {
                var localizedPage = await session.LocalizeFor(requestCulture.Culture).LoadAsync<Page>(node.PageId);
                bindingContext.ActionContext.HttpContext.Items[DefaultRouter.CurrentPageKey] = localizedPage;
                bindingContext.Result = ModelBindingResult.Success(localizedPage);
                //return await ModelBindingResult.SuccessAsync(bindingContext.ModelName, localizedPage);
            }
        }
Ejemplo n.º 8
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            if (bindingContext.ModelType == typeof(bool))
            {
                var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (valueProviderResult == ValueProviderResult.None)
                {
                    return Task.CompletedTask;
                }

                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                if (valueProviderResult.Values == "✓")
                {
                    bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, true);
                }
                else if (valueProviderResult.Values == "✗")
                {
                    bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, false);
                }
            }

            return TaskCache.CompletedTask;
        }
 public TrimmingModelBinderTests()
 {
     binder = new TrimmingModelBinder();
     context = new DefaultModelBindingContext();
     context.ModelState = new ModelStateDictionary();
     context.ValueProvider = Substitute.For<IValueProvider>();
 }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult == null)
            {
                return(Task.CompletedTask);
            }

            var value = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(value))
            {
                return(Task.CompletedTask);
            }

            // Remove unnecessary commas and spaces //  string.Empty
            value = value.Replace(".", ",").Trim();

            decimal myValue = 0;

            if (!decimal.TryParse(value, out myValue))
            {
                // Error
                bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    "Could not parse MyValue.");
                return(Task.CompletedTask);
            }

            bindingContext.Result = ModelBindingResult.Success(myValue);
            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
        private static Type ResolveBinderType(ModelBindingContext context)
        {
            var modelType = context.ModelType;

            return GetPageModelBinder(modelType) ??
                   GetModelBinder(modelType);
        }
        public Task BindModelAsync(Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext bindingContext)
        {
            var discriminator = bindingContext.ValueProvider.GetValue("Account.AccountType").ToString();
            var myType        = AccountExtensions.Type(discriminator);
            var r             = new Assignement
            {
                Account = Account.GetInstanceOf(myType)
            };

            r.Account.Id       = bindingContext.ValueProvider.GetValue("Account.Id").ToString();
            r.Account.Nickname = bindingContext.ValueProvider.GetValue("Account.Nickname").ToString();
            r.Account.Email    = bindingContext.ValueProvider.GetValue("Account.Email").ToString();
            r.User.Name        = bindingContext.ValueProvider.GetValue("User.Name").ToString();
            r.User.Surname     = bindingContext.ValueProvider.GetValue("User.Surname").ToString();
            //var result = Account.GetInstanceOf(discriminator);
            //result.Id = bindingContext.ValueProvider.GetValue("Account.Id").ToString();
            //result.Nickname = bindingContext.ValueProvider.GetValue("Account.Nickname").ToString();
            //result.Email = bindingContext.ValueProvider.GetValue("Account.Email").ToString();
            //  result.User.Id = bindingContext.ValueProvider.GetValue("User.Id").ToString();
            //bindingContext.ModelState.SetModelValue(
            //        bindingContext.ModelName, );
            bindingContext.Result = ModelBindingResult.Success(r);
            return(Task.CompletedTask);
            //return ModelBindingResult.Success(result);
        }
		public async Task BindModelAsync(ModelBindingContext bindingContext)
		{
			if (bindingContext == null)
			{
				throw new ArgumentNullException(nameof(bindingContext));
			}

			try
			{
				var model = (ICustomRepresentationModel)Activator.CreateInstance(bindingContext.ModelType);
				if (!model.CanRead(bindingContext.HttpContext))
				{
					// TODO: Consider to add reference to Model documentation
					bindingContext.ModelState.TryAddModelError(
						bindingContext.ModelName,
						"Imposible to parse request body, verify Content-Type header.");
					// This model binder is the only handler for ICustomRepresentationModel binding source and it cannot run
					// twice. Always tell the model binding system to skip other model binders and never to fall back i.e.
					// indicate a fatal error.
					return;
				}
				await model.SetContentAsync(bindingContext.HttpContext.Request);
				bindingContext.Result = ModelBindingResult.Success(model);
			}
			catch (Exception exception)
			{
				bindingContext.ModelState.TryAddModelError(
					bindingContext.ModelName,
					exception,
					bindingContext.ModelMetadata);
			}
		}
Ejemplo n.º 14
0
        /// <inheritdoc />
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var model = bindingContext.HttpContext.GetHttpRequestMessage();
            bindingContext.ValidationState.Add(model, new ValidationStateEntry() { SuppressValidation = true });
            bindingContext.Result = ModelBindingResult.Success(model);

            return TaskCache.CompletedTask;
        }
Ejemplo n.º 15
0
        private async Task BindModelAsync(ModelBindingContext bindingContext, IModelBinder binder)
        {
            await binder.BindModelAsync(bindingContext);
            
/*            bindingContext.Result = await binder.BindModelAsync(bindingContext);
            var modelBindingResult = result != ModelBindingResult.NoResult
                ? result
                : ModelBindingResult.NoResult;

            return bindingContext;*/
        }
Ejemplo n.º 16
0
        public virtual async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            BindModelCount += 1;

            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            Debug.Assert(bindingContext.Result == null);

            await _callback.Invoke(bindingContext);
        }
Ejemplo n.º 17
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {            
            IFormCollection form = await bindingContext.ActionContext.HttpContext.Request.ReadFormAsync();
            var contentType = form[ContentType];
            if (string.IsNullOrEmpty(contentType))
            {
                bindingContext.Result = ModelBindingResult.Failed();
                //return ModelBindingResult.NoResult;
            }
            var model = Activator.CreateInstance(Type.GetType(contentType));

            bindingContext.Result = ModelBindingResult.Success(model);
        }
Ejemplo n.º 18
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var modelStringValue = bindingContext.HttpContext.Request.Query[bindingContext.ModelName];

            var result = JsonConvert.DeserializeObject(modelStringValue, bindingContext.ModelType, JsonFormatter.SerializerSettings);

            var metadataProvider = (IModelMetadataProvider)bindingContext.HttpContext.RequestServices.GetService(typeof(IModelMetadataProvider));

            bindingContext.ModelMetadata = metadataProvider.GetMetadataForType(result.GetType());
            bindingContext.Result = ModelBindingResult.Success(result);

            return Task.CompletedTask;
        }
Ejemplo n.º 19
0
        private ModelBindingResult BindModel(ModelBindingContext context)
        {
            ValueProviderResult result = context.ValueProvider.GetValue(context.ModelName);
            if (result == ValueProviderResult.None)
                return context.Result;

            String value = result.FirstValue.Trim();
            context.ModelState.SetModelValue(context.ModelName, result);

            if (value.Length == 0 && context.ModelMetadata.ConvertEmptyStringToNull)
                return ModelBindingResult.Success(null);

            return ModelBindingResult.Success(value);
        }
Ejemplo n.º 20
0
        public Task BindModelAsync(Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            var buffer = new byte[Convert.ToInt32(bindingContext.ActionContext.HttpContext.Request.ContentLength)];

            bindingContext.ActionContext.HttpContext.Request.Body.ReadAsync(buffer, 0, buffer.Length);
            var body = Encoding.UTF8.GetString(buffer);
            List <Dictionary <string, object> > result = JSONSerializer.Deserialize <List <Dictionary <string, object> > >(body);

            bindingContext.Result = ModelBindingResult.Success(result);
            return(Task.CompletedTask);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));

            _baseBinder.BindModelAsync(bindingContext);


            if (bindingContext.Result.IsModelSet)
            {
                var timeZoneId = bindingContext.ValueProvider.GetValue(_timeZoneIdPropertyName).FirstValue;
                var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
                DateTimeOffset dateTimeOffsetModel = (DateTimeOffset)bindingContext.Result.Model;
                var adjustedDateTimeOffset = new DateTimeOffset(dateTimeOffsetModel.DateTime, timeZone.GetUtcOffset(dateTimeOffsetModel.DateTime));
                bindingContext.Result = ModelBindingResult.Success(adjustedDateTimeOffset);
            }

            return TaskCache.CompletedTask;
        }
Ejemplo n.º 22
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var binderType = ResolveBinderType(bindingContext);
            if (binderType == null)
            {
                bindingContext.Result = ModelBindingResult.Failed();
            }

            var binder = (IModelBinder)Activator.CreateInstance(binderType, _documentStore);

            var collectionBinder = binder as ICollectionModelBinder;
            if (collectionBinder != null &&
                bindingContext.Model == null &&
                !collectionBinder.CanCreateInstance(bindingContext.ModelType))
            {
                // Able to resolve a binder type but need a new model instance and that binder cannot create it.
                bindingContext.Result = ModelBindingResult.Failed();
            }

            return BindModelAsync(bindingContext, binder);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Binds the DateTime object.
        /// </summary>
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value.FirstValue == null && bindingContext.ModelType == typeof(DateTime?))
            {
                bindingContext.Result = ModelBindingResult.Success(null);
                return Task.CompletedTask;
            }

            DateTime dateTime;
            if (!DateTime.TryParse(value.FirstValue, out dateTime))
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid date/time.");
                bindingContext.Result = ModelBindingResult.Failed();
                return Task.CompletedTask;
            }

            bindingContext.Result = ModelBindingResult.Success(_timeZoneProvider.ToUtcTime(dateTime));
            return Task.CompletedTask;
        }
Ejemplo n.º 24
0
        protected ICollection <coreevent.SortObject> GetSortObjects(Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext bindingContext)
        {
            var list       = new List <coreevent.SortObject>();
            var filterKeys = new List <KeyValuePair <string, string> >();

            //sort[0][field]=Date&sort[0][dir]=asc
            for (int i = 0; i < 10; i++)
            {
                var fieldName = bindingContext.ValueProvider.GetValue($"sort[{i}][field]").FirstValue;
                if (fieldName == null)
                {
                    break;
                }
                else
                {
                    var srtObj = new coreevent.SortObject(fieldName, bindingContext.ValueProvider.GetValue($"sort[{i}][dir]").FirstValue);

                    list.Add(srtObj);
                }
            }
            return(list);
        }
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            await _simpleTypeModelBinder.BindModelAsync(bindingContext);

            if (!bindingContext.Result.IsModelSet)
            {
                return;
            }

            if (_type == typeof(DateTime))
            {
                var dateTime = (DateTime)bindingContext.Result.Model;
                bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime));
            }
            else
            {
                var dateTime = (DateTime?)bindingContext.Result.Model;
                if (dateTime != null)
                {
                    bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime.Value));
                }
            }
        }
Ejemplo n.º 26
0
		/// <summary>Attempts to bind a model.</summary>
		/// <param name="bindingContext">The <see cref="ModelBindingContext" />.</param>
		/// <returns>
		///     <para>
		///         A <see cref="System.Threading.Tasks.Task" /> which will complete when the model binding process completes.
		///     </para>
		///     <para>
		///         If model binding was successful, the <see cref="ModelBindingContext.Result" /> should have
		///         <see cref="ModelBindingResult.IsModelSet" /> set to <c>true</c>.
		///     </para>
		///     <para>
		///         A model binder that completes successfully should set <see cref="ModelBindingContext.Result" /> to
		///         a value returned from <see cref="ModelBindingResult.Success(object)" />.
		///     </para>
		/// </returns>
		public Task BindModelAsync(ModelBindingContext bindingContext)
		{
			// Only accept enum values
			if (!bindingContext.ModelMetadata.IsFlagsEnum)
			{
				return TaskCache.CompletedTask;
			}

			var provideValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

			// Do nothing if there is no actual values
			if (provideValue == ValueProviderResult.None)
			{
				return TaskCache.CompletedTask;
			}

			// Get the real enum type
			var enumType = bindingContext.ModelType;
			enumType = Nullable.GetUnderlyingType(enumType) ?? enumType;

			// Each value self may contains a series of actual values, split it with comma
			var strs = provideValue.Values.SelectMany(s => s.Split(','));

			// Convert all items into enum items.
			var actualValues = strs.Select(valueString => Enum.Parse(enumType, valueString));

			// Merge to final result
			var result = actualValues.Aggregate(0, (current, value) => current | (int) value);

			// Convert to Enum object
			var realResult = Enum.ToObject(enumType, result);

			// Result
			bindingContext.Result = ModelBindingResult.Success(realResult);

			return TaskCache.CompletedTask;
		}
 public Task BindModelAsync(ModelBindingContext bindingContext)
 {
     bindingContext.Result = ModelBindingResult.Success(null);
     return Microsoft.AspNetCore.Mvc.Internal.TaskCache.CompletedTask;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Initializes the <see cref="NestedScope"/> for a <see cref="ModelBindingContext"/>.
 /// </summary>
 /// <param name="context"></param>
 public NestedScope(ModelBindingContext context)
 {
     _context = context;
 }
Ejemplo n.º 29
0
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }
                Debug.Assert(bindingContext.Result == null);

                throw new NotImplementedException();
            }
Ejemplo n.º 30
0
 public Task BindModelAsync(ModelBindingContext bindingContext)
 {
     return TaskCache.CompletedTask;
 }
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }

                Debug.Assert(bindingContext.Result == ModelBindingResult.Failed());

                var allowedBindingSource = bindingContext.BindingSource;
                if (allowedBindingSource == null ||
                    !allowedBindingSource.CanAcceptDataFrom(BindAddressAttribute.Source))
                {
                    // Binding Sources are opt-in. This model either didn't specify one or specified something
                    // incompatible so let other binders run.
                    return TaskCache.CompletedTask;
                }

                bindingContext.Result = ModelBindingResult.Success(new Address());
                return TaskCache.CompletedTask;
            }
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(ClassifyImageViewModel))
            {
                bindingContext.Result = ModelBindingResult.Failed();
                return;
            }

            var result = new ClassifyImageViewModel();

            try
            {
                result.ImageData = (string)bindingContext.ValueProvider.GetValue(ImageDataKey);
                result.ImageSet = ((string)bindingContext.ValueProvider.GetValue(UseImageSetKey)) ??
                    ((string)bindingContext.ValueProvider.GetValue(TestImageSetKey));
                result.Url = (string)bindingContext.ValueProvider.GetValue(UrlKey);

                Uri imageUri;
                string fileExt = "";
                result.IsUrl = Uri.TryCreate(result.Url, UriKind.Absolute, out imageUri);
                if (result.IsUrl)
                {
                    // download the file
                    using (var client = new HttpClient())
                    {
                        var response = await client.GetAsync(result.Url);
                        if (!response.IsSuccessStatusCode)
                        {
                            // return 400 status
                            bindingContext.Result = ModelBindingResult.Failed();
                            return;
                        }

                        fileExt = Path.GetExtension(result.Url);
                        result.ImageByteContent = await response.Content.ReadAsByteArrayAsync();
                    }
                }
                else if (!string.IsNullOrEmpty(result.Url))
                {
                    // relative path given for a sample image
                    try
                    {
                        fileExt = Path.GetExtension(result.Url);
                        var hostingEnvironmentService = (IHostingEnvironment)bindingContext
                            .HttpContext.RequestServices.GetService(typeof(IHostingEnvironment));

                        result.ImageByteContent = File.ReadAllBytes(
                            Path.Combine(hostingEnvironmentService.WebRootPath, result.Url));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                }
                else if (!string.IsNullOrEmpty(result.ImageData))
                {
                    string fileType = "";
                    string encodedFile = "";
                    try
                    {
                        var fileEncoderService = (IFileEncoderService)bindingContext.HttpContext
                            .RequestServices.GetService(typeof(IFileEncoderService));

                        string[] encodedFileParts = result.ImageData.Split(';');
                        encodedFile = encodedFileParts[1].Split(',')[1];
                        fileType = encodedFileParts[0].Split('/')[1];
                        fileExt = "." + fileType;
                        result.ImageByteContent = await fileEncoderService.DecodeFileAsync(encodedFile);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                }
                if (!string.IsNullOrEmpty(fileExt))
                {
                    result.ImageFileName = result.ImageSet + fileExt;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                bindingContext.Result = ModelBindingResult.Failed();
                return;
            }

            try
            {
                string classifierJson = bindingContext.HttpContext.Request.Cookies[CookiesClassifierKey];
                // only use this classifier if we're looking at test images
                if (classifierJson != null &&
                    !string.IsNullOrEmpty(((string)bindingContext.ValueProvider.GetValue(TestImageSetKey))))
                {
                    result.Classifier = ClassifierMapper.Map(
                        Newtonsoft.Json.JsonConvert.DeserializeObject<Classifier>(classifierJson));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            bindingContext.Result = ModelBindingResult.Success(result);
            return;
        }
Ejemplo n.º 33
0
 public Task BindModelAsync(ModelBindingContext bindingContext)
 {
     return Inner.BindModelAsync(bindingContext);
 }
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }

                Debug.Assert(bindingContext.Result == ModelBindingResult.Failed());

                if (bindingContext.ModelType != typeof(Address3))
                {
                    return TaskCache.CompletedTask;
                }

                var address = new Address3 { Street = "SomeStreet" };

                bindingContext.ModelState.SetModelValue(
                    ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Street"),
                    new string[] { address.Street },
                    address.Street);

                bindingContext.Result = ModelBindingResult.Success(address);
                return TaskCache.CompletedTask;
            }
 public Task BindModelAsync(ModelBindingContext bindingContext) {
     var loadOptions = new DataSourceLoadOptions();
     DataSourceLoadOptionsParser.Parse(loadOptions, key => bindingContext.ValueProvider.GetValue(key).FirstOrDefault());
     bindingContext.Result = ModelBindingResult.Success(loadOptions);
     return Task.CompletedTask;
 }
Ejemplo n.º 36
0
 public Task BindModelAsync(ModelBindingContext context)
 {
     return new SimpleTypeModelBinder(typeof(String)).BindModelAsync(context);
 }
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }
                Debug.Assert(bindingContext.Result == ModelBindingResult.Failed());

                var model = "Success";
                bindingContext.ModelState.SetModelValue(
                    bindingContext.ModelName,
                    new string[] { model },
                    model);

                bindingContext.Result =ModelBindingResult.Success(model);
                return TaskCache.CompletedTask;
            }
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }
                Debug.Assert(bindingContext.Result == ModelBindingResult.Failed());

                bindingContext.Result = ModelBindingResult.Failed();
                return TaskCache.CompletedTask;
            }