public void ReadOnlyThrows()
        {
            var collection = new EventDescriptorCollection(null, true);

            // The readonly check occurs before anything else, so we don't need to pass in actual valid values
            Assert.Throws<NotSupportedException>(() => collection.Add(null));
            Assert.Throws<NotSupportedException>(() => collection.Insert(1, null));
            Assert.Throws<NotSupportedException>(() => collection.RemoveAt(1));
            Assert.Throws<NotSupportedException>(() => collection.Remove(null));
            Assert.Throws<NotSupportedException>(() => collection.Clear());
        }
        public void ConstructorReadOnlyTests()
        {
            var descriptors = new EventDescriptor[]
            {
                new MockEventDescriptor("descriptor1")
            };

            var collection = new EventDescriptorCollection(descriptors, true);

            Assert.Equal(descriptors, collection.Cast<EventDescriptor>());

            // These methods are implemented as explicit properties so we need to ensure they are what we expect
            Assert.True(((IList)collection).IsReadOnly);
            Assert.True(((IList)collection).IsFixedSize);
        }
        public void Sort1()
        {
            EventDescriptorCollection descriptors;
            EventDescriptorCollection sorted;

            EventDescriptor descA = new MockEventDescriptor("Foo", "B");
            EventDescriptor descB = new MockEventDescriptor("Aim", "C");
            EventDescriptor descC = new MockEventDescriptor("Bim", "A");
            EventDescriptor descD = new MockEventDescriptor("AIm", "E");
            EventDescriptor descE = new MockEventDescriptor("Boo", "D");
            EventDescriptor descF = new MockEventDescriptor("FOo", "F");

            EventDescriptor [] props = new EventDescriptor [] {
                descA, descB, descC, descD, descE, descF
            };
            descriptors = new EventDescriptorCollection(props);

            Assert.AreSame(descA, descriptors [0], "#A1");
            Assert.AreSame(descB, descriptors [1], "#A2");
            Assert.AreSame(descC, descriptors [2], "#A3");
            Assert.AreSame(descD, descriptors [3], "#A4");
            Assert.AreSame(descE, descriptors [4], "#A5");
            Assert.AreSame(descF, descriptors [5], "#A6");

            sorted = descriptors.Sort();

            Assert.AreSame(descA, descriptors [0], "#B1");
            Assert.AreSame(descB, descriptors [1], "#B2");
            Assert.AreSame(descC, descriptors [2], "#B3");
            Assert.AreSame(descD, descriptors [3], "#B4");
            Assert.AreSame(descE, descriptors [4], "#B5");
            Assert.AreSame(descF, descriptors [5], "#B6");

            Assert.AreSame(descB, sorted [0], "#C1");
            Assert.AreSame(descD, sorted [1], "#C2");
            Assert.AreSame(descC, sorted [2], "#C3");
            Assert.AreSame(descE, sorted [3], "#C4");
            Assert.AreSame(descA, sorted [4], "#C5");
            Assert.AreSame(descF, sorted [5], "#C6");
        }
Example #4
0
        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);
        }
Example #5
0
 PropertyDescriptorCollection IEventBindingService.GetEventProperties(EventDescriptorCollection events)
 {
     if (events == null)
     {
         throw new ArgumentNullException("events");
     }
     PropertyDescriptor[] props = new PropertyDescriptor[events.Count];
     if (this._eventProperties == null)
     {
         this._eventProperties = new Hashtable();
     }
     for (int i = 0; i < events.Count; i++)
     {
         object eventHashCode = this.GetEventDescriptorHashCode(events[i]);
         props[i] = (PropertyDescriptor)this._eventProperties[eventHashCode];
         if (props[i] == null)
         {
             props[i] = new EventPropertyDescriptor(events[i], this);
             this._eventProperties[eventHashCode] = props[i];
         }
     }
     return(new PropertyDescriptorCollection(props));
 }
