public void Can_access_ModelWithFieldsOfDifferentTypes()
		{
			var idAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("Id");
			var nameAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("Name");
			var longIdAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("LongId");
			var guidAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("Guid");
			var boolAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("Bool");
			var dateTimeAccessor = new PropertyAccessor<ModelWithFieldsOfDifferentTypes>("DateTime");

			var original = ModelWithFieldsOfDifferentTypesFactory.Instance.CreateInstance(1);

			Assert.That(idAccessor.GetPropertyFn()(original), Is.EqualTo(original.Id));
			Assert.That(nameAccessor.GetPropertyFn()(original), Is.EqualTo(original.Name));
			Assert.That(longIdAccessor.GetPropertyFn()(original), Is.EqualTo(original.LongId));
			Assert.That(guidAccessor.GetPropertyFn()(original), Is.EqualTo(original.Guid));
			Assert.That(boolAccessor.GetPropertyFn()(original), Is.EqualTo(original.Bool));
			Assert.That(dateTimeAccessor.GetPropertyFn()(original), Is.EqualTo(original.DateTime));

			var to = ModelWithFieldsOfDifferentTypesFactory.Instance.CreateInstance(2);

			idAccessor.SetPropertyFn()(original, to.Id);
			nameAccessor.SetPropertyFn()(original, to.Name);
			longIdAccessor.SetPropertyFn()(original, to.LongId);
			guidAccessor.SetPropertyFn()(original, to.Guid);
			boolAccessor.SetPropertyFn()(original, to.Bool);
			dateTimeAccessor.SetPropertyFn()(original, to.DateTime);

			ModelWithFieldsOfDifferentTypesFactory.Instance.AssertIsEqual(original, to);
		}
        public void Can_access_ModelWithComplexTypes()
        {
            var idAccessor = new PropertyAccessor<ModelWithComplexTypes>("Id");
            var stringListAccessor = new PropertyAccessor<ModelWithComplexTypes>("StringList");
            var intListAccessor = new PropertyAccessor<ModelWithComplexTypes>("IntList");
            var stringMapAccessor = new PropertyAccessor<ModelWithComplexTypes>("StringMap");
            var intMapAccessor = new PropertyAccessor<ModelWithComplexTypes>("IntMap");
            var childAccessor = new PropertyAccessor<ModelWithComplexTypes>("Child");

            var original = ModelWithComplexTypesFactory.Instance.CreateInstance(1);

            Assert.That(idAccessor.GetPropertyFn()(original), Is.EqualTo(original.Id));
            Assert.That(stringListAccessor.GetPropertyFn()(original), Is.EqualTo(original.StringList));
            Assert.That(intListAccessor.GetPropertyFn()(original), Is.EqualTo(original.IntList));
            Assert.That(stringMapAccessor.GetPropertyFn()(original), Is.EqualTo(original.StringMap));
            Assert.That(intMapAccessor.GetPropertyFn()(original), Is.EqualTo(original.IntMap));
            Assert.That(childAccessor.GetPropertyFn()(original), Is.EqualTo(original.Child));

            var to = ModelWithComplexTypesFactory.Instance.CreateInstance(2);

            idAccessor.SetPropertyFn()(original, to.Id);
            stringListAccessor.SetPropertyFn()(original, to.StringList);
            intListAccessor.SetPropertyFn()(original, to.IntList);
            stringMapAccessor.SetPropertyFn()(original, to.StringMap);
            intMapAccessor.SetPropertyFn()(original, to.IntMap);
            childAccessor.SetPropertyFn()(original, to.Child);

            ModelWithComplexTypesFactory.Instance.AssertIsEqual(original, to);
        }
