Example #1
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);
        }
        internal string GetNewComponentName(System.Type compClass)
        {
            IServiceProvider     sp         = this;
            INameCreationService nameCreate = (INameCreationService)sp.GetService(typeof(INameCreationService));

            if (nameCreate != null)
            {
                return(nameCreate.CreateName(this.Container, compClass));
            }
            string        baseName = compClass.Name;
            StringBuilder b        = new StringBuilder(baseName.Length);

            for (int i = 0; i < baseName.Length; i++)
            {
                if (char.IsUpper(baseName[i]) && (((i == 0) || (i == (baseName.Length - 1))) || char.IsUpper(baseName[i + 1])))
                {
                    b.Append(char.ToLower(baseName[i]));
                }
                else
                {
                    b.Append(baseName.Substring(i));
                    break;
                }
            }
            baseName = b.ToString();
            int    idx       = 1;
            string finalName = baseName + idx.ToString();

            while (this.Container.Components[finalName] != null)
            {
                idx++;
                finalName = baseName + idx.ToString();
            }
            return(finalName);
        }
        private string CreateListViewGroupName(ListViewGroupCollection lvgCollection)
        {
            string lvgName = "ListViewGroup";
            string resultName;
            INameCreationService ncs       = GetService(typeof(INameCreationService)) as INameCreationService;
            IContainer           container = GetService(typeof(IContainer)) as IContainer;

            if (ncs != null && container != null)
            {
                lvgName = ncs.CreateName(container, typeof(ListViewGroup));
            }

            // strip the digits from the end.
            while (char.IsDigit(lvgName[lvgName.Length - 1]))
            {
                lvgName = lvgName.Substring(0, lvgName.Length - 1);
            }

            int i = 1;

            resultName = lvgName + i.ToString(System.Globalization.CultureInfo.CurrentCulture);

            while (lvgCollection[resultName] != null)
            {
                i++;
                resultName = lvgName + i.ToString(System.Globalization.CultureInfo.CurrentCulture);
            }

            return(resultName);
        }
        private string CreateControlName(string prevName, IContainer container, Type dataType, List <EntityCPNode> listAllComps)
        {
            INameCreationService nameService = designerHost.GetService(typeof(INameCreationService)) as INameCreationService;

            bool isValidName = true;

            if (container.Components[prevName] != null)
            {
                isValidName = false;
            }

            if (isValidName)
            {
                return(prevName);
            }
            else
            {
                string currName = nameService.CreateName(container, dataType);
                if (currName == prevName)
                {
                    return(prevName);
                }
                else
                {
                    foreach (EntityCPNode item in listAllComps)
                    {
                        if (item.ControlName == prevName)
                        {
                            item.ControlName = currName;
                        }
                    }
                    return(currName);
                }
            }
        }
        protected string GetUniqueName(IDesignerSerializationManager manager, object instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            string name = manager.GetName(instance);

            if (name == null)
            {
                INameCreationService service = manager.GetService(typeof(INameCreationService)) as INameCreationService;
                name = service.CreateName(null, instance.GetType());
                if (name == null)
                {
                    name = instance.GetType().Name.ToLower();
                }
                manager.SetName(instance, name);
            }
            return(name);
        }
 protected override bool ProcessDialogKey(Keys keyData)
 {
     if ((keyData & ~Keys.KeyCode) == Keys.None)
     {
         Keys keys = keyData & Keys.KeyCode;
         if (keys == Keys.Enter)
         {
             IDesignerHost        service             = null;
             INameCreationService nameCreationService = null;
             IContainer           container           = null;
             service = this.liveDataGridView.Site.GetService(iDesignerHostType) as IDesignerHost;
             if (service != null)
             {
                 container = service.Container;
             }
             nameCreationService = this.liveDataGridView.Site.GetService(iNameCreationServiceType) as INameCreationService;
             string errorString = string.Empty;
             if (ValidName(this.nameTextBox.Text, this.dataGridViewColumns, container, nameCreationService, this.liveDataGridView.Columns, !this.persistChangesToDesigner, out errorString))
             {
                 this.AddColumn();
                 base.Close();
             }
             else
             {
                 IUIService uiService = (IUIService)this.liveDataGridView.Site.GetService(iUIServiceType);
                 DataGridViewDesigner.ShowErrorDialog(uiService, errorString, this.liveDataGridView);
             }
             return(true);
         }
     }
     return(base.ProcessDialogKey(keyData));
 }