Example #6
0
        // This method uses the IEventBindingService.ShowCode
        // method to start the Code Editor. It places the caret
        // in the timer_tick method created by the CreateTimer method.
        private void ShowEventHandlerCode()
        {
            if (_createdTimer == null)
            {
                return;                        // ================================================
            }
            Timer timer = _createdTimer;

            if (timer != null)
            {
                EventDescriptorCollection eventColl =
                    TypeDescriptor.GetEvents(timer, new Attribute[0]);
                if (eventColl != null)
                {
                    var eventDescriptor = eventColl["Tick"] as EventDescriptor;
                    if (eventDescriptor != null)
                    {
                        var eventBindingService = UIDesigner_Service.IEventBindingService_FromHost(_host);
                        eventBindingService.ShowCode(timer, eventDescriptor);
                    }
                }
            }
        }
        [Test]         // this [String]
        public void Indexer2()
        {
            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 ["heh_\u0061\u030a"], "#1");
            Assert.IsNull(col ["hehe_\u00e5"], "#2");
            Assert.AreSame(descA, col ["hehe_\u0061\u030a"], "#3");
            Assert.AreSame(descB, col ["heh_\u00e5"], "#4");
            Assert.IsNull(col ["foo"], "#5");
            Assert.AreSame(descD, col ["FOo"], "#6");
            Assert.IsNull(col ["fOo"], "#7");
            Assert.IsNull(col ["AIm"], "#8");
            Assert.IsNull(col ["AiM"], "#9");
            Assert.AreSame(descE, col ["Aim"], "#10");
            Assert.IsNull(col [(string)null], "#11");
        }
        private static EventDescriptorCollection GetFilteredEventDescriptorCollection(Type objectType, object instance)
        {
            EventDescriptorCollection eventDescriptors = null;

            if (instance != null)
            {
                eventDescriptors = TypeDescriptor.GetEvents(instance);
            }
            else
            {
                if (objectType == null)
                {
                    throw new ArgumentException("At least one argument should be non-null");
                }
                eventDescriptors = TypeDescriptor.GetEvents(objectType);
            }
            BindingFlags bindingFlags          = BindingFlags.Public | BindingFlags.Instance;
            Type         typeToUseForCBMBridge = GetTypeToUseForCBMBridge(objectType);

            return(new EventDescriptorCollection((from e in s_cbmTdpBridge.GetFilteredEvents(typeToUseForCBMBridge, bindingFlags)
                                                  let d = eventDescriptors[e]
                                                          where d != null
                                                          select d).ToArray <EventDescriptor>()));
        }
Example #9
0
        /// <summary>
        ///  Converts a set of events to a set of properties.
        /// </summary>
        PropertyDescriptorCollection IEventBindingService.GetEventProperties(EventDescriptorCollection events)
        {
            if (events is null)
            {
                throw new ArgumentNullException(nameof(events));
            }

            List <PropertyDescriptor> props = new List <PropertyDescriptor>(events.Count);

            // We cache the property descriptors here for speed.  Create those for
            // events that we don't have yet.
            for (int i = 0; i < events.Count; i++)
            {
                if (HasGenericArgument(events[i]))
                {
                    continue;
                }

                PropertyDescriptor prop = new EventPropertyDescriptor(events[i], this);
                props.Add(prop);
            }

            return(new PropertyDescriptorCollection(props.ToArray()));
        }
        public void CountTests()
        {
            var descriptors = new EventDescriptor[]
            {
                new MockEventDescriptor("descriptor1"),
                new MockEventDescriptor("descriptor2")
            };
            var collection = new EventDescriptorCollection(descriptors);

            Assert.Equal(2, descriptors.Length);
            Assert.Equal(2, ((ICollection)descriptors).Count);
        }
Example #11
0
        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);
        }
Example #12
0
 /// <summary>
 /// Construct a custom type.
 /// </summary>
 /// <param name="className">The class name.</param>
 /// <param name="properties">The class properties.</param>
 /// <param name="attributes">The class attributes.</param>
 /// <param name="events">The class events.</param>
 public CustomType(string className = "CustomClass", PropertyDescriptorCollection properties = null, IEnumerable <Attribute> attributes = null, EventDescriptorCollection events = null)
 {
     ClassName  = className;
     Attributes = attributes != null ? new AttributeCollection(attributes.ToArray()) : new AttributeCollection();
     Properties = properties ?? new PropertyDescriptorCollection(new PropertyDescriptor[0]);
     Events     = events ?? new EventDescriptorCollection(new EventDescriptor[0]);
 }
