Ejemplo n.º 1
0
        public void Everything_should_match_hash()
        {
            var bindingInfo = new BindingInfo(new QueueInfo("the queue", true, false, false, null), "#");

            bindingInfo.RoutingKeyMatches("abc").ShouldBeTrue();
            bindingInfo.RoutingKeyMatches("def").ShouldBeTrue();
        }
Ejemplo n.º 2
0
        //        private DomainModel.Person.PersonRole TransformRole(DTO.Role role)
        //        {
        //            return (DomainModel.Person.PersonRole)Enum.Parse(
        //                    typeof(DomainModel.Person.PersonRole), role.ToString(), true);
        //        }
        public void AddPerson(DTO.Person dto, BindingInfo personBinding,
            BindingInfo[] addressBindings)
        {
            //            DomainModel.Person person = new DomainModel.Person(dto.Name, dto.Password);
            DomainModel.Person person = ((Person.PersonFactory)Registry.Instance.getFactory(typeof(Person)))
                .createPerson(dto.Name, dto.Password);
            //            if(dto.Roles != null)
            //            {
            //                foreach(DTO.Role role in dto.Roles)
            //                {
            //                    person.AddRole(TransformRole(role));
            //                }
            //            }
            new TimestampIdBinding(person, personBinding);
            if(dto.Addresses != null)
            {
                for(int i = 0; i < dto.Addresses.Length; i++)
                {
                    DTO.Address dtoAddress = dto.Addresses[i];

                    Address address = ((Address.AddressFactory)Registry.Instance.getFactory(typeof(Address)))
                        .createAddress(person, dtoAddress.City, dtoAddress.Street, dtoAddress.Postalcode,
                            dtoAddress.Phone, dtoAddress.Email);
                    person.addAddress(address);
            //                    DomainModel.Address address =
            //                        person.AddAddress(dtoAddress.Street,
            //                            dtoAddress.City, dtoAddress.Postalcode,
            //                            dtoAddress.Email, dtoAddress.Phone);

                    new TimestampIdBinding(address, addressBindings[i]);
                }
            }
        }
Ejemplo n.º 3
0
        public void Should_exact_match_should_match()
        {
            var bindingInfo = new BindingInfo(new QueueInfo("the queue", true, false, false, null), "abc");

            bindingInfo.RoutingKeyMatches("abc").ShouldBeTrue();
            bindingInfo.RoutingKeyMatches("def").ShouldBeFalse();
        }
Ejemplo n.º 4
0
        public void Dot_separated_keys_should_match_with_wild_cards()
        {
            var bindingInfo = new BindingInfo(new QueueInfo("the queue", true, false, false, null), "a.*.c");

            bindingInfo.RoutingKeyMatches("a.b.c").ShouldBeTrue();
            bindingInfo.RoutingKeyMatches("a.d.c").ShouldBeTrue();
            bindingInfo.RoutingKeyMatches("a.b.d").ShouldBeFalse();
        }
Ejemplo n.º 5
0
        public DomainModel.Product AddProduct(DTO.Product dto, BindingInfo bindingInfo)
        {
            //            DomainModel.Product product = new DomainModel.Product(
            //                dto.Name, dto.QuantityPerUnit, dto.UnitPrice, dto.Category);
            Product product = ((Product.ProductFactory)Registry.Instance.getFactory(typeof(Product)))
                .createProduct(dto.Name, dto.QuantityPerUnit, dto.UnitPrice, dto.Category);

            new TimestampIdBinding(product, bindingInfo);
            return product;
        }
Ejemplo n.º 6
0
        //        public void AddRole(int personId, DTO.Role role, BindingInfo bindingInfo)
        //        {
        //            DomainModel.Person person = LoadPerson(personId);
        //            person.AddRole(TransformRole(role));
        //            new TimestampIdBinding(person, bindingInfo);
        //        }
        //
        //        public void RemoveRole(int personId, DTO.Role role, BindingInfo bindingInfo)
        //        {
        //            DomainModel.Person person = LoadPerson(personId);
        //            person.RemoveRole(TransformRole(role));
        //            new TimestampIdBinding(person, bindingInfo);
        //        }
        public void AddAddress(int personId, DTO.Address dto, BindingInfo bindingInfo)
        {
            DomainModel.Person person = LoadPerson(personId);
            Address address = ((Address.AddressFactory)Registry.Instance.getFactory(typeof(Address)))
                .createAddress(person, dto.City, dto.Street, dto.Postalcode, dto.Phone, dto.Email);
            person.addAddress(address);
            //            DomainModel.Address address = person.AddAddress(
            //                dto.Street, dto.City, dto.Postalcode, dto.Email, dto.Phone);

            new TimestampIdBinding(address, bindingInfo);
        }
Ejemplo n.º 7
0
 public void AddOrderDetail(int orderId, DTO.OrderDetail dto, 
     BindingInfo bindingInfo)
 {
     DomainModel.Order order = LoadOrder(orderId);
     if(order != null)
     {
         DomainModel.Product product = ProductService.LoadProduct(dto.ProductId);
         DomainModel.OrderDetail detail =
             order.AddOrderDetail(product, dto.UnitPrice, dto.Quantity);
         new TimestampIdBinding(detail, bindingInfo);
     }
 }
Ejemplo n.º 8
0
 public void UpdateProduct(DTO.Product dto, BindingInfo bindingInfo)
 {
     DomainModel.Product product = LoadProduct(dto.Id);
     if(product != null)
     {
         if(product.Timestamp.Equals(new Timestamp(dto.Timestamp)) == false)
             throw new ApplicationException("ConcurrencyException");
         product.ProductName = dto.Name;
         product.QuantityPerUnit = dto.QuantityPerUnit;
         product.UnitPrice = dto.UnitPrice;
         new TimestampIdBinding(product, bindingInfo);
     }
 }