Example #7
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);
            }
        }
 internal void SetComponent(IComponent component)
 {
     this.component = component;
     if (name == null)
     {
         INameCreationService nameService = (INameCreationService)GetService(typeof(INameCreationService));
         name = nameService.CreateName(host.Container, component.GetType());
     }
 }
Example #9
0
        public override DesignerControlDefinition Create(INameCreationService namingService)
        {
            var uniqueName = namingService.CreateName(typeName);

            return(new DesignerControlDefinition
            {
                Control = string.Format(Properties.Snippets.HeaderControlControl, uniqueName),
                Style = string.Format(Properties.Snippets.HeaderControlStyle, uniqueName)
            });
        }
Example #10
0
        void OnDesignerLoaded(object sender, DesignerLoadedEventArgs e)
        {
            INameCreationService nc = e.DesignerHost.GetService(typeof(INameCreationService)) as INameCreationService;

            MyNameCreationService myNC = new MyNameCreationService(nc);

            e.DesignerHost.RemoveService(typeof(INameCreationService));

            e.DesignerHost.AddService(typeof(INameCreationService), myNC);
        }
 protected override ISite CreateSite(IComponent component, string name)
 {
     if (name == null)
     {
         INameCreationService nameService = this.GetService(typeof(INameCreationService)) as INameCreationService;
         if (nameService != null)
         {
             name = nameService.CreateName(this, component.GetType());
         }
     }
     return(new DesignModeSite(component, name, this, this));
 }
        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);
        }
Example #13
0
 public static IComponent CreateComponent(IDesignerLoaderHost host, Type type, string name)
 {
     if (typeof(IComponent).IsAssignableFrom(type))
     {
         if (host != null)
         {
             INameCreationService cs = host.GetService(typeof(INameCreationService)) as INameCreationService;
             if (cs != null)
             {
                 IVplNameService ns = cs as IVplNameService;
                 if (ns != null)
                 {
                     ns.ComponentType = type;
                 }
             }
             return(host.CreateComponent(type, name));
         }
         else
         {
             IComponent ic = (IComponent)CreateObject(type);
             ic.Site      = new XTypeSite(ic);
             ic.Site.Name = name;
             return(ic);
         }
     }
     if (host != null)
     {
         INameCreationService cs = host.GetService(typeof(INameCreationService)) as INameCreationService;
         if (cs != null)
         {
             IVplNameService ns = cs as IVplNameService;
             if (ns != null)
             {
                 ns.ComponentType = typeof(XClass);
             }
         }
         XClass obj = (XClass)host.CreateComponent(typeof(XClass), name);
         obj.AssignType(type);
         obj.AssignValue(CreateObject(type));
         return(obj);
     }
     else
     {
         XClass obj = new XClass();
         obj.Site      = new XTypeSite(obj);
         obj.Site.Name = name;
         obj.AssignType(type);
         obj.AssignValue(CreateObject(type));
         return(obj);
     }
 }
Example #14
0
 private string GetNewDataSourceName(System.Type dataSourceType)
 {
     if (dataSourceType != null)
     {
         ISite site = this.GetSite();
         if (site != null)
         {
             INameCreationService service = (INameCreationService)site.GetService(typeof(INameCreationService));
             if (service != null)
             {
                 return(service.CreateName(site.Container, dataSourceType));
             }
             return(site.Name + "_DataSource");
         }
     }
     return(string.Empty);
 }
Example #15
0
        private void CreateComponentName(IComponent component, ref string name)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(component);
            PropertyDescriptor           find       = properties.Find("Name", true);

            if (find != null)
            {
                string currentName = find.GetValue(component) as string;
                if (currentName != null && currentName.Length > 0)
                {
                    name = currentName;
                    return;
                }
            }
            if (name == null)
            {
                INameCreationService nameService = (INameCreationService)GetService(typeof(INameCreationService));
                name = nameService.CreateName(this, component.GetType());
            }
        }
