Пример #1
0
        /// <summary>
        /// Determine a unique site name for a component, starting from a base name. Return value should be passed into the Container.Add() method. If null is returned, this just means "let container generate a default name based on component type".
        /// </summary>
        public static string GetUniqueSiteName(IDesignerHost host, string name)
        {
            // Item has no explicit name, so let host generate a type-based name instead
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            // Get the name creation service from the designer host
            INameCreationService nameCreationService = (INameCreationService)host.GetService(typeof(INameCreationService));

            if (nameCreationService == null)
            {
                return(null);
            }

            // See if desired name is already in use
            object existingComponent = host.Container.Components[name];

            if (existingComponent == null)
            {
                // Name is not in use - but make sure that it contains valid characters before using it!
                return(nameCreationService.IsValidName(name) ? name : null);
            }
            else
            {
                // Name is in use (and therefore basically valid), so start appending numbers
                string nameN = name;
                for (int i = 1; !nameCreationService.IsValidName(nameN); ++i)
                {
                    nameN = name + i.ToString(CultureInfo.InvariantCulture);
                }
                return(nameN);
            }
        }
Пример #2
0
        public static string GetUniqueSiteName(IDesignerHost host, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            INameCreationService service = (INameCreationService)host.GetService(typeof(INameCreationService));

            if (service == null)
            {
                return(null);
            }
            if (host.Container.Components[name] == null)
            {
                if (!service.IsValidName(name))
                {
                    return(null);
                }
                return(name);
            }
            string str = name;

            for (int i = 1; !service.IsValidName(str); i++)
            {
                str = name + i.ToString(CultureInfo.InvariantCulture);
            }
            return(str);
        }
        private string NameFromText(string text, System.Type itemType, INameCreationService nameCreationService, bool adjustCapitalization)
        {
            string name = null;

            if (text == "-")
            {
                name = "toolStripSeparator";
            }
            else
            {
                string        str2    = itemType.Name;
                StringBuilder builder = new StringBuilder(text.Length + str2.Length);
                bool          flag    = false;
                for (int j = 0; j < text.Length; j++)
                {
                    char c = text[j];
                    if (char.IsLetterOrDigit(c))
                    {
                        if (!flag)
                        {
                            c    = char.ToLower(c, CultureInfo.CurrentCulture);
                            flag = true;
                        }
                        builder.Append(c);
                    }
                }
                builder.Append(str2);
                name = builder.ToString();
                if (adjustCapitalization)
                {
                    string str3 = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), this._designer.Component.Site);
                    if (!string.IsNullOrEmpty(str3) && char.IsUpper(str3[0]))
                    {
                        name = char.ToUpper(name[0], CultureInfo.InvariantCulture) + name.Substring(1);
                    }
                }
            }
            if (this._host.Container.Components[name] == null)
            {
                if (!nameCreationService.IsValidName(name))
                {
                    return(nameCreationService.CreateName(this._host.Container, itemType));
                }
                return(name);
            }
            string str4 = name;

            for (int i = 1; !nameCreationService.IsValidName(str4); i++)
            {
                str4 = name + i.ToString(CultureInfo.InvariantCulture);
            }
            return(str4);
        }
 public static bool ValidName(string name, DataGridViewColumnCollection columns, IContainer container, INameCreationService nameCreationService, DataGridViewColumnCollection liveColumns, bool allowDuplicateNameInLiveColumnCollection)
 {
     if (columns.Contains(name))
     {
         return(false);
     }
     if (((container != null) && (container.Components[name] != null)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         return(false);
     }
     return(((nameCreationService == null) || nameCreationService.IsValidName(name)) || ((allowDuplicateNameInLiveColumnCollection && (liveColumns != null)) && liveColumns.Contains(name)));
 }
 public static bool ValidName(string name, DataGridViewColumnCollection columns, IContainer container, INameCreationService nameCreationService, DataGridViewColumnCollection liveColumns, bool allowDuplicateNameInLiveColumnCollection, out string errorString)
 {
     if (columns.Contains(name))
     {
         errorString = System.Design.SR.GetString("DataGridViewDuplicateColumnName", new object[] { name });
         return(false);
     }
     if (((container != null) && (container.Components[name] != null)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = System.Design.SR.GetString("DesignerHostDuplicateName", new object[] { name });
         return(false);
     }
     if (((nameCreationService != null) && !nameCreationService.IsValidName(name)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = System.Design.SR.GetString("CodeDomDesignerLoaderInvalidIdentifier", new object[] { name });
         return(false);
     }
     errorString = string.Empty;
     return(true);
 }
 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);
             }
         }
     }
 }
        /// <summary>
        ///  Computes a name from a text label by removing all spaces and non-alphanumeric characters.
        /// </summary>
        private string NameFromText(string text, Type itemType, INameCreationService nameCreationService, bool adjustCapitalization)
        {
            string baseName;

            // for separators, name them ToolStripSeparator...
            if (text == "-")
            {
                baseName = "toolStripSeparator";
            }
            else
            {
                string nameSuffix = itemType.Name;
                // remove all the non letter and number characters.   Append length of "MenuItem"
                Text.StringBuilder name = new Text.StringBuilder(text.Length + nameSuffix.Length);
                bool firstCharSeen      = false;
                for (int i = 0; i < text.Length; i++)
                {
                    char c = text[i];
                    if (char.IsLetterOrDigit(c))
                    {
                        if (!firstCharSeen)
                        {
                            c             = char.ToLower(c, CultureInfo.CurrentCulture);
                            firstCharSeen = true;
                        }

                        name.Append(c);
                    }
                }

                name.Append(nameSuffix);
                baseName = name.ToString();
                if (adjustCapitalization)
                {
                    string nameOfRandomItem = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), _designer.Component.Site);
                    if (!string.IsNullOrEmpty(nameOfRandomItem) && char.IsUpper(nameOfRandomItem[0]))
                    {
                        baseName = char.ToUpper(baseName[0], CultureInfo.InvariantCulture) + baseName.Substring(1);
                    }
                }
            }

            // see if this name matches another one in the container..
            object existingComponent = _host.Container.Components[baseName];

            if (existingComponent is null)
            {
                if (!nameCreationService.IsValidName(baseName))
                {
                    // we don't have a name collision but this still isn't a valid name...something is wrong and we can't make a valid identifier out of this so bail.
                    return(nameCreationService.CreateName(_host.Container, itemType));
                }
                else
                {
                    return(baseName);
                }
            }
            else
            {
                // start appending numbers.
                string newName = baseName;
                for (int indexer = 1; !nameCreationService.IsValidName(newName); indexer++)
                {
                    newName = baseName + indexer.ToString(CultureInfo.InvariantCulture);
                }

                return(newName);
            }
        }