Ejemplo n.º 9
0
        public void Bind(
            INotifyPropertyChanged source, string sourcePropertyName,
            INotifyPropertyChanged target, string targetPropertyName)
        {
            var bindingInfo = new BindingInfo
                                  {
                                      Source = source,
                                      SourcePropertyName = sourcePropertyName,
                                      Target = target,
                                      TargetPropertyName = targetPropertyName
                                  };

            _binding.Add(bindingInfo);

            source.PropertyChanged += PropertyChangedEventHandler;
            target.PropertyChanged += PropertyChangedEventHandler;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates a group with the fields for send port parsing.
        /// </summary>
        /// <returns>A populated <see cref="ParsedBizTalkApplicationGroup"/>.</returns>
        private static ParsedBizTalkApplicationGroup CreateGroup()
        {
            var group             = new ParsedBizTalkApplicationGroup();
            var application       = new ParsedBizTalkApplication();
            var bindingInfo       = new BindingInfo();
            var distributionLists = new List <DistributionList>
            {
                new DistributionList()
                {
                    Name = "Send Port Group 1", Filter = ""
                }
            };

            bindingInfo.DistributionListCollection = distributionLists.ToArray();
            application.Application.Bindings       = new BindingFile("TestContainer", "BindingInfo")
            {
                BindingInfo = bindingInfo
            };
            group.Applications.Add(application);
            return(group);
        }
Ejemplo n.º 11
0
        public static bool HasExistingBinding(List <BindingInfo> bindings, BindingInfo spec)
        {
            foreach (var b in bindings)
            {
                // same protocol
                if (b.Protocol == spec.Protocol && b.Port == spec.Port)
                {
                    // same or blank host
                    if (b.Host == spec.Host || (string.IsNullOrEmpty(b.Host) && string.IsNullOrEmpty(spec.Host)))
                    {
                        // same or unassigned IP
                        if (spec.IP == b.IP || (unassignedIPs.Contains(spec.IP) && unassignedIPs.Contains(b.IP)))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 12
0
        private void ConfigureParameters(ControllerModel controller)
        {
            foreach (var action in controller.Actions)
            {
                foreach (var para in action.Parameters)
                {
                    if (para.BindingInfo != null)
                    {
                        continue;
                    }

                    if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(para.ParameterInfo.ParameterType))
                    {
                        if (CanUseFormBodyBinding(action, para))
                        {
                            para.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() });
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public override IModelBinder CreateBinder(ModelMetadata metadata, BindingInfo bindingInfo)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException(nameof(metadata));
            }

            if (bindingInfo == null)
            {
                throw new ArgumentNullException(nameof(bindingInfo));
            }

            // For non-root nodes we use the ModelMetadata as the cache token. This ensures that all non-root
            // nodes with the same metadata will have the same binder. This is OK because for an non-root
            // node there's no opportunity to customize binding info like there is for a parameter.
            var token = metadata;

            var nestedContext = new DefaultModelBinderProviderContext(this, metadata, bindingInfo);

            return(_factory.CreateBinderCoreCached(nestedContext, token));
        }
Ejemplo n.º 14
0
        private int FindAncestorLevel(BindingInfo binding)
        {
            int level  = 1;
            var parent = (TypeNode)Parent;

            while (parent != null)
            {
                if (binding != null)
                {
                    if (binding.AncestorLevel == level || parent.Type == binding.AncestorType)
                    {
                        return(level);
                    }
                }

                parent = (TypeNode)parent.Parent;
                level++;
            }

            return(level);
        }
Ejemplo n.º 15
0
        private void CreateSampleStep(StepDefinition stepDefinition)
        {
            BindingInfo bindingInfo = bindingByStepDef[stepDefinition];
            Debug.Assert(bindingInfo != null);
            switch (stepDefinition.Type)
            {
                case "Given":
                    stepDefinition.ScenarioStep = new Given();
                    break;
                case "When":
                    stepDefinition.ScenarioStep = new When();
                    break;
                case "Then":
                    stepDefinition.ScenarioStep = new Then();
                    break;
                default:
                    throw new InvalidOperationException();
            }

            stepDefinition.ScenarioStep.Text = GetSampleText(bindingInfo);
        }
Ejemplo n.º 16
0
        public async Task BindModelAsync_WithBindProperty_EnforcesBindRequired(int?input, bool isValid)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = nameof(TestController.BindRequiredProp),
                ParameterType = typeof(string),
                BindingInfo   = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Method = "POST";

                if (input.HasValue)
                {
                    request.QueryString = new QueryString($"?{parameter.Name}={input.Value}");
                }
            });

            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var modelMetadata         = modelMetadataProvider
                                        .GetMetadataForProperty(typeof(TestController), parameter.Name);

            // Act
            var result = await parameterBinder.BindModelAsync(
                parameter,
                testContext,
                modelMetadataProvider,
                modelMetadata);

            // Assert
            Assert.Equal(input.HasValue, result.IsModelSet);
            Assert.Equal(isValid, testContext.ModelState.IsValid);
            if (isValid)
            {
                Assert.Equal(input.Value, Assert.IsType <int>(result.Model));
            }
        }
        private ControllerActionDescriptor CreateActionDescriptor(
            string httpMethod, string routeTemplate, string actionFixtureName)
        {
            var descriptor = new ControllerActionDescriptor();

            descriptor.SetProperty(new ApiDescriptionActionData());
            descriptor.DisplayName = actionFixtureName;

            descriptor.ActionConstraints = new List <IActionConstraintMetadata>
            {
                new HttpMethodConstraint(new[] { httpMethod })
            };
            descriptor.AttributeRouteInfo = new AttributeRouteInfo {
                Template = routeTemplate
            };

            descriptor.MethodInfo = typeof(ActionFixtures).GetMethod(actionFixtureName);
            if (descriptor.MethodInfo == null)
            {
                throw new InvalidOperationException(
                          string.Format("{0} is not declared in ActionFixtures", actionFixtureName));
            }

            descriptor.Parameters = descriptor.MethodInfo.GetParameters()
                                    .Select(paramInfo => new ParameterDescriptor
            {
                Name          = paramInfo.Name,
                ParameterType = paramInfo.ParameterType,
                BindingInfo   = BindingInfo.GetBindingInfo(paramInfo.GetCustomAttributes(false))
            })
                                    .ToList();

            // Set some additional properties - typically done via IApplicationModelConvention
            var attributes = descriptor.MethodInfo.GetCustomAttributes(true);

            descriptor.Properties.Add("ActionAttributes", attributes);
            descriptor.Properties.Add("IsObsolete", attributes.OfType <ObsoleteAttribute>().Any());

            return(descriptor);
        }
Ejemplo n.º 18
0
        private void ApplyDockingLayout(string text)
        {
            // Save the binding expressions of all the current anchorables
            var bindings = new Dictionary <string, List <BindingInfo> >();

            foreach (var anchorable in AvalonDockHelper.GetAllAnchorables(DockingManager).Where(x => !string.IsNullOrEmpty(x.ContentId)))
            {
                var titleBindingInfo     = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, LayoutContent.TitleProperty));
                var isVisibleBindingInfo = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, AvalonDockHelper.IsVisibleProperty));
                bindings.Add(anchorable.ContentId, new List <BindingInfo> {
                    titleBindingInfo, isVisibleBindingInfo
                });
            }
            // Unregister docking manager
            AvalonDockHelper.UnregisterDockingManager(DockingManager);
            // Deserialize the string
            using (var stream = new MemoryStream())
            {
                var writer = new StreamWriter(stream);
                writer.Write(text);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                var serializer = new XmlLayoutSerializer(DockingManager);
                serializer.Deserialize(stream);
            }
            // Apply saved the binding expressions to the newly deserialized anchorables
            foreach (var anchorable in AvalonDockHelper.GetAllAnchorables(DockingManager).Where(x => !string.IsNullOrEmpty(x.ContentId)))
            {
                List <BindingInfo> bindingInfos;
                if (bindings.TryGetValue(anchorable.ContentId, out bindingInfos))
                {
                    foreach (var bindingInfo in bindingInfos)
                    {
                        BindingOperations.SetBinding(anchorable, bindingInfo.Property, bindingInfo.Binding);
                    }
                }
            }
            // Re-register docking manager with new layout
            AvalonDockHelper.RegisterDockingManager(session.ServiceProvider, DockingManager);
        }
        public async Task FromBodyOnParameterType_WithData_Succeeds(BindingInfo bindingInfo)
        {
            // Arrange
            var inputText        = "{ \"Street\" : \"someStreet\" }";
            var metadataProvider = new TestModelMetadataProvider();

            metadataProvider
            .ForType <Address6>()
            .BindingDetails(binding => binding.BindingSource = BindingSource.Body);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(metadataProvider);
            var parameter       = new ParameterDescriptor
            {
                Name          = "parameter-name",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Address6),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(inputText));
                request.ContentType = "application/json";
            });

            testContext.MetadataProvider = metadataProvider;
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var address = Assert.IsType <Address6>(modelBindingResult.Model);

            Assert.Equal("someStreet", address.Street, StringComparer.Ordinal);

            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
        public async Task BinderTypeOnParameterType_WithDataEmptyPrefixAndVersion20_GetsBound(
            BindingInfo bindingInfo)
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext(
                // ParameterBinder will use ModelMetadata for typeof(Address), not Parameter1's ParameterInfo.
                updateOptions: options => options.AllowValidatingTopLevelNodes = false);

            var modelState      = testContext.ModelState;
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext.HttpContext.RequestServices);
            var parameter       = new ParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Address),
            };

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var address = Assert.IsType <Address>(modelBindingResult.Model);

            Assert.Equal("SomeStreet", address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var kvp = Assert.Single(modelState);

            Assert.Equal("Street", kvp.Key);
            var entry = kvp.Value;

            Assert.NotNull(entry);
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it.
        }
        protected virtual BindingInfo CreateBindingInfo <TNamingConvention>(IApplicationBinding <TNamingConvention> applicationBinding)
            where TNamingConvention : class
        {
            ((ISupportValidation)applicationBinding).Validate();

            var bi = new BindingInfo();

            bi.BindingParameters = new BindingParameters(new Version(bi.Version))
            {
                BindingActions  = BindingParameters.BindingActionTypes.Bind,
                BindingItems    = BindingParameters.BindingItemTypes.All,
                BindingScope    = BindingParameters.BindingScopeType.Application,
                BindingSetState = BindingParameters.BindingSetStateType.UseServiceState
            };
            bi.Description         = applicationBinding.Description;
            bi.ModuleRefCollection = new ModuleRefCollection {
                new ModuleRef(string.Format("[Application:{0}]", ApplicationName), string.Empty, string.Empty, string.Empty)
                // TODO ref schemas, transforms, and other artifacts
            };
            bi.Timestamp = applicationBinding.Timestamp;
            return(bi);
        }