Exemplo n.º 3
0
 public void Dispose()
 {
     if (_propertyAccessor != null)
     {
         Marshal.ReleaseComObject(_propertyAccessor);
         _propertyAccessor = null;
     }
 }
        public void Can_access_ModelWithFieldsOfDifferentAndNullableTypes()
        {
            var idAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("Id");
            var idNAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NId");
            var longIdAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NLongId");
            var guidAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NGuid");
            var boolAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NBool");
            var dateTimeAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NDateTime");
            var floatAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NFloat");
            var doubleAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NDouble");
            var decimalAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NDecimal");
            var timespanAccessor = new PropertyAccessor<ModelWithFieldsOfNullableTypes>("NTimeSpan");

            var original = ModelWithFieldsOfNullableTypesFactory.Instance.CreateInstance(1);

            Assert.That(idAccessor.GetPropertyFn()(original), Is.EqualTo(original.Id));
            Assert.That(idNAccessor.GetPropertyFn()(original), Is.EqualTo(original.NId));
            Assert.That(longIdAccessor.GetPropertyFn()(original), Is.EqualTo(original.NLongId));
            Assert.That(guidAccessor.GetPropertyFn()(original), Is.EqualTo(original.NGuid));
            Assert.That(boolAccessor.GetPropertyFn()(original), Is.EqualTo(original.NBool));
            Assert.That(dateTimeAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDateTime));
            Assert.That(floatAccessor.GetPropertyFn()(original), Is.EqualTo(original.NFloat));
            Assert.That(doubleAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDouble));
            Assert.That(decimalAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDecimal));
            Assert.That(timespanAccessor.GetPropertyFn()(original), Is.EqualTo(original.NTimeSpan));

            var to = ModelWithFieldsOfNullableTypesFactory.Instance.CreateInstance(2);

            idAccessor.SetPropertyFn()(original, to.Id);
            idNAccessor.SetPropertyFn()(original, to.NId);
            longIdAccessor.SetPropertyFn()(original, to.NLongId);
            guidAccessor.SetPropertyFn()(original, to.NGuid);
            boolAccessor.SetPropertyFn()(original, to.NBool);
            dateTimeAccessor.SetPropertyFn()(original, to.NDateTime);
            floatAccessor.SetPropertyFn()(original, to.NFloat);
            doubleAccessor.SetPropertyFn()(original, to.NDouble);
            decimalAccessor.SetPropertyFn()(original, to.NDecimal);
            timespanAccessor.SetPropertyFn()(original, to.NTimeSpan);

            ModelWithFieldsOfNullableTypesFactory.Instance.AssertIsEqual(original, to);

            //Can handle nulls
            original = new ModelWithFieldsOfNullableTypes();

            Assert.That(idAccessor.GetPropertyFn()(original), Is.EqualTo(original.Id));
            Assert.That(idNAccessor.GetPropertyFn()(original), Is.EqualTo(original.NId));
            Assert.That(longIdAccessor.GetPropertyFn()(original), Is.EqualTo(original.NLongId));
            Assert.That(guidAccessor.GetPropertyFn()(original), Is.EqualTo(original.NGuid));
            Assert.That(boolAccessor.GetPropertyFn()(original), Is.EqualTo(original.NBool));
            Assert.That(dateTimeAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDateTime));
            Assert.That(floatAccessor.GetPropertyFn()(original), Is.EqualTo(original.NFloat));
            Assert.That(doubleAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDouble));
            Assert.That(decimalAccessor.GetPropertyFn()(original), Is.EqualTo(original.NDecimal));
            Assert.That(timespanAccessor.GetPropertyFn()(original), Is.EqualTo(original.NTimeSpan));
        }