Пример #8
0
        public void Add(IComponent component, string name)
        {
            IDesigner designer = null;

            //input checks
            if (component == null)
            {
                throw new ArgumentException("Cannot add null component to container", "component");
            }
            if (!(component is Control))
            {
                throw new ArgumentException("This Container only accepts System.Web.UI.Control-derived components", "component");
            }
            if (component.Site != null && component.Site.Container != this)
            {
                component.Site.Container.Remove(component);
            }

            //Check the name and create one if necessary
            INameCreationService nameService = host.GetService(typeof(INameCreationService)) as INameCreationService;

            if (nameService == null)
            {
                throw new Exception("The container must have access to a INameCreationService implementation");
            }

            if (name == null || !nameService.IsValidName(name))
            {
                name = nameService.CreateName(this, component.GetType());
                System.Diagnostics.Trace.WriteLine("Generated name for component: " + name);
            }

            //check we don't already have component with same name
            if (GetComponent(name) != null)
            {
                throw new ArgumentException("There is already a component with this name in the container", "name");
            }

            //we're definately adding it now, so broadcast
            OnComponentAdding(component);

            //get a site and set ID property
            //this way (not PropertyDescriptor.SetValue) won't fire change events
            ((Control)component).ID = name;
            component.Site          = new DesignSite(component, this);

            //Get designer. If first component, designer must be an IRootDesigner
            if (components.Count == 0)
            {
                host.SetRootComponent(component);
                designer = new RootDesigner(component);
            }

            //FIXME: Give Mono some base designers to find! We should never encounter this!
            //else
            //	designer = TypeDescriptor.CreateDesigner (component, typeof(System.ComponentModel.Design.IDesigner));


            if (designer == null)
            {
                //component.Site = null;
                //throw new Exception ("Designer could not be obtained for this component.");
            }
            else
            {
                //track and initialise it
                designers.Add(component, designer);
                designer.Initialize(component);
            }

            //add references to referenceManager, unless root component
            if (components.Count != 1)
            {
                host.WebFormReferenceManager.AddReference(component.GetType());
            }

            //Finally put in container
            components.Add(component);

            //and broadcast completion
            OnComponentAdded(component);
        }