Ejemplo n.º 22
0
        private static bool TrySourceAdditionalParameter(
            BindingInfo bindingInfo,
            IWebHookBindingMetadata bindingMetadata,
            string parameterName)
        {
            var parameter = bindingMetadata?.Parameters
                            .FirstOrDefault(item => string.Equals(parameterName, item.Name, StringComparison.OrdinalIgnoreCase));

            if (parameter == null)
            {
                return(false);
            }

            bindingInfo.BinderModelName = parameter.SourceName;
            switch (parameter.ParameterType)
            {
            case WebHookParameterType.Header:
                bindingInfo.BindingSource = BindingSource.Header;
                break;

            case WebHookParameterType.RouteValue:
                bindingInfo.BindingSource = BindingSource.Path;
                break;

            case WebHookParameterType.QueryParameter:
                bindingInfo.BindingSource = BindingSource.Query;
                break;

            default:
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.General_InvalidEnumValue,
                    nameof(WebHookParameterType),
                    parameter.ParameterType);
                throw new InvalidOperationException(message);
            }

            return(true);
        }
        public async Task BinderTypeOnParameterType_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameters      = typeof(TestController).GetMethod(nameof(TestController.Action)).GetParameters();
            var parameter       = new ControllerParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterInfo = parameters[0],
                ParameterType = typeof(Address),
            };

            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var address = Assert.IsType <Address>(modelBindingResult.Model);

            Assert.Equal("SomeStreet", address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var kvp = Assert.Single(modelState);

            Assert.Equal("Street", kvp.Key);
            var entry = kvp.Value;

            Assert.NotNull(entry);
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it.
        }
