Ejemplo n.º 1
0
        public static void AccessedThroughPropertyAttributeTests()
        {
            var attr1 = new AccessedThroughPropertyAttribute(null);

            Assert.Null(attr1.PropertyName);

            var attr2 = new AccessedThroughPropertyAttribute("MyProperty");

            Assert.Equal("MyProperty", attr2.PropertyName);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///  Adds inherited components to the <see cref="InheritanceService"/>.
        /// </summary>
        protected virtual void AddInheritedComponents(Type type, IComponent component, IContainer container)
        {
            // We get out now if this component type is not assignable from IComponent.  We only walk down to the component level.
            if (type is null || !typeof(IComponent).IsAssignableFrom(type))
            {
                return;
            }

            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Searching for inherited components on '" + type.FullName + "'.");
            Debug.Indent();
            ISite site = component.Site;
            IComponentChangeService cs  = null;
            INameCreationService    ncs = null;

            if (site is not null)
            {
                ncs = (INameCreationService)site.GetService(typeof(INameCreationService));
                cs  = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
                if (cs is not null)
                {
                    cs.ComponentAdding += new ComponentEventHandler(OnComponentAdding);
                }
            }

            try
            {
                while (type != typeof(object))
                {
                    Type        reflect = TypeDescriptor.GetReflectionType(type);
                    FieldInfo[] fields  = reflect.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic);
                    Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found " + fields.Length.ToString(CultureInfo.InvariantCulture) + " fields.");
                    for (int i = 0; i < fields.Length; i++)
                    {
                        FieldInfo field = fields[i];
                        string    name  = field.Name;

                        // Get out now if this field is not assignable from IComponent.
                        Type reflectionType = GetReflectionTypeFromTypeHelper(field.FieldType);
                        if (!GetReflectionTypeFromTypeHelper(typeof(IComponent)).IsAssignableFrom(reflectionType))
                        {
                            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Not IComponent");
                            continue;
                        }

                        // Now check the attributes of the field and get out if it isn't something that can be inherited.
                        Debug.Assert(!field.IsStatic, "Instance binding shouldn't have found this field");

                        // If the value of the field is null, then don't mess with it.  If it wasn't assigned when our base class was created then we can't really use it.
                        object value = field.GetValue(component);
                        if (value is null)
                        {
                            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Contains NULL");
                            continue;
                        }

                        // We've been fine up to this point looking at the field.  Now, however, we must check to see if this field has an AccessedThroughPropertyAttribute on it.  If it does, then we must look for the property and use its name and visibility for the remainder of the scan.  Should any of this bail we just use the field.
                        MemberInfo member = field;

                        object[] fieldAttrs = field.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false);
                        if (fieldAttrs is not null && fieldAttrs.Length > 0)
                        {
                            Debug.Assert(fieldAttrs.Length == 1, "Non-inheritable attribute has more than one copy");
                            Debug.Assert(fieldAttrs[0] is AccessedThroughPropertyAttribute, "Reflection bug:  GetCustomAttributes(type) didn't discriminate by type");
                            AccessedThroughPropertyAttribute propAttr = (AccessedThroughPropertyAttribute)fieldAttrs[0];

                            PropertyInfo fieldProp = reflect.GetProperty(propAttr.PropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                            Debug.Assert(fieldProp is not null, "Field declared with AccessedThroughPropertyAttribute has no associated property");
                            Debug.Assert(fieldProp.PropertyType == field.FieldType, "Field declared with AccessedThroughPropertyAttribute is associated with a property with a different return type.");
                            if (fieldProp is not null && fieldProp.PropertyType == field.FieldType)
                            {
                                // If the property cannot be read, it is useless to us.
                                if (!fieldProp.CanRead)
                                {
                                    continue;
                                }

                                // We never access the set for the property, so we can concentrate on just the get method.
                                member = fieldProp.GetGetMethod(true);
                                Debug.Assert(member is not null, "GetGetMethod for property didn't return a method, but CanRead is true");
                                name = propAttr.PropertyName;
                            }
                        }

                        // Add a user hook to add or remove members.  The default hook here ignores all inherited private members.
                        bool ignoreMember = IgnoreInheritedMember(member, component);

                        // We now have an inherited member.  Gather some information about it and then add it to our list.  We must always add to our list, but we may not want to  add it to the container.  That is up to the IgnoreInheritedMember method. We add here because there are components in the world that, when sited, add their children to the container too. That's fine, but we want to make sure we account for them in the inheritance service too.
                        Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found inherited member '" + name + "'");
                        Debug.Indent();
                        Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Type: " + field.FieldType.FullName);

                        InheritanceAttribute attr;

                        Debug.Assert(value is IComponent, "Value of inherited field is not IComponent.  How did this value get into the datatype?");

                        bool privateInherited = false;

                        if (ignoreMember)
                        {
                            // If we are ignoring this member, then always mark it as private. The designer doesn't want it; we only do this in case some other component adds this guy to the container.
                            privateInherited = true;
                        }
                        else
                        {
                            if (member is FieldInfo fi)
                            {
                                privateInherited = fi.IsPrivate | fi.IsAssembly;
                            }
                            else if (member is MethodInfo mi)
                            {
                                privateInherited = mi.IsPrivate | mi.IsAssembly;
                            }
                        }

                        if (privateInherited)
                        {
                            attr = InheritanceAttribute.InheritedReadOnly;
                            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Private");
                        }
                        else
                        {
                            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Public");
                            attr = InheritanceAttribute.Inherited;
                        }

                        bool notPresent = (_inheritedComponents[value] is null);
                        _inheritedComponents[value] = attr;

                        if (!ignoreMember && notPresent)
                        {
                            Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Adding " + name + " to container.");
                            try
                            {
                                _addingComponent = (IComponent)value;
                                _addingAttribute = attr;

                                // Lets make sure this is a valid name
                                if (ncs is null || ncs.IsValidName(name))
                                {
                                    try
                                    {
                                        container.Add((IComponent)value, name);
                                    }
                                    catch
                                    { // We do not always control the base components, and there could be a lot of rogue base components. If there are exceptions when adding them, lets just ignore and continue.
                                    }
                                }
                            }
                            finally
                            {
                                _addingComponent = null;
                                _addingAttribute = null;
                            }
                        }

                        Debug.Unindent();
                    }

                    type = type.BaseType;
                }
            }
            finally
            {
                if (cs is not null)
                {
                    cs.ComponentAdding -= new ComponentEventHandler(OnComponentAdding);
                }

                Debug.Unindent();
            }
        }
