Example #1
0
        private static bool HasValueGeneratedFlag(this PropertyEntry property, ValueGenerated valueGenerated)
        {
            if (property.Metadata.ValueGenerated.HasFlag(valueGenerated))
            {
                return(true);
            }

            if (property.Metadata.IsPrimaryKey( ))
            {
                var principal = property.Metadata.FindFirstPrincipal( );
                if (principal != null && principal.ValueGenerated.HasFlag(valueGenerated))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #2
0
        /// <summary>
        /// Gets the entities changes for this entry.
        /// </summary>
        /// <param name="context">The audit db context.</param>
        /// <param name="entry">The entry.</param>
        private List <EventEntryChange> GetChanges(IAuditDbContext context, EntityEntry entry)
        {
            var result = new List <EventEntryChange>();
            var props  = entry.Metadata.GetProperties();

            foreach (var prop in props)
            {
                PropertyEntry propEntry = entry.Property(prop.Name);
                if (propEntry.IsModified)
                {
                    if (IncludeProperty(context, entry, prop.Name))
                    {
                        result.Add(new EventEntryChange()
                        {
                            ColumnName    = GetColumnName(prop),
                            NewValue      = HasPropertyValue(context, entry, prop.Name, propEntry.CurrentValue, out object currValue) ? currValue : propEntry.CurrentValue,
                            OriginalValue = HasPropertyValue(context, entry, prop.Name, propEntry.OriginalValue, out object origValue) ? origValue : propEntry.OriginalValue
                        });
Example #3
0
        public BindingExpression(BindingExpressionKey key, BindingBase binding, PropertyEntry<object> propertyEntry)
        {
            this.propertyEntry = propertyEntry;
            Binding = binding;
            this.Key = key;
            if(IsTwoWayBinding && string.IsNullOrEmpty(((Binding)this.Binding).Path))
                Guard.InvalidOperation(SR.TwoWayBindingRequiresPathExceptionMessage);
            WpfBindingMode mode = IsTwoWayBinding ? WpfBindingMode.TwoWay : WpfBindingMode.OneWay;
            WpfBinding wpfBinding = new WpfBinding("PropertyValue." + ((Binding)binding).Path) { Source = propertyEntry, Mode = mode};

            if(Property == null)
                Guard.ArgumentException("propertyName");
            MethodInfo createMethod = typeof(PropertyChangeListener<>).MakeGenericType(key.property.PropertyType).GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
            listener = (IPropertyChangeListener)createMethod.Invoke(null, new object[] { wpfBinding, new Action<object>(UpdateTargetProperty), Property.GetValue(Control) });

            if(IsTwoWayBinding)
                Property.AddValueChanged(Control, OnTargerPropertyChanged);
        }
Example #4
0
 private void RefreshConsumedProperties(ObservableCollection <PropertyEntry> unconsumedProperties, ObservableCollection <PropertyEntry> allProperties, ObservableCollection <CategoryEditor> categoryEditors)
 {
     if (allProperties == null || unconsumedProperties == null || unconsumedProperties.Count == allProperties.Count)
     {
         return;
     }
     using (IEnumerator <PropertyEntry> enumerator = allProperties.GetEnumerator())
     {
         while (((IEnumerator)enumerator).MoveNext())
         {
             PropertyEntry current = enumerator.Current;
             if (!unconsumedProperties.Contains(current))
             {
                 this.AddProperty(current, unconsumedProperties, allProperties, categoryEditors);
             }
         }
     }
 }
        #pragma warning disable EF1001 // Internal EF Core API usage.
        private static bool MayGetTemporaryValue(PropertyEntry propertyEntry)
        {
            var valueGeneration = propertyEntry.EntityEntry.Context.GetDependencies( ).StateManager.ValueGenerationManager;

            if (valueGeneration.MayGetTemporaryValue(propertyEntry.Metadata, propertyEntry.Metadata.DeclaringEntityType))
            {
                return(true);
            }

            var principal = propertyEntry.Metadata.FindFirstPrincipal( );

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

            return(valueGeneration.MayGetTemporaryValue(principal, principal.DeclaringEntityType));
        }
Example #6
0
        // <summary>
        // Looks for the x:Name or Name property of the given PropertyValue and returns it if found.
        // Note: this method is expensive because it evaluates all the sub-properties of the given
        // PropertyValue.
        // </summary>
        // <param name="propertyValue">PropertyValue instance to look at</param>
        // <returns>Name if the PropertyValue defines one, null otherwise</returns>
        public static string GetPropertyName(PropertyValue propertyValue)
        {
            if (propertyValue == null)
            {
                return(null);
            }

            if (propertyValue.HasSubProperties)
            {
                PropertyEntry nameProperty = propertyValue.SubProperties["Name"];
                if (nameProperty != null)
                {
                    return(nameProperty.PropertyValue.StringValue);
                }
            }

            return(null);
        }
        /// <summary>
        /// Adds new value, if key exists value will be overwriten
        /// </summary>
        /// <param name="index">The property index</param>
        /// <param name="key">The key used to remove value later</param>
        /// <param name="value">The value added</param>
        public void Set(int index, object key, double value)
        {
            lock (m_LockObject)
            {
                PropertyEntry entry = (PropertyEntry)m_properties[index];
                if (entry == null)
                {
                    entry = new PropertyEntry();
                    m_properties[index] = entry;
                }

                if (entry.values == null)
                    entry.values = new HybridDictionary();

                entry.values[key] = value;
                entry.CalculateCachedValue();
            }
        }
Example #8
0
        /// <summary>
        ///     Reads an update that occures when a new edict enters the PVS (potentially visible system)
        /// </summary>
        /// <returns>The new Entity.</returns>
        private static Entity ReadEnterPVS(IBitStream reader, int id, DemoParser parser)
        {
            //What kind of entity?
            var serverClassID = (int)reader.ReadInt(parser.SendTableParser.ClassBits);

            //So find the correct server class
            var entityClass = parser.SendTableParser.ServerClasses[serverClassID];

            reader.ReadInt(10); //Entity serial.
            //Never used anywhere I guess. Every parser just skips this


            var newEntity = new Entity(id, entityClass);

            //give people the chance to subscribe to events for this
            newEntity.ServerClass.AnnounceNewEntity(newEntity);

            //And then parse the instancebaseline.
            //basically you could call
            //newEntity.ApplyUpdate(parser.instanceBaseline[entityClass];
            //This code below is just faster, since it only parses stuff once
            //which is faster.

            if (parser.PreprocessedBaselines.TryGetValue(serverClassID, out var fastBaseline))
            {
                PropertyEntry.Emit(newEntity, fastBaseline);
            }
            else
            {
                var preprocessedBaseline = new List <object>();
                if (parser.instanceBaseline.ContainsKey(serverClassID))
                {
                    using (var collector = new PropertyCollector(newEntity, preprocessedBaseline))
                        using (var bitStream = BitStreamUtil.BitStreamUtil.Create(parser.instanceBaseline[serverClassID]))
                        {
                            newEntity.ApplyUpdate(bitStream);
                        }
                }

                parser.PreprocessedBaselines.Add(serverClassID, preprocessedBaseline.ToArray());
            }

            return(newEntity);
        }
Example #9
0
 void UpdateCategoryEditorDataContext(PropertyEntry property, FrameworkElement editor, Container context)
 {
     try
     {
         editor.DataContext = null;
         ModelItem      modelItem          = null;
         ModelItem      propertyParentItem = null;
         EditingContext editingContext     = null;
         this.GetPropertyData(property, out modelItem, out propertyParentItem, out editingContext);
         context.Context             = editingContext;
         context.WorkflowViewElement = (null == modelItem ? null : modelItem.View);
         context.ModelItem           = modelItem;
         editor.DataContext          = context;
     }
     catch (Exception err)
     {
         Fx.Assert(false, err.Message);
     }
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            PropertyEntry propertyEntry = value as PropertyEntry;

            if (null == propertyEntry)
            {
                PropertyValue propertyValue = value as PropertyValue;
                if (null != propertyValue)
                {
                    propertyEntry = propertyValue.ParentProperty;
                }
            }

            ModelPropertyEntry modelPropertyEntry = propertyEntry as ModelPropertyEntry;

            ModelProperty modelProperty = null;

            if (modelPropertyEntry != null)
            {
                modelProperty = modelPropertyEntry.FirstModelProperty;
            }

            if (modelProperty == null)
            {
                return(Binding.DoNothing);
            }

            string optionName = parameter as string;

            if (optionName == null)
            {
                return(Binding.DoNothing);
            }

            object optionValue;

            if (EditorOptionAttribute.TryGetOptionValue(modelProperty.Attributes, optionName, out optionValue))
            {
                return(optionValue);
            }

            return(Binding.DoNothing);
        }
 protected override void SetValueCore(object value)
 {
     for (PropertyValue parentValue = this.ParentProperty.ParentValue; parentValue != null; parentValue = parentValue.ParentProperty.ParentValue)
     {
         PropertyEntry parentProperty = parentValue.ParentProperty;
         if (parentValue.Source != DependencyPropertyValueSource.LocalValue && parentValue.Source != DependencyPropertyValueSource.InheritedValue && parentValue.Source != DependencyPropertyValueSource.DefaultValue)
         {
             throw new InvalidOperationException(ExceptionStringTable.SettingSubpropertyOfExpression);
         }
     }
     if (value == null && this.property.ShouldClearValueWhenSettingNull)
     {
         this.property.ClearValue();
     }
     else
     {
         this.property.SetValue(value);
     }
 }
Example #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldListRemovedRelationshipProperties() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldListRemovedRelationshipProperties()
        {
            // Given
            int   propertyKeyId = _ops.propertyKeyTokenHolder().getOrCreateId("theKey");
            Value prevValue     = Values.of("prevValue");

            _state.relationshipDoRemoveProperty(1L, propertyKeyId);
            _ops.withRelationship(1, 0, 0, 0, genericMap("theKey", prevValue));

            // When
            IEnumerable <PropertyEntry <Relationship> > propertyEntries = Snapshot().removedRelationshipProperties();

            // Then
            PropertyEntry <Relationship> entry = single(propertyEntries);

            assertThat(entry.Key(), equalTo("theKey"));
            assertThat(entry.PreviouslyCommitedValue(), equalTo("prevValue"));
            assertThat(entry.Entity().Id, equalTo(1L));
        }
Example #13
0
        //
        // Adds the given property to the specified property bucket (use
        // ModelCategoryEntry.BasicProperties, ModelCategoryEntry.AdvancedProperties, or
        // ModelCategoryEntry.GetBucket()) sorted using the specified comparer.
        //
        private void Add(
            PropertyEntry property,
            ObservableCollection <PropertyEntry> bucket,
            IComparer <PropertyEntry> comparer,
            bool fireCollectionChangedEvent)
        {
            if (property == null)
            {
                throw FxTrace.Exception.ArgumentNull("property");
            }
            if (bucket == null)
            {
                throw FxTrace.Exception.ArgumentNull("bucket");
            }
            if (comparer == null)
            {
                throw FxTrace.Exception.ArgumentNull("comparer");
            }

            ObservableCollectionWorkaround <PropertyEntry> castBucket = bucket as ObservableCollectionWorkaround <PropertyEntry>;
            int insertionIndex = 0;

            if (castBucket == null)
            {
                Debug.Fail("Invalid property bucket.  The property sort order will be broken.");
            }
            else
            {
                insertionIndex = castBucket.BinarySearch(property, comparer);
                if (insertionIndex < 0)
                {
                    insertionIndex = ~insertionIndex;
                }
            }

            bucket.Insert(insertionIndex, property);

            if (fireCollectionChangedEvent)
            {
                FirePropertiesChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, property));
            }
        }
        /// <summary>
        /// Gets an entry from the stream represented by the PropertyEntry
        /// </summary>
        /// <param name="entry">A property entry</param>
        /// <param name="storage">The storage to read from</param>
        /// <returns>An object representing the variable-length property</returns>
        internal object GetVariableLengthProperty(PropertyEntry entry, string storage = null)
        {
            object   obj;
            CFStream stream;
            //Get the value of the property.
            string name = string.Format("__substg1.0_{0:X4}{1:X4}", entry.PropertyTag.ID, (short)entry.PropertyTag.Type);

            if (storage == null)
            {
                stream = _compoundFile.RootStorage.GetStream(name);
            }
            else
            {
                stream = _compoundFile.RootStorage.GetStorage(storage).GetStream(name);
            }
            switch (entry.PropertyTag.Type)
            {
            case PropertyType.PtypString:
                obj = Encoding.Unicode.GetString(stream.GetData());
                break;

            case PropertyType.PtypString8:
                obj = Encoding.Default.GetString(stream.GetData());
                break;

            case PropertyType.PtypBinary:
                obj = stream.GetData();     //binary data. Just return as-is. May be in the following format: https://msdn.microsoft.com/en-us/library/dd947045(v=office.12).aspx
                break;

            case PropertyType.PtypGuid:
                obj = new Guid(stream.GetData());
                break;

            case PropertyType.PtypObject:
            //See https://msdn.microsoft.com/en-us/library/ee200950(v=exchg.80).aspx
            //Drink lots!
            default:
                obj = null;
                break;
            }
            return(obj);
        }
Example #15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldListAddedNodePropertiesProperties() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldListAddedNodePropertiesProperties()
        {
            // Given
            int   propertyKeyId = _ops.propertyKeyTokenHolder().getOrCreateId("theKey");
            Value prevValue     = Values.of("prevValue");

            _state.nodeDoChangeProperty(1L, propertyKeyId, Values.of("newValue"));
            _ops.withNode(1, _noLabels, genericMap("theKey", prevValue));

            // When
            IEnumerable <PropertyEntry <Node> > propertyEntries = Snapshot().assignedNodeProperties();

            // Then
            PropertyEntry <Node> entry = single(propertyEntries);

            assertThat(entry.Key(), equalTo("theKey"));
            assertThat(entry.Value(), equalTo("newValue"));
            assertThat(entry.PreviouslyCommitedValue(), equalTo("prevValue"));
            assertThat(entry.Entity().Id, equalTo(1L));
        }
Example #16
0
        /// <summary>
        /// Gets the entities changes for this entry.
        /// </summary>
        /// <param name="entry">The entry.</param>
        private List <EventEntryChange> GetChanges(EntityEntry entry)
        {
            var result = new List <EventEntryChange>();
            var props  = Model.FindEntityType(entry.Entity.GetType()).GetProperties();

            foreach (var prop in props)
            {
                PropertyEntry propEntry = entry.Property(prop.Name);
                if (propEntry.IsModified)
                {
                    result.Add(new EventEntryChange()
                    {
                        ColumnName    = GetColumnName(prop),
                        NewValue      = propEntry.CurrentValue,
                        OriginalValue = propEntry.OriginalValue
                    });
                }
            }
            return(result);
        }
        /// <summary>
        /// Adds new value, if key exists value will be overwriten
        /// </summary>
        /// <param name="index">The property index</param>
        /// <param name="key">The key used to remove value later</param>
        /// <param name="value">The value added</param>
        public void Set(int index, object key, double value)
        {
            lock (_lockObject)
            {
                PropertyEntry entry = (PropertyEntry)_properties[index];
                if (entry == null)
                {
                    entry = new PropertyEntry();
                    _properties[index] = entry;
                }

                if (entry.Values == null)
                {
                    entry.Values = new HybridDictionary();
                }

                entry.Values[key] = value;
                entry.CalculateCachedValue();
            }
        }
        private void TrimFieldValue(PropertyEntry property)
        {
            var metaData     = property.Metadata;
            var currentValue = property.CurrentValue?.ToString();
            var maxLength    = metaData.GetMaxLength();

            if (!maxLength.HasValue || currentValue == null)
            {
                return;
            }
            else
            {
                property.CurrentValue = currentValue.Trim();
            }

            if (currentValue.Length > maxLength.Value)
            {
                property.CurrentValue = currentValue.Substring(0, maxLength.Value);
            }
        }
Example #19
0
        private static PropertyEntry GetEditedProperty(object showDialogCommandSource, object commandParamater)
        {
            PropertyEntry propertyEntry = commandParamater as PropertyEntry;

            if (propertyEntry != null)
            {
                return(propertyEntry);
            }
            DependencyObject dependencyObject = showDialogCommandSource as DependencyObject;

            if (dependencyObject != null)
            {
                PropertyContainer propertyContainer = PropertyContainer.GetOwningPropertyContainer(dependencyObject);
                if (propertyContainer != null)
                {
                    return(propertyContainer.get_PropertyEntry());
                }
            }
            return((PropertyEntry)null);
        }
        /// <summary>
        /// Creates an instance using the specified DependencyObject <see cref="Type"/>
        /// </summary>
        /// <param name="ownerType">The owner type</param>
        public DependencyPropertyDetailsCollection(Type ownerType, DependencyProperty dataContextProperty, DependencyProperty templatedParentProperty)
        {
            _ownerType = ownerType;

            var propertiesForType = DependencyProperty.GetPropertiesForType(ownerType);

            var entries = new PropertyEntry[propertiesForType.Length];

            for (int i = 0; i < propertiesForType.Length; i++)
            {
                entries[i].Id = propertiesForType[i].UniqueId;
            }

            // Entries are pre-sorted by the DependencyProperty.GetPropertiesForType method
            AssignEntries(entries, sort: false);

            // Prefecth known properties for faster access
            DataContextPropertyDetails     = GetPropertyDetails(dataContextProperty);
            TemplatedParentPropertyDetails = GetPropertyDetails(templatedParentProperty);
        }
        /// <summary>
        /// Gets the entities changes for this entry.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="entry">The entry.</param>
        private List <EventEntryChange> GetChanges(DbContext dbContext, EntityEntry entry)
        {
            var result = new List <EventEntryChange>();
            var props  = entry.Metadata.GetProperties();

            foreach (var prop in props)
            {
                PropertyEntry propEntry = entry.Property(prop.Name);
                if (propEntry.IsModified)
                {
                    result.Add(new EventEntryChange()
                    {
                        ColumnName    = GetColumnName(prop),
                        NewValue      = propEntry.CurrentValue,
                        OriginalValue = propEntry.OriginalValue
                    });
                }
            }
            return(result);
        }
Example #22
0
        // <summary>
        // Looks for the PropertyEntry and its parent CategoryEntry for the specified property
        // </summary>
        // <param name="propertyName">Property to look for</param>
        // <param name="parentCategory">Parent CategoryEntry of the given property</param>
        // <returns>Corresponding PropertyEntry if found, null otherwise.</returns>
        internal PropertyEntry FindPropertyEntry(string propertyName, out ModelCategoryEntry parentCategory)
        {
            parentCategory = null;
            if (propertyName == null)
            {
                return(null);
            }

            foreach (ModelCategoryEntry category in this.Items)
            {
                PropertyEntry property = category[propertyName];
                if (property != null)
                {
                    parentCategory = category;
                    return(property);
                }
            }

            return(null);
        }
Example #23
0
 private void RefreshPropertyCategorization()
 {
     for (int index = this.basicProperties.Count - 1; index >= 0; --index)
     {
         PropertyEntry propertyEntry = this.basicProperties[index];
         if (propertyEntry.get_IsAdvanced())
         {
             this.basicProperties.RemoveAt(index);
             this.advancedProperties.Add(propertyEntry);
         }
     }
     for (int index = this.advancedProperties.Count - 1; index >= 0; --index)
     {
         PropertyEntry propertyEntry = this.advancedProperties[index];
         if (!propertyEntry.get_IsAdvanced())
         {
             this.advancedProperties.RemoveAt(index);
             this.basicProperties.Add(propertyEntry);
         }
     }
 }
Example #24
0
        /// <summary>
        /// a few checks for modified entries, primairly for identity
        /// </summary>
        private static bool ModifiedChecks(PropertyEntry property)
        {
            if (!property.IsModified) // if property isn't modified, skip
            {
                return(false);
            }

            if (property.OriginalValue?.ToString() == property.CurrentValue?.ToString()) // if old and new are the same, skip (mainly for indentity)
            {
                return(false);
            }

            string[] skippedIdentityFields = { "concurrencystamp", "securitystamp" };

            if (skippedIdentityFields.Contains(property.Metadata.Name.ToLower())) // skipping concurrency stamp and security stamp in identity (will always be different)
            {
                return(false);
            }

            return(true);
        }
        public void Cannot_set_or_get_original_value_when_not_tracked_generic()
        {
            var entity = new FullyNotifyingWotty {
                Id = 1, ConcurrentPrimate = "Monkey"
            };

            var entry = InMemoryTestHelpers.Instance.CreateInternalEntry(
                BuildModel(),
                EntityState.Unchanged,
                entity);

            var propertyEntry = new PropertyEntry <FullyNotifyingWotty, string>(entry, "Primate");

            Assert.Equal(
                CoreStrings.OriginalValueNotTracked("Primate", "FullyNotifyingWotty"),
                Assert.Throws <InvalidOperationException>(() => propertyEntry.OriginalValue).Message);

            Assert.Equal(
                CoreStrings.OriginalValueNotTracked("Primate", "FullyNotifyingWotty"),
                Assert.Throws <InvalidOperationException>(() => propertyEntry.OriginalValue = "Chimp").Message);
        }
Example #26
0
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            if (element != null)
            {
                PropertyEntry property = ((PropertyContainer)element).PropertyEntry;

                if (property != null)
                {
                    // Make each PropertyContainer its own selection stop
                    PropertySelection.SetSelectionStop(element, new PropertySelectionStop(property));
                }

                PropertyContainer container = element as PropertyContainer;
                if (container != null)
                {
                    container.Loaded += new RoutedEventHandler(OnPropertyContainerLoaded);
                }
            }
        }
        public static void TryResetModificationState(this PropertyEntry property)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            if (!property.IsModified)
            {
                return;
            }

            var comparer    = property.Metadata.GetValueComparer( );
            var isUnchanged = comparer?.Equals(property.CurrentValue, property.OriginalValue) ??
                              Equals(property.CurrentValue, property.OriginalValue);

            if (isUnchanged)
            {
                property.IsModified = false;
            }
        }
Example #28
0
        public void Run()
        {
            Debugger.Break();

            // Die die eingebttete Ressource ein JSON-Dokument erzeugen
            // string techEventJson = constructTechEventJson();

            // Entität aus Json konstrieren
            TechEvent techEvent = getTechEventFromJson();

            // Verbessert seit EF Core 2.0
            // _efContext.Attach(techEvent);

            // oder

            // Entität durchlaufen rekursive
            _efContext.ChangeTracker.TrackGraph(techEvent, node =>
            {
                // node: EntityEntryGraphNode
                EntityEntry entry = node.Entry;
                Console.WriteLine(entry.Entity.GetType().ToString());

                PropertyEntry propertyEntry = entry.Property("Id");

                // Entscheiden, was neu und was modifiziert ist
                // Und was gelöscht?
                if ((int)propertyEntry.CurrentValue < 0)
                {
                    entry.State = EntityState.Added;
                    propertyEntry.IsTemporary = true;
                }
                else
                {
                    entry.State = EntityState.Modified;
                }
            });

            // Speichern
            _efContext.SaveChanges();
        }
        /// <summary>
        /// Builds the consolidated column dictionary scanning all <see cref="imbSCI.Core.collection.PropertyCollectionExtended"/> items.
        /// </summary>
        /// <remarks>
        /// <para>If <c>__allowedColumns</c> are not specified it will include any newly column found inside collection</para>
        /// </remarks>
        /// <param name="obligatoryColumns">The obligatory columns.</param>
        /// <param name="__allowedColumns">The allowed columns.</param>
        /// <returns>Set of columns ready to be used for DataTable creation and for similar tasks</returns>
        public static PropertyEntryDictionary buildConsolidatedColumnDictionary(this IEnumerable <PropertyCollectionExtended> items, PropertyEntryColumn obligatoryColumns, object[] __allowedColumns = null)
        {
            List <PropertyEntryColumn> columnList = obligatoryColumns.getEnumListFromFlags <PropertyEntryColumn>();

            List <object> allowedColumns = __allowedColumns.getFlatList <object>();

            PropertyEntryDictionary output = new PropertyEntryDictionary();

            foreach (PropertyCollectionExtended pair in items)
            {
                foreach (object key in pair.Keys)
                {
                    if (!output.ContainsKey(key))
                    {
                        bool allowed = !allowedColumns.Any();
                        if (allowedColumns.Contains(key))
                        {
                            allowed = true;
                        }
                        if (allowed)
                        {
                            output.Add(key, pair.entries[key]);
                        }
                    }
                }
            }

            foreach (PropertyEntryColumn c in columnList)
            {
                if (!output.ContainsKey(c))
                {
                    PropertyEntry pe = new PropertyEntry(c, "", c.toColumnCaption(false), c.getDescriptionForKey());
                    output.Add(c, pe);
                }
            }

            //pel.Sort((x, y) => x.priority.CompareTo(y.priority));

            return(output);
        }
Example #30
0
        // ###################################################
        // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - BEGIN
        // ###################################################

        // This method used to be non-virtual, private
        protected virtual void AddProperty(PropertyEntry property, ObservableCollection <PropertyEntry> unconsumedProperties, ObservableCollection <PropertyEntry> referenceOrder, ObservableCollection <CategoryEditor> categoryEditors)
        {
            // ###################################################
            // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - END
            // ###################################################

            bool consumed = false;

            foreach (CategoryEditor categoryEditor in categoryEditors)
            {
                if (categoryEditor.ConsumesProperty(property))
                {
                    consumed = true;
                }
            }
            if (!consumed)
            {
                // We need to insert this property in the correct location.  Reference order is sorted and contains all properties in the unconsumed properties collection.
                Fx.Assert(referenceOrder.Contains(property), "Reference order should contain the property to be added.");
#if DEBUG
                foreach (PropertyEntry unconsumedProperty in unconsumedProperties)
                {
                    Fx.Assert(referenceOrder.Contains(unconsumedProperty), "Reference order should contain all unconsumed properties.");
                }
#endif

                // We'll walk both collections, and advance the insertion index whenever we see an unconsumed property come ahead of the target in the reference order.
                int referenceIndex = 0;
                int insertionIndex = 0;
                while (referenceOrder[referenceIndex] != property && insertionIndex < unconsumedProperties.Count)
                {
                    if (unconsumedProperties[insertionIndex] == referenceOrder[referenceIndex])
                    {
                        insertionIndex++;
                    }
                    referenceIndex++;
                }
                unconsumedProperties.Insert(insertionIndex, property);
            }
        }
Example #31
0
        /// <summary>
        /// This will read an entry from the property stream
        /// </summary>
        /// <param name="entry">An array of bytes representing an entry</param>
        /// <returns>A parsed PropertyEntry structure</returns>
        private PropertyEntry ReadPropertyEntry(byte[] entry)
        {
            PropertyEntry propEntry;
            PropertyTag   tag = new PropertyTag();

            tag.Type = (PropertyType)BitConverter.ToInt16(entry, 0);
            tag.ID   = BitConverter.ToUInt16(entry, 2);
            if (TypeMapper.IsFixedLength(tag.Type))
            {
                propEntry = new PropertyEntry();
            }
            else
            {
                propEntry = new VariableLengthPropertyEntry();
            }

            propEntry.PropertyTag = tag;
            propEntry.Flags       = BitConverter.ToInt32(entry, 4);
            propEntry.Value       = entry.Skip(8).ToArray();

            return(propEntry);
        }
Example #32
0
        /// <summary>
        /// Asynchronously update a <typeparamref name="TValue"/> in a <see cref="DbContext"/> and return the result.
        /// </summary>
        /// <typeparam name="TValue">Type of the stored entity.</typeparam>
        /// <param name="context">context to save to.</param>
        /// <param name="value">object to save.</param>
        /// <param name="propertiesToUpdate">Name of each property that should be updated. If none are provided then ALL PROPERTIES WILL BE UPDATED.</param>
        /// <returns></returns>
        public static async Task <TValue> UpdateAsync <TValue>(this DbContext context, TValue value, params string[] propertiesToUpdate) where TValue : class
        {
            EntityEntry <TValue> updateEntity;

            if (propertiesToUpdate.Length == 0)
            {
                updateEntity = context.Update(value);
            }
            else
            {
                updateEntity       = context.Attach(value);
                updateEntity.State = EntityState.Modified;
                foreach (string propertyName in propertiesToUpdate)
                {
                    PropertyEntry property = updateEntity.Properties.Single(p => p.Metadata.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));
                    property.IsModified = true;
                }
            }
            await context.SaveChangesAsync();

            return(updateEntity.Entity);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="entry"></param>
 public void AddProperty(PropertyEntry entry)
 {
     properties[entry.Key] = entry.Value;
 }
Example #34
0
        /// <summary>
        ///     Private constructor.
        /// </summary>
        private PropertyConstraints()
        {
            _data = new Dictionary<String, List<PropertyEntry>>();
            try
            {
                Stream mask0 = ResourceLoader.CreateStream("Encog.Resources.analyst.csv");
                var csv = new ReadCSV(mask0, false, CSVFormat.EgFormat);

                while (csv.Next())
                {
                    String sectionStr = csv.Get(0);
                    String nameStr = csv.Get(1);
                    String typeStr = csv.Get(2);

                    // determine type
                    PropertyType t;
                    if ("boolean".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeBoolean;
                    }
                    else if ("real".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeDouble;
                    }
                    else if ("format".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeFormat;
                    }
                    else if ("int".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeInteger;
                    }
                    else if ("list-string".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeListString;
                    }
                    else if ("string".Equals(typeStr, StringComparison.InvariantCultureIgnoreCase))
                    {
                        t = PropertyType.TypeString;
                    }
                    else
                    {
                        throw new AnalystError("Unknown type constraint: "
                                               + typeStr);
                    }

                    var entry = new PropertyEntry(t, nameStr,
                                                  sectionStr);
                    List<PropertyEntry> list;

                    if (_data.ContainsKey(sectionStr))
                    {
                        list = _data[sectionStr];
                    }
                    else
                    {
                        list = new List<PropertyEntry>();
                        _data[sectionStr] = list;
                    }

                    list.Add(entry);
                }

                csv.Close();
                mask0.Close();
            }
            catch (IOException e)
            {
                throw new EncogError(e);
            }
        }
Example #35
0
		/// <summary>
		/// Set a Property using the values in the <see cref="LevelEntry"/> argument
		/// </summary>
		/// <param name="propertyEntry">the property value</param>
		/// <remarks>
		/// <para>
		/// Set a Property using the values in the <see cref="LevelEntry"/> argument.
		/// </para>
		/// <para>
		/// Supports setting property values via the configuration file.
		/// </para>
		/// </remarks>
		internal void AddProperty(PropertyEntry propertyEntry)
		{
			if (propertyEntry == null) throw new ArgumentNullException("propertyEntry");
			if (propertyEntry.Key == null) throw new ArgumentNullException("propertyEntry.Key");

			Properties[propertyEntry.Key] = propertyEntry.Value;
		}
 private static void ShowChange(int id, PropertyEntry propertyEntry)
 {
     WriteLine($"id: {id}, current: {propertyEntry.CurrentValue}, original: {propertyEntry.OriginalValue}, modified: {propertyEntry.IsModified}");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SimplifiedProperties.PropertyException"/> class.
 /// </summary>
 /// <param name="message">Message.</param>
 /// <param name="entry">Entry.</param>
 public PropertyException(string @message, PropertyEntry @entry)
     : base(@message)
 {
     Entry = @entry;
 }
Example #38
0
 private PropertyConstraints()
 {
     try
     {
         ReadCSV dcsv;
         string str;
         string str2;
         string str3;
         PropertyType typeFormat;
         PropertyEntry entry;
         List<PropertyEntry> list;
         Stream stream = ResourceLoader.CreateStream("Encog.Resources.analyst.csv");
         goto Label_01A2;
     Label_0021:
         list.Add(entry);
     Label_002A:
         if (dcsv.Next())
         {
             goto Label_017D;
         }
         dcsv.Close();
         stream.Close();
         return;
     Label_0048:
         if (0 == 0)
         {
             goto Label_0059;
         }
     Label_004B:
         if (this._x4a3f0a05c02f235f.ContainsKey(str))
         {
             goto Label_009E;
         }
     Label_0059:
         list = new List<PropertyEntry>();
         this._x4a3f0a05c02f235f[str] = list;
         goto Label_00BC;
     Label_0070:
         if ("string".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             goto Label_00B1;
         }
         throw new AnalystError("Unknown type constraint: " + str3);
     Label_0091:
         entry = new PropertyEntry(typeFormat, str2, str);
         goto Label_004B;
     Label_009E:
         list = this._x4a3f0a05c02f235f[str];
         goto Label_00B6;
     Label_00AE:
         if (0 == 0)
         {
             goto Label_0070;
         }
     Label_00B1:
         typeFormat = PropertyType.TypeString;
         goto Label_0091;
     Label_00B6:
         if (0 == 0)
         {
             goto Label_0021;
         }
     Label_00BC:
         if (8 != 0)
         {
             goto Label_01B8;
         }
     Label_00CA:
         while ("list-string".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             typeFormat = PropertyType.TypeListString;
             goto Label_0091;
         }
         if (3 == 0)
         {
             goto Label_0185;
         }
         goto Label_00AE;
     Label_00EC:
         if ("int".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             goto Label_0114;
         }
         goto Label_013C;
     Label_00FD:
         if (!"format".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             goto Label_00EC;
         }
         typeFormat = PropertyType.TypeFormat;
         goto Label_0091;
     Label_0114:
         typeFormat = PropertyType.TypeInteger;
         goto Label_0091;
     Label_0119:
         if ("real".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             goto Label_0153;
         }
         if (0 != 0)
         {
             goto Label_009E;
         }
         if (15 == 0)
         {
             goto Label_0021;
         }
         goto Label_00FD;
     Label_013C:
         if (2 != 0)
         {
             goto Label_00CA;
         }
         if (0 == 0)
         {
             goto Label_01A2;
         }
         goto Label_0091;
     Label_014B:
         if (0 != 0)
         {
             goto Label_0048;
         }
         goto Label_0119;
     Label_0153:
         typeFormat = PropertyType.TypeDouble;
         if (-2147483648 == 0)
         {
             goto Label_017D;
         }
         goto Label_0091;
     Label_0167:
         if ("boolean".Equals(str3, StringComparison.InvariantCultureIgnoreCase))
         {
             goto Label_019D;
         }
         goto Label_014B;
     Label_017D:
         str = dcsv.Get(0);
     Label_0185:
         str2 = dcsv.Get(1);
         str3 = dcsv.Get(2);
         if (15 != 0)
         {
             goto Label_0167;
         }
     Label_019D:
         typeFormat = PropertyType.TypeBoolean;
         goto Label_0091;
     Label_01A2:
         dcsv = new ReadCSV(stream, false, CSVFormat.EgFormat);
         goto Label_002A;
     Label_01B8:
         if (0 == 0)
         {
             goto Label_0021;
         }
     }
     catch (IOException exception)
     {
         throw new EncogError(exception);
     }
 }
        /// <summary>
        /// Load the config file and reads it's contents.
        /// </summary>
        public void Load()
        {
            if (!_fileInfo.Exists)
                _fileInfo.Create().Close();
            using (TextReader reader = _fileInfo.OpenText())
            {

                var list = new PropertyList(string.Empty);
                list.Loaded = true;

                Regex groupStartRegex = new Regex(REGEX_GROUP_START);
                Regex keyValueRegex = new Regex(REGEX_KEY_VALUE);
                Regex arrayValueRegex = new Regex(REGEX_ARRAY_VALUE);
                Regex blockCommentRegex = new Regex(REGEX_COMMENT);
                Regex commentRegex = new Regex(REGEX_COMMENT);
                Regex concatRegex = new Regex(REGEX_CONCAT);
                Regex groupEndRegex = new Regex(REGEX_GROUP_END);
                Regex newLineRegex = new Regex(REGEX_NEW_LINE);
                Regex invalidRegex = new Regex(REGEX_INVALID);

                string allText = reader.ReadToEnd();
                PropertyEntry previousValueEntry = null;

                while (!allText.IsNullEmptyOrWhite())
                {
                    PropertyEntry newEntry = null;
                    string result = null;
                    var groupStartGroups = groupStartRegex.Match(allText).Groups;
                    if (groupStartGroups["r"].Success)
                    {
                        result = groupStartGroups["r"].Value;
                        string key = groupStartGroups["k"].Value;
                        string comment = groupStartGroups["c"].Value;
                        var newList = new PropertyList(key, comment);
                        newList.Parent = list;
                        list = newList;
                        previousValueEntry = null;
                    }
                    var keyValueGroups = keyValueRegex.Match(allText).Groups;
                    if (result == null && keyValueGroups["r"].Success)
                    {
                        result = keyValueGroups["r"].Value;
                        string key = keyValueGroups["k"].Value;
                        string value = keyValueGroups["v"].Value;
                        string comment = keyValueGroups["c"].Value;
                        newEntry = new PropertyEntry(key, value, comment);
                        previousValueEntry = newEntry;
                    }
                    var arrayValueGroups = arrayValueRegex.Match(allText).Groups;
                    if (result == null && arrayValueGroups["r"].Success)
                    {
                        result = arrayValueGroups["r"].Value;
                        string value = arrayValueGroups["v"].Value;
                        string comment = arrayValueGroups["c"].Value;
                        newEntry = new ArrayEntry(value, comment);
                        previousValueEntry = newEntry;
                    }
                    var concatGroups = concatRegex.Match(allText).Groups;
                    if (result == null && concatGroups["r"].Success)
                    {
                        if (previousValueEntry != null)
                        {
                            result = concatGroups["r"].Value;
                            string value = concatGroups["v"].Value;
                            string comment = concatGroups["c"].Value;
                            if (previousValueEntry is ConcatenatedEntry)
                            {
                                (previousValueEntry as ConcatenatedEntry).AddConcat(value, comment);
                            }
                            else
                            {
                                list.RemoveEntry(previousValueEntry);
                                newEntry = new ConcatenatedEntry(
                                    previousValueEntry.Key,
                                    new string[]{ previousValueEntry.StringValue, value },
                                    new string[]{ previousValueEntry.Comment, comment });
                                newEntry.LineNumber = previousValueEntry.LineNumber;
                                previousValueEntry = newEntry;
                            }
                        }
                    }
                    var blockCommentGroups = blockCommentRegex.Match(allText).Groups;
                    if (result == null && blockCommentGroups["r"].Success)
                    {
                        result = blockCommentGroups["r"].Value;
                        string comment = blockCommentGroups["c"].Value;
                        newEntry = new BlockCommentEntry(comment);
                    }
                    var commentGroups = commentRegex.Match(allText).Groups;
                    if (result == null && commentGroups["r"].Success)
                    {
                        result = commentGroups["r"].Value;
                        string comment = commentGroups["c"].Value;
                        newEntry = new CommentEntry(comment);
                    }
                    var groupEndGroups = groupEndRegex.Match(allText).Groups;
                    if (result == null && groupEndGroups["r"].Success)
                    {
                        result = groupEndGroups["r"].Value;
                        string comment = groupEndGroups["c"].Value;
                        list.CloseComment = comment;
                        list = list.Parent;
                        previousValueEntry = null;
                    }
                    var newLineGroups = newLineRegex.Match(allText).Groups;
                    if (result == null && newLineGroups["r"].Success)
                    {
                        result = newLineGroups["r"].Value;
                        newEntry = new NewLineEntry();
                    }
                    var invalidGroups = invalidRegex.Match(allText).Groups;
                    if (result == null)
                    {
                        result = invalidGroups["r"].Value;
                    }
                    if (newEntry != null)
                    {
                        if (newEntry.LineNumber == 0)
                            newEntry.LineNumber = currentLineNumber;
                        newEntry.Loaded = !CommentUnloadedEntries;
                        list.AddEntry(newEntry);
                    }

                    currentLineNumber += Tools.Count('\n', result);
                    allText = allText.Remove(0, result.Length);
                }
                if (list.Parent != null)
                    throw new PropertyException("Missing closing curly brace.", list);
                Properties = list.Root;
            }
        }
        public void Can_reject_changes_when_clearing_modified_flag()
        {
            var entity = new Wotty { Id = 1, Primate = "Monkey", Marmate = "Bovril" };

            var entry = TestHelpers.Instance.CreateInternalEntry(
                BuildModel(),
                EntityState.Unchanged,
                entity);

            var primateEntry = new PropertyEntry(entry, "Primate");
            primateEntry.OriginalValue = "Chimp";
            primateEntry.IsModified = true;

            var marmateEntry = new PropertyEntry(entry, "Marmate");
            marmateEntry.OriginalValue = "Marmite";
            marmateEntry.IsModified = true;

            Assert.Equal(EntityState.Modified, entry.EntityState);
            Assert.Equal("Monkey", entity.Primate);
            Assert.Equal("Bovril", entity.Marmate);

            primateEntry.IsModified = false;

            Assert.Equal(EntityState.Modified, entry.EntityState);
            Assert.Equal("Chimp", entity.Primate);
            Assert.Equal("Bovril", entity.Marmate);

            marmateEntry.IsModified = false;

            Assert.Equal(EntityState.Unchanged, entry.EntityState);
            Assert.Equal("Chimp", entity.Primate);
            Assert.Equal("Marmite", entity.Marmate);
        }
        public void Cannot_set_or_get_original_value_when_not_tracked_generic()
        {
            var entity = new FullyNotifyingWotty { Id = 1, ConcurrentPrimate = "Monkey" };

            var entry = TestHelpers.Instance.CreateInternalEntry(
                BuildModel(),
                EntityState.Unchanged,
                entity);

            var propertyEntry = new PropertyEntry<FullyNotifyingWotty, string>(entry, "Primate");

            Assert.Equal(
                CoreStrings.OriginalValueNotTracked("Primate", "FullyNotifyingWotty"),
                Assert.Throws<InvalidOperationException>(() => propertyEntry.OriginalValue).Message);

            Assert.Equal(
                CoreStrings.OriginalValueNotTracked("Primate", "FullyNotifyingWotty"),
                Assert.Throws<InvalidOperationException>(() => propertyEntry.OriginalValue = "Chimp").Message);
        }