Пример #9
0
        private static void SetValidControlName(Control aControl, INameCreationService aNameCreationService, string aName)
        {
            LoggingService.EnterMethod();

            System.Diagnostics.Trace.Assert(aNameCreationService != null);
            string _Name = aName;
            PropertyDescriptor _PropertyDescriptor = TypeDescriptor.GetProperties(aControl)["Name"];
            System.Diagnostics.Trace.Assert(_PropertyDescriptor != null);
            if (aNameCreationService.IsValidName(_Name))
            {
                try
                {
                    _PropertyDescriptor.SetValue(aControl, _Name);
                    LoggingService.Info("The name is " + _Name + " finally.");
                    string after = _PropertyDescriptor.GetValue(aControl) as string;
                    int j = 0;
                    while (after != _Name)
                    {
                        LoggingService.Info("Naming fails, try again.");
                        _PropertyDescriptor.SetValue(aControl, _Name);
                        after = _PropertyDescriptor.GetValue(aControl) as string;
                        j++;
                        if (j > 10)
                        {
                            break;
                        }
                    }
                    LoggingService.LeaveMethod();

                    return;
                }
                catch (Exception ex)
                {
                    LoggingService.Error(ex);
                }
            }
            else
            {
                LoggingService.Warn("Name (" + _Name + ") is not valid.");
            }

            if (_Name.EndsWith("1", StringComparison.Ordinal))
            {
                _Name = _Name.TrimEnd(new char[] { '1' });
                LoggingService.Info("1 is removed from name.");
            }
            else
            {
                LoggingService.Warn("There is not 1 in the name.");
            }

            int i = 1;

            while (true)
            {
                try
                {
                    _PropertyDescriptor.SetValue(aControl, _Name + i);
                    LoggingService.Info("The name is " + _Name + i + " finally.");
                    string after = _PropertyDescriptor.GetValue(aControl) as string;
                    int j = 0;
                    while (after != _Name + i)
                    {
                        LoggingService.Info("Naming fails, try again.");
                        _PropertyDescriptor.SetValue(aControl, _Name + i);
                        after = _PropertyDescriptor.GetValue(aControl) as string;
                        j++;
                        if (j > 10)
                        {
                            break;
                        }
                    }
                    LoggingService.LeaveMethod();

                    return;
                }
                catch (Exception ex)
                {
                    LoggingService.Error(ex);
                }

                i++;

                // To be sure that we don't have an infinit loop for an
                // invalid name (Prefix)
                if (i > 100)
                {
                    LoggingService.Debug("i > 100, exit.");
                    LoggingService.LeaveMethod();

                    return;
                }
            }
        }