Example #13
0
        public EventDescriptorCollection GetEvents()
        {
            EventDescriptorCollection edc = TypeDescriptor.GetEvents(this, true);

            return(edc);
        }
Example #14
0
        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;
                    }
                }
            }
        }
Example #15
0
            private void CacheStateIfNecessary()
            {
                if (this.eventHandlers != null)
                {
                    return;
                }
                this.eventHandlers = (ICollection <EventHandlerModel>) new List <EventHandlerModel>();
                this.solution      = this.designerContext.ProjectManager.CurrentSolution;
                this.project       = ProjectHelper.GetProject(this.designerContext.ProjectManager, this.document.DocumentContext);
                if (this.project == null)
                {
                    return;
                }
                ITypeId typeId = (ITypeId)this.document.XamlDocument.CodeBehindClass;

                if (typeId == null)
                {
                    this.state = EventsModel.State.NoCodeBehind;
                }
                else
                {
                    if (this.node == null)
                    {
                        return;
                    }
                    IProjectItem projectItem = this.project.FindItem(this.document.DocumentReference);
                    if (projectItem == null)
                    {
                        return;
                    }
                    IProjectItem codeBehindItem = projectItem.CodeBehindItem;
                    if (codeBehindItem == null)
                    {
                        this.state = EventsModel.State.NoCodeBehind;
                    }
                    else
                    {
                        ICodeGeneratorHost codeGeneratorHost = codeBehindItem.DocumentType as ICodeGeneratorHost;
                        if (codeGeneratorHost == null)
                        {
                            return;
                        }
                        ITypeDeclaration     typeInFile           = this.designerContext.CodeModelService.FindTypeInFile((object)this.solution, (object)codeBehindItem, (IEnumerable <string>)EventsModel.Model.GetProjectItemPath(codeBehindItem), typeId.FullName);
                        CodeDomProvider      codeDomProvider      = codeGeneratorHost.CodeDomProvider;
                        EventHandlerProvider eventHandlerProvider = new EventHandlerProvider(this.designerContext, this.document, typeInFile);
                        this.state = EventsModel.State.Enabled;
                        IProjectContext           projectContext = this.document.ProjectContext;
                        IType                     type           = this.node.Type;
                        List <EventInformation>   list           = new List <EventInformation>(EventInformation.GetEventsForType((ITypeResolver)projectContext, type, MemberType.LocalEvent));
                        EventDescriptorCollection events         = TypeUtilities.GetEvents(type.RuntimeType);
                        list.Sort(new Comparison <EventInformation>(EventInformation.CompareNames));
                        foreach (EventInformation eventInfo in list)
                        {
                            EventDescriptor     eventDescriptor = events[eventInfo.EventName];
                            AttributeCollection eventAttributes = eventDescriptor != null?TypeUtilities.GetAttributes((MemberDescriptor)eventDescriptor) : (AttributeCollection)null;

                            this.eventHandlers.Add(new EventHandlerModel(eventInfo, this.node, codeDomProvider, (IEventHandlerProvider)eventHandlerProvider, eventAttributes));
                        }
                    }
                }
            }
Example #16
0
        public void CreateEmptyCollectionWithNull()
        {
            var collection = new EventDescriptorCollection(null);

            Assert.Equal(0, collection.Count);
        }
