コード例 #1
0
        private void CreateCheckBoxes()
        {
            CheckBox Init(string title)
            {
                var checkBox = _controlFactory.Create <CheckBox>();

                checkBox.Text = title;
                checkBox.Margin.SetTopAndBottom(5);
                return(checkBox);
            }

            _encryptionCheckBox           = Init("Encryption ?");
            _encryptionCheckBox.IsChecked = true;
            _pbeCheckBox       = Init("PBE ?");
            _integrityCheckBox = Init("Integrity ?");

            var isEncryptActiveProperty = new PropertyWrapper <CryptoConfig, bool>(_config,
                                                                                   p => p.IsEncryptActive, (p, v) => p.IsEncryptActive = v);

            isEncryptActiveProperty.BindTo(_encryptionCheckBox.PropertyIsChecked);
            _encryptionCheckBox.InputState.Clicked += ToggleEncryptionSection;

            var isPbeActiveProperty = new PropertyWrapper <CryptoConfig, bool>(_config,
                                                                               p => p.IsPbeActive, (p, v) => p.IsPbeActive = v);

            isPbeActiveProperty.BindTo(_pbeCheckBox.PropertyIsChecked);
            _pbeCheckBox.InputState.Clicked += TogglePbeSection;
            _pbeCheckBox.PropertyIsChecked.PropertyChanged += OnPbeCheckBoxIsCheckedChanged;

            var isIntegrityActiveProperty = new PropertyWrapper <CryptoConfig, bool>(_config,
                                                                                     p => p.IsIntegrityActive, (p, v) => p.IsIntegrityActive = v);

            isIntegrityActiveProperty.BindTo(_integrityCheckBox.PropertyIsChecked);
            _integrityCheckBox.InputState.Clicked += ToggleIntegritySection;
        }
コード例 #2
0
        public override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            if (listAccessors == null)
            {
                if (props == null)
                {
                    /*
                     * props = new PropertyDescriptorCollection(
                     *  base.GetItemProperties(null).Cast<PropertyDescriptor>()
                     *  .Select(pd => new PropertyWrapper(pd, this)).ToArray());*/
                    props = base.GetItemProperties(null);
                    if (props == null)
                    {
                        return(null);
                    }
                    PropertyDescriptor[] arr = new PropertyDescriptor[props.Count];

                    for (int i = 0; i < props.Count; i++)
                    {
                        arr[i] = new PropertyWrapper(props[i], this);
                    }
                    props = new PropertyDescriptorCollection(arr);
                }
                return(props);
            }
            return(base.GetItemProperties(listAccessors));
        }
コード例 #3
0
        public void Test_Map_WhenHasSingleReverseRel_ShouldReturnNull()
        {
            //For the BusinessObject 'FakeBOWithReverseSingleRel'
            //If the Related Type (in this case 'FakeBOWithTwoSingleRel')
            // for the Relatiosnhip 'MySingleRelationship'
            // has a Single Relationship back 'MyReverseSingleRel'
            // then this should not be mapped as a M:1.
            //---------------Set up test pack-------------------
            var             classType        = typeof(FakeBOWithReverseSingleRel);
            var             reverseClassType = typeof(FakeBOWithTwoSingleRel);
            const string    expectedPropName = "MySingleRelationship";
            var             propertyInfo     = classType.GetProperty(expectedPropName);
            PropertyWrapper propWrapper      = propertyInfo.ToPropertyWrapper();

            //---------------Assert Precondition----------------
            classType.AssertPropertyExists(expectedPropName);
            propertyInfo.AssertIsOfType <FakeBOWithTwoSingleRel>();
            var reversePropInfo = reverseClassType.GetProperty("MyReverseSingleRel");

            Assert.IsNotNull(reversePropInfo);
            reversePropInfo.AssertIsOfType <FakeBOWithReverseSingleRel>();

            Assert.IsTrue(propWrapper.HasSingleReverseRelationship);
            Assert.IsFalse(propWrapper.HasMultipleReverseRelationship);
            //---------------Execute Test ----------------------
            var relationshipDef = propertyInfo.MapManyToOne();

            //---------------Test Result -----------------------
            Assert.IsNull(relationshipDef);
        }
コード例 #4
0
    private bool TryAddNewPair(PropertyWrapper wrapper, SerializedProperty newKey)
    {
        bool suchKeyExists = false;

        for (int i = 0; i < wrapper.Count; i++)
        {
            var curKey = wrapper.GetKeyAtIndex(i);
            if (Holder.KeysAreEqual(curKey, newKey))
            {
                suchKeyExists = true;
            }
        }

        if (!suchKeyExists)
        {
            int curSize = wrapper.Count;
            wrapper.InsertPairAtIndex(curSize);
            Holder.PutValue(wrapper.GetKeyAtIndex(curSize));
            wrapper.Apply();
            return(true);
        }
        else
        {
            CustomDebug.LogError("Key already exists " + newKey.ToString());
            return(false);
        }
    }
コード例 #5
0
        public static IReadOnlyCollection <SyntaxKind> GetModifiers(this PropertyWrapper property)
        {
            if (property.DeclaringType.TypeKind == SymbolTypeKind.Interface)
            {
                return(Array.Empty <SyntaxKind>());
            }

            var modifierList = new List <SyntaxKind>(6);

            modifierList.AddRange(AccessibilityToSyntaxKind(property.Accessibility));

            var anyGetter = property.AnyAccessor;

            if (anyGetter == null)
            {
                return(modifierList);
            }

            foreach (var value in GetModifiersList(anyGetter))
            {
                if (!modifierList.Contains(value))
                {
                    modifierList.Add(value);
                }
            }

            if (property.ReturnType is PointerWrapper)
            {
                modifierList.Add(SyntaxKind.UnsafeKeyword);
            }

            return(modifierList);
        }
