コード例 #1
0
        public void HaveAConstructorThatTakesTypeNameAndBaseType()
        {
            var className = "ClassA";
            var baseType  = typeof(List <string>);

            _typeExtender = new TypeExtender(className, baseType);

            Assert.AreEqual(className, _typeExtender.TypeName);
            Assert.AreEqual(baseType, _typeExtender.BaseType);
        }
コード例 #2
0
ファイル: TypeExtenderTest.cs プロジェクト: 5l1v3r1/Aphid
 public void Extend01(
     [PexAssumeUnderTest] TypeExtender target,
     string type,
     AphidObject extensions,
     string ctorHandler,
     string dynamicHandler
     )
 {
     target.Extend(type, extensions, ctorHandler, dynamicHandler);
     // TODO: add assertions to method TypeExtenderTest.Extend01(TypeExtender, String, AphidObject, String, String)
 }
コード例 #3
0
ファイル: TypeExtenderTest.cs プロジェクト: 5l1v3r1/Aphid
 public void ExtendTest(
     [PexAssumeUnderTest] TypeExtender target,
     IdentifierExpression type,
     AphidObject extensions,
     string ctorHandler,
     string dynamicHandler
     )
 {
     target.Extend(type, extensions, ctorHandler, dynamicHandler);
     // TODO: add assertions to method TypeExtenderTest.ExtendTest(TypeExtender, IdentifierExpression, AphidObject, String, String)
 }
コード例 #4
0
        public void ReturnATypeWithThePassedName()
        {
            var className = "ClassA";

            _typeExtender = new TypeExtender(className);

            var returnedClass = _typeExtender.FetchType();
            var name          = returnedClass.Name;

            Assert.AreEqual(className, name);
        }
コード例 #5
0
        /// <summary>
        /// Get the (unextended) container type associated with a type
        /// </summary>
        /// <param name="t">The type</param>
        /// <returns>The associated unextended type</returns>
        public static Type UnextendedType(this Type t)
        {
            Type res = t;

            if (res.IsGenericType())
            {
                res = res.GetGenericArguments().First();
            }
            res = res.UnproxiedType();
            res = TypeExtender.BaseType(res);
            return(res);
        }
コード例 #6
0
        public void AddAttributesWithParamsToDerivedClass()
        {
            _typeExtender = new TypeExtender("ClassA");
            _typeExtender.AddAttribute <CustomAAttribute>(new object[] { "Jon Snow" });

            var returnedClass = _typeExtender.FetchType();
            var attributes    = returnedClass.GetCustomAttributes(typeof(CustomAAttribute), false);
            var attribute     = attributes.Single().GetType();

            Assert.AreEqual(typeof(CustomAAttribute).Name, attribute.Name);
            Assert.AreEqual(typeof(CustomAAttribute).FullName, attribute.FullName);
        }
コード例 #7
0
        public void ReturnATypeWithThePassedNameAndBaseClass()
        {
            var className = "ClassA";
            var baseType  = typeof(List <string>);

            _typeExtender = new TypeExtender(className, baseType);

            var returnedClass    = _typeExtender.FetchType();
            var name             = returnedClass.Name;
            var basetypeReturned = returnedClass.BaseType;

            Assert.AreEqual(className, name);
            Assert.AreEqual(baseType, basetypeReturned);
        }
コード例 #8
0
        protected override IList <JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList <JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            var baseType = TypeExtender.BaseType(type);

            if (type == baseType)
            {
                return(properties);
            }
            else
            {
                var baseTypeProps = baseType.GetProperties().Select(pi => pi.Name).ToList();
                return(properties.Where(p => baseTypeProps.Contains(p.PropertyName)).ToList());
            }
        }
コード例 #9
0
ファイル: TypeExtenderTest.cs プロジェクト: 5l1v3r1/Aphid
        public AphidObject TryResolve(
            AphidObject scope,
            AphidObject obj,
            string key,
            bool isAphidType,
            bool isCtor,
            bool isDynamic,
            bool returnRef
            )
        {
            AphidObject result
                = TypeExtender.TryResolve(scope, obj, key, isAphidType, isCtor, isDynamic, returnRef);

            return(result);
            // TODO: add assertions to method TypeExtenderTest.TryResolve(AphidObject, AphidObject, String, Boolean, Boolean, Boolean, Boolean)
        }