Example #17
0
        public EventDescriptorCollection GetEvents(Attribute[] attributes)
        {
            EventDescriptorCollection retval = TypeDescriptor.GetEvents(this, attributes, true);

            return(retval);
        }
        private void AssertReadOnly(EventDescriptorCollection descriptors, string testCase)
        {
            MockEventDescriptor desc = new MockEventDescriptor(
                "Date", "NOW");

            try {
                descriptors.Add(desc);
                Assert.Fail(testCase + "#1");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                descriptors.Add(null);
                Assert.Fail(testCase + "#2");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                descriptors.Clear();
                Assert.Fail(testCase + "#3");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                descriptors.Insert(0, desc);
                Assert.Fail(testCase + "#4");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                descriptors.Insert(0, null);
                Assert.Fail(testCase + "#5");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                descriptors.Remove(desc);
                Assert.Fail(testCase + "#6");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                descriptors.Remove(null);
                Assert.Fail(testCase + "#7");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                descriptors.RemoveAt(0);
                Assert.Fail(testCase + "#8");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            IList list = (IList)descriptors;

            Assert.IsTrue(((IList)descriptors).IsReadOnly, testCase + "#9");
            Assert.IsTrue(((IList)descriptors).IsFixedSize, testCase + "#10");

            try {
                list.Add(desc);
                Assert.Fail(testCase + "#11");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                list.Add(null);
                Assert.Fail(testCase + "#12");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                list.Clear();
                Assert.Fail(testCase + "#13");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                list.Insert(0, desc);
                Assert.Fail(testCase + "#14");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                list.Insert(0, null);
                Assert.Fail(testCase + "#15");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                list.Remove(desc);
                Assert.Fail(testCase + "#16");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                list.Remove(null);
                Assert.Fail(testCase + "#17");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                list.RemoveAt(0);
                Assert.Fail(testCase + "#18");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            try {
                list[0] = desc;
                Assert.Fail(testCase + "#19");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }

            // ensure read-only check if performed before value is checked
            try {
                list[0] = null;
                Assert.Fail(testCase + "#20");
            } catch (NotSupportedException) {
                // read-only collection cannot be modified
            }
        }
        public void Sort4()
        {
            EventDescriptorCollection descriptors;
            EventDescriptorCollection sorted;

            EventDescriptor descA = new MockEventDescriptor("Foo", "B");
            EventDescriptor descB = new MockEventDescriptor("Aim", "C");
            EventDescriptor descC = new MockEventDescriptor("Bim", "A");
            EventDescriptor descD = new MockEventDescriptor("AIm", "E");
            EventDescriptor descE = new MockEventDescriptor("Boo", "D");
            EventDescriptor descF = new MockEventDescriptor("FOo", "F");

            EventDescriptor [] props = new EventDescriptor [] {
                descA, descB, descC, descD, descE, descF
            };
            descriptors = new EventDescriptorCollection(props);

            Assert.AreSame(descA, descriptors [0], "#A1");
            Assert.AreSame(descB, descriptors [1], "#A2");
            Assert.AreSame(descC, descriptors [2], "#A3");
            Assert.AreSame(descD, descriptors [3], "#A4");
            Assert.AreSame(descE, descriptors [4], "#A5");
            Assert.AreSame(descF, descriptors [5], "#A6");

            sorted = descriptors.Sort(new string [] { "B", "Foo", null, "A", "Boo" },
                                      new CategoryComparer());

            Assert.AreSame(descA, descriptors [0], "#B1");
            Assert.AreSame(descB, descriptors [1], "#B2");
            Assert.AreSame(descC, descriptors [2], "#B3");
            Assert.AreSame(descD, descriptors [3], "#B4");
            Assert.AreSame(descE, descriptors [4], "#B5");
            Assert.AreSame(descF, descriptors [5], "#B6");

            Assert.AreSame(descA, sorted [0], "#C1");
            Assert.AreSame(descE, sorted [1], "#C2");
            Assert.AreSame(descC, sorted [2], "#C3");
            Assert.AreSame(descB, sorted [3], "#C4");
            Assert.AreSame(descD, sorted [4], "#C5");
            Assert.AreSame(descF, sorted [5], "#C6");

            sorted = descriptors.Sort((string [])null, new CategoryComparer());

            Assert.AreSame(descA, descriptors [0], "#D1");
            Assert.AreSame(descB, descriptors [1], "#D2");
            Assert.AreSame(descC, descriptors [2], "#D3");
            Assert.AreSame(descD, descriptors [3], "#D4");
            Assert.AreSame(descE, descriptors [4], "#D5");
            Assert.AreSame(descF, descriptors [5], "#D6");

            Assert.AreSame(descC, sorted [0], "#E1");
            Assert.AreSame(descA, sorted [1], "#E2");
            Assert.AreSame(descB, sorted [2], "#E3");
            Assert.AreSame(descE, sorted [3], "#E4");
            Assert.AreSame(descD, sorted [4], "#E5");
            Assert.AreSame(descF, sorted [5], "#E6");

            sorted = descriptors.Sort(new string [] { "B", "Foo", null, "A", "Boo" },
                                      (Comparer)null);

            Assert.AreSame(descA, descriptors [0], "#F1");
            Assert.AreSame(descB, descriptors [1], "#F2");
            Assert.AreSame(descC, descriptors [2], "#F3");
            Assert.AreSame(descD, descriptors [3], "#F4");
            Assert.AreSame(descE, descriptors [4], "#F5");
            Assert.AreSame(descF, descriptors [5], "#F6");

            Assert.AreSame(descA, sorted [0], "#G1");
            Assert.AreSame(descE, sorted [1], "#G2");
            Assert.AreSame(descB, sorted [2], "#G3");
            Assert.AreSame(descD, sorted [3], "#G4");
            Assert.AreSame(descC, sorted [4], "#G5");
            Assert.AreSame(descF, sorted [5], "#G6");

            sorted = descriptors.Sort((string [])null, (Comparer)null);

            Assert.AreSame(descA, descriptors [0], "#H1");
            Assert.AreSame(descB, descriptors [1], "#H2");
            Assert.AreSame(descC, descriptors [2], "#H3");
            Assert.AreSame(descD, descriptors [3], "#H4");
            Assert.AreSame(descE, descriptors [4], "#H5");
            Assert.AreSame(descF, descriptors [5], "#H6");

            Assert.AreSame(descB, sorted [0], "#I1");
            Assert.AreSame(descD, sorted [1], "#I2");
            Assert.AreSame(descC, sorted [2], "#I3");
            Assert.AreSame(descE, sorted [3], "#I4");
            Assert.AreSame(descA, sorted [4], "#I5");
            Assert.AreSame(descF, sorted [5], "#I6");
        }
            public override EventDescriptorCollection GetEvents()
            {
                var events = new EventDescriptorCollection(new EventDescriptor[] { _eventDescriptor });

                return(events);
            }
Example #21
0
        EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
        {
            EventDescriptorCollection edc = TypeDescriptor.GetEvents(this, attributes, true);

            return(edc);
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

#if WINDOWS_APP
                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;
#endif

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged += OnGeofenceStatusChanged;
            }
#if WINDOWS_APP
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
#endif
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #23
0
        /// <include file='doc\EventsTab.uex' path='docs/doc[@for="EventsTab.GetProperties2"]/*' />
        /// <devdoc>
        ///    <para>Gets the properties of the specified component...</para>
        /// </devdoc>
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object component, Attribute[] attributes)
        {
            //Debug.Assert(component != null, "Can't get properties for a null item!");

            IEventBindingService eventPropertySvc = GetEventPropertyService(component, context);

            if (eventPropertySvc == null)
            {
                return(new PropertyDescriptorCollection(null));
            }
            EventDescriptorCollection    events     = TypeDescriptor.GetEvents(component, attributes);
            PropertyDescriptorCollection realEvents = eventPropertySvc.GetEventProperties(events);


            // Add DesignerSerializationVisibilityAttribute.Content to attributes to see if we have any.
            Attribute[] attributesPlusNamespace = new Attribute[attributes.Length + 1];
            Array.Copy(attributes, 0, attributesPlusNamespace, 0, attributes.Length);
            attributesPlusNamespace[attributes.Length] = DesignerSerializationVisibilityAttribute.Content;

            // If we do, then we traverse them to see if they have any events under the current attributes,
            // and if so, we'll show them as top-level properties so they can be drilled down into to get events.
            PropertyDescriptorCollection namespaceProperties = TypeDescriptor.GetProperties(component, attributesPlusNamespace);

            if (namespaceProperties.Count > 0)
            {
                ArrayList list = null;
                for (int i = 0; i < namespaceProperties.Count; i++)
                {
                    PropertyDescriptor nsProp = namespaceProperties[i];

                    TypeConverter tc = nsProp.Converter;

                    if (!tc.GetPropertiesSupported())
                    {
                        continue;
                    }

                    object namespaceValue = nsProp.GetValue(component);
                    EventDescriptorCollection namespaceEvents = TypeDescriptor.GetEvents(namespaceValue, attributes);
                    if (namespaceEvents.Count > 0)
                    {
                        if (list == null)
                        {
                            list = new ArrayList();
                        }

                        // make this non-mergable
                        //
                        nsProp = TypeDescriptor.CreateProperty(nsProp.ComponentType, nsProp, MergablePropertyAttribute.No);
                        list.Add(nsProp);
                    }
                }

                // we've found some, so add them to the event list.
                if (list != null)
                {
                    PropertyDescriptor[] realNamespaceProperties = new PropertyDescriptor[list.Count];
                    list.CopyTo(realNamespaceProperties, 0);
                    PropertyDescriptor[] finalEvents = new PropertyDescriptor[realEvents.Count + realNamespaceProperties.Length];
                    realEvents.CopyTo(finalEvents, 0);
                    Array.Copy(realNamespaceProperties, 0, finalEvents, realEvents.Count, realNamespaceProperties.Length);
                    realEvents = new PropertyDescriptorCollection(finalEvents);
                }
            }

            return(realEvents);
        }
Example #24
0
 public PropertyDescriptorCollection GetEventProperties(EventDescriptorCollection events)
 {
     return(_realService.GetEventProperties(events));
 }
Example #25
0
        private XmlNode WriteObject(XmlDocument document, IDictionary nametable, object value)
        {
            IDesignerHost idh = (IDesignerHost)this.host.GetService(typeof(IDesignerHost));

            Debug.Assert(value != null, "Should not invoke WriteObject with a null value");

            XmlNode      node     = document.CreateElement("Object");
            XmlAttribute typeAttr = document.CreateAttribute("type");

            typeAttr.Value = value.GetType().AssemblyQualifiedName;
            node.Attributes.Append(typeAttr);

            IComponent component = value as IComponent;

            if (component != null && component.Site != null && component.Site.Name != null)
            {
                XmlAttribute nameAttr = document.CreateAttribute("name");

                nameAttr.Value = component.Site.Name;
                node.Attributes.Append(nameAttr);
                Debug.Assert(nametable[component] == null, "WriteObject should not be called more than once for the same object.  Use WriteReference instead");
                nametable[value] = component.Site.Name;
            }

            bool isControl = (value is Control);

            if (isControl)
            {
                XmlAttribute childAttr = document.CreateAttribute("children");

                childAttr.Value = "Controls";
                node.Attributes.Append(childAttr);
            }

            if (component != null)
            {
                if (isControl)
                {
                    foreach (Control child in ((Control)value).Controls)
                    {
                        if (child.Site != null && child.Site.Container == idh.Container)
                        {
                            node.AppendChild(WriteObject(document, nametable, child));
                        }
                    }
                }                // if isControl

                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value, propertyAttributes);

                if (isControl)
                {
                    PropertyDescriptor controlProp = properties["Controls"];

                    if (controlProp != null)
                    {
                        PropertyDescriptor[] propArray = new PropertyDescriptor[properties.Count - 1];
                        int idx = 0;

                        foreach (PropertyDescriptor p in properties)
                        {
                            if (p != controlProp)
                            {
                                propArray[idx++] = p;
                            }
                        }

                        properties = new PropertyDescriptorCollection(propArray);
                    }
                }

                WriteProperties(document, properties, value, node, "Property");

                EventDescriptorCollection events   = TypeDescriptor.GetEvents(value, propertyAttributes);
                IEventBindingService      bindings = host.GetService(typeof(IEventBindingService)) as IEventBindingService;

                if (bindings != null)
                {
                    properties = bindings.GetEventProperties(events);
                    WriteProperties(document, properties, value, node, "Event");
                }
            }
            else
            {
                WriteValue(document, value, node);
            }

            return(node);
        }