コード例 #6
0
    private bool DrawOneElement(ref Rect inputRect, PropertyWrapper wrapper, int index)
    {
        Rect currentRect = RectExtention.CutRectVertical(ref inputRect, wrapper.GetElementHeight(index));

        Rect buttonRect = RectExtention.CutRectHorizontal(ref currentRect, TotalLineSpacing);

        buttonRect.width = buttonRect.height = EditorGUIUtility.singleLineHeight;
        if (GUI.Button(buttonRect, "-"))
        {
            wrapper.DeletePairAtIndex(index);
            return(false);
        }
        else
        {
            EditorGUI.BeginDisabledGroup(true);
            {
                EditorGUI.PropertyField(RectExtention.CutRectHorizontalRelative(ref currentRect, 0.3f),
                                        wrapper.GetKeyAtIndex(index),
                                        GUIContent.none,
                                        true);
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.indentLevel++;
            {
                EditorGUI.PropertyField(currentRect,
                                        wrapper.GetValueAtIndex(index),
                                        GUIContent.none,
                                        true);
            }
            EditorGUI.indentLevel--;

            return(true);
        }
    }
コード例 #7
0
        public override string CreateUpdate(ChangedObject obj)
        {
            ClassWrapper currentClassWrapper = wrappingHandler.GetClassWrapper(obj.RuntimeObject.GetType());

            string result = "UPDATE ";

            result += currentClassWrapper.Name;

            result += " SET ";

            string delimiter = "";

            foreach (var elm in obj.GetChangedFields())
            {
                PropertyWrapper currentFieldWrapper = currentClassWrapper.GetFieldWrapper(elm.Key);

                result += delimiter + currentFieldWrapper.Name;
                result += " = ";
                //            result += normalizeValueForInsertStatement(currentFieldWrapper.getOriginalField().getType(), elm.getValue());
                result += fieldTypeParser.NormalizeValueForInsertStatement(elm.Value);

                if (delimiter == "")
                {
                    delimiter = " , ";
                }
            }

            result += " WHERE ";
            result += currentClassWrapper.GetPrimaryKeyMember().Name + " = ";
            result += "'" + obj.RuntimeObject.ID + "'";


            return(result);
        }
コード例 #8
0
        public void Wrapper_PropertyNameExposedThroughNameProperty()
        {
            var propertyWrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            // this should match the name of whatever property is accessed in the lambda above
            CheckName("Property1", propertyWrapper);
        }
コード例 #9
0
        private string GetPropertyCodeLine(PropertyWrapper wrapper)
        {
            string jsPropName = wrapper.Name.DecapitalizeFirstLetter();
            string line       = $"{PropIndent}{jsPropName};";

            return(line);
        }
コード例 #10
0
 private void DoRebuild()
 {
     lock (this)
     {
         if (!_needsRebuild || ParentContainer == null)
         {
             return;
         }
         bool hasCallback = false;
         HasDecision = !string.IsNullOrEmpty(ConditionID);
         DoDestroy();
         _propWrapper = PropertyWrapper.Create(GetFullID(), typeof(bool), OnPropertyChanged);
         if (_propWrapper != null && _propWrapper.Target is CompBase)
         {
             _propertyExpression = _propWrapper.GetGetPropExpression <bool>() as Expression <Func <bool> >;
             if (_propertyExpression != null)
             {
                 U.RegisterOnChanged(_propertyExpression, OnBoolPropertyChanged);
                 //(_propWrapper.Target as CompBase).RegisterOnChanged(_propertyExpression, OnBoolPropertyChanged);
                 hasCallback = true;
             }
             else
             {
                 _propWrapper = null;
             }
         }
         HasCallback   = hasCallback;
         _needsRebuild = false;
     }
 }
コード例 #11
0
        public void Test_Map_WhenHasMultipleReverseRel_ShouldReturnRel_WithReverseRelNameSet()
        {
            //For the BusinessObject 'FakeBOWithUndefinableSingleRel'
            //If the Related Type (in this case 'FakeBOWithSingleAndMultipleRelToSameType')
            // for the Relatiosnhip 'MySingleRelWithOneToManyAttribute'
            // and has a Multiple Reverse Relationship 'MyMultipleRevRel'
            // then it should create the Relationship
            //---------------Set up test pack-------------------
            var             classType        = typeof(FakeBOWithUndefinableSingleRel);
            var             reverseClassType = typeof(FakeBOWithSingleAndMultipleRelToSameType);
            const string    expectedPropName = "MySingleRelWithOneToManyAttribute";
            var             propertyInfo     = classType.GetProperty(expectedPropName);
            PropertyWrapper propWrapper      = propertyInfo.ToPropertyWrapper();

            //---------------Assert Precondition----------------
            classType.AssertPropertyExists(expectedPropName);
            propertyInfo.AssertIsOfType(reverseClassType);
            var reversePropInfo = reverseClassType.GetProperty("MySingleRevRel");

            Assert.IsNotNull(reversePropInfo);
            reversePropInfo.AssertIsOfType <FakeBOWithUndefinableSingleRel>();

            Assert.IsTrue(propWrapper.HasMultipleReverseRelationship);
            Assert.IsTrue(propWrapper.HasAttribute <AutoMapManyToOneAttribute>());
            //---------------Execute Test ----------------------
            var relationshipDef = propertyInfo.MapManyToOne();

            //---------------Test Result -----------------------
            Assert.IsNotNull(relationshipDef);
            Assert.AreEqual("MyMultipleRevRel", relationshipDef.ReverseRelationshipName);
        }
コード例 #12
0
ファイル: ParserHandler.cs プロジェクト: parreirinha/AVE
        public void AddProp(string name, int col)
        {
            if (parsers.ContainsKey(name))
            {
                throw new PropertyException("Allready constains a property with that name");
            }
            if (!Array.Exists(pi, p => p.Name == name))
            {
                throw new PropertyException($"No such property found in {type.Name}");
            }

            CsvBasicInfo    bInfo    = new CsvBasicInfo(type, name, col, separator);
            PropertyInfo    pInfo    = type.GetProperty(name);
            Type            propType = pInfo.PropertyType;                      // prop Type
            PropertyWrapper pw;
            IReflection     reflect;

            if (ReflectorsCache.cache.TryGetValue(propType, out reflect))
            {
                // if reflect of type propType exists, get it from cache
                pw = new PropertyWrapper((PropertyReflect)reflect, bInfo);
                parsers.Add(name, pw);
            }
            else
            {
                //if not build a new onde, add to cache and create PropertyWrapper
                //and add it to parsers Dictionary
                PropertyReflect pr = new PropertyReflect(propType);
                ReflectorsCache.cache.Add(propType, pr);
                pw = new PropertyWrapper(pr, bInfo);
                parsers.Add(name, pw);
            }
        }
コード例 #13
0
        public static void AssertHasAttribute <T>(this PropertyInfo propertyInfo) where T : class
        {
            PropertyWrapper propertyWrapper = propertyInfo.ToPropertyWrapper();

            Assert.IsTrue(propertyWrapper.HasAttribute <T>()
                          , propertyWrapper.Name + string.Format(" does not have a '{0}' attribute", typeof(T)));
        }
コード例 #14
0
        private Tuple <PropertyWrapper, CableProperties.Direction, object> OnPropertyGUI(CableProperties.Direction dir,
                                                                                         CableProperties properties,
                                                                                         GUISkin skin)
        {
            Tuple <PropertyWrapper, CableProperties.Direction, object> changed = null;
            var data = EditorData.Instance.GetData(properties, "CableProperty" + dir.ToString());

            if (GUI.Foldout(data, GUI.MakeLabel(dir.ToString()), skin))
            {
                using (new GUI.Indent(12)) {
                    GUI.Separator();

                    var wrappers = PropertyWrapper.FindProperties <CableProperty>(System.Reflection.BindingFlags.Instance |
                                                                                  System.Reflection.BindingFlags.Public);
                    foreach (var wrapper in wrappers)
                    {
                        if (wrapper.GetContainingType() == typeof(float) && InspectorEditor.ShouldBeShownInInspector(wrapper.Member))
                        {
                            var value = EditorGUILayout.FloatField(InspectorGUI.MakeLabel(wrapper.Member),
                                                                   wrapper.Get <float>(properties[dir]));
                            if (UnityEngine.GUI.changed)
                            {
                                changed = new Tuple <PropertyWrapper, CableProperties.Direction, object>(wrapper, dir, value);
                                UnityEngine.GUI.changed = false;
                            }
                        }
                    }
                }
            }
            return(changed);
        }
コード例 #15
0
        public static void AssertHasAttribute <TRelAttribute>(this PropertyWrapper relProp, Func <TRelAttribute, bool> expr) where TRelAttribute : AutoMapRelationshipAttribute
        {
            var customRelationship = relProp.GetAttributes <TRelAttribute>();

            Assert.IsTrue(customRelationship.Any(expr),
                          relProp.Name + " on " + relProp.DeclaringClassName + " should have an AutoMapRelationshipAttribute attribute matching ???");
        }
コード例 #16
0
        public static void AssertHasAutoMapReverseRelationship(PropertyWrapper relProp, string reverseRelName)
        {
            var customRelationship = relProp.GetAttributes <AutoMapRelationshipAttribute>();

            Assert.IsTrue(customRelationship.Any(o => (o.ReverseRelationshipName == reverseRelName)),
                          relProp.Name + " on " + relProp.DeclaringClassName + " should have an AutoMapRelationshipAttribute attribute");
        }
コード例 #17
0
        /// <summary>
        /// Writes a property container the specified buffer.
        /// </summary>
        /// <param name="writer">The buffer to write the object to.</param>
        /// <param name="value">The container to write.</param>
        /// <param name="parameters">The parameters to use when writing.</param>
        /// <typeparam name="T">The type to serialize.</typeparam>
        public static void ToJson <T>(JsonWriter writer, T value, JsonSerializationParameters parameters = default)
        {
            var container = new PropertyWrapper <T>(value);

            var serializedReferences = default(SerializedReferences);
            var state = parameters.State ?? (parameters.RequiresThreadSafety ? new JsonSerializationState() : GetSharedState());

            if (!parameters.DisableSerializedReferences)
            {
                serializedReferences = state.GetSerializedReferences();
                var serializedReferenceVisitor = state.GetSerializedReferenceVisitor();
                serializedReferenceVisitor.SetSerializedReference(serializedReferences);
                PropertyContainer.Accept(serializedReferenceVisitor, ref container);
            }

            var visitor = state.GetJsonPropertyWriter();

            visitor.SetWriter(writer);
            visitor.SetSerializedType(parameters.SerializedType);
            visitor.SetDisableRootAdapters(parameters.DisableRootAdapters);
            visitor.SetGlobalAdapters(GetGlobalAdapters());
            visitor.SetUserDefinedAdapters(parameters.UserDefinedAdapters);
            visitor.SetGlobalMigrations(GetGlobalMigrations());
            visitor.SetUserDefinedMigration(parameters.UserDefinedMigrations);
            visitor.SetSerializedReferences(serializedReferences);

            using (visitor.Lock()) PropertyContainer.Accept(visitor, ref container);
        }
コード例 #18
0
 protected static List <PropertyWrapper> GetWrappers(Type type)
 {
     if (!mProp2Actions.ContainsKey(type))
     {
         List <PropertyWrapper> wrappers = new List <PropertyWrapper>();
         mProp2Actions.Add(type, wrappers);
         PropertyInfo[] props = type.GetProperties();
         TypeParams[0] = type;
         foreach (PropertyInfo prop in props)
         {
             MethodInfo      setMethod = prop.GetSetMethod(true);
             PropertyWrapper wrapper   = new PropertyWrapper();
             wrapper.Name         = prop.Name;
             wrapper.PropertyType = prop.PropertyType;
             try
             {
                 TypeParams[1] = prop.PropertyType;
                 var act = typeof(Action <,>).MakeGenericType(TypeParams);
                 wrapper.Action = Delegate.CreateDelegate(act, null, setMethod);
                 wrappers.Add(wrapper);
             }
             catch (Exception e)
             {
                 DebugUtils.Log(InfoType.Error, e.Message + e.StackTrace);
             }
         }
     }
     return(mProp2Actions[type]);
 }
コード例 #19
0
        /// <summary>
        /// Writes a property container the specified buffer.
        /// </summary>
        /// <param name="buffer">The buffer to write the object to.</param>
        /// <param name="value">The container to write.</param>
        /// <param name="parameters">The parameters to use when writing.</param>
        /// <typeparam name="T">The type to serialize.</typeparam>
        public static void ToJson <T>(JsonStringBuffer buffer, T value, JsonSerializationParameters parameters = default)
        {
            var container = new PropertyWrapper <T>(value);

            var serializedReferences = default(SerializedReferences);

            if (!parameters.DisableSerializedReferences)
            {
                serializedReferences = parameters.RequiresThreadSafety ? new SerializedReferences() : GetSharedSerializedReferences();
                var serializedReferenceVisitor = parameters.RequiresThreadSafety ? new SerializedReferenceVisitor() : GetSharedSerializedReferenceVisitor();
                serializedReferenceVisitor.SetSerializedReference(serializedReferences);
                PropertyContainer.Visit(ref container, serializedReferenceVisitor);
            }

            var visitor = parameters.RequiresThreadSafety || s_SharedJsonPropertyWriter.IsLocked ? new JsonPropertyWriter() : GetSharedJsonPropertyWriter();

            visitor.SetStringWriter(buffer);
            visitor.SetSerializedType(parameters.SerializedType);
            visitor.SetDisableRootAdapters(parameters.DisableRootAdapters);
            visitor.SetGlobalAdapters(GetGlobalAdapters());
            visitor.SetUserDefinedAdapters(parameters.UserDefinedAdapters);
            visitor.SetGlobalMigrations(GetGlobalMigrations());
            visitor.SetUserDefinedMigration(parameters.UserDefinedMigrations);
            visitor.SetSerializedReferences(serializedReferences);
            visitor.SetMinified(parameters.Minified);
            visitor.SetSimplified(parameters.Simplified);

            using (visitor.Lock()) PropertyContainer.Visit(ref container, visitor);
        }
コード例 #20
0
 public PropertyUpdater(PropertyWrapper <T> prop, T src, T targ, float durTime, GetValAtUpdate getValAtUpdate)
 {
     this.prop           = prop;
     this.src            = src;
     this.targ           = targ;
     this.durTime        = durTime;
     this.getValAtUpdate = getValAtUpdate;
 }
コード例 #21
0
 ///<summary>
 /// Construct a One to One Relationship mapper.
 ///</summary>
 ///<param name="propWrap"></param>
 ///<exception cref="ArgumentNullException"></exception>
 public OneToOneAutoMapper(PropertyWrapper propWrap)
 {
     if (propWrap == null)
     {
         throw new ArgumentNullException("propWrap");
     }
     this.PropertyWrapper = propWrap;
 }
コード例 #22
0
    public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
    {
        PropertyWrapper  propertyWrapper  = (PropertyWrapper)item;
        FrameworkElement frameworkElement = (FrameworkElement)container;
        DataTemplate     dataTemplate     = (DataTemplate)frameworkElement.TryFindResource(propertyWrapper.PropertyType);

        return(dataTemplate);
    }
コード例 #23
0
 /// <summary>
 /// Construct the AutoMapper for a specified propertyWrapper.
 /// </summary>
 /// <param name="propertyWrapper"></param>
 public OneToManyAutoMapper(PropertyWrapper propertyWrapper)
 {
     if (propertyWrapper == null)
     {
         throw new ArgumentNullException("propertyWrapper");
     }
     this.PropertyWrapper = propertyWrapper;
 }
コード例 #24
0
 /// <summary>
 /// Construct the AutoMapper for a specified PropertyInfo.
 /// </summary>
 /// <param name="propInfo"></param>
 public OneToManyAutoMapper(PropertyInfo propInfo)
 {
     if (propInfo == null)
     {
         throw new ArgumentNullException("propInfo");
     }
     this.PropertyWrapper = propInfo.ToPropertyWrapper();
 }
コード例 #25
0
        public void TestFieldType()
        {
            PropertyWrapper wrapper1 = new PropertyWrapper(typeof(DummyClass).GetProperty(nameof(DummyClass.b1)));
            PropertyWrapper wrapper2 = new PropertyWrapper(typeof(DummyClass).GetProperty(nameof(DummyClass.i)));

            Assert.Same(typeof(bool), wrapper1.FieldType);
            Assert.Same(typeof(int), wrapper2.FieldType);
        }
コード例 #26
0
 /// <summary>
 /// Returns the Related Property name.
 /// </summary>
 /// <returns></returns>
 public string GetRelatedPropName()
 {
     if (this.PropertyWrapper.HasSingleReverseRelationship)
     {
         PropertyWrapper reverseRelPropInfo = this.PropertyWrapper.GetSingleReverseRelPropInfos()[0];
         return(PropNamingConvention.GetSingleRelOwningPropName(reverseRelPropInfo.Name));
     }
     return(GetOwningPropName(this.PropertyWrapper.DeclaringType));
 }
コード例 #27
0
        public void Wrapper_Copy_CopyReadonlyPropertyThrows()
        {
            var propertyWrapper = new PropertyWrapper<TestObjectWithReadonlyProperty, int>(o => o.ReadonlyProperty);

            var instance1 = new TestObjectWithReadonlyProperty();
            var instance2 = new TestObjectWithReadonlyProperty();

            propertyWrapper.Copy(instance1, instance2);
        }
コード例 #28
0
 public string GenerateForeignKeyDefinition(PropertyWrapper wr)
 {
     if (wr.IsForeignKey())
     {
         return(" FOREIGN KEY(" + wr.Name + ") REFERENCES " + wr.GetForeignKey().AssociationPartnerClass.Name
                + "(" + wr.GetForeignKey().ReferencingPrimaryKeyName + ") ");
     }
     return("");
 }
コード例 #29
0
        public void Create <TProperty>(string name, out IProperty <TProperty> property, TProperty defValue = default)
        {
            var args = PropertyArgsStore <T> .GetArgs <TProperty>(name);

            var wrapper = new PropertyWrapper <TProperty>(_notifier, args, defValue);

            property = wrapper.Property;
            AddProperty(name, wrapper);
        }
コード例 #30
0
        public void TestSetValue__Private()
        {
            PropertyInfo    property = typeof(DummyClass).GetProperty(nameof(DummyClass.b3));
            PropertyWrapper wrapper2 = new PropertyWrapper(property);
            DummyClass      c        = new DummyClass();

            wrapper2.SetValue(c, true);
            Assert.Equal(true, c.b3);
        }
コード例 #31
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_AreEqual_CustomComparer_WorksProperly()
        {
            var property3Wrapper = new PropertyWrapper<MergeTestObject, string>(o => o.Property3, new SoftStringEqualityComparer(StringComparisonOptions.CaseInsensitive));

            var instance1 = new MergeTestObject()
            {
                Property3 = "foo"
            };

            var instance2 = new MergeTestObject()
            {
                Property3 = "FOO"
            };

            Conflict conflict;
            Assert.IsTrue(property3Wrapper.AreEqual(instance1, instance2, out conflict));
        }
コード例 #32
0
 private void SetStringLengthPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper,int minLength,int maxLength)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapStringLengthPropRuleAttribute>()).Return(
            new AutoMapStringLengthPropRuleAttribute(minLength,maxLength));
     wrapper.Stub(propertyWrapper => propertyWrapper.HasStringLengthRuleAttribute).Return(true);
 }
