public void SetUpFixture() { using (DesignSurface designSurface = new DesignSurface(typeof(Form))) { IDesignerHost host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost)); IEventBindingService eventBindingService = new MockEventBindingService(host); host.AddService(typeof(IEventBindingService), eventBindingService); Form form = (Form)host.RootComponent; form.ClientSize = new Size(200, 300); PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(form); PropertyDescriptor namePropertyDescriptor = descriptors.Find("Name", false); namePropertyDescriptor.SetValue(form, "MainForm"); // Simulate giving a name to the Load event handler in the property grid. EventDescriptorCollection events = TypeDescriptor.GetEvents(form); EventDescriptor loadEvent = events.Find("Load", false); PropertyDescriptor loadEventProperty = eventBindingService.GetEventProperty(loadEvent); loadEventProperty.SetValue(form, "MainFormLoad"); // Add a second event handler method. EventDescriptor closedEvent = events.Find("FormClosed", false); PropertyDescriptor closedEventProperty = eventBindingService.GetEventProperty(closedEvent); closedEventProperty.SetValue(form, "MainFormClosed"); DesignerSerializationManager serializationManager = new DesignerSerializationManager(host); using (serializationManager.CreateSession()) { PythonCodeDomSerializer serializer = new PythonCodeDomSerializer(" "); generatedPythonCode = serializer.GenerateInitializeComponentMethodBody(host, serializationManager, String.Empty, 1); } } }
public void Find_Key_Null() { EventDescriptorCollection descriptors = new EventDescriptorCollection( new EventDescriptor[] { new MockEventDescriptor("A", "X"), new MockEventDescriptor("b", "Y") }); Assert.IsNull(descriptors.Find(null, false), "#1"); Assert.IsNull(descriptors.Find(null, true), "#2"); }
// <Snippet1> private void FindEvent() { // Creates a new collection and assigns it the events for button1. EventDescriptorCollection events = TypeDescriptor.GetEvents(button1); // Sets an EventDescriptor to the specific event. EventDescriptor myEvent = events.Find("Resize", false); // Prints the event name and event description. textBox1.Text = myEvent.Name + ": " + myEvent.Description; }
public void SetUpFixture() { using (DesignSurface designSurface = new DesignSurface(typeof(Form))) { IDesignerHost host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost)); IEventBindingService eventBindingService = new MockEventBindingService(host); host.AddService(typeof(IEventBindingService), eventBindingService); Form form = (Form)host.RootComponent; form.ClientSize = new Size(284, 264); PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(form); PropertyDescriptor namePropertyDescriptor = descriptors.Find("Name", false); namePropertyDescriptor.SetValue(form, "MainForm"); Panel panel = (Panel)host.CreateComponent(typeof(Panel), "panel1"); panel.Location = new Point(10, 15); panel.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; panel.TabIndex = 0; panel.Size = new Size(100, 120); TextBox textBox = (TextBox)host.CreateComponent(typeof(TextBox), "textBox1"); textBox.Location = new Point(5, 5); textBox.TabIndex = 0; textBox.Size = new Size(110, 20); panel.Controls.Add(textBox); // Add an event handler to the panel to check that this code is generated // before the text box is initialized. EventDescriptorCollection events = TypeDescriptor.GetEvents(panel); EventDescriptor clickEvent = events.Find("Click", false); PropertyDescriptor clickEventProperty = eventBindingService.GetEventProperty(clickEvent); clickEventProperty.SetValue(panel, "Panel1Click"); form.Controls.Add(panel); DesignerSerializationManager serializationManager = new DesignerSerializationManager(host); using (serializationManager.CreateSession()) { RubyCodeDomSerializer serializer = new RubyCodeDomSerializer(" "); generatedRubyCode = serializer.GenerateInitializeComponentMethodBody(host, serializationManager, 1); } } }
EventDescriptorCollection ITypeDescriptionProvider.GetEvents() { EventDescriptorCollection col1 = Provider.GetEvents(); EventDescriptorCollection col2 = BaseTypeDescriptor.GetEvents(); EventDescriptorCollection col = new EventDescriptorCollection(new EventDescriptor[0]); foreach (EventDescriptor ed in col1) { col.Add(ed); } foreach (EventDescriptor ed in col2) { if (col.Find(ed.Name, false) == null) { col.Add(ed); } } return(col); }
public ServerObjectParsingObject(Type type, Hashtable attributes, string tagid, ParsingObject parent) : base(tagid, parent) { //create the object if (type.GetInterface("System.ComponentModel.IComponent") != null) { //note: this automatically adds to parent's container, as some controls //need to be sited e.g. if they use site dictionaries //TODO: should this action be passed up the tree so controls can intercept? obj = ((AspNetEdit.Editor.ComponentModel.DesignerHost)base.DesignerHost).CreateComponent(type, attributes["ID"] as string, false); } else { obj = Activator.CreateInstance(type); } //and populate it from the attributes pdc = TypeDescriptor.GetProperties(obj); foreach (DictionaryEntry de in attributes) { if (0 == string.Compare((string)de.Key, "runat")) { continue; } if (0 == string.Compare((string)de.Key, "ID")) { continue; } //use the dash subproperty syntax string[] str = ((string)de.Key).Split('-'); PropertyDescriptor pd = pdc.Find(str[0], true); //if property not found, try events if (str.Length == 1 && pd == null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(str[0].ToLower(), "on")) { IEventBindingService iebs = (IEventBindingService)DesignerHost.GetService(typeof(IEventBindingService)); if (iebs == null) { throw new Exception("Could not obtain IEventBindingService from host"); } EventDescriptorCollection edc = TypeDescriptor.GetEvents(obj); EventDescriptor e = edc.Find(str[0].Remove(0, 2), true); if (e != null) { pd = iebs.GetEventProperty(e); } else { throw new Exception("Could not find event " + str[0].Remove(0, 2)); } } object loopObj = obj; for (int i = 0; i < str.Length; i++) { if (pd == null) { throw new Exception("Could not find property " + (string)de.Key); } if (i == str.Length - 1) { pd.SetValue(obj, pd.Converter.ConvertFromString((string)de.Value)); break; } loopObj = pd.GetValue(loopObj); pd = TypeDescriptor.GetProperties(loopObj).Find(str[0], true); } } parseAtt = TypeDescriptor.GetAttributes(obj)[typeof(ParseChildrenAttribute)] as ParseChildrenAttribute; //FIXME: fix this in MCS classlib if (parseAtt.DefaultProperty.Length == 0) { parseAtt = null; } //work out how we're trying to parse the children if (parseAtt != null) { if (parseAtt.DefaultProperty != null) { PropertyDescriptor pd = pdc[parseAtt.DefaultProperty]; if (pd == null) { throw new Exception("Default property does not exist"); } if (pd.PropertyType.GetInterface("System.Collections.IList") == (typeof(IList))) { mode = ParseChildrenMode.DefaultCollectionProperty; } else { mode = ParseChildrenMode.DefaultProperty; } } else if (parseAtt.ChildrenAsProperties) { mode = ParseChildrenMode.Properties; } else { mode = ParseChildrenMode.Controls; } } else { //FIXME: these are actually persistence hints, but ParseChildrenAttribute doesn't always exist. //FIXME: logic would be dodgy with bad input parseAtt = ParseChildrenAttribute.Default; mode = ParseChildrenMode.Controls; foreach (PropertyDescriptor pd in pdc) { PersistenceModeAttribute modeAttrib = pd.Attributes[typeof(PersistenceModeAttribute)] as PersistenceModeAttribute; if (modeAttrib == null) { return; } switch (modeAttrib.Mode) { case PersistenceMode.Attribute: continue; case PersistenceMode.EncodedInnerDefaultProperty: parseAtt.DefaultProperty = pd.Name; mode = ParseChildrenMode.DefaultEncodedProperty; break; case PersistenceMode.InnerDefaultProperty: parseAtt.DefaultProperty = pd.Name; if (pd.PropertyType.GetInterface("System.Collections.IList") == (typeof(IList))) { mode = ParseChildrenMode.DefaultCollectionProperty; } else { mode = ParseChildrenMode.DefaultProperty; } break; case PersistenceMode.InnerProperty: mode = ParseChildrenMode.Properties; break; } } } }
public void Find() { EventDescriptor descA = new MockEventDescriptor("hehe_\u0061\u030a", null); EventDescriptor descB = new MockEventDescriptor("heh_\u00e5", null); EventDescriptor descC = new MockEventDescriptor("Foo", null); EventDescriptor descD = new MockEventDescriptor("FOo", null); EventDescriptor descE = new MockEventDescriptor("Aim", null); EventDescriptor descF = new MockEventDescriptor("Bar", null); EventDescriptorCollection col = new EventDescriptorCollection( new EventDescriptor [] { descA, descB, descC, descD, descE, descF }); Assert.IsNull(col.Find("heh_\u0061\u030a", false), "#1"); Assert.IsNull(col.Find("hehe_\u00e5", false), "#2"); Assert.AreSame(descA, col.Find("hehe_\u0061\u030a", false), "#3"); Assert.AreSame(descB, col.Find("heh_\u00e5", false), "#4"); Assert.IsNull(col.Find("foo", false), "#5"); Assert.AreSame(descC, col.Find("foo", true), "#6"); Assert.AreSame(descD, col.Find("FOo", false), "#7"); Assert.AreSame(descC, col.Find("FOo", true), "#8"); Assert.IsNull(col.Find("fOo", false), "#9"); Assert.AreSame(descC, col.Find("fOo", true), "#10"); Assert.IsNull(col.Find("AIm", false), "#11"); Assert.AreSame(descE, col.Find("AIm", true), "#12"); Assert.IsNull(col.Find("AiM", false), "#13"); Assert.AreSame(descE, col.Find("AiM", true), "#14"); Assert.AreSame(descE, col.Find("Aim", false), "#15"); Assert.AreSame(descE, col.Find("Aim", true), "#16"); }
private void AddPropertyInternal(string name, string value, ControlBuilder builder, bool fItemProp) { PropertySetterEntry entry = new PropertySetterEntry(); bool fTemplate = false; string nameForCodeGen = null; entry._value = value; entry._builder = builder; entry._fItemProp = fItemProp; MemberInfo memberInfo = null; PropertyInfo propInfo = null; FieldInfo fieldInfo = null; // Is the property a template? if (builder != null && builder is TemplateBuilder) { fTemplate = true; } if (_objType != null && name != null) // attempt to locate a public property or field // of given name on this type of object { memberInfo = PropertyMapper.GetMemberInfo(_objType, name, out nameForCodeGen); } if (memberInfo != null) // memberInfo may be a PropertyInfo or FieldInfo { if (memberInfo is PropertyInfo) // public property { propInfo = (PropertyInfo)memberInfo; entry._propType = propInfo.PropertyType; if (propInfo.GetSetMethod() == null) // property is readonly { if (builder == null && !_fSupportsAttributes) // only complex property is allowed to be readonly { throw new HttpException( HttpRuntime.FormatResourceString(SR.Property_readonly, name)); } if (builder != null) // complex property is allowed to be readonly // set a flag to note that property is readonly { entry._fReadOnlyProp = true; } else if (_fSupportsAttributes) // allow attribute to be set via SetAttribute { entry._propType = null; entry._name = name; } } } else // public field { fieldInfo = (FieldInfo)memberInfo; entry._propType = fieldInfo.FieldType; } if (entry._propType != null) { entry._propInfo = propInfo; entry._fieldInfo = fieldInfo; entry._name = nameForCodeGen; // If it's a databound prop, we don't want to mess with the value, // since it's a piece of code. if (!_fDataBound) { // check that the property is persistable, i.e., it makes sense to have it in // the aspx template if (_checkPersistable && nameForCodeGen != null) { PropertyDescriptor propDesc = _descriptors[nameForCodeGen]; if (propDesc != null) { if (propDesc.Attributes.Contains(DesignerSerializationVisibilityAttribute.Hidden)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Property_Not_Persistable, name)); } } } else { if (_isHtmlControl) { PropertyDescriptor propDesc = _descriptors[nameForCodeGen]; if (propDesc != null) { if (propDesc.Attributes.Contains(HtmlControlPersistableAttribute.No)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Property_Not_Persistable, name)); } } } } entry._propValue = PropertyConverter.ObjectFromString(entry._propType, memberInfo, entry._value); // use actual property value to get the proper case-sensitive name for enum types if (entry._propType.IsEnum) { if (entry._propValue == null) { throw new HttpException( HttpRuntime.FormatResourceString(SR.Invalid_enum_value, entry._value, name, entry._propType.FullName)); } entry._value = Enum.Format(entry._propType, entry._propValue, "G"); } else if (entry._propType == typeof(Boolean)) { // get the proper case-sensitive value for boolean if (entry._value != null && entry._value.Length > 0) { entry._value = entry._value.ToLower(CultureInfo.InvariantCulture); } else { entry._propValue = true; } } if (fTemplate) { // Check if the property has a TemplateContainerAttribute, and if // it does, get the type out of it. TemplateContainerAttribute templateAttrib = (TemplateContainerAttribute)Attribute.GetCustomAttribute(propInfo, typeof(TemplateContainerAttribute), false); if (templateAttrib != null) { if (!typeof(INamingContainer).IsAssignableFrom(templateAttrib.ContainerType)) { throw new HttpException(HttpRuntime.FormatResourceString( SR.Invalid_template_container, name, templateAttrib.ContainerType.FullName)); } builder._ctrlType = templateAttrib.ContainerType; } } } } } else if (fItemProp) { } else // could not locate a public property or field // determine if there is an event of this name. // do not look for events when running in designer { if (!_fInDesigner && _objType != null && name.Length >= 2 && string.Compare(name.Substring(0, 2), "on", true, CultureInfo.InvariantCulture) == 0) { string eventName = name.Substring(2); if (_eventDescs == null) { _eventDescs = TypeDescriptor.GetEvents(_objType); } EventDescriptor eventFound = _eventDescs.Find(eventName, true); if (eventFound != null) // an Add method has been located { PropertySetterEventEntry eventEntry = new PropertySetterEventEntry(); eventEntry._eventName = eventFound.Name; eventEntry._handlerType = eventFound.EventType; if (value == null || value.Length == 0) { throw new HttpException( HttpRuntime.FormatResourceString(SR.Event_handler_cant_be_empty, name)); } eventEntry._handlerMethodName = value; if (_events == null) { _events = new ArrayList(3); } // add to the list of events _events.Add(eventEntry); return; } } // If attributes are not supported, or the property is a template or a // complex property (which cannot be set through SetAttribute), fail. if (!_fInDesigner && (!_fSupportsAttributes || builder != null)) { if (_objType != null) { throw new HttpException( HttpRuntime.FormatResourceString(SR.Type_doesnt_have_property, _objType.FullName, name)); } if (String.Compare(name, "name", true, CultureInfo.InvariantCulture) != 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Templates_cannot_have_properties)); } else { return; } } // use the original property name for generic SetAttribute entry._name = name; } if (_entries == null) { _entries = new ArrayList(3); } // add entry to the list _entries.Add(entry); }
/// <summary> /// Parses the control's tag and sets the properties of the corresponding component /// </summary> /// <description> /// Parses the control's tag's attributes and sets the component's properties. /// The method can filter all the properties which are not explicitly set as attributes /// and set them to their default value. That functionality is useful when an undo /// is performed and we have to revert the component's stage. /// </description> /// <param name='element'> /// The ASP.NET tag /// </param> /// <param name='component'> /// The sited component /// </param> /// <param name='checkForDefaults'> /// Filter the non-explicitly defined properties and set them to the default value. /// </param> void ProcessControlProperties(XElement element, IComponent component, bool checkForDefaults) { if (component is ListControl) { ParseListItems(component as ListControl, element); } if ((component is HtmlContainerControl) && !element.IsSelfClosing) { var containerControl = component as HtmlContainerControl; containerControl.InnerHtml = GetTextFromEditor(element.Region.End, element.ClosingTag.Region.Begin); } // get only the properties that can be browsed through the property grid and that are not read-only Attribute[] filter = new Attribute[] { BrowsableAttribute.Yes, ReadOnlyAttribute.No }; PropertyDescriptorCollection pCollection = TypeDescriptor.GetProperties(component.GetType(), filter); PropertyDescriptor desc = null; EventDescriptorCollection eCollection = TypeDescriptor.GetEvents(component.GetType(), filter); EventDescriptor evDesc = null; List <PropertyDescriptor> explicitDeclarations = new List <PropertyDescriptor> (); foreach (XAttribute attr in element.Attributes) { desc = pCollection.Find(attr.Name.Name, true); // if we have an event attribute if (desc == null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(attr.Name.Name.ToLower(), "on")) { IEventBindingService iebs = host.GetService(typeof(IEventBindingService)) as IEventBindingService; if (iebs == null) { throw new Exception("Could not obtain IEventBindingService from host"); } // remove the "on" prefix from the attribute's name string eventName = attr.Name.Name.Remove(0, 2); // try to find an event descriptor with that name evDesc = eCollection.Find(eventName, true); if (evDesc != null) { desc = iebs.GetEventProperty(evDesc); } } if (desc == null) { continue; } //throw new Exception ("Could not find property " + attr.Name.Name + " of type " + component.GetType ().ToString ()); desc.SetValue(component, desc.Converter.ConvertFromString(attr.Value)); // add the descriptor to the properties which are defined in the tag if (checkForDefaults) { explicitDeclarations.Add(desc); } } // find properties not defined as attributes in the element's tag and set them to the default value if (checkForDefaults) { // go through all the properties in the collection foreach (PropertyDescriptor pDesc in pCollection) { // the property is explicitly defined in the contrl's tag. skip it if (explicitDeclarations.Contains(pDesc)) { continue; } // check if the component has it's default value. if yes - skip it object currVal = pDesc.GetValue(component); if (pDesc.Attributes.Contains(new DefaultValueAttribute(currVal))) { continue; } object defVal = (pDesc.Attributes [typeof(DefaultValueAttribute)] as DefaultValueAttribute).Value; // some of the default values attributes are set in different types if (!pDesc.PropertyType.IsAssignableFrom(defVal.GetType())) { // usually the default value that mismatches the type of the property is a string if (defVal.GetType() != typeof(String)) { continue; } // if it's an empty string and the property is an integer we have a problem // the empty string is usually interpreted as -1 // FIXME: find a not so hacky solution for the problem if (pDesc.PropertyType.IsAssignableFrom(typeof(Int32)) && String.IsNullOrEmpty((string)defVal)) { defVal = (object)-1; } else { // finally we have string which we can convert with the help of the property's typeconver defVal = pDesc.Converter.ConvertFromString((string)defVal); } } // finally, set the default value to the property pDesc.SetValue(component, defVal); } } }