Example #26
0
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime          = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar         = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection    = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged        += OnGeofenceStatusChanged;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #27
0
        /// <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);
                }
            }
        }
Example #28
0
        private void CheckBinding()
        {
            this.bindToObject.CheckBinding();

            if (control != null && propertyName.Length > 0)
            {
                control.DataBindings.CheckDuplicates(this);

                Type controlClass = control.GetType();

                // Check Properties
                string                       propertyNameIsNull = propertyName + "IsNull";
                Type                         propType           = null;
                PropertyDescriptor           tempPropInfo       = null;
                PropertyDescriptor           tempPropIsNullInfo = null;
                PropertyDescriptorCollection propInfos;

                // If the control is being inherited, then get the properties for
                // the control's type rather than for the control itself.  Getting
                // properties for the control will merge the control's properties with
                // those of its designer.  Normally we want that, but for
                // inherited controls we don't because an inherited control should
                // "act" like a runtime control.
                //
                InheritanceAttribute attr = (InheritanceAttribute)TypeDescriptor.GetAttributes(control)[typeof(InheritanceAttribute)];
                if (attr != null && attr.InheritanceLevel != InheritanceLevel.NotInherited)
                {
                    propInfos = TypeDescriptor.GetProperties(controlClass);
                }
                else
                {
                    propInfos = TypeDescriptor.GetProperties(control);
                }

                for (int i = 0; i < propInfos.Count; i++)
                {
                    if (tempPropInfo == null && string.Equals(propInfos[i].Name, propertyName, StringComparison.OrdinalIgnoreCase))
                    {
                        tempPropInfo = propInfos[i];
                        if (tempPropIsNullInfo != null)
                        {
                            break;
                        }
                    }
                    if (tempPropIsNullInfo == null && string.Equals(propInfos[i].Name, propertyNameIsNull, StringComparison.OrdinalIgnoreCase))
                    {
                        tempPropIsNullInfo = propInfos[i];
                        if (tempPropInfo != null)
                        {
                            break;
                        }
                    }
                }

                if (tempPropInfo == null)
                {
                    throw new ArgumentException(string.Format(SR.ListBindingBindProperty, propertyName), "PropertyName");
                }
                if (tempPropInfo.IsReadOnly && this.controlUpdateMode != ControlUpdateMode.Never)
                {
                    throw new ArgumentException(string.Format(SR.ListBindingBindPropertyReadOnly, propertyName), "PropertyName");
                }

                propInfo          = tempPropInfo;
                propType          = propInfo.PropertyType;
                propInfoConverter = propInfo.Converter;

                if (tempPropIsNullInfo != null && tempPropIsNullInfo.PropertyType == typeof(bool) && !tempPropIsNullInfo.IsReadOnly)
                {
                    propIsNullInfo = tempPropIsNullInfo;
                }

                // Check events
                EventDescriptor           tempValidateInfo = null;
                string                    validateName     = "Validating";
                EventDescriptorCollection eventInfos       = TypeDescriptor.GetEvents(control);
                for (int i = 0; i < eventInfos.Count; i++)
                {
                    if (tempValidateInfo == null && string.Equals(eventInfos[i].Name, validateName, StringComparison.OrdinalIgnoreCase))
                    {
                        tempValidateInfo = eventInfos[i];
                        break;
                    }
                }
                validateInfo = tempValidateInfo;
            }
            else
            {
                propInfo     = null;
                validateInfo = null;
            }

            // go see if we become bound now.
            UpdateIsBinding();
        }