コード例 #33
0
 private static void AssertMockPropSetupCorrectly(PropertyWrapper propertyWrapper, TypeWrapper ownerType, TypeWrapper relatedType, string relationshipName, string reverseRelName)
 {
     Assert.AreEqual(reverseRelName, propertyWrapper.GetSingleReverseRelationshipName<AutoMapOneToOneAttribute>());
     Assert.AreSame(ownerType, propertyWrapper.DeclaringType);
     Assert.AreSame(relatedType, propertyWrapper.RelatedClassType);
     Assert.AreEqual(relationshipName, propertyWrapper.Name);
 }
コード例 #34
0
        /// <summary>
        ///     Main executor function.
        /// </summary>
        /// <returns>A CodeCompileUnit.</returns>
        public CodeCompileUnit Execute()
        {
            var codeCompileUnit = new CodeCompileUnit();

            // Set namespace
            var nsWrap = new NamespaceWrapper(new CodeNamespace(_codeNamespace));

            // Set class
            var codeClass = new CodeTypeDeclaration(_schemaDocument.Title) {Attributes = MemberAttributes.Public};
            var clWrap = new ClassWrapper(codeClass);

            // Add imports for interfaces and dependencies
            nsWrap.AddImportsFromWrapper(_schemaWrapper);

            // Add comments and attributes for class
            if (!String.IsNullOrEmpty(_schemaDocument.Description))
            {
                clWrap.AddComment(_schemaDocument.Description);
            }

            // Add extended class
            if (_schemaDocument.Extends != null && _schemaDocument.Extends.Count > 0)
            {
                clWrap.AddInterface(JsonSchemaUtils.GetType(_schemaDocument.Extends[0], _codeNamespace).Name);
            }

            // Add interfaces
            foreach (Type t in _schemaWrapper.Interfaces)
            {
                clWrap.AddInterface(t.Name);
            }

            // Add properties with getters/setters
            if (_schemaDocument.Properties != null)
            {
                foreach (var i in _schemaDocument.Properties)
                {
                    JsonSchema schema = i.Value;

                    // Sanitize inputs
                    if (!String.IsNullOrEmpty(schema.Description))
                    {
                        schema.Description = Regex.Unescape(schema.Description);
                    }

                    // If it is an enum
                    var propertyName = i.Key.Capitalize();
                    if (schema.Enum != null)
                    {
                        var enumField = new CodeTypeDeclaration(propertyName);
                        var enumWrap = new EnumWrapper(enumField);

                        // Add comment if not null
                        if (!String.IsNullOrEmpty(schema.Description))
                        {
                            enumField.Comments.Add(new CodeCommentStatement(schema.Description));
                        }

                        foreach (JToken j in schema.Enum)
                        {
                            enumWrap.AddMember(j.ToString().SanitizeIdentifier());
                        }

                        // Add to namespace
                        nsWrap.AddClass(enumWrap.Property);
                    }
                    else
                    {
                        // WARNING: This assumes the namespace of the property is the same as the parent.
                        // This should not be a problem since imports are handled for all dependencies at the beginning.
                        Type type = JsonSchemaUtils.GetType(schema, _codeNamespace);
                        bool isCustomType = type.Namespace != null && type.Namespace.Equals(_codeNamespace);
                        string strType = String.Empty;

                        // Add imports
                        nsWrap.AddImport(type.Namespace);
                        nsWrap.AddImportsFromSchema(schema);

                        // Get the property type
                        if (isCustomType)
                        {
                            strType = JsonSchemaUtils.IsArray(schema) ? string.Format("{0}<{1}>", JsonSchemaUtils.GetArrayType(schema), type.Name) : type.Name;
                        }
                        else if (JsonSchemaUtils.IsArray(schema))
                        {
                            strType = string.Format("{0}<{1}>", JsonSchemaUtils.GetArrayType(schema),
                                new CSharpCodeProvider().GetTypeOutput(new CodeTypeReference(type)));
                        }

                        //var field = new CodeMemberField
                        //{
                        //    Attributes = MemberAttributes.Private,
                        //    Name = "_" + i.Key,
                        //    Type =
                        //        TypeUtils.IsPrimitive(type) && !JsonSchemaUtils.IsArray(schema)
                        //            ? new CodeTypeReference(type)
                        //            : new CodeTypeReference(strType)
                        //};


                        //clWrap.Property.Members.Add(field);

                        var property = CreateProperty(propertyName, TypeUtils.IsPrimitive(type) && !JsonSchemaUtils.IsArray(schema)
                                    ? new CodeTypeReference(type)
                                    : new CodeTypeReference(strType));

                        var prWrap = new PropertyWrapper(property);

                        // Add comments and attributes
                        prWrap.Populate(schema, _attributeType);

                        // Add default, if any
                        if (schema.Default != null)
                        {
                            clWrap.AddDefault(propertyName, property.Type, schema.Default.ToString());
                        }

                        clWrap.Property.Members.Add(property);
                    }
                }
            }

            // Add class to namespace
            nsWrap.AddClass(clWrap.Property);
            codeCompileUnit.Namespaces.Add(nsWrap.Namespace);

            return codeCompileUnit;
        }