コード例 #10
0
        private IList GetExtensionAspects()
        {
            IList extensionAspects = new ArrayList();

            foreach (IClassMap classMap in this.Context.DomainMap.ClassMaps)
            {
                IList generatedPropertyMaps = classMap.GetGeneratedPropertyMaps();
                if (generatedPropertyMaps.Count > 0)
                {
                    Type targetType = AssemblyManager.GetBaseType(
                        this.context.AssemblyManager.MustGetTypeFromClassMap(classMap));

                    TypeExtender    extender = new TypeExtender();
                    SignatureAspect aspect   = new SignatureAspect(classMap.Name + "GeneratedPropertiesExtender", targetType,
                                                                   new Type[] { }, new IPointcut[] { });

                    foreach (IPropertyMap generatedPropertyMap in generatedPropertyMaps)
                    {
                        ExtendedProperty property = new ExtendedProperty();
                        property.Name      = generatedPropertyMap.Name;
                        property.FieldName = generatedPropertyMap.GetFieldName();
                        if (generatedPropertyMap.IsCollection)
                        {
                            property.Type = typeof(IList);
                        }
                        else
                        {
                            if (generatedPropertyMap.ReferenceType != ReferenceType.None)
                            {
                                IClassMap refClassMap = generatedPropertyMap.MustGetReferencedClassMap();
                                property.Type = AssemblyManager.GetBaseType(
                                    this.context.AssemblyManager.MustGetTypeFromClassMap(refClassMap));
                            }
                            else
                            {
                                property.Type = Type.GetType(generatedPropertyMap.DataType);
                            }
                        }
                        extender.Members.Add(property);
                    }

                    aspect.TypeExtenders.Add(extender);
                    extensionAspects.Add(aspect);
                }
            }
            return(extensionAspects);
        }
コード例 #11
0
        public void AddPropertyWithAttribute()
        {
            var attributeType   = typeof(CustomAAttribute);
            var attributeParams = new object[] { "Jon Snow" };

            _typeExtender = new TypeExtender("ClassA");
            _typeExtender.AddProperty("IsAdded", typeof(bool), attributeType, attributeParams);

            var returnedClass = _typeExtender.FetchType();
            var property      = returnedClass.GetProperty("IsAdded");
            var attributes    = property.GetCustomAttributes(attributeType, false);
            var attribute     = attributes[0] as CustomAAttribute;

            Assert.AreEqual(1, attributes.Length);
            Assert.NotNull(attribute);
            Assert.AreEqual("Jon Snow", attribute.Name);
        }
コード例 #12
0
ファイル: Tests.cs プロジェクト: BackupTheBerlios/puzzle-svn
        public void ExtendingProperties()
        {
            Engine c = new Engine("ExtendingProperties");

            SignatureAspect aspect = new SignatureAspect("PropertyAdder", typeof(Foo), new Type[] { }, new IPointcut[] { });

            TypeExtender extender = new TypeExtender();

            ExtendedProperty property1 = new ExtendedProperty();

            property1.Name      = "MyIntProperty";
            property1.FieldName = "_MyIntProperty";
            property1.Type      = typeof(int);
            extender.Members.Add(property1);

            ExtendedProperty property2 = new ExtendedProperty();

            property2.Name      = "MyStringProperty";
            property2.FieldName = "_MyStringProperty";
            property2.Type      = typeof(string);
            extender.Members.Add(property2);

            aspect.TypeExtenders.Add(extender);

            c.Configuration.Aspects.Add(aspect);
            Foo proxy = (Foo)c.CreateProxy(typeof(Foo));

            PropertyInfo property1Info = proxy.GetType().GetProperty("MyIntProperty");
            PropertyInfo property2Info = proxy.GetType().GetProperty("MyStringProperty");

            Assert.IsNotNull(property1, "Property1 was not emitted");
            Assert.IsNotNull(property2, "Property2 was not emitted");


            property1Info.SetValue(proxy, 123, null);
            int resInt = (int)property1Info.GetValue(proxy, null);

            Assert.IsTrue(resInt == 123, "Property1 does not hold the correct value");


            property2Info.SetValue(proxy, "Hello", null);
            string resString = (string)property2Info.GetValue(proxy, null);

            Assert.IsTrue(resString == "Hello", "Property2 does not hold the correct value");
        }
