Exemplo n.º 1
0
    static Storyboard()
    {
        PropertyMetadata targetPropertyMetadata = new PropertyMetadata();
        targetPropertyMetadata.FreezeValueCallback = TargetFreezeValueCallback;

        TargetProperty = DependencyProperty.RegisterAttached("Target", typeof(DependencyObject), typeof(Storyboard), targetPropertyMetadata);
    }
        /// <summary>
        /// Registers a new attached property.
        /// </summary>
        /// <param name="name">The attached property's name.</param>
        /// <param name="uvssName">The attached property's name within the UVSS styling system.</param>
        /// <param name="propertyType">The attached property's value type.</param>
        /// <param name="ownerType">The attached property's owner type.</param>
        /// <param name="metadata">The attached property's metadata.</param>
        /// <returns>A <see cref="DependencyProperty"/> instance which represents the registered attached property.</returns>
        public static DependencyProperty RegisterAttached(String name, String uvssName, Type propertyType, Type ownerType, PropertyMetadata metadata = null)
        {
            Contract.Require(name, "name");
            Contract.Require(propertyType, "propertyType");
            Contract.Require(ownerType, "ownerType");

            var dp = new DependencyProperty(dpid++, name, uvssName, propertyType, ownerType, metadata, isAttached: true);
            RegisterInternal(dp, ownerType);
            return dp;
        }
Exemplo n.º 3
0
            public void ShouldReturnFalseWhenPropertyIsNotPublic()
            {
                // Given
                var publicProperty = typeof(Exception).GetProperties(BindingFlags.Public | BindingFlags.Instance).First();
                var metadata = new PropertyMetadata(publicProperty, true);

                // When
                var isNotPublic = metadata.IsNotPublic;

                // Then
                isNotPublic.Should().BeFalse();
            }
 private static ArgumentException CreatePrimaryKeyTypeUnsupportedException(
     PropertyMetadata primaryKeyPropertyMetadata)
 {
     return new ArgumentException(string.Format(
         "Only nullable ints, longs, or GUIDs can be used as primary key properties. "
         + "Property {0} is not a valid primary key property because it is of type {1}. "
         + "Choose a property of a supported type to mark with the [PrimaryKey] attribute. "
         + "If the underlying database table has a primary key of a different type, you "
         + "must change the primary key definition.",
         primaryKeyPropertyMetadata.Prop.Name,
         primaryKeyPropertyMetadata.Prop.PropertyType.FullName));
 }
 private static void CheckHasPrimaryKeyProperty(
     DtoMetadata dtoMetadata,
     PropertyMetadata primaryKeyPropertyMetadata)
 {
     if (null == primaryKeyPropertyMetadata)
     {
         throw new ArgumentException(string.Format(
             "Type {0} cannot be written to the database because it has no primary key defined on it. "
             + "Add a [PrimaryKey] attribute to the property representing the primary key column. "
             + "If no primary key is defined on the underlying database table, add a primary key first.",
             dtoMetadata.DtoType.FullName));
     }
 }