Exemplo n.º 5
0
                public bool MoveNext()
                {
                    if (_enumerator.MoveNext() == false)
                    {
                        return(false);
                    }

                    var output = _enumerator.Current;

                    using (_createBlittableResult.Start())
                    {
                        IPropertyAccessor accessor;

                        if (_parent._isMultiMap == false)
                        {
                            accessor = _parent._propertyAccessor ??
                                       (_parent._propertyAccessor = PropertyAccessor.CreateMapReduceOutputAccessor(output.GetType(), output, _groupByFields));
                        }
                        else
                        {
                            accessor = TypeConverter.GetPropertyAccessorForMapReduceOutput(output, _groupByFields);
                        }

                        var mapResult = new DynamicJsonValue();

                        _reduceKeyProcessor.Reset();

                        foreach (var property in accessor.GetPropertiesInOrder(output))
                        {
                            var value          = property.Value;
                            var blittableValue = TypeConverter.ToBlittableSupportedType(value);
                            mapResult[property.Key] = blittableValue;

                            if (property.IsGroupByField)
                            {
                                _reduceKeyProcessor.Process(_parent._indexContext.Allocator, blittableValue);
                            }
                        }

                        if (_reduceKeyProcessor.ProcessedFields != _groupByFields.Count)
                        {
                            ThrowMissingGroupByFieldsInMapOutput(output, _groupByFields, _parent._compiledIndex);
                        }

                        var reduceHashKey = _reduceKeyProcessor.Hash;

                        Current.Data          = _parent._indexContext.ReadObject(mapResult, "map-result");
                        Current.ReduceKeyHash = reduceHashKey;
                    }

                    return(true);
                }
            public Builder <TProvisioner, TClientObject> Map <T>(
                Expression <Func <TClientObject, T> > clientObjectProperty,
                Expression <Func <TProvisioner, T> > provisionerProperty
                )
            {
                if (provisionerProperty == null)
                {
                    throw Logger.Fatal.ArgumentNull(nameof(provisionerProperty));
                }

                if (clientObjectProperty == null)
                {
                    throw Logger.Fatal.ArgumentNull(nameof(clientObjectProperty));
                }

                var metadata = Metadata ??
                               HarshProvisionerMetadataRepository.Get(
                    typeof(TProvisioner)
                    );

                var provisionerPropertyInfo =
                    provisionerProperty.ExtractLastPropertyAccess();

                if (!IsParameter(provisionerPropertyInfo))
                {
                    throw Logger.Fatal.ArgumentFormat(
                              nameof(provisionerProperty),
                              SR.ClientObjectUpdater_NotAParameter,
                              provisionerPropertyInfo
                              );
                }

                var provisionerAccessor = metadata.GetPropertyAccessor(
                    provisionerPropertyInfo
                    );

                var clientObjectAccessor = new PropertyAccessor(
                    clientObjectProperty.ExtractLastPropertyAccess()
                    );

                var mappings = Mappings ??
                               ImmutableDictionary <PropertyAccessor, PropertyAccessor>
                               .Empty;

                return(new Builder <TProvisioner, TClientObject>(
                           metadata,
                           mappings.Add(
                               provisionerAccessor,
                               clientObjectAccessor
                               )
                           ));
            }
        private static void FixAccessor(PropertyAccessor accessor, string textToInsert, int insertionIndex)
        {
            if (accessor != null)
            {
                // Need to set the text range of the get {}
                var accessorText = accessor.ToString().Trim();
                int startIndex   = textToInsert.IndexOf(accessorText) + insertionIndex;
                int endIndex     = startIndex + accessorText.Length;

                accessor.TextRange.StartOffset = startIndex;
                accessor.TextRange.EndOffset   = endIndex;
            }
        }
        static AsyncOrganizationServiceProxy()
        {
            var knownAssemblyAttributeType = typeof(IOrganizationService).Assembly.GetType("Microsoft.Xrm.Sdk.KnownAssemblyAttribute");
            var knownAssemblyAttribute     = (Attribute)Activator.CreateInstance(knownAssemblyAttributeType);

            TypeDescriptor.AddAttributes(typeof(IWcfAsyncOrganizationService), knownAssemblyAttribute);

            var baseType = typeof(ServiceProxy <IWcfAsyncOrganizationService>);

            _isAuthenticated   = ReflectionUtils.CreatePropertyAccessor <bool>(baseType, nameof(IsAuthenticated));
            _homeRealmUri      = ReflectionUtils.CreatePropertyAccessor <Uri>(baseType, nameof(HomeRealmUri));
            _deviceCredentials = ReflectionUtils.CreatePropertyAccessor <ClientCredentials>(baseType, nameof(DeviceCredentials));
        }
        public override T Add <T>(T entity)
        {
            var sequence   = _provider.GetSequenceName(typeof(T));
            var primaryKey = ((IMetaDataProvider)Repository).GetPrimaryKey <T>();

            if (primaryKey.Length == 1)
            {
                var property = typeof(T).GetProperty(primaryKey[0]);
                var value    = GenerateId(sequence, property.PropertyType, (SqlConnection)((IDataContext <DbContext>)Repository.DataContext).Session.Database.GetDbConnection());
                PropertyAccessor.Set(entity, property.Name, value);
            }
            return(base.Add(entity));
        }