コード例 #35
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_IsReadonly()
        {
            var wrapper = new PropertyWrapper<TestObjectWithReadonlyProperty, int>(o => o.ReadonlyProperty);

            Assert.IsTrue(wrapper.IsReadonly);
        }
コード例 #36
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_Copy_OnlyWrappedPropertiesCopied()
        {
            var propertyWrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            var instance1 = new MergeTestObject()
            {
                Property1 = 1
            };

            var canary = 666;
            var instance2 = new MergeTestObject()
            {
                Property2 = canary,
                Property3 = canary.ToString()
            };

            propertyWrapper.Copy(instance1, instance2);

            Assert.AreEqual(canary, instance2.Property2);
            Assert.AreEqual(canary.ToString(), instance2.Property3);
        }
コード例 #37
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_AreEqual_ReturnsTrueAndNullConflict()
        {
            var property1Wrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            var instance1 = new MergeTestObject()
            {
                Property1 = 1
            };

            var instance2 = new MergeTestObject()
            {
                Property1 = instance1.Property1
            };

            Conflict conflict;
            Assert.IsTrue(property1Wrapper.AreEqual(instance1, instance2, out conflict));
            Assert.IsNull(conflict);
        }
コード例 #38
0
 /// <summary>
 /// Construct the AutoMapper for a specified PropertyInfo.
 /// </summary>
 /// <param name="propInfo"></param>
 public OneToManyAutoMapper(PropertyInfo propInfo)
 {
     if (propInfo == null) throw new ArgumentNullException("propInfo");
     this.PropertyWrapper = propInfo.ToPropertyWrapper();
 }