Ejemplo n.º 24
0
 protected override BindingInfo <IThreadManager> GetThreadManager()
 {
     if (Context.Platform.Platform != PlatformType.WinForms)
     {
         return(BindingInfo <IThreadManager> .Empty);
     }
     if (UseSimpleThreadManager)
     {
         return(BindingInfo <IThreadManager> .FromType <SynchronousThreadManager>(DependencyLifecycle.SingleInstance));
     }
     return(BindingInfo <IThreadManager> .FromMethod((container, list) =>
     {
         var context = SynchronizationContext.Current as WindowsFormsSynchronizationContext;
         if (context == null)
         {
             context = new WindowsFormsSynchronizationContext();
             SynchronizationContext.SetSynchronizationContext(context);
             WindowsFormsSynchronizationContext.AutoInstall = false;
         }
         return new ThreadManager(context);
     }, DependencyLifecycle.SingleInstance));
 }
Ejemplo n.º 25
0
        public async Task <IActionResult> Post(BindingInfo info)
        {
            var table = _utilities.GetCloudTable("Bindings");

            var operation = TableOperation.InsertOrReplace(new TableEntity
            {
                PartitionKey = info.SourceId,
                RowKey       = info.TargetId
            });

            await table.ExecuteAsync(operation);

            operation = TableOperation.InsertOrReplace(new TableEntity
            {
                PartitionKey = info.TargetId,
                RowKey       = info.SourceId
            });

            await table.ExecuteAsync(operation);

            return(new NoContentResult());
        }
Ejemplo n.º 26
0
        public void Test_Apply_AddsParameterMetadataSetsBinding()
        {
            var metadata        = new MethodMetadata(new JsonRpcMethodOptions(), new JsonName("", ""), new JsonName("", ""));
            var controllerModel = new Mock <ControllerModel>(typeof(JsonRpcTestController).GetTypeInfo(), new List <object>()).Object;
            var actionModel     = new Mock <ActionModel>(typeof(JsonRpcTestController).GetMethod(nameof(MvcTestController.VoidAction)), new List <object>()).Object;

            actionModel.Properties[typeof(MethodMetadata)] = metadata;
            var model = new Mock <ParameterModel>(typeof(JsonRpcTestController).GetMethod(nameof(MvcTestController.VoidAction)).GetParameters()[0], new List <object>()).Object;

            actionModel.Controller = controllerModel;
            model.Action           = actionModel;
            var binding = new BindingInfo();

            model.BindingInfo   = binding;
            model.ParameterName = "test";
            var parameterConvention = testEnvironment.ServiceProvider.GetRequiredService <ParameterConvention>();

            parameterConvention.Apply(model);

            metadata.ParametersInternal.Should().HaveCount(1);
            model.BindingInfo.Should().NotBeNull();
        }