Example #16
0
        }//end (ExecuteMethod)

        /// <summary>
        /// Return the object of Add-IN to engine.
        /// </summary>
        /// <param name="sName"></param>
        /// <returns></returns>
        public object GetObject(string sName)
        {
            ClockAddIn objClockAddIn = new ClockAddIn();

            if (m_ObjEngine != null)
            {
                objClockAddIn.SetEngine(m_ObjEngine);
            }
            if (m_objHost != null)
            {
                INameCreationService objINameCreationService = m_objHost.GetService(DesignerService.INameCreationService) as INameCreationService;
                if (objINameCreationService != null)
                {
                    objClockAddIn.SetEngine(m_ObjEngine);
                    objClockAddIn.ObjectName = objINameCreationService.GetName(this.Name);
                    return(objClockAddIn);
                }
            }
            return(objClockAddIn);
        }//end (GetObject)
        private void nameTextBox_Validating(object sender, CancelEventArgs e)
        {
            IDesignerHost        service             = null;
            INameCreationService nameCreationService = null;
            IContainer           container           = null;

            service = this.liveDataGridView.Site.GetService(iDesignerHostType) as IDesignerHost;
            if (service != null)
            {
                container = service.Container;
            }
            nameCreationService = this.liveDataGridView.Site.GetService(iNameCreationServiceType) as INameCreationService;
            string errorString = string.Empty;

            if (!ValidName(this.nameTextBox.Text, this.dataGridViewColumns, container, nameCreationService, this.liveDataGridView.Columns, !this.persistChangesToDesigner, out errorString))
            {
                IUIService uiService = (IUIService)this.liveDataGridView.Site.GetService(iUIServiceType);
                DataGridViewDesigner.ShowErrorDialog(uiService, errorString, this.liveDataGridView);
                e.Cancel = true;
            }
        }
 internal bool CheckName(string name)
 {
     if ((name == null) || (name.Length == 0))
     {
         Exception ex = new Exception("Components must have a name");
         throw ex;
     }
     if (((IContainer)this).Components[name] != null)
     {
         return(false);
     }
     if (this.nameService == null)
     {
         IServiceProvider sp = this;
         this.nameService = (INameCreationService)sp.GetService(typeof(INameCreationService));
     }
     if (this.nameService != null)
     {
         this.nameService.ValidateName(name);
     }
     return(true);
 }
Example #19
0
        public void AssertCanGetAllServices()
        {
            IContainer container = Host.GetService(typeof(IContainer)) as IContainer;

            Assert.IsNotNull(container);
            IComponentChangeService changeService = Host.GetService(typeof(IComponentChangeService)) as IComponentChangeService;

            Assert.IsNotNull(changeService);
            INodeNameCreationService nodeNameCreationService = Host.GetService(typeof(INodeNameCreationService)) as INodeNameCreationService;

            Assert.IsNotNull(nodeNameCreationService);
            INameCreationService nameCreationService = Host.GetService(typeof(INameCreationService)) as INameCreationService;

            Assert.IsNotNull(nameCreationService);
            IUIHierarchyService hierarchyService = Host.GetService(typeof(IUIHierarchyService)) as IUIHierarchyService;

            Assert.IsNotNull(hierarchyService);
            IDictionaryService dictionaryService = Host.GetService(typeof(IDictionaryService)) as IDictionaryService;

            Assert.IsNotNull(dictionaryService);
            IConfigurationErrorLogService configurationErrorLogService = Host.GetService(typeof(IConfigurationErrorLogService)) as IConfigurationErrorLogService;

            Assert.IsNotNull(configurationErrorLogService);
            INodeCreationService nodeCreationService = Host.GetService(typeof(INodeCreationService)) as INodeCreationService;

            Assert.IsNotNull(nodeCreationService);
            IXmlIncludeTypeService xmlIncludeTypeService = Host.GetService(typeof(IXmlIncludeTypeService)) as IXmlIncludeTypeService;

            Assert.IsNotNull(xmlIncludeTypeService);
            ILinkNodeService linkNodeService = Host.GetService(typeof(ILinkNodeService)) as ILinkNodeService;

            Assert.IsNotNull(linkNodeService);
            IMenuContainerService menuContainerService = Host.GetService(typeof(IMenuContainerService)) as IMenuContainerService;

            Assert.IsNotNull(menuContainerService);
        }
        private string CreateListViewGroupName(ListViewGroupCollectionEx lvgCollection)
        {
            string str = "ListViewGroupEx";
            INameCreationService service   = base.GetService(typeof(INameCreationService)) as INameCreationService;
            IContainer           container = base.GetService(typeof(IContainer)) as IContainer;

            if ((service != null) && (container != null))
            {
                str = service.CreateName(container, typeof(ListViewGroupEx));
            }
            while (char.IsDigit(str[str.Length - 1]))
            {
                str = str.Substring(0, str.Length - 1);
            }
            int    num  = 1;
            string str2 = str + num.ToString(System.Globalization.CultureInfo.CurrentCulture);

            while (lvgCollection[str2] != null)
            {
                num++;
                str2 = str + num.ToString(System.Globalization.CultureInfo.CurrentCulture);
            }
            return(str2);
        }