Example #29
0
 public PropertyDescriptorCollection GetEventProperties(EventDescriptorCollection events)
 {
     throw new NotImplementedException();
 }
Example #30
0
        public EventDescriptorCollection GetEvents(System.Attribute[] attributes)
        {
            EventDescriptorCollection edc = TypeDescriptor.GetEvents(this, attributes, true);

            return(edc);
        }
 public PropertyDescriptorCollection GetEventProperties(EventDescriptorCollection events)
 {
     return(new PropertyDescriptorCollection(new PropertyDescriptor[] { }, true));
 }
Example #32
0
        public void GetEvents_InvokeAttributesWithParent_ReturnsExpected(Attribute[] attributes, EventDescriptorCollection result)
        {
            var mockParentDescriptor = new Mock <ICustomTypeDescriptor>(MockBehavior.Strict);

            mockParentDescriptor
            .Setup(d => d.GetEvents(attributes))
            .Returns(result)
            .Verifiable();
            var descriptor = new SubCustomTypeDescriptor(mockParentDescriptor.Object);

            Assert.Same(result, descriptor.GetEvents(attributes));
            mockParentDescriptor.Verify(d => d.GetEvents(attributes), Times.Once());

            // Call again.
            Assert.Same(result, descriptor.GetEvents(attributes));
            mockParentDescriptor.Verify(d => d.GetEvents(attributes), Times.Exactly(2));
        }
        public void CreateEmptyCollectionWithNull()
        {
            var collection = new EventDescriptorCollection(null);

            Assert.Equal(0, collection.Count);
        }