Exemplo n.º 6
0
        public static PropertyMetadata GetDocs(this PropertyInfo propInfo, XPathNavigator docs)
        {
            var node = docs.SelectSingleNode(propInfo.XPathQuery());

            var rtn = new PropertyMetadata
                {
                    Name = propInfo.Name,
                    DataType = Utils.GetCleanTypeName(propInfo.PropertyType),
                    Remarks = Utils.GetNodeValue(node, "remarks"),
                    Summary = Utils.GetNodeValue(node, "summary")
                };

            return rtn;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DependencyProperty"/> class.
        /// </summary>
        /// <param name="id">The dependency property's unique identifier.</param>
        /// <param name="name">The dependency property's name.</param>
        /// <param name="uvssName">The dependency property's name within the UVSS styling system.</param>
        /// <param name="propertyType">The dependency property's value type.</param>
        /// <param name="ownerType">The dependency property's owner type.</param>
        /// <param name="metadata">The dependency property's metadata.</param>
        /// <param name="isReadOnly">A value indicating whether this is a read-only dependency property.</param>
        /// <param name="isAttached">A value indicating whether this is an attached property.</param>
        internal DependencyProperty(Int64 id, String name, String uvssName, Type propertyType, Type ownerType, PropertyMetadata metadata, Boolean isReadOnly = false, Boolean isAttached = false)
        {
            this.id              = id;
            this.name            = name;
            this.uvssName        = uvssName ?? UvssNameGenerator.GenerateUvssName(name);
            this.propertyType    = propertyType;
            this.underlyingType  = Nullable.GetUnderlyingType(propertyType);
            this.ownerType       = ownerType;
            this.defaultMetadata = metadata ?? (PropertyMetadata)typeof(PropertyMetadata<>).MakeGenericType(propertyType).GetField("Empty").GetValue(null);
            this.isReadOnly      = isReadOnly;
            this.isAttached      = isAttached;
            this.styleSetter     = CreateStyleSetter();

            this.changeNotificationServer = new DependencyPropertyChangeNotificationServer(this);
        }
        public void Foreign_Key_Metadata_Is_Correct()
        {
            //Arrange
            var productEntity = TestModel.Model.GetEntityType(typeof(Product));
            var productCategoryIdProperty = productEntity.GetProperty("ProductCategoryId");

            //Act
            var propertyMetadata = new PropertyMetadata(productCategoryIdProperty);

            //Assert
            Assert.Equal("ProductCategoryId", propertyMetadata.PropertyName);
            Assert.Equal(false, propertyMetadata.IsPrimaryKey);
            Assert.Equal(true, propertyMetadata.IsForeignKey);
            Assert.Equal(typeof(int).FullName, propertyMetadata.TypeName);
            Assert.Equal(false, propertyMetadata.IsEnum);
        }
        public void String_Property_Metadata_Is_Correct()
        {
            //Arrange
            var productEntity = TestModel.Model.GetEntityType(typeof(Product));
            var productNameProperty = productEntity.GetProperty("ProductName");

            //Act
            var propertyMetadata = new PropertyMetadata(productNameProperty);

            //Assert
            Assert.Equal("ProductName", propertyMetadata.PropertyName);
            Assert.Equal(false, propertyMetadata.IsPrimaryKey);
            Assert.Equal(false, propertyMetadata.IsForeignKey);
            Assert.Equal(typeof(string).FullName, propertyMetadata.TypeName);
            Assert.Equal(false, propertyMetadata.IsEnum);
        }
Exemplo n.º 10
0
        public async Task AddPropertyAsync(string entityName,
                                           [FromQuery] string propertyName,
                                           [FromQuery] PropertyType propertyType,
                                           [FromQuery] bool isNullable)
        {
            var dbEntiy = _db.Model.FindEntityType(entityName);

            MetadataModel model = null;

            var customization = await _db.Customizations.OrderByDescending(p => p.Id).FirstOrDefaultAsync();

            if (customization != null)
            {
                var entities = JsonSerializer.Deserialize <IEnumerable <EntityMetadata> >(customization.Metadata);

                model = new MetadataModel(customization.Id, entities);
            }
            else
            {
                model = new MetadataModel(0, new EntityMetadata[] { });
            }

            EntityMetadata entity = model.Entities.FirstOrDefault(p => p.EntityName == entityName);

            if (entity == null)
            {
                entity = new EntityMetadata(entityName, new PropertyMetadata[] { });
                model.Entities.Add(entity);
            }

            var prop = new PropertyMetadata(propertyName, isNullable, propertyType);

            entity.Properties.Add(prop);

            var addColumn = new AddColumnOperation
            {
                Name       = propertyName,
                ClrType    = CrmContext.GetClrType(prop),
                IsNullable = prop.IsNullable,
                Table      = dbEntiy.GetTableName(),
                Schema     = dbEntiy.GetSchema(),
            };

            var generator = ((IInfrastructure <IServiceProvider>)_db).Instance.GetRequiredService <IMigrationsSqlGenerator>();

            var scripts = generator.Generate(new[] { addColumn });

            await using (var transaction = await _db.Database.BeginTransactionAsync())
            {
                foreach (var script in scripts)
                {
                    await _db.Database.ExecuteSqlRawAsync(script.CommandText);
                }

                var dbCustomization = new Customization {
                    Created = DateTime.UtcNow, Metadata = JsonSerializer.Serialize(model.Entities)
                };
                _db.Add(dbCustomization);

                await _db.SaveChangesAsync();

                var newId = dbCustomization.Id;

                var newModel = new MetadataModel(newId, model.Entities);

                await transaction.CommitAsync();

                _setter.SetModel(newModel);
            }
        }
Exemplo n.º 11
0
        protected bool IsFieldValid(string fieldName)
        {
            PropertyMetadata propertyMetadata = null;

            return(QueryLite.EntityType.GetEntityMetadata().Properties.TryGetValue(fieldName, out propertyMetadata) && propertyMetadata.SqlField != null);
        }
Exemplo n.º 12
0
 protected override void OnPropertyInvalidated(DependencyProperty dp, PropertyMetadata metadata) {}
Exemplo n.º 13
0
    /// <summary>
    ///     Check to see if there is a complex path that started with the
    /// given target object and property.  If so, process the complex path
    /// information and return the results.
    /// </summary>
    internal static void GetComplexPathValue(
            DependencyObject targetObject,
            DependencyProperty targetProperty,
        ref EffectiveValueEntry entry, 
            PropertyMetadata metadata)
    {
        CloneCacheEntry cacheEntry = GetComplexPathClone(targetObject, targetProperty);

        if (cacheEntry != null)
        {
            object baseValue = entry.Value;
            if (baseValue == DependencyProperty.UnsetValue)
            {
                // If the incoming baseValue is DependencyProperty.UnsetValue, that
                // means the current property value is the default value.  Either
                // the cacheEntry.Clone was a clone of a default value (and should be
                // returned to the caller) or someone called ClearValue() (and
                // cacheEntry.Clone should be cleared accordingly).
                // To distinguish these cases we must check the cached source
                // against the default value.
                //
                // We don't have to handle the ClearValue case in this clause;
                // the comparison with the cached source to the base value
                // will fail in that case (since the cached source won't be UnsetValue)
                // and we'll clear out the cache.

                Debug.Assert(cacheEntry.Source != DependencyProperty.UnsetValue,
                    "Storyboard complex path’s clone cache should never contain DependencyProperty.UnsetValue.  Either something went wrong in Storyboard.ProcessComplexPath() or somebody else is messing with the Storyboard clone cache.");

                if (cacheEntry.Source == metadata.GetDefaultValue(targetObject, targetProperty))
                {
                    //  The cacheEntry.Clone is the clone of the default value.  In normal
                    //  non-Storyboard code paths, BaseValueSourceInternal is Unknown for default
                    //  values at this time, so we need to switch it over explicitly.
                    //
                    //  And to prevent DependencyObject.UpdateEffectiveValue from misconstruing this
                    //  as an unaltered default value (which would result in UEV thinking no change
                    //  in value occurred and discarding this new value), we will go ahead and set the 
                    //  animated value modifier on this value entry. (jeffbog:  B#1616678  5/19/2006)
                    //
                    //  In all other cases, valueSource should have the correct
                    //  valueSource corresponding to the object we cloned from,
                    //  so we don't need to do anything.

                    entry.BaseValueSourceInternal = BaseValueSourceInternal.Default;
                    entry.SetAnimatedValue(cacheEntry.Clone, DependencyProperty.UnsetValue);
                    return;
                }
            }

            // If the incoming baseValue is a deferred object, we need to get the
            //  real value to make a valid comparison against the cache entry source.
            DeferredReference deferredBaseValue = baseValue as DeferredReference;
            if (deferredBaseValue != null)
            {
                baseValue = deferredBaseValue.GetValue(entry.BaseValueSourceInternal);
                entry.Value = baseValue;
            }

            // If the incoming baseValue is different from the original source object that
            // we cloned and cached then we need to invalidate this cache. Otherwise we use
            // the value in the cache as is.
            if (cacheEntry.Source == baseValue)
            {
                CloneEffectiveValue(ref entry, cacheEntry);
                return;
            }
            else
            {
                // Setting to DependencyProperty.UnsetValue is how FrugalMap does delete.
                SetComplexPathClone(
                        targetObject, 
                        targetProperty, 
                        DependencyProperty.UnsetValue, 
                        DependencyProperty.UnsetValue);
            }
        }
    }
 private string GetUserProperty(PropertyMetadata property, InMemoryUser user)
 {
     string value;
     if (property.TryGet(user, out value))
     {
         return value;
     }
     
     switch (property.Type)
     {
         case "role.admin":
             return user.Claims.HasValue(Constants.ClaimTypes.Role, "admin").ToString().ToLower();
         case "gravatar":
             return user.Claims.GetValue("gravatar");
     }
    
     throw new Exception("Invalid property type " + property.Type);
 }
        /// <summary>
        /// GetCurrentPropertyValue
        /// </summary>
        /// <returns></returns>
        internal static object GetCurrentPropertyValue(
            AnimationStorage storage,
            DependencyObject d,
            DependencyProperty dp,
            PropertyMetadata metadata,
            object baseValue)
        {
            Debug.Assert(storage != null,
                "The 'storage' parameter cannot be passed into the GetCurrentPropertyValue method as null.");

            // If changes have been made to the snapshot value since the last tick
            // that value represents the current value of the property until the
            // next tick when the flag will be cleared. We will only take one
            // snapshot value between ticks.
            //
            // Since CurrentTimeInvaliated is raised before CurrentStateInvalidated
            // we need to check the state of the first clock as well to avoid
            // potential first frame issues. In this case _hasStickySnapshotValue
            // will be updated to false shortly.
            if (   storage._hasStickySnapshotValue
                && storage._animationClocks[0].CurrentState == ClockState.Stopped)
            {
                return storage._snapshotValue;
            }

            if (   storage._animationClocks == null
                && storage._propertyTriggerLayers == null)
            {
                Debug.Assert(storage._snapshotValue != DependencyProperty.UnsetValue);

                return storage._snapshotValue;
            }

            object currentPropertyValue = baseValue;

            if (currentPropertyValue == DependencyProperty.UnsetValue)
            {
                currentPropertyValue = metadata.GetDefaultValue(d, dp);
            }

            Debug.Assert(currentPropertyValue != DependencyProperty.UnsetValue);

            //
            // Process property trigger animations.
            //

            if (storage._propertyTriggerLayers != null)
            {
                int count = storage._propertyTriggerLayers.Count;

                Debug.Assert(count > 0);

                IList<AnimationLayer> layers = storage._propertyTriggerLayers.Values;

                for (int i = 0; i < count; i++)
                {
                    currentPropertyValue = layers[i].GetCurrentValue(currentPropertyValue);
                }
            }

            //
            // Process local animations
            //

            if (storage._animationClocks != null)
            {
                FrugalObjectList<AnimationClock> clocks = storage._animationClocks;
                int clocksCount = clocks.Count;
                bool hasActiveOrFillingClock = false;

                // default destination value will be the current property value
                // calculated by the previous layer.
                object defaultDestinationValue = currentPropertyValue;
                object currentLayerValue = currentPropertyValue;

                // if we have a snapshot value, then that will be the new
                // initial current property value.
                if (storage._snapshotValue != DependencyProperty.UnsetValue)
                {
                    currentLayerValue = storage._snapshotValue;
                }

                Debug.Assert(clocksCount > 0);
                Debug.Assert(defaultDestinationValue != DependencyProperty.UnsetValue);

                for (int i = 0; i < clocksCount; i++)
                {
                    if (clocks[i].CurrentState != ClockState.Stopped)
                    {
                        hasActiveOrFillingClock = true;

                        currentLayerValue = clocks[i].GetCurrentValue(currentLayerValue, defaultDestinationValue);

                        // An animation may not return DependencyProperty.UnsetValue as its
                        // current value.
                        if (currentLayerValue == DependencyProperty.UnsetValue)
                        {
                            throw new InvalidOperationException(SR.Get(
                                SRID.Animation_ReturnedUnsetValueInstance,
                                clocks[i].Timeline.GetType().FullName,
                                dp.Name,
                                d.GetType().FullName));
                        }
                    }
                }

                // The currentLayerValue only applies when there is at least one
                // active or filling clock.
                if (hasActiveOrFillingClock)
                {
                    currentPropertyValue = currentLayerValue;
                }
            }

            // We have a calculated currentPropertyValue, so return it if the type matches.
            if (DependencyProperty.IsValidType(currentPropertyValue, dp.PropertyType))
            {
                return currentPropertyValue;
            }
            else
            {
                // If the animation(s) applied to the property have calculated an
                // invalid value for the property then raise an exception.
                throw new InvalidOperationException(
                    SR.Get(
                        SRID.Animation_CalculatedValueIsInvalidForProperty,
                        dp.Name,
                        (currentPropertyValue == null ? "null" : currentPropertyValue.ToString())));
            }
        }
Exemplo n.º 16
0
 protected override void UpdateEntity(Entity entity, ICollection <PropertyAggregatorUpdate> updates, PropertyMetadata property, decimal newValue)
 {
     _result.Update(entity, updates, property, newValue);
 }
Exemplo n.º 17
0
            private static object ReadValue(Type inst_type, JsonReader reader)
            {
                reader.Read();

                if (reader.Token == JsonToken.ArrayEnd)
                {
                    return(null);
                }

                Type underlying_type = Nullable.GetUnderlyingType(inst_type);
                Type value_type      = underlying_type ?? inst_type;

                if (reader.Token == JsonToken.Null)
                {
                    if (inst_type.IsClass || underlying_type != null)
                    {
                        return(null);
                    }

                    throw new JsonException(String.Format(
                                                "Can't assign null to an instance of type {0}",
                                                inst_type));
                }

                if (reader.Token == JsonToken.Double ||
                    reader.Token == JsonToken.Int ||
                    reader.Token == JsonToken.Long ||
                    reader.Token == JsonToken.String ||
                    reader.Token == JsonToken.Boolean)
                {
                    Type json_type = reader.Value.GetType();

                    if (value_type.IsAssignableFrom(json_type))
                    {
                        return(reader.Value);
                    }

                    // If there's a custom importer that fits, use it
                    if (custom_importers_table.ContainsKey(json_type) &&
                        custom_importers_table[json_type].ContainsKey(
                            value_type))
                    {
                        ImporterFunc importer =
                            custom_importers_table[json_type][value_type];

                        return(importer(reader.Value));
                    }

                    // Maybe there's a base importer that works
                    if (base_importers_table.ContainsKey(json_type) &&
                        base_importers_table[json_type].ContainsKey(
                            value_type))
                    {
                        ImporterFunc importer =
                            base_importers_table[json_type][value_type];

                        return(importer(reader.Value));
                    }

                    // Maybe it's an enum
                    if (value_type.IsEnum)
                    {
                        return(Enum.ToObject(value_type, reader.Value));
                    }

                    // Try using an implicit conversion operator
                    MethodInfo conv_op = GetConvOp(value_type, json_type);

                    if (conv_op != null)
                    {
                        return(conv_op.Invoke(null,
                                              new object[] { reader.Value }));
                    }

                    // No luck
                    throw new JsonException(String.Format(
                                                "Can't assign value '{0}' (type {1}) to type {2}",
                                                reader.Value, json_type, inst_type));
                }

                object instance = null;

                if (reader.Token == JsonToken.ArrayStart)
                {
                    AddArrayMetadata(inst_type);
                    ArrayMetadata t_data = array_metadata[inst_type];

                    if (!t_data.IsArray && !t_data.IsList)
                    {
                        throw new JsonException(String.Format(
                                                    "Type {0} can't act as an array",
                                                    inst_type));
                    }

                    IList list;
                    Type  elem_type;

                    if (!t_data.IsArray)
                    {
                        list      = (IList)Activator.CreateInstance(inst_type);
                        elem_type = t_data.ElementType;
                    }
                    else
                    {
                        list      = new ArrayList();
                        elem_type = inst_type.GetElementType();
                    }

                    while (true)
                    {
                        object item = ReadValue(elem_type, reader);
                        if (item == null && reader.Token == JsonToken.ArrayEnd)
                        {
                            break;
                        }

                        list.Add(item);
                    }

                    if (t_data.IsArray)
                    {
                        int n = list.Count;
                        instance = Array.CreateInstance(elem_type, n);

                        for (int i = 0; i < n; i++)
                        {
                            ((Array)instance).SetValue(list[i], i);
                        }
                    }
                    else
                    {
                        instance = list;
                    }
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    AddObjectMetadata(value_type);
                    ObjectMetadata t_data = object_metadata[value_type];

                    instance = Activator.CreateInstance(value_type);

                    while (true)
                    {
                        reader.Read();

                        if (reader.Token == JsonToken.ObjectEnd)
                        {
                            break;
                        }

                        string property = (string)reader.Value;

                        if (t_data.Properties.ContainsKey(property))
                        {
                            PropertyMetadata prop_data =
                                t_data.Properties[property];

                            if (prop_data.IsField)
                            {
                                ((FieldInfo)prop_data.Info).SetValue(
                                    instance, ReadValue(prop_data.Type, reader));
                            }
                            else
                            {
                                PropertyInfo p_info =
                                    (PropertyInfo)prop_data.Info;

                                if (p_info.CanWrite)
                                {
                                    p_info.SetValue(
                                        instance,
                                        ReadValue(prop_data.Type, reader),
                                        null);
                                }
                                else
                                {
                                    ReadValue(prop_data.Type, reader);
                                }
                            }
                        }
                        else
                        {
                            if (!t_data.IsDictionary)
                            {
                                if (!reader.SkipNonMembers)
                                {
                                    throw new JsonException(String.Format(
                                                                "The type {0} doesn't have the " +
                                                                "property '{1}'",
                                                                inst_type, property));
                                }
                                else
                                {
                                    ReadSkip(reader);
                                    continue;
                                }
                            }

                            ((IDictionary)instance).Add(
                                property, ReadValue(
                                    t_data.ElementType, reader));
                        }
                    }
                }

                return(instance);
            }
Exemplo n.º 18
0
            private static void AddObjectMetadata(Type type)
            {
                if (object_metadata.ContainsKey(type))
                {
                    return;
                }

                ObjectMetadata data = new ObjectMetadata();

                if (type.GetInterface("System.Collections.IDictionary") != null)
                {
                    data.IsDictionary = true;
                }

                data.Properties = new Dictionary <string, PropertyMetadata>();

                foreach (PropertyInfo p_info in type.GetProperties())
                {
                    if (p_info.Name == "Item")
                    {
                        ParameterInfo[] parameters = p_info.GetIndexParameters();

                        if (parameters.Length != 1)
                        {
                            continue;
                        }

                        if (parameters[0].ParameterType == typeof(string))
                        {
                            data.ElementType = p_info.PropertyType;
                        }

                        continue;
                    }

                    PropertyMetadata p_data = new PropertyMetadata();
                    p_data.Info = p_info;
                    p_data.Type = p_info.PropertyType;

                    data.Properties.Add(p_info.Name, p_data);
                }

                foreach (FieldInfo f_info in type.GetFields())
                {
                    PropertyMetadata p_data = new PropertyMetadata();
                    p_data.Info    = f_info;
                    p_data.IsField = true;
                    p_data.Type    = f_info.FieldType;

                    data.Properties.Add(f_info.Name, p_data);
                }

                lock (object_metadata_lock)
                {
                    try
                    {
                        object_metadata.Add(type, data);
                    }
                    catch (ArgumentException)
                    {
                        return;
                    }
                }
            }
Exemplo n.º 19
0
        /// <summary>
        /// GetCurrentPropertyValue
        /// </summary>
        /// <returns></returns>
        internal static object GetCurrentPropertyValue(
            AnimationStorage storage,
            DependencyObject d,
            DependencyProperty dp,
            PropertyMetadata metadata,
            object baseValue)
        {
            Debug.Assert(storage != null,
                         "The 'storage' parameter cannot be passed into the GetCurrentPropertyValue method as null.");

            // If changes have been made to the snapshot value since the last tick
            // that value represents the current value of the property until the
            // next tick when the flag will be cleared. We will only take one
            // snapshot value between ticks.
            //
            // Since CurrentTimeInvaliated is raised before CurrentStateInvalidated
            // we need to check the state of the first clock as well to avoid
            // potential first frame issues. In this case _hasStickySnapshotValue
            // will be updated to false shortly.
            if (storage._hasStickySnapshotValue &&
                storage._animationClocks[0].CurrentState == ClockState.Stopped)
            {
                return(storage._snapshotValue);
            }

            if (storage._animationClocks == null &&
                storage._propertyTriggerLayers == null)
            {
                Debug.Assert(storage._snapshotValue != DependencyProperty.UnsetValue);

                return(storage._snapshotValue);
            }

            object currentPropertyValue = baseValue;

            if (currentPropertyValue == DependencyProperty.UnsetValue)
            {
                currentPropertyValue = metadata.GetDefaultValue(d, dp);
            }

            Debug.Assert(currentPropertyValue != DependencyProperty.UnsetValue);

            //
            // Process property trigger animations.
            //

            if (storage._propertyTriggerLayers != null)
            {
                int count = storage._propertyTriggerLayers.Count;

                Debug.Assert(count > 0);

                IList <AnimationLayer> layers = storage._propertyTriggerLayers.Values;

                for (int i = 0; i < count; i++)
                {
                    currentPropertyValue = layers[i].GetCurrentValue(currentPropertyValue);
                }
            }

            //
            // Process local animations
            //

            if (storage._animationClocks != null)
            {
                FrugalObjectList <AnimationClock> clocks = storage._animationClocks;
                int  clocksCount             = clocks.Count;
                bool hasActiveOrFillingClock = false;

                // default destination value will be the current property value
                // calculated by the previous layer.
                object defaultDestinationValue = currentPropertyValue;
                object currentLayerValue       = currentPropertyValue;

                // if we have a snapshot value, then that will be the new
                // initial current property value.
                if (storage._snapshotValue != DependencyProperty.UnsetValue)
                {
                    currentLayerValue = storage._snapshotValue;
                }

                Debug.Assert(clocksCount > 0);
                Debug.Assert(defaultDestinationValue != DependencyProperty.UnsetValue);

                for (int i = 0; i < clocksCount; i++)
                {
                    if (clocks[i].CurrentState != ClockState.Stopped)
                    {
                        hasActiveOrFillingClock = true;

                        currentLayerValue = clocks[i].GetCurrentValue(currentLayerValue, defaultDestinationValue);

                        // An animation may not return DependencyProperty.UnsetValue as its
                        // current value.
                        if (currentLayerValue == DependencyProperty.UnsetValue)
                        {
                            throw new InvalidOperationException(SR.Get(
                                                                    SRID.Animation_ReturnedUnsetValueInstance,
                                                                    clocks[i].Timeline.GetType().FullName,
                                                                    dp.Name,
                                                                    d.GetType().FullName));
                        }
                    }
                }

                // The currentLayerValue only applies when there is at least one
                // active or filling clock.
                if (hasActiveOrFillingClock)
                {
                    currentPropertyValue = currentLayerValue;
                }
            }

            // We have a calculated currentPropertyValue, so return it if the type matches.
            if (DependencyProperty.IsValidType(currentPropertyValue, dp.PropertyType))
            {
                return(currentPropertyValue);
            }
            else
            {
                // If the animation(s) applied to the property have calculated an
                // invalid value for the property then raise an exception.
                throw new InvalidOperationException(
                          SR.Get(
                              SRID.Animation_CalculatedValueIsInvalidForProperty,
                              dp.Name,
                              (currentPropertyValue == null ? "null" : currentPropertyValue.ToString())));
            }
        }
Exemplo n.º 20
0
        private void OnCurrentTimeInvalidated(object sender, EventArgs args)
        {
            object target = _dependencyObject.Target;

            if (target == null)
            {
                // If the target has been garbage collected, remove this handler
                // from the AnimationClock so that this collection can be
                // released also.
                DetachAnimationClock((AnimationClock)sender, _removeRequestedHandler);
            }
            else
            {
                // recompute animated value
                try
                {
                    DependencyObject targetDO = ((DependencyObject)target);

                    // fetch the existing entry
                    EffectiveValueEntry oldEntry = targetDO.GetValueEntry(
                        targetDO.LookupEntry(_dependencyProperty.GlobalIndex),
                        _dependencyProperty,
                        null,
                        RequestFlags.RawEntry);

                    EffectiveValueEntry newEntry;
                    object value;

                    // create a copy of that entry, removing animated & coerced values

                    if (!oldEntry.HasModifiers)
                    {
                        // no modifiers; just use it, removing deferred references
                        newEntry = oldEntry;
                        value    = newEntry.Value;
                        if (newEntry.IsDeferredReference)
                        {
                            value          = ((DeferredReference)value).GetValue(newEntry.BaseValueSourceInternal);
                            newEntry.Value = value;
                        }
                    }
                    else
                    {
                        // else entry has modifiers; preserve expression but throw away
                        // coerced & animated values, since we'll be recomputing an animated value
                        newEntry = new EffectiveValueEntry();
                        newEntry.BaseValueSourceInternal = oldEntry.BaseValueSourceInternal;
                        newEntry.PropertyIndex           = oldEntry.PropertyIndex;
                        newEntry.HasExpressionMarker     = oldEntry.HasExpressionMarker;

                        value = oldEntry.ModifiedValue.BaseValue;
                        if (oldEntry.IsDeferredReference)
                        {
                            DeferredReference dr = value as DeferredReference;
                            if (dr != null)
                            {
                                value = dr.GetValue(newEntry.BaseValueSourceInternal);
                            }
                        }

                        newEntry.Value = value;

                        if (oldEntry.IsExpression)
                        {
                            value = oldEntry.ModifiedValue.ExpressionValue;
                            if (oldEntry.IsDeferredReference)
                            {
                                DeferredReference dr = value as DeferredReference;
                                if (dr != null)
                                {
                                    value = dr.GetValue(newEntry.BaseValueSourceInternal);
                                }
                            }
                            newEntry.SetExpressionValue(value, newEntry.Value);
                        }
                    }

                    // compute the new value for the property

                    PropertyMetadata metadata      = _dependencyProperty.GetMetadata(targetDO.DependencyObjectType);
                    object           animatedValue = AnimationStorage.GetCurrentPropertyValue(this, targetDO, _dependencyProperty, metadata, value);

                    if (_dependencyProperty.IsValidValueInternal(animatedValue))
                    {
                        // update the new entry to contain the new animated value
                        newEntry.SetAnimatedValue(animatedValue, value);

                        // call UpdateEffectiveValue to put the new entry in targetDO's effective values table
                        targetDO.UpdateEffectiveValue(
                            targetDO.LookupEntry(_dependencyProperty.GlobalIndex),
                            _dependencyProperty,
                            metadata,
                            oldEntry,
                            ref newEntry,
                            false /* coerceWithDeferredReference */,
                            false /* coerceWithCurrentValue */,
                            OperationType.Unknown);

                        if (_hadValidationError)
                        {
                            if (TraceAnimation.IsEnabled)
                            {
                                TraceAnimation.TraceActivityItem(
                                    TraceAnimation.AnimateStorageValidationNoLongerFailing,
                                    this,
                                    animatedValue,
                                    target,
                                    _dependencyProperty);

                                _hadValidationError = false;
                            }
                        }
                    }
                    else if (!_hadValidationError)
                    {
                        if (TraceAnimation.IsEnabled)
                        {
                            TraceAnimation.TraceActivityItem(
                                TraceAnimation.AnimateStorageValidationFailed,
                                this,
                                animatedValue,
                                target,
                                _dependencyProperty);
                        }

                        _hadValidationError = true;
                    }
                }
                catch (Exception e)
                {
                    // Catch all exceptions thrown during the InvalidateProperty callstack
                    // and wrap them in an AnimationException

                    throw new AnimationException(
                              (AnimationClock)sender,
                              _dependencyProperty,
                              (IAnimatable)target,
                              SR.Get(
                                  SRID.Animation_Exception,
                                  _dependencyProperty.Name,
                                  target.GetType().FullName,
                                  ((AnimationClock)sender).Timeline.GetType().FullName),
                              e);
                }
            }
        }
Exemplo n.º 21
0
 private static void AppendJoinConditionArgument(StringBuilder fromAndJoinsBuff, PropertyMetadata property, string alias)
 {
     AppendJoinConditionArgument(fromAndJoinsBuff, property.ColumnName, alias);
 }
Exemplo n.º 22
0
		protected virtual void Merge (PropertyMetadata baseMetadata, DependencyProperty dp)
		{
			if (defaultValue == null)
				defaultValue = baseMetadata.defaultValue;
			if (propertyChangedCallback == null)
				propertyChangedCallback = baseMetadata.propertyChangedCallback;
			if (coerceValueCallback == null)
				coerceValueCallback = baseMetadata.coerceValueCallback;
		}
Exemplo n.º 23
0
 protected override object GetValueCore(DependencyProperty property, object baseValue, PropertyMetadata metadata)
 {
   throw new NotImplementedException();
 }
        public virtual IdentityManagerMetadata GetStandardMetadata(bool includeAccountProperties = true)
        {
            var update = new List <PropertyMetadata>();

            if (userAccountService.Configuration.EmailIsUsername)
            {
                update.AddRange(new PropertyMetadata[] {
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Username, GetUsername, SetUsername, name: "Email", dataType: PropertyDataType.Email, required: true),
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Password, x => null, SetPassword, name: "Password", dataType: PropertyDataType.Password, required: true),
                });
            }
            else
            {
                update.AddRange(new PropertyMetadata[] {
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Username, GetUsername, SetUsername, name: "Username", dataType: PropertyDataType.String, required: true),
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Password, x => null, SetPassword, name: "Password", dataType: PropertyDataType.Password, required: true),
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Email, GetEmail, SetConfirmedEmail, name: "Email", dataType: PropertyDataType.Email, required: userAccountService.Configuration.RequireAccountVerification),
                });
            }

            var create = new List <PropertyMetadata>();

            if (!userAccountService.Configuration.EmailIsUsername && !userAccountService.Configuration.RequireAccountVerification)
            {
                create.AddRange(update.Where(x => x.Required).ToArray());
                create.AddRange(new PropertyMetadata[] {
                    PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Email, GetEmail, SetConfirmedEmail, name: "Email", dataType: PropertyDataType.Email, required: false),
                });
            }

            update.AddRange(new PropertyMetadata[] {
                PropertyMetadata.FromFunctions <TAccount, string>(Constants.ClaimTypes.Phone, GetPhone, SetConfirmedPhone, name: "Phone", dataType: PropertyDataType.String, required: false),
                PropertyMetadata.FromFunctions <TAccount, bool>("IsLoginAllowed", GetIsLoginAllowed, SetIsLoginAllowed, name: "Is Login Allowed", dataType: PropertyDataType.Boolean, required: false),
            });

            if (includeAccountProperties)
            {
                update.AddRange(PropertyMetadata.FromType <TAccount>());
            }

            var user = new UserMetadata
            {
                SupportsCreate   = true,
                SupportsDelete   = true,
                SupportsClaims   = true,
                CreateProperties = create,
                UpdateProperties = update
            };

            var meta = new IdentityManagerMetadata {
                UserMetadata = user
            };

            if (this.groupService != null && this.groupQuery != null)
            {
                meta.RoleMetadata.SupportsCreate   = true;
                meta.RoleMetadata.SupportsDelete   = true;
                meta.RoleMetadata.RoleClaimType    = Constants.ClaimTypes.Role;
                meta.RoleMetadata.CreateProperties = new PropertyMetadata[] {
                    new PropertyMetadata {
                        Name     = "Name",
                        Type     = Constants.ClaimTypes.Name,
                        DataType = PropertyDataType.String,
                        Required = true
                    }
                };
            }

            return(meta);
        }
 protected string GetScopeProperty(PropertyMetadata propMetadata, Data.StoredScope scope)
 {
     string val;
     if (propMetadata.TryGet(scope, out val))
     {
         return val;
     }
     throw new Exception("Invalid property type " + propMetadata.Type);
 }
 public virtual PropertyMetadata GetMetadataForClaim(string type, string name = null, PropertyDataType dataType = PropertyDataType.String, bool required = false)
 {
     return(PropertyMetadata.FromFunctions <TAccount, string>(type, GetForClaim(type), SetForClaim(type), name, dataType, required));
 }