Пример #10
0
        public static string BuildNameFromText(
            string text,
            System.Type componentType,
            System.IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                return((string)null);
            }
            INameCreationService service1 = serviceProvider.GetService(typeof(INameCreationService)) as INameCreationService;
            IContainer           service2 = (IContainer)serviceProvider.GetService(typeof(IContainer));

            if (service1 == null || service2 == null)
            {
                return((string)null);
            }
            string name1 = service1.CreateName(service2, componentType);

            if (text == null || text.Length == 0 || text == "-")
            {
                return(name1);
            }
            string        name2         = componentType.Name;
            StringBuilder stringBuilder = new StringBuilder(text.Length + name2.Length);
            bool          flag          = false;

            for (int index = 0; index < text.Length; ++index)
            {
                char c = text[index];
                if (flag)
                {
                    if (char.IsLower(c))
                    {
                        c = char.ToUpper(c, CultureInfo.CurrentCulture);
                    }
                    flag = false;
                }
                if (char.IsLetterOrDigit(c))
                {
                    if (stringBuilder.Length == 0)
                    {
                        if (!char.IsDigit(c))
                        {
                            if (char.IsLower(c) != char.IsLower(name1[0]))
                            {
                                c = !char.IsLower(c) ? char.ToLower(c, CultureInfo.CurrentCulture) : char.ToUpper(c, CultureInfo.CurrentCulture);
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    stringBuilder.Append(c);
                }
                else if (char.IsWhiteSpace(c))
                {
                    flag = true;
                }
            }
            if (stringBuilder.Length == 0)
            {
                return(name1);
            }
            stringBuilder.Append(name2);
            string name3 = stringBuilder.ToString();

            if (service2.Components[name3] == null)
            {
                if (!service1.IsValidName(name3))
                {
                    return(name1);
                }
                return(name3);
            }
            string name4 = name3;
            int    num   = 1;

            while (!service1.IsValidName(name4) || service2.Components[name4] != null)
            {
                name4 = name3 + num.ToString((IFormatProvider)CultureInfo.InvariantCulture);
                ++num;
            }
            return(name4);
        }
Пример #11
0
 public bool IsValidName(string name)
 {
     return(nc.IsValidName(name));
 }
 public static bool ValidName(string name, DataGridViewColumnCollection columns, IContainer container, INameCreationService nameCreationService, DataGridViewColumnCollection liveColumns, bool allowDuplicateNameInLiveColumnCollection, out string errorString)
 {
     if (columns.Contains(name))
     {
         errorString = System.Design.SR.GetString("DataGridViewDuplicateColumnName", new object[] { name });
         return false;
     }
     if (((container != null) && (container.Components[name] != null)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = System.Design.SR.GetString("DesignerHostDuplicateName", new object[] { name });
         return false;
     }
     if (((nameCreationService != null) && !nameCreationService.IsValidName(name)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = System.Design.SR.GetString("CodeDomDesignerLoaderInvalidIdentifier", new object[] { name });
         return false;
     }
     errorString = string.Empty;
     return true;
 }
 public static bool ValidName(string name, DataGridViewColumnCollection columns, IContainer container, INameCreationService nameCreationService, DataGridViewColumnCollection liveColumns, bool allowDuplicateNameInLiveColumnCollection)
 {
     if (columns.Contains(name))
     {
         return false;
     }
     if (((container != null) && (container.Components[name] != null)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         return false;
     }
     return (((nameCreationService == null) || nameCreationService.IsValidName(name)) || ((allowDuplicateNameInLiveColumnCollection && (liveColumns != null)) && liveColumns.Contains(name)));
 }
 public static bool ValidName(string name, FilterColumnCollection columns, IContainer container, INameCreationService nameCreationService, FilterColumnCollection liveColumns, bool allowDuplicateNameInLiveColumnCollection, out string errorString)
 {
     if (columns.Contains(name))
     {
         errorString = "DuplicateColumnName[{0}]".FormatArgs(new object[] { name });
         return false;
     }
     if (((container != null) && (container.Components[name] != null)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = "DesignerHostDuplicateName[{0}]".FormatArgs(new object[] { name });
         return false;
     }
     if (((nameCreationService != null) && !nameCreationService.IsValidName(name)) && ((!allowDuplicateNameInLiveColumnCollection || (liveColumns == null)) || !liveColumns.Contains(name)))
     {
         errorString = "CodeDomDesignerLoaderInvalidIdentifier[{0}]".FormatArgs(new object[] { name });
         return false;
     }
     errorString = string.Empty;
     return true;
 }
 private string NameFromText(string text, System.Type itemType, INameCreationService nameCreationService, bool adjustCapitalization)
 {
     string name = null;
     if (text == "-")
     {
         name = "toolStripSeparator";
     }
     else
     {
         string str2 = itemType.Name;
         StringBuilder builder = new StringBuilder(text.Length + str2.Length);
         bool flag = false;
         for (int j = 0; j < text.Length; j++)
         {
             char c = text[j];
             if (char.IsLetterOrDigit(c))
             {
                 if (!flag)
                 {
                     c = char.ToLower(c, CultureInfo.CurrentCulture);
                     flag = true;
                 }
                 builder.Append(c);
             }
         }
         builder.Append(str2);
         name = builder.ToString();
         if (adjustCapitalization)
         {
             string str3 = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), this._designer.Component.Site);
             if (!string.IsNullOrEmpty(str3) && char.IsUpper(str3[0]))
             {
                 name = char.ToUpper(name[0], CultureInfo.InvariantCulture) + name.Substring(1);
             }
         }
     }
     if (this._host.Container.Components[name] == null)
     {
         if (!nameCreationService.IsValidName(name))
         {
             return nameCreationService.CreateName(this._host.Container, itemType);
         }
         return name;
     }
     string str4 = name;
     for (int i = 1; !nameCreationService.IsValidName(str4); i++)
     {
         str4 = name + i.ToString(CultureInfo.InvariantCulture);
     }
     return str4;
 }
Пример #16
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();
            }
        }
Пример #17
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;
                }
            }