コード例 #13
0
        public void AddFieldToDerivedClass()
        {
            // Arrange
            _typeExtender = new TypeExtender("ClassA");
            _typeExtender.AddField("IsAdded", typeof(bool));
            _typeExtender.AddField <bool>("IsEnabled");

            //Act
            var returnedClass  = _typeExtender.FetchType();
            var isAddedField   = returnedClass.GetField("IsAdded");
            var isEnabledField = returnedClass.GetField("IsEnabled");

            //Assert
            Assert.AreEqual("IsAdded", isAddedField.Name);
            Assert.AreEqual(typeof(bool), isAddedField.FieldType);
            Assert.AreEqual("IsEnabled", isEnabledField.Name);
            Assert.AreEqual(typeof(bool), isEnabledField.FieldType);
        }
コード例 #14
0
        public void AddACollectionOfPropertiesWithSameType()
        {
            _typeExtender = new TypeExtender("ClassA");
            var properites1 = new string[] { "IsEnabled", "CanFollowUp", "IsAdded" };
            var properties2 = new string[] { "Length", "Width", "Height" };

            _typeExtender.AddProperty(properites1, typeof(bool));
            _typeExtender.AddProperty <double>(properties2);
            var returnedClass = _typeExtender.FetchType();

            var properties = returnedClass.GetProperties();
            var all        = properites1.Union(properties2);

            foreach (var prop in all)
            {
                Assert.Contains(prop, properties.Select(x => x.Name).ToList());
            }
        }
コード例 #15
0
ファイル: TypeExtension01.cs プロジェクト: f5074/winforms
        public void AddType()
        {
            var className = "MES.Client.Core.Model.ClientEntityBase";

            _typeExtender = new TypeExtender(className);
            _typeExtender.AddProperty("IsAdded", typeof(bool));
            //_typeExtender.AddProperty("IsEnabled", typeof(bool), true);
            //_typeExtender.AddProperty<double>("Length");
            //_typeExtender.AddProperty<double>("Width", true);

            //Act
            var returnedClass     = _typeExtender.FetchType();
            var isAddedProperty   = returnedClass.GetProperty("IsAdded");
            var isEnabledProperty = returnedClass.GetProperty("IsEnabled");
            var lengthProperty    = returnedClass.GetProperty("Length");
            var widthProperty     = returnedClass.GetProperty("Width");

            baseTextBox.Text = isAddedProperty.ToString();
        }
コード例 #16
0
        /// <summary>
        /// Get a list of (only) the properties of a container type which are required
        /// to generate a summary.
        /// </summary>
        /// <param name="containerType">The container type</param>
        /// <returns>List of PropertyInfos of the properties required to generate a summary</returns>
        public List <PropertyInfo> ContainerSummaryFields(Type containerType)
        {
            Type baseType          = TypeExtender.BaseType(containerType);
            var  excludedPropNames = new List <string>();

            if (baseType.GetCustomAttribute <SummaryTypeAttribute>() != null) // has a declared summary type
            {
                // Exclude all properties in the base type which aren't marked as in the summary
                excludedPropNames = baseType.GetPersistedProperties()
                                    .Where(pi => pi.GetCustomAttribute <SummaryAttribute>() == null &&
                                           pi.GetCustomAttribute <AddressComponentAttribute>() == null &&
                                           pi.GetCustomAttribute <KeyAttribute>() == null)
                                    .Select(pi => pi.Name)
                                    .ToList();
            }

            return(containerType.GetPersistedProperties()
                   .Where(pi => !excludedPropNames.Contains(pi.Name) && pi.GetCustomAttribute <NotSummarisedAttribute>() == null)
                   .ToList());
        }