Exemplo n.º 27
0
 private static bool TargetFreezeValueCallback(
     DependencyObject d,
     DependencyProperty dp,
     EntryIndex entryIndex,
     PropertyMetadata metadata,
     bool isChecking)
 {
     // We allow the object to which the Target property is attached to be
     // frozen, even though the value of the Target property is not usable
     // from other threads.  Clocks clone & freeze copies of their original
     // timelines because the clocks will not respond to changes to those
     // timelines.
     return true;
 }
Exemplo n.º 28
0
        public INTERNAL_PropertyStorage(DependencyObject owner, DependencyProperty property, PropertyMetadata typeMetadata)
        {
            //_defaultValue = INTERNAL_NoValue.NoValue;
            Owner        = owner;
            Property     = property;
            TypeMetadata = typeMetadata;
            if (property == FrameworkElement.IsEnabledProperty || property == FrameworkElement.IsHitTestVisibleProperty)
            {
                _isIsEnabledOrIsHitTestVisibleProperty = true;
            }
            CoercedValue       = INTERNAL_NoValue.NoValue;
            VisualStateValue   = INTERNAL_NoValue.NoValue;
            ActiveLocalValue   = new INTERNAL_LocalValue();
            LocalStyleValue    = INTERNAL_NoValue.NoValue;
            ImplicitStyleValue = INTERNAL_NoValue.NoValue;
            InheritedValue     = INTERNAL_NoValue.NoValue;

            // The default value is used initially for the Actual Value:
            ActualValue = typeMetadata != null ? typeMetadata.DefaultValue : null;
        }
        private void AppendPropertyToInsertStatement(
            StringBuilder colBuff, StringBuilder valBuff, PropertyMetadata property,
            ref int index, BaseInsertDeleteOperation operation, ArrayList values, MethodInfo getter)
        {
            if (property.HasAttribute<ForeignKeyReferenceAttribute>()
                && null != operation.OwnerMetadata
                && _dtoMetadataCache.GetValidatedMetadataFor(
                    property.GetAttribute<ForeignKeyReferenceAttribute>().ReferencedDto).TableName ==
                operation.OwnerMetadata.TableName)
            {
                values.Add(
                    new Func<object>(() => operation.OwnerPrimaryKeyAsObject));
            }
            else if (property.HasAttribute<ManyToOneAttribute>() && property.GetAttribute<ManyToOneAttribute>().ForeignKeyTargetColumnName != null)
            {
                var propValue = property.GetValue(operation.Value);
                var propTypeMetadata = _dtoMetadataCache.GetValidatedMetadataFor(property.Prop.PropertyType);
                if (null != propValue && null != propTypeMetadata)
                {
                    var targetName = property.GetAttribute<ManyToOneAttribute>().ForeignKeyTargetColumnName;
                    var fkTargetProperty = propTypeMetadata[targetName];
                    if (fkTargetProperty == null)
                    {
                        throw new ArgumentException(string.Format(
                            "Cannot INSERT foreign key value for non existent target column '{0}'"
                            + " specified from column '{1}'.",
                            targetName,
                            property.ColumnName));
                    }

                    values.Add(new Func<object>(() => fkTargetProperty.GetValue(propValue)));
                }
                else
                {
                    values.Add(new Func<object>(() => null));
                }
            }
            else if (property.HasAttribute<ManyToOneAttribute>() || property.HasAttribute<OneToOneAttribute>())
            {
                if (property.HasAttribute<OneToOneAttribute>() && !property.HasAttribute<ForeignKeyReferenceAttribute>())
                {
                    //  One to one relationship where child table references parent rather than the other way around.
                    //  This will be saved along with the child object.
                    return;
                }

                object propValue = property.GetValue(operation.Value);
                DtoMetadata propMetadata = _dtoMetadataCache.GetValidatedMetadataFor(property.Prop.PropertyType);
                values.Add(
                    new Func<object>(
                        () =>
                            propValue == null || propMetadata == null
                                ? null
                                : propMetadata.GetPrimaryKeyValueAsObject(propValue)));
            }
            else
            {
                values.Add(getter.Invoke(operation.Value, new object[0]));
            }

            if (colBuff.Length > 0) {
                colBuff.Append(@", ");
                valBuff.Append(@", ");
            }

            colBuff.Append("[" + property.ColumnName + "]");

            valBuff.Append("{");
            valBuff.Append(index);
            valBuff.Append("}");

            ++index;
        }