コード例 #39
0
 private static void SetStringPatternMatchPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper, string emailPatternMatch)
 {
     SetStringPatternMatchPropRuleAttributeWithDefaultConstructor(wrapper, emailPatternMatch, "");
 }
コード例 #40
0
 private static void SetIntPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapIntPropRuleAttribute>()).Return(
             new AutoMapIntPropRuleAttribute());
     wrapper.Stub(propertyWrapper => propertyWrapper.HasIntPropRuleAttribute).Return(true);
 }
コード例 #41
0
ファイル: GetMemberNode.cs プロジェクト: menozz/lens
        /// <summary>
        /// Attempts to resolve current node and sets either of the following fields:
        /// _Field, _Method, _Property
        /// 
        /// The following fields are also set:
        /// _Type, _Static
        /// </summary>
        private void resolveSelf(Context ctx)
        {
            Action check = () =>
            {
                if (Expression == null && !_IsStatic)
                    error(CompilerMessages.DynamicMemberFromStaticContext, _Type, MemberName);

                if (_Method == null && TypeHints.Count > 0)
                    error(CompilerMessages.TypeArgumentsForNonMethod, _Type, MemberName);
            };

            _Type = StaticType != null
                ? ctx.ResolveType(StaticType)
                : Expression.Resolve(ctx);

            // special case: array length
            if (_Type.IsArray && MemberName == "Length")
            {
                check();
                return;
            }

            // check for field
            try
            {
                _Field = ctx.ResolveField(_Type, MemberName);
                _IsStatic = _Field.IsStatic;

                check();
                return;
            }
            catch (KeyNotFoundException) { }

            // check for property
            try
            {
                _Property = ctx.ResolveProperty(_Type, MemberName);

                if(!_Property.CanGet)
                    error(CompilerMessages.PropertyNoGetter, _Type, MemberName);

                _IsStatic = _Property.IsStatic;

                check();
                return;
            }
            catch (KeyNotFoundException) { }

            // check for event: events are only allowed at the left side of += and -=
            try
            {
                ctx.ResolveEvent(_Type, MemberName);
                error(CompilerMessages.EventAsExpr);
            }
            catch (KeyNotFoundException) { }

            // find method
            var argTypes = TypeHints.Select(t => t.FullSignature == "_" ? null : ctx.ResolveType(t)).ToArray();
            var methods = ctx.ResolveMethodGroup(_Type, MemberName).Where(m => checkMethodArgs(argTypes, m)).ToArray();

            if (methods.Length == 0)
                error(argTypes.Length == 0 ? CompilerMessages.TypeIdentifierNotFound : CompilerMessages.TypeMethodNotFound, _Type.Name, MemberName);

            if (methods.Length > 1)
                error(CompilerMessages.TypeMethodAmbiguous, _Type.Name, MemberName);

            _Method = methods[0];
            if (_Method.ArgumentTypes.Length > 16)
                error(CompilerMessages.CallableTooManyArguments);

            _IsStatic = _Method.IsStatic;

            check();
        }