Example #21
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();
            }
        }
 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;
 }
 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)));
 }
 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;
 }
        //****
        //****
        //**** Sample Designer Host methods
        //****
        //****



        ///     Validates that the given name is OK to use.  Not only does it have to
        ///     be a valid identifier, but it must not already be in our container.
        internal void CheckName(string name) {

            if (name == null || name.Length == 0) {
                Exception ex = new Exception("Components must have a name");
                throw ex;
            }

            if (((IContainer)this).Components[name] != null) {
                Exception ex = new Exception("We already have a component named " + name);
                throw ex;
            }
            
            if (nameService == null) {
                IServiceProvider sp = (IServiceProvider)this;
                nameService = (INameCreationService)sp.GetService(typeof(INameCreationService));
            }
            
            if (nameService != null) {
                nameService.ValidateName(name);
            }
        }
Example #26
0
        internal void Initialize( )
        {
            Control control = null;

            DesignerHost = (IDesignerHost)this.GetService(typeof(IDesignerHost));
            if (DesignerHost == null)
            {
                return;
            }

            ((ABCControls.ABCView)DesignerHost.RootComponent).Surface = this;

            try
            {
                #region Set the backcolor
                Type hostType = DesignerHost.RootComponent.GetType();
                if (hostType == typeof(DevExpress.XtraEditors.XtraForm))
                {
                    control           = this.View as Control;
                    control.BackColor = Color.White;
                }
                else if (hostType == typeof(UserControl))
                {
                    control           = this.View as Control;
                    control.BackColor = Color.White;
                }
                else if (hostType == typeof(Component))
                {
                    control           = this.View as Control;
                    control.BackColor = Color.FloralWhite;
                }
                else if (hostType == typeof(ABCControls.ABCView))
                {
                    control = this.View as Control;
                    //      control.BackColor=Color.FloralWhite;
                }
                else
                {
                    throw new Exception("Undefined Host Type: " + hostType.ToString());
                }
                #endregion

                #region  Set Services
                ServiceSelection       = (ISelectionService)(this.ServiceContainer.GetService(typeof(ISelectionService)));
                ServiceComponentChange = (IComponentChangeService)this.ServiceContainer.GetService(typeof(IComponentChangeService));
                ServiceMenuCommand     = (IMenuCommandService)this.ServiceContainer.GetService(typeof(IMenuCommandService));
                ServiceSerializer      = (IDesignerSerializationService)this.ServiceContainer.GetService(typeof(IDesignerSerializationService));

                #region Undo
                UndoEngine = new UndoEngineImpl(this.ServiceContainer);
                UndoEngine.CanUndoChanged += new EventHandler(UndoEngine_CanUndoChanged);
                UndoEngine.CanRedoChanged += new EventHandler(UndoEngine_CanRedoChanged);

                //disable the UndoEngine
                UndoEngine.Enabled = false;
                if (UndoEngine != null)
                {
                    //- the UndoEngine is ready to be replaced
                    this.ServiceContainer.RemoveService(typeof(UndoEngine), false);
                    this.ServiceContainer.AddService(typeof(UndoEngine), UndoEngine);
                }
                #endregion

                NameCreationService = (INameCreationService)(this.GetService(typeof(INameCreationService)));

                #endregion

                ((System.Windows.Forms.Control)(this.View)).PreviewKeyDown += new PreviewKeyDownEventHandler(HostSurface_PreviewKeyDown);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
        }
Example #27
0
 public DesignerControlCreatorService(INameCreationService namingService)
 {
     _namingService = namingService;
 }
Example #28
0
        /// <include file='doc\InstanceDescriptorCodeDomSerializer.uex' path='docs/doc[@for="InstanceDescriptorCodeDomSerializer.Serialize"]/*' />
        /// <devdoc>
        ///     Serializes the given object into a CodeDom object.
        /// </devdoc>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            object expression = null;

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "InstanceDescriptorCodeDomSerializer::Serialize");
            Debug.Indent();

            // To serialize a primitive type, we must assign its value to the current statement.  We get the current
            // statement by asking the context.

            object statement = manager.Context.Current;

            Debug.Assert(statement != null, "Statement is null -- we need a context to be pushed for instance descriptors to serialize");

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Value: " + value.ToString());
            Debug.WriteLineIf(traceSerialization.TraceVerbose && statement != null, "Statement: " + statement.GetType().Name);

            TypeConverter      converter  = TypeDescriptor.GetConverter(value);
            InstanceDescriptor descriptor = (InstanceDescriptor)converter.ConvertTo(value, typeof(InstanceDescriptor));

            if (descriptor != null)
            {
                expression = SerializeInstanceDescriptor(manager, value, descriptor);
            }
            else
            {
                Debug.WriteLineIf(traceSerialization.TraceError, "*** Converter + " + converter.GetType().Name + " failed to give us an instance descriptor");
            }

            // Ok, we have the "new Foo(arg, arg, arg)" done.  Next, check to see if the instance
            // descriptor has given us a complete representation of the object.  If not, we must
            // go through the additional work of creating a local variable and saving properties.
            //
            if (descriptor != null && !descriptor.IsComplete)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Incomplete instance descriptor; creating local variable declaration and serializing properties.");
                CodeStatementCollection statements = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)];
                Debug.WriteLineIf(traceSerialization.TraceError && statements == null, "*** No CodeStatementCollection on context stack so we can generate a local variable statement.");

                if (statements != null)
                {
                    MemberInfo mi = descriptor.MemberInfo;
                    Type       targetType;

                    if (mi is PropertyInfo)
                    {
                        targetType = ((PropertyInfo)mi).PropertyType;
                    }
                    else if (mi is MethodInfo)
                    {
                        targetType = ((MethodInfo)mi).ReturnType;
                    }
                    else
                    {
                        targetType = mi.DeclaringType;
                    }

                    string localName = manager.GetName(value);

                    if (localName == null)
                    {
                        string baseName;

                        INameCreationService ns = (INameCreationService)manager.GetService(typeof(INameCreationService));
                        Debug.WriteLineIf(traceSerialization.TraceWarning && (ns == null), "WARNING: Need to generate name for local variable but we have no service.");

                        if (ns != null)
                        {
                            baseName = ns.CreateName(null, targetType);
                        }
                        else
                        {
                            baseName = targetType.Name.ToLower(CultureInfo.InvariantCulture);
                        }

                        int suffixIndex = 1;

                        // Declare this name to the serializer.  If there is already a name defined,
                        // keep trying.
                        //
                        while (true)
                        {
                            localName = baseName + suffixIndex.ToString();

                            if (manager.GetInstance(localName) == null)
                            {
                                manager.SetName(value, localName);
                                break;
                            }

                            suffixIndex++;
                        }
                    }

                    Debug.WriteLineIf(traceSerialization.TraceVerbose, "Named local variable " + localName);

                    CodeVariableDeclarationStatement localStatement = new CodeVariableDeclarationStatement(targetType, localName);
                    localStatement.InitExpression = (CodeExpression)expression;
                    statements.Add(localStatement);

                    expression = new CodeVariableReferenceExpression(localName);

                    // Create a CodeValueExpression to place on the context stack.
                    CodeValueExpression cve = new CodeValueExpression((CodeExpression)expression, value);

                    manager.Context.Push(cve);

                    try {
                        // Now that we have hooked the return expression up and declared the local,
                        // it's time to save off the properties for the object.
                        //
                        SerializeProperties(manager, statements, value, runTimeProperties);
                    }
                    finally {
                        Debug.Assert(manager.Context.Current == cve, "Context stack corrupted");
                        manager.Context.Pop();
                    }
                }
            }

            Debug.Unindent();
            return(expression);
        }
        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;
                }
            }
        }
 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);
             }
         }
     }
 }