Exemplo n.º 30
0
        public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
        {
            DependencyProperty property = Register(name, propertyType, ownerType, typeMetadata);

            property._isAttached = true;
            return(property);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Overrides the property's metadata for the specified type.
        /// </summary>
        /// <param name="forType">The type for which to override property metadata.</param>
        /// <param name="typeMetadata">The property metadata for the specified type.</param>
        public void OverrideMetadata(Type forType, PropertyMetadata typeMetadata)
        {
            Contract.Require(ownerType, "ownerType");

            if (metadataOverrides.ContainsKey(forType))
                throw new InvalidOperationException(PresentationStrings.DependencyPropertyAlreadyRegistered);

            var merged = false;

            var currentType = forType.BaseType;
            while (currentType != null)
            {
                PropertyMetadata currentTypeMetadata;
                if (metadataOverrides.TryGetValue(currentType, out currentTypeMetadata))
                {
                    if (typeMetadata == null)
                    {
                        typeMetadata = currentTypeMetadata;
                    }
                    else
                    {
                        typeMetadata.Merge(currentTypeMetadata, this);
                    }
                    merged = true;
                    break;
                }
                currentType = currentType.BaseType;
            }

            if (!merged)
            {
                var baseMetadata = GetMetadataForOwner(ownerType);
                if (typeMetadata == null)
                {
                    typeMetadata = baseMetadata;
                }
                else
                {
                    typeMetadata.Merge(baseMetadata, this);
                }
                merged = true;
            }

            metadataOverrides[forType] = typeMetadata;
        }
Exemplo n.º 32
0
        /// <summary>
        /// Registers a dependency property with the specified property name, property type, owner type, and property metadata.
        /// </summary>
        /// <param name="name">The property name.</param>
        /// <param name="propertyType">The type of the property.</param>
        /// <param name="ownerType">The type of the property's owner.</param>
        /// <param name="typeMetadata">The property metadata.</param>
        /// <returns>The DependencyProperty.</returns>
        public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
        {
#if PERFSTAT
            var t = Performance.now();
#endif
            PropertyMetadata defaultMetadata = typeMetadata;
            if (defaultMetadata == null)
            {
                //Create metadata if not set
                defaultMetadata = new PropertyMetadata();
            }
            // Make sure typeMetadata default value is valid.
            EnsureDefaultValue(defaultMetadata, propertyType, name, ownerType);

            var newDependencyProperty = new DependencyProperty()
            {
                Name          = name,
                PropertyType  = propertyType,
                OwnerType     = ownerType,
                _typeMetadata = defaultMetadata
                                //Store = INTERNAL_PropertyStore.Instance
            };

            // Add the dependency property to the list of all the dependency properties of the object:
            INTERNAL_TypeToDependencyProperties.Add(ownerType, newDependencyProperty);

            // Add the dependency property to the list that is used to know whether to always call "PropertyChanged" when the UI element is loaded into the Visual Tree:
            if (typeMetadata != null && typeMetadata.CallPropertyChangedWhenLoadedIntoVisualTree == WhenToCallPropertyChangedEnum.Always)
            {
                INTERNAL_TypeToDependencyPropertiesThatRequirePropertyChanged.Add(ownerType, newDependencyProperty);
            }

            //Add the dependencyProperty's name to the dictionary that allows to get the dependencyProperty from its name:
            Dictionary <string, DependencyProperty> stringsToDependencyProperties = INTERNAL_TypeToStringsToDependencyProperties.GetDictionaryForType(ownerType);
            if (stringsToDependencyProperties.ContainsKey(name))
            {
#if !MIGRATION
                // THE FOLLOWING CHECK IS DISABLED IN THE SILVERLIGHT COMPATIBLE VERSION
                // BECAUSE IT APPEARS THAT SILVERLIGHT IS TOLERANT TO DECLARING TWICE
                // THE SAME DEPENDENCY PROPERTY OR ATTACHED PROPERTY. FOR AN EXAMPLE OF
                // USE, SEE THE CLASS "RatingsView" IN THE CLIENT APPLICATION "STAR".
                if (stringsToDependencyProperties[name] != null)
                {
                    throw new Exception("Cannot register multiple properties with the same PropertyName");
                }
#endif
                stringsToDependencyProperties[name] = newDependencyProperty;
            }
            else
            {
                stringsToDependencyProperties.Add(name, newDependencyProperty);
            }
#if PERFSTAT
            Performance.Counter("DependencyProperty.Register", t);
#endif
            return(newDependencyProperty);
        }
Exemplo n.º 33
0
 public PropertyTreeView(PropertyMetadata property)
 {
     _property      = property;
     Name           = property.Name;
     TypeOfMetadata = "property";
 }
Exemplo n.º 34
0
        void OnDPSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBoxItem        selected = (ListBoxItem)e.AddedItems[0]; // we won't handle multiselect
            PropertyMetadata   pm;
            DependencyProperty dp = null;

            switch (selected.Content.ToString())
            {
            case ("ToggleButton.IsChecked"):
                dp = ToggleButton.IsCheckedProperty;
                break;

            case ("Control.Background"):
                dp = Control.BackgroundProperty;
                break;

            case ("Storyboard.TargetName"):
                dp = Storyboard.TargetNameProperty;
                break;

            case ("FrameworkElement.DataContext"):
                dp = FrameworkElement.DataContextProperty;
                break;

            case ("FrameworkElement.Margin"):
                dp = FrameworkElement.MarginProperty;
                break;

            case ("ToolBar.Orientation"):
                dp = ToolBar.OrientationProperty;
                break;

            case ("UIElement.Visibility"):
                dp = UIElement.VisibilityProperty;
                break;
            }
            //<SnippetDPProps>
            //<SnippetDPGetMetadataSingle>
            pm = dp.GetMetadata(dp.OwnerType);
            //</SnippetDPGetMetadataSingle>
            MetadataClass.Text        = pm.GetType().Name;
            TypeofPropertyValue.Text  = dp.PropertyType.Name;
            DefaultPropertyValue.Text = (pm.DefaultValue != null) ? pm.DefaultValue.ToString() : "null";
            HasCoerceValue.Text       = (pm.CoerceValueCallback == null) ? "No" : pm.CoerceValueCallback.Method.Name;
            HasPropertyChanged.Text   = (pm.PropertyChangedCallback == null) ? "No" : pm.PropertyChangedCallback.Method.Name;
            ReadOnly.Text             = (dp.ReadOnly) ? "Yes" : "No";
            //</SnippetDPProps>
            //<SnippetFPMProperties>
            FrameworkPropertyMetadata fpm = pm as FrameworkPropertyMetadata;

            if (fpm != null)
            {
                AffectsArrange.Text       = (fpm.AffectsArrange) ? "Yes" : "No";
                AffectsMeasure.Text       = (fpm.AffectsMeasure) ? "Yes" : "No";
                AffectsRender.Text        = (fpm.AffectsRender) ? "Yes" : "No";
                Inherits.Text             = (fpm.Inherits) ? "Yes" : "No";
                IsDataBindingAllowed.Text = (fpm.IsDataBindingAllowed) ? "Yes" : "No";
                BindsTwoWayByDefault.Text = (fpm.BindsTwoWayByDefault) ? "Yes" : "No";
            }
            //</SnippetFPMProperties>
            else
            {
                AffectsArrange.Text       = "N/A";
                AffectsMeasure.Text       = "N/A";
                AffectsRender.Text        = "N/A";
                Inherits.Text             = "N/A";
                IsDataBindingAllowed.Text = "N/A";
                BindsTwoWayByDefault.Text = "N/A";
            }
            //<SnippetDPDefaultValue>
            PropertyMetadata pmDefault = dp.DefaultMetadata;
            //</SnippetDPDefaultValue>
        }