コード例 #17
0
        protected virtual ContentItem GetNewRecord(Type type, string path)
        {
            var newCI = System.Repository.New <ContentItem>();

            newCI.Path     = path;
            newCI.DataType = type.FullName;
            Type extType    = System.Extender[type] ?? type;
            var  newContent = Activator.CreateInstance(extType);
            var  address    = new Address(type, path);

            address.SetAddressFields(newContent);
            if (newContent is ICoreMetadata)
            {
                TypeExtender.CopyExtensionData(newCI, newContent);
            }
            newContent = System.Events.ProcessEvent("ContentItem.New", this, newContent).Data;

            newCI.SetContent(System, newContent);
            // ensure it is created in the current version
            System.Versions.SetVersion(System.Versions.CurrentVersion, newCI);
            return(newCI);
        }
コード例 #18
0
 public object GetContent(TypeExtender extender)
 {
     throw new NotImplementedException();
 }
コード例 #19
0
ファイル: Tests.cs プロジェクト: BackupTheBerlios/puzzle-svn
        public void ExtendingProperties()
        {
            Engine c = new Engine("ExtendingProperties");

            SignatureAspect aspect = new SignatureAspect("PropertyAdder", typeof(Foo), new Type[] { }, new IPointcut[] { });

            TypeExtender extender = new TypeExtender();

            ExtendedProperty property1 = new ExtendedProperty();
            property1.Name = "MyIntProperty";
            property1.FieldName = "_MyIntProperty";
            property1.Type = typeof(int);
            extender.Members.Add(property1);

            ExtendedProperty property2 = new ExtendedProperty();
            property2.Name = "MyStringProperty";
            property2.FieldName = "_MyStringProperty";
            property2.Type = typeof(string);
            extender.Members.Add(property2);

            aspect.TypeExtenders.Add(extender);

            c.Configuration.Aspects.Add(aspect);
            Foo proxy = (Foo)c.CreateProxy(typeof(Foo));

            PropertyInfo property1Info = proxy.GetType().GetProperty("MyIntProperty");
            PropertyInfo property2Info = proxy.GetType().GetProperty("MyStringProperty");

            Assert.IsNotNull(property1, "Property1 was not emitted");
            Assert.IsNotNull(property2, "Property2 was not emitted");

            property1Info.SetValue(proxy, 123, null);
            int resInt = (int)property1Info.GetValue(proxy, null);
            Assert.IsTrue(resInt == 123, "Property1 does not hold the correct value");

            property2Info.SetValue(proxy, "Hello", null);
            string resString = (string)property2Info.GetValue(proxy, null);
            Assert.IsTrue(resString == "Hello", "Property2 does not hold the correct value");
        }
コード例 #20
0
ファイル: Tests.cs プロジェクト: BackupTheBerlios/puzzle-svn
        public void InterceptExtendedProperties()
        {
            Engine c = new Engine("InterceptExtendedProperties");

            SignatureAspect aspect = new SignatureAspect("PropertyAdder", typeof(Foo), new Type[] { }, new IPointcut[] { });
            aspect.Pointcuts.Add(new SignaturePointcut("get_MyIntProperty", new IncreaseReturnValueInterceptor()));

            TypeExtender extender = new TypeExtender();

            ExtendedProperty property1 = new ExtendedProperty();
            property1.Name = "MyIntProperty";
            property1.FieldName = "_MyIntProperty";
            property1.Type = typeof(int);
            extender.Members.Add(property1);

            aspect.TypeExtenders.Add(extender);

            c.Configuration.Aspects.Add(aspect);
            Foo proxy = (Foo)c.CreateProxy(typeof(Foo));

            PropertyInfo property1Info = proxy.GetType().GetProperty("MyIntProperty");

            Assert.IsNotNull(property1, "Property1 was not emitted");

            property1Info.SetValue(proxy, 123, null);
            int resInt = (int)property1Info.GetValue(proxy, null);
            Assert.IsTrue(resInt == 124, "Property1 Was not intercepted");
        }
コード例 #21
0
ファイル: StandardLibrary.cs プロジェクト: rajpaswan/aphid
        public static void Extend(AphidInterpreter interpreter, AphidObject type, AphidObject extensions)
        {
            var typeStr = (string)type.Value;

            TypeExtender.Extend(interpreter, (string)type.Value, extensions);
        }