Ejemplo n.º 3
0
        private void GetDelegateHookupsFromHandlesClauses(Hashtable handlers, CodeTypeDeclaration codeTypeDecl, CodeStatementCollection statements)
        {
            CodeDomLoader.StartMark();

            // unfortunately, we have to essentially parse the code to find the objects
            // that we are instantiating to get their types and names
            //
            // then we get the default event for each type, and then we walk through our list
            // of handlers and add statement hookups for the default ones.
            //
            // why do we go through all this work?  because we need to know which ones are set by
            // parse time or when we double click on the same control, we'll think we have to add another handler.
            //

            Hashtable objs = new Hashtable();

            foreach (CodeTypeMember member in codeTypeDecl.Members)
            {
                CodeMemberField field = member as CodeMemberField;
                if (field != null)
                {
                    objs[field.Name] = field.Type.BaseType;
                }
            }


            // and add our base type...
            //
            objs["MyBase"] = codeTypeDecl.BaseTypes[0].BaseType;

            // again by name because Visual Basic keeps switching back and forth...
            //
            objs[codeTypeDecl.Name] = codeTypeDecl.BaseTypes[0].BaseType;

            // now we have all the created objects, so we walk through the
            // handlers we've found and see which ones are default handlers for those objects.
            //
            ITypeResolutionService typeLoader = provider.TypeLoader;
            Type baseType = null;

            if (typeLoader != null)
            {
                // now walk through them, checking each to see if we're on a default event
                //

                foreach (DictionaryEntry de in handlers)
                {
                    // get the handler and and the data for this field
                    //
                    string handler   = (string)de.Key;
                    int    dot       = handler.IndexOf('.');
                    string fieldName = handler.Substring(0, dot);

                    object objInfo   = objs[fieldName];
                    Type   fieldType = null;

                    if (objInfo == null)
                    {
                        // this means this thing isn't an IComponent...try to reflect against the base type
                        //
                        if (baseType == null)
                        {
                            baseType = typeLoader.GetType(codeTypeDecl.BaseTypes[0].BaseType, false);
                        }
                        if (baseType != null)
                        {
                            // because of the wonderful magicalness of VB, there isn't actually a field called "button1", it's a
                            // property. so we get to walk all the fields, looking for one who has the neat
                            // little Accessed through property attribute that matches the name of this member.
                            //
                            foreach (FieldInfo field in baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                            {
                                if (field.Name == fieldName)
                                {
                                    fieldType = field.FieldType;
                                    break;
                                }

                                object[] fieldAttrs = field.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false);
                                if (fieldAttrs != null && fieldAttrs.Length > 0)
                                {
                                    AccessedThroughPropertyAttribute propAttr = (AccessedThroughPropertyAttribute)fieldAttrs[0];
                                    // does the property name on the attribute match what we're looking for?
                                    //
                                    if (propAttr.PropertyName == fieldName)
                                    {
                                        PropertyInfo fieldProp = baseType.GetProperty(propAttr.PropertyName,
                                                                                      BindingFlags.Instance |
                                                                                      BindingFlags.Public |
                                                                                      BindingFlags.NonPublic);

                                        // now go find the property and get its value
                                        //
                                        if (fieldProp != null)
                                        {
                                            MethodInfo getMethod = fieldProp.GetGetMethod(true);
                                            if (getMethod != null && !getMethod.IsPrivate)
                                            {
                                                fieldType = fieldProp.PropertyType;
                                            }
                                            break;
                                        }
                                    }
                                }
                            }

                            if (fieldType != null)
                            {
                                objs[fieldName] = fieldType;
                                objInfo         = fieldType;
                            }
                            else
                            {
                                // flag failure of this type so we
                                // don't check again.
                                //
                                objs[fieldName] = false;
                                objInfo         = false;
                                continue;
                            }
                        }
                    }

                    if (objInfo is string)
                    {
                        // it's the type name, get the default handler from the TypeDescriptor
                        //
                        Type t = typeLoader.GetType((string)objInfo, false);

                        if (t != null)
                        {
                            objs[fieldName] = t;
                            fieldType       = t;
                        }
                    }
                    else if (objInfo is Type)
                    {
                        // just grab the handler
                        //
                        fieldType = (Type)objInfo;
                    }
                    else if (objInfo is bool)
                    {
                        // we've failed here before, just give up!
                        //
                        continue;
                    }
                    else
                    {
                        // errr, how'd we get here?
                        //
                        Debug.Fail("Why does the handler data have a '" + objInfo.GetType().FullName + "'?");
                        continue;
                    }

                    // now that we have a default event, see if the
                    // handler we're currently on, say "button1.Click" matches
                    // what the handles clause for this component would look like.
                    //

                    if (fieldType != null)
                    {
                        string eventName = handler.Substring(dot + 1);

                        // Make sure this is a valid event for this type
                        EventDescriptor eventDesc = TypeDescriptor.GetEvents(fieldType)[eventName];

                        // (bug 120608) if we got null, we may be hooking up a private interface member. Try to find it.
                        //
                        if (eventDesc == null)
                        {
                            foreach (Type interfaceType in fieldType.GetInterfaces())
                            {
                                EventInfo eventInfo = interfaceType.GetEvent(eventName);
                                if (eventInfo != null)
                                {
                                    eventDesc = TypeDescriptor.CreateEvent(interfaceType, eventName, eventInfo.EventHandlerType);
                                    break;
                                }
                            }
                        }

                        Debug.Assert(eventDesc != null, "Handles clause '" + handler + "' found, but type '" + fieldType.FullName + "' does not have an event '" + eventName + "'");

                        if (eventDesc != null)
                        {
                            CodeMemberMethod method          = de.Value as CodeMemberMethod;
                            CodeStatement    attachStatement = CreateEventAttachStatement(fieldName == "MyBase" ? null : fieldName, eventDesc, method.Name);
                            attachStatement.UserData[CodeDomXmlProcessor.KeyXmlParsedStatement] = CodeDomXmlProcessor.KeyXmlParsedStatement;
                            statements.Add(attachStatement);
                        }
                    }
                }
            }

            CodeDomLoader.EndMark("Handles clauses to delegate hookups");
        }
 protected virtual void AddInheritedComponents(Type type, IComponent component, IContainer container)
 {
     if ((type != null) && typeof(IComponent).IsAssignableFrom(type))
     {
         ISite site = component.Site;
         IComponentChangeService service  = null;
         INameCreationService    service2 = null;
         if (site != null)
         {
             service2 = (INameCreationService)site.GetService(typeof(INameCreationService));
             service  = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
             if (service != null)
             {
                 service.ComponentAdding += new ComponentEventHandler(this.OnComponentAdding);
             }
         }
         try
         {
             while (type != typeof(object))
             {
                 Type reflectionType = TypeDescriptor.GetReflectionType(type);
                 foreach (FieldInfo info in reflectionType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                 {
                     string name = info.Name;
                     if (typeof(IComponent).IsAssignableFrom(info.FieldType))
                     {
                         object obj2 = info.GetValue(component);
                         if (obj2 != null)
                         {
                             InheritanceAttribute inheritedReadOnly;
                             MemberInfo           member           = info;
                             object[]             customAttributes = info.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false);
                             if ((customAttributes != null) && (customAttributes.Length > 0))
                             {
                                 AccessedThroughPropertyAttribute attribute = (AccessedThroughPropertyAttribute)customAttributes[0];
                                 PropertyInfo property = reflectionType.GetProperty(attribute.PropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                                 if ((property != null) && (property.PropertyType == info.FieldType))
                                 {
                                     if (!property.CanRead)
                                     {
                                         continue;
                                     }
                                     member = property.GetGetMethod(true);
                                     name   = attribute.PropertyName;
                                 }
                             }
                             bool flag  = this.IgnoreInheritedMember(member, component);
                             bool flag2 = false;
                             if (flag)
                             {
                                 flag2 = true;
                             }
                             else if (member is FieldInfo)
                             {
                                 FieldInfo info4 = (FieldInfo)member;
                                 flag2 = info4.IsPrivate | info4.IsAssembly;
                             }
                             else if (member is MethodInfo)
                             {
                                 MethodInfo info5 = (MethodInfo)member;
                                 flag2 = info5.IsPrivate | info5.IsAssembly;
                             }
                             if (flag2)
                             {
                                 inheritedReadOnly = InheritanceAttribute.InheritedReadOnly;
                             }
                             else
                             {
                                 inheritedReadOnly = InheritanceAttribute.Inherited;
                             }
                             bool flag3 = this.inheritedComponents[obj2] == null;
                             this.inheritedComponents[obj2] = inheritedReadOnly;
                             if (!flag && flag3)
                             {
                                 try
                                 {
                                     this.addingComponent = (IComponent)obj2;
                                     this.addingAttribute = inheritedReadOnly;
                                     if ((service2 == null) || service2.IsValidName(name))
                                     {
                                         try
                                         {
                                             container.Add((IComponent)obj2, name);
                                         }
                                         catch
                                         {
                                         }
                                     }
                                 }
                                 finally
                                 {
                                     this.addingComponent = null;
                                     this.addingAttribute = null;
                                 }
                             }
                         }
                     }
                 }
                 type = type.BaseType;
             }
         }
         finally
         {
             if (service != null)
             {
                 service.ComponentAdding -= new ComponentEventHandler(this.OnComponentAdding);
             }
         }
     }
 }
Ejemplo n.º 5
0
            public void AddInheritedComponents(IComponent component, IContainer container)
            {
                if (component != m_owner.Component || !m_owner.Inline)
                {
                    if (m_parentService != null)
                    {
                        m_parentService.AddInheritedComponents(component, container);
                    }
                    return;
                }

                ISite site = component.Site;
                INameCreationService nameService = null;

                if (site != null)
                {
                    nameService = (INameCreationService)site.GetService(typeof(INameCreationService));
                }

                IDesignerHost host = (IDesignerHost)m_owner.GetService(typeof(IDesignerHost));

                if (host != null)
                {
                    m_manager = (IDesignerSerializationManager)host.GetService(typeof(IDesignerSerializationManager));
                }

                try
                {
                    Type   compType = component.GetType();
                    string stopType = GetFullTypeName <DelphiClasses.TFrame>();
                    while (compType != typeof(object) && compType.FullName != stopType)
                    {
                        Type reflectionType = TypeDescriptor.GetReflectionType(compType);
                        foreach (FieldInfo info in reflectionType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                        {
                            string name = info.Name;
                            Type   reflectionTypeFromTypeHelper = GetReflectionTypeFromTypeHelper(info.FieldType);
                            if (GetReflectionTypeFromTypeHelper(typeof(IComponent)).IsAssignableFrom(reflectionTypeFromTypeHelper))
                            {
                                object obj2 = info.GetValue(component);
                                if (obj2 != null)
                                {
                                    MemberInfo member           = info;
                                    object[]   customAttributes = info.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false);
                                    if ((customAttributes != null) && (customAttributes.Length != 0x0))
                                    {
                                        AccessedThroughPropertyAttribute attribute2 = (AccessedThroughPropertyAttribute)customAttributes[0x0];
                                        PropertyInfo property = reflectionType.GetProperty(attribute2.PropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                                        if ((property != null) && (property.PropertyType == info.FieldType))
                                        {
                                            if (!property.CanRead)
                                            {
                                                continue;
                                            }

                                            member = property.GetGetMethod(true);
                                            name   = attribute2.PropertyName;
                                        }
                                    }

                                    if (!IgnoreInheritedMember(member, component) &&
                                        m_inheritedComponents.Add((IComponent)obj2))
                                    {
                                        if (nameService == null || nameService.IsValidName(name))
                                        {
                                            try
                                            {
                                                container.Add((IComponent)obj2, name);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        compType = compType.BaseType;
                    }
                }
                finally
                {
                    m_manager = null;
                }
            }