Exemplo n.º 35
0
 public ForeignKeyMappingInfo(PropertyMetadata metadata, PropertyMetadata metadataForSave, NavigationPropertyMetadata navPropertyMetadata, PropertyMetadata keyPropertyMetadata) : base(metadata, metadataForSave)
 {
     NavPropertyMetadata = navPropertyMetadata ?? throw new ArgumentNullException(nameof(navPropertyMetadata));
     KeyPropertyMetadata = keyPropertyMetadata ?? throw new ArgumentNullException(nameof(keyPropertyMetadata));
     KeyType             = GetKeyType(keyPropertyMetadata);
 }
Exemplo n.º 36
0
        static void RenderElementsAndRaiseChangedEventOnAllDependencyProperties(DependencyObject dependencyObject)
        {
            //--------------------------------------------------------------
            // RAISE "PROPERTYCHANGED" FOR ALL THE PROPERTIES THAT HAVE
            // A VALUE THAT HAS BEEN SET, INCLUDING ATTACHED PROPERTIES,
            // AND CALL THE "METHOD TO UPDATE DOM"
            //--------------------------------------------------------------

            // This is used to force a redraw of all the properties that are
            // set on the object (including Attached Properties!). For
            // example, if a Border has a colored background, this is the
            // moment when that color will be applied. Properties that have
            // no value set by the user are not concerned (their default
            // state is rendered elsewhere).

#if PERFSTAT
            var t0 = Performance.now();
#endif
            // we copy the Dictionary so that the foreach doesn't break when
            // we modify a DependencyProperty inside the Changed of another
            // one (which causes it to be added to the Dictionary).
            // we exclude properties where source is set to default because
            // it means they have been set at some point, and unset afterward,
            // so we should not call the PropertyChanged callback.
            var list = dependencyObject.INTERNAL_PropertyStorageDictionary
                       .Where(s => s.Value.BaseValueSourceInternal > BaseValueSourceInternal.Default)
                       .ToList();
#if PERFSTAT
            Performance.Counter("VisualTreeManager: Copy list of properties", t0);
#endif

            foreach (KeyValuePair <DependencyProperty, INTERNAL_PropertyStorage> propertiesAndTheirStorage in list)
            {
                // Read the value:
                DependencyProperty property = propertiesAndTheirStorage.Key;

#if PERFSTAT
                var t1 = Performance.now();
#endif

                PropertyMetadata propertyMetadata = property.GetTypeMetaData(dependencyObject.GetType());

                if (propertyMetadata != null)
                {
                    INTERNAL_PropertyStorage storage = propertiesAndTheirStorage.Value;
                    object value             = null;
                    bool   valueWasRetrieved = false;

                    //--------------------------------------------------
                    // Call "Apply CSS", which uses "GetCSSEquivalent/s"
                    //--------------------------------------------------

                    if (propertyMetadata.GetCSSEquivalent != null || propertyMetadata.GetCSSEquivalents != null)
                    {
                        if (!valueWasRetrieved)
                        {
                            value             = INTERNAL_PropertyStore.GetEffectiveValue(storage);
                            valueWasRetrieved = true;
                        }

                        INTERNAL_PropertyStore.ApplyCssChanges(value, value, propertyMetadata, storage.Owner);
                    }

                    //--------------------------------------------------
                    // Call "MethodToUpdateDom"
                    //--------------------------------------------------
                    if (propertyMetadata.MethodToUpdateDom != null)
                    {
                        if (!valueWasRetrieved)
                        {
                            value             = INTERNAL_PropertyStore.GetEffectiveValue(storage);
                            valueWasRetrieved = true;
                        }

                        // Call the "Method to update DOM"
                        propertyMetadata.MethodToUpdateDom(storage.Owner, value);
                    }

                    //--------------------------------------------------
                    // Call PropertyChanged
                    //--------------------------------------------------

                    if (propertyMetadata.PropertyChangedCallback != null &&
                        propertyMetadata.CallPropertyChangedWhenLoadedIntoVisualTree != WhenToCallPropertyChangedEnum.Never)
                    {
                        if (!valueWasRetrieved)
                        {
                            value             = INTERNAL_PropertyStore.GetEffectiveValue(storage);
                            valueWasRetrieved = true;
                        }

                        // Raise the "PropertyChanged" event
                        propertyMetadata.PropertyChangedCallback(storage.Owner, new DependencyPropertyChangedEventArgs(value, value, property));
                    }
                }


#if PERFSTAT
                Performance.Counter("VisualTreeManager: RaisePropertyChanged for property '" + property.Name + "'", t1);
#endif
            }
        }
Exemplo n.º 37
0
		internal void DoMerge (PropertyMetadata baseMetadata, DependencyProperty dp, Type targetType)
		{
			Merge (baseMetadata, dp);
			OnApply (dp, targetType);
			isSealed = true;
		}
Exemplo n.º 38
0
 protected override object GetValueCore(DependencyProperty property, object baseValue, PropertyMetadata metadata)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 39
0
        protected IDbDataParameter CreateParameter(PropertyMetadata property, string fieldName)
        {
            var field = property.SqlField;
            string parameterName = DataService.EntityLiteProvider.ParameterPrefix + fieldName;
            IDbDataParameter parameter = DataService.DbProviderFactory.CreateParameter();
            parameter.ParameterName = parameterName;
            Type propertyType = property.PropertyInfo.PropertyType.UndelyingType();

            if (typeof(System.Data.SqlTypes.INullable).IsAssignableFrom(propertyType))
            {
                parameter.DbType = DbType.String;
                if (propertyType == typeof(Microsoft.SqlServer.Types.SqlHierarchyId))
                {
                    parameter.Size = 4000;
                }
                else
                {
                    parameter.Size = 1073741823;
                }
                return parameter;
            }
            parameter.DbType = field.DbType;
            parameter.Size = field.Size;
            parameter.SourceColumn = fieldName;
            if (field.Precision != 255 && field.Precision != 0)
            {
                parameter.Precision = field.Precision;
            }
            if (field.Scale != 255 && field.Scale != 0)
            {
                parameter.Scale = field.Scale;
            }
            return parameter;
        }