Ejemplo n.º 27
0
        public async Task BinderTypeOnProperty_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Person3),
            };

            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var person = Assert.IsType <Person3>(modelBindingResult.Model);

            Assert.NotNull(person.Address);
            Assert.Equal("SomeStreet", person.Address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var kvp = Assert.Single(modelState);

            Assert.Equal("Address.Street", kvp.Key);
            var entry = kvp.Value;

            Assert.NotNull(entry);
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it.
        }
        /// <summary>
        /// Creates a <see cref="PagePropertyModel"/> for the <paramref name="property"/>.
        /// </summary>
        /// <param name="property">The <see cref="PropertyInfo"/>.</param>
        /// <returns>The <see cref="PagePropertyModel"/>.</returns>
        protected virtual PagePropertyModel CreatePropertyModel(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            var propertyAttributes = property.GetCustomAttributes(inherit: true);

            // BindingInfo for properties can be either specified by decorating the property with binding-specific attributes.
            // ModelMetadata also adds information from the property's type and any configured IBindingMetadataProvider.
            var propertyMetadata = _modelMetadataProvider.GetMetadataForProperty(property.DeclaringType, property.Name);
            var bindingInfo      = BindingInfo.GetBindingInfo(propertyAttributes, propertyMetadata);

            if (bindingInfo == null)
            {
                // Look for BindPropertiesAttribute on the handler type if no BindingInfo was inferred for the property.
                // This allows a user to enable model binding on properties by decorating the controller type with BindPropertiesAttribute.
                var declaringType           = property.DeclaringType;
                var bindPropertiesAttribute = declaringType.GetCustomAttribute <BindPropertiesAttribute>(inherit: true);
                if (bindPropertiesAttribute != null)
                {
                    var requestPredicate = bindPropertiesAttribute.SupportsGet ? _supportsAllRequests : _supportsNonGetRequests;
                    bindingInfo = new BindingInfo
                    {
                        RequestPredicate = requestPredicate,
                    };
                }
            }

            var model = new PagePropertyModel(property, propertyAttributes)
            {
                PropertyName = property.Name,
                BindingInfo  = bindingInfo,
            };

            return(model);
        }
        internal void SendFunctionLoadRequest(FunctionRegistrationContext context)
        {
            FunctionMetadata metadata = context.Metadata;

            // associate the invocation input buffer with the function
            _functionInputBuffers[context.Metadata.FunctionId] = context.InputBuffer;

            // send a load request for the registered function
            FunctionLoadRequest request = new FunctionLoadRequest()
            {
                FunctionId = metadata.FunctionId,
                Metadata   = new RpcFunctionMetadata()
                {
                    Name       = metadata.Name,
                    Directory  = metadata.FunctionDirectory ?? string.Empty,
                    EntryPoint = metadata.EntryPoint ?? string.Empty,
                    ScriptFile = metadata.ScriptFile ?? string.Empty
                }
            };

            if (_managedDependencyOptions?.Value != null)
            {
                _workerChannelLogger?.LogInformation($"Adding dependency download request to {_workerConfig.Language} language worker");
                request.ManagedDependencyEnabled = _managedDependencyOptions.Value.Enabled;
            }

            foreach (var binding in metadata.Bindings)
            {
                BindingInfo bindingInfo = binding.ToBindingInfo();

                request.Metadata.Bindings.Add(binding.Name, bindingInfo);
            }

            SendStreamingMessage(new StreamingMessage
            {
                FunctionLoadRequest = request
            });
        }