Exemplo n.º 10
0
        public static void PopulateFromDataReader <T>(this T obj, IDataReader reader, bool tryRead) where T : class, new()
        {
            if (obj == null)
            {
                throw new InvalidOperationException(
                          "Cannot call PopulateFromDataReader<T> on a null object - initialise it before populating.");
            }

            if (!tryRead || reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    string name = reader.GetName(i);
                    KeyValuePair <Type, string> key = new KeyValuePair <Type, string>(typeof(T), name);
                    object value = reader[i].IsDbNull() ? null : reader[i];

                    PropertyInfo propertyInfo = propertyCache[key];
                    if (propertyInfo != null)
                    {
                        try
                        {
                            PropertyAccessor.Create(propertyInfo).Set(obj, value);
                        }
                        catch (Exception ex)
                        {
                            throw new InvalidOperationException(
                                      string.Format("Failed to populate property {0} of type {1} with value of type {2}", name,
                                                    propertyInfo.PropertyType, value != null ? value.GetType().Name : "null"), ex);
                        }
                    }
                    else
                    {
                        try
                        {
                            FieldInfo fieldInfo = fieldCache[key];

                            if (fieldInfo != null)
                            {
                                fieldInfo.SetValue(obj, value);
                            }
                        }
                        catch (ArgumentException ex)
                        {
                            throw new InvalidOperationException(
                                      string.Format("Failed to populate property or field {0} with value of type {1}", name,
                                                    value != null ? value.GetType().Name : "null"), ex);
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        private static void CascadeImplementation <T>(T root, Action <T, T> action, HashSet <T> ancestors, IReadOnlyCollection <string> paths = null, int level = 0)
        {
            ancestors = ancestors ?? new HashSet <T>();
            ancestors.Add(root);

            var set = new HashSet <string>(paths != null ? paths.Select(i => i.Split('.')).Select(i => i.ElementAtOrDefault(level)).Where(i => i != null) : Enumerable.Empty <string>());

            var properties = root.GetType().GetProperties();

            if (paths != null)
            {
                properties = properties.Where(p => set.Contains(p.Name)).ToArray();
            }

            var objectProperties     = properties.Where(t => typeof(T).IsAssignableFrom(t.PropertyType));
            var collectionProperties = properties.Where(t => t.PropertyType.IsGenericType &&
                                                        (t.PropertyType.IsClass || typeof(IEnumerable).IsAssignableFrom(t.PropertyType)) &&
                                                        typeof(ICollection <T>).IsAssignableFrom(t.PropertyType.GetGenericTypeDefinition().MakeGenericType(typeof(T))) &&
                                                        typeof(T).IsAssignableFrom(t.PropertyType.GetGenericArguments()[0]));

            foreach (var property in objectProperties)
            {
                var item = PropertyAccessor.Get(root.GetType(), root, property.Name);
                if (!(item is T) || ancestors.Contains((T)item))
                {
                    continue;
                }

                action(root, (T)item);
                CascadeImplementation((T)item, action, ancestors, paths, level + 1);
            }

            foreach (var property in collectionProperties)
            {
                var items = (IEnumerable)PropertyAccessor.Get(root.GetType(), root, property.Name);
                if (items == null)
                {
                    continue;
                }
                foreach (var item in items)
                {
                    if (!(item is T) || ancestors.Contains((T)item))
                    {
                        continue;
                    }

                    action(root, (T)item);
                    CascadeImplementation((T)item, action, ancestors, paths, level + 1);
                }
            }
        }
Exemplo n.º 12
0
        public static void GitClone()
        {
            string path = KBCodeReviewHelper.GetKBCodeReviewDirectory();

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string gitUser   = GetGitUser();
            string gitPwd    = GetGitPassword();
            string gitServer = PropertyAccessor.GetValueString(UIServices.KB.CurrentModel, "Git remote server");
            string user2     = PropertyAccessor.GetValueString(UIServices.KB.CurrentModel, "Git UserName");
            string url       = "https://" + gitUser + ":" + gitPwd.ToString() + "@" + gitServer;
            //string result2;
            //ArrayList debug = new ArrayList();
            //result2 = "User: "******"Password: "******"GitServer: " + GitServer.ToString();
            //debug.Add(result2);
            //result2 = "GitUrl: " + url.ToString();
            //debug.Add(result2);
            //result2 = "User2: " + user2.ToString();
            //debug.Add(result2);


            bool success = false;

            if (gitServer != "")
            {
                if ((gitUser != "") && (gitPwd != ""))
                {
                    success = GitHelper.GitClone(url);
                }
                else
                {
                    GxConsoleHandler.WriteOutput("Configure Git user and password");
                }
            }
            else
            {
                GxConsoleHandler.WriteOutput("Git remote server can not be null");
            }

            if (success)
            {
                success = GitHelper.SetNotepadAsEditor();
            }
        }
Exemplo n.º 13
0
        public void Model轉換()
        {
            var expected = Data.CreateDefaultData();
            var actual   = new Data();

            foreach (var propertyInfo in expected.GetType().GetProperties())
            {
                var accessor = new PropertyAccessor(propertyInfo);
                var value    = accessor.GetValue(expected);
                accessor.SetValue(actual, value);
            }

            actual.Should().BeEquivalentTo(expected);
        }
        public void HandleReference_OneOne_RealSide_Null()
        {
            Computer source        = DomainObjectMother.CreateObjectInTransaction <Computer> (SourceTransaction);
            Computer clone         = DomainObjectMother.CreateObjectInTransaction <Computer> (CloneTransaction);
            Employee sourceRelated = null;
            Employee cloneRelated  = null;

            PropertyAccessor sourceReference = source.Properties[typeof(Computer), "Employee"];
            PropertyAccessor cloneReference  = clone.Properties[typeof(Computer), "Employee"];

            source.Employee = sourceRelated;

            HandleReference_OneOne_RealSide_Checks_Null(sourceRelated, sourceReference, cloneRelated, cloneReference);
        }
Exemplo n.º 15
0
        public void OverrideReadOnly_CanSetValue()
        {
            var controller = new PropertyAccessController(BindingState.Bound);
            var accessor   = new PropertyAccessor <int>(controller, string.Empty, BindingAccess.Read | BindingAccess.Write);

            //Set readonly
            accessor.IsReadOnly = true;
            Assert.True(accessor.IsReadOnly);
            Assert.Equal(0, accessor.Value);

            accessor.SetValue(1, overrideReadOnly: true);
            Assert.True(accessor.HasBeenModified);
            Assert.Equal(1, accessor.Value);
        }
Exemplo n.º 16
0
        bool HasUnsavedValue(PrimaryKeyProperty pk, PropertyAccessor pinf, object entity, ITypeConverterStore converterStore, out object pkValue)
        {
            if (!pk.UnsavedValueProcessed)
            {
                pk.UnsavedValue          = pk.GetUnsavedValue(pinf.PropertyType, converterStore);
                pk.UnsavedValueProcessed = true;
            }

            pkValue = pinf.GetMethod(entity);

            var rlt = object.Equals(pkValue, pk.UnsavedValue);

            return(rlt);
        }
Exemplo n.º 17
0
        protected T GetSetting <T>(Expression <Func <T> > settingProperty, T defaultValue = default(T))
        {
            var accessor = new PropertyAccessor <T>(settingProperty);

            if (_appSettings.AllKeys.Contains(accessor.Name))
            {
                var textValue = _appSettings[accessor.Name];
                return((T)ConvertEx.ChangeType <T>(textValue));
            }
            else
            {
                return(defaultValue);
            }
        }
        public void HandleReference_OneMany_RealSide_Null()
        {
            OrderItem source        = DomainObjectMother.CreateObjectInTransaction <OrderItem> (SourceTransaction);
            OrderItem clone         = DomainObjectMother.CreateObjectInTransaction <OrderItem> (CloneTransaction);
            Order     sourceRelated = null;
            Order     cloneRelated  = null;

            PropertyAccessor sourceReference = source.Properties[typeof(OrderItem), "Order"];
            PropertyAccessor cloneReference  = clone.Properties[typeof(OrderItem), "Order"];

            source.Order = sourceRelated;

            HandleReference_OneMany_RealSide_Checks_Null(sourceRelated, sourceReference, cloneRelated, cloneReference);
        }
        public void HandleReference_OneOne_VirtualSide()
        {
            Employee source        = DomainObjectMother.CreateObjectInTransaction <Employee> (SourceTransaction);
            Employee clone         = DomainObjectMother.CreateObjectInTransaction <Employee> (CloneTransaction);
            Computer sourceRelated = DomainObjectMother.CreateObjectInTransaction <Computer> (SourceTransaction);
            Computer cloneRelated  = DomainObjectMother.CreateObjectInTransaction <Computer> (CloneTransaction);

            PropertyAccessor sourceReference = source.Properties[typeof(Employee), "Computer"];
            PropertyAccessor cloneReference  = clone.Properties[typeof(Employee), "Computer"];

            source.Computer = sourceRelated;

            HandleReference_OneOne_VirtualSide_Checks(sourceRelated, sourceReference, cloneRelated, cloneReference);
        }
Exemplo n.º 20
0
        private static Object GetValue(PropertyAccessor property, Object target)
        {
            var value = property.GetValue(target);

            if (value == null)
            {
                Logger.Debug(
                    "Property {PropertyName} is null, skipping.",
                    property.Name
                    );
            }

            return(value);
        }
Exemplo n.º 21
0
 private void AssertFailure(string expression)
 {
     try {
         string value = new PropertyAccessor(_project, _project.RootTargetCallStack).ExpandProperties("${" + expression + "}", Location.UnknownLocation);
         // we shouldn't get here
         Assert.Fail("Expected BuildException while evaluating ${" + expression + "}, nothing was thrown. The returned value was " + value);
     } catch (BuildException ex) {
         (_project as ITargetLogger).Log(Level.Debug, "Got expected failure on ${" + expression + "}: " + ((ex.InnerException != null) ? ex.InnerException.Message : ""));
         // ok - this one should have been thrown
     } catch (Exception ex) {
         // some other exception has been thrown - fail
         Assert.Fail("Expected BuildException while evaluating ${" + expression + "}, but " + ex.GetType().FullName + " was thrown.");
     }
 }
Exemplo n.º 22
0
        private static void MergeObjectProperties(DbContext context, object source, object target, IEqualityComparer <object> comparer, HashSet <object> ancestors, IReadOnlyCollection <string[]> paths, int level, PropertyInfo[] properties)
        {
            foreach (var property in properties.Where(p => p.PropertyType != typeof(string) && p.CanRead && p.CanWrite && p.PropertyType.IsClass && !typeof(IEnumerable).IsAssignableFrom(p.PropertyType)))
            {
                var value    = PropertyAccessor.Get(target.GetType(), target, property.Name);
                var newValue = PropertyAccessor.Get(source.GetType(), source, property.Name);

                if (ancestors.Contains(newValue))
                {
                    continue;
                }

                if (value == null && newValue != null)
                {
                    context.Entry(target).Member(property.Name).CurrentValue = newValue;
                }
                else if (newValue == null && value != null)
                {
                    context.Entry(target).Member(property.Name).CurrentValue = null;
                }
                else if (value != null)
                {
                    try
                    {
                        context.Entry(value).CurrentValues.SetValues(newValue);
                    }
                    catch (Exception ex)
                    {
                        // Merge failed as we tried to change the parent
                        // Now try actually changing the parent
                        var hash     = comparer.GetHashCode(newValue);
                        var local    = GetLocal(context, newValue.GetType());
                        var attached = local.Cast <object>().FirstOrDefault(e => comparer.GetHashCode(e) == hash);
                        if (attached != null && attached != newValue)
                        {
                            // Found unchanged locally
                            // Assign existing parent
                            PropertyAccessor.Set(target.GetType(), target, property.Name, attached);
                        }
                        else
                        {
                            PropertyAccessor.Set(target.GetType(), target, property.Name, newValue);
                            context.Entry(newValue).State = EntityState.Unchanged;
                        }
                    }
                    MergeImplementation(context, newValue, value, comparer, new HashSet <object>(ancestors), paths, level + 1);
                }
            }
        }
Exemplo n.º 23
0
        [Test] // bug #1556326
        public void Remove_Readonly_Property()
        {
            Project p = CreateFilebasedProject("<project />");
            var     propertyAccessor = new PropertyAccessor(p, p.RootTargetCallStack);

            propertyAccessor.Set("test", "value1", readOnly: true);
            Assert.IsTrue(propertyAccessor.IsReadOnlyProperty("test"), "#1");
            Assert.IsTrue(propertyAccessor.Contains("test"), "#2");
            propertyAccessor.Remove("test");
            Assert.IsFalse(propertyAccessor.IsReadOnlyProperty("test"), "#3");
            Assert.IsFalse(propertyAccessor.Contains("test"), "#4");
            propertyAccessor.Set("test", "value2");
            Assert.IsFalse(propertyAccessor.IsReadOnlyProperty("test"), "#5");
            Assert.IsTrue(propertyAccessor.Contains("test"), "#6");
        }
Exemplo n.º 24
0
        public IEnumerable <IPropertyChange> GetChangedProperties()
        {
            var simpleProperties = _originalValues.Select(x => new SimplePropertyChange(
                                                              x.Key,
                                                              x.Value,
                                                              PropertyAccessor.Get(Target.GetType().GetProperty(x.Key)).GetValue(Target)))
                                   .Cast <IPropertyChange>();

            var collectionProperties = _collectionProxies
                                       .Where(x => x.Value.Added.Any() || x.Value.Removed.Any())
                                       .Select(x => new CollectionPropertyChange(x.Key, x.Value.Added, x.Value.Removed))
                                       .Cast <IPropertyChange>();

            return(simpleProperties.Concat(collectionProperties).ToList());
        }
Exemplo n.º 25
0
        /// <summary>
        ///Ein Test für "SetValue"
        ///</summary>
        public void SetValueTestHelper <TValueType>()
        {
            var obj          = new TweeningTestObject();
            var propertyInfo = obj.GetType().GetProperty("GenericProperty");
            var target       = new PropertyAccessor <TValueType>(obj, propertyInfo);

            const int containedValue = 100;
            var       value          = (TValueType)Convert.ChangeType(new GenericParameterHelper(containedValue), typeof(TValueType));

            target.SetValue(value);
            var expected = (TValueType)Convert.ChangeType(obj.GenericProperty, typeof(TValueType));

            Assert.AreEqual(expected, value);
            Assert.AreEqual(obj.GenericProperty.Data, containedValue);
        }
Exemplo n.º 26
0
        private static IResolveBuilder GetResolveBuilder(PropertyAccessor property, Object value)
        {
            var resolveBuilder = value as IResolveBuilder;

            if (resolveBuilder == null)
            {
                Logger.Debug(
                    "Property {PropertyName} value {$Value} is not an IResolveBuilder, skipping.",
                    property.Name,
                    value
                    );
            }

            return(resolveBuilder);
        }
Exemplo n.º 27
0
        public void SimplePropertyReadOnlySetAndUnset_ObjectIsReadWritable()
        {
            var controller = new PropertyAccessController(BindingState.Bound);
            var accessor   = new PropertyAccessor <int>(8, controller, string.Empty, BindingAccess.Read | BindingAccess.Write);

            //Set readonly
            accessor.IsReadOnly = true;

            //Un-set readonly
            accessor.IsReadOnly = false;
            Assert.False(accessor.IsReadOnly);
            accessor.Value = 10;
            Assert.Equal(10, accessor.Value);
            Assert.True(accessor.HasBeenModified);
        }
Exemplo n.º 28
0
        // Constructors

        /// <summary>
        /// Initializes new instance of this type.
        /// </summary>
        /// <exception cref="InvalidOperationException">No current Comparer.</exception>
        public ComparisonContext()
        {
            Comparer = Comparer.Current;
            if (Comparer == null)
            {
                throw new InvalidOperationException(Strings.ExNoCurrentComparer);
            }
            Parent = Comparer.Context;
            if (Parent == null)
            {
                return;
            }
            Difference       = Parent.Difference;
            PropertyAccessor = Parent.PropertyAccessor;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(ValidationResult.Success);
            }
            string[]      fields      = Fields.Split(',');
            List <string> errorFields = new List <string>();
            StringBuilder sb          = new StringBuilder();

            foreach (string x in fields)
            {
                string field = x.Trim();

                PropertyAccessor po = new PropertyAccessor(value, field, false);

                object ob = po.Value;
                if (ob == null || (RejectEmptyIEnumerables && (ob is IEnumerable) && !(ob as IEnumerable).GetEnumerator().MoveNext()))
                {
                    errorFields.Add(field);
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(po.DisplayName);
                    continue;
                }
                if (!ob.GetType().GetTypeInfo().IsValueType)
                {
                    continue;
                }
                if (ob.Equals(Activator.CreateInstance(ob.GetType())))
                {
                    errorFields.Add(field);
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(po.DisplayName);
                }
            }
            if (errorFields.Count == 0)
            {
                return(ValidationResult.Success);
            }
            allErrorFieldNames = sb.ToString();
            return(new ValidationResult(null, errorFields));
        }
Exemplo n.º 30
0
 public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
 {
     IMemberAccessor destMember = null;
     var propertyInfo = _typeMap.DestinationType.GetProperty(name);
     if (propertyInfo != null)
     {
         destMember = new PropertyAccessor(propertyInfo);
     }
     if (destMember == null)
     {
         var fieldInfo = _typeMap.DestinationType.GetField(name);
         destMember = new FieldAccessor(fieldInfo);
     }
     ForDestinationMember(destMember, memberOptions);
     return new MappingExpression(_typeMap, _typeConverterCtor);
 }
		public void Can_access_ModelWithIdAndName()
		{
			var idAccessor = new PropertyAccessor<ModelWithIdAndName>("Id");
			var nameAccessor = new PropertyAccessor<ModelWithIdAndName>("Name");

			var obj = new ModelWithIdAndName { Id = 1, Name = "A" };

			Assert.That(idAccessor.GetPropertyFn()(obj), Is.EqualTo(1));
			Assert.That(nameAccessor.GetPropertyFn()(obj), Is.EqualTo("A"));

			idAccessor.SetPropertyFn()(obj, 2);
			nameAccessor.SetPropertyFn()(obj, "B");

			Assert.That(obj.Id, Is.EqualTo(2));
			Assert.That(obj.Name, Is.EqualTo("B"));
		}
Exemplo n.º 32
0
        public void ComplexPropertyReadOnlySetAndUnset_ObjectIsReadWritable()
        {
            var controller = new PropertyAccessController(BindingState.Bound);
            var property   = new DummyComplexProperty();
            var accessor   = new PropertyAccessor <DummyComplexProperty>(property, controller, string.Empty, BindingAccess.Read | BindingAccess.Write);

            //Set readonly
            accessor.IsReadOnly = true;

            //Un-set readonly
            accessor.IsReadOnly = false;
            Assert.False(accessor.Value.IsReadOnly);
            Assert.False(accessor.IsReadOnly);
            accessor.Value.HasBeenModified = true;
            Assert.True(accessor.HasBeenModified);
        }
        public void HandleReference_OneMany_VirtualSide()
        {
            Cloner.CloneTransaction = CloneTransaction;

            Order     source        = DomainObjectMother.CreateObjectInTransaction <Order> (SourceTransaction);
            Order     clone         = DomainObjectMother.CreateObjectInTransaction <Order> (CloneTransaction);
            OrderItem sourceRelated = DomainObjectMother.CreateObjectInTransaction <OrderItem> (SourceTransaction);
            OrderItem cloneRelated  = DomainObjectMother.CreateObjectInTransaction <OrderItem> (CloneTransaction);

            PropertyAccessor sourceReference = source.Properties[typeof(Order), "OrderItems"];
            PropertyAccessor cloneReference  = clone.Properties[typeof(Order), "OrderItems"];

            source.OrderItems.Add(sourceRelated);

            HandleReference_OneMany_VirtualSide_Checks(sourceRelated, sourceReference, cloneRelated, cloneReference);
        }
Exemplo n.º 34
0
        public static MethodDefinition?Select(this PropertyDefinition property, PropertyAccessor accessor)
        {
            if (accessor != PropertyAccessor.Get && accessor != PropertyAccessor.Set)
            {
                throw new ArgumentException(nameof(accessor));
            }

            if (accessor == PropertyAccessor.Get)
            {
                return(property.GetMethod);
            }
            else
            {
                return(property.SetMethod);
            }
        }
Exemplo n.º 35
0
        private object getDelay(string delayRef, object model, object fixedDelay = null, bool invertSign = false)
        {
            if (delayRef != null && delayRef.StartsWith("!"))
            {
                if (TargetType == typeof(DateTime) || TargetType == typeof(TimeSpan) || TargetType == typeof(Week) || TargetType == typeof(Month))
                {
                    fixedDelay = TimeSpan.Parse(delayRef.Substring(1), CultureInfo.InvariantCulture);
                }
                else
                {
                    fixedDelay = Convert.ChangeType(delayRef.Substring(1), TargetType, CultureInfo.InvariantCulture);
                }
            }

            object res = fixedDelay;

            if (fixedDelay == null)
            {
                if (string.IsNullOrWhiteSpace(delayRef))
                {
                    return(null);
                }
                PropertyAccessor delayProp = null;
                try
                {
                    delayProp = new PropertyAccessor(model, delayRef, false);
                }
                catch
                {
                    return(null);
                }
                if (delayProp == null)
                {
                    return(null);
                }
                res = delayProp.Value;
            }
            if (invertSign)
            {
                res = changeSign(res);
            }
            if ((TargetType == typeof(DateTime) || TargetType == typeof(TimeSpan) || TargetType == typeof(Week) || TargetType == typeof(Month)) && res != null)
            {
                return(Convert.ToInt64(((TimeSpan)res).TotalMilliseconds));
            }
            return(res);
        }
Exemplo n.º 36
0
        public AttributeFactory(CustomAttributeData data)
        {
            this.Data = data;

            var ctorInvoker = new ConstructorInvoker(data.Constructor);
            var ctorArgs = data.ConstructorArguments.Select(a => a.Value).ToArray();
            this.m_attributeCreator = () => ctorInvoker.Invoke(ctorArgs);

            this.m_propertySetters = new List<Action<object>>();
            foreach (var arg in data.NamedArguments)
            {
                var property = (PropertyInfo)arg.MemberInfo;
                var propertyAccessor = new PropertyAccessor(property);
                var value = arg.TypedValue.Value;
                this.m_propertySetters.Add(o => propertyAccessor.SetValue(o, value));
            }
        }
Exemplo n.º 37
0
 public Sort(string column, bool ascending)
 {
     this.column = column;
     this.ascending = ascending;
     this.property = CalcProperty();
 }
Exemplo n.º 38
0
 public PropertyToColumn(PropertyAccessor typedPropertyDescriptor)
 {
     Property = typedPropertyDescriptor;
     ColumnName = Property.Name;
     Property.Name = Property.Name; // TODO allow for this to differ
 }
Exemplo n.º 39
0
 public WsPropertyAccessor(PropertyAccessor propertyAccessor)
 {
     _propertyAccessor = propertyAccessor;
 }
 public TargetFailurePoint(Uri target, PropertyAccessor<StatusCode> statusProperty)
 {
     _target = target;
     _statusProperty = statusProperty;
 }
 public ProxyFailurePoint(Uri proxy, PropertyAccessor<StatusCode> statusProperty)
 {
     _proxy = proxy;
     _statusProperty = statusProperty;
 }