コード例 #42
0
 private static void SetShortPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper, short minValue, short maxValue)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapShortPropRuleAttribute>()).Return(
             new AutoMapShortPropRuleAttribute(minValue, maxValue));
     wrapper.Stub(propertyWrapper => propertyWrapper.HasShortPropRuleAttribute).Return(true);
 }
コード例 #43
0
 private static void SetStringPatternMatchPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper, string regexPattern, string message)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapStringPatternMatchPropRuleAttribute>()).Return(
           new AutoMapStringPatternMatchPropRuleAttribute(regexPattern, message));
     wrapper.Stub(propertyWrapper => propertyWrapper.HasStringPatternMatchRuleAttribute).Return(true);
 }
コード例 #44
0
 /// <summary>
 /// Constructs the Property Automapper for a particular <see cref="ReflectionWrappers.PropertyWrapper"/>
 /// where a PropertyWrapper typically wraps a <see cref="PropertyInfo"/> and provides additional methods.
 /// </summary>
 /// <param name="propertyWrapper"></param>
 public PropertyAutoMapper(PropertyWrapper propertyWrapper)
 {
     if (propertyWrapper == null) throw new ArgumentNullException("propertyWrapper");
     this.PropertyWrapper = propertyWrapper;
 }
コード例 #45
0
ファイル: ForeachNode.cs プロジェクト: impworks/lens
        /// <summary>
        /// Calculates the variable type and other required values for enumeration of an IEnumerable`1.
        /// </summary>
        private void detectEnumerableType(Context ctx)
        {
            var seqType = IterableExpression.Resolve(ctx);
            if (seqType.IsArray)
            {
                _VariableType = seqType.GetElementType();
                return;
            }

            var ifaces = seqType.ResolveInterfaces();
            if (seqType.IsInterface)
                ifaces = ifaces.Union(new[] { seqType }).ToArray();

            var generic = ifaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>));
            if (generic != null)
                _EnumeratorType = typeof(IEnumerator<>).MakeGenericType(generic.GetGenericArguments()[0]);

            else if (ifaces.Contains(typeof(IEnumerable)))
                _EnumeratorType = typeof(IEnumerator);

            else
                error(IterableExpression, CompilerMessages.TypeNotIterable, seqType);

            _CurrentProperty = ctx.ResolveProperty(_EnumeratorType, "Current");
            _VariableType = _CurrentProperty.PropertyType;
        }