Ejemplo n.º 30
0
        public void LongPropertyPathForSource()
        {
            var simpleClass1 = new SimpleClass1
            {
                Child = new SimpleClass1()
            };
            var simpleClass2 = new SimpleClass1();

            var bindingInfo = new BindingInfo
            {
                BindingMode = BindingMode.OneWay,
                SourcePath  = nameof(simpleClass1.Child) + "." + LastName,
                Source      = simpleClass1,
                Target      = simpleClass2,
                TargetPath  = LastName
            };

            bindingInfo.Connect();

            simpleClass1.Child.LastName = "Alex0";

            MustEqual("Alex0", simpleClass2.LastName);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Parses the service bindings.
        /// </summary>
        /// <param name="bindingInfo">The binding info containing the service bindings to parse.</param>
        /// <param name="bindingResourceDefintion">The binding resource definition to add the new resources to.</param>
        private void ParseServiceBindings(BindingInfo bindingInfo, ResourceDefinition bindingResourceDefintion)
        {
            foreach (var serviceBinding in bindingInfo.ModuleRefCollection.SelectMany(m => m.Services))
            {
                // Create the resource under the binding definition.
                var serviceBindingResource = new ResourceItem
                {
                    Key         = string.Concat(bindingResourceDefintion.Key, ":", serviceBinding.Name),
                    Name        = serviceBinding.Name,
                    Description = serviceBinding.Description,
                    Type        = ModelConstants.ResourceServiceBinding,
                    ParentRefId = bindingResourceDefintion.RefId,
                    Rating      = ConversionRating.NotSupported
                };
                serviceBinding.ResourceKey          = serviceBindingResource.Key;
                serviceBinding.Resource             = serviceBindingResource; // Maintain pointer to the resource.
                serviceBindingResource.SourceObject = serviceBinding;         // Maintain backward pointer.

                bindingResourceDefintion.Resources.Add(serviceBindingResource);

                _logger.LogTrace(TraceMessages.ResourceCreated, nameof(BindingFileParser), serviceBindingResource.Key, serviceBindingResource.Name, serviceBindingResource.Type, bindingResourceDefintion.Key);
            }
        }
        protected override BindingInfo <IViewModelPresenter> GetViewModelPresenter()
        {
#if WPF
            if (Context.Platform.Platform != PlatformType.WPF)
            {
                MvvmApplication.Initialized += MvvmApplicationOnInitialized;
                return(BindingInfo <IViewModelPresenter> .Empty);
            }
#endif
            return(BindingInfo <IViewModelPresenter> .FromMethod((container, list) =>
            {
                var presenter = new ViewModelPresenter();
                presenter.DynamicPresenters.Add(new DynamicViewModelNavigationPresenter());
#if !WINDOWS_PHONE
                presenter.DynamicPresenters.Add(
                    new DynamicViewModelWindowPresenter(container.Get <IViewMappingProvider>(), container.Get <IViewManager>(),
                                                        container.Get <IWrapperManager>(), container.Get <IThreadManager>(),
                                                        container.Get <IOperationCallbackManager>()));
#endif

                return presenter;
            }, DependencyLifecycle.SingleInstance));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// The function is responsible for binding a source objects property to a target objects property. Both properties have to have the usual qooxdoo getter and setter. The source property also needs to fire change-events on every change of its value. Please keep in mind, that this binding is unidirectional. If you need a binding in both directions, you have to use two of this bindings.
        /// It’s also possible to bind some kind of a hierarchy as a source. This means that you can separate the source properties with a dot and bind by that the object referenced to this property chain. Example with an object ‘a’ which has object ‘b’ stored in its ‘child’ property. Object b has a string property named abc:
        ///
        /// qx.data.SingleValueBinding.bind(a, "child.abc", textfield, "value");
        ///
        /// In that case, if the property abc of b changes, the textfield will automatically contain the new value. Also if the child of a changes, the new value (abc of the new child) will be in the textfield.
        /// There is also a possibility of binding an array. Therefore the array  qx.data.IListData is needed because this array has change events which the native does not. Imagine a qooxdoo object a which has a children property containing an array holding more of its own kind. Every object has a name property as a string.
        ///
        /// var svb = qx.data.SingleValueBinding;
        /// // bind the first child's name of 'a' to a textfield
        /// svb.bind(a, "children[0].name", textfield, "value");
        /// // bind the last child's name of 'a' to a textfield
        /// svb.bind(a, "children[last].name", textfield2, "value");
        /// // also deeper bindings are possible
        /// svb.bind(a, "children[0].children[0].name", textfield3, "value");
        ///
        /// As you can see in this example, the abc property of a’s b will be bound to the textfield. If now the value of b changed or even the a will get a new b, the binding still shows the right value.
        /// </summary>
        /// <param name="sourcePropertyChain">The property chain which represents the source property.</param>
        /// <param name="targetObject">The object which the source should be bind to.</param>
        /// <param name="targetProperty">The property chain to the target object.</param>
        /// <param name="options">A map containing the options.
        /// •  converter: A converter function which takes four parameters and should return the converted value.
        /// 1.	The data to convert
        /// 2.	The corresponding model object, which is only set in case of the use of an controller.
        /// 3.	The source object for the binding
        /// 4.	The target object.
        /// If no conversion has been done, the given value should be returned. e.g. a number to boolean converter function(data, model, source, target) {return data > 100;}
        /// •  onUpdate: A callback function can be given here. This method will be called if the binding was updated successful. There will be three parameter you do get in that method call.
        /// 1.	The source object
        /// 2.	The target object
        /// 3.	The data
        /// Here is a sample: onUpdate : function(source, target, data) {...}
        /// •  onSetFail: A callback function can be given here. This method will be called if the set of the value fails.
        /// •  ignoreConverter: A string which will be matched using the current property chain. If it matches, the converter will not be called.
        /// </param>
        /// <returns></returns>
        public object Bind(string sourcePropertyChain, qxDotNet.Core.Object targetObject, string targetProperty, Map options = null)
        {
            var b = new BindingInfo();

            b.sourceProperty = sourcePropertyChain;
            b.target         = targetObject;
            b.targetProperty = targetProperty;
            b.options        = options;
            var key = b.getKey();

            _bindings[key] = b;
            var c = new ClientMethodCall("bind")
                    .SetKeyParameter(b.sourceProperty)
                    .SetKeyParameter(b.target)
                    .SetKeyParameter(b.targetProperty);

            if (b.options != null)
            {
                c.SetParameter(b.options);
            }
            CallClientMethod(c);
            return(b);
        }
Ejemplo n.º 34
0
        public DefaultModelBinderProviderContext(
            ModelBinderFactory factory,
            ModelBinderFactoryContext factoryContext)
        {
            _factory = factory;
            Metadata = factoryContext.Metadata;
            BindingInfo bindingInfo;

            if (factoryContext.BindingInfo != null)
            {
                bindingInfo = new BindingInfo(factoryContext.BindingInfo);
            }
            else
            {
                bindingInfo = new BindingInfo();
            }

            bindingInfo.TryApplyBindingInfo(Metadata);
            BindingInfo = bindingInfo;

            MetadataProvider = _factory._metadataProvider;
            Visited          = new Dictionary <Key, IModelBinder?>();
        }
Ejemplo n.º 35
0
        public async Task BindModelAsync_WithBindProperty_DoesNotBindModel_WhenRequestIsGet()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Person),
                BindingInfo   = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Method      = "GET";
                request.QueryString = new QueryString("?parameter.Name=Joey");
            });

            // Act
            var result = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.False(result.IsModelSet);
        }
Ejemplo n.º 36
0
        protected IMyInput CreateInput(BindingInfo info)
        {
            if (info.Input != null)
            {
                if (info.Input == "none")
                {
                    return(null);
                }
                switch (info.Input[0])
                {
                case 'd': return(new MyDateBox());

                case 't': return(new MyTimeBox());

                case 'm': return(new MyMultyLineBox());

                case 'p': return(new MyPasswordBox());

                case 'c': return(new MyComboBox());
                }
            }
            return(new MyTextBox());
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Creates a <see cref="PagePropertyModel"/> for the <paramref name="property"/>.
        /// </summary>
        /// <param name="property">The <see cref="PropertyInfo"/>.</param>
        /// <returns>The <see cref="PagePropertyModel"/>.</returns>
        protected virtual PagePropertyModel CreatePropertyModel(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            var propertyAttributes = property.GetCustomAttributes(inherit: true);
            var handlerAttributes  = property.DeclaringType.GetCustomAttributes(inherit: true);

            // Look for binding info on the handler if nothing is specified on the property.
            // This allows BindProperty attributes on handlers to apply to properties.
            var bindingInfo = BindingInfo.GetBindingInfo(propertyAttributes) ??
                              BindingInfo.GetBindingInfo(handlerAttributes);

            var model = new PagePropertyModel(property, propertyAttributes)
            {
                PropertyName = property.Name,
                BindingInfo  = bindingInfo,
            };

            return(model);
        }
Ejemplo n.º 38
0
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var         contentType = bindingContext.ActionContext.HttpContext.Request.ContentType;
        BindingInfo bindingInfo = new BindingInfo();

        if (contentType == "application/json")
        {
        }
        else if (contentType == "application/x-www-form-urlencoded")
        {
            bindingInfo.BindingSource = BindingSource.Form;
        }
        else
        {
            bindingContext.Result = ModelBindingResult.Failed();
        }
        var binder = factory.CreateBinder(new ModelBinderFactoryContext
        {
            Metadata    = bindingContext.ModelMetadata,
            BindingInfo = bindingInfo,
        });
        await binder.BindModelAsync(bindingContext);
    }