コード例 #22
0
ファイル: ContentItem.cs プロジェクト: slamj1/lyniconanc
 /// <summary>
 /// Get the contained content item of type T
 /// </summary>
 /// <typeparam name="T">The type of the content item</typeparam>
 /// <param name="extender">Type extender for creating content type</param>
 /// <returns>The contained content item</returns>
 public T GetContent <T>(TypeExtender extender) where T : class
 {
     return(GetContent(extender) as T);
 }
コード例 #23
0
        private ContentItem GetContentItem(Address a, object data)
        {
            string      dataPath    = null;
            string      routePath   = null;
            ContentItem contentItem = null;

            // try and get path from data via attributes
            Address address = new Address(data);

            if (address.Count > 0)
            {
                dataPath = address.GetAsContentPath();
            }

            // Get requested path
            if (a != null)
            {
                routePath = a.GetAsContentPath();
            }

            // We have path in data and address parameter and they disagree
            if (dataPath != null && routePath != null && dataPath != routePath)
            {
                // Raise event here for when address is changed via changing addressed mapped fields on data
                System.Events.ProcessEvent("Content.Move", this, Tuple.Create(a, data));
                // regenerate path in case event processor changed data
                address   = new Address(data);
                dataPath  = address.GetAsContentPath();
                routePath = a.GetAsContentPath();
            }

            string path = dataPath ?? routePath;

            // if we have an extended content object, we can use the OriginalRecord if must as we have no path, or if the path is the same
            if (data is ICoreMetadata)
            {
                contentItem = (ContentItem)Activator.CreateInstance(System.Extender[typeof(ContentItem)] ?? typeof(ContentItem));
                TypeExtender.CopyExtensionData(data, contentItem);
                contentItem.DataType = data.GetType().UnextendedType().FullName;

                if (path == null || path == contentItem.Path)
                {
                    contentItem.SetContent(System, data);
                    return(contentItem);
                }
            }

            // If we get to here, we can't find the path
            if (path == null)
            {
                throw new ArgumentException("Cannot find path of " + data.GetType().FullName);
            }

            // Now we have to get the content item from the db so we get the right ids etc
            var findPath     = routePath ?? dataPath;
            var contentItems = System.Repository.Get <ContentItem>(data.GetType(), iq => iq.Where(ci => ci.Path == findPath)).ToList();

            if (contentItems.Count > 1)
            {
                throw new Exception("Duplicate content items at " + findPath + " of type " + data.GetType().FullName);
            }

            contentItem = contentItems.SingleOrDefault();
            // If we can't we build a new one
            if (contentItem == null)
            {
                contentItem          = Repository.New <ContentItem>();
                contentItem.DataType = data.GetType().FullName;
            }

            contentItem.Path = path;

            contentItem.SetContent(System, data);

            if (data is ICoreMetadata)
            {
                TypeExtender.CopyExtensionData(contentItem, data);
            }

            return(contentItem);
        }
コード例 #24
0
        private IList GetExtensionAspects()
        {
            IList extensionAspects = new ArrayList();
            foreach (IClassMap classMap in this.Context.DomainMap.ClassMaps)
            {
                IList generatedPropertyMaps = classMap.GetGeneratedPropertyMaps();
                if (generatedPropertyMaps.Count > 0)
                {
                    Type targetType = AssemblyManager.GetBaseType(
                        this.context.AssemblyManager.MustGetTypeFromClassMap(classMap));

                    TypeExtender extender = new TypeExtender();
                    SignatureAspect aspect = new SignatureAspect(classMap.Name + "GeneratedPropertiesExtender", targetType,
                        new Type[] { }, new IPointcut[] { });

                    foreach (IPropertyMap generatedPropertyMap in generatedPropertyMaps)
                    {
                        ExtendedProperty property = new ExtendedProperty();
                        property.Name = generatedPropertyMap.Name;
                        property.FieldName = generatedPropertyMap.GetFieldName();
                        if (generatedPropertyMap.IsCollection)
                            property.Type = typeof(IList);
                        else
                        {
                            if (generatedPropertyMap.ReferenceType != ReferenceType.None)
                            {
                                IClassMap refClassMap = generatedPropertyMap.MustGetReferencedClassMap();
                                property.Type = AssemblyManager.GetBaseType(
                                    this.context.AssemblyManager.MustGetTypeFromClassMap(refClassMap));
                            }
                            else
                            {
                                property.Type = Type.GetType(generatedPropertyMap.DataType);
                            }
                        }
                        extender.Members.Add(property);
                    }

                    aspect.TypeExtenders.Add(extender);
                    extensionAspects.Add(aspect);
                }
            }
            return extensionAspects;
        }