コード例 #46
0
ファイル: ActionData.cs プロジェクト: cyotek/translateclient
 public void Dispose()
 {
     Detach(component.Site.DesignMode);
     textWrapper.Detach();
     textWrapper = null;
     enabledWrapper.Detach();
     enabledWrapper = null;
     checkedWrapper.Detach();
     checkedWrapper = null;
     visibleWrapper.Detach();
     visibleWrapper = null;
 }
コード例 #47
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_AreEqual_ReturnsFalseAndConflictHasProperValues()
        {
            var property1Wrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            var instance1 = new MergeTestObject()
            {
                Property1 = 1
            };

            var instance2 = new MergeTestObject()
            {
                Property1 = 2
            };

            Conflict conflict;
            Assert.IsFalse(property1Wrapper.AreEqual(instance1, instance2, out conflict));

            Assert.IsNotNull(conflict);
            Assert.AreEqual("Property1", conflict.PropertyName);    // the property name in the lambda above
            Assert.AreEqual(instance1.Property1.ToString(), conflict.SourceValue);
            Assert.AreEqual(instance2.Property1.ToString(), conflict.DestinationValue);
        }
コード例 #48
0
 private static void SetReadWriteAttribute(PropertyWrapper wrapper, PropReadWriteRule rule)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapReadWriteRuleAttribute>()).Return(
             new AutoMapReadWriteRuleAttribute(rule));
     wrapper.Stub(propertyWrapper => propertyWrapper.HasReadWriteRuleAttribute).Return(true);
 }