Ejemplo n.º 39
0
        static void DownloadAsync(string url, string filePath, string name, Action <string, string, object, byte[]> callBack, object context = null)
        {
            for (int i = 0; i < lbi.Count; i++)
            {
                if (lbi[i].filePath == filePath)
                {
                    return;
                }
            }
            var uwr = UnityWebRequest.Get(url);
            var ao  = uwr.SendWebRequest();

            ao.completed += DownloadComplete;
            BindingInfo info = new BindingInfo();

            info.url        = url;
            info.filePath   = filePath;
            info.webRequest = uwr;
            info.name       = name;
            info.context    = context;
            info.CallBack   = callBack;
            lbi.Add(info);
        }
Ejemplo n.º 40
0
        public DomainModel.Order AddOrder(int personId, DTO.Order dto, 
            BindingInfo orderBinding, BindingInfo[] orderDetailBindings)
        {
            DomainModel.Person person = PersonService.LoadPerson(personId);
            DomainModel.Order order = ((Order.OrderFactory)Registry.Instance.getFactory(typeof(Order)))
                .createOrder(person, dto.OrderDate, DateTime.MaxValue, "");
            person.addOrder(order);
            //            DomainModel.Order order = person.AddOrder(dto.OrderDate);
            new TimestampIdBinding(order, orderBinding);

            for(int i = 0; i < dto.OrderDetails.Length; i++)
            {
                DTO.OrderDetail dtoDetail = dto.OrderDetails[i];
                DomainModel.Product product =
                    ProductService.LoadProduct(dtoDetail.ProductId);
                if(product != null)
                {
                    DomainModel.OrderDetail orderDetail =
                        order.AddOrderDetail(product, product.UnitPrice, dtoDetail.Quantity);
                    new TimestampIdBinding(orderDetail, orderDetailBindings[i]);
                }
            }
            return order;
        }
        private string GetSampleText(BindingInfo bindingInfo, string text, Match match)
        {
            StringBuilder sampleText = new StringBuilder(text);
            for (int groupIndex = match.Groups.Count - 1; groupIndex >= 1; groupIndex--)
            {
                int paramIndex = groupIndex - 1;
                var paramText = paramIndex >= bindingInfo.ParameterNames.Length ? "{?param?}" :
                                                                                                  "{" + bindingInfo.ParameterNames[paramIndex] + "}";

                var gr = match.Groups[groupIndex];
                sampleText.Remove(gr.Index, gr.Length);
                sampleText.Insert(gr.Index, paramText);
            }
            return sampleText.ToString();
        }
Ejemplo n.º 42
0
 public override void CreateWebSite(string name, string path, string appPool, bool https, BindingInfo binding)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 43
0
        private int FindAncestorLevel(BindingInfo binding)
        {
            var level = 1;
            var parent = (TypeNode) Parent;
            while (parent != null)
            {
                if (binding != null)
                {
                    if (binding.AncestorLevel == level || parent.Type == binding.AncestorType)
                    {
                        return level;
                    }
                }

                parent = (TypeNode) parent.Parent;
                level++;
            }

            return level;
        }
Ejemplo n.º 44
0
 public void UpdateOrderData(int orderId, DateTime orderDate, 
     DateTime shippedDate, byte[] timestamp, BindingInfo bindingInfo)
 {
     DomainModel.Order order = LoadOrder(orderId);
     if(order != null)
     {
         if(order.Timestamp.Equals(new Timestamp(timestamp)) == false)
             throw new ApplicationException("ConcurrencyException");
         order.OrderDate = orderDate;
         order.ShippedDate = shippedDate;
         if(bindingInfo != null)
             new TimestampIdBinding(order, bindingInfo);
     }
 }
Ejemplo n.º 45
0
 public void UpdateOrderDetail(int orderId, DTO.OrderDetail dto,
     BindingInfo bindingInfo)
 {
     DomainModel.Order order = LoadOrder(orderId);
     if(order != null)
     {
         DomainModel.OrderDetail detail = order[dto.ProductId];
         if(detail != null)
         {
             if(detail.Timestamp.Equals(new Timestamp(dto.Timestamp)) == false)
                 throw new ApplicationException("ConcurrencyException");
             detail.Quantity = dto.Quantity;
             detail.UnitPrice = dto.UnitPrice;
             new TimestampIdBinding(detail, bindingInfo);
         }
     }
 }
Ejemplo n.º 46
0
 public void UpdatePersonData(int personId, string name, string password, 
     byte[] timestamp, BindingInfo bindingInfo)
 {
     DomainModel.Person person = LoadPerson(personId);
     if(person == null)
         return;
     if(person.Timestamp.Equals(new Timestamp(timestamp)) == false)
     {
         throw new ApplicationException("ConcurrencyException");
     }
     person.Name = name;
     person.Password = password;
     new TimestampIdBinding(person, bindingInfo);
 }