コード例 #25
0
ファイル: ContentItem.cs プロジェクト: slamj1/lyniconanc
        /// <summary>
        /// Get the content of the item as an object
        /// </summary>
        /// <returns>The contained content item</returns>
        public object GetContent(TypeExtender extender)
        {
            Type type    = this.ContentType;
            Type extType = extender[type] ?? type;

            if (contentObject != null)
            {
                return(contentObject);
            }

            JObject contentJObject = null;

            if (string.IsNullOrEmpty(this.Content))
            {
                contentObject = Activator.CreateInstance(extType);
                if (this.Id != Guid.Empty) // shouldn't normally happen
                {
                    log.WarnFormat("Reading content from contentitem {0} with no content: {1}", this.Id, Environment.StackTrace);
                }
            }
            else
            {
                contentJObject = JObject.Parse(this.Content);
                var sz = JsonSerializer.Create(GetSerializerSettings(type, this.Id));
                contentObject = contentJObject.ToObject(extType, sz);
                if (contentObject == null)
                {
                    contentObject = Activator.CreateInstance(extType);
                }
            }


            var summaryMap = GetSummaryProperties(type);

            // Set the summary property(ies) if record field has data
            if (!string.IsNullOrEmpty(this.Summary) && summaryMap.Count > 0)
            {
                var summType = GetSummaryType(type);
                var summ     = JsonConvert.DeserializeObject(this.Summary, summType, GetSerializerSettings(type, this.Id));
                if (summaryMap.ContainsKey(""))
                {
                    summaryMap[""].SetValue(contentObject, summ);
                }
                else
                {
                    JToken dummy;
                    // We check contentJObject to see if the summary property existed in the serialization of the
                    // content, in which case we don't use the property from the summary.  This allows us to safely
                    // change the content classes by adding a property to the summary without losing the data in
                    // that property.  Removal of a property from the summary will still cause data loss however.
                    summaryMap.Do(kvp =>
                    {
                        if (kvp.Value.CanWrite &&
                            kvp.Value.GetCustomAttribute <JsonIgnoreAttribute>() == null &&
                            !contentJObject.TryGetValue(kvp.Value.Name, out dummy))
                        {
                            if (summType.GetProperty(kvp.Key) == null)
                            {
                                throw new Exception("Type " + type.FullName + " has property " + kvp.Key + " incorrectly marked as being on summary type " + summType.FullName);
                            }

                            kvp.Value.SetValue(contentObject, summType.GetProperty(kvp.Key).GetValue(summ));
                        }
                    });
                }
            }

            if (this.Title != null)
            {
                if (summaryMap.ContainsKey(""))
                {
                    var summ = summaryMap[""].GetValue(contentObject);
                    // we know it has the property Title as it inherits from Summary
                    summ.GetType().GetProperty("Title").SetValue(summ, this.Title);
                    summaryMap[""].SetValue(contentObject, summ);
                }
                else
                {
                    var titleProp = type.GetProperty("Title");
                    if (summaryMap.ContainsKey("Title"))
                    {
                        titleProp = summaryMap["Title"];
                    }

                    if (titleProp != null)
                    {
                        titleProp.SetValue(contentObject, this.Title);
                    }
                }
            }

            // Set up metadata if possible
            if (typeof(ICoreMetadata).IsAssignableFrom(extType))
            {
                TypeExtender.CopyExtensionData(this, contentObject);
            }

            return(contentObject);
        }
コード例 #26
0
        public void GetReadProperties_returns_null_when_called_with_null()
        {
            var res = TypeExtender.GetReadProperties(null);

            res.Should().BeNull();
        }