Example #31
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);
        }
 internal bool CheckName(string name)
 {
     if ((name == null) || (name.Length == 0))
     {
         Exception ex = new Exception("Components must have a name");
         throw ex;
     }
     if (((IContainer) this).Components[name] != null)
     {
         return false;
     }
     if (this.nameService == null)
     {
         IServiceProvider sp = this;
         this.nameService = (INameCreationService) sp.GetService(typeof(INameCreationService));
     }
     if (this.nameService != null)
     {
         this.nameService.ValidateName(name);
     }
     return true;
 }
        /// <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);
            }
        }
Example #34
0
        public void NameCreationServiceCreated()
        {
            INameCreationService nameCreationService = (INameCreationService)loaderHost.GetService(typeof(INameCreationService));

            Assert.IsTrue(nameCreationService is XmlDesignerLoader.NameCreationService);
        }
 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;
 }
        /// <summary>
        ///  Here is where all the fun stuff starts.  We create the structure and apply the naming here.
        /// </summary>
        private void CreateStandardToolStrip(IDesignerHost host, ToolStrip tool)
        {
            // build the static menu items structure.
            //
            string[] menuItemNames = new string[] { SR.StandardMenuNew, SR.StandardMenuOpen, SR.StandardMenuSave, SR.StandardMenuPrint, "-", SR.StandardToolCut, SR.StandardMenuCopy, SR.StandardMenuPaste, "-", SR.StandardToolHelp };

            // build a image list mapping one-one the above menuItems list... this is required so that the in LOCALIZED build we dont use the Localized item string.
            string[] menuItemImageNames = new string[] { "new", "open", "save", "print", "-", "cut", "copy", "paste", "-", "help" };
            Debug.Assert(host != null, "can't create standard menu without designer _host.");

            if (host is null)
            {
                return;
            }

            tool.SuspendLayout();
            ToolStripDesigner.s_autoAddNewItems = false;
            // create a transaction so this happens as an atomic unit.
            DesignerTransaction createMenu = _host.CreateTransaction(SR.StandardMenuCreateDesc);

            try
            {
                INameCreationService nameCreationService = (INameCreationService)_provider.GetService(typeof(INameCreationService));
                string defaultName = "standardMainToolStrip";
                string name        = defaultName;
                int    index       = 1;
                if (host != null)
                {
                    while (_host.Container.Components[name] != null)
                    {
                        name = defaultName + (index++).ToString(CultureInfo.InvariantCulture);
                    }
                }

                //keep an index in the MenuItemImageNames .. so that mapping is maintained.
                int menuItemImageNamesCount = 0;
                // now build the menu items themselves.
                foreach (string itemText in menuItemNames)
                {
                    name = null;
                    // for separators, just use the default name.  Otherwise, remove any non-characters and get the name from the text.
                    defaultName = "ToolStripButton";
                    name        = NameFromText(itemText, typeof(ToolStripButton), nameCreationService, true);
                    ToolStripItem item = null;
                    if (name.Contains("Separator"))
                    {
                        // create the componennt.
                        item = (ToolStripSeparator)_host.CreateComponent(typeof(ToolStripSeparator), name);
                        IDesigner designer = _host.GetDesigner(item);
                        if (designer is ComponentDesigner)
                        {
                            ((ComponentDesigner)designer).InitializeNewComponent(null);
                        }
                    }
                    else
                    {
                        // create the component.
                        item = (ToolStripButton)_host.CreateComponent(typeof(ToolStripButton), name);
                        IDesigner designer = _host.GetDesigner(item);
                        if (designer is ComponentDesigner)
                        {
                            ((ComponentDesigner)designer).InitializeNewComponent(null);
                        }

                        PropertyDescriptor displayStyleProperty = TypeDescriptor.GetProperties(item)["DisplayStyle"];
                        Debug.Assert(displayStyleProperty != null, "Could not find 'Text' property in ToolStripItem.");
                        if (displayStyleProperty != null)
                        {
                            displayStyleProperty.SetValue(item, ToolStripItemDisplayStyle.Image);
                        }

                        PropertyDescriptor textProperty = TypeDescriptor.GetProperties(item)["Text"];
                        Debug.Assert(textProperty != null, "Could not find 'Text' property in ToolStripItem.");
                        if (textProperty != null)
                        {
                            textProperty.SetValue(item, itemText);
                        }

                        Bitmap image = null;
                        try
                        {
                            image = GetImage(menuItemImageNames[menuItemImageNamesCount]);
                        }
                        catch
                        {
                            // eat the exception.. as you may not find image for all MenuItems.
                        }

                        if (image != null)
                        {
                            PropertyDescriptor imageProperty = TypeDescriptor.GetProperties(item)["Image"];
                            Debug.Assert(imageProperty != null, "Could not find 'Image' property in ToolStripItem.");
                            if (imageProperty != null)
                            {
                                imageProperty.SetValue(item, image);
                            }

                            item.ImageTransparentColor = Color.Magenta;
                        }
                    }

                    tool.Items.Add(item);
                    //increment the counter...
                    menuItemImageNamesCount++;
                }

                // finally, add it to the Main ToolStrip.
                MemberDescriptor topMember = TypeDescriptor.GetProperties(tool)["Items"];
                _componentChangeSvc.OnComponentChanging(tool, topMember);
                _componentChangeSvc.OnComponentChanged(tool, topMember, null, null);
            }
            catch (Exception e)
            {
                if (e is InvalidOperationException)
                {
                    IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService));
                    uiService.ShowError(e.Message);
                }

                if (createMenu != null)
                {
                    createMenu.Cancel();
                    createMenu = null;
                }
            }
            finally
            {
                //Reset the AutoAdd state
                ToolStripDesigner.s_autoAddNewItems = true;
                if (createMenu != null)
                {
                    createMenu.Commit();
                    createMenu = null;
                }

                tool.ResumeLayout();
                // Select the Main Menu...
                ISelectionService selSvc = (ISelectionService)_provider.GetService(typeof(ISelectionService));
                if (selSvc != null)
                {
                    selSvc.SetSelectedComponents(new object[] { _designer.Component });
                }

                //Refresh the Glyph
                DesignerActionUIService actionUIService = (DesignerActionUIService)_provider.GetService(typeof(DesignerActionUIService));
                if (actionUIService != null)
                {
                    actionUIService.Refresh(_designer.Component);
                }

                // this will invalidate the Selection Glyphs.
                SelectionManager selMgr = (SelectionManager)_provider.GetService(typeof(SelectionManager));
                selMgr.Refresh();
            }
        }
        /// <summary>
        ///  Here is where all the fun stuff starts.  We create the structure and apply the naming here.
        /// </summary>
        private void CreateStandardMenuStrip(IDesignerHost host, MenuStrip tool)
        {
            // build the static menu items structure.
            string[][] menuItemNames = new string[][]
            {
                new string[] { SR.StandardMenuFile, SR.StandardMenuNew, SR.StandardMenuOpen, "-", SR.StandardMenuSave, SR.StandardMenuSaveAs, "-", SR.StandardMenuPrint, SR.StandardMenuPrintPreview, "-", SR.StandardMenuExit },
                new string[] { SR.StandardMenuEdit, SR.StandardMenuUndo, SR.StandardMenuRedo, "-", SR.StandardMenuCut, SR.StandardMenuCopy, SR.StandardMenuPaste, "-", SR.StandardMenuSelectAll },
                new string[] { SR.StandardMenuTools, SR.StandardMenuCustomize, SR.StandardMenuOptions },
                new string[] { SR.StandardMenuHelp, SR.StandardMenuContents, SR.StandardMenuIndex, SR.StandardMenuSearch, "-", SR.StandardMenuAbout }
            };

            // build the static menu items image list that maps one-one with above menuItems structure. this is required so that the in LOCALIZED build we dont use the Localized item string.
            string[][] menuItemImageNames = new string[][]
            {
                new string[] { "", "new", "open", "-", "save", "", "-", "print", "printPreview", "-", "" },
                new string[] { "", "", "", "-", "cut", "copy", "paste", "-", "" },
                new string[] { "", "", "" },
                new string[] { "", "", "", "", "-", "" }
            };

            Keys[][] menuItemShortcuts = new Keys[][]
            {
                new Keys[] { /*File*/ Keys.None, /*New*/ Keys.Control | Keys.N, /*Open*/ Keys.Control | Keys.O, /*Separator*/ Keys.None, /*Save*/ Keys.Control | Keys.S, /*SaveAs*/ Keys.None, Keys.None, /*Print*/ Keys.Control | Keys.P, /*PrintPreview*/ Keys.None, /*Separator*/ Keys.None, /*Exit*/ Keys.None },
                new Keys[] { /*Edit*/ Keys.None, /*Undo*/ Keys.Control | Keys.Z, /*Redo*/ Keys.Control | Keys.Y, /*Separator*/ Keys.None, /*Cut*/ Keys.Control | Keys.X, /*Copy*/ Keys.Control | Keys.C, /*Paste*/ Keys.Control | Keys.V, /*Separator*/ Keys.None, /*SelectAll*/ Keys.None },
                new Keys[] { /*Tools*/ Keys.None, /*Customize*/ Keys.None, /*Options*/ Keys.None },
                new Keys[] { /*Help*/ Keys.None, /*Contents*/ Keys.None, /*Index*/ Keys.None, /*Search*/ Keys.None, /*Separator*/ Keys.None, /*About*/ Keys.None }
            };

            Debug.Assert(host != null, "can't create standard menu without designer _host.");
            if (host is null)
            {
                return;
            }

            tool.SuspendLayout();
            ToolStripDesigner.s_autoAddNewItems = false;
            // create a transaction so this happens as an atomic unit.
            DesignerTransaction createMenu = _host.CreateTransaction(SR.StandardMenuCreateDesc);

            try
            {
                INameCreationService nameCreationService = (INameCreationService)_provider.GetService(typeof(INameCreationService));
                string defaultName = "standardMainMenuStrip";
                string name        = defaultName;
                int    index       = 1;

                if (host != null)
                {
                    while (_host.Container.Components[name] != null)
                    {
                        name = defaultName + (index++).ToString(CultureInfo.InvariantCulture);
                    }
                }

                // now build the menu items themselves.
                for (int j = 0; j < menuItemNames.Length; j++)
                {
                    string[]          menuArray = menuItemNames[j];
                    ToolStripMenuItem rootItem  = null;
                    for (int i = 0; i < menuArray.Length; i++)
                    {
                        name = null;
                        // for separators, just use the default name.  Otherwise, remove any non-characters and  get the name from the text.
                        string itemText = menuArray[i];
                        name = NameFromText(itemText, typeof(ToolStripMenuItem), nameCreationService, true);
                        ToolStripItem item = null;
                        if (name.Contains("Separator"))
                        {
                            // create the componennt.
                            item = (ToolStripSeparator)_host.CreateComponent(typeof(ToolStripSeparator), name);
                            IDesigner designer = _host.GetDesigner(item);
                            if (designer is ComponentDesigner)
                            {
                                ((ComponentDesigner)designer).InitializeNewComponent(null);
                            }

                            item.Text = itemText;
                        }
                        else
                        {
                            // create the componennt.
                            item = (ToolStripMenuItem)_host.CreateComponent(typeof(ToolStripMenuItem), name);
                            IDesigner designer = _host.GetDesigner(item);
                            if (designer is ComponentDesigner)
                            {
                                ((ComponentDesigner)designer).InitializeNewComponent(null);
                            }

                            item.Text = itemText;
                            Keys shortcut = menuItemShortcuts[j][i];
                            if ((item is ToolStripMenuItem) && shortcut != Keys.None)
                            {
                                if (!ToolStripManager.IsShortcutDefined(shortcut) && ToolStripManager.IsValidShortcut(shortcut))
                                {
                                    ((ToolStripMenuItem)item).ShortcutKeys = shortcut;
                                }
                            }

                            Bitmap image = null;
                            try
                            {
                                image = GetImage(menuItemImageNames[j][i]);
                            }
                            catch
                            {
                                // eat the exception.. as you may not find image for all MenuItems.
                            }

                            if (image != null)
                            {
                                PropertyDescriptor imageProperty = TypeDescriptor.GetProperties(item)["Image"];
                                Debug.Assert(imageProperty != null, "Could not find 'Image' property in ToolStripItem.");
                                if (imageProperty != null)
                                {
                                    imageProperty.SetValue(item, image);
                                }

                                item.ImageTransparentColor = Color.Magenta;
                            }
                        }

                        // the first item in each array is the root item.
                        if (i == 0)
                        {
                            rootItem = (ToolStripMenuItem)item;
                            rootItem.DropDown.SuspendLayout();
                        }
                        else
                        {
                            rootItem.DropDownItems.Add(item);
                        }

                        //If Last SubItem Added the Raise the Events
                        if (i == menuArray.Length - 1)
                        {
                            // member is OK to be null...
                            MemberDescriptor member = TypeDescriptor.GetProperties(rootItem)["DropDownItems"];
                            _componentChangeSvc.OnComponentChanging(rootItem, member);
                            _componentChangeSvc.OnComponentChanged(rootItem, member, null, null);
                        }
                    }

                    // finally, add it to the MainMenu.
                    rootItem.DropDown.ResumeLayout(false);
                    tool.Items.Add(rootItem);
                    //If Last SubItem Added the Raise the Events
                    if (j == menuItemNames.Length - 1)
                    {
                        // member is OK to be null...
                        MemberDescriptor topMember = TypeDescriptor.GetProperties(tool)["Items"];
                        _componentChangeSvc.OnComponentChanging(tool, topMember);
                        _componentChangeSvc.OnComponentChanged(tool, topMember, null, null);
                    }
                }
            }
            catch (Exception e)
            {
                if (e is InvalidOperationException)
                {
                    IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService));
                    uiService.ShowError(e.Message);
                }

                if (createMenu != null)
                {
                    createMenu.Cancel();
                    createMenu = null;
                }
            }
            finally
            {
                ToolStripDesigner.s_autoAddNewItems = true;
                if (createMenu != null)
                {
                    createMenu.Commit();
                    createMenu = null;
                }

                tool.ResumeLayout();
                // Select the Main Menu...
                ISelectionService selSvc = (ISelectionService)_provider.GetService(typeof(ISelectionService));
                if (selSvc != null)
                {
                    selSvc.SetSelectedComponents(new object[] { _designer.Component });
                }

                //Refresh the Glyph
                DesignerActionUIService actionUIService = (DesignerActionUIService)_provider.GetService(typeof(DesignerActionUIService));
                if (actionUIService != null)
                {
                    actionUIService.Refresh(_designer.Component);
                }

                // this will invalidate the Selection Glyphs.
                SelectionManager selMgr = (SelectionManager)_provider.GetService(typeof(SelectionManager));
                selMgr.Refresh();
            }
        }