Ejemplo n.º 47
0
        private void ExportBindings()
        {
            // not supported, only export bindings at application level
            //  -GroupLevel        Optional. If specified, all bindings in the current group are exported.
            //  -GlobalParties     Optional. If specified, the global party information for the group is exported.
            //  -AssemblyName      Optional. The full name of the BizTalk assembly.
            if (this.BindingFile == null)
            {
                // -Destination       Required. Path and file name of the XML binding file to write.
                this.Log.LogError("BindingFile is required");
                return;
            }

            // use default app if no app name is provided
            if (string.IsNullOrEmpty(this.Application))
            {
                // -ApplicationName   Optional. The name of the BizTalk application.
                this.Application = this.explorer.DefaultApplication.Name;
                this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Using default application {0}", this.Application));
            }

            // create dir if it doesn't exist
            string dir = Path.GetDirectoryName(Path.GetFullPath(this.BindingFile.ItemSpec));

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
                this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Created directory {0}", dir));
            }

            using (SqlConnection sqlConnection = new SqlConnection(this.explorer.ConnectionString))
            {
                using (BindingInfo info = new BindingInfo())
                {
                    BindingParameters bindingParameters = new BindingParameters(new Version(info.Version)) { BindingItems = BindingParameters.BindingItemTypes.All, BindingScope = BindingParameters.BindingScopeType.Application };
                    info.AddApplicationRef(sqlConnection, this.Application);
                    info.Select(sqlConnection, bindingParameters);
                    info.SaveXml(this.BindingFile.ItemSpec);

                    this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Exported {0} bindings to {1}", this.Application, this.BindingFile.ItemSpec));
                }
            }
        }
Ejemplo n.º 48
0
 public override void CreateWebSite(string name, string path, string appPool, bool https, BindingInfo binding)
 {
     using (var manager = new ServerManager())
     {
         var site = manager.Sites.Add(name, https ? "https" : "http", binding.ToString(), path);
         site.ApplicationDefaults.ApplicationPoolName = appPool;
         manager.CommitChanges();
     }
 }
 private string GetSampleText(BindingInfo bindingInfo)
 {
     var sampleText = bindingInfo.Regex.ToString().Trim('$', '^');
     Regex re = new Regex(@"\([^\)]+\)");
     int paramIndex = 0;
     sampleText = re.Replace(sampleText, delegate
                                             {
                                                 return paramIndex >= bindingInfo.ParameterNames.Length ? "{?param?}" :
                                                                                                                          "{" + bindingInfo.ParameterNames[paramIndex++] + "}";
                                             });
     return sampleText;
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Sets a new binding
        /// </summary>
        /// <param name="buffer">VertexBufferObject for the binding</param>
        /// <param name="vertexOffset">Vertex offset in the buffer</param>
        /// <param name="frequency">Number of instance to draw</param>
        /// <param name="index">Index where to insert the binding</param>
        public void SetBinding(VertexBufferObject buffer, int vertexOffset, int frequency, int index)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            BindingInfo inf = new BindingInfo
            {
                BufferObject = buffer,
                VertexOffset = vertexOffset,
                Frequency = frequency
            };

            if(index >= _bindings.Count)
                _bindings.Add(inf);
            else
                _bindings.Insert(index, inf);

            buffer.VertexBufferAllocated += BufferAllocated;
            ResizeBindingArray();
        }
Ejemplo n.º 51
0
 public CallToConstraint(BindingInfo call, string functionName)
     : base(call)
 {
     _functionName = functionName;
     CorrectCall = call;
 }
Ejemplo n.º 52
0
 public void UpdateAddress(int personId, DTO.Address dto, BindingInfo bindingInfo)
 {
     DomainModel.Person person = LoadPerson(personId);
     if(person == null)
         return;
     DomainModel.Address address = person.findAddress(dto.Id);
     if(address == null)
         return;
     if(address.Timestamp.Equals(new Timestamp(dto.Timestamp)) == false)
         throw new ApplicationException("ConcurrencyException");
     address.Street = dto.Street;
     address.Phone = dto.Phone;
     address.PostalCode = dto.Postalcode;
     address.Email = dto.Email;
     address.City = dto.City;
     new TimestampIdBinding(address, bindingInfo);
 }
Ejemplo n.º 53
0
		public static bool Bind (WebBrowser control, IntPtr handle, int width, int height)
		{
			if (!isInitialized ())
				return false;

			BindingInfo info = new BindingInfo ();
			info.callback = new CallbackBinder (control.callbacks);
			IntPtr ptrCallback = Marshal.AllocHGlobal (Marshal.SizeOf (info.callback));
			Marshal.StructureToPtr (info.callback, ptrCallback, true);
			
			info.gluezilla = gluezilla_bind (ptrCallback, handle, width, height, Environment.CurrentDirectory, monoMozDir, control.platform);
			lock (initLock) {
				if (info.gluezilla == IntPtr.Zero) {
					Marshal.FreeHGlobal (ptrCallback);
					info = null;
					initialized = false;
					return false;
				}
			}
			boundControls.Add (control as IWebBrowser, info);
			return true;
		}
Ejemplo n.º 54
0
 /// <summary>
 /// Creates a new website.
 /// </summary>
 /// <param name="name">The name of the website.</param>
 /// <param name="path">The physical path of the website.</param>
 /// <param name="appPool">The name of the application pool.</param>
 /// <param name="https">Binds to HTTPS instead of HTTP</param>
 /// <param name="binding">The port, hostname, and IP of the website.</param>
 public abstract void CreateWebSite(string name, string path, string appPool, bool https, BindingInfo binding);
Ejemplo n.º 55
0
        public int GetBindingLevel(BindingInfo binding)
        {
            var level = 0;

            switch (binding.RelativeSourceMode)
            {
                case RelativeSourceMode.Self:
                    level = 1;
                    break;
                case RelativeSourceMode.FindAncestor:
                    level = FindAncestorLevel(binding);
                    break;
                case RelativeSourceMode.PreviousData:
                    throw new NotImplementedException();
                case RelativeSourceMode.SerializationContext:
                    level = FindAncestorLevel(null);
                    break;
            }

            return level;
        }