コード例 #49
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_Copy_CopyReadonlyPropertyThrows()
        {
            var propertyWrapper = new PropertyWrapper<TestObjectWithReadonlyProperty, int>(o => o.ReadonlyProperty);

            var instance1 = new TestObjectWithReadonlyProperty();
            var instance2 = new TestObjectWithReadonlyProperty();

            propertyWrapper.Copy(instance1, instance2);
        }
コード例 #50
0
 private static void SetHasDisplayNameAttribute(PropertyWrapper wrapper, bool hasDisplayName, string displayName)
 {
     wrapper.Stub(wrapper1 => wrapper1.HasDisplayNameAttribute).Return(hasDisplayName);
     if (hasDisplayName)
     {
         wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapDisplayNameAttribute>()).Return(
             new AutoMapDisplayNameAttribute(displayName));
     }
 }
コード例 #51
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_Copy_ValueCopied()
        {
            var propertyWrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            var instance1 = new MergeTestObject()
            {
                Property1 = 1
            };

            var instance2 = new MergeTestObject();

            propertyWrapper.Copy(instance1, instance2);

            Assert.AreEqual(instance1.Property1, instance2.Property1);
        }
コード例 #52
0
 private static void AssertHasOneToOneWithReverseRelationship(PropertyWrapper propertyInfo, string expectedRevRelName)
 {
     Assert.IsTrue(propertyInfo.HasAutoMapOneToOneAttribute(expectedRevRelName), string.Format("Should have AutoMapOneToOne with ReverseRelationship '{0}'", expectedRevRelName));
 }
コード例 #53
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_PropertyNameExposedThroughNameProperty()
        {
            var propertyWrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);

            // this should match the name of whatever property is accessed in the lambda above
            CheckName("Property1", propertyWrapper);
        }
コード例 #54
0
 private static void SetHasDefaultAttribute(PropertyWrapper wrapper, bool hasDefault, string defaultValue)
 {
     wrapper.Stub(wrapper1 => wrapper1.HasDefaultAttribute).Return(hasDefault);
     if(hasDefault)
     {
         wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapDefaultAttribute>()).Return(
             new AutoMapDefaultAttribute(defaultValue));
     }
 }
コード例 #55
0
ファイル: PropertyWrapperTests.cs プロジェクト: vermie/Merger
        public void Wrapper_AreEqual_DefaultComparer_WorksProperly()
        {
            var property1Wrapper = new PropertyWrapper<MergeTestObject, int>(o => o.Property1);
            var property3Wrapper = new PropertyWrapper<MergeTestObject, string>(o => o.Property3);

            var instance1 = new MergeTestObject()
            {
                Property1 = 1,
                Property3 = "foo"
            };

            var instance2 = new MergeTestObject()
            {
                Property1 = instance1.Property1,
                Property3 = instance1.Property3
            };

            Conflict conflict;
            Assert.IsTrue(property1Wrapper.AreEqual(instance1, instance2, out conflict));
            Assert.IsTrue(property3Wrapper.AreEqual(instance1, instance2, out conflict));
        }
コード例 #56
0
 /// <summary>
 /// If the <paramref name="propertyWrapper"/> is defined as Composition or Aggregation via attributes then return true.
 /// </summary>
 /// <param name="propertyWrapper"></param>
 /// <returns></returns>
 private static bool IsDefinedAsCompositionOrAggregation(PropertyWrapper propertyWrapper)
 {
     if(propertyWrapper == null) return false;
     var autoMapAttribute = propertyWrapper.GetAttribute<AutoMapOneToOneAttribute>();
     if (autoMapAttribute == null) return false;
     return (autoMapAttribute.RelationshipType != RelationshipType.Association);
 }
コード例 #57
0
 private AutoMapOneToOneAttribute GetAutomapAttribute(PropertyWrapper propertyWrapper)
 {
     return propertyWrapper.GetAttribute<AutoMapOneToOneAttribute>();
 }
コード例 #58
0
 ///<summary>
 /// Construct a One to One Relationship mapper.
 ///</summary>
 ///<param name="propWrap"></param>
 ///<exception cref="ArgumentNullException"></exception>
 public OneToOneAutoMapper(PropertyWrapper propWrap)
 {
     if (propWrap == null) throw new ArgumentNullException("propWrap");
     this.PropertyWrapper = propWrap;
 }
コード例 #59
0
        private static void SetupMockPropWrapper(PropertyWrapper propertyWrapper, TypeWrapper ownerType, TypeWrapper relatedType, string relationshipName, string reverseRelName)
        {
            propertyWrapper.SetName(relationshipName);
            propertyWrapper.SetDeclaringType(ownerType);
            propertyWrapper.SetOneToOneReverseRelName(reverseRelName);
            propertyWrapper.SetRelatedType(relatedType);
            propertyWrapper.Stub(wrapper => wrapper.HasSingleReverseRelationship).Return(true);
            propertyWrapper.Stub(wrapper1 => wrapper1.IsPublic).Return(true);

            propertyWrapper.Stub(wrapper => wrapper.PropertyInfo).Return(MockRepository.GenerateMock<FakePropertyInfo>());
        }
コード例 #60
0
 private void SetDateTimeStringPropRuleAttributeWithDefaultConstructor(PropertyWrapper wrapper, string startDate, string endDate)
 {
     wrapper.Stub(propertyWrapper => propertyWrapper.GetAttribute<AutoMapDateTimePropRuleAttribute>()).Return(
            new AutoMapDateTimePropRuleAttribute(startDate, endDate));
     wrapper.Stub(propertyWrapper => propertyWrapper.HasDateTimeStringRuleAttribute).Return(true);
 }