Exemplo n.º 40
0
        internal static INTERNAL_PropertyStorage GetInheritedPropertyStorageOrCreateNewIfNotFound(DependencyObject dependencyObject, DependencyProperty dependencyProperty)
        {
            // Create the dictionary of it does not already exist:
            if (dependencyObject.INTERNAL_AllInheritedProperties == null)
            {
                dependencyObject.INTERNAL_AllInheritedProperties = new Dictionary <DependencyProperty, INTERNAL_PropertyStorage>();
            }

            // Create the Storage if it does not already exist, and if "createAndSaveNewStorageIfNotExists" is True:
            INTERNAL_PropertyStorage storage;

            if (!dependencyObject.INTERNAL_AllInheritedProperties.TryGetValue(dependencyProperty, out storage))
            {
                // Create the dictionary of it does not already exist:
                if (dependencyObject.INTERNAL_PropertyStorageDictionary == null)
                {
                    dependencyObject.INTERNAL_PropertyStorageDictionary = new Dictionary <DependencyProperty, INTERNAL_PropertyStorage>();
                }

                // Get the storage or create a new one:
                if (dependencyObject.INTERNAL_PropertyStorageDictionary.ContainsKey(dependencyProperty))
                {
                    storage = dependencyObject.INTERNAL_PropertyStorageDictionary[dependencyProperty];
                }
                else
                {
                    // Get the type metadata (if any):
                    PropertyMetadata typeMetadata = dependencyProperty.GetTypeMetaData(dependencyObject.GetType());

                    // Create the storage:
                    storage = new INTERNAL_PropertyStorage(dependencyObject, dependencyProperty, typeMetadata);
                }
                dependencyObject.INTERNAL_AllInheritedProperties.Add(dependencyProperty, storage);

                //-----------------------
                // CHECK IF THE PROPERTY BELONGS TO THE OBJECT (OR TO ONE OF ITS ANCESTORS):
                //-----------------------
                //below: we check if the property is useful to the current DependencyObject, in which case we set it as its inheritedValue in "PropertyStorageDictionary"
                if (dependencyProperty.OwnerType.IsAssignableFrom(dependencyObject.GetType()))
                {
                    //-----------------------
                    // ADD THE STORAGE TO "INTERNAL_PropertyStorageDictionary" IF IT IS NOT ALREADY THERE:
                    //-----------------------
                    if (dependencyObject.INTERNAL_PropertyStorageDictionary == null)
                    {
                        dependencyObject.INTERNAL_PropertyStorageDictionary = new Dictionary <DependencyProperty, INTERNAL_PropertyStorage>();
                    }

                    if (!dependencyObject.INTERNAL_PropertyStorageDictionary.ContainsKey(dependencyProperty))
                    {
                        dependencyObject.INTERNAL_PropertyStorageDictionary.Add(dependencyProperty, storage);
                    }
                }
            }

            return(storage);


            #region OldStuff

            /*
             * // This method ensures that the two dictionaries ("INTERNAL_PropertyStorageDictionary" and "INTERNAL_AllInheritedProperties") always share the same instances of Storages (for properties that are in common):
             * // This is how it works:
             * // - If both in INTERNAL_PropertyStorageDictionary and in INTERNAL_AllInheritedProperties, return any one
             * // - If in INTERNAL_PropertyStorageDictionary but not in INTERNAL_AllInheritedProperties, copy it to INTERNAL_AllInheritedProperties and return it
             * // - If in INTERNAL_AllInheritedProperties but not in INTERNAL_PropertyStorageDictionary, AND the property belongs to the object (or one of its ancestors), copy it to INTERNAL_PropertyStorageDictionary and return it
             * // - If in neither INTERNAL_PropertyStorageDictionary nor INTERNAL_AllInheritedProperties, create it in INTERNAL_AllInheritedProperties, and, if the property belongs to the object (or one of its ancestors), copy it to INTERNAL_PropertyStorageDictionary and return it
             *
             * if (dependencyObject.INTERNAL_PropertyStorageDictionary != null && dependencyObject.INTERNAL_PropertyStorageDictionary.ContainsKey(dependencyProperty))
             * {
             *  if (dependencyObject.INTERNAL_AllInheritedProperties != null && dependencyObject.INTERNAL_AllInheritedProperties.ContainsKey(dependencyProperty))
             *  {
             *      //--------------------------------------------
             *      // The property storage is in both INTERNAL_PropertyStorageDictionary and INTERNAL_AllInheritedProperties, so we return any one:
             *      //--------------------------------------------
             *      return dependencyObject.INTERNAL_AllInheritedProperties[dependencyProperty];
             *  }
             *  else
             *  {
             *      //--------------------------------------------
             *      // The property storage is in INTERNAL_PropertyStorageDictionary but not in INTERNAL_AllInheritedProperties, so we copy it to INTERNAL_AllInheritedProperties and return it:
             *      //--------------------------------------------
             *      var storage = dependencyObject.INTERNAL_PropertyStorageDictionary[dependencyProperty];
             *      if (createAndSaveNewStorageIfNotExists)
             *      {
             *          if (dependencyObject.INTERNAL_AllInheritedProperties == null)
             *              dependencyObject.INTERNAL_AllInheritedProperties = new Dictionary<DependencyProperty,INTERNAL_PropertyStorage>();
             *          dependencyObject.INTERNAL_AllInheritedProperties.Add(dependencyProperty, storage);
             *      }
             *      return storage;
             *  }
             * }
             * else
             * {
             *  if (dependencyObject.INTERNAL_AllInheritedProperties != null && dependencyObject.INTERNAL_AllInheritedProperties.ContainsKey(dependencyProperty))
             *  {
             *      //--------------------------------------------
             *      // The property storage is in INTERNAL_AllInheritedProperties but not in INTERNAL_PropertyStorageDictionary, therefore, if the property belongs to the object (or one of its ancestors), we copy it to INTERNAL_PropertyStorageDictionary and we return it
             *      //--------------------------------------------
             *      var storage = dependencyObject.INTERNAL_AllInheritedProperties[dependencyProperty];
             *      if (createAndSaveNewStorageIfNotExists && dependencyProperty.OwnerType.IsAssignableFrom(dependencyObject.GetType())) // The second condition checks if the property belongs to the object (or one of its ancestors)
             *      {
             *          if (dependencyObject.INTERNAL_PropertyStorageDictionary == null)
             *              dependencyObject.INTERNAL_PropertyStorageDictionary = new Dictionary<DependencyProperty,INTERNAL_PropertyStorage>();
             *          dependencyObject.INTERNAL_PropertyStorageDictionary.Add(dependencyProperty, storage);
             *      }
             *      return storage;
             *  }
             *  else
             *  {
             *      //--------------------------------------------
             *      // The property storage is in neither INTERNAL_PropertyStorageDictionary nor INTERNAL_AllInheritedProperties, therefore, we create it in INTERNAL_AllInheritedProperties, and, if the property belongs to the object (or one of its ancestors), we copy it to INTERNAL_PropertyStorageDictionary and return it:
             *      //--------------------------------------------
             *      var storage = new INTERNAL_PropertyStorage(dependencyObject, dependencyProperty);
             *      if (createAndSaveNewStorageIfNotExists)
             *      {
             *          if (dependencyObject.INTERNAL_AllInheritedProperties == null)
             *                  dependencyObject.INTERNAL_AllInheritedProperties = new Dictionary<DependencyProperty,INTERNAL_PropertyStorage>();
             *          dependencyObject.INTERNAL_AllInheritedProperties.Add(dependencyProperty, storage);
             *
             *          if (dependencyProperty.OwnerType.IsAssignableFrom(dependencyObject.GetType())) // This checks if the property belongs to the object (or one of its ancestors)
             *          {
             *              if (dependencyObject.INTERNAL_PropertyStorageDictionary == null)
             *                  dependencyObject.INTERNAL_PropertyStorageDictionary = new Dictionary<DependencyProperty,INTERNAL_PropertyStorage>();
             *              dependencyObject.INTERNAL_PropertyStorageDictionary.Add(dependencyProperty, storage);
             *          }
             *      }
             *      return storage;
             *  }
             * }
             */
            #endregion
        }
        internal void EvaluateAnimatedValue(
            PropertyMetadata    metadata,
            ref EffectiveValueEntry entry)
        {
            DependencyObject d = (DependencyObject)_dependencyObject.Target;

            if (d == null)
            {
                return;
            }

            object value = entry.GetFlattenedEntry(RequestFlags.FullyResolved).Value;
            if (entry.IsDeferredReference)
            {
                DeferredReference dr = (DeferredReference)value;
                value = dr.GetValue(entry.BaseValueSourceInternal);

                // Set the baseValue back into the entry
                entry.SetAnimationBaseValue(value);
            }

            object animatedValue = GetCurrentPropertyValue(this, d, _dependencyProperty, metadata, value);

            if (!_dependencyProperty.IsValidValueInternal(animatedValue))
            {
                // If the animation(s) applied to the property have calculated an
                // invalid value for the property then raise an exception.
                throw new InvalidOperationException(
                    SR.Get(
                        SRID.Animation_CalculatedValueIsInvalidForProperty,
                        _dependencyProperty.Name,
                        null));
            }
            
            entry.SetAnimatedValue(animatedValue, value);
        }
Exemplo n.º 42
0
        private static void SetDecomposedProperty(IReadOnlyDictionary <string, object> source, object target, string decompositionPrefix, PropertyMetadata property)
        {
            object child = null;

            if (property.CanRead)
            {
                child = property.InvokeGet(target);
            }

            if (child == null && property.CanWrite && property.PropertyType.GetConstructor(new Type[0]) != null)
            {
                child = Activator.CreateInstance(property.PropertyType);
                property.InvokeSet(target, child);
            }

            if (child != null)
            {
                PopulateComplexObject(source, child, decompositionPrefix + property.DecompositionPrefix);
            }
        }
 protected string GetClientProperty(PropertyMetadata propMetadata, Data.StoredClient client)
 {
     string val;
     if (propMetadata.TryGet(client, out val))
     {
         return val;
     }
     throw new Exception("Invalid property type " + propMetadata.Type);
 }
Exemplo n.º 44
0
        private static object SetProperty <T>(T target, PropertyMetadata property, object value, OrdinalMappedProperty <T> mapper)
        {
            var targetType = property.PropertyType;

            if (value != null && targetType != value.GetType())
            {
                var targetTypeInfo = targetType.GetTypeInfo();
                //var isNullable = !targetTypeInfo.IsValueType;

                //For Nullable<T>, we only care about the type parameter
                if (targetType.Name == "Nullable`1" && targetTypeInfo.IsGenericType)
                {
                    //isNullable = true;
                    targetType     = targetType.GenericTypeArguments[0];
                    targetTypeInfo = targetType.GetTypeInfo();
                }

                //some database return strings when we want strong types
                if (value is string)
                {
                    if (targetType == typeof(XElement))
                    {
                        value = XElement.Parse((string)value);
                    }
                    else if (targetType == typeof(XDocument))
                    {
                        value = XDocument.Parse((string)value);
                    }
                    else if (targetTypeInfo.IsEnum)
                    {
                        value = Enum.Parse(targetType, (string)value);
                    }

                    else if (targetType == typeof(bool))
                    {
                        value = bool.Parse((string)value);
                    }
                    else if (targetType == typeof(short))
                    {
                        value = short.Parse((string)value);
                    }
                    else if (targetType == typeof(int))
                    {
                        value = int.Parse((string)value);
                    }
                    else if (targetType == typeof(long))
                    {
                        value = long.Parse((string)value);
                    }
                    else if (targetType == typeof(float))
                    {
                        value = float.Parse((string)value);
                    }
                    else if (targetType == typeof(double))
                    {
                        value = double.Parse((string)value);
                    }
                    else if (targetType == typeof(decimal))
                    {
                        value = decimal.Parse((string)value);
                    }

                    else if (targetType == typeof(DateTime))
                    {
                        value = DateTime.Parse((string)value);
                    }
                    else if (targetType == typeof(DateTimeOffset))
                    {
                        value = DateTimeOffset.Parse((string)value);
                    }
                }
                else
                {
                    if (targetTypeInfo.IsEnum)
                    {
                        value = Enum.ToObject(targetType, value);
                    }
                }

                //this will handle numeric conversions
                if (value != null && targetType != value.GetType())
                {
                    try
                    {
                        value = Convert.ChangeType(value, targetType);
                    }
                    catch (Exception ex)
                    {
                        throw new MappingException($"Cannot map value of type {value.GetType().FullName} to property {property.Name} of type {targetType.Name}.", ex);
                    }
                }
            }

            if (mapper == null || value == null)
            {
                property.InvokeSet(target, value);
            }
            else
            {
                mapper.InvokeSet(target, value);
            }

            return(value);
        }