Example #34
0
 PropertyDescriptorCollection IEventBindingService.GetEventProperties(EventDescriptorCollection events)
 {
     throw null;
 }
 private void CheckBinding()
 {
     this.bindToObject.CheckBinding();
     if ((this.control == null) || (this.propertyName.Length <= 0))
     {
         this.propInfo     = null;
         this.validateInfo = null;
     }
     else
     {
         PropertyDescriptorCollection properties;
         this.control.DataBindings.CheckDuplicates(this);
         System.Type          componentType = this.control.GetType();
         string               b             = this.propertyName + "IsNull";
         PropertyDescriptor   descriptor    = null;
         PropertyDescriptor   descriptor2   = null;
         InheritanceAttribute attribute     = (InheritanceAttribute)TypeDescriptor.GetAttributes(this.control)[typeof(InheritanceAttribute)];
         if ((attribute != null) && (attribute.InheritanceLevel != InheritanceLevel.NotInherited))
         {
             properties = TypeDescriptor.GetProperties(componentType);
         }
         else
         {
             properties = TypeDescriptor.GetProperties(this.control);
         }
         for (int i = 0; i < properties.Count; i++)
         {
             if ((descriptor == null) && string.Equals(properties[i].Name, this.propertyName, StringComparison.OrdinalIgnoreCase))
             {
                 descriptor = properties[i];
                 if (descriptor2 != null)
                 {
                     break;
                 }
             }
             if ((descriptor2 == null) && string.Equals(properties[i].Name, b, StringComparison.OrdinalIgnoreCase))
             {
                 descriptor2 = properties[i];
                 if (descriptor != null)
                 {
                     break;
                 }
             }
         }
         if (descriptor == null)
         {
             throw new ArgumentException(System.Windows.Forms.SR.GetString("ListBindingBindProperty", new object[] { this.propertyName }), "PropertyName");
         }
         if (descriptor.IsReadOnly && (this.controlUpdateMode != System.Windows.Forms.ControlUpdateMode.Never))
         {
             throw new ArgumentException(System.Windows.Forms.SR.GetString("ListBindingBindPropertyReadOnly", new object[] { this.propertyName }), "PropertyName");
         }
         this.propInfo = descriptor;
         System.Type propertyType = this.propInfo.PropertyType;
         this.propInfoConverter = this.propInfo.Converter;
         if (((descriptor2 != null) && (descriptor2.PropertyType == typeof(bool))) && !descriptor2.IsReadOnly)
         {
             this.propIsNullInfo = descriptor2;
         }
         EventDescriptor           descriptor3 = null;
         string                    str2        = "Validating";
         EventDescriptorCollection events      = TypeDescriptor.GetEvents(this.control);
         for (int j = 0; j < events.Count; j++)
         {
             if ((descriptor3 == null) && string.Equals(events[j].Name, str2, StringComparison.OrdinalIgnoreCase))
             {
                 descriptor3 = events[j];
                 break;
             }
         }
         this.validateInfo = descriptor3;
     }
     this.UpdateIsBinding();
 }