Exemplo n.º 45
0
 /// <summary>
 /// 构造方法。
 /// </summary>
 /// <param name="screen">屏幕枚举</param>
 /// <param name="metadata">视图模型的属性元数据信息</param>
 public CustomControl(Screen screen, PropertyMetadata metadata) : base(screen, metadata)
 {
     this.Class = string.Empty;
 }
Exemplo n.º 46
0
 public MappedProperty(string mappedColumnName, PropertyMetadata propertyMetadata)
 {
     MappedColumnName = mappedColumnName;
     PropertyMetadata = propertyMetadata;
 }
        private string GetRoleProperty(PropertyMetadata property, InMemoryRole role)
        {
            string value;
            if (property.TryGet(role, out value))
            {
                return value;
            }

            throw new Exception("Invalid property type " + property.Type);
        }
Exemplo n.º 48
0
 public virtual void InvokeSet(TTarget target, object value)
 {
     PropertyMetadata.InvokeSet(target, value);
 }
Exemplo n.º 49
0
        internal override void Stop(FrameworkElement frameworkElement, string groupName, bool revertToFormerValue = false)
        {
            base.Stop(frameworkElement, groupName, revertToFormerValue);


            DependencyObject target;
            PropertyPath     propertyPath;

            GetTargetElementAndPropertyInfo(frameworkElement, out target, out propertyPath);
            Type         lastElementType = target.GetType();
            PropertyInfo propertyInfo    = lastElementType.GetProperty(propertyPath.INTERNAL_DependencyPropertyName);


            //todo: find out why we put the test on target and put it back? (I removed it because id kept ScaleTransform from working properly)
            if (To != null)// && target is FrameworkElement) //todo: "To" can never be "null", fix this.
            {
                Type      dependencyPropertyContainerType = propertyInfo.DeclaringType;
                FieldInfo dependencyPropertyField         = dependencyPropertyContainerType.GetField(propertyPath.INTERNAL_DependencyPropertyName + "Property");
                // - Get the DependencyProperty
#if MIGRATION
                DependencyProperty dp = (global::System.Windows.DependencyProperty)dependencyPropertyField.GetValue(null);
#else
                DependencyProperty dp = (global::Windows.UI.Xaml.DependencyProperty)dependencyPropertyField.GetValue(null);
#endif
                // - Get the propertyMetadata from the property
                PropertyMetadata propertyMetadata = dp.GetTypeMetaData(target.GetType());
                // - Get the cssPropertyName from the PropertyMetadata

                //we make a specific name for this animation:
                string specificGroupName = groupName + animationInstanceSpecificName.ToString();

                if (propertyMetadata.GetCSSEquivalent != null)
                {
                    CSSEquivalent cssEquivalent = propertyMetadata.GetCSSEquivalent(target);
                    UIElement     uiElement     = cssEquivalent.UIElement ?? (target as UIElement); // If no UIElement is specified, we assume that the property is intended to be applied to the instance on which the PropertyChanged has occurred.

                    bool hasTemplate = (uiElement is Control) && ((Control)uiElement).HasTemplate;

                    if (!hasTemplate || cssEquivalent.ApplyAlsoWhenThereIsAControlTemplate)
                    {
                        if (cssEquivalent.DomElement == null && uiElement != null)
                        {
                            cssEquivalent.DomElement = uiElement.INTERNAL_OuterDomElement; // Default value
                        }
                        if (cssEquivalent.DomElement != null)
                        {
                            CSHTML5.Interop.ExecuteJavaScriptAsync(@"
Velocity($0, ""stop"", $1);", cssEquivalent.DomElement, specificGroupName);
                        }
                    }
                }
                if (propertyMetadata.GetCSSEquivalents != null)
                {
                    List <CSSEquivalent> cssEquivalents = propertyMetadata.GetCSSEquivalents(target);
                    foreach (CSSEquivalent equivalent in cssEquivalents)
                    {
                        if (equivalent.DomElement != null)
                        {
                            CSHTML5.Interop.ExecuteJavaScriptAsync(@"
Velocity($0, ""stop"", $1);", equivalent.DomElement, specificGroupName);
                        }
                    }
                }
            }
            else
            {
                propertyPath.INTERNAL_PropertySetVisualState(target, To); //To = null here --> Is it really what we want to do?
            }

            if (revertToFormerValue) //todo: check if this is sufficient or if we need to put stuff into the GetCSSEquivalents thing like for ColorAnimation:
            {
                object formerValue = propertyInfo.GetValue(target);
                propertyInfo.SetValue(target, formerValue);
            }
        }
Exemplo n.º 50
0
 /// <summary>
 /// Registers a new dependency property.
 /// </summary>
 /// <param name="name">The dependency property's name.</param>
 /// <param name="uvssName">The dependency property's name within the UVSS styling system.</param>
 /// <param name="propertyType">The dependency property's value type.</param>
 /// <param name="ownerType">The dependency property's owner type.</param>
 /// <param name="metadata">The dependency property's metadata.</param>
 /// <returns>A <see cref="DependencyProperty"/> instance which represents the registered dependency property.</returns>
 public static DependencyProperty Register(String name, String uvssName, Type propertyType, Type ownerType, PropertyMetadata metadata = null)
 {
     return DependencyPropertySystem.Register(name, uvssName, propertyType, ownerType, metadata);
 }
 public void OverrideMetadata(Type forType, PropertyMetadata typeMetadata)
 {
     dependencyProperty.OverrideMetadata (forType, typeMetadata, this);
 }
Exemplo n.º 52
0
        protected virtual void GenerateFilterForCondition(DbCommand cmd, ConditionLite condition, StringBuilder sb, ref int paramIndex, ref bool firstCondition, int indentation)
        {
            if (condition == null)
            {
                throw new ArgumentNullException(nameof(condition));
            }
            if (cmd == null)
            {
                throw new ArgumentNullException(nameof(cmd));
            }
            if (sb == null)
            {
                throw new ArgumentNullException(nameof(sb));
            }
            string parameterName = null;

            if (condition.Filter != null && condition.Filter.IsEmpty())
            {
                return;
            }
            if (firstCondition)
            {
                ;
            }
            else if (condition.LogicalOperator == LogicalOperatorLite.And)
            {
                sb.NewIndentedLine(indentation).Append("AND ");
            }
            else if (condition.LogicalOperator == LogicalOperatorLite.Or)
            {
                sb.NewIndentedLine(indentation).Append("OR ");
            }
            else
            {
                throw new NotImplementedException("Logical operator " + condition.LogicalOperator.ToString() + " not implemented");
            }
            firstCondition = false;

            if (condition.Filter != null)
            {
                sb.Append(GetFilter(cmd, ref paramIndex, condition.Filter, indentation, true));
                return;
            }

            IEnumerable   values       = condition.FieldValue as IEnumerable;
            IQueryBuilder queryBuilder = condition.SubQuery == null ? null : condition.SubQuery.QueryBuilder;

            if (condition.Operator == OperatorLite.In || condition.Operator == OperatorLite.NotIn)
            {
                if (values == null && queryBuilder == null)
                {
                    throw new ArgumentException("The value for In and NotIn operators must be enumerable or a subquery", nameof(condition));
                }
                if (values != null)
                {
                    bool hasAnyValue = values.AreThereMoreThan(0);
                    if (!hasAnyValue)
                    {
                        if (condition.Operator == OperatorLite.In)
                        {
                            sb.Append(" 1=0");
                        }
                        else
                        {
                            sb.Append(" 1=1");
                        }
                        return;
                    }
                }
            }
            PropertyMetadata propertyMetadata = null;
            string           fieldName        = condition.FieldName;
            string           quotedColumnName = null;

            if (fieldName == null && condition.Operator != OperatorLite.Exists && condition.Operator != OperatorLite.NotExists)
            {
                throw new InvalidOperationException("Field Name must be not null for condition");
            }
            if (fieldName != null)
            {
                propertyMetadata = GetPropertyMetadata(this.QueryLite.EntityType, fieldName);
                quotedColumnName = this.QueryLite.DataService.EntityLiteProvider.StartQuote + propertyMetadata.SqlField.ColumnName + this.QueryLite.DataService.EntityLiteProvider.EndQuote;
                if (condition.Operator != OperatorLite.In && condition.Operator != OperatorLite.NotIn)
                {
                    sb.Append(quotedColumnName);
                }
            }

            if (condition.Operator == OperatorLite.IsNull)
            {
                sb.Append(" IS NULL");
                return;
            }
            if (condition.Operator == OperatorLite.IsNotNull)
            {
                sb.Append(" IS NOT NULL");
                return;
            }

            if (condition.Operator == OperatorLite.In || condition.Operator == OperatorLite.NotIn)
            {
                AddListCondition(cmd, condition, sb, ref paramIndex, ref indentation, values, queryBuilder, propertyMetadata, quotedColumnName);
                return;
            }
            else if (condition.Operator == OperatorLite.Exists || condition.Operator == OperatorLite.NotExists)
            {
                if (condition.Operator == OperatorLite.Exists)
                {
                    sb.Append("EXISTS (\n");
                }
                else
                {
                    sb.Append("NOT EXISTS (\n");
                }
                sb.Append(queryBuilder.GetSelectQuery(cmd, ref paramIndex, ++indentation));
                sb.NewIndentedLine(--indentation).Append(')');
                return;
            }

            var fieldReference = condition.FieldValue as FieldReference;

            if (fieldReference == null)
            {
                var parameter = CreateParameter(propertyMetadata, condition.FieldValue, ref paramIndex, out parameterName);
                cmd.Parameters.Add(parameter);
            }
            else
            {
                var              fieldReferenceEntityType       = fieldReference.Alias?.EntityType ?? this.QueryLite.EntityType;
                string           fieldReferenceName             = fieldReference.FieldName;
                PropertyMetadata fieldReferencePropertyMetadata = GetPropertyMetadata(fieldReferenceEntityType, fieldReferenceName);
                var              aliasName = fieldReference.Alias?.Name ?? this.QueryLite.Alias?.Name;
                if (!string.IsNullOrEmpty(aliasName))
                {
                    parameterName = aliasName + ".";
                }
                else
                {
                    parameterName = string.Empty;
                }
                parameterName += this.QueryLite.DataService.EntityLiteProvider.StartQuote + fieldReferencePropertyMetadata.SqlField.ColumnName + this.QueryLite.DataService.EntityLiteProvider.EndQuote;
            }


            switch (condition.Operator)
            {
            case OperatorLite.Contains:
                sb.Append(" LIKE " + QueryLite.DataService.EntityLiteProvider.Concat("'%'", parameterName, "'%'"));
                break;

            case OperatorLite.FbContaining:
                sb.Append(" CONTAINING ").Append(parameterName);
                break;

            case OperatorLite.FbNotContaining:
                sb.Append(" NOT CONTAINING ").Append(parameterName);
                break;

            case OperatorLite.Equals:
                sb.Append(" = ").Append(parameterName);
                break;

            case OperatorLite.Greater:
                sb.Append(" > ").Append(parameterName);
                break;

            case OperatorLite.GreaterOrEquals:
                sb.Append(" >= ").Append(parameterName);
                break;

            case OperatorLite.Less:
                sb.Append(" < ").Append(parameterName);
                break;

            case OperatorLite.LessOrEquals:
                sb.Append(" <= ").Append(parameterName);
                break;

            case OperatorLite.NotContains:
                sb.Append(" NOT LIKE " + QueryLite.DataService.EntityLiteProvider.Concat("'%'", parameterName, "'%'"));
                break;

            case OperatorLite.NotEquals:
                sb.Append(" <> ").Append(parameterName);
                break;

            case OperatorLite.NotStartsWith:
                sb.Append(" NOT LIKE " + QueryLite.DataService.EntityLiteProvider.Concat(parameterName, "'%'"));
                break;

            case OperatorLite.StartsWith:
                sb.Append(" LIKE " + QueryLite.DataService.EntityLiteProvider.Concat(parameterName, "'%'"));
                break;

            case OperatorLite.IsDescendantOf:
                sb.Append(".IsDescendantOf(" + parameterName + ") = 1");
                break;

            case OperatorLite.IsChildOf:
                sb.Append(".GetAncestor(1) = " + parameterName);
                break;

            case OperatorLite.IsGrandChildOf:
                sb.Append(".GetAncestor(2) = " + parameterName);
                break;

            case OperatorLite.HierarchyLevelEquals:
                sb.Append(".GetLevel() = " + parameterName);
                break;

            case OperatorLite.STEquals:
                sb.Append(".STEquals(" + parameterName + ") = 1");
                break;

            case OperatorLite.STIntersects:
                sb.Append(".STIntersects(" + parameterName + ") = 1");
                break;

            case OperatorLite.STDistanceLess:
            case OperatorLite.STDistanceLessOrEquals:
                string pname = QueryLite.DataService.EntityLiteProvider.ParameterPrefix + "P" + paramIndex.ToString(CultureInfo.InvariantCulture);
                cmd.Parameters.AddWithValue(pname, condition.Parameter);
                paramIndex++;
                sb.Append(".STDistance(" + parameterName + ") " + (condition.Operator == OperatorLite.STDistanceLess ? "< " : "<= ") + pname);
                break;

            default:
                throw new NotImplementedException("operator " + condition.Operator.ToString() + " not implemented yet");
            }
        }
Exemplo n.º 53
0
        internal sealed override void EvaluateAnimatedValueCore(
                DependencyProperty  dp,
                PropertyMetadata    metadata,
            ref EffectiveValueEntry entry)
        {
            if (IAnimatable_HasAnimatedProperties)
            {
                AnimationStorage storage = AnimationStorage.GetStorage(this, dp);

                if (storage != null)
                {
                    storage.EvaluateAnimatedValue(metadata, ref entry);                      
                }
            }
        }
Exemplo n.º 54
0
 bool IsPropertyGuid(PropertyMetadata property)
 {
     return(String.Equals("System.Guid", property.TypeName, StringComparison.OrdinalIgnoreCase));
 }
Exemplo n.º 55
0
        /// <summary>
        /// Adds a new owning type to this dependency property.
        /// </summary>
        /// <param name="ownerType">The owner type to add to this dependency property.</param>
        /// <param name="typeMetadata">The property metadata for this owning type, which will override the default metadata.</param>
        /// <returns>A reference to this dependency property instance.</returns>
        public DependencyProperty AddOwner(Type ownerType, PropertyMetadata typeMetadata)
        {
            Contract.Require(ownerType, "ownerType");

            DependencyPropertySystem.AddOwner(this, ownerType);

            OverrideMetadata(ownerType, typeMetadata);

            return this;
        }
Exemplo n.º 56
0
        protected IDbDataParameter CreateParameter(PropertyMetadata propertyMetadata, object paramValue, ref int paramIndex, out string parameterName)
        {
            if (propertyMetadata == null)
            {
                throw new ArgumentNullException(nameof(propertyMetadata));
            }
            parameterName = QueryLite.DataService.EntityLiteProvider.ParameterPrefix + "P" + paramIndex.ToString(CultureInfo.InvariantCulture);
            IDbDataParameter parameter = QueryLite.DataService.DbProviderFactory.CreateParameter();

            parameter.ParameterName = parameterName;
            parameter.Size          = propertyMetadata.SqlField.Size;

            Type propertyType = propertyMetadata.PropertyInfo.PropertyType.UndelyingType();
            var  sqlParam     = parameter as SqlParameter;

            if (propertyType.FullName.StartsWith("Microsoft.SqlServer.Types.Sql", StringComparison.Ordinal))
            {
                if (sqlParam != null)
                {
                    sqlParam.SqlDbType = SqlDbType.Udt;
                    //TODO: En .NET Core no va a funcionar porque no existe la propiedad "UdtTypeName" y dará un error en tiempo de ejecución.
#pragma warning disable CA1308 // Normalize strings to uppercase
                    udtTypeNameSetter?.Invoke(sqlParam, propertyType.Name.ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
                }
                else
                {
                    parameter.DbType = DbType.String;
                    if (propertyType.Name.StartsWith("SqlHierarchyId", StringComparison.Ordinal))
                    {
                        parameter.Size = 4000;
                    }
                    else
                    {
                        parameter.Size = 1073741823;
                    }
                }
            }
            else
            {
                if (propertyMetadata.SqlField.ProviderType != int.MaxValue)
                {
                    this.QueryLite.DataService.EntityLiteProvider.SetProviderTypeToParameter(parameter, propertyMetadata.SqlField.ProviderType);
                }
                else if (propertyMetadata.SqlField.DbType == DbType.AnsiStringFixedLength)
                {
                    parameter.DbType = DbType.AnsiString;
                }
                else if (propertyMetadata.SqlField.DbType == DbType.StringFixedLength)
                {
                    parameter.DbType = DbType.String;
                }
                else if (propertyMetadata.SqlField.DbType == DbType.Time && sqlParam != null)
                {
                    sqlParam.SqlDbType = SqlDbType.Time;
                }
                else
                {
                    parameter.DbType = propertyMetadata.SqlField.DbType;
                }
                parameter.SourceColumn = propertyMetadata.PropertyInfo.Name;
                if (propertyMetadata.SqlField.Precision != 255 && propertyMetadata.SqlField.Precision != 0)
                {
                    parameter.Precision = propertyMetadata.SqlField.Precision;
                }
                if (propertyMetadata.SqlField.Scale != 255)
                {
                    parameter.Scale = propertyMetadata.SqlField.Scale;
                }
            }

            if (paramValue != null && (parameter.DbType == DbType.String || parameter.DbType == DbType.AnsiString) && !(paramValue is string))
            {
                var convertible = paramValue as IConvertible;
                if (convertible != null)
                {
                    paramValue = convertible.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    paramValue = paramValue.ToString();
                }
            }
            INullable sqlNullable = paramValue as INullable;
            parameter.Value = (paramValue == null || (sqlNullable != null && sqlNullable.IsNull)) ? DBNull.Value : paramValue;
            paramIndex++;
            return(parameter);
        }
Exemplo n.º 57
0
// A foreign key, e.g. CategoryID, will have an association name of Category
        string GetAssociationName(PropertyMetadata property)
        {
            RelatedModelMetadata propertyModel = GetRelatedModelMetadata(property);

            return(propertyModel != null ? propertyModel.AssociationPropertyName : property.PropertyName);
        }
Exemplo n.º 58
0
 private void AddListCondition(DbCommand cmd, ConditionLite condition, StringBuilder sb, ref int paramIndex, ref int indentation, IEnumerable values, IQueryBuilder queryBuilder, PropertyMetadata propertyMetadata, string quotedColumnName)
 {
     if (values != null)
     {
         bool firstValue         = true;
         var  isNumericField     = propertyMetadata.PropertyInfo.PropertyType.IsNumericType();
         var  undelyingFieldType = propertyMetadata.PropertyInfo.PropertyType.UndelyingType();
         var  isStringField      = propertyMetadata.PropertyInfo.PropertyType == typeof(string);
         if ((isNumericField || isStringField) && values.AreThereMoreThan(8))
         {
             bool firstChunk = true;
             int  valueCount = 0;
             sb.Append('(');
             foreach (object v in values)
             {
                 object value = v;
                 if (valueCount % 1000 == 0)
                 {
                     firstValue = true;
                     if (firstChunk)
                     {
                         firstChunk = false;
                     }
                     else
                     {
                         sb.Append(") ").Append(condition.Operator == OperatorLite.In ? " OR " : " AND ");
                     }
                     sb.Append(quotedColumnName).Append(condition.Operator == OperatorLite.In ? " IN (" : " NOT IN (");
                 }
                 string valueStr = null;
                 if (value == null)
                 {
                     valueStr = "NULL";
                 }
                 else
                 {
                     if (isNumericField && !value.IsNumeric())
                     {
                         try
                         {
                             value = Convert.ChangeType(value, undelyingFieldType, CultureInfo.InvariantCulture);
                         }
                         catch (Exception ex)
                         {
                             throw new ArgumentException($"A non numeric value has been found for {condition.Operator} operator and field {propertyMetadata.PropertyInfo.Name}", ex);
                         }
                     }
                     valueStr = Convert.ToString(value, CultureInfo.InvariantCulture);
                     if (isStringField)
                     {
                         valueStr = "'" + valueStr.Replace("'", "''") + "'";
                     }
                 }
                 if (firstValue)
                 {
                     firstValue = false;
                 }
                 else
                 {
                     sb.Append(", ");
                 }
                 sb.Append(valueStr);
                 valueCount++;
             }
             sb.Append("))");
         }
         else
         {
             sb.Append(quotedColumnName).Append(condition.Operator == OperatorLite.In ? " IN (": " NOT IN (");
             string parameterName;
             foreach (object value in values)
             {
                 var param = CreateParameter(propertyMetadata, value, ref paramIndex, out parameterName);
                 cmd.Parameters.Add(param);
                 if (firstValue)
                 {
                     firstValue = false;
                 }
                 else
                 {
                     sb.Append(", ");
                 }
                 sb.Append(parameterName);
             }
             sb.Append(')');
         }
     }
     else
     {
         sb.Append(quotedColumnName).Append(condition.Operator == OperatorLite.In ? " IN (" : " NOT IN (");
         sb.Append('\n').Append(queryBuilder.GetSelectQuery(cmd, ref paramIndex, ++indentation));
         sb.NewIndentedLine(--indentation);
         sb.Append(')');
     }
 }
Exemplo n.º 59
0
 /// <summary>
 /// Registers a new read-only dependency property.
 /// </summary>
 /// <param name="name">The dependency property's name.</param>
 /// <param name="propertyType">The dependency property's value type.</param>
 /// <param name="ownerType">The dependency property's owner type.</param>
 /// <param name="metadata">The dependency property's metadata.</param>
 /// <returns>A <see cref="DependencyPropertyKey"/> instance which provides access to the read-only dependency property.</returns>
 public static DependencyPropertyKey RegisterReadOnly(String name, Type propertyType, Type ownerType, PropertyMetadata metadata = null)
 {
     return DependencyPropertySystem.RegisterReadOnly(name, null, propertyType, ownerType, metadata);
 }
Exemplo n.º 60
0
// A foreign key, e.g. CategoryID, will have a value expression of Category.CategoryID
        string GetValueExpression(PropertyMetadata property)
        {
            RelatedModelMetadata propertyModel = GetRelatedModelMetadata(property);

            return(propertyModel != null ? propertyModel.AssociationPropertyName + "." + propertyModel.DisplayPropertyName : property